forked from pachyderm/pachyderm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
api_server.go
2318 lines (2117 loc) · 72.8 KB
/
api_server.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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package server
import (
"crypto/sha256"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"path"
"regexp"
"strings"
"sync"
"time"
"google.golang.org/grpc/metadata"
etcd "github.com/coreos/etcd/clientv3"
"github.com/crewjam/saml"
"github.com/gogo/protobuf/types"
"github.com/google/go-github/github"
logrus "github.com/sirupsen/logrus"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/sync/errgroup"
"github.com/pachyderm/pachyderm/src/client"
authclient "github.com/pachyderm/pachyderm/src/client/auth"
enterpriseclient "github.com/pachyderm/pachyderm/src/client/enterprise"
"github.com/pachyderm/pachyderm/src/client/pkg/grpcutil"
"github.com/pachyderm/pachyderm/src/client/pps"
"github.com/pachyderm/pachyderm/src/server/pkg/backoff"
col "github.com/pachyderm/pachyderm/src/server/pkg/collection"
"github.com/pachyderm/pachyderm/src/server/pkg/log"
"github.com/pachyderm/pachyderm/src/server/pkg/ppsconsts"
"github.com/pachyderm/pachyderm/src/server/pkg/uuid"
"github.com/pachyderm/pachyderm/src/server/pkg/watch"
)
const (
// DisableAuthenticationEnvVar specifies an environment variable that, if set, causes
// Pachyderm authentication to ignore github and authmatically generate a
// pachyderm token for any username in the AuthenticateRequest.GitHubToken field
DisableAuthenticationEnvVar = "PACHYDERM_AUTHENTICATION_DISABLED_FOR_TESTING"
tokensPrefix = "/tokens"
authenticationCodesPrefix = "/auth-codes"
aclsPrefix = "/acls"
adminsPrefix = "/admins"
membersPrefix = "/members"
groupsPrefix = "/groups"
configPrefix = "/config"
defaultTokenTTLSecs = 30 * 24 * 60 * 60 // 30 days
defaultSAMLTTLSecs = 24 * 60 * 60 // 24 hours
// defaultAuthCodeTTLSecs is the lifetime of an Authentication Code from
// GetOneTimePassword
defaultAuthCodeTTLSecs = 120
// magicUser is a special, unrevokable cluster administrator. It's not
// possible to log in as magicUser, but pipelines with no owner are run as
// magicUser when auth is activated. This string is not secret, but is long
// and random to avoid collisions with real usernames
magicUser = `magic:GZD4jKDGcirJyWQt6HtK4hhRD6faOofP1mng34xNZsI`
// configKey is a key (in etcd, in the config collection) that maps to the
// auth configuration. This is the only key in that collection (due to
// implemenation details of our config library, we can't use an empty key)
configKey = "config"
// SamlPort is the port where SAML ID Providers can send auth assertions
SamlPort = 654
)
// githubTokenRegex is used when pachd is deployed in "dev mode" (i.e. when
// pachd is deployed with "pachctl deploy local") to guess whether a call to
// Authenticate or Authorize contains a real GitHub access token.
//
// If the field GitHubToken matches this regex, it's assumed to be a GitHub
// token and pachd retrieves the corresponding user's GitHub username. If not,
// pachd automatically authenticates the the caller as the GitHub user whose
// username is the string in "GitHubToken".
var githubTokenRegex = regexp.MustCompile("^[0-9a-f]{40}$")
// epsilon is small, nonempty protobuf to use as an etcd value (the etcd client
// library can't distinguish between empty values and missing values, even
// though empty values are still stored in etcd)
var epsilon = &types.BoolValue{Value: true}
type apiServer struct {
pachLogger log.Logger
etcdClient *etcd.Client
address string // address of a Pachd server
pachClient *client.APIClient // pachd client
pachClientOnce sync.Once // used to initialize pachClient
adminCache map[string]struct{} // cache of current cluster admins
adminMu sync.Mutex // guard 'adminCache'
configCache *canonicalConfig // cache of auth config in etcd
configMu sync.Mutex // guard 'configCache'. Always lock before 'samlSPMu' (if using both)
samlSP *saml.ServiceProvider // object for parsing saml responses
redirectAddress *url.URL // address where users will be redirected after authenticating
samlSPMu sync.Mutex // guard 'samlSP'. Always lock after 'configMu' (if using both)
// tokens is a collection of hashedToken -> TokenInfo mappings. These tokens are
// returned to users by Authenticate()
tokens col.Collection
// authenticationCodes is a collection of hash(code) -> TokenInfo mappings.
// These codes are generated internally, and converted to regular tokens by
// Authenticate()
authenticationCodes col.Collection
// acls is a collection of repoName -> ACL mappings.
acls col.Collection
// admins is a collection of username -> Empty mappings (keys indicate which
// github users are cluster admins)
admins col.Collection
// members is a collection of username -> groups mappings.
members col.Collection
// groups is a collection of group -> usernames mappings.
groups col.Collection
// collection containing the auth config (under the key configKey)
authConfig col.Collection
// This is a cache of the PPS master token. It's set once on startup and then
// never updated
ppsToken string
// public addresses the fact that pachd in full mode initializes two auth
// servers: one that exposes a public API, possibly over TLS, and one that
// exposes a private API, for internal services. Only the public-facing auth
// service should export the SAML ACS and Metadata services, so if public
// is true and auth is active, this may export those SAML services
public bool
}
// LogReq is like log.Logger.Log(), but it assumes that it's being called from
// the top level of a GRPC method implementation, and correspondingly extracts
// the method name from the parent stack frame
func (a *apiServer) LogReq(request interface{}) {
a.pachLogger.Log(request, nil, nil, 0)
}
// LogResp is like log.Logger.Log(). However,
// 1) It assumes that it's being called from a defer() statement in a GRPC
// method , and correspondingly extracts the method name from the grandparent
// stack frame
// 2) It logs NotActivatedError at DebugLevel instead of ErrorLevel, as, in most
// cases, this error is expected, and logging it frequently may confuse users
func (a *apiServer) LogResp(request interface{}, response interface{}, err error, duration time.Duration) {
if err == nil {
a.pachLogger.LogAtLevelFromDepth(request, response, err, duration, logrus.InfoLevel, 4)
} else if authclient.IsErrNotActivated(err) {
a.pachLogger.LogAtLevelFromDepth(request, response, err, duration, logrus.DebugLevel, 4)
} else {
a.pachLogger.LogAtLevelFromDepth(request, response, err, duration, logrus.ErrorLevel, 4)
}
}
func (a *apiServer) getPachClient() *client.APIClient {
a.pachClientOnce.Do(func() {
var err error
a.pachClient, err = client.NewFromAddress(a.address)
if err != nil {
panic(err)
}
})
return a.pachClient
}
// NewAuthServer returns an implementation of authclient.APIServer.
func NewAuthServer(pachdAddress string, etcdAddress string, etcdPrefix string, public bool) (authclient.APIServer, error) {
etcdClient, err := etcd.New(etcd.Config{
Endpoints: []string{etcdAddress},
DialOptions: client.DefaultDialOptions(),
})
if err != nil {
return nil, fmt.Errorf("error constructing etcdClient: %v", err)
}
s := &apiServer{
pachLogger: log.NewLogger("authclient.API"),
etcdClient: etcdClient,
address: pachdAddress,
adminCache: make(map[string]struct{}),
tokens: col.NewCollection(
etcdClient,
path.Join(etcdPrefix, tokensPrefix),
nil,
&authclient.TokenInfo{},
nil,
nil,
),
authenticationCodes: col.NewCollection(
etcdClient,
path.Join(etcdPrefix, authenticationCodesPrefix),
nil,
&authclient.OTPInfo{},
nil,
nil,
),
acls: col.NewCollection(
etcdClient,
path.Join(etcdPrefix, aclsPrefix),
nil,
&authclient.ACL{},
nil,
nil,
),
admins: col.NewCollection(
etcdClient,
path.Join(etcdPrefix, adminsPrefix),
nil,
&types.BoolValue{}, // smallest value that etcd actually stores
nil,
nil,
),
members: col.NewCollection(
etcdClient,
path.Join(etcdPrefix, membersPrefix),
nil,
&authclient.Groups{},
nil,
nil,
),
groups: col.NewCollection(
etcdClient,
path.Join(etcdPrefix, groupsPrefix),
nil,
&authclient.Users{},
nil,
nil,
),
authConfig: col.NewCollection(
etcdClient,
path.Join(etcdPrefix, configKey),
nil,
&authclient.AuthConfig{},
nil,
nil,
),
public: public,
}
go s.retrieveOrGeneratePPSToken()
go s.getPachClient() // initialize connection to Pachd
go s.watchAdmins(path.Join(etcdPrefix, adminsPrefix))
if public {
// start SAML service (won't respond to
// anything until config is set)
go s.serveSAML()
}
// Watch for new auth config options
go s.watchConfig()
return s, nil
}
type activationState int
const (
none activationState = iota
partial
full
)
// activationState returns 'none' if auth is totally inactive, 'partial' if
// auth.Activate has been called, but hasn't finished or failed, and full
// if auth.Activate has been called and succeeded.
//
// When the activation state is 'partial' users cannot authenticate; the only
// functioning auth API calls are Activate() (to retry activation) and
// Deactivate() (to give up and revert to the 'none' state)
func (a *apiServer) activationState() activationState {
a.adminMu.Lock()
defer a.adminMu.Unlock()
if len(a.adminCache) == 0 {
return none
}
if _, magicUserIsAdmin := a.adminCache[magicUser]; magicUserIsAdmin {
return partial
}
return full
}
// Retrieve the PPS master token, or generate it and put it in etcd.
// TODO This is a hack. It avoids the need to return superuser tokens from
// GetAuthToken (essentially, PPS and Auth communicate through etcd instead of
// an API) but we should define an internal API and use that instead.
func (a *apiServer) retrieveOrGeneratePPSToken() {
var tokenProto types.StringValue // will contain PPS token
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
b := backoff.NewExponentialBackOff()
b.MaxElapsedTime = 60 * time.Second
b.MaxInterval = 5 * time.Second
if err := backoff.Retry(func() error {
if _, err := col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
superUserTokenCol := col.NewCollection(a.etcdClient, ppsconsts.PPSTokenKey, nil, &types.StringValue{}, nil, nil).ReadWrite(stm)
// TODO(msteffen): Don't use an empty key, as it will not be erased by
// superUserTokenCol.DeleteAll()
err := superUserTokenCol.Get("", &tokenProto)
if err == nil {
return nil
}
if col.IsErrNotFound(err) {
// no existing token yet -- generate token
token := uuid.NewWithoutDashes()
tokenProto.Value = token
if err := superUserTokenCol.Create("", &tokenProto); err != nil {
return err
}
}
return nil
}); err != nil {
return err
}
a.ppsToken = tokenProto.Value
return nil
}, b); err != nil {
panic(fmt.Sprintf("couldn't create/retrieve PPS superuser token within 60s of starting up: %v", err))
}
}
func (a *apiServer) watchAdmins(fullAdminPrefix string) {
b := backoff.NewExponentialBackOff()
backoff.RetryNotify(func() error {
// Watch for the addition/removal of new admins. Note that this will return
// any existing admins, so if the auth service is already activated, it will
// stay activated.
watcher, err := a.admins.ReadOnly(context.Background()).Watch()
if err != nil {
return err
}
defer watcher.Close()
// The auth service is activated if we have admins, and not
// activated otherwise.
for {
ev, ok := <-watcher.Watch()
if !ok {
return errors.New("admin watch closed unexpectedly")
}
b.Reset() // event successfully received
if err := func() error {
// Lock a.adminMu in case we need to modify a.adminCache
a.adminMu.Lock()
defer a.adminMu.Unlock()
// Parse event data and potentially update adminCache
var key string
var boolProto types.BoolValue
ev.Unmarshal(&key, &boolProto)
username := strings.TrimPrefix(key, fullAdminPrefix+"/")
switch ev.Type {
case watch.EventPut:
a.adminCache[username] = struct{}{}
case watch.EventDelete:
delete(a.adminCache, username)
case watch.EventError:
return ev.Err
}
return nil // unlock mu
}(); err != nil {
return err
}
}
}, b, func(err error, d time.Duration) error {
logrus.Errorf("error watching admin collection: %v; retrying in %v", err, d)
return nil
})
}
func (a *apiServer) watchConfig() {
b := backoff.NewExponentialBackOff()
backoff.RetryNotify(func() error {
// Watch for the addition/removal of new admins. Note that this will return
// any existing admins, so if the auth service is already activated, it will
// stay activated.
watcher, err := a.authConfig.ReadOnly(context.Background()).Watch()
if err != nil {
return err
}
defer watcher.Close()
// Wait for new config events to arrive
for {
ev, ok := <-watcher.Watch()
if !ok {
return errors.New("admin watch closed unexpectedly")
}
b.Reset() // event successfully received
if a.activationState() != full {
return fmt.Errorf("received config event while auth not fully " +
"activated (should be impossible), restarting")
}
if err := func() error {
// Lock a.configMu in case we need to modify a.configCache
a.configMu.Lock()
defer a.configMu.Unlock()
a.samlSPMu.Lock()
defer a.samlSPMu.Unlock()
// Parse event data and potentially update configCache
var key string // always configKey, just need to put it somewhere
var configProto authclient.AuthConfig
ev.Unmarshal(&key, &configProto)
switch ev.Type {
case watch.EventPut:
if err := a.updateConfig(&configProto); err != nil {
logrus.Warnf("could not update SAML service with new config: %v", err)
}
case watch.EventDelete:
a.configCache = nil
a.samlSP = nil
case watch.EventError:
return ev.Err
}
return nil // unlock configMu and samlSPMu
}(); err != nil {
return err
}
}
}, b, func(err error, d time.Duration) error {
logrus.Errorf("error watching auth config: %v; retrying in %v", err, d)
return nil
})
}
func (a *apiServer) getEnterpriseTokenState() (enterpriseclient.State, error) {
pachClient := a.getPachClient()
resp, err := pachClient.Enterprise.GetState(context.Background(),
&enterpriseclient.GetStateRequest{})
if err != nil {
return 0, fmt.Errorf("could not get Enterprise status: %v", grpcutil.ScrubGRPC(err))
}
return resp.State, nil
}
func (a *apiServer) Activate(ctx context.Context, req *authclient.ActivateRequest) (resp *authclient.ActivateResponse, retErr error) {
pachClient := a.getPachClient().WithCtx(ctx)
ctx = a.pachClient.Ctx()
// We don't want to actually log the request/response since they contain
// credentials.
defer func(start time.Time) { a.LogResp(nil, nil, retErr, time.Since(start)) }(time.Now())
// If the cluster's Pachyderm Enterprise token isn't active, the auth system
// cannot be activated
state, err := a.getEnterpriseTokenState()
if err != nil {
return nil, fmt.Errorf("error confirming Pachyderm Enterprise token: %v", err)
}
if state != enterpriseclient.State_ACTIVE {
return nil, fmt.Errorf("Pachyderm Enterprise is not active in this " +
"cluster, and the Pachyderm auth API is an Enterprise-level feature")
}
// Activating an already activated auth service should fail, because
// otherwise anyone can just activate the service again and set
// themselves as an admin. If activation failed in PFS, calling auth.Activate
// again should work (in this state, the only admin will be 'magicUser')
if a.activationState() == full {
return nil, fmt.Errorf("already activated")
}
// The Pachyderm token that Activate() returns will have the TTL
// - 'defaultTokenTTLSecs' if the initial admin is a GitHub user (who can get
// a new token by re-authenticating via GitHub after this token expires)
// - 0 (no TTL, indefinite lifetime) if the initial admin is a robot user
// (who has no way to acquire a new token once this token expires)
ttlSecs := int64(defaultTokenTTLSecs)
// Authenticate the caller (or generate a new auth token if req.Subject is a
// robot user)
if req.Subject != "" {
req.Subject, err = a.canonicalizeSubject(ctx, req.Subject)
if err != nil {
return nil, err
}
}
switch {
case req.Subject == "":
fallthrough
case strings.HasPrefix(req.Subject, authclient.GitHubPrefix):
username, err := GitHubTokenToUsername(ctx, req.GitHubToken)
if err != nil {
return nil, err
}
if req.Subject != "" && req.Subject != username {
return nil, fmt.Errorf("asserted subject \"%s\" did not match owner of GitHub token \"%s\"", req.Subject, username)
}
req.Subject = username
case strings.HasPrefix(req.Subject, authclient.RobotPrefix):
// req.Subject will be used verbatim, and the resulting code will
// authenticate the holder as the robot account therein
ttlSecs = 0 // no expiration for robot tokens -- see above
default:
return nil, fmt.Errorf("invalid subject in request (must be a GitHub user or robot): \"%s\"", req.Subject)
}
// Hack: set the cluster admins to just {magicUser}. This puts the auth system
// in the "partial" activation state. Users cannot authenticate, but auth
// checks are now enforced, which means no pipelines or repos can be created
// while ACLs are being added to every repo for the existing pipelines
if _, err = col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
return a.admins.ReadWrite(stm).Put(magicUser, epsilon)
}); err != nil {
return nil, err
}
// wait until watchAdmins has updated the local cache (changing the activation
// state)
b := backoff.NewExponentialBackOff()
b.MaxElapsedTime = 30 * time.Second
if err := backoff.Retry(func() error {
if a.activationState() != partial {
return fmt.Errorf("auth never entered \"partial\" activation state")
}
return nil
}, b); err != nil {
return nil, err
}
time.Sleep(time.Second) // give other pachd nodes time to update their cache
// Call PPS.ActivateAuth to set up all affected pipelines and repos
superUserClient := pachClient.WithCtx(pachClient.Ctx()) // clone pachClient
superUserClient.SetAuthToken(a.ppsToken)
if _, err := superUserClient.ActivateAuth(superUserClient.Ctx(), &pps.ActivateAuthRequest{}); err != nil {
return nil, err
}
// Generate a new Pachyderm token (as the caller is authenticating) and
// initialize admins (watchAdmins() above will see the write)
pachToken := uuid.NewWithoutDashes()
if _, err = col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
admins := a.admins.ReadWrite(stm)
tokens := a.tokens.ReadWrite(stm)
if err := admins.Delete(magicUser); err != nil {
return err
}
if err := admins.Put(req.Subject, epsilon); err != nil {
return err
}
return tokens.PutTTL(
hashToken(pachToken),
&authclient.TokenInfo{
Subject: req.Subject,
Source: authclient.TokenInfo_AUTHENTICATE,
},
ttlSecs,
)
}); err != nil {
return nil, err
}
// wait until watchAdmins has updated the local cache (changing the
// activation state), so that Activate() is less likely to race with
// subsequent calls that expect auth to be activated.
// TODO this is a bit hacky (checking repeatedly in a spin loop) but
// Activate() is rarely called, and it helps avoid races due to other pachd
// pods being out of date.
if err := backoff.Retry(func() error {
if a.activationState() != full {
return fmt.Errorf("auth never entered \"full\" activation state")
}
return nil
}, b); err != nil {
return nil, err
}
time.Sleep(time.Second) // give other pachd nodes time to update their cache
return &authclient.ActivateResponse{PachToken: pachToken}, nil
}
func (a *apiServer) Deactivate(ctx context.Context, req *authclient.DeactivateRequest) (resp *authclient.DeactivateResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
if a.activationState() == none {
// users should be able to call "deactivate" from the "partial" activation
// state, in case activation fails and they need to revert to "none"
return nil, authclient.ErrNotActivated
}
// Check if the cluster is in a partially-activated state. If so, allow it to
// be completely deactivated so that it returns to normal
var magicUserIsAdmin bool
func() {
a.adminMu.Lock()
defer a.adminMu.Unlock()
_, magicUserIsAdmin = a.adminCache[magicUser]
}()
if magicUserIsAdmin {
_, err := col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
a.admins.ReadWrite(stm).DeleteAll() // watchAdmins() will see the write
return nil
})
if err != nil {
return nil, err
}
return &authclient.DeactivateResponse{}, nil
}
// Get calling user. The user must be a cluster admin to disable auth for the
// cluster
callerInfo, err := a.getAuthenticatedUser(ctx)
if err != nil {
return nil, err
}
isAdmin, err := a.isAdmin(ctx, callerInfo.Subject)
if err != nil {
return nil, err
}
if !isAdmin {
return nil, &authclient.ErrNotAuthorized{
Subject: callerInfo.Subject,
AdminOp: "DeactivateAuth",
}
}
_, err = col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
a.acls.ReadWrite(stm).DeleteAll()
a.tokens.ReadWrite(stm).DeleteAll()
a.admins.ReadWrite(stm).DeleteAll() // watchAdmins() will see the write
a.members.ReadWrite(stm).DeleteAll()
a.groups.ReadWrite(stm).DeleteAll()
a.authConfig.ReadWrite(stm).DeleteAll()
return nil
})
if err != nil {
return nil, err
}
// wait until watchAdmins has deactivated auth, so that Deactivate() is less
// likely to race with subsequent calls that expect auth to be deactivated.
// TODO this is a bit hacky (checking repeatedly in a spin loop) but
// Deactivate() is rarely called, and it helps avoid races due to other pachd
// pods being out of date.
if err := backoff.Retry(func() error {
if a.activationState() != none {
return fmt.Errorf("auth still activated")
}
return nil
}, backoff.RetryEvery(time.Second)); err != nil {
return nil, err
}
time.Sleep(time.Second) // give other pachd nodes time to update their cache
return &authclient.DeactivateResponse{}, nil
}
// GitHubTokenToUsername takes a OAuth access token issued by GitHub and uses
// it discover the username of the user who obtained the code (or verify that
// the code belongs to githubUsername). This is how Pachyderm currently
// implements authorization in a production cluster
func GitHubTokenToUsername(ctx context.Context, oauthToken string) (string, error) {
if !githubTokenRegex.MatchString(oauthToken) && os.Getenv(DisableAuthenticationEnvVar) == "true" {
logrus.Warnf("Pachyderm is deployed in DEV mode. The provided auth token "+
"will NOT be verified with GitHub; the caller is automatically "+
"authenticated as the GitHub user \"%s\"", oauthToken)
return authclient.GitHubPrefix + oauthToken, nil
}
// Initialize GitHub client with 'oauthToken'
ts := oauth2.StaticTokenSource(
&oauth2.Token{
AccessToken: oauthToken,
},
)
tc := oauth2.NewClient(ctx, ts)
gclient := github.NewClient(tc)
// Retrieve the caller's GitHub Username (the empty string gets us the
// authenticated user)
user, _, err := gclient.Users.Get(ctx, "")
if err != nil {
return "", fmt.Errorf("error getting the authenticated user: %v", err)
}
verifiedUsername := user.GetLogin()
return authclient.GitHubPrefix + verifiedUsername, nil
}
func (a *apiServer) GetAdmins(ctx context.Context, req *authclient.GetAdminsRequest) (resp *authclient.GetAdminsResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
switch a.activationState() {
case none:
return nil, authclient.ErrNotActivated
case full:
// Get calling user. There is no auth check to see the list of cluster
// admins, other than that the user must log in. Otherwise how will users
// know who to ask for admin privileges? Requiring the user to be logged in
// mitigates phishing
_, err := a.getAuthenticatedUser(ctx)
if err != nil {
return nil, err
}
}
a.adminMu.Lock()
defer a.adminMu.Unlock()
resp = &authclient.GetAdminsResponse{
Admins: make([]string, 0, len(a.adminCache)),
}
for admin := range a.adminCache {
resp.Admins = append(resp.Admins, admin)
}
return resp, nil
}
func (a *apiServer) validateModifyAdminsRequest(add []string, remove []string) error {
// Check to make sure that req doesn't remove all cluster admins
m := make(map[string]struct{})
// copy existing admins into m
func() {
a.adminMu.Lock()
defer a.adminMu.Unlock()
for u := range a.adminCache {
m[u] = struct{}{}
}
}()
for _, u := range add {
m[u] = struct{}{}
}
for _, u := range remove {
delete(m, u)
}
// Confirm that there will be at least one admin.
//
// This is required so that the admin can get the cluster out of any broken
// state that it may enter.
if len(m) == 0 {
return fmt.Errorf("invalid request: cannot remove all cluster administrators while auth is active, to avoid unfixable cluster states")
}
return nil
}
func (a *apiServer) ModifyAdmins(ctx context.Context, req *authclient.ModifyAdminsRequest) (resp *authclient.ModifyAdminsResponse, retErr error) {
a.LogReq(req)
defer func(start time.Time) { a.LogResp(req, resp, retErr, time.Since(start)) }(time.Now())
switch a.activationState() {
case none:
return nil, authclient.ErrNotActivated
case partial:
return nil, authclient.ErrPartiallyActivated
}
// Get calling user. The user must be an admin to change the list of admins
callerInfo, err := a.getAuthenticatedUser(ctx)
if err != nil {
return nil, err
}
isAdmin, err := a.isAdmin(ctx, callerInfo.Subject)
if err != nil {
return nil, err
}
if !isAdmin {
return nil, &authclient.ErrNotAuthorized{
Subject: callerInfo.Subject,
AdminOp: "ModifyAdmins",
}
}
// Canonicalize GitHub usernames in request (must canonicalize before we can
// validate, so we know who is actually being added/removed & can confirm
// that not all admins are being removed)
eg := &errgroup.Group{}
canonicalizedToAdd := make([]string, len(req.Add))
for i, user := range req.Add {
i, user := i, user
eg.Go(func() error {
user, err = a.canonicalizeSubject(ctx, user)
if err != nil {
return err
}
canonicalizedToAdd[i] = user
return nil
})
}
canonicalizedToRemove := make([]string, len(req.Remove))
for i, user := range req.Remove {
i, user := i, user
eg.Go(func() error {
user, err = a.canonicalizeSubject(ctx, user)
if err != nil {
return err
}
canonicalizedToRemove[i] = user
return nil
})
}
if err := eg.Wait(); err != nil {
return nil, err
}
err = a.validateModifyAdminsRequest(canonicalizedToAdd, canonicalizedToRemove)
if err != nil {
return nil, err
}
// Update "admins" list (watchAdmins() will update admins cache)
for _, user := range canonicalizedToAdd {
if _, err = col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
return a.admins.ReadWrite(stm).Put(user, epsilon)
}); err != nil && retErr == nil {
retErr = err
}
}
for _, user := range canonicalizedToRemove {
if _, err = col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
return a.admins.ReadWrite(stm).Delete(user)
}); err != nil && retErr == nil {
retErr = err
}
}
if retErr != nil {
return nil, retErr
}
return &authclient.ModifyAdminsResponse{}, nil
}
// expiredClusterAdminCheck enforces that if the cluster's enterprise token is
// expired, only admins may log in.
func (a *apiServer) expiredClusterAdminCheck(ctx context.Context, username string) error {
state, err := a.getEnterpriseTokenState()
if err != nil {
return fmt.Errorf("error confirming Pachyderm Enterprise token: %v", err)
}
isAdmin, err := a.isAdmin(ctx, username)
if err != nil {
return err
}
if state != enterpriseclient.State_ACTIVE && !isAdmin {
return errors.New("Pachyderm Enterprise is not active in this " +
"cluster (until Pachyderm Enterprise is re-activated or Pachyderm " +
"auth is deactivated, only cluster admins can perform any operations)")
}
return nil
}
func (a *apiServer) Authenticate(ctx context.Context, req *authclient.AuthenticateRequest) (resp *authclient.AuthenticateResponse, retErr error) {
switch a.activationState() {
case none:
// PPS is authenticated by a token read from etcd. It never calls or needs
// to call authenticate, even while the cluster is partway through the
// activation process
return nil, authclient.ErrNotActivated
case partial:
return nil, authclient.ErrPartiallyActivated
}
// We don't want to actually log the request/response since they contain
// credentials.
defer func(start time.Time) { a.LogResp(nil, nil, retErr, time.Since(start)) }(time.Now())
// verify whatever credential the user has presented, and write a new
// Pachyderm token for the user that their credential belongs to
var pachToken string
switch {
case req.GitHubToken != "":
// Determine caller's Pachyderm/GitHub username
username, err := GitHubTokenToUsername(ctx, req.GitHubToken)
if err != nil {
return nil, err
}
// If the cluster's enterprise token is expired, only admins may log in
if err := a.expiredClusterAdminCheck(ctx, username); err != nil {
return nil, err
}
// Generate a new Pachyderm token and write it
pachToken = uuid.NewWithoutDashes()
if _, err := col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
tokens := a.tokens.ReadWrite(stm)
return tokens.PutTTL(hashToken(pachToken),
&authclient.TokenInfo{
Subject: username,
Source: authclient.TokenInfo_AUTHENTICATE,
},
defaultTokenTTLSecs)
}); err != nil {
return nil, fmt.Errorf("error storing auth token for user \"%s\": %v", username, err)
}
case req.OneTimePassword != "":
if _, err := col.NewSTM(ctx, a.etcdClient, func(stm col.STM) error {
// read short-lived authentication code (and delete it if found)
codes := a.authenticationCodes.ReadWrite(stm)
key := hashToken(req.OneTimePassword)
var otpInfo authclient.OTPInfo
if err := codes.Get(key, &otpInfo); err != nil {
return err
}
codes.Delete(key)
// If the cluster's enterprise token is expired, only admins may log in
if err := a.expiredClusterAdminCheck(ctx, otpInfo.Subject); err != nil {
return err
}
// Determine new token's TTL
ttl := int64(defaultTokenTTLSecs)
if otpInfo.SessionExpiration != nil {
expiration, err := types.TimestampFromProto(otpInfo.SessionExpiration)
if err != nil {
return fmt.Errorf("invalid timestamp in OTPInfo, could not " +
"authenticate (try obtaining a new OTP)")
}
if !expiration.IsZero() {
// divide instead of calling Seconds() to avoid float-based rounding
// errors
newTTL := int64(expiration.Sub(time.Now()) / time.Second)
if newTTL < ttl {
ttl = newTTL
}
}
}
// write long-lived pachyderm token
pachToken = uuid.NewWithoutDashes()
return a.tokens.ReadWrite(stm).PutTTL(hashToken(pachToken), &authclient.TokenInfo{
Subject: otpInfo.Subject,
Source: authclient.TokenInfo_AUTHENTICATE,
}, ttl)
}); err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("unrecognized authentication mechanism (old pachd?)")
}
// Return new pachyderm token to caller
return &authclient.AuthenticateResponse{
PachToken: pachToken,
}, nil
}
func (a *apiServer) getCallerTTL(ctx context.Context) (int64, error) {
token, err := getAuthToken(ctx)
if err != nil {
return 0, err
}
ttl, err := a.tokens.ReadOnly(ctx).TTL(hashToken(token)) // lookup token TTL
if err != nil {
return 0, fmt.Errorf("error looking up TTL for token: %v", err)
}
return ttl, nil
}
func (a *apiServer) GetOneTimePassword(ctx context.Context, req *authclient.GetOneTimePasswordRequest) (resp *authclient.GetOneTimePasswordResponse, retErr error) {
// We don't want to actually log the request/response since they contain
// credentials.
defer func(start time.Time) { a.LogResp(nil, nil, retErr, time.Since(start)) }(time.Now())
// Make sure auth is activated
switch a.activationState() {
case none:
// PPS is authenticated by a token read from etcd. It never calls or needs
// to call authenticate, even while the cluster is partway through the
// activation process
return nil, authclient.ErrNotActivated
case partial:
return nil, authclient.ErrPartiallyActivated
}
if req.Subject == magicUser {
return nil, fmt.Errorf("GetAuthTokenRequest.Subject is invalid")
}
// Get current caller and check if they're authorized if req.Subject is set
// to a different user
callerInfo, err := a.getAuthenticatedUser(ctx)
if err != nil {
return nil, err
}
isAdmin, err := a.isAdmin(ctx, callerInfo.Subject)
if err != nil {
return nil, err
}
// Canonicalize req.Subject, authorize caller
if req.Subject == "" {
// [Simple case] caller wants an implicit OTP for themselves
// Canonicalization: callerInfo.Subject is already canonical.
// Authorization: Getting an OTP for yourself is always authorized
// TTL: Use caller's current token if non-admin, default OTP TTL otherwise
// NOTE: After this point, req.Subject may be magicUser (even though we
// reject magicUser when set explicitly
req.Subject = callerInfo.Subject
} else {
// [Harder case] explicit req.Subject
// canonicalize req.Subject
subject, err := a.canonicalizeSubject(ctx, req.Subject)
if err != nil {
return nil, err
}
req.Subject = subject
// Authorization: caller must be admin to get OTP for another user
if !isAdmin && req.Subject != callerInfo.Subject {
return nil, &authclient.ErrNotAuthorized{
Subject: callerInfo.Subject,
AdminOp: "GetOneTimePassword on behalf of another user",