/
factory.go
602 lines (522 loc) · 17 KB
/
factory.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
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
package oauth
import (
"encoding/json"
"fmt"
"golang.org/x/oauth2/github"
"golang.org/x/oauth2/google"
"io/ioutil"
"math/rand"
"net/url"
"strings"
"time"
"github.com/enfabrica/enkit/lib/kflags"
"github.com/enfabrica/enkit/lib/logger"
"github.com/enfabrica/enkit/lib/token"
"golang.org/x/oauth2"
)
type ExtractorFlags struct {
// Version of the cookie format.
Version int
BaseCookie string
SymmetricKey []byte
TokenVerifyingKey []byte
// When generating credentials, how long should the token be valid for?
LoginTime time.Duration
// When checking credentials, tokens older than MaxLoginTime will be
// rejected no matter what.
MaxLoginTime time.Duration
}
func (f *ExtractorFlags) Register(set kflags.FlagSet, prefix string) *ExtractorFlags {
set.IntVar(&f.Version, prefix+"token-version", f.Version,
"Which kind of token to generate. 0 indicates version 0, 1 indicates version 1")
set.DurationVar(&f.LoginTime, prefix+"login-time", f.LoginTime,
"How long should the generated authentication tokens be valid for.")
set.DurationVar(&f.MaxLoginTime, prefix+"max-login-time", f.MaxLoginTime,
"When verifying a cookie, reject cookies older than this long no matter what.")
set.StringVar(&f.BaseCookie, prefix+"base-cookie", "",
"Prefix to append to the cookies used for authentication")
set.ByteFileVar(&f.SymmetricKey, prefix+"token-encryption-key", "",
"Path of the file containing the symmetric key to use to encrypt/decrypt returned client tokens. "+
"If not supplied, a new key is generated")
set.ByteFileVar(&f.TokenVerifyingKey, prefix+"token-verifying-key", "",
"Path of the file containing the public key to use to verify the signature of client tokens. "+
"If both token-encryption-key and token-signing-key are not specified, a key is generated")
return f
}
func DefaultExtractorFlags() *ExtractorFlags {
o := DefaultOptions(nil)
return &ExtractorFlags{
LoginTime: o.loginTime,
MaxLoginTime: o.maxLoginTime,
}
}
type SigningExtractorFlags struct {
*ExtractorFlags
// Keys used to generate signed tokens.
TokenSigningKey []byte
}
func (f *SigningExtractorFlags) Register(set kflags.FlagSet, prefix string) *SigningExtractorFlags {
set.ByteFileVar(&f.TokenSigningKey, prefix+"token-signing-key", "",
"Path of the file containing the private key to use to sign the returned client tokens. "+
"If both token-encryption-key and token-signing-key are not specified, a key is generated")
f.ExtractorFlags.Register(set, prefix)
return f
}
func DefaultSigningExtractorFlags() *SigningExtractorFlags {
return &SigningExtractorFlags{
ExtractorFlags: DefaultExtractorFlags(),
}
}
type RedirectorFlags struct {
*ExtractorFlags
AuthURL string
}
func DefaultRedirectorFlags() *RedirectorFlags {
return &RedirectorFlags{
ExtractorFlags: DefaultExtractorFlags(),
}
}
func (rf *RedirectorFlags) Register(set kflags.FlagSet, prefix string) *RedirectorFlags {
rf.ExtractorFlags.Register(set, prefix)
set.StringVar(&rf.AuthURL, "auth-url", "", "Where to redirect users for authentication.")
return rf
}
// Flags defines the basic configuration parameters to run the oauth cycle.
//
// Use Flags if you have your own code to handle the specific oauth provider.
// To allow the configuration and use of one of the providers this library
// supports, use providers.ProviderFlags.
//
// To pass Flags to one of the constructurs, use `WithFlags`.
type Flags struct {
*SigningExtractorFlags
// The URL at the end of the oauth authentication process.
TargetURL string
// A buffer containing a JSON file with the Credentials struct (below).
// This is passed to WithFileSecrets().
OauthSecretJSON []byte
// Alternative to OauthSecretJSON, OauthSecretID and OauthSecretKey can be used.
OauthSecretID string
OauthSecretKey string
// A JSON file containing all the details of the oauth provider to use.
// See the jsonAuth struct below.
OAuthFile []byte
// How long is the token used to authenticate with the oauth servers.
// Limit the total time a login can take.
AuthTime time.Duration
}
func DefaultFlags() *Flags {
o := DefaultOptions(nil)
return &Flags{
SigningExtractorFlags: DefaultSigningExtractorFlags(),
AuthTime: o.authTime,
}
}
func (f *Flags) Register(set kflags.FlagSet, prefix string) *Flags {
set.ByteFileVar(&f.OauthSecretJSON, prefix+"secret-file", "",
"Path of the file containing the oauth credentials to use with the remote auth provider")
set.StringVar(&f.OauthSecretID, prefix+"secret-id", "",
"Prefer using the --"+prefix+"secret-file option - as it hides the secret from 'ps'. ID of the client to use with the oauth provider")
set.StringVar(&f.OauthSecretKey, prefix+"secret-key", "",
"Prefer using the --"+prefix+"secret-file option - as it hides the secret from 'ps'. Secret key of the client to use with the oauth provider")
set.DurationVar(&f.AuthTime, prefix+"auth-time", f.AuthTime,
"How long should the token forwarded to the remote oauth server be valid for. This bounds how long the oauth authentication process can take at most")
set.ByteFileVar(&f.OAuthFile, prefix+"oauth-file", "",
"JSON file describing the oauth provider and credentials to use, extracts most parameters automatically")
f.SigningExtractorFlags.Register(set, prefix)
return f
}
// Credentials structs are generally read from json files.
// They contain the oauth credentials used by the remote service to recognize the client.
type Credentials struct {
ID string `json:"id"`
Secret string `json:"secret"`
}
type Modifier func(auth *Options) error
type Modifiers []Modifier
func (mods Modifiers) Apply(o *Options) error {
for _, m := range mods {
if err := m(o); err != nil {
return err
}
}
return nil
}
func WithLogging(log logger.Logger) Modifier {
return func(opt *Options) error {
opt.log = log
return nil
}
}
func WithAuthURL(url *url.URL) Modifier {
return func(opt *Options) error {
opt.authURL = url
return nil
}
}
func WithTargetURL(url string) Modifier {
return func(opt *Options) error {
opt.conf.RedirectURL = url
return nil
}
}
func WithScopes(scopes []string) Modifier {
return func(opt *Options) error {
opt.conf.Scopes = append(opt.conf.Scopes, scopes...)
return nil
}
}
func WithSecrets(cid, csecret string) Modifier {
return func(opt *Options) error {
if cid != "" {
opt.conf.ClientID = cid
}
if csecret != "" {
opt.conf.ClientSecret = csecret
}
return nil
}
}
func WithSecretJSON(data []byte) Modifier {
return func(opt *Options) error {
var cred Credentials
if err := json.Unmarshal(data, &cred); err != nil {
return err
}
return WithSecrets(cred.ID, cred.Secret)(opt)
}
}
func WithSecretFile(path string) Modifier {
return func(opt *Options) error {
data, err := ioutil.ReadFile(path)
if err != nil {
return err
}
var cred Credentials
if err := json.Unmarshal(data, &cred); err != nil {
return err
}
return WithSecrets(cred.ID, cred.Secret)(opt)
}
}
func WithEndpoint(endpoint oauth2.Endpoint) Modifier {
return func(opt *Options) error {
opt.conf.Endpoint = endpoint
return nil
}
}
// WithFactory configures a validation factory.
//
// Mandatory. Must be invoked after secrets have been configured.
func WithFactory(factory VerifierFactory) Modifier {
return func(opt *Options) error {
verifier, err := factory(opt.conf)
if err != nil {
return err
}
if err := WithScopes(verifier.Scopes())(opt); err != nil {
return err
}
opt.verifiers = append(opt.verifiers, verifier)
return nil
}
}
func WithModifiers(mods ...Modifier) Modifier {
return func(opt *Options) error {
for _, m := range mods {
if err := m(opt); err != nil {
return err
}
}
return nil
}
}
func WithSymmetricOptions(mods ...token.SymmetricSetter) Modifier {
return func(opt *Options) error {
opt.symmetricSetters = append(opt.symmetricSetters, mods...)
return nil
}
}
func WithSigningOptions(mods ...token.SigningSetter) Modifier {
return func(opt *Options) error {
opt.signingSetters = append(opt.signingSetters, mods...)
return nil
}
}
func WithAuthTime(at time.Duration) Modifier {
return func(opt *Options) error {
opt.authTime = at
return nil
}
}
func WithLoginTime(lt time.Duration) Modifier {
return func(opt *Options) error {
opt.loginTime = lt
return nil
}
}
func WithVersion(version int) Modifier {
return func(opt *Options) error {
if version != 0 && version != 1 {
return fmt.Errorf("invalid version number %d - only 0 or 1 are valid", version)
}
opt.version = version
return nil
}
}
func WithMaxLoginTime(lt time.Duration) Modifier {
return func(opt *Options) error {
opt.maxLoginTime = lt
return nil
}
}
func WithRedirectorFlags(fl *RedirectorFlags) Modifier {
return func(o *Options) error {
authURL := fl.AuthURL
if authURL == "" {
return kflags.NewUsageErrorf("--auth-url must be supplied")
}
if strings.Index(authURL, "//") < 0 {
authURL = "https://" + authURL
}
u, err := url.Parse(authURL)
if err != nil || u.Host == "" {
return kflags.NewUsageErrorf("invalid url %s supplied with --auth-url: %w", fl.AuthURL, err)
}
WithAuthURL(u)(o)
return WithExtractorFlags(fl.ExtractorFlags)(o)
}
}
func WithRng(rng *rand.Rand) Modifier {
return func(o *Options) error {
o.rng = rng
return nil
}
}
func WithExtractorFlags(fl *ExtractorFlags) Modifier {
return func(o *Options) error {
mods := []Modifier{WithCookiePrefix(fl.BaseCookie)}
if len(fl.TokenVerifyingKey) != 0 {
key, err := token.VerifyingKeyFromSlice(fl.TokenVerifyingKey)
if err != nil {
return fmt.Errorf("invalid key specified with --token-verifying-key - %s", err)
}
mods = append(mods, WithSigningOptions(token.UseVerifyingKey(key)))
}
mods = append(mods, WithSymmetricOptions(token.UseSymmetricKey(fl.SymmetricKey)), WithLoginTime(fl.LoginTime), WithMaxLoginTime(fl.MaxLoginTime), WithVersion(fl.Version))
return Modifiers(mods).Apply(o)
}
}
func WithSigningExtractorFlags(fl *SigningExtractorFlags) Modifier {
return func(o *Options) error {
mods := []Modifier{}
if len(fl.TokenSigningKey) != 0 {
key, err := token.SigningKeyFromSlice(fl.TokenSigningKey)
if err != nil {
return fmt.Errorf("invalid key specified with --token-signing-key - %s", err)
}
mods = append(mods, WithSigningOptions(token.UseSigningKey(key)))
}
mods = append(mods, WithExtractorFlags(fl.ExtractorFlags))
return Modifiers(mods).Apply(o)
}
}
func WithCookiePrefix(prefix string) Modifier {
return func(o *Options) error {
o.baseCookie = prefix
return nil
}
}
func WithFlags(fl *Flags) Modifier {
return func(o *Options) error {
var mods []Modifier
if len(fl.OAuthFile) == 0 {
if len(fl.OauthSecretJSON) == 0 && (fl.OauthSecretID == "" || fl.OauthSecretKey == "") {
return fmt.Errorf("you must specify the secret-file or (secret-key and secret-id) options")
}
if len(fl.TargetURL) == 0 {
return fmt.Errorf("you must specify the target-url flag")
}
}
if fl.TargetURL != "" {
mods = append(mods, WithTargetURL(fl.TargetURL))
}
if len(fl.OauthSecretJSON) > 0 {
mods = append(mods, WithSecretJSON(fl.OauthSecretJSON))
}
if len(fl.SymmetricKey) == 0 {
// 0 is the key length, causes the default length to be used.
key, err := token.GenerateSymmetricKey(o.rng, 0)
if err != nil {
return fmt.Errorf("no key specified with --token-encryption-key, and generating one failed with - %w", err)
}
fl.SymmetricKey = key
}
if len(fl.TokenSigningKey) == 0 && len(fl.TokenVerifyingKey) == 0 {
verify, sign, err := token.GenerateSigningKey(o.rng)
if err != nil {
return fmt.Errorf("no key specified with --token-signing-key and --token-verifying-key, and generating one failed with - %s", err)
}
fl.TokenSigningKey = (*sign.ToBytes())[:]
fl.TokenVerifyingKey = (*verify.ToBytes())[:]
}
mods = append(mods,
WithAuthTime(fl.AuthTime),
WithSecrets(fl.OauthSecretID, fl.OauthSecretKey),
WithSigningExtractorFlags(fl.SigningExtractorFlags),
WithOAuthFile(fl.OAuthFile),
)
return Modifiers(mods).Apply(o)
}
}
func WithOAuthFile(fileContent []byte) Modifier {
return func(opt *Options) error {
if len(fileContent) == 0 {
return nil
}
type jsonAuth struct {
Type string
Name string
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
}
d := jsonAuth{}
if err := json.Unmarshal(fileContent, &d); err != nil {
return err
}
var endpoint oauth2.Endpoint
if d.Type == "google" {
endpoint = google.Endpoint
} else if d.Type == "github" {
endpoint = github.Endpoint
} else {
return fmt.Errorf("oauth: authentication endpoint %s is not supported", d.Type)
}
c := oauth2.Config{
ClientID: d.ClientID,
ClientSecret: d.ClientSecret,
Endpoint: endpoint,
RedirectURL: opt.conf.RedirectURL,
Scopes: []string{"email"},
}
opt.conf = &c
return nil
}
}
type Options struct {
rng *rand.Rand
authTime time.Duration // How long the user has to complete authentication.
loginTime time.Duration // How long the token is valid for after successful authentication.
maxLoginTime time.Duration // Tokens issued more than maxLoginTime ago will always be rejected.
version int
conf *oauth2.Config
verifiers []Verifier
baseCookie string
authURL *url.URL // Only used by the Redirector.
symmetricSetters []token.SymmetricSetter
signingSetters []token.SigningSetter
log logger.Logger
}
func DefaultOptions(rng *rand.Rand) Options {
return Options{
rng: rng,
authTime: time.Minute * 30,
loginTime: time.Hour * 24,
maxLoginTime: time.Hour * 24 * 365,
conf: &oauth2.Config{},
log: logger.Nil,
}
}
func (opt *Options) NewAuthenticator() (*Authenticator, error) {
extractor, err := opt.NewExtractor()
if err != nil {
return nil, err
}
be, err := token.NewSymmetricEncoder(opt.rng, opt.symmetricSetters...)
if err != nil {
return nil, fmt.Errorf("error setting up authenticating cipher: %w", err)
}
te := token.NewTypeEncoder(token.NewChainedEncoder(token.NewTimeEncoder(nil, opt.authTime), be, token.NewBase64UrlEncoder()))
authenticator := &Authenticator{
Extractor: *extractor,
rng: opt.rng,
log: opt.log,
authEncoder: te,
verifiers: opt.verifiers,
conf: opt.conf,
}
if authenticator.conf.RedirectURL == "" {
return nil, fmt.Errorf("API used incorrectly - must supply a target auth url with WithTargetURL")
}
if authenticator.conf.ClientID == "" || authenticator.conf.ClientSecret == "" {
return nil, fmt.Errorf("API used incorrectly - must supply secrets with WithSecrets")
}
if len(authenticator.verifiers) <= 0 {
return nil, fmt.Errorf("API used incorrectly - must supply at least one verifier with WithFactory")
}
if len(authenticator.conf.Scopes) == 0 {
return nil, fmt.Errorf("API used incorrectly - no scopes configured")
}
if authenticator.conf.Endpoint.AuthURL == "" || authenticator.conf.Endpoint.TokenURL == "" {
return nil, fmt.Errorf("API used incorrectly - endpoint has no AuthURL or TokenURL - %#v", authenticator.conf.Endpoint)
}
return authenticator, nil
}
// NewExtractor creates either a simple Extractor, or a SigningExtractor.
//
// An Extractor is an object able to parse and extract data from a signed and
// encrypted cookie.
//
// A SigningExtractor is just like an extractor, except it is also capable
// of generating new signing cookies.
func (opt *Options) NewExtractor() (*Extractor, error) {
be, err := token.NewSymmetricEncoder(opt.rng, opt.symmetricSetters...)
if err != nil {
return nil, fmt.Errorf("error setting up symmetric cipher: %w", err)
}
se, err := token.NewSigningEncoder(opt.rng, opt.signingSetters...)
if err != nil {
return nil, fmt.Errorf("error setting up signing cipher: %w", err)
}
ue := token.NewBase64UrlEncoder()
return &Extractor{
version: opt.version,
baseCookie: opt.baseCookie,
loginEncoder0: token.NewTypeEncoder(token.NewChainedEncoder(token.NewTimeEncoder(nil, opt.loginTime), be, se, ue)),
loginEncoder1: token.NewTypeEncoder(token.NewChainedEncoder(token.NewTimeEncoder(nil, opt.maxLoginTime), token.NewExpireEncoder(nil, opt.loginTime), be, se, ue)),
}, nil
}
func (opt *Options) NewRedirector() (*Redirector, error) {
extractor, err := opt.NewExtractor()
if err != nil {
return nil, err
}
if opt.authURL == nil {
return nil, fmt.Errorf("API usage error - an authURL must be supplied with WithAuthURL")
}
return &Redirector{
Extractor: extractor,
AuthURL: opt.authURL,
}, nil
}
func NewRedirector(modifiers ...Modifier) (*Redirector, error) {
options := DefaultOptions(nil)
if err := Modifiers(modifiers).Apply(&options); err != nil {
return nil, err
}
return options.NewRedirector()
}
func NewExtractor(modifiers ...Modifier) (*Extractor, error) {
options := DefaultOptions(nil)
if err := Modifiers(modifiers).Apply(&options); err != nil {
return nil, err
}
return options.NewExtractor()
}
func New(rng *rand.Rand, modifiers ...Modifier) (*Authenticator, error) {
options := DefaultOptions(rng)
if err := Modifiers(modifiers).Apply(&options); err != nil {
return nil, err
}
return options.NewAuthenticator()
}