-
Notifications
You must be signed in to change notification settings - Fork 9
/
impl.go
1314 lines (1117 loc) · 31.2 KB
/
impl.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
// @author Couchbase <info@couchbase.com>
// @copyright 2015-2023 Couchbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package cbauthimpl contains internal implementation details of
// cbauth. It's APIs are subject to change without notice.
package cbauthimpl
import (
"bytes"
"crypto/md5"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"reflect"
"strings"
"sync"
"time"
"github.com/couchbase/cbauth/utils"
)
// TLSRefreshCallback type describes callback for reinitializing TLSConfig when ssl certificate
// or client cert auth setting changes.
type TLSRefreshCallback func() error
const (
CFG_CHANGE_CERTS_TLSCONFIG uint64 = 1 << iota
CFG_CHANGE_CLUSTER_ENCRYPTION
CFG_CHANGE_USER_LIMITS
CFG_CHANGE_CLIENT_CERTS_TLSCONFIG
_MAX_CFG_CHANGE_FLAGS
)
// ConfigRefreshCallback type describes the callback called when any of the following
// are updated:
// 1. SSL certificates
// 2. TLS configuration
// 3. Cluster encryption configuration
//
// The clients are notified of the configuration changes by OR'ing
// the appropriate flags defined above and passing them as an argument to the
// callback function.
type ConfigRefreshCallback func(uint64) error
// TLSConfig contains tls settings to be used by cbauth clients
// When something in tls config changes user is notified via TLSRefreshCallback
type TLSConfig struct {
MinVersion uint16
CipherSuites []uint16
CipherSuiteNames []string
CipherSuiteOpenSSLNames []string
PreferServerCipherSuites bool
ClientAuthType tls.ClientAuthType
present bool
PrivateKeyPassphrase []byte
ClientPrivateKeyPassphrase []byte
}
// LimitsConfig contains info about whether Limits needs to be enforced and what
// the limits version is.
type LimitsConfig struct {
EnforceLimits bool
UserLimitsVersion string
}
// ClusterEncryptionConfig contains info about whether to use SSL ports for
// communication channels and whether to disable non-SSL ports.
type ClusterEncryptionConfig struct {
EncryptData bool
DisableNonSSLPorts bool
}
type tlsConfigImport struct {
MinTLSVersion string
Ciphers []uint16
CipherNames []string
CipherOpenSSLNames []string
CipherOrder bool
Present bool
PrivateKeyPassphrase []byte
ClientPrivateKeyPassphrase []byte
}
// ErrNoAuth is an error that is returned when the user credentials
// are not recognized
var ErrNoAuth = errors.New("Authentication failure")
// ErrNoUuid is an error that is returned when the uuid for user is
// empty
var ErrNoUuid = errors.New("No UUID for user")
// ErrCallbackAlreadyRegistered is used to signal that certificate refresh callback is already registered
var ErrCallbackAlreadyRegistered = errors.New("Certificate refresh callback is already registered")
// ErrUserNotFound is used to signal when username can't be extracted from client certificate.
var ErrUserNotFound = errors.New("Username not found")
// Node struct is used as part of Cache messages to describe creds and
// ports of some cluster node.
type Node struct {
Host string
User string
Password string
Ports []int
Local bool
}
func matchHost(n Node, host string) bool {
NodeHostIP := net.ParseIP(n.Host)
HostIP := net.ParseIP(host)
if NodeHostIP.IsLoopback() {
return true
}
if HostIP.IsLoopback() && n.Local {
return true
}
// If both are IP addresses then use the standard API to check if they are equal.
if NodeHostIP != nil && HostIP != nil {
return HostIP.Equal(NodeHostIP)
}
return host == n.Host
}
func getMemcachedCreds(n Node, host string, port int) (user, password string) {
if !matchHost(n, host) {
return "", ""
}
for _, p := range n.Ports {
if p == port {
return n.User, n.Password
}
}
return "", ""
}
type credsDB struct {
nodes []Node
authCheckURL string
permissionCheckURL string
limitsCheckURL string
uuidCheckURL string
userBucketsURL string
specialUser string
specialPasswords []string
permissionsVersion string
userVersion string
authVersion string
certVersion int
clientCertVersion int
extractUserFromCertURL string
clientCertAuthVersion string
limitsConfig LimitsConfig
clusterEncryptionConfig ClusterEncryptionConfig
tlsConfig TLSConfig
}
// Cache is a structure into which the revrpc json is unmarshalled
type Cache struct {
Nodes []Node
AuthCheckURL string `json:"authCheckUrl"`
PermissionCheckURL string `json:"permissionCheckUrl"`
LimitsCheckURL string
UuidCheckURL string
UserBucketsURL string
SpecialUser string `json:"specialUser"`
SpecialPasswords []string `json:"specialPasswords"`
PermissionsVersion string
LimitsConfig LimitsConfig
UserVersion string
AuthVersion string
CertVersion int
ClientCertVersion int
ExtractUserFromCertURL string `json:"extractUserFromCertURL"`
ClientCertAuthState string `json:"clientCertAuthState"`
ClientCertAuthVersion string `json:"clientCertAuthVersion"`
ClusterEncryptionConfig ClusterEncryptionConfig `json:"clusterEncryptionConfig"`
TLSConfig tlsConfigImport `json:"tlsConfig"`
}
// CredsImpl implements cbauth.Creds interface.
type CredsImpl struct {
name string
domain string
uuid string
password string
s *Svc
}
// Name method returns user name (e.g. for auditing)
func (c *CredsImpl) Name() string {
return c.name
}
// Domain method returns user domain (for auditing)
func (c *CredsImpl) Domain() string {
switch c.domain {
case "admin", "ro_admin":
return "builtin"
}
return c.domain
}
// User method returns user and domain for non-auditing purpose.
func (c *CredsImpl) User() (name, domain string) {
return c.name, c.domain
}
// User uuid used for generating user stats, need not be present.
// Only present for local users.
func (c *CredsImpl) Uuid() (string, error) {
if c.uuid == "" {
return c.uuid, ErrNoUuid
}
return c.uuid, nil
}
// IsAllowed method returns true if the permission is granted
// for these credentials
func (c *CredsImpl) IsAllowed(permission string) (bool, error) {
return checkPermission(c.s, c.name, c.domain, permission)
}
func verifySpecialCreds(db *credsDB, user, password string) bool {
if len(user) == 0 || user[0] != '@' {
return false
}
for _, sp := range db.specialPasswords {
if password == sp {
return true
}
}
return false
}
type semaphore chan int
func (s semaphore) signal() {
<-s
}
func (s semaphore) wait() {
s <- 1
}
type cfgChangeNotifier struct {
l sync.Mutex
ch chan uint64
callback ConfigRefreshCallback
}
func newCfgChangeNotifier() *cfgChangeNotifier {
return &cfgChangeNotifier{
ch: make(chan uint64, 1),
}
}
func (n *cfgChangeNotifier) notifyCfgChangeLocked(changes uint64) {
select {
case n.ch <- changes:
default:
}
}
func (n *cfgChangeNotifier) notifyCfgChange(changes uint64) {
n.l.Lock()
defer n.l.Unlock()
n.notifyCfgChangeLocked(changes)
}
func (n *cfgChangeNotifier) registerCallback(callback ConfigRefreshCallback) error {
n.l.Lock()
defer n.l.Unlock()
if n.callback != nil {
return ErrCallbackAlreadyRegistered
}
n.callback = callback
n.notifyCfgChangeLocked(_MAX_CFG_CHANGE_FLAGS - 1)
return nil
}
func (n *cfgChangeNotifier) getCallback() ConfigRefreshCallback {
n.l.Lock()
defer n.l.Unlock()
return n.callback
}
func (n *cfgChangeNotifier) maybeExecuteCallback(changes uint64) error {
callback := n.getCallback()
if callback != nil {
return callback(changes)
}
return nil
}
func (n *cfgChangeNotifier) loop() {
retry := (<-chan time.Time)(nil)
var changes uint64 = 0
for {
select {
case <-retry:
retry = nil
case changes = <-n.ch:
}
err := n.maybeExecuteCallback(changes)
if err == nil {
retry = nil
changes = 0
continue
}
if retry == nil {
retry = time.After(5 * time.Second)
}
}
}
// NOTE: Type 'tlsNotifier' will be removed when all the clients start
//
// using the new 'RegisterConfigRefreshCallback' API.
type tlsNotifier struct {
l sync.Mutex
ch chan struct{}
callback TLSRefreshCallback
}
func newTLSNotifier() *tlsNotifier {
return &tlsNotifier{
ch: make(chan struct{}, 1),
}
}
func (n *tlsNotifier) notifyTLSChangeLocked() {
select {
case n.ch <- struct{}{}:
default:
}
}
func (n *tlsNotifier) notifyTLSChange() {
n.l.Lock()
defer n.l.Unlock()
n.notifyTLSChangeLocked()
}
func (n *tlsNotifier) registerCallback(callback TLSRefreshCallback) error {
n.l.Lock()
defer n.l.Unlock()
if n.callback != nil {
return ErrCallbackAlreadyRegistered
}
n.callback = callback
n.notifyTLSChangeLocked()
return nil
}
func (n *tlsNotifier) getCallback() TLSRefreshCallback {
n.l.Lock()
defer n.l.Unlock()
return n.callback
}
func (n *tlsNotifier) maybeExecuteCallback() error {
callback := n.getCallback()
if callback != nil {
return callback()
}
return nil
}
func (n *tlsNotifier) loop() {
retry := (<-chan time.Time)(nil)
for {
select {
case <-retry:
retry = nil
case <-n.ch:
}
err := n.maybeExecuteCallback()
if err == nil {
retry = nil
continue
}
if retry == nil {
retry = time.After(5 * time.Second)
}
}
}
// Svc is a struct that holds state of cbauth service.
type Svc struct {
l sync.RWMutex
db *credsDB
staleErr error
freshChan chan struct{}
ulCache ReqCache
uuidCache ReqCache
userBktsCache ReqCache
upCache ReqCache
authCache *utils.Cache
authCacheOnce sync.Once
clientCertCache *utils.Cache
clientCertCacheOnce sync.Once
httpClient *http.Client
semaphore semaphore
tlsNotifier *tlsNotifier
cfgChangeNotifier *cfgChangeNotifier
}
func cacheToCredsDB(c *Cache) (db *credsDB) {
db = &credsDB{
nodes: c.Nodes,
authCheckURL: c.AuthCheckURL,
permissionCheckURL: c.PermissionCheckURL,
limitsCheckURL: c.LimitsCheckURL,
uuidCheckURL: c.UuidCheckURL,
userBucketsURL: c.UserBucketsURL,
specialUser: c.SpecialUser,
specialPasswords: c.SpecialPasswords,
permissionsVersion: c.PermissionsVersion,
limitsConfig: c.LimitsConfig,
userVersion: c.UserVersion,
authVersion: c.AuthVersion,
certVersion: c.CertVersion,
clientCertVersion: c.ClientCertVersion,
extractUserFromCertURL: c.ExtractUserFromCertURL,
clientCertAuthVersion: c.ClientCertAuthVersion,
clusterEncryptionConfig: c.ClusterEncryptionConfig,
tlsConfig: importTLSConfig(&c.TLSConfig, c.ClientCertAuthState),
}
return
}
func updateDBLocked(s *Svc, db *credsDB) {
s.db = db
if s.freshChan != nil {
close(s.freshChan)
s.freshChan = nil
}
}
// UpdateDB is a revrpc method that is used by ns_server update cbauth
// state.
func (s *Svc) UpdateDB(c *Cache, outparam *bool) error {
if outparam != nil {
*outparam = true
}
// BUG(alk): consider some kind of CAS later
db := cacheToCredsDB(c)
s.l.Lock()
cfgChanges := s.needConfigRefresh(db)
updateDBLocked(s, db)
s.l.Unlock()
if cfgChanges != 0 {
s.tlsNotifier.notifyTLSChange()
s.cfgChangeNotifier.notifyCfgChange(cfgChanges)
}
return nil
}
// ResetSvc marks service's db as stale.
func ResetSvc(s *Svc, staleErr error) {
if staleErr == nil {
panic("staleErr must be non-nil")
}
s.l.Lock()
s.staleErr = staleErr
updateDBLocked(s, nil)
s.l.Unlock()
}
func staleError(s *Svc) error {
if s.staleErr == nil {
panic("impossible Svc state where staleErr is nil!")
}
return s.staleErr
}
// NewSVC constructs Svc instance. Period is initial period of time
// where attempts to access stale DB won't cause DBStaleError responses,
// but service will instead wait for UpdateDB call.
func NewSVC(period time.Duration, staleErr error) *Svc {
return NewSVCForTest(period, staleErr, func(period time.Duration, freshChan chan struct{}, body func()) {
time.AfterFunc(period, body)
})
}
// NewSVCForTest constructs Svc isntance.
func NewSVCForTest(period time.Duration, staleErr error, waitfn func(time.Duration, chan struct{}, func())) *Svc {
if staleErr == nil {
panic("staleErr must be non-nil")
}
s := &Svc{
staleErr: staleErr,
semaphore: make(semaphore, 10),
tlsNotifier: newTLSNotifier(),
cfgChangeNotifier: newCfgChangeNotifier(),
}
dt, ok := http.DefaultTransport.(*http.Transport)
if !ok {
panic("http.DefaultTransport not an *http.Transport")
}
tr := &http.Transport{
Proxy: dt.Proxy,
DialContext: dt.DialContext,
MaxIdleConns: dt.MaxIdleConns,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: dt.IdleConnTimeout,
ExpectContinueTimeout: dt.ExpectContinueTimeout,
}
SetTransport(s, tr)
if period != time.Duration(0) {
s.freshChan = make(chan struct{})
waitfn(period, s.freshChan, func() {
s.l.Lock()
if s.freshChan != nil {
close(s.freshChan)
s.freshChan = nil
}
s.l.Unlock()
})
}
go s.tlsNotifier.loop()
go s.cfgChangeNotifier.loop()
return s
}
// SetTransport allows to change RoundTripper for Svc
func SetTransport(s *Svc, rt http.RoundTripper) {
s.httpClient = &http.Client{Transport: rt}
}
func (s *Svc) needConfigRefresh(db *credsDB) uint64 {
var changes uint64 = 0
if s.db == nil {
return _MAX_CFG_CHANGE_FLAGS - 1
}
if s.serverTLSSettingsChanged(db) {
changes |= CFG_CHANGE_CERTS_TLSCONFIG
}
if s.clientTLSSettingsChanged(db) {
changes |= CFG_CHANGE_CLIENT_CERTS_TLSCONFIG
}
if s.db.clusterEncryptionConfig != db.clusterEncryptionConfig {
changes |= CFG_CHANGE_CLUSTER_ENCRYPTION
}
if s.db.limitsConfig != db.limitsConfig {
changes |= CFG_CHANGE_USER_LIMITS
}
return changes
}
func (s *Svc) serverTLSSettingsChanged(db *credsDB) bool {
return s.db.certVersion != db.certVersion ||
s.db.tlsConfig.MinVersion != db.tlsConfig.MinVersion ||
!reflect.DeepEqual(s.db.tlsConfig.CipherSuites,
db.tlsConfig.CipherSuites) ||
s.db.tlsConfig.PreferServerCipherSuites !=
db.tlsConfig.PreferServerCipherSuites ||
s.db.tlsConfig.ClientAuthType != db.tlsConfig.ClientAuthType ||
!reflect.DeepEqual(s.db.tlsConfig.PrivateKeyPassphrase,
db.tlsConfig.PrivateKeyPassphrase)
}
func (s *Svc) clientTLSSettingsChanged(db *credsDB) bool {
return s.db.clientCertVersion != db.clientCertVersion ||
!reflect.DeepEqual(s.db.tlsConfig.ClientPrivateKeyPassphrase,
db.tlsConfig.ClientPrivateKeyPassphrase)
}
func fetchDB(s *Svc) *credsDB {
s.l.RLock()
db := s.db
c := s.freshChan
s.l.RUnlock()
if db != nil || c == nil {
return db
}
// if db is stale try to wait a bit
<-c
// double receive doesn't change anything from correctness
// standpoint (we close channel), but helps a lot for tests
<-c
s.l.RLock()
db = s.db
s.l.RUnlock()
return db
}
const tokenHeader = "ns-server-ui"
// IsAuthTokenPresent returns true iff ns_server's ui token header
// ("ns-server-ui") is set to "yes". UI is using that header to
// indicate that request is using so called token auth.
func IsAuthTokenPresent(req *http.Request) bool {
return req.Header.Get(tokenHeader) == "yes"
}
func copyHeader(name string, from, to http.Header) {
if val := from.Get(name); val != "" {
to.Set(name, val)
}
}
func verifyPasswordOnServer(s *Svc, user, password string) (*CredsImpl, error) {
req, err := http.NewRequest("GET", "http://host/", nil)
if err != nil {
panic("Must not happen: " + err.Error())
}
req.SetBasicAuth(user, password)
return VerifyOnServer(s, req.Header)
}
// VerifyOnBehalf authenticates http request with on behalf header
func VerifyOnBehalf(s *Svc, user, password, onBehalfUser,
onBehalfDomain string) (*CredsImpl, error) {
db := fetchDB(s)
if db == nil {
return nil, staleError(s)
}
if verifySpecialCreds(db, user, password) {
return &CredsImpl{
name: onBehalfUser,
s: s,
domain: onBehalfDomain}, nil
}
return nil, ErrNoAuth
}
// VerifyOnServer authenticates http request by calling POST /_cbauth REST endpoint
func VerifyOnServer(s *Svc, reqHeaders http.Header) (*CredsImpl, error) {
db := fetchDB(s)
if db == nil {
return nil, staleError(s)
}
if s.db.authCheckURL == "" {
return nil, ErrNoAuth
}
s.semaphore.wait()
defer s.semaphore.signal()
req, err := http.NewRequest("POST", db.authCheckURL, nil)
if err != nil {
panic(err)
}
copyHeader(tokenHeader, reqHeaders, req.Header)
copyHeader("ns-server-auth-token", reqHeaders, req.Header)
copyHeader("Cookie", reqHeaders, req.Header)
copyHeader("Authorization", reqHeaders, req.Header)
rv, err := executeReqAndGetCreds(s, req)
if err != nil {
return nil, err
}
return rv, nil
}
func executeReqAndGetCreds(s *Svc, req *http.Request) (*CredsImpl, error) {
hresp, err := s.httpClient.Do(req)
if err != nil {
return nil, err
}
defer hresp.Body.Close()
defer io.Copy(ioutil.Discard, hresp.Body)
if hresp.StatusCode == 401 {
return nil, ErrNoAuth
}
if hresp.StatusCode != 200 {
err = fmt.Errorf("Expecting 200 or 401 from ns_server auth endpoint. Got: %s", hresp.Status)
return nil, err
}
body, err := ioutil.ReadAll(hresp.Body)
if err != nil {
return nil, err
}
resp := struct {
User, Domain, Uuid string
}{}
err = json.Unmarshal(body, &resp)
if err != nil {
return nil, err
}
rv := CredsImpl{name: resp.User, domain: resp.Domain, uuid: resp.Uuid, s: s}
return &rv, nil
}
type ReqCache struct {
cache *utils.Cache
cacheOnce sync.Once
}
type CacheParams struct {
cache *ReqCache
key interface{}
size int
}
type processResponse func(*http.Response) (interface{}, error)
type ReqParams struct {
respCallback processResponse
url string
user string
domain string
service string
permission string
}
func getFromServer(s *Svc, db *credsDB, params *ReqParams) (interface{}, error) {
s.semaphore.wait()
defer s.semaphore.signal()
req, err := http.NewRequest("GET", params.url, nil)
if err != nil {
return nil, err
}
if len(db.specialPasswords) > 0 {
req.SetBasicAuth(db.specialUser, db.specialPasswords[0])
}
v := url.Values{}
v.Set("user", params.user)
v.Set("domain", params.domain)
if params.service != "" {
v.Set("service", params.service)
}
if params.permission != "" {
v.Set("permission", params.permission)
}
req.URL.RawQuery = v.Encode()
hresp, err := s.httpClient.Do(req)
if err != nil {
return nil, err
}
defer hresp.Body.Close()
defer io.Copy(ioutil.Discard, hresp.Body)
val, err := params.respCallback(hresp)
return val, err
}
// GET response callback for GetUserLimits
func processResponseUserLimits(resp *http.Response) (interface{}, error) {
var limits = map[string]int{}
if resp.StatusCode == 200 {
body, readErr := ioutil.ReadAll(resp.Body)
if readErr != nil {
return nil, fmt.Errorf("Unexpected readErr %v", readErr)
}
jsonErr := json.Unmarshal(body, &limits)
if jsonErr != nil {
return nil, fmt.Errorf("Unexpected json unmarshal error %v", jsonErr)
}
return limits, nil
}
return nil, fmt.Errorf("Unexpected return code %v", resp.StatusCode)
}
// GET response callback for GetUserUuid
func processResponseUuid(resp *http.Response) (interface{}, error) {
if resp.StatusCode == 200 {
body, readErr := ioutil.ReadAll(resp.Body)
if readErr != nil {
return nil, fmt.Errorf("Unexpected readErr %v", readErr)
}
uuidResp := struct {
User, Domain, Uuid string
}{}
jsonErr := json.Unmarshal(body, &uuidResp)
if jsonErr != nil {
return nil, fmt.Errorf("Unexpected json unmarshal error %v", jsonErr)
}
if uuidResp.Uuid == "" {
return nil, ErrNoUuid
}
return uuidResp.Uuid, nil
}
return nil, fmt.Errorf("Unexpected return code %v", resp.StatusCode)
}
// GET response callback for GetUserBuckets
func processResponseUserBuckets(resp *http.Response) (interface{}, error) {
var bucketAndPerms = []string{}
if resp.StatusCode == 200 {
body, readErr := ioutil.ReadAll(resp.Body)
if readErr != nil {
return nil, fmt.Errorf("Unexpected readErr %v", readErr)
}
jsonErr := json.Unmarshal(body, &bucketAndPerms)
if jsonErr != nil {
return nil, fmt.Errorf("Unexpected json unmarshal error %v", jsonErr)
}
return bucketAndPerms, nil
}
return nil, fmt.Errorf("Unexpected return code %v", resp.StatusCode)
}
// GET response callback for IsAllowed
func processResponsePermission(resp *http.Response) (interface{}, error) {
switch resp.StatusCode {
case 200:
return true, nil
case 401:
return false, nil
}
return nil, fmt.Errorf("Unexpected return code %v", resp.StatusCode)
}
// Handles GetUserBuckets, GetUserLimits, GetUserUuid, IsAllowed GET requests
func handleGetRequest(s *Svc, db *credsDB, reqParams *ReqParams,
cacheParams *CacheParams) (interface{}, error) {
if cacheParams != nil {
cacheParams.cache.cacheOnce.Do(
func() {
cacheParams.cache.cache = utils.NewCache(cacheParams.size)
})
cachedVal, found := cacheParams.cache.cache.Get(cacheParams.key)
if found {
return cachedVal, nil
}
}
val, err := getFromServer(s, db, reqParams)
if err == nil && cacheParams != nil {
cacheParams.cache.cache.Add(cacheParams.key, val)
}
return val, err
}
type serviceLimits struct {
version string
user string
domain string
service string
}
func GetUserLimits(s *Svc, user, domain, service string) (map[string]int, error) {
var limits = map[string]int{}
if domain != "local" {
return limits, nil
}
db := fetchDB(s)
if db == nil {
return limits, staleError(s)
}
reqParams := &ReqParams{
respCallback: processResponseUserLimits,
url: db.limitsCheckURL,
user: user,
domain: domain,
service: service,
}
cacheParams := &CacheParams{
cache: &s.ulCache,
key: serviceLimits{db.limitsConfig.UserLimitsVersion, user, domain, service},
size: 1024,
}
val, err := handleGetRequest(s, db, reqParams, cacheParams)
if err == nil {
limits = val.(map[string]int)
}
return limits, err
}
type userUUID struct {
version string
user string
domain string
}
func GetUserUuid(s *Svc, user, domain string) (string, error) {
uuid := ""
if domain != "local" {
return uuid, ErrNoUuid
}
db := fetchDB(s)
if db == nil {
return uuid, staleError(s)
}
reqParams := &ReqParams{
respCallback: processResponseUuid,
url: db.uuidCheckURL,
user: user,
domain: domain,
}
cacheParams := &CacheParams{
cache: &s.uuidCache,
key: userUUID{db.userVersion, user, domain},
size: 256,
}
val, err := handleGetRequest(s, db, reqParams, cacheParams)
if err == nil {
uuid = val.(string)
}
return uuid, err
}
type userBuckets struct {
version string
user string
domain string
}
func GetUserBuckets(s *Svc, user, domain string) ([]string, error) {
var bucketAndPerms = []string{}
db := fetchDB(s)
if db == nil {
return bucketAndPerms, staleError(s)
}
reqParams := &ReqParams{
respCallback: processResponseUserBuckets,
url: db.userBucketsURL,
user: user,
domain: domain,
}
cacheParams := &CacheParams{
cache: &s.userBktsCache,
key: userBuckets{db.permissionsVersion, user, domain},