-
Notifications
You must be signed in to change notification settings - Fork 477
Expand file tree
/
Copy pathauth.go
More file actions
298 lines (275 loc) · 8.75 KB
/
auth.go
File metadata and controls
298 lines (275 loc) · 8.75 KB
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package auth
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"sort"
"strings"
"time"
"github.com/Gentleman-Programming/engram/internal/cloud/cloudstore"
"github.com/Gentleman-Programming/engram/internal/store"
)
var ErrSecretTooShort = errors.New("jwt secret must be at least 32 bytes")
var ErrBearerTokenNotConfigured = errors.New("cloud bearer token is not configured")
var ErrInvalidDashboardSessionToken = errors.New("invalid dashboard session token")
var ErrProjectNotAllowed = errors.New("project is not allowed for this token")
type Service struct {
store *cloudstore.CloudStore
expectedToken string
dashboardAuth map[string]struct{}
allowed map[string]struct{}
allowedAll bool
jwtSecret []byte
now func() time.Time
}
type ProjectScopeAuthorizer struct {
allowed map[string]struct{}
allowedAll bool
}
func NewService(store *cloudstore.CloudStore, jwtSecret string) (*Service, error) {
if len(jwtSecret) < 32 {
return nil, ErrSecretTooShort
}
return &Service{store: store, jwtSecret: []byte(jwtSecret), now: time.Now}, nil
}
func NewProjectScopeAuthorizer(projects []string) *ProjectScopeAuthorizer {
a := &ProjectScopeAuthorizer{allowed: make(map[string]struct{})}
a.SetAllowedProjects(projects)
return a
}
type dashboardSessionClaims struct {
TokenHash string `json:"token_hash"`
Exp int64 `json:"exp"`
Iat int64 `json:"iat"`
}
// MintDashboardSession returns a signed dashboard session token.
// The token is opaque to clients and validated by ParseDashboardSession.
func (s *Service) MintDashboardSession(bearerToken string) (string, error) {
bearerToken = strings.TrimSpace(bearerToken)
if bearerToken == "" {
return "", fmt.Errorf("bearer token is required")
}
issuedAt := s.now().UTC()
claims := dashboardSessionClaims{
TokenHash: s.dashboardTokenHash(bearerToken),
Iat: issuedAt.Unix(),
Exp: issuedAt.Add(8 * time.Hour).Unix(),
}
payload, err := json.Marshal(claims)
if err != nil {
return "", err
}
payloadPart := base64.RawURLEncoding.EncodeToString(payload)
signature := s.sign(payloadPart)
return payloadPart + "." + base64.RawURLEncoding.EncodeToString(signature), nil
}
// ParseDashboardSession verifies and decodes a signed dashboard session token.
func (s *Service) ParseDashboardSession(sessionToken string) (string, error) {
sessionToken = strings.TrimSpace(sessionToken)
parts := strings.Split(sessionToken, ".")
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return "", ErrInvalidDashboardSessionToken
}
expectedSig := s.sign(parts[0])
providedSig, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return "", ErrInvalidDashboardSessionToken
}
if !hmac.Equal(expectedSig, providedSig) {
return "", ErrInvalidDashboardSessionToken
}
payload, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return "", ErrInvalidDashboardSessionToken
}
var claims dashboardSessionClaims
if err := json.Unmarshal(payload, &claims); err != nil {
return "", ErrInvalidDashboardSessionToken
}
if strings.TrimSpace(claims.TokenHash) == "" {
return "", ErrInvalidDashboardSessionToken
}
if claims.Exp <= s.now().UTC().Unix() {
return "", ErrInvalidDashboardSessionToken
}
expectedToken := strings.TrimSpace(s.expectedToken)
if expectedToken == "" {
return "", ErrBearerTokenNotConfigured
}
if hmac.Equal([]byte(claims.TokenHash), []byte(s.dashboardTokenHash(expectedToken))) {
return expectedToken, nil
}
for token := range s.dashboardAuth {
token = strings.TrimSpace(token)
if token == "" || token == expectedToken {
continue
}
if hmac.Equal([]byte(claims.TokenHash), []byte(s.dashboardTokenHash(token))) {
return token, nil
}
}
return "", ErrInvalidDashboardSessionToken
}
func (s *Service) sign(payloadPart string) []byte {
mac := hmac.New(sha256.New, s.jwtSecret)
_, _ = mac.Write([]byte(payloadPart))
return mac.Sum(nil)
}
func (s *Service) dashboardTokenHash(token string) string {
mac := hmac.New(sha256.New, s.jwtSecret)
_, _ = mac.Write([]byte("dashboard:"))
_, _ = mac.Write([]byte(token))
return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
}
func (s *Service) SetBearerToken(token string) {
s.expectedToken = strings.TrimSpace(token)
}
func (s *Service) SetDashboardSessionTokens(tokens []string) {
s.dashboardAuth = make(map[string]struct{})
for _, token := range tokens {
token = strings.TrimSpace(token)
if token == "" {
continue
}
s.dashboardAuth[token] = struct{}{}
}
}
func (s *Service) SetAllowedProjects(projects []string) {
s.allowed = make(map[string]struct{})
s.allowedAll = false
for _, project := range projects {
if strings.TrimSpace(project) == "*" {
s.allowedAll = true
return
}
normalized, _ := store.NormalizeProject(project)
normalized = strings.TrimSpace(normalized)
if normalized == "" {
continue
}
s.allowed[normalized] = struct{}{}
}
}
func (s *Service) AuthorizeProject(project string) error {
if s.allowedAll {
normalized, _ := store.NormalizeProject(project)
normalized = strings.TrimSpace(normalized)
if normalized == "" {
return fmt.Errorf("project is required")
}
return nil
}
return authorizeProjectAgainstAllowlist(project, s.allowed)
}
// EnrolledProjects returns the sorted list of projects that this Service is
// authorized to serve. Used by cloudserver's mutation pull to filter mutations
// to the caller's enrolled projects (REQ-202).
//
// When the wildcard "*" is configured, nil is returned to signal "no project
// filter" — callers must treat nil as "allow all" (matching the ListMutationsSince
// nil-means-all contract).
//
// The interface is cloudserver.EnrolledProjectsProvider; this method makes
// *Service satisfy it without importing cloudserver (structural assertion).
func (s *Service) EnrolledProjects() []string {
if s.allowedAll {
return nil
}
return sortedAllowlist(s.allowed)
}
func (a *ProjectScopeAuthorizer) SetAllowedProjects(projects []string) {
a.allowed = make(map[string]struct{})
a.allowedAll = false
for _, project := range projects {
if strings.TrimSpace(project) == "*" {
a.allowedAll = true
return
}
normalized, _ := store.NormalizeProject(project)
normalized = strings.TrimSpace(normalized)
if normalized == "" {
continue
}
a.allowed[normalized] = struct{}{}
}
}
func (a *ProjectScopeAuthorizer) AuthorizeProject(project string) error {
if a.allowedAll {
normalized, _ := store.NormalizeProject(project)
normalized = strings.TrimSpace(normalized)
if normalized == "" {
return fmt.Errorf("project is required")
}
return nil
}
return authorizeProjectAgainstAllowlist(project, a.allowed)
}
// EnrolledProjects returns the sorted list of projects this authorizer allows.
// Matches the cloudserver.EnrolledProjectsProvider contract so mutation pull
// can filter server-side by the caller's enrolled projects (REQ-202) rather
// than fail-closing to an empty result set.
//
// When the wildcard "*" is configured, nil is returned to signal "no project
// filter" (matching the ListMutationsSince nil-means-all contract).
func (a *ProjectScopeAuthorizer) EnrolledProjects() []string {
if a.allowedAll {
return nil
}
return sortedAllowlist(a.allowed)
}
// sortedAllowlist returns a sorted slice of the map keys.
// Isolated to one spot so both Service and ProjectScopeAuthorizer behave
// identically and tests can pin ordering.
func sortedAllowlist(allowed map[string]struct{}) []string {
if len(allowed) == 0 {
return []string{}
}
out := make([]string, 0, len(allowed))
for project := range allowed {
out = append(out, project)
}
sort.Strings(out)
return out
}
func authorizeProjectAgainstAllowlist(project string, allowed map[string]struct{}) error {
if len(allowed) == 0 {
return fmt.Errorf("cloud project allowlist is not configured")
}
normalized, _ := store.NormalizeProject(project)
normalized = strings.TrimSpace(normalized)
if normalized == "" {
return fmt.Errorf("project is required")
}
if _, ok := allowed[normalized]; ok {
return nil
}
return fmt.Errorf("%w", ErrProjectNotAllowed)
}
func (s *Service) Authorize(r *http.Request) error {
if strings.TrimSpace(s.expectedToken) == "" {
return ErrBearerTokenNotConfigured
}
header := strings.TrimSpace(r.Header.Get("Authorization"))
if header == "" {
return fmt.Errorf("missing authorization header")
}
parts := strings.Fields(header)
if len(parts) != 2 {
return fmt.Errorf("authorization must use Bearer token")
}
if !strings.EqualFold(parts[0], "Bearer") {
return fmt.Errorf("authorization must use Bearer token")
}
token := strings.TrimSpace(parts[1])
if token == "" {
return fmt.Errorf("bearer token is required")
}
if !hmac.Equal([]byte(token), []byte(s.expectedToken)) {
return fmt.Errorf("invalid bearer token")
}
return nil
}