-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
87 lines (79 loc) · 2.31 KB
/
middleware.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package sns
import (
"context"
"encoding/json"
"fmt"
"net/http"
)
const (
XAmzSnsMessageType string = "x-amz-sns-message-type"
XAmzSnsTopicArn string = "x-amz-sns-topic-arn"
)
type subscriber interface {
ConfirmSubscription(msg SubscriptionConfirmation) (string, error)
ValidateCertURL(certURL string) error
CheckSignature(ms MessageSignature) error
}
type Middleware struct {
subscriber subscriber
}
func NewMiddleware() *Middleware {
return &Middleware{
subscriber: NewClient(),
}
}
func (m *Middleware) Subscribe(snsTopicARN string) func(http.HandlerFunc) http.HandlerFunc {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
topicArn := r.Header.Get(XAmzSnsTopicArn)
if topicArn != snsTopicARN {
http.Error(w, "invalid SNS TopicArn", http.StatusForbidden)
return
}
var ctx context.Context
switch NewMessageType(r.Header.Get(XAmzSnsMessageType)) {
case MessageTypeSubscriptionConfirmation:
var msg SubscriptionConfirmation
if err := json.NewDecoder(r.Body).Decode(&msg); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := m.subscriber.ValidateCertURL(msg.SigningCertURL); err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
if err := m.subscriber.CheckSignature(msg.MessageSignature()); err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
body, err := m.subscriber.ConfirmSubscription(msg)
if err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, body)
return
case MessageTypeNotification:
var msg Notification
if err := json.NewDecoder(r.Body).Decode(&msg); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := m.subscriber.ValidateCertURL(msg.SigningCertURL); err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
if err := m.subscriber.CheckSignature(msg.MessageSignature()); err != nil {
http.Error(w, err.Error(), http.StatusForbidden)
return
}
ctx = SetNotification(r, msg)
default:
http.Error(w, "unexpected message type", http.StatusForbidden)
return
}
next(w, r.WithContext(ctx))
}
}
}