-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathziti.go
2194 lines (1793 loc) · 65.7 KB
/
ziti.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
/*
Copyright 2019 NetFoundry 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
https://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 ziti
import (
"encoding/json"
"fmt"
"github.com/go-openapi/strfmt"
"github.com/google/uuid"
"github.com/kataras/go-events"
"github.com/openziti/edge-api/rest_client_api_client/authentication"
"github.com/openziti/edge-api/rest_client_api_client/service"
rest_session "github.com/openziti/edge-api/rest_client_api_client/session"
"github.com/openziti/foundation/v2/concurrenz"
"github.com/openziti/foundation/v2/errorz"
"github.com/openziti/foundation/v2/stringz"
apis "github.com/openziti/sdk-golang/edge-apis"
"github.com/openziti/secretstream/kx"
"math"
"math/rand"
"net"
"net/url"
"reflect"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/michaelquigley/pfxlog"
"github.com/openziti/channel/v3"
"github.com/openziti/channel/v3/latency"
"github.com/openziti/edge-api/rest_client_api_client/current_api_session"
"github.com/openziti/edge-api/rest_model"
"github.com/openziti/foundation/v2/versions"
"github.com/openziti/identity"
"github.com/openziti/metrics"
"github.com/openziti/sdk-golang/ziti/edge"
"github.com/openziti/sdk-golang/ziti/edge/network"
"github.com/openziti/sdk-golang/ziti/signing"
"github.com/openziti/transport/v2"
cmap "github.com/orcaman/concurrent-map/v2"
"github.com/pkg/errors"
metrics2 "github.com/rcrowley/go-metrics"
"github.com/sirupsen/logrus"
)
type SessionType rest_model.DialBind
const (
LatencyCheckInterval = 30 * time.Second
LatencyCheckTimeout = 10 * time.Second
ClientConfigV1 = "ziti-tunneler-client.v1"
InterceptV1 = "intercept.v1"
SessionDial = rest_model.DialBindDial
SessionBind = rest_model.DialBindBind
)
// MfaCodeResponse is a handler used to return a string (TOTP) code
type MfaCodeResponse func(code string) error
// Context is the main interface for SDK instances that may be used to authenticate, connect to services, or host
// services.
type Context interface {
// Authenticate attempts to use credentials configured on the Context to perform authentication. The authentication
// implementation used is configured via the Credentials field on an Option struct provided during Context
// creation.
Authenticate() error
// SetCredentials sets the credentials used to authenticate against the Edge Client API.
SetCredentials(authenticator apis.Credentials)
// GetCredentials returns the currently set credentials used to authenticate against the Edge Client API.
GetCredentials() apis.Credentials
// GetCurrentIdentity returns the Edge API details of the currently authenticated identity.
GetCurrentIdentity() (*rest_model.IdentityDetail, error)
// GetCurrentIdentityWithBackoff returns the Edge API details of the currently authenticated identity. with retry if necessary
GetCurrentIdentityWithBackoff() (*rest_model.IdentityDetail, error)
// Dial attempts to connect to a service using a given service name; authenticating as necessary in order to obtain
// a service session, attach to Edge Routers, and connect to a service.
Dial(serviceName string) (edge.Conn, error)
// DialWithOptions performs the same logic as Dial but allows specification of DialOptions.
DialWithOptions(serviceName string, options *DialOptions) (edge.Conn, error)
// DialAddr finds the service for given address and performs a Dial for it.
DialAddr(network string, addr string) (edge.Conn, error)
// Listen attempts to host a service by the given service name; authenticating as necessary in order to obtain
// a service session, attach to Edge Routers, and bind (host) the service.
Listen(serviceName string) (edge.Listener, error)
// ListenWithOptions performs the same logic as Listen, but allows the specification of ListenOptions.
ListenWithOptions(serviceName string, options *ListenOptions) (edge.Listener, error)
// GetServiceId will return the id of a specific service by service name. If not found, false, will be returned
// with an empty string.
GetServiceId(serviceName string) (string, bool, error)
// GetServices will return a slice of service details that the current authenticating identity can access for
// dial (connect) or bind (host/listen).
GetServices() ([]rest_model.ServiceDetail, error)
// GetService will return the service details of a specific service by service name.
GetService(serviceName string) (*rest_model.ServiceDetail, bool)
// GetServiceForAddr finds the service with intercept that matches best to given address
GetServiceForAddr(network, hostname string, port uint16) (*rest_model.ServiceDetail, int, error)
// RefreshServices forces the context to refresh the list of services the current authenticating identity has access
// to.
RefreshServices() error
// RefreshService forces the context to refresh just the service with the given name. If the given service isn't
// found, a nil will be returned
RefreshService(serviceName string) (*rest_model.ServiceDetail, error)
// GetServiceTerminators will return a slice of rest_model.TerminatorClientDetail for a specific service name.
// The offset and limit options can be used to page through excessive lists of items. A max of 500 is imposed on
// limit.
GetServiceTerminators(serviceName string, offset, limit int) ([]*rest_model.TerminatorClientDetail, int, error)
// GetSession will return the session detail associated with a specific session id.
GetSession(id string) (*rest_model.SessionDetail, error)
// Metrics will return the current context's metrics Registry.
Metrics() metrics.Registry
// Close closes any connections open to edge routers
Close()
// Deprecated: AddZitiMfaHandler adds a Ziti MFA handler, invoked during authentication.
// Replaced with event functionality. Use `zitiContext.Events().AddMfaTotpCodeListener(func(Context, *rest_model.AuthQueryDetail, MfaCodeResponse))` instead.
AddZitiMfaHandler(handler func(query *rest_model.AuthQueryDetail, resp MfaCodeResponse) error)
// EnrollZitiMfa will attempt to enable TOTP 2FA on the currently authenticating identity if not already enrolled.
EnrollZitiMfa() (*rest_model.DetailMfa, error)
// VerifyZitiMfa will attempt to complete enrollment of TOTP 2FA with the given code.
VerifyZitiMfa(code string) error
// RemoveZitiMfa will attempt to remove TOTP 2FA for the current identity
RemoveZitiMfa(code string) error
// GetId returns a unique context id
GetId() string
// SetId allows the setting of a context's id
SetId(id string)
Events() Eventer
}
var _ Context = &ContextImpl{}
type ContextImpl struct {
options *Options
Id string
routerConnections cmap.ConcurrentMap[string, edge.RouterConn]
CtrlClt *CtrlClient
services cmap.ConcurrentMap[string, *rest_model.ServiceDetail] // name -> Service
sessions cmap.ConcurrentMap[string, *rest_model.SessionDetail] // svcID:type -> Session
intercepts cmap.ConcurrentMap[string, *edge.InterceptV1Config]
metrics metrics.Registry
firstAuthOnce sync.Once
closed atomic.Bool
closeNotify chan struct{}
authQueryHandlers map[string]func(query *rest_model.AuthQueryDetail, response MfaCodeResponse) error
events.EventEmmiter
lastSuccessfulApiSessionRefresh time.Time
routerProxy func(addr string) *transport.ProxyConfiguration
}
func (context *ContextImpl) AddServiceAddedListener(handler func(Context, *rest_model.ServiceDetail)) func() {
listener := func(args ...interface{}) {
details, ok := args[0].(*rest_model.ServiceDetail)
if !ok {
pfxlog.Logger().Fatalf("could not convert args[0] to %T was %T", details, args[0])
}
if details == nil {
pfxlog.Logger().Fatalf("expected arg[0] was nil, unexpected")
}
handler(context, details)
}
context.AddListener(EventServiceAdded, listener)
return func() {
context.RemoveListener(EventServiceAdded, listener)
}
}
func (context *ContextImpl) AddServiceChangedListener(handler func(Context, *rest_model.ServiceDetail)) func() {
listener := func(args ...interface{}) {
details, ok := args[0].(*rest_model.ServiceDetail)
if !ok {
pfxlog.Logger().Fatalf("could not convert args[0] to %T was %T", details, args[0])
}
if details == nil {
pfxlog.Logger().Fatalf("expected arg[0] was nil, unexpected")
}
handler(context, details)
}
context.AddListener(EventServiceChanged, listener)
return func() {
context.RemoveListener(EventServiceChanged, listener)
}
}
func (context *ContextImpl) AddServiceRemovedListener(handler func(Context, *rest_model.ServiceDetail)) func() {
listener := func(args ...interface{}) {
details, ok := args[0].(*rest_model.ServiceDetail)
if !ok {
pfxlog.Logger().Fatalf("could not convert args[0] to %T was %T", details, args[0])
}
if details == nil {
pfxlog.Logger().Fatalf("expected arg[0] was nil, unexpected")
}
handler(context, details)
}
context.AddListener(EventServiceRemoved, listener)
return func() {
context.RemoveListener(EventServiceRemoved, listener)
}
}
func (context *ContextImpl) AddRouterConnectedListener(handler func(Context, string, string)) func() {
listener := func(args ...interface{}) {
name, ok := args[0].(string)
if !ok {
pfxlog.Logger().Fatalf("could not convert args[0] to %T was %T", name, args[0])
}
addr, ok := args[1].(string)
if !ok {
pfxlog.Logger().Fatalf("could not convert args[1] to %T was %T", addr, args[1])
}
handler(context, name, addr)
}
context.AddListener(EventRouterConnected, listener)
return func() {
context.RemoveListener(EventRouterConnected, listener)
}
}
func (context *ContextImpl) AddRouterDisconnectedListener(handler func(Context, string, string)) func() {
listener := func(args ...interface{}) {
name, ok := args[0].(string)
if !ok {
pfxlog.Logger().Fatalf("could not convert args[0] to %T was %T", name, args[0])
}
addr, ok := args[1].(string)
if !ok {
pfxlog.Logger().Fatalf("could not convert args[1] to %T was %T", addr, args[1])
}
handler(context, name, addr)
}
context.AddListener(EventRouterDisconnected, listener)
return func() {
context.RemoveListener(EventRouterDisconnected, listener)
}
}
func (context *ContextImpl) AddMfaTotpCodeListener(handler func(Context, *rest_model.AuthQueryDetail, MfaCodeResponse)) func() {
listener := func(args ...interface{}) {
authQuery, ok := args[0].(*rest_model.AuthQueryDetail)
if !ok {
pfxlog.Logger().Fatalf("could not convert args[0] to %T was %T", authQuery, args[0])
}
if authQuery == nil {
pfxlog.Logger().Fatalf("expected arg[0] was nil, unexpected")
}
responder, ok := args[1].(MfaCodeResponse)
if !ok {
pfxlog.Logger().Fatalf("could not convert args[1] to %T was %T", responder, args[1])
}
if responder == nil {
pfxlog.Logger().Fatalf("expected arg[0] was nil, unexpected")
}
handler(context, authQuery, responder)
}
context.AddListener(EventMfaTotpCode, listener)
return func() {
context.RemoveListener(EventMfaTotpCode, listener)
}
}
func (context *ContextImpl) AddAuthQueryListener(handler func(Context, *rest_model.AuthQueryDetail)) func() {
listener := func(args ...interface{}) {
authQuery, ok := args[0].(*rest_model.AuthQueryDetail)
if !ok {
pfxlog.Logger().Fatalf("could not convert args[0] to %T was %T", authQuery, args[0])
}
if authQuery == nil {
pfxlog.Logger().Fatalf("expected arg[0] was nil, unexpected")
}
handler(context, authQuery)
}
context.AddListener(EventAuthQuery, listener)
return func() {
context.RemoveListener(EventAuthQuery, listener)
}
}
func (context *ContextImpl) AddAuthenticationStatePartialListener(handler func(Context, apis.ApiSession)) func() {
listener := func(args ...interface{}) {
apiSession, ok := args[0].(apis.ApiSession)
if !ok {
pfxlog.Logger().Fatalf("could not convert args[0] to %T was %T", apiSession, args[0])
}
if apiSession == nil {
pfxlog.Logger().Fatalf("expected arg[0] was nil, unexpected")
}
handler(context, apiSession)
}
context.AddListener(EventAuthenticationStatePartial, listener)
return func() {
context.RemoveListener(EventAuthenticationStatePartial, listener)
}
}
func (context *ContextImpl) AddAuthenticationStateFullListener(handler func(Context, apis.ApiSession)) func() {
listener := func(args ...interface{}) {
apiSession, ok := args[0].(apis.ApiSession)
if !ok {
pfxlog.Logger().Fatalf("could not convert args[0] to %T was %T", apiSession, args[0])
}
if apiSession == nil {
pfxlog.Logger().Fatalf("expected arg[0] was nil, unexpected")
}
handler(context, apiSession)
}
context.AddListener(EventAuthenticationStateFull, listener)
return func() {
context.RemoveListener(EventAuthenticationStateFull, listener)
}
}
func (context *ContextImpl) AddAuthenticationStateUnauthenticatedListener(handler func(Context, apis.ApiSession)) func() {
listener := func(args ...interface{}) {
var apiSession apis.ApiSession
if args[0] != nil {
var ok bool
apiSession, ok = args[0].(apis.ApiSession)
if !ok {
pfxlog.Logger().Fatalf("could not convert args[0] to %T was %T", apiSession, args[0])
}
}
handler(context, apiSession)
}
context.AddListener(EventAuthenticationStateUnauthenticated, listener)
return func() {
context.RemoveListener(EventAuthenticationStateUnauthenticated, listener)
}
}
func (context *ContextImpl) AddControllerUrlsUpdateListener(handler func(Context, []*url.URL)) func() {
listener := func(args ...interface{}) {
var apiUrls []*url.URL
if args[0] != nil {
var ok bool
apiUrls, ok = args[0].([]*url.URL)
if !ok {
pfxlog.Logger().Fatalf("could not convert args[0] to %T was %T", apiUrls, args[0])
}
}
handler(context, apiUrls)
}
context.AddListener(EventControllerUrlsUpdated, listener)
return func() {
context.RemoveListener(EventAuthenticationStateUnauthenticated, listener)
}
}
func (context *ContextImpl) Events() Eventer {
return context
}
func (context *ContextImpl) GetId() string {
return context.Id
}
func (context *ContextImpl) SetId(id string) {
context.Id = id
}
func (context *ContextImpl) SetCredentials(credentials apis.Credentials) {
context.CtrlClt.Credentials = credentials
}
func (context *ContextImpl) GetCredentials() apis.Credentials {
return context.CtrlClt.Credentials
}
func (context *ContextImpl) Sessions() ([]*rest_model.SessionDetail, error) {
var sessions []*rest_model.SessionDetail
context.sessions.IterCb(func(key string, s *rest_model.SessionDetail) {
sessions = append(sessions, s)
})
return sessions, nil
}
func (context *ContextImpl) OnClose(routerConn edge.RouterConn) {
logrus.Debugf("connection to router [%s] was closed", routerConn.Key())
context.Emit(EventRouterDisconnected, routerConn.GetRouterName(), routerConn.Key())
context.routerConnections.Remove(routerConn.Key())
}
func (context *ContextImpl) processServiceUpdates(services []*rest_model.ServiceDetail) {
pfxlog.Logger().Debugf("processing service updates with %v services", len(services))
idMap := make(map[string]*rest_model.ServiceDetail)
for _, s := range services {
idMap[*s.ID] = s
}
// process Deletes
var deletes []string
context.services.IterCb(func(key string, svc *rest_model.ServiceDetail) {
if _, found := idMap[*svc.ID]; !found {
deletes = append(deletes, key)
if context.options.OnServiceUpdate != nil {
context.options.OnServiceUpdate(ServiceRemoved, svc)
}
context.Emit(EventServiceRemoved, svc)
context.deleteServiceSessions(*svc.ID)
}
})
for _, deletedKey := range deletes {
context.services.Remove(deletedKey)
context.intercepts.Remove(deletedKey)
}
// Adds and Updates
for _, s := range services {
context.processServiceAddOrUpdated(s)
}
context.refreshServiceQueryMap()
}
func (context *ContextImpl) processSingleServiceUpdate(name string, s *rest_model.ServiceDetail) {
// process Deletes
if s == nil {
var deletes []string
context.services.IterCb(func(key string, svc *rest_model.ServiceDetail) {
if *svc.Name == name {
deletes = append(deletes, key)
if context.options.OnServiceUpdate != nil {
context.options.OnServiceUpdate(ServiceRemoved, svc)
}
context.Emit(EventServiceRemoved, svc)
context.deleteServiceSessions(*svc.ID)
}
})
for _, deletedKey := range deletes {
context.services.Remove(deletedKey)
context.intercepts.Remove(deletedKey)
}
} else {
// Adds and Updates
context.processServiceAddOrUpdated(s)
}
context.refreshServiceQueryMap()
}
func (context *ContextImpl) processServiceAddOrUpdated(s *rest_model.ServiceDetail) {
isChange := false
valuesDiffer := false
_ = context.services.Upsert(*s.Name, s, func(exist bool, valueInMap *rest_model.ServiceDetail, newValue *rest_model.ServiceDetail) *rest_model.ServiceDetail {
isChange = exist
if isChange {
valuesDiffer = !reflect.DeepEqual(newValue, valueInMap)
}
return newValue
})
if isChange {
context.Emit(EventServiceChanged, s)
} else {
context.Emit(EventServiceAdded, s)
}
if context.options.OnServiceUpdate != nil {
if isChange {
if valuesDiffer {
context.options.OnServiceUpdate(ServiceChanged, s)
}
} else {
context.services.Set(*s.Name, s)
context.options.OnServiceUpdate(ServiceAdded, s)
}
}
intercept := &edge.InterceptV1Config{}
ok, err := edge.ParseServiceConfig(s, InterceptV1, intercept)
if err != nil {
pfxlog.Logger().Warnf("failed to parse config[%s] for service[%s]", InterceptV1, *s.Name)
} else if ok {
intercept.Service = s
context.intercepts.Set(*s.Name, intercept)
} else {
cltCfg := &edge.ClientConfig{}
ok, err := edge.ParseServiceConfig(s, ClientConfigV1, cltCfg)
if err == nil && ok {
intercept = cltCfg.ToInterceptV1Config()
intercept.Service = s
context.intercepts.Set(*s.Name, intercept)
}
}
}
func (context *ContextImpl) refreshServiceQueryMap() {
serviceQueryMap := map[string]map[string]rest_model.PostureQuery{} //serviceId -> queryId -> query
context.services.IterCb(func(key string, svc *rest_model.ServiceDetail) {
for _, querySets := range svc.PostureQueries {
for _, query := range querySets.PostureQueries {
var queryMap map[string]rest_model.PostureQuery
var ok bool
if queryMap, ok = serviceQueryMap[*svc.ID]; !ok {
queryMap = map[string]rest_model.PostureQuery{}
serviceQueryMap[*svc.ID] = queryMap
}
queryMap[*query.ID] = *query
}
}
})
context.CtrlClt.PostureCache.SetServiceQueryMap(serviceQueryMap)
}
func (context *ContextImpl) refreshSessions() {
log := pfxlog.Logger()
edgeRouters := make(map[string]string)
var toDelete []string
for entry := range context.sessions.IterBuffered() {
key := entry.Key
session := entry.Val
log.Debugf("refreshing session for %s", key)
if s, err := context.refreshSession(session); err != nil {
log.WithError(err).Errorf("failed to refresh session for %s", key)
toDelete = append(toDelete, *session.ID)
} else {
for _, er := range s.EdgeRouters {
for _, u := range er.SupportedProtocols {
if context.options.isEdgeRouterUrlAccepted(u) {
edgeRouters[u] = *er.Name
}
}
}
}
}
for _, id := range toDelete {
context.sessions.Remove(id)
}
for u, name := range edgeRouters {
go context.handleConnectEdgeRouter(name, u, nil)
}
}
func (context *ContextImpl) RefreshServices() error {
return context.refreshServices(true)
}
func (context *ContextImpl) refreshServices(forceCheck bool) error {
if err := context.ensureApiSession(); err != nil {
return fmt.Errorf("failed to refresh services: %v", err)
}
var checkService bool
var lastServiceUpdate *strfmt.DateTime
var err error
log := pfxlog.Logger()
log.Debug("checking if service updates available")
if checkService, lastServiceUpdate, err = context.CtrlClt.IsServiceListUpdateAvailable(); err != nil {
log.WithError(err).Error("failed to check if service list update is available")
target := ¤t_api_session.ListServiceUpdatesUnauthorized{}
if errors.As(err, &target) {
checkService = true
} else {
if err = context.Authenticate(); err != nil {
log.WithError(err).Error("unable to re-authenticate during session refresh")
} else {
if checkService, lastServiceUpdate, err = context.CtrlClt.IsServiceListUpdateAvailable(); err != nil {
checkService = true
}
}
}
}
if checkService || forceCheck {
log.Debug("refreshing services")
services, err := context.CtrlClt.GetServices()
if err != nil {
target := &service.ListServicesUnauthorized{}
if errors.As(err, &target) {
log.Info("attempting to re-authenticate")
if authErr := context.Authenticate(); authErr != nil {
log.WithError(authErr).Error("unable to re-authenticate during services refresh")
return err
}
if services, err = context.CtrlClt.GetServices(); err != nil {
return err
}
} else {
return err
}
}
context.CtrlClt.lastServiceUpdate = lastServiceUpdate
context.processServiceUpdates(services)
}
return nil
}
func (context *ContextImpl) RefreshService(serviceName string) (*rest_model.ServiceDetail, error) {
if err := context.ensureApiSession(); err != nil {
return nil, fmt.Errorf("failed to refresh service: %v", err)
}
var err error
log := pfxlog.Logger().WithField("serviceName", serviceName)
log.Debug("refreshing service")
serviceDetail, err := context.CtrlClt.GetService(serviceName)
if err != nil {
target := &service.ListServicesUnauthorized{}
if errors.As(err, &target) {
log.Info("attempting to re-authenticate")
if authErr := context.Authenticate(); authErr != nil {
log.WithError(authErr).Error("unable to re-authenticate during service refresh")
return nil, err
}
if serviceDetail, err = context.CtrlClt.GetService(serviceName); err != nil {
return nil, err
}
} else {
return nil, err
}
}
context.processSingleServiceUpdate(serviceName, serviceDetail)
return serviceDetail, nil
}
func (context *ContextImpl) updateTokenOnAllErs(apiSession apis.ApiSession) {
if apiSession.RequiresRouterTokenUpdate() {
for tpl := range context.routerConnections.IterBuffered() {
erConn := tpl.Val
erKey := tpl.Key
go func() {
if err := erConn.UpdateToken(apiSession.GetToken(), 10*time.Second); err != nil {
pfxlog.Logger().WithError(err).WithField("er", erKey).Warn("error updating apiSession token to connected ER")
}
}()
}
}
}
func (context *ContextImpl) runRefreshes() {
log := pfxlog.Logger()
svcRefreshInterval := context.options.RefreshInterval
if svcRefreshInterval == 0 {
svcRefreshInterval = DefaultServiceRefreshInterval
}
if svcRefreshInterval < MinRefreshInterval {
svcRefreshInterval = MinRefreshInterval
}
svcRefreshTick := time.NewTicker(svcRefreshInterval)
defer svcRefreshTick.Stop()
sessionRefreshInterval := context.options.SessionRefreshInterval
if sessionRefreshInterval == 0 {
sessionRefreshInterval = DefaultSessionRefreshInterval
}
if sessionRefreshInterval < MinRefreshInterval {
sessionRefreshInterval = MinRefreshInterval
}
sessionRefreshTick := time.NewTicker(sessionRefreshInterval)
defer sessionRefreshTick.Stop()
refreshAt := time.Now().Add(30 * time.Second)
if currentApiSession := context.CtrlClt.GetCurrentApiSession(); currentApiSession != nil && currentApiSession.GetExpiresAt() != nil {
refreshAt = (*currentApiSession.GetExpiresAt()).Add(-10 * time.Second)
}
for {
select {
case <-context.closeNotify:
return
case <-time.After(time.Until(refreshAt)):
apiSession := context.CtrlClt.GetCurrentApiSession()
if apiSession == nil {
pfxlog.Logger().Warn("could not refresh api session, current api session is nil, authenticating")
if err := context.Authenticate(); err != nil {
pfxlog.Logger().WithError(err).Error("failed to authenticate")
}
refreshAt = time.Now().Add(5 * time.Second)
continue
}
newApiSession, err := context.CtrlClt.Refresh()
if err != nil {
log.Errorf("could not refresh apiSession: %v", err)
refreshAt = time.Now().Add(5 * time.Second)
} else {
exp := newApiSession.GetExpiresAt()
refreshAt = exp.Add(-10 * time.Second)
log.Debugf("apiSession refreshed, new expiration[%s]", *exp)
context.updateTokenOnAllErs(newApiSession)
}
case <-svcRefreshTick.C:
log.Debug("refreshing services")
if err := context.refreshServices(false); err != nil {
log.WithError(err).Error("failed to load service updates")
}
case <-sessionRefreshTick.C:
log.Debug("refreshing sessions")
context.refreshSessions()
}
}
}
func (context *ContextImpl) EnsureAuthenticated(options edge.ConnOptions) error {
operation := func() error {
pfxlog.Logger().Info("attempting to establish new api session")
err := context.Authenticate()
if err != nil {
return backoff.Permanent(err)
}
return err
}
expBackoff := backoff.NewExponentialBackOff()
expBackoff.MaxInterval = 10 * time.Second
expBackoff.MaxElapsedTime = options.GetConnectTimeout()
return backoff.Retry(operation, expBackoff)
}
func (context *ContextImpl) GetCurrentIdentity() (*rest_model.IdentityDetail, error) {
if err := context.ensureApiSession(); err != nil {
return nil, errors.Wrap(err, "failed to establish api session")
}
return context.CtrlClt.GetCurrentIdentity()
}
func (context *ContextImpl) GetCurrentIdentityWithBackoff() (*rest_model.IdentityDetail, error) {
expBackoff := backoff.NewExponentialBackOff()
expBackoff.InitialInterval = time.Second
expBackoff.MaxInterval = 30 * time.Second
expBackoff.MaxElapsedTime = 5 * time.Minute
var detail *rest_model.IdentityDetail
operation := func() error {
var err error
detail, err = context.GetCurrentIdentity()
return err
}
if err := backoff.Retry(operation, expBackoff); err != nil {
return nil, err
}
return detail, nil
}
func (context *ContextImpl) setUnauthenticated() {
prevApiSessionPtr := context.CtrlClt.ApiSession.Swap(nil)
willEmit := prevApiSessionPtr != nil
context.CtrlClt.ApiSessionCertificate = nil
context.CloseAllEdgeRouterConns()
context.sessions.Clear()
if willEmit {
context.Emit(EventAuthenticationStateUnauthenticated, *prevApiSessionPtr)
}
}
func (context *ContextImpl) authenticate() error {
logrus.Debug("attempting to authenticate")
context.services = cmap.New[*rest_model.ServiceDetail]()
context.sessions = cmap.New[*rest_model.SessionDetail]()
context.intercepts = cmap.New[*edge.InterceptV1Config]()
context.setUnauthenticated()
apiSession, err := context.CtrlClt.Authenticate()
if err != nil {
return err
}
authQueries := apiSession.GetAuthQueries()
if len(authQueries) != 0 {
context.Emit(EventAuthenticationStatePartial, apiSession)
for _, authQuery := range apiSession.GetAuthQueries() {
if err := context.handleAuthQuery(authQuery); err != nil {
return err
}
}
return nil
}
return context.onFullAuth(apiSession)
}
func (context *ContextImpl) Reauthenticate() error {
context.CtrlClt.ApiSession.Store(nil)
context.CtrlClt.ApiSessionCertificate = nil
return context.authenticate()
}
func (context *ContextImpl) Authenticate() error {
if context.CtrlClt.GetCurrentApiSession() != nil {
if time.Since(context.lastSuccessfulApiSessionRefresh) < 5*time.Second {
return nil
}
logrus.Debug("previous apiSession detected, checking if valid")
if err := context.RefreshApiSessionWithBackoff(); err == nil {
logrus.Info("previous apiSession refreshed")
context.lastSuccessfulApiSessionRefresh = time.Now()
return nil
} else {
logrus.WithError(err).Info("previous apiSession failed to refresh, attempting to authenticate")
}
}
return context.authenticate()
}
func (context *ContextImpl) RefreshApiSessionWithBackoff() error {
expBackoff := backoff.NewExponentialBackOff()
expBackoff.InitialInterval = 5 * time.Second
expBackoff.MaxInterval = 5 * time.Minute
expBackoff.MaxElapsedTime = 24 * time.Hour
operation := func() error {
newApiSession, err := context.CtrlClt.Refresh()
if err == nil {
context.updateTokenOnAllErs(newApiSession)
return nil
}
unauthorizedErr := ¤t_api_session.GetCurrentAPISessionUnauthorized{}
if errors.As(err, &unauthorizedErr) {
logrus.Info("previous apiSession expired")
return backoff.Permanent(err)
}
logrus.WithError(err).Info("unable to refresh apiSession, will retry")
return err
}
return backoff.Retry(operation, expBackoff)
}
func (context *ContextImpl) CloseAllEdgeRouterConns() {
for entry := range context.routerConnections.IterBuffered() {
key, val := entry.Key, entry.Val
if !val.IsClosed() {
if err := val.Close(); err != nil {
pfxlog.Logger().WithError(err).Error("error while closing edge router connection")
}
}
context.routerConnections.Remove(key)
}
}
func (context *ContextImpl) onFullAuth(apiSession apis.ApiSession) error {
var doOnceErr error
context.firstAuthOnce.Do(func() {
if context.options.OnContextReady != nil {
context.options.OnContextReady(context)
}
go context.runRefreshes()
metricsTags := map[string]string{
"srcId": apiSession.GetIdentityId(),
}
context.metrics = metrics.NewRegistry(apiSession.GetIdentityName(), metricsTags)
})