/
login.go
867 lines (734 loc) · 27.4 KB
/
login.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package controlplane
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/public"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
"github.com/microsoft/tyger/cli/internal/client"
"github.com/microsoft/tyger/cli/internal/controlplane/model"
"sigs.k8s.io/yaml"
)
const (
CacheFileEnvVarName = "TYGER_CACHE_FILE"
userScope = "Read.Write"
servicePrincipalScope = ".default"
discardTokenIfExpiringWithinSeconds = 10 * 60
LocalUriSentinel = "local"
sshConcurrencyLimit = 8
dockerConcurrencyLimit = 6
)
type LoginConfig struct {
ServerUri string `json:"serverUri"`
ServicePrincipal string `json:"servicePrincipal,omitempty"`
CertificatePath string `json:"certificatePath,omitempty"`
CertificateThumbprint string `json:"certificateThumbprint,omitempty"`
Proxy string `json:"proxy,omitempty"`
DisableTlsCertificateValidation bool `json:"disableTlsCertificateValidation,omitempty"`
// These are options for tyger-proxy that are ignored here but we don't want unmarshal to fail if present
Port int `json:"port,omitempty"`
AllowedClientCIDRs []string `json:"allowedClientCIDRs,omitempty"`
LogPath string `json:"logPath,omitempty"`
UseDeviceCode bool `json:"-"`
Persisted bool `json:"-"`
}
type serviceInfo struct {
ServerUri string `json:"serverUri"`
parsedServerUri *url.URL
ClientAppUri string `json:"clientAppUri,omitempty"`
ClientId string `json:"clientId,omitempty"`
LastToken string `json:"lastToken,omitempty"`
LastTokenExpiry int64 `json:"lastTokenExpiration,omitempty"`
Principal string `json:"principal,omitempty"`
CertPath string `json:"certPath,omitempty"`
CertThumbprint string `json:"certThumbprint,omitempty"`
Authority string `json:"authority,omitempty"`
Audience string `json:"audience,omitempty"`
FullCache string `json:"fullCache,omitempty"`
DataPlaneProxy string `json:"dataPlaneProxy,omitempty"`
parsedDataPlaneProxy *url.URL
Proxy string `json:"proxy,omitempty"`
parsedProxy *url.URL
DisableTlsCertificateValidation bool `json:"disableTlsCertificateValidation,omitempty"`
confidentialClient *confidential.Client
}
func Login(ctx context.Context, options LoginConfig) (*client.TygerClient, error) {
if options.ServerUri == LocalUriSentinel {
optionsClone := options
optionsClone.ServerUri = client.DefaultControlPlaneUnixSocketUrl
c, errUnix := Login(ctx, optionsClone)
if errUnix == nil {
return c, nil
}
optionsClone.ServerUri = "docker://"
c, errDocker := Login(ctx, optionsClone)
if errDocker == nil {
return c, nil
}
return nil, errUnix
}
normalizedServerUri, err := NormalizeServerUri(options.ServerUri)
if err != nil {
return nil, err
}
options.ServerUri = normalizedServerUri.String()
si := &serviceInfo{
ServerUri: options.ServerUri,
parsedServerUri: normalizedServerUri,
Principal: options.ServicePrincipal,
CertPath: options.CertificatePath,
CertThumbprint: options.CertificateThumbprint,
Proxy: options.Proxy,
DisableTlsCertificateValidation: options.DisableTlsCertificateValidation,
}
defaultClientOptions := client.ClientOptions{
ProxyString: options.Proxy,
DisableTlsCertificateValidation: options.DisableTlsCertificateValidation,
}
if err := client.SetDefaultNetworkClientSettings(&defaultClientOptions); err != nil {
return nil, err
}
var tygerClient *client.TygerClient
if normalizedServerUri.Scheme == "docker" {
dockerParams, err := client.ParseDockerUrl(normalizedServerUri)
if err != nil {
return nil, fmt.Errorf("invalid Docker URL: %w", err)
}
loginCommand := exec.CommandContext(ctx, "docker", dockerParams.FormatLoginArgs()...)
var outb, errb bytes.Buffer
loginCommand.Stdout = &outb
loginCommand.Stderr = &errb
if err := loginCommand.Run(); err != nil {
return nil, fmt.Errorf("failed to establish a tyger connection: %w. stderr: %s", err, errb.String())
}
socketUrl, err := NormalizeServerUri(outb.String())
if err != nil {
return nil, fmt.Errorf("failed to parse socket URL: %w", err)
}
if socketUrl.Scheme != "http+unix" {
panic(fmt.Sprintf("unexpected scheme: %s", socketUrl.Scheme))
}
dockerParams.SocketPath = strings.Split(socketUrl.Path, ":")[0]
si.parsedServerUri = dockerParams.URL()
si.ServerUri = si.parsedServerUri.String()
controlPlaneClientOptions := defaultClientOptions // clone
controlPlaneClientOptions.ProxyString = "none"
controlPlaneClientOptions.CreateTransport = client.MakeCommandTransport(dockerConcurrencyLimit, "docker", dockerParams.FormatCmdLine()...)
controlPlaneClient, err := client.NewControlPlaneClient(&controlPlaneClientOptions)
if err != nil {
return nil, fmt.Errorf("unable to create control plane client: %w", err)
}
dataPlaneClientOptions := controlPlaneClientOptions
dataPlaneClientOptions.DisableRetries = true
dataPlaneClient, err := client.NewDataPlaneClient(&dataPlaneClientOptions)
if err != nil {
return nil, fmt.Errorf("unable to create data plane client: %w", err)
}
tygerClient = &client.TygerClient{
ControlPlaneUrl: socketUrl,
ControlPlaneClient: controlPlaneClient,
GetAccessToken: si.GetAccessToken,
DataPlaneClient: dataPlaneClient,
Principal: si.Principal,
RawControlPlaneUrl: si.parsedServerUri,
RawProxy: si.parsedProxy,
}
} else if normalizedServerUri.Scheme == "ssh" {
sshParams, err := client.ParseSshUrl(normalizedServerUri)
if err != nil {
return nil, fmt.Errorf("invalid ssh URL: %w", err)
}
// Give the user a chance accept remote host key if necessary
preFlightCommand := exec.CommandContext(ctx, "ssh", sshParams.FormatLoginArgs("--preflight")...)
preFlightCommand.Stdin = os.Stdin
preFlightCommand.Stdout = os.Stdout
preFlightCommand.Stderr = os.Stderr
if err := preFlightCommand.Run(); err != nil {
return nil, fmt.Errorf("failed to establish a remote tyger connection: %w", err)
}
loginCommand := exec.CommandContext(ctx, "ssh", sshParams.FormatLoginArgs()...)
var outb, errb bytes.Buffer
loginCommand.Stdout = &outb
loginCommand.Stderr = &errb
if err := loginCommand.Run(); err != nil {
return nil, fmt.Errorf("failed to establish a remote tyger connection: %w. stderr: %s", err, errb.String())
}
socketUrl, err := NormalizeServerUri(outb.String())
if err != nil {
return nil, fmt.Errorf("failed to parse socket URL: %w", err)
}
if socketUrl.Scheme != "http+unix" {
panic(fmt.Sprintf("unexpected scheme: %s", socketUrl.Scheme))
}
sshParams.SocketPath = strings.Split(socketUrl.Path, ":")[0]
si.parsedServerUri = sshParams.URL()
si.ServerUri = si.parsedServerUri.String()
controlPlaneOptions := defaultClientOptions // clone
controlPlaneOptions.ProxyString = "none"
controlPlaneOptions.CreateTransport = client.MakeCommandTransport(sshConcurrencyLimit, "ssh", sshParams.FormatCmdLine()...)
controlPlaneClient, err := client.NewControlPlaneClient(&controlPlaneOptions)
if err != nil {
return nil, fmt.Errorf("unable to create control plane client: %w", err)
}
dataPlaneOptions := controlPlaneOptions // clone
dataPlaneOptions.CreateTransport = client.MakeCommandTransport(sshConcurrencyLimit, "ssh", sshParams.FormatDataPlaneCmdLine()...)
dataPlaneClient, err := client.NewDataPlaneClient(&dataPlaneOptions)
if err != nil {
return nil, fmt.Errorf("unable to create data plane client: %w", err)
}
tygerClient = &client.TygerClient{
ControlPlaneUrl: socketUrl,
ControlPlaneClient: controlPlaneClient,
GetAccessToken: si.GetAccessToken,
DataPlaneClient: dataPlaneClient,
Principal: si.Principal,
RawControlPlaneUrl: si.parsedServerUri,
RawProxy: si.parsedProxy,
}
} else {
if err := validateServiceInfo(si); err != nil {
return nil, err
}
serviceMetadata, err := getServiceMetadata(ctx, options.ServerUri)
if err != nil {
return nil, err
}
// augment with data received from the metadata endpoint
si.ServerUri = options.ServerUri
si.Authority = serviceMetadata.Authority
si.Audience = serviceMetadata.Audience
si.ClientAppUri = serviceMetadata.CliAppUri
si.DataPlaneProxy = serviceMetadata.DataPlaneProxy
if err := validateServiceInfo(si); err != nil {
return nil, err
}
if serviceMetadata.Authority != "" {
useServicePrincipal := options.ServicePrincipal != ""
var authResult public.AuthResult
if useServicePrincipal {
authResult, err = si.performServicePrincipalLogin(ctx)
} else {
authResult, err = si.performUserLogin(ctx, options.UseDeviceCode)
}
if err != nil {
return nil, err
}
si.LastToken = authResult.AccessToken
si.LastTokenExpiry = authResult.ExpiresOn.Unix()
if !useServicePrincipal {
si.Principal = authResult.IDToken.PreferredUsername
// We used the client app URI as the client ID when logging in interactively.
// This works, but the refresh token will only be valid for the client ID (GUID).
// So we need to extract the client ID from the access token and use that next time.
claims := jwt.MapClaims{}
if _, _, err := jwt.NewParser().ParseUnverified(authResult.AccessToken, claims); err != nil {
return nil, fmt.Errorf("unable to parse access token: %w", err)
} else {
si.ClientId = claims["appid"].(string)
}
}
}
controlPlaneOptions := defaultClientOptions
dataPlaneOptions := defaultClientOptions
if si.DataPlaneProxy != "" {
dataPlaneOptions.ProxyString = si.DataPlaneProxy
}
switch si.parsedServerUri.Scheme {
case "http+unix", "https+unix":
controlPlaneOptions.DisableRetries = true
dataPlaneOptions.DisableRetries = true
case "http", "https":
default:
panic(fmt.Sprintf("unhandled scheme: %s", si.parsedServerUri.Scheme))
}
cpClient, err := client.NewControlPlaneClient(&controlPlaneOptions)
if err != nil {
return nil, fmt.Errorf("unable to create control plane client: %w", err)
}
dpClient, err := client.NewDataPlaneClient(&controlPlaneOptions)
if err != nil {
return nil, fmt.Errorf("unable to create data plane client: %w", err)
}
tygerClient = &client.TygerClient{
ControlPlaneUrl: si.parsedServerUri,
ControlPlaneClient: cpClient,
GetAccessToken: si.GetAccessToken,
DataPlaneClient: dpClient,
Principal: si.Principal,
RawControlPlaneUrl: si.parsedServerUri,
RawProxy: si.parsedProxy,
}
}
if options.Persisted {
err = si.persist()
if err != nil {
return nil, err
}
}
return tygerClient, nil
}
func NormalizeServerUri(uri string) (*url.URL, error) {
uri = strings.TrimRight(uri, "/")
parsedUrl, err := url.Parse(uri)
if err != nil || !parsedUrl.IsAbs() {
return nil, errors.New("a valid absolute uri is required")
}
if parsedUrl.Scheme == "unix" {
parsedUrl.Scheme = "http+unix"
}
if parsedUrl.Scheme == "http+unix" || parsedUrl.Scheme == "https+unix" {
if !strings.HasSuffix(uri, ":") {
parsedUrl.Path += ":"
}
}
return parsedUrl, err
}
func Logout() error {
return (&serviceInfo{}).persist()
}
func (c *serviceInfo) GetAccessToken(ctx context.Context) (string, error) {
// Quick check to see if the last token is still valid.
// This token is in the full MSAL token cache, but unfortunately calling
// client.AcquireTokenSilent currently always calls an AAD discovery endpoint, which
// can take > 0.5 seconds. So we store it ourselves and use it here if it is still valid.
if c.LastTokenExpiry-discardTokenIfExpiringWithinSeconds > time.Now().UTC().Unix() && c.LastToken != "" {
return c.LastToken, nil
}
if c.Authority == "" {
return "", nil
}
var authResult public.AuthResult
if c.CertPath != "" || c.CertThumbprint != "" {
var err error
authResult, err = c.performServicePrincipalLogin(ctx)
if err != nil {
return "", err
}
} else {
customHttpClient := &clientIdReplacingHttpClient{
clientAppUri: c.ClientAppUri,
clientAppId: c.ClientId,
innerClient: http.DefaultClient,
}
// fall back to using the refresh token from the cache
client, err := public.New(
c.ClientAppUri,
public.WithAuthority(c.Authority),
public.WithCache(c),
public.WithHTTPClient(customHttpClient),
)
if err != nil {
return "", err
}
accounts, err := client.Accounts(ctx)
if err != nil {
return "", fmt.Errorf("unable to get accounts from token cache: %w", err)
}
if len(accounts) != 1 {
return "", errors.New("corrupted token cache")
}
authResult, err = client.AcquireTokenSilent(ctx, []string{fmt.Sprintf("%s/%s", c.Audience, userScope)}, public.WithSilentAccount(accounts[0]))
if err != nil {
return "", err
}
}
c.LastToken = authResult.AccessToken
c.LastTokenExpiry = authResult.ExpiresOn.Unix()
return authResult.AccessToken, c.persist()
}
func GetCachePath() (string, error) {
var cacheDir string
var fileName string
if path := os.Getenv(CacheFileEnvVarName); path != "" {
cacheDir = filepath.Dir(path)
fileName = filepath.Base(path)
} else {
var err error
cacheDir, err = os.UserCacheDir()
if err != nil {
return "", fmt.Errorf("unable to locate cache directory: %w; to provide a file path directly, set the $%s environment variable", err, CacheFileEnvVarName)
}
cacheDir = filepath.Join(cacheDir, "tyger")
fileName = ".tyger"
}
err := os.MkdirAll(cacheDir, 0775)
if err != nil {
return "", fmt.Errorf("unable to create %s directory", cacheDir)
}
return filepath.Join(cacheDir, fileName), nil
}
func (si *serviceInfo) persist() error {
path, err := GetCachePath()
if err == nil {
var bytes []byte
bytes, err = yaml.Marshal(si)
if err == nil {
err = persistCacheContents(path, bytes)
}
}
if err != nil {
return fmt.Errorf("failed to write auth cache: %w", err)
}
return nil
}
func persistCacheContents(path string, bytes []byte) error {
// Write to a temp file in the same directory first
tempFileName := fmt.Sprintf("%s.`%v`", path, uuid.New())
defer os.Remove(tempFileName)
if err := os.WriteFile(tempFileName, bytes, 0600); err != nil {
return err
}
// Now rename the temp file to the final name.
// If the file is not writable due to a permission error,
// it could be because another process is holding the file open.
// In that case, we retry over a short period of time.
var err error
for i := 0; i < 50; i++ {
if i > 0 {
time.Sleep(100 * time.Millisecond)
}
err = os.Rename(tempFileName, path)
if err == nil || !errors.Is(err, os.ErrPermission) {
break
}
}
return err
}
func GetClientFromCache() (*client.TygerClient, error) {
si, err := readCachedServiceInfo()
if err != nil {
return nil, err
}
if si.parsedServerUri == nil {
return nil, errors.New("not logged in")
}
defaultClientOptions := client.ClientOptions{
ProxyString: si.Proxy,
DisableTlsCertificateValidation: si.DisableTlsCertificateValidation,
}
if err := client.SetDefaultNetworkClientSettings(&defaultClientOptions); err != nil {
return nil, err
}
if si.parsedServerUri.Scheme == "docker" {
dockerParams, err := client.ParseDockerUrl(si.parsedServerUri)
if err != nil {
return nil, fmt.Errorf("invalid ssh URL: %w", err)
}
controlPlaneClientOptions := defaultClientOptions
controlPlaneClientOptions.ProxyString = "none"
controlPlaneClientOptions.CreateTransport = client.MakeCommandTransport(dockerConcurrencyLimit, "docker", dockerParams.FormatCmdLine()...)
cpClient, err := client.NewClient(&controlPlaneClientOptions)
if err != nil {
return nil, fmt.Errorf("unable to create control plane client: %w", err)
}
dataPlaneClientOptions := controlPlaneClientOptions // clone
dataPlaneClientOptions.DisableRetries = true
dpClient, err := client.NewDataPlaneClient(&dataPlaneClientOptions)
if err != nil {
return nil, fmt.Errorf("unable to create data plane client: %w", err)
}
endpoint := url.URL{Scheme: "http+unix", Path: fmt.Sprintf("%s:", dockerParams.SocketPath)}
return &client.TygerClient{
ControlPlaneUrl: &endpoint,
ControlPlaneClient: cpClient,
GetAccessToken: si.GetAccessToken,
DataPlaneClient: dpClient,
Principal: si.Principal,
RawControlPlaneUrl: si.parsedServerUri,
RawProxy: si.parsedProxy,
}, nil
} else if si.parsedServerUri.Scheme == "ssh" {
sshParams, err := client.ParseSshUrl(si.parsedServerUri)
if err != nil {
return nil, fmt.Errorf("invalid ssh URL: %w", err)
}
controlPlaneOptions := defaultClientOptions
controlPlaneOptions.ProxyString = "none"
controlPlaneOptions.CreateTransport = client.MakeCommandTransport(sshConcurrencyLimit, "ssh", sshParams.FormatCmdLine()...)
dataPlaneClientOptions := controlPlaneOptions // clone
dataPlaneClientOptions.CreateTransport = client.MakeCommandTransport(sshConcurrencyLimit, "ssh", sshParams.FormatDataPlaneCmdLine()...)
cpClient, err := client.NewClient(&controlPlaneOptions)
if err != nil {
return nil, fmt.Errorf("unable to create control plane client: %w", err)
}
dpClient, err := client.NewDataPlaneClient(&dataPlaneClientOptions)
if err != nil {
return nil, fmt.Errorf("unable to create data plane client: %w", err)
}
endpoint := url.URL{Scheme: "http+unix", Path: fmt.Sprintf("%s:", sshParams.SocketPath)}
return &client.TygerClient{
ControlPlaneUrl: &endpoint,
ControlPlaneClient: cpClient,
GetAccessToken: si.GetAccessToken,
DataPlaneClient: dpClient,
Principal: si.Principal,
RawControlPlaneUrl: si.parsedServerUri,
RawProxy: si.parsedProxy,
}, nil
} else {
controlPlaneOptions := defaultClientOptions
dataPlaneOptions := defaultClientOptions
if si.DataPlaneProxy != "" {
dataPlaneOptions.ProxyString = si.DataPlaneProxy
}
switch si.parsedServerUri.Scheme {
case "http+unix", "https+unix":
controlPlaneOptions.DisableRetries = true
dataPlaneOptions.DisableRetries = true
case "http", "https":
}
controlPlaneClient, err := client.NewClient(&controlPlaneOptions)
if err != nil {
return nil, fmt.Errorf("unable to create control plane client: %w", err)
}
dataPlaneClient, err := client.NewDataPlaneClient(&dataPlaneOptions)
if err != nil {
return nil, fmt.Errorf("unable to create data plane client: %w", err)
}
return &client.TygerClient{
ControlPlaneUrl: si.parsedServerUri,
ControlPlaneClient: controlPlaneClient,
GetAccessToken: si.GetAccessToken,
DataPlaneClient: dataPlaneClient,
Principal: si.Principal,
RawControlPlaneUrl: si.parsedServerUri,
RawProxy: si.parsedProxy,
}, nil
}
}
func validateServiceInfo(si *serviceInfo) error {
var err error
if si.ServerUri != "" {
si.parsedServerUri, err = NormalizeServerUri(si.ServerUri)
if err != nil {
return fmt.Errorf("the server URI is invalid")
}
}
if si.DataPlaneProxy != "" {
si.parsedDataPlaneProxy, err = url.Parse(si.DataPlaneProxy)
if err != nil {
return fmt.Errorf("the data plane proxy URI is invalid")
}
}
switch si.Proxy {
case "none", "auto", "automatic", "":
default:
si.parsedProxy, err = url.Parse(si.Proxy)
if err != nil || si.parsedProxy.Host == "" {
// It may be that the URI was given in the form "host:1234", and the scheme ends up being "host"
si.parsedProxy, err = url.Parse("http://" + si.Proxy)
if err != nil {
return fmt.Errorf("proxy must be 'auto', 'automatic', '' (same as 'auto/automatic'), 'none', or a valid URI")
}
}
}
return nil
}
func readCachedServiceInfo() (*serviceInfo, error) {
path, err := GetCachePath()
if err != nil {
return nil, err
}
var bytes []byte
// If the file is not readable due to a permission error,
// it could be because another process is holding the file open.
// In that case, we retry over a short period of time.
for i := 0; i < 50; i++ {
if i > 0 {
time.Sleep(100 * time.Millisecond)
}
bytes, err = os.ReadFile(path)
if err == nil || !errors.Is(err, os.ErrPermission) {
break
}
}
if err != nil {
return nil, err
}
si := serviceInfo{}
err = yaml.Unmarshal(bytes, &si)
if err != nil {
return nil, err
}
if err := validateServiceInfo(&si); err != nil {
return nil, err
}
return &si, nil
}
func getServiceMetadata(ctx context.Context, serverUri string) (*model.ServiceMetadata, error) {
// Not using a retryable client because when doing `tyger login --local` we first try to use the unix socket
// before trying the docker gateway and we don't want to wait for retries.
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s/v1/metadata", serverUri), nil)
if err != nil {
return nil, fmt.Errorf("unable to create request: %w", err)
}
resp, err := client.DefaultClient.HTTPClient.Do(req)
if err != nil {
return nil, err
}
serviceMetadata := &model.ServiceMetadata{}
if err := json.NewDecoder(resp.Body).Decode(serviceMetadata); err != nil {
return nil, errors.New("the server URL does not appear to point to a valid tyger server")
}
return serviceMetadata, nil
}
func (si *serviceInfo) performServicePrincipalLogin(ctx context.Context) (authResult confidential.AuthResult, err error) {
newClient := si.confidentialClient == nil
if newClient {
cred, err := si.createServicePrincipalCredential()
if err != nil {
return authResult, fmt.Errorf("error creating credential: %w", err)
}
client, err := confidential.New(si.Authority, si.Principal, cred, confidential.WithHTTPClient(client.DefaultClient.StandardClient()))
if err != nil {
return authResult, err
}
si.confidentialClient = &client
}
scopes := []string{fmt.Sprintf("%s/%s", si.Audience, servicePrincipalScope)}
if !newClient {
authResult, err = si.confidentialClient.AcquireTokenSilent(ctx, scopes)
}
if newClient || err != nil {
authResult, err = si.confidentialClient.AcquireTokenByCredential(ctx, scopes)
}
return authResult, err
}
func (si *serviceInfo) createServicePrincipalCredential() (confidential.Credential, error) {
if si.CertThumbprint != "" {
return createCredentialFromSystemCertificateStore(si.CertThumbprint)
}
certBytes, err := os.ReadFile(si.CertPath)
if err != nil {
return confidential.Credential{}, fmt.Errorf("unable to read certificate file: %w", err)
}
certs, privateKey, err := confidential.CertFromPEM(certBytes, "")
if err != nil {
return confidential.Credential{}, fmt.Errorf("error decoding certificate: %w", err)
}
cred, err := confidential.NewCredFromCert(certs, privateKey)
if err != nil {
return confidential.Credential{}, fmt.Errorf("error creating credential: %w", err)
}
return cred, nil
}
func (si *serviceInfo) performUserLogin(ctx context.Context, useDeviceCode bool) (authResult public.AuthResult, err error) {
client, err := public.New(
si.ClientAppUri,
public.WithAuthority(si.Authority),
public.WithCache(si),
public.WithHTTPClient(client.DefaultClient.StandardClient()),
)
if err != nil {
return
}
scopes := []string{fmt.Sprintf("%s/%s", si.Audience, userScope)}
if useDeviceCode {
dc, err := client.AcquireTokenByDeviceCode(ctx, scopes)
if err != nil {
return authResult, err
}
fmt.Println(dc.Result.Message)
return dc.AuthenticationResult(ctx)
}
// 🚨HACK ALERT🚨
// If the BROWSER variable is set, its value should be the preferred
// executable to call to bring up a browser window.
// The underlying library that gets called here (github.com/pkg/browser) only looks for the executables
// "xdg-open", "x-www-browser" and "www-browser", so we put put in a little hack
// to prepend a temp dir to the PATH variable and add an executable shim script called
// "xdg-open" that calls the script in the the BROWSER variable.
// TODO: this has only been tested on Linux.
// TODO: The value could actually be a separated list of executables like in
// https://docs.python.org/3/library/webbrowser.html
if browserVar := os.Getenv("BROWSER"); browserVar != "" {
if _, err := os.Stat(browserVar); err == nil {
tempDir, createDirErr := os.MkdirTemp("", "prefix")
if createDirErr == nil {
defer os.RemoveAll(tempDir)
shimPath := filepath.Join(tempDir, "xdg-open")
shimContents := fmt.Sprintf(`#!/usr/bin/env sh
set -eu
%s "$@"`, browserVar)
if err = os.WriteFile(shimPath, []byte(shimContents), 0700); err == nil {
os.Setenv("PATH", fmt.Sprintf("%s%s%s", tempDir, string(filepath.ListSeparator), os.Getenv("PATH")))
}
}
}
}
timer := time.AfterFunc(time.Second, func() {
fmt.Println("The default web browser has been opened. Please continue the login in the web browser. " +
"If no web browser is available or if the web browser fails to open, use the device code flow with `tyger login --use-device-code`.")
})
authResult, err = client.AcquireTokenInteractive(ctx, scopes, public.WithRedirectURI("http://localhost:41087"))
timer.Stop()
if err == nil {
return authResult, err
}
var exitError *exec.ExitError
if errors.Is(err, exec.ErrNotFound) || errors.As(err, &exitError) {
// this means that we were not able to bring up the browser. Fall back to using the device code flow.
return si.performUserLogin(ctx, true)
}
return authResult, err
}
// Implementing the cache.ExportReplace interface to read in the token cache
func (si *serviceInfo) Replace(ctx context.Context, unmarshaler cache.Unmarshaler, hints cache.ReplaceHints) error {
data, err := base64.StdEncoding.DecodeString(si.FullCache)
if err == nil {
unmarshaler.Unmarshal(data)
}
return err
}
// Implementing the cache.ExportReplace interface to write out the token cache
func (si *serviceInfo) Export(ctx context.Context, marshaler cache.Marshaler, hints cache.ExportHints) error {
data, err := marshaler.Marshal()
if err == nil {
si.FullCache = base64.StdEncoding.EncodeToString(data)
}
return err
}
type clientIdReplacingHttpClient struct {
innerClient *http.Client
clientAppUri string
clientAppId string
}
func (c *clientIdReplacingHttpClient) Do(req *http.Request) (*http.Response, error) {
if req.Method == http.MethodPost && c.clientAppId != "" && c.clientAppUri != "" {
// Replace the client_id in the form data with the client ID of the CLI app
// when POSTing to the token endpoint.
// We used the client app URI as the client ID when logging in interactively,
// but AAD requires the client ID when using the refresh token.
if err := req.ParseForm(); err == nil && req.PostForm != nil {
if clientId := req.PostForm.Get("client_id"); clientId == c.clientAppUri {
req.PostForm.Set("client_id", c.clientAppId)
enc := req.PostForm.Encode()
req.ContentLength = int64(len(enc))
req.Body = io.NopCloser(strings.NewReader(enc))
req.GetBody = func() (io.ReadCloser, error) {
return io.NopCloser(strings.NewReader(enc)), nil
}
}
}
}
return c.innerClient.Do(req)
}
func (c *clientIdReplacingHttpClient) CloseIdleConnections() {
c.innerClient.CloseIdleConnections()
}