-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathauthorizer.go
More file actions
364 lines (294 loc) · 9.29 KB
/
authorizer.go
File metadata and controls
364 lines (294 loc) · 9.29 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package tokenizer
import (
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/superfly/flysrc-go"
"github.com/superfly/macaroon"
"github.com/superfly/macaroon/bundle"
"github.com/superfly/macaroon/flyio"
"github.com/superfly/macaroon/flyio/machinesapi"
tkmac "github.com/superfly/tokenizer/macaroon"
"golang.org/x/exp/slices"
)
const (
headerProxyAuthorization = "Proxy-Authorization"
maxFlySrcAge = 30 * time.Second
)
var redactedStr = "REDACTED"
var redactedBase64 []byte
func init() {
redactedBase64, _ = base64.StdEncoding.DecodeString("REDACTED")
}
type AuthContext interface {
GetFlysrcParser() *flysrc.Parser
}
type AuthConfig interface {
AuthRequest(authctx AuthContext, req *http.Request) error
StripHazmat() AuthConfig
}
type wireAuth struct {
BearerAuthConfig *BearerAuthConfig `json:"bearer_auth,omitempty"`
MacaroonAuthConfig *MacaroonAuthConfig `json:"macaroon_auth,omitempty"`
FlyioMacaroonAuthConfig *FlyioMacaroonAuthConfig `json:"flyio_macaroon_auth,omitempty"`
FlySrcAuthConfig *FlySrcAuthConfig `json:"fly_src_auth,omitempty"`
NoAuthConfig *NoAuthConfig `json:"no_auth,omitempty"`
}
func newWireAuth(ac AuthConfig) (wireAuth, error) {
switch a := ac.(type) {
case *BearerAuthConfig:
return wireAuth{BearerAuthConfig: a}, nil
case *MacaroonAuthConfig:
return wireAuth{MacaroonAuthConfig: a}, nil
case *FlyioMacaroonAuthConfig:
return wireAuth{FlyioMacaroonAuthConfig: a}, nil
case *FlySrcAuthConfig:
return wireAuth{FlySrcAuthConfig: a}, nil
case *NoAuthConfig:
return wireAuth{NoAuthConfig: a}, nil
default:
return wireAuth{}, fmt.Errorf("bad auth config: %T", ac)
}
}
func (wa *wireAuth) getAuthConfig() (AuthConfig, error) {
var ac AuthConfig
var na int
if wa.BearerAuthConfig != nil {
na += 1
ac = wa.BearerAuthConfig
}
if wa.MacaroonAuthConfig != nil {
na += 1
ac = wa.MacaroonAuthConfig
}
if wa.FlyioMacaroonAuthConfig != nil {
na += 1
ac = wa.FlyioMacaroonAuthConfig
}
if wa.FlySrcAuthConfig != nil {
na += 1
ac = wa.FlySrcAuthConfig
}
if wa.NoAuthConfig != nil {
na += 1
ac = wa.NoAuthConfig
}
if na != 1 {
return nil, errors.New("bad auth config")
}
return ac, nil
}
type BearerAuthConfig struct {
Digest []byte `json:"digest"`
}
func NewBearerAuthConfig(token string) *BearerAuthConfig {
digest := sha256.Sum256([]byte(token))
return &BearerAuthConfig{digest[:]}
}
var _ AuthConfig = (*BearerAuthConfig)(nil)
func (c *BearerAuthConfig) AuthRequest(authctx AuthContext, req *http.Request) error {
for _, tok := range proxyAuthorizationTokens(req) {
hdrDigest := sha256.Sum256([]byte(tok))
if subtle.ConstantTimeCompare(c.Digest, hdrDigest[:]) == 1 {
return nil
}
}
return fmt.Errorf("%w: bad or missing proxy auth", ErrNotAuthorized)
}
func (c *BearerAuthConfig) StripHazmat() AuthConfig {
return &BearerAuthConfig{redactedBase64}
}
type MacaroonAuthConfig struct {
Key []byte `json:"key"`
}
func NewMacaroonAuthConfig(key []byte) *MacaroonAuthConfig {
return &MacaroonAuthConfig{Key: key}
}
var _ AuthConfig = (*MacaroonAuthConfig)(nil)
func (c *MacaroonAuthConfig) AuthRequest(authctx AuthContext, req *http.Request) error {
var (
expectedKID = tkmac.KeyFingerprint(c.Key)
log = logrus.WithField("expected-kid", hex.EncodeToString(expectedKID))
ctx = req.Context()
)
for _, tok := range proxyAuthorizationTokens(req) {
bun, err := bundle.ParseBundle(tkmac.Location, tok)
if err != nil {
log.WithError(err).Warn("bad macaroon format")
continue
}
if _, err = bun.Verify(ctx, bundle.WithKey(expectedKID, c.Key, nil)); err != nil {
log.WithError(err).Warn("bad macaroon signature")
continue
}
if err = bun.Validate(&tkmac.Access{Request: req}); err != nil {
log.WithError(err).Warn("bad macaroon authz")
continue
}
return nil
}
return fmt.Errorf("%w: bad or missing proxy auth", ErrNotAuthorized)
}
func (c *MacaroonAuthConfig) StripHazmat() AuthConfig {
return &MacaroonAuthConfig{redactedBase64}
}
func (c *MacaroonAuthConfig) Macaroon(caveats ...macaroon.Caveat) (string, error) {
m, err := macaroon.New(tkmac.KeyFingerprint(c.Key), tkmac.Location, c.Key)
if err != nil {
return "", err
}
if err := m.Add(caveats...); err != nil {
return "", err
}
mb, err := m.Encode()
if err != nil {
return "", err
}
return macaroon.ToAuthorizationHeader(mb), nil
}
type FlyioMacaroonAuthConfig struct {
Access flyio.Access `json:"access"`
}
func NewFlyioMacaroonAuthConfig(access *flyio.Access) *FlyioMacaroonAuthConfig {
return &FlyioMacaroonAuthConfig{Access: *access}
}
var _ AuthConfig = (*FlyioMacaroonAuthConfig)(nil)
func (c *FlyioMacaroonAuthConfig) AuthRequest(authctx AuthContext, req *http.Request) error {
var ctx = req.Context()
for _, tok := range proxyAuthorizationTokens(req) {
bun, err := flyio.ParseBundle(tok)
if err != nil {
logrus.WithError(err).Warn("bad macaroon format")
continue
}
if _, err := bun.Verify(ctx, machinesapi.DefaultClient); err != nil {
logrus.WithError(err).Warn("bad macaroon signature")
continue
}
if err := bun.Validate(&c.Access); err != nil {
logrus.WithError(err).Warn("bad macaroon authz")
continue
}
return nil
}
return fmt.Errorf("%w: bad or missing proxy auth", ErrNotAuthorized)
}
func (c *FlyioMacaroonAuthConfig) StripHazmat() AuthConfig {
return c
}
// FlySrcAuthConfig allows permitting access to a secret based on the Fly-Src
// header added to Flycast requests between Fly.io machines/apps/orgs.
// https://community.fly.io/t/fly-src-authenticating-http-requests-between-fly-apps/20566
type FlySrcAuthConfig struct {
// AllowedOrgs is a list of Fly.io organization slugs that are allowed to
// use the secret. An empty/missing value means that the `org` portion of
// the Fly-Src header is not checked.
AllowedOrgs []string `json:"allowed_orgs"`
// AllowedApps is a list of Fly.io application slugs that are allowed to use
// the secret. An empty/missing value means that the `app` portion of the
// Fly-Src header is not checked.
AllowedApps []string `json:"allowed_apps"`
// AllowedInstances is a list of Fly.io instance IDs that are allowed to use
// the secret. An empty/missing value means that the `instance` portion of
// the Fly-Src header is not checked.
AllowedInstances []string `json:"allowed_instances"`
}
type FlySrcOpt func(*FlySrcAuthConfig)
// AllowlistFlySrcOrgs sets the list of allowed Fly.io organization slugs.
func AllowlistFlySrcOrgs(orgs ...string) FlySrcOpt {
return func(c *FlySrcAuthConfig) {
c.AllowedOrgs = append(c.AllowedOrgs, orgs...)
}
}
// AllowlistFlySrcApps sets the list of allowed Fly App names.
func AllowlistFlySrcApps(apps ...string) FlySrcOpt {
return func(c *FlySrcAuthConfig) {
c.AllowedApps = append(c.AllowedApps, apps...)
}
}
// AllowlistFlySrcInstances sets the list of allowed Fly.io instances.
func AllowlistFlySrcInstances(instances ...string) FlySrcOpt {
return func(c *FlySrcAuthConfig) {
c.AllowedInstances = append(c.AllowedInstances, instances...)
}
}
// NewFlySrcAuthConfig creates a new FlySrcAuthConfig with the given options.
func NewFlySrcAuthConfig(opts ...FlySrcOpt) *FlySrcAuthConfig {
c := new(FlySrcAuthConfig)
for _, opt := range opts {
opt(c)
}
return c
}
var _ AuthConfig = (*FlySrcAuthConfig)(nil)
func (c *FlySrcAuthConfig) AuthRequest(authctx AuthContext, req *http.Request) error {
flysrcParser := authctx.GetFlysrcParser()
if flysrcParser == nil {
return fmt.Errorf("%w: no flysrc parser", ErrNotAuthorized)
}
fs, err := flysrcParser.FromRequest(req)
if err != nil {
return fmt.Errorf("%w: %w", ErrNotAuthorized, err)
}
if len(c.AllowedOrgs) > 0 && !slices.Contains(c.AllowedOrgs, fs.Org) {
return fmt.Errorf("%w: org %s not allowed", ErrNotAuthorized, fs.Org)
}
if len(c.AllowedApps) > 0 && !slices.Contains(c.AllowedApps, fs.App) {
return fmt.Errorf("%w: app %s not allowed", ErrNotAuthorized, fs.App)
}
if len(c.AllowedInstances) > 0 && !slices.Contains(c.AllowedInstances, fs.Instance) {
return fmt.Errorf("%w: instance %s not allowed", ErrNotAuthorized, fs.Instance)
}
return nil
}
func (c *FlySrcAuthConfig) StripHazmat() AuthConfig {
return c
}
type NoAuthConfig struct{}
var _ AuthConfig = (*NoAuthConfig)(nil)
func (c *NoAuthConfig) AuthRequest(authctx AuthContext, req *http.Request) error {
return nil
}
func (c *NoAuthConfig) StripHazmat() AuthConfig {
return c
}
func proxyAuthorizationTokens(req *http.Request) (ret []string) {
hdrLoop:
for _, hdr := range req.Header.Values(headerProxyAuthorization) {
scheme, rest, ok := strings.Cut(hdr, " ")
if !ok {
logrus.Warn("missing authorization scheme")
continue hdrLoop
}
switch scheme {
case "Bearer", "FlyV1":
ret = append(ret, rest)
case "Basic":
raw, err := base64.StdEncoding.DecodeString(rest)
if err != nil {
logrus.WithError(err).Warn("bad basic auth encoding")
continue hdrLoop
}
_, pword, ok := strings.Cut(string(raw), ":")
if !ok {
logrus.Warn("bad basic auth format")
continue hdrLoop
}
ret = append(ret, pword)
if plainPword, err := url.QueryUnescape(pword); err == nil {
ret = append(ret, plainPword)
}
default:
logrus.WithField("scheme", scheme).Warn("bad authorization scheme")
}
}
return
}