-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.go
166 lines (140 loc) · 3.93 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package main
import (
"context"
"fmt"
"log/slog"
"net/http"
"os"
"strings"
"time"
scyllaridae "github.com/lehigh-university-libraries/scyllaridae/internal/config"
"github.com/lehigh-university-libraries/scyllaridae/pkg/api"
"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/lestrrat-go/jwx/v2/jwt"
)
type contextKey string
const cmdKey contextKey = "scyllaridaeCmd"
const msgKey contextKey = "scyllaridaeMsg"
type statusRecorder struct {
http.ResponseWriter
statusCode int
}
func (rec *statusRecorder) WriteHeader(code int) {
rec.statusCode = code
rec.ResponseWriter.WriteHeader(code)
}
func (s *Server) LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
statusWriter := &statusRecorder{
ResponseWriter: w,
statusCode: http.StatusOK,
}
auth := ""
if s.Config.ForwardAuth {
auth = r.Header.Get("Authorization")
}
message, err := api.DecodeAlpacaMessage(r, auth)
if err != nil {
slog.Error("Error decoding alpaca message", "err", err)
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
cmd, err := scyllaridae.BuildExecCommand(message, s.Config)
if err != nil {
slog.Error("Error building command", "err", err)
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
ctx := context.WithValue(r.Context(), cmdKey, cmd)
ctx = context.WithValue(ctx, msgKey, message)
next.ServeHTTP(statusWriter, r.WithContext(ctx))
duration := time.Since(start)
slog.Info("Incoming request",
"method", r.Method,
"path", r.URL.Path,
"status", statusWriter.statusCode,
"duration", duration,
"client_ip", r.RemoteAddr,
"user_agent", r.UserAgent(),
"command", cmd.String(),
)
})
}
// JWTAuthMiddleware validates a JWT token and adds claims to the context
func (s *Server) JWTAuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
a := r.Header.Get("Authorization")
if a == "" || len(a) <= 7 || !strings.EqualFold(a[:7], "bearer ") {
if os.Getenv("SKIP_JWT_VERIFY") != "true" {
http.Error(w, "Missing Authorization header", http.StatusBadRequest)
return
}
}
if os.Getenv("SKIP_JWT_VERIFY") != "true" {
tokenString := a[7:]
err := s.verifyJWT(tokenString)
if err != nil {
slog.Error("JWT verification failed", "err", err)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
}
next.ServeHTTP(w, r)
})
}
func (s *Server) verifyJWT(tokenString string) error {
keySet, err := s.fetchJWKS()
if err != nil {
return fmt.Errorf("unable to fetch JWKS: %v", err)
}
// islandora will only ever provide a single key to sign JWTs
// so just use the one key in JWKS
key, ok := keySet.Key(0)
if !ok {
return fmt.Errorf("no key in jwks")
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var token jwt.Token
if keySet.Len() > 1 {
token, err = jwt.Parse([]byte(tokenString),
jwt.WithContext(ctx),
jwt.WithKeySet(keySet),
)
} else {
token, err = jwt.Parse([]byte(tokenString),
jwt.WithContext(ctx),
jwt.WithKey(jwa.RS256, key),
)
}
if err != nil {
return fmt.Errorf("unable to parse token: %v", err)
}
err = jwt.Validate(token)
if err != nil {
return fmt.Errorf("unable to validate token: %v", err)
}
return nil
}
// fetchJWKS fetches the JSON Web Key Set (JWKS) from the given URI
func (s *Server) fetchJWKS() (jwk.Set, error) {
var err error
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
jwksURI := os.Getenv("JWKS_URI")
ks, ok := s.KeySets.Get(jwksURI)
if ok {
return ks, nil
}
ks, err = jwk.Fetch(ctx, jwksURI)
if err != nil {
return nil, fmt.Errorf("unable to fetch jwks: %v", err)
}
evicted := s.KeySets.Add(jwksURI, ks)
if evicted {
slog.Warn("server jwks cache is too small")
}
return ks, nil
}