-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathauth_connections.go
More file actions
1644 lines (1488 loc) · 61.1 KB
/
Copy pathauth_connections.go
File metadata and controls
1644 lines (1488 loc) · 61.1 KB
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 cmd
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/kernel/cli/pkg/interactive"
"github.com/kernel/cli/pkg/util"
"github.com/kernel/kernel-go-sdk"
"github.com/kernel/kernel-go-sdk/option"
"github.com/kernel/kernel-go-sdk/packages/pagination"
"github.com/kernel/kernel-go-sdk/packages/ssestream"
"github.com/pterm/pterm"
"github.com/samber/lo"
"github.com/spf13/cobra"
)
// AuthConnectionService defines the subset of the Kernel SDK auth connection client that we use.
type AuthConnectionService interface {
New(ctx context.Context, body kernel.AuthConnectionNewParams, opts ...option.RequestOption) (res *kernel.ManagedAuth, err error)
Get(ctx context.Context, id string, opts ...option.RequestOption) (res *kernel.ManagedAuth, err error)
Update(ctx context.Context, id string, body kernel.AuthConnectionUpdateParams, opts ...option.RequestOption) (res *kernel.ManagedAuth, err error)
List(ctx context.Context, query kernel.AuthConnectionListParams, opts ...option.RequestOption) (res *pagination.OffsetPagination[kernel.ManagedAuth], err error)
Delete(ctx context.Context, id string, opts ...option.RequestOption) (err error)
Login(ctx context.Context, id string, body kernel.AuthConnectionLoginParams, opts ...option.RequestOption) (res *kernel.LoginResponse, err error)
Submit(ctx context.Context, id string, body kernel.AuthConnectionSubmitParams, opts ...option.RequestOption) (res *kernel.SubmitFieldsResponse, err error)
Timeline(ctx context.Context, id string, query kernel.AuthConnectionTimelineParams, opts ...option.RequestOption) (res *pagination.OffsetPagination[kernel.ManagedAuthTimelineEvent], err error)
FollowStreaming(ctx context.Context, id string, opts ...option.RequestOption) (stream *ssestream.Stream[kernel.AuthConnectionFollowResponseUnion])
}
// AuthConnectionCmd handles auth connection operations independent of cobra.
type AuthConnectionCmd struct {
svc AuthConnectionService
prompter interactive.Prompter
}
type AuthConnectionCreateInput struct {
Domain string
ProfileName string
LoginURL string
AllowedDomains []string
CredentialName string
CredentialProvider string
CredentialPath string
CredentialAuto bool
ProxyID string
ProxyName string
ProxyMode string
Stealth BoolFlag
SaveCredentials bool
NoSaveCredentials bool
HealthCheckInterval int
NoHealthChecks bool
NoAutoReauth bool
RecordSession BoolFlag
Telemetry string
TelemetryCdpExclude string
TelemetryExport string
Output string
}
type AuthConnectionGetInput struct {
ID string
Output string
}
type AuthConnectionUpdateInput struct {
ID string
LoginURL string
LoginURLSet bool
AllowedDomains []string
AllowedDomainsSet bool
CredentialName string
CredentialNameSet bool
CredentialProvider string
CredentialProviderSet bool
CredentialPath string
CredentialPathSet bool
CredentialAuto BoolFlag
ProxyID string
ProxyIDSet bool
ProxyName string
ProxyNameSet bool
ProxyMode string
Stealth BoolFlag
SaveCredentials BoolFlag
HealthCheckInterval int
HealthCheckIntervalSet bool
HealthChecks BoolFlag
AutoReauth BoolFlag
RecordSession BoolFlag
Telemetry string
TelemetryCdpExclude string
TelemetryExport string
Output string
}
type AuthConnectionListInput struct {
Domain string
ProfileName string
Query string
Limit int
Offset int
Output string
}
type AuthConnectionDeleteInput struct {
ID string
SkipConfirm bool
}
type AuthConnectionLoginInput struct {
ID string
ProxyID string
ProxyName string
ProxyMode string
Stealth BoolFlag
RecordSession BoolFlag
Telemetry string
TelemetryCdpExclude string
TelemetryExport string
Output string
}
type AuthConnectionSubmitInput struct {
ID string
// FieldValues holds legacy --field name=value pairs, submitted as `fields`.
FieldValues map[string]string
// CanonicalFieldValues holds --field-value id=value pairs, submitted as the
// canonical `field_values` keyed by the field IDs the API returned.
CanonicalFieldValues map[string]string
// SelectedChoiceID is the canonical choice ID from the API's `choices` list.
SelectedChoiceID string
// InteractionID pins the submission to the canonical interaction the values
// were read from. Left empty, the CLI reads the connection's current
// interaction ID, since the API requires one for canonical submissions.
InteractionID string
MfaOptionID string
SignInOptionID string
SSOButtonSelector string
SSOProvider string
Output string
}
type AuthConnectionTimelineInput struct {
ID string
Type string
Page int
PerPage int
Output string
}
type AuthConnectionFollowInput struct {
ID string
Output string
}
func (c AuthConnectionCmd) Create(ctx context.Context, in AuthConnectionCreateInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
if in.Domain == "" {
return fmt.Errorf("--domain is required")
}
if in.ProfileName == "" {
return fmt.Errorf("--profile-name is required")
}
params := kernel.AuthConnectionNewParams{
ManagedAuthCreateRequest: kernel.ManagedAuthCreateRequestParam{
Domain: in.Domain,
ProfileName: in.ProfileName,
},
}
if in.LoginURL != "" {
params.ManagedAuthCreateRequest.LoginURL = kernel.Opt(in.LoginURL)
}
if len(in.AllowedDomains) > 0 {
params.ManagedAuthCreateRequest.AllowedDomains = in.AllowedDomains
}
if in.HealthCheckInterval > 0 {
params.ManagedAuthCreateRequest.HealthCheckInterval = kernel.Opt(int64(in.HealthCheckInterval))
}
// Handle credential reference
if in.CredentialName != "" {
params.ManagedAuthCreateRequest.Credential = kernel.ManagedAuthCreateRequestCredentialParam{
Name: kernel.Opt(in.CredentialName),
}
} else if in.CredentialProvider != "" {
params.ManagedAuthCreateRequest.Credential = kernel.ManagedAuthCreateRequestCredentialParam{
Provider: kernel.Opt(in.CredentialProvider),
}
if in.CredentialPath != "" {
params.ManagedAuthCreateRequest.Credential.Path = kernel.Opt(in.CredentialPath)
} else {
// Default to domain auto-lookup when no explicit --credential-path is
// given. This matches the dashboard's UX, where picking a provider
// without a specific item always means "look up by domain". Without
// this default, the server receives { provider } with no path or
// auto flag, which is a valid-but-inert credential reference that
// causes the managed auth session to never fetch credentials.
params.ManagedAuthCreateRequest.Credential.Auto = kernel.Opt(true)
}
if in.CredentialAuto {
params.ManagedAuthCreateRequest.Credential.Auto = kernel.Opt(true)
}
}
sel := proxySelection{ID: in.ProxyID, Name: in.ProxyName, Mode: in.ProxyMode}
if sel.set() {
proxy, err := buildProxyConfigParam(sel)
if err != nil {
return err
}
params.ManagedAuthCreateRequest.Browser.Proxy = proxy
}
if in.Stealth.Set {
params.ManagedAuthCreateRequest.Browser.Stealth = kernel.Opt(in.Stealth.Value)
}
if in.NoSaveCredentials {
params.ManagedAuthCreateRequest.SaveCredentials = kernel.Opt(false)
}
if in.NoHealthChecks {
params.ManagedAuthCreateRequest.HealthChecks = kernel.Opt(false)
}
if in.NoAutoReauth {
params.ManagedAuthCreateRequest.AutoReauth = kernel.Opt(false)
}
if in.RecordSession.Set {
params.ManagedAuthCreateRequest.RecordSession = kernel.Opt(in.RecordSession.Value)
}
if in.Telemetry != "" || in.TelemetryCdpExclude != "" || in.TelemetryExport != "" {
t, err := buildManagedAuthTelemetryParam(in.Telemetry, in.TelemetryCdpExclude, in.TelemetryExport, true)
if err != nil {
return err
}
params.ManagedAuthCreateRequest.Browser.Telemetry = t
}
if in.Output != "json" {
pterm.Info.Printf("Creating managed auth for %s...\n", in.Domain)
}
auth, err := c.svc.New(ctx, params)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if in.Output == "json" {
return util.PrintPrettyJSON(auth)
}
pterm.Success.Printf("Created managed auth: %s\n", auth.ID)
printManagedAuthSummary(auth)
return nil
}
func printManagedAuthSummary(auth *kernel.ManagedAuth) {
tableData := pterm.TableData{
{"Property", "Value"},
{"ID", auth.ID},
{"Domain", auth.Domain},
{"Profile Name", auth.ProfileName},
{"Status", string(auth.Status)},
{"Can Reauth", fmt.Sprintf("%t", auth.CanReauth)},
}
if auth.CanReauthReason != "" {
tableData = append(tableData, []string{"Can Reauth Reason", string(auth.CanReauthReason)})
}
if auth.Credential.Name != "" {
tableData = append(tableData, []string{"Credential Name", auth.Credential.Name})
}
if auth.Credential.Provider != "" {
tableData = append(tableData, []string{"Credential Provider", auth.Credential.Provider})
}
tableData = append(tableData, managedAuthBrowserRows(auth.Browser)...)
PrintTableNoPad(tableData, true)
}
// managedAuthBrowserRows renders the browser configuration a connection applies to
// its login, reauthentication, and health-check sessions.
func managedAuthBrowserRows(cfg kernel.ManagedAuthBrowserConfig) pterm.TableData {
rows := pterm.TableData{}
if proxy := formatBrowserProxyConfig(cfg.Proxy); proxy != "" {
rows = append(rows, []string{"Browser Proxy", proxy})
}
// Stealth defaults to true when omitted, so only report what the API sent.
if cfg.JSON.Stealth.Valid() {
rows = append(rows, []string{"Browser Stealth", fmt.Sprintf("%t", cfg.Stealth)})
}
if cfg.Telemetry.Enabled || len(telemetryEnabledCategories(kernel.BrowserTelemetryConfig{Browser: cfg.Telemetry.Browser})) > 0 {
rows = append(rows, []string{"Browser Telemetry", formatManagedAuthTelemetry(cfg.Telemetry)})
}
return rows
}
func (c AuthConnectionCmd) Update(ctx context.Context, in AuthConnectionUpdateInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
params := kernel.AuthConnectionUpdateParams{
ManagedAuthUpdateRequest: kernel.ManagedAuthUpdateRequestParam{},
}
hasChanges := false
if in.HealthCheckIntervalSet {
params.ManagedAuthUpdateRequest.HealthCheckInterval = kernel.Opt(int64(in.HealthCheckInterval))
hasChanges = true
}
if in.LoginURLSet {
params.ManagedAuthUpdateRequest.LoginURL = kernel.Opt(in.LoginURL)
hasChanges = true
}
if in.SaveCredentials.Set {
params.ManagedAuthUpdateRequest.SaveCredentials = kernel.Opt(in.SaveCredentials.Value)
hasChanges = true
}
if in.HealthChecks.Set {
params.ManagedAuthUpdateRequest.HealthChecks = kernel.Opt(in.HealthChecks.Value)
hasChanges = true
}
if in.AutoReauth.Set {
params.ManagedAuthUpdateRequest.AutoReauth = kernel.Opt(in.AutoReauth.Value)
hasChanges = true
}
if in.RecordSession.Set {
params.ManagedAuthUpdateRequest.RecordSession = kernel.Opt(in.RecordSession.Value)
hasChanges = true
}
if in.AllowedDomainsSet {
params.ManagedAuthUpdateRequest.AllowedDomains = in.AllowedDomains
hasChanges = true
}
credentialChanged := in.CredentialNameSet || in.CredentialProviderSet || in.CredentialPathSet || in.CredentialAuto.Set
if credentialChanged {
if strings.TrimSpace(in.CredentialName) != "" && strings.TrimSpace(in.CredentialProvider) != "" {
return fmt.Errorf("credential reference must use either --credential-name or --credential-provider")
}
params.ManagedAuthUpdateRequest.Credential = kernel.ManagedAuthUpdateRequestCredentialParam{}
if in.CredentialNameSet {
params.ManagedAuthUpdateRequest.Credential.Name = kernel.Opt(in.CredentialName)
}
if in.CredentialProviderSet {
params.ManagedAuthUpdateRequest.Credential.Provider = kernel.Opt(in.CredentialProvider)
}
if in.CredentialPathSet {
params.ManagedAuthUpdateRequest.Credential.Path = kernel.Opt(in.CredentialPath)
}
if in.CredentialAuto.Set {
params.ManagedAuthUpdateRequest.Credential.Auto = kernel.Opt(in.CredentialAuto.Value)
}
hasChanges = true
}
// A proxy is selected by ID or name, so an empty value is not a way to clear it:
// dropping back to the connection's stealth-derived egress is a mode change.
if (in.ProxyIDSet && in.ProxyID == "") || (in.ProxyNameSet && in.ProxyName == "") {
return fmt.Errorf("proxy selection requires a non-empty value; use --proxy-mode=default to drop the selected proxy, or --proxy-mode=direct for direct egress")
}
sel := proxySelection{ID: in.ProxyID, Name: in.ProxyName, Mode: in.ProxyMode}
if sel.set() {
proxy, err := buildProxyConfigParam(sel)
if err != nil {
return err
}
params.ManagedAuthUpdateRequest.Browser.Proxy = proxy
hasChanges = true
}
if in.Stealth.Set {
params.ManagedAuthUpdateRequest.Browser.Stealth = kernel.Opt(in.Stealth.Value)
hasChanges = true
}
if in.Telemetry != "" || in.TelemetryCdpExclude != "" || in.TelemetryExport != "" {
t, err := buildManagedAuthTelemetryParam(in.Telemetry, in.TelemetryCdpExclude, in.TelemetryExport, false)
if err != nil {
return err
}
params.ManagedAuthUpdateRequest.Browser.Telemetry = t
hasChanges = true
}
if !hasChanges {
return fmt.Errorf("must provide at least one field to update")
}
if in.Output != "json" {
pterm.Info.Printf("Updating managed auth %s...\n", in.ID)
}
auth, err := c.svc.Update(ctx, in.ID, params)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if in.Output == "json" {
return util.PrintPrettyJSON(auth)
}
pterm.Success.Printf("Updated managed auth: %s\n", auth.ID)
printManagedAuthSummary(auth)
return nil
}
// managedAuthInputField is the shared shape of a canonical input field. The SDK
// models the one on `get` and the one on the `follow` event stream as two
// identical but distinct types, so both are converted to this before rendering.
type managedAuthInputField struct {
ID string
Label string
Type string
Ref string
Hint string
Reason string
Required bool
}
// managedAuthInputChoice is the choice counterpart of managedAuthInputField.
type managedAuthInputChoice struct {
ID string
Label string
DisplayText string
Type string
MfaType string
MaskedDestination string
}
// formatManagedAuthField renders one canonical input field as
// `id (Label) [type, ref=…, required, hint="…"]`. The hint carries the API's
// context for the field, such as the masked destination a one-time code was
// sent to, so it is often what tells the user which value to supply.
func formatManagedAuthField(f managedAuthInputField) string {
meta := make([]string, 0, 5)
if f.Type != "" {
meta = append(meta, f.Type)
}
if f.Ref != "" {
meta = append(meta, "ref="+f.Ref)
}
if f.Required {
meta = append(meta, "required")
}
if f.Reason != "" {
meta = append(meta, "reason="+f.Reason)
}
if f.Hint != "" {
meta = append(meta, fmt.Sprintf("hint=%q", f.Hint))
}
entry := f.ID
if f.Label != "" {
entry = fmt.Sprintf("%s (%s)", f.ID, f.Label)
}
if len(meta) > 0 {
entry = fmt.Sprintf("%s [%s]", entry, strings.Join(meta, ", "))
}
return entry
}
// formatManagedAuthChoice renders one canonical choice as
// `id (Label) [type, sms, to=+1 ••• 1234]`. The MFA type and masked destination
// are what distinguish otherwise identical-looking options, so both are shown
// when the API captured them.
func formatManagedAuthChoice(c managedAuthInputChoice) string {
meta := make([]string, 0, 3)
if c.Type != "" {
meta = append(meta, c.Type)
}
if c.MfaType != "" {
meta = append(meta, c.MfaType)
}
if c.MaskedDestination != "" {
meta = append(meta, "to="+c.MaskedDestination)
}
// display_text is the text as it appeared on the page; it stands in when the
// API did not derive a separate label.
label := c.Label
if label == "" {
label = c.DisplayText
}
entry := c.ID
if label != "" {
entry = fmt.Sprintf("%s (%s)", c.ID, label)
}
if len(meta) > 0 {
entry = fmt.Sprintf("%s [%s]", entry, strings.Join(meta, ", "))
}
return entry
}
func (c AuthConnectionCmd) Get(ctx context.Context, in AuthConnectionGetInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
auth, err := c.svc.Get(ctx, in.ID)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if in.Output == "json" {
return util.PrintPrettyJSON(auth)
}
tableData := pterm.TableData{
{"Property", "Value"},
{"ID", auth.ID},
{"Domain", auth.Domain},
{"Profile Name", auth.ProfileName},
{"Status", string(auth.Status)},
{"Can Reauth", fmt.Sprintf("%t", auth.CanReauth)},
}
if auth.CanReauthReason != "" {
tableData = append(tableData, []string{"Can Reauth Reason", string(auth.CanReauthReason)})
}
if auth.Credential.Name != "" {
tableData = append(tableData, []string{"Credential Name", auth.Credential.Name})
}
if auth.Credential.Provider != "" {
tableData = append(tableData, []string{"Credential Provider", auth.Credential.Provider})
}
if auth.FlowStatus != "" {
tableData = append(tableData, []string{"Flow Status", string(auth.FlowStatus)})
}
if auth.FlowStep != "" {
tableData = append(tableData, []string{"Flow Step", string(auth.FlowStep)})
}
// Canonical fields/choices supersede discovered_fields, mfa_options and
// pending_sso_buttons. Show them first so the IDs needed by `submit
// --field-value` and `submit --choice-id` are the first thing visible.
// The interaction ID scopes those submissions and only accompanies canonical
// input, so show it alongside them.
if auth.InteractionID != "" {
tableData = append(tableData, []string{"Interaction ID", auth.InteractionID})
}
if len(auth.Fields) > 0 {
fields := make([]string, 0, len(auth.Fields))
for _, f := range auth.Fields {
fields = append(fields, formatManagedAuthField(managedAuthInputField{
ID: f.ID,
Label: f.Label,
Type: f.Type,
Ref: f.Ref,
Hint: f.Hint,
Reason: f.Reason,
Required: f.Required,
}))
}
tableData = append(tableData, []string{"Fields", strings.Join(fields, "; ")})
}
if len(auth.Choices) > 0 {
choices := make([]string, 0, len(auth.Choices))
for _, ch := range auth.Choices {
choices = append(choices, formatManagedAuthChoice(managedAuthInputChoice{
ID: ch.ID,
Label: ch.Label,
DisplayText: ch.DisplayText,
Type: ch.Type,
MfaType: ch.MfaType,
MaskedDestination: ch.MaskedDestination,
}))
}
tableData = append(tableData, []string{"Choices", strings.Join(choices, "; ")})
}
if len(auth.DiscoveredFields) > 0 {
discoveredFields := make([]string, 0, len(auth.DiscoveredFields))
for _, field := range auth.DiscoveredFields {
fieldName := field.Name
if fieldName == "" {
fieldName = field.Label
} else if field.Label != "" && field.Label != field.Name {
fieldName = fmt.Sprintf("%s (%s)", field.Name, field.Label)
}
fieldMeta := make([]string, 0, 2)
if field.Type != "" {
fieldMeta = append(fieldMeta, field.Type)
}
if field.Required {
fieldMeta = append(fieldMeta, "required")
}
if len(fieldMeta) > 0 {
fieldName = fmt.Sprintf("%s [%s]", fieldName, strings.Join(fieldMeta, ", "))
}
discoveredFields = append(discoveredFields, fieldName)
}
tableData = append(tableData, []string{"Discovered Fields", strings.Join(discoveredFields, "; ")})
}
if len(auth.MfaOptions) > 0 {
mfaOptions := make([]string, 0, len(auth.MfaOptions))
for _, option := range auth.MfaOptions {
optionName := option.Label
if optionName == "" {
optionName = option.Type
} else if option.Type != "" {
optionName = fmt.Sprintf("%s (%s)", option.Label, option.Type)
}
mfaOptions = append(mfaOptions, optionName)
}
tableData = append(tableData, []string{"MFA Options", strings.Join(mfaOptions, "; ")})
}
if len(auth.PendingSSOButtons) > 0 {
pendingSSOButtons := make([]string, 0, len(auth.PendingSSOButtons))
for _, button := range auth.PendingSSOButtons {
buttonLabel := button.Label
if buttonLabel == "" {
buttonLabel = button.Provider
} else if button.Provider != "" {
buttonLabel = fmt.Sprintf("%s (%s)", button.Label, button.Provider)
}
pendingSSOButtons = append(pendingSSOButtons, buttonLabel)
}
tableData = append(tableData, []string{"Pending SSO Buttons", strings.Join(pendingSSOButtons, "; ")})
}
if auth.ExternalActionMessage != "" {
tableData = append(tableData, []string{"External Action", auth.ExternalActionMessage})
}
if auth.HostedURL != "" {
tableData = append(tableData, []string{"Hosted URL", auth.HostedURL})
}
if auth.LiveViewURL != "" {
tableData = append(tableData, []string{"Live View URL", auth.LiveViewURL})
}
if auth.WebsiteError != "" {
tableData = append(tableData, []string{"Website Error", auth.WebsiteError})
}
if !auth.FlowExpiresAt.IsZero() {
tableData = append(tableData, []string{"Flow Expires At", util.FormatLocal(auth.FlowExpiresAt)})
}
if auth.ErrorCode != "" {
tableData = append(tableData, []string{"Error Code", auth.ErrorCode})
}
if auth.ErrorMessage != "" {
tableData = append(tableData, []string{"Error Message", auth.ErrorMessage})
}
if !auth.LastAuthAt.IsZero() {
tableData = append(tableData, []string{"Last Auth At", util.FormatLocal(auth.LastAuthAt)})
}
if len(auth.AllowedDomains) > 0 {
tableData = append(tableData, []string{"Allowed Domains", strings.Join(auth.AllowedDomains, ", ")})
}
if auth.HealthCheckInterval > 0 {
tableData = append(tableData, []string{"Health Check Interval", fmt.Sprintf("%d seconds", auth.HealthCheckInterval)})
}
if auth.BrowserSessionID != "" {
tableData = append(tableData, []string{"Browser Session ID", auth.BrowserSessionID})
}
tableData = append(tableData, managedAuthBrowserRows(auth.Browser)...)
PrintTableNoPad(tableData, true)
return nil
}
func (c AuthConnectionCmd) List(ctx context.Context, in AuthConnectionListInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
params := kernel.AuthConnectionListParams{}
if in.Domain != "" {
params.Domain = kernel.Opt(in.Domain)
}
if in.ProfileName != "" {
params.ProfileName = kernel.Opt(in.ProfileName)
}
if in.Query != "" {
params.Query = kernel.Opt(in.Query)
}
if in.Limit > 0 {
params.Limit = kernel.Opt(int64(in.Limit))
}
if in.Offset > 0 {
params.Offset = kernel.Opt(int64(in.Offset))
}
page, err := c.svc.List(ctx, params)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
var auths []kernel.ManagedAuth
if page != nil {
auths = page.Items
}
if in.Output == "json" {
if page == nil {
fmt.Println("[]")
return nil
}
if page.RawJSON() != "" {
return util.PrintPrettyJSON(page)
}
if len(auths) == 0 {
fmt.Println("[]")
return nil
}
return util.PrintPrettyJSONSlice(auths)
}
if len(auths) == 0 {
pterm.Info.Println("No managed auths found")
return nil
}
tableData := pterm.TableData{{"ID", "Domain", "Profile Name", "Status", "Can Reauth"}}
for _, auth := range auths {
tableData = append(tableData, []string{
auth.ID,
auth.Domain,
auth.ProfileName,
string(auth.Status),
fmt.Sprintf("%t", auth.CanReauth),
})
}
PrintTableNoPad(tableData, true)
return nil
}
func (c AuthConnectionCmd) Delete(ctx context.Context, in AuthConnectionDeleteInput) error {
if !in.SkipConfirm {
ok, err := c.prompter.Confirm(
fmt.Sprintf("delete managed auth '%s'", in.ID),
fmt.Sprintf("Are you sure you want to delete managed auth '%s'?", in.ID),
)
if err != nil {
return err
}
if !ok {
pterm.Info.Println("Deletion cancelled")
return nil
}
}
if err := c.svc.Delete(ctx, in.ID); err != nil {
if util.IsNotFound(err) {
pterm.Info.Printf("Managed auth '%s' not found\n", in.ID)
return nil
}
return util.CleanedUpSdkError{Err: err}
}
pterm.Success.Printf("Deleted managed auth: %s\n", in.ID)
return nil
}
func (c AuthConnectionCmd) Login(ctx context.Context, in AuthConnectionLoginInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
params := kernel.AuthConnectionLoginParams{}
sel := proxySelection{ID: in.ProxyID, Name: in.ProxyName, Mode: in.ProxyMode}
if sel.set() {
proxy, err := buildProxyConfigParam(sel)
if err != nil {
return err
}
params.Browser.Proxy = proxy
}
if in.Stealth.Set {
params.Browser.Stealth = kernel.Opt(in.Stealth.Value)
}
if in.RecordSession.Set {
params.RecordSession = kernel.Opt(in.RecordSession.Value)
}
if in.Telemetry != "" || in.TelemetryCdpExclude != "" || in.TelemetryExport != "" {
t, err := buildManagedAuthTelemetryParam(in.Telemetry, in.TelemetryCdpExclude, in.TelemetryExport, false)
if err != nil {
return err
}
params.Browser.Telemetry = t
}
if in.Output != "json" {
pterm.Info.Println("Starting login flow...")
}
resp, err := c.svc.Login(ctx, in.ID, params)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if in.Output == "json" {
return util.PrintPrettyJSON(resp)
}
pterm.Success.Printf("Login flow started: %s\n", resp.FlowType)
tableData := pterm.TableData{
{"Property", "Value"},
{"ID", resp.ID},
{"Flow Type", string(resp.FlowType)},
{"Hosted URL", resp.HostedURL},
{"Flow Expires At", util.FormatLocal(resp.FlowExpiresAt)},
}
if resp.LiveViewURL != "" {
tableData = append(tableData, []string{"Live View URL", resp.LiveViewURL})
}
PrintTableNoPad(tableData, true)
return nil
}
func (c AuthConnectionCmd) Submit(ctx context.Context, in AuthConnectionSubmitInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
// Validate that we have some input to submit
hasFields := len(in.FieldValues) > 0
hasCanonicalFields := len(in.CanonicalFieldValues) > 0
hasChoice := in.SelectedChoiceID != ""
hasMfaOption := in.MfaOptionID != ""
hasSignInOption := in.SignInOptionID != ""
hasSSOButton := in.SSOButtonSelector != ""
hasSSOProvider := in.SSOProvider != ""
submitModes := 0
for _, active := range []bool{hasFields, hasCanonicalFields, hasChoice, hasMfaOption, hasSignInOption, hasSSOButton, hasSSOProvider} {
if active {
submitModes++
}
}
const submitModeFlags = "--field-value, --choice-id, --field, --mfa-option-id, --sign-in-option-id, --sso-button-selector, or --sso-provider"
if submitModes == 0 {
return fmt.Errorf("must provide exactly one of: %s", submitModeFlags)
}
if submitModes > 1 {
return fmt.Errorf("provide exactly one of: %s", submitModeFlags)
}
// The API binds canonical submissions to the interaction the values were read
// from, and rejects an interaction ID sent with a legacy submit mode.
isCanonical := hasCanonicalFields || hasChoice
if in.InteractionID != "" && !isCanonical {
return fmt.Errorf("the --interaction-id flag is only valid with --field-value or --choice-id")
}
if isCanonical && in.InteractionID == "" {
// Resolve the current interaction rather than making the user copy it out
// of `get` or `follow` first. The ID changes on every actionable pause, so
// the freshly read one is the only one worth defaulting to; passing
// --interaction-id explicitly pins the submission to an older interaction
// and lets the API reject it as stale.
conn, err := c.svc.Get(ctx, in.ID)
if err != nil {
return util.CleanedUpSdkError{Err: fmt.Errorf("failed to fetch connection for interaction ID resolution: %w", err)}
}
if conn == nil || conn.InteractionID == "" {
return fmt.Errorf("connection %s has no canonical interaction awaiting input; run 'kernel auth connections get %s' to see what the flow is waiting on", in.ID, in.ID)
}
in.InteractionID = conn.InteractionID
}
// Resolve MFA option: the user may pass the label (e.g. "Get a text"), the
// type (e.g. "sms"), or the display string ("Get a text (sms)"). The API
// expects the type, so look up the connection's available options and map
// whatever the user provided to the correct type value.
if hasMfaOption {
conn, err := c.svc.Get(ctx, in.ID)
if err != nil {
return util.CleanedUpSdkError{Err: fmt.Errorf("failed to fetch connection for MFA option resolution: %w", err)}
}
if len(conn.MfaOptions) > 0 {
resolved := false
for _, opt := range conn.MfaOptions {
displayName := fmt.Sprintf("%s (%s)", opt.Label, opt.Type)
if strings.EqualFold(in.MfaOptionID, opt.Type) ||
strings.EqualFold(in.MfaOptionID, opt.Label) ||
strings.EqualFold(in.MfaOptionID, displayName) {
in.MfaOptionID = opt.Type
resolved = true
break
}
}
if !resolved {
available := make([]string, 0, len(conn.MfaOptions))
for _, opt := range conn.MfaOptions {
available = append(available, fmt.Sprintf("%s (%s)", opt.Label, opt.Type))
}
return fmt.Errorf("unknown MFA option %q; available: %s", in.MfaOptionID, strings.Join(available, ", "))
}
}
}
params := kernel.AuthConnectionSubmitParams{
SubmitFieldsRequest: kernel.SubmitFieldsRequestParam{},
}
// Only attach legacy `fields` when it carries values. An empty-but-non-nil map
// still marshals as `"fields": {}`, which the API reads as a second submit mode
// alongside whichever canonical or legacy selector the user actually chose.
if hasFields {
params.SubmitFieldsRequest.Fields = in.FieldValues
}
if hasCanonicalFields {
params.SubmitFieldsRequest.FieldValues = in.CanonicalFieldValues
}
if hasChoice {
params.SubmitFieldsRequest.SelectedChoiceID = kernel.Opt(in.SelectedChoiceID)
}
if in.InteractionID != "" {
params.SubmitFieldsRequest.InteractionID = kernel.Opt(in.InteractionID)
}
if hasMfaOption {
params.SubmitFieldsRequest.MfaOptionID = kernel.Opt(in.MfaOptionID)
}
if hasSignInOption {
params.SubmitFieldsRequest.SignInOptionID = kernel.Opt(in.SignInOptionID)
}
if hasSSOButton {
params.SubmitFieldsRequest.SSOButtonSelector = kernel.Opt(in.SSOButtonSelector)
}
if hasSSOProvider {
params.SubmitFieldsRequest.SSOProvider = kernel.Opt(in.SSOProvider)
}
if in.Output != "json" {
pterm.Info.Println("Submitting to managed auth...")
}
resp, err := c.svc.Submit(ctx, in.ID, params)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
if in.Output == "json" {
return util.PrintPrettyJSON(resp)
}
if resp.Accepted {
pterm.Success.Println("Submission accepted")
} else {
pterm.Warning.Println("Submission not accepted")
}
return nil
}
func (c AuthConnectionCmd) Timeline(ctx context.Context, in AuthConnectionTimelineInput) error {
if err := validateJSONOutput(in.Output); err != nil {
return err
}
page := in.Page
perPage := in.PerPage
if page <= 0 {
page = 1
}
if perPage <= 0 {
perPage = 20
}
params := kernel.AuthConnectionTimelineParams{}
if in.Type != "" {
switch in.Type {
case string(kernel.AuthConnectionTimelineParamsTypeLogin),
string(kernel.AuthConnectionTimelineParamsTypeReauth),
string(kernel.AuthConnectionTimelineParamsTypeHealthCheck):
params.Type = kernel.AuthConnectionTimelineParamsType(in.Type)
default:
return fmt.Errorf("invalid --type %q: must be one of login, reauth, health_check", in.Type)
}
}
// Request one extra event so we can report whether another page exists
// without spending a second round trip on the pagination headers.
params.Limit = kernel.Opt(int64(perPage + 1))
params.Offset = kernel.Opt(int64((page - 1) * perPage))
result, err := c.svc.Timeline(ctx, in.ID, params)
if err != nil {
return util.CleanedUpSdkError{Err: err}
}
var events []kernel.ManagedAuthTimelineEvent
if result != nil {
events = result.Items
}
hasMore := len(events) > perPage
if hasMore {
events = events[:perPage]