Repository navigation
Expand file tree
/
Copy pathauth_wif_test.go
More file actions
1312 lines (1247 loc) · 48.8 KB
/
Copy pathauth_wif_test.go
File metadata and controls
1312 lines (1247 loc) · 48.8 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 gosnowflake
import (
"context"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strings"
"testing"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
)
type mockWifAttestationCreator struct {
providerType wifProviderType
returnError error
}
func (m *mockWifAttestationCreator) createAttestation() (*wifAttestation, error) {
if m.returnError != nil {
return nil, m.returnError
}
return &wifAttestation{
ProviderType: string(m.providerType),
}, nil
}
func TestGetAttestation(t *testing.T) {
awsError := errors.New("aws attestation error")
gcpError := errors.New("gcp attestation error")
azureError := errors.New("azure attestation error")
oidcError := errors.New("oidc attestation error")
provider := &wifAttestationProvider{
context: context.Background(),
awsCreator: &mockWifAttestationCreator{providerType: awsWif},
gcpCreator: &mockWifAttestationCreator{providerType: gcpWif},
azureCreator: &mockWifAttestationCreator{providerType: azureWif},
oidcCreator: &mockWifAttestationCreator{providerType: oidcWif},
}
providerWithErrors := &wifAttestationProvider{
context: context.Background(),
awsCreator: &mockWifAttestationCreator{providerType: awsWif, returnError: awsError},
gcpCreator: &mockWifAttestationCreator{providerType: gcpWif, returnError: gcpError},
azureCreator: &mockWifAttestationCreator{providerType: azureWif, returnError: azureError},
oidcCreator: &mockWifAttestationCreator{providerType: oidcWif, returnError: oidcError},
}
tests := []struct {
name string
provider *wifAttestationProvider
identityProvider string
expectedResult *wifAttestation
expectedError error
}{
{
name: "AWS success",
provider: provider,
identityProvider: "AWS",
expectedResult: &wifAttestation{ProviderType: string(awsWif)},
expectedError: nil,
},
{
name: "AWS error",
provider: providerWithErrors,
identityProvider: "AWS",
expectedResult: nil,
expectedError: awsError,
},
{
name: "GCP success",
provider: provider,
identityProvider: "GCP",
expectedResult: &wifAttestation{ProviderType: string(gcpWif)},
expectedError: nil,
},
{
name: "GCP error",
provider: providerWithErrors,
identityProvider: "GCP",
expectedResult: nil,
expectedError: gcpError,
},
{
name: "AZURE success",
provider: provider,
identityProvider: "AZURE",
expectedResult: &wifAttestation{ProviderType: string(azureWif)},
expectedError: nil,
},
{
name: "AZURE error",
provider: providerWithErrors,
identityProvider: "AZURE",
expectedResult: nil,
expectedError: azureError,
},
{
name: "OIDC success",
provider: provider,
identityProvider: "OIDC",
expectedResult: &wifAttestation{ProviderType: string(oidcWif)},
expectedError: nil,
},
{
name: "OIDC error",
provider: providerWithErrors,
identityProvider: "OIDC",
expectedResult: nil,
expectedError: oidcError,
},
{
name: "Unknown provider",
provider: provider,
identityProvider: "UNKNOWN",
expectedResult: nil,
expectedError: errors.New("unknown WorkloadIdentityProvider specified: UNKNOWN. Valid values are: AWS, GCP, AZURE, OIDC"),
},
{
name: "Empty provider",
provider: provider,
identityProvider: "",
expectedResult: nil,
expectedError: errors.New("unknown WorkloadIdentityProvider specified: . Valid values are: AWS, GCP, AZURE, OIDC"),
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
attestation, err := test.provider.getAttestation(test.identityProvider)
if test.expectedError != nil {
assertNilE(t, attestation)
assertNotNilF(t, err)
assertEqualE(t, test.expectedError.Error(), err.Error())
} else if test.expectedResult != nil {
assertNilE(t, err)
assertNotNilF(t, attestation)
assertEqualE(t, test.expectedResult.ProviderType, attestation.ProviderType)
} else {
t.Fatal("test case must specify either expectedError or expectedResult")
}
})
}
}
func TestAwsIdentityAttestationCreator(t *testing.T) {
tests := []struct {
name string
config Config
attestationSvc awsAttestationMetadataProvider
expectedError error
expectedProvider string
expectedStsHost string
}{
{
name: "No attestation service",
attestationSvc: nil,
expectedError: fmt.Errorf("AWS attestation service could not be created"),
},
{
name: "No AWS credentials",
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: aws.Credentials{},
region: "us-west-2",
},
expectedError: fmt.Errorf("no AWS credentials were found"),
},
{
name: "No AWS region",
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: mockCreds,
region: "",
},
expectedError: fmt.Errorf("no AWS region was found"),
},
{
name: "Successful attestation",
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: mockCreds,
region: "us-west-2",
},
expectedProvider: "AWS",
expectedStsHost: "sts.us-west-2.amazonaws.com",
},
{
name: "Successful attestation for CN region",
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: mockCreds,
region: "cn-northwest-1",
},
expectedProvider: "AWS",
expectedStsHost: "sts.cn-northwest-1.amazonaws.com.cn",
},
{
// ISO partitions do not use an amazonaws.com suffix at all, so this pins
// the host that actually reaches the envelope, not just the resolver.
name: "Successful attestation for ISO region",
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: mockCreds,
region: "us-iso-east-1",
},
expectedProvider: "AWS",
expectedStsHost: "sts.us-iso-east-1.c2s.ic.gov",
},
{
name: "Successful attestation with single role chaining",
config: Config{
WorkloadIdentityImpersonationPath: []string{"arn:aws:iam::123456789012:role/test-role"},
},
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: mockCreds,
chainingCreds: aws.Credentials{
AccessKeyID: "chainedAccessKey",
SecretAccessKey: "chainedSecretKey",
SessionToken: "chainedSessionToken",
},
region: "us-east-1",
useRoleChaining: true,
},
expectedProvider: "AWS",
expectedStsHost: "sts.us-east-1.amazonaws.com",
},
{
name: "Successful attestation with multiple role chaining",
config: Config{
WorkloadIdentityImpersonationPath: []string{
"arn:aws:iam::123456789012:role/role1",
"arn:aws:iam::123456789012:role/role2",
"arn:aws:iam::123456789012:role/role3",
},
},
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: mockCreds,
chainingCreds: aws.Credentials{
AccessKeyID: "finalRoleAccessKey",
SecretAccessKey: "finalRoleSecretKey",
SessionToken: "finalRoleSessionToken",
},
region: "us-west-2",
useRoleChaining: true,
},
expectedProvider: "AWS",
expectedStsHost: "sts.us-west-2.amazonaws.com",
},
{
name: "Role chaining with no credentials",
config: Config{
WorkloadIdentityImpersonationPath: []string{"arn:aws:iam::123456789012:role/test-role"},
},
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: aws.Credentials{},
region: "us-west-2",
useRoleChaining: true,
},
expectedError: fmt.Errorf("no AWS credentials were found"),
},
{
name: "Role chaining with no region",
config: Config{
WorkloadIdentityImpersonationPath: []string{"arn:aws:iam::123456789012:role/test-role"},
},
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: aws.Credentials{
AccessKeyID: "chainedAccessKey",
SecretAccessKey: "chainedSecretKey",
SessionToken: "chainedSessionToken",
},
region: "",
useRoleChaining: true,
},
expectedError: fmt.Errorf("no AWS region was found"),
},
{
name: "Role chaining failure",
config: Config{
WorkloadIdentityImpersonationPath: []string{"arn:aws:iam::123456789012:role/test-role"},
},
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: mockCreds,
region: "us-west-2",
chainingError: fmt.Errorf("failed to assume role: AccessDenied"),
useRoleChaining: true,
},
expectedError: fmt.Errorf("failed to assume role: AccessDenied"),
},
{
name: "Cross-account role chaining",
config: Config{
WorkloadIdentityImpersonationPath: []string{
"arn:aws:iam::111111111111:role/cross-account-role",
"arn:aws:iam::222222222222:role/target-role",
},
},
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: mockCreds,
chainingCreds: aws.Credentials{
AccessKeyID: "crossAccountAccessKey",
SecretAccessKey: "crossAccountSecretKey",
SessionToken: "crossAccountSessionToken",
},
region: "us-east-1",
useRoleChaining: true,
},
expectedProvider: "AWS",
expectedStsHost: "sts.us-east-1.amazonaws.com",
},
{
name: "Role chaining in CN region",
config: Config{
WorkloadIdentityImpersonationPath: []string{"arn:aws-cn:iam::123456789012:role/cn-role"},
},
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: mockCreds,
chainingCreds: aws.Credentials{
AccessKeyID: "cnRoleAccessKey",
SecretAccessKey: "cnRoleSecretKey",
SessionToken: "cnRoleSessionToken",
},
region: "cn-north-1",
useRoleChaining: true,
},
expectedProvider: "AWS",
expectedStsHost: "sts.cn-north-1.amazonaws.com.cn",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
creator := &awsIdentityAttestationCreator{
attestationServiceFactory: func(ctx context.Context, cfg *Config) awsAttestationMetadataProvider {
return test.attestationSvc
},
ctx: context.Background(),
cfg: &test.config,
}
attestation, err := creator.createAttestation()
if test.expectedError != nil {
assertNilF(t, attestation)
assertNotNilE(t, err)
assertEqualE(t, test.expectedError.Error(), err.Error())
} else {
assertNilE(t, err)
assertNotNilE(t, attestation)
assertNotNilE(t, attestation.Credential)
assertEqualE(t, test.expectedProvider, attestation.ProviderType)
decoded, err := base64.StdEncoding.DecodeString(attestation.Credential)
if err != nil {
t.Fatalf("Failed to decode credential: %v", err)
}
var credentialMap map[string]any
if err := json.Unmarshal(decoded, &credentialMap); err != nil {
t.Fatalf("Failed to unmarshal credential JSON: %v", err)
}
assertEqualE(t, fmt.Sprintf("https://%s?Action=GetCallerIdentity&Version=2011-06-15", test.expectedStsHost), credentialMap["url"])
}
})
}
}
type mockAwsAttestationMetadataProvider struct {
creds aws.Credentials
region string
chainingCreds aws.Credentials
chainingError error
useRoleChaining bool
webIdentityToken string
webIdentityError error
}
var mockCreds = aws.Credentials{
AccessKeyID: "mockAccessKey",
SecretAccessKey: "mockSecretKey",
SessionToken: "mockSessionToken",
}
func (m *mockAwsAttestationMetadataProvider) awsCredentials() (aws.Credentials, error) {
return m.creds, nil
}
func (m *mockAwsAttestationMetadataProvider) awsCredentialsViaRoleChaining() (aws.Credentials, error) {
if m.chainingError != nil {
return aws.Credentials{}, m.chainingError
}
if m.chainingCreds.AccessKeyID != "" {
return m.chainingCreds, nil
}
return m.creds, nil
}
func (m *mockAwsAttestationMetadataProvider) awsRegion() string {
return m.region
}
func (m *mockAwsAttestationMetadataProvider) awsWebIdentityToken(_ aws.Credentials, _ string) (string, error) {
if m.webIdentityError != nil {
return "", m.webIdentityError
}
return m.webIdentityToken, nil
}
func TestAwsIdentityAttestationCreatorOutboundToken(t *testing.T) {
const jwt = "header.payload.signature"
tests := []struct {
name string
config Config
attestationSvc awsAttestationMetadataProvider
expectedError error
expectedCredential string
}{
{
name: "Successful outbound attestation",
config: Config{
WorkloadIdentityAwsUseOutboundToken: ConfigBoolTrue,
},
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: mockCreds,
region: "us-west-2",
webIdentityToken: jwt,
},
expectedCredential: jwt,
},
{
name: "Successful outbound attestation with role chaining",
config: Config{
WorkloadIdentityAwsUseOutboundToken: ConfigBoolTrue,
WorkloadIdentityImpersonationPath: []string{"arn:aws:iam::123456789012:role/test-role"},
},
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: mockCreds,
chainingCreds: aws.Credentials{
AccessKeyID: "chainedAccessKey",
SecretAccessKey: "chainedSecretKey",
SessionToken: "chainedSessionToken",
},
region: "us-east-1",
useRoleChaining: true,
webIdentityToken: jwt,
},
expectedCredential: jwt,
},
{
name: "STS returns no token",
config: Config{
WorkloadIdentityAwsUseOutboundToken: ConfigBoolTrue,
},
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: mockCreds,
region: "us-west-2",
webIdentityToken: "",
},
expectedError: fmt.Errorf("failed to obtain AWS web identity token from STS"),
},
{
name: "STS call fails",
config: Config{
WorkloadIdentityAwsUseOutboundToken: ConfigBoolTrue,
},
attestationSvc: &mockAwsAttestationMetadataProvider{
creds: mockCreds,
region: "us-west-2",
webIdentityError: fmt.Errorf("AccessDenied"),
},
expectedError: fmt.Errorf("AccessDenied"),
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
creator := &awsIdentityAttestationCreator{
attestationServiceFactory: func(ctx context.Context, cfg *Config) awsAttestationMetadataProvider {
return test.attestationSvc
},
ctx: context.Background(),
cfg: &test.config,
}
attestation, err := creator.createAttestation()
if test.expectedError != nil {
assertNilF(t, attestation)
assertNotNilE(t, err)
assertEqualE(t, test.expectedError.Error(), err.Error())
} else {
assertNilE(t, err)
assertNotNilE(t, attestation)
assertEqualE(t, "AWS", attestation.ProviderType)
// The outbound token is sent verbatim, not base64-encoded.
assertEqualE(t, test.expectedCredential, attestation.Credential)
}
})
}
}
func TestGcpIdentityAttestationCreator(t *testing.T) {
tests := []struct {
name string
wiremockMappingPath string
config Config
expectedError error
expectedSub string
}{
{
name: "Successful flow",
wiremockMappingPath: "auth/wif/gcp/successful_flow.json",
expectedError: nil,
expectedSub: "some-subject",
},
{
name: "Successful impersonation flow",
wiremockMappingPath: "auth/wif/gcp/successful_impersionation_flow.json",
config: Config{
WorkloadIdentityImpersonationPath: []string{
"delegate1",
"delegate2",
"targetServiceAccount",
},
},
expectedError: nil,
expectedSub: "some-impersonated-subject",
},
{
name: "No GCP credential - http error",
wiremockMappingPath: "auth/wif/gcp/http_error.json",
expectedError: fmt.Errorf("no GCP token was found"),
expectedSub: "",
},
{
name: "missing issuer claim",
wiremockMappingPath: "auth/wif/gcp/missing_issuer_claim.json",
expectedError: fmt.Errorf("could not extract claims from token: missing issuer claim in JWT token"),
expectedSub: "",
},
{
name: "missing sub claim",
wiremockMappingPath: "auth/wif/gcp/missing_sub_claim.json",
expectedError: fmt.Errorf("could not extract claims from token: missing sub claim in JWT token"),
expectedSub: "",
},
{
name: "unparsable token",
wiremockMappingPath: "auth/wif/gcp/unparsable_token.json",
expectedError: fmt.Errorf("could not extract claims from token: unable to extract JWT claims from token: token is malformed: token contains an invalid number of segments"),
expectedSub: "",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
creator := &gcpIdentityAttestationCreator{
cfg: &test.config,
metadataServiceBaseURL: wiremock.baseURL(),
iamCredentialsURL: wiremock.baseURL(),
}
wiremock.registerMappings(t, wiremockMapping{filePath: test.wiremockMappingPath})
attestation, err := creator.createAttestation()
if test.expectedError != nil {
assertNilF(t, attestation)
assertNotNilF(t, err)
assertEqualE(t, test.expectedError.Error(), err.Error())
} else {
assertNilF(t, err)
assertNotNilF(t, attestation)
assertEqualE(t, string(gcpWif), attestation.ProviderType)
assertEqualE(t, test.expectedSub, attestation.Metadata["sub"])
}
})
}
}
func TestOidcIdentityAttestationCreator(t *testing.T) {
const (
/*
* {
* "sub": "some-subject",
* "iat": 1743761213,
* "exp": 1743764813,
* "aud": "www.example.com"
* }
*/
missingIssuerClaimToken = "eyJ0eXAiOiJhdCtqd3QiLCJhbGciOiJFUzI1NiIsImtpZCI6ImU2M2I5NzA1OTRiY2NmZTAxMDlkOTg4OWM2MDk3OWEwIn0.eyJzdWIiOiJzb21lLXN1YmplY3QiLCJpYXQiOjE3NDM3NjEyMTMsImV4cCI6MTc0Mzc2NDgxMywiYXVkIjoid3d3LmV4YW1wbGUuY29tIn0.H6sN6kjA82EuijFcv-yCJTqau5qvVTCsk0ZQ4gvFQMkB7c71XPs4lkwTa7ZlNNlx9e6TpN1CVGnpCIRDDAZaDw" // pragma: allowlist secret
/*
* {
* "iss": "https://accounts.google.com",
* "iat": 1743761213,
* "exp": 1743764813,
* "aud": "www.example.com"
* }
*/
missingSubClaimToken = "eyJ0eXAiOiJhdCtqd3QiLCJhbGciOiJFUzI1NiIsImtpZCI6ImU2M2I5NzA1OTRiY2NmZTAxMDlkOTg4OWM2MDk3OWEwIn0.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJpYXQiOjE3NDM3NjEyMTMsImV4cCI6MTc0Mzc2NDgxMywiYXVkIjoid3d3LmV4YW1wbGUuY29tIn0.w0njdpfWFETVK8Ktq9GdvuKRQJjvhOplcSyvQ_zHHwBUSMapqO1bjEWBx5VhGkdECZIGS1VY7db_IOqT45yOMA" // pragma: allowlist secret
/*
* {
* "iss": "https://oidc.eks.us-east-2.amazonaws.com/id/3B869BC5D12CEB5515358621D8085D58",
* "iat": 1743692017,
* "exp": 1775228014,
* "aud": "www.example.com",
* "sub": "system:serviceaccount:poc-namespace:oidc-sa"
* }
*/
validToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL29pZGMuZWtzLnVzLWVhc3QtMi5hbWF6b25hd3MuY29tL2lkLzNCODY5QkM1RDEyQ0VCNTUxNTM1ODYyMUQ4MDg1RDU4IiwiaWF0IjoxNzQ0Mjg3ODc4LCJleHAiOjE3NzU4MjM4NzgsImF1ZCI6Ind3dy5leGFtcGxlLmNvbSIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpwb2MtbmFtZXNwYWNlOm9pZGMtc2EifQ.a8H6KRIF1XmM8lkqL6kR8ccInr7wAzQrbKd3ZHFgiEg" // pragma: allowlist secret
unparsableToken = "unparsable_token"
emptyToken = ""
)
type testCase struct {
name string
token string
expectedError error
expectedSub string
}
tests := []testCase{
{
name: "no token input",
token: emptyToken,
expectedError: fmt.Errorf("no OIDC token was specified"),
},
{
name: "valid token returns proper attestation",
token: validToken,
expectedError: nil,
expectedSub: "system:serviceaccount:poc-namespace:oidc-sa",
},
{
name: "missing issuer returns error",
token: missingIssuerClaimToken,
expectedError: errors.New("missing issuer claim in JWT token"),
},
{
name: "missing sub returns error",
token: missingSubClaimToken,
expectedError: errors.New("missing sub claim in JWT token"),
},
{
name: "unparsable token returns error",
token: unparsableToken,
expectedError: errors.New("unable to extract JWT claims from token: token is malformed: token contains an invalid number of segments"),
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
creator := &oidcIdentityAttestationCreator{token: func() (string, error) {
return test.token, nil
}}
attestation, err := creator.createAttestation()
if test.expectedError != nil {
assertNotNilE(t, err)
assertNilF(t, attestation)
assertEqualE(t, test.expectedError.Error(), err.Error())
} else {
assertNilE(t, err)
assertNotNilE(t, attestation)
assertEqualE(t, string(oidcWif), attestation.ProviderType)
assertEqualE(t, test.expectedSub, attestation.Metadata["sub"])
}
})
}
}
func TestAzureIdentityAttestationCreator(t *testing.T) {
tests := []struct {
name string
wiremockMappingPath string
metadataProvider *mockAzureAttestationMetadataProvider
cfg *Config
expectedIss string
expectedError error
}{
/*
* {
* "iss": "https://sts.windows.net/fa15d692-e9c7-4460-a743-29f29522229/",
* "sub": "77213E30-E8CB-4595-B1B6-5F050E8308FD"
* }
*/
{
name: "Successful flow",
wiremockMappingPath: "auth/wif/azure/successful_flow_basic.json",
metadataProvider: azureVMMetadataProvider(),
expectedIss: "https://sts.windows.net/fa15d692-e9c7-4460-a743-29f29522229/",
expectedError: nil,
},
/*
* {
* "iss": "https://login.microsoftonline.com/fa15d692-e9c7-4460-a743-29f29522229/",
* "sub": "77213E30-E8CB-4595-B1B6-5F050E8308FD"
* }
*/
{
name: "Successful flow v2 issuer",
wiremockMappingPath: "auth/wif/azure/successful_flow_v2_issuer.json",
metadataProvider: azureVMMetadataProvider(),
expectedIss: "https://login.microsoftonline.com/fa15d692-e9c7-4460-a743-29f29522229/",
expectedError: nil,
},
/*
* {
* "iss": "https://sts.windows.net/fa15d692-e9c7-4460-a743-29f29522229/",
* "sub": "77213E30-E8CB-4595-B1B6-5F050E8308FD"
* }
*/
{
name: "Successful flow azure functions",
wiremockMappingPath: "auth/wif/azure/successful_flow_azure_functions.json",
metadataProvider: azureFunctionsMetadataProvider(),
expectedIss: "https://sts.windows.net/fa15d692-e9c7-4460-a743-29f29522229/",
expectedError: nil,
},
/*
* {
* "iss": "https://login.microsoftonline.com/fa15d692-e9c7-4460-a743-29f29522229/",
* "sub": "77213E30-E8CB-4595-B1B6-5F050E8308FD"
* }
*/
{
name: "Successful flow azure functions v2 issuer",
wiremockMappingPath: "auth/wif/azure/successful_flow_azure_functions_v2_issuer.json",
metadataProvider: azureFunctionsMetadataProvider(),
expectedIss: "https://login.microsoftonline.com/fa15d692-e9c7-4460-a743-29f29522229/",
expectedError: nil,
},
/*
* {
* "iss": "https://sts.windows.net/fa15d692-e9c7-4460-a743-29f29522229/",
* "sub": "77213E30-E8CB-4595-B1B6-5F050E8308FD"
* }
*/
{
name: "Successful flow azure functions no client ID",
wiremockMappingPath: "auth/wif/azure/successful_flow_azure_functions_no_client_id.json",
metadataProvider: &mockAzureAttestationMetadataProvider{
identityEndpointValue: wiremock.baseURL() + "/metadata/identity/endpoint/from/env",
identityHeaderValue: "some-identity-header-from-env",
clientIDValue: "",
},
expectedIss: "https://sts.windows.net/fa15d692-e9c7-4460-a743-29f29522229/",
expectedError: nil,
},
/*
* {
* "iss": "https://sts.windows.net/fa15d692-e9c7-4460-a743-29f29522229/",
* "sub": "77213E30-E8CB-4595-B1B6-5F050E8308FD"
* }
*/
{
name: "Successful flow azure functions custom Entra resource",
wiremockMappingPath: "auth/wif/azure/successful_flow_azure_functions_custom_entra_resource.json",
metadataProvider: azureFunctionsMetadataProvider(),
cfg: &Config{WorkloadIdentityEntraResource: "api://1111111-2222-3333-44444-55555555"},
expectedIss: "https://sts.windows.net/fa15d692-e9c7-4460-a743-29f29522229/",
expectedError: nil,
},
{
name: "Non-json response",
wiremockMappingPath: "auth/wif/azure/non_json_response.json",
metadataProvider: azureVMMetadataProvider(),
expectedError: fmt.Errorf("failed to extract token from JSON: invalid character 'o' in literal null (expecting 'u')"),
},
{
name: "Identity endpoint but no identity header",
metadataProvider: &mockAzureAttestationMetadataProvider{
identityEndpointValue: wiremock.baseURL() + "/metadata/identity/endpoint/from/env",
identityHeaderValue: "",
clientIDValue: "managed-client-id-from-env",
},
expectedError: fmt.Errorf("managed identity is not enabled on this Azure function"),
},
{
name: "Unparsable token",
wiremockMappingPath: "auth/wif/azure/unparsable_token.json",
metadataProvider: azureVMMetadataProvider(),
expectedError: fmt.Errorf("failed to extract sub and iss claims from token: unable to extract JWT claims from token: token is malformed: token contains an invalid number of segments"),
},
{
name: "HTTP error",
metadataProvider: azureVMMetadataProvider(),
wiremockMappingPath: "auth/wif/azure/http_error.json",
expectedError: fmt.Errorf("could not fetch Azure token"),
},
{
name: "Missing sub or iss claim",
wiremockMappingPath: "auth/wif/azure/missing_issuer_claim.json",
metadataProvider: azureVMMetadataProvider(),
expectedError: fmt.Errorf("failed to extract sub and iss claims from token: missing issuer claim in JWT token"),
},
{
name: "Missing sub claim",
wiremockMappingPath: "auth/wif/azure/missing_sub_claim.json",
metadataProvider: azureVMMetadataProvider(),
expectedError: fmt.Errorf("failed to extract sub and iss claims from token: missing sub claim in JWT token"),
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if test.wiremockMappingPath != "" {
wiremock.registerMappings(t, wiremockMapping{filePath: test.wiremockMappingPath})
}
creator := &azureIdentityAttestationCreator{
cfg: test.cfg,
azureMetadataServiceBaseURL: wiremock.baseURL(),
azureAttestationMetadataProvider: test.metadataProvider,
workloadIdentityEntraResource: determineEntraResource(test.cfg),
}
attestation, err := creator.createAttestation()
if test.expectedError != nil {
assertNilF(t, attestation)
assertNotNilE(t, err)
assertEqualE(t, test.expectedError.Error(), err.Error())
} else {
assertNilF(t, err)
assertNotNilF(t, attestation)
assertEqualE(t, string(azureWif), attestation.ProviderType)
assertEqualE(t, test.expectedIss, attestation.Metadata["iss"])
assertEqualE(t, "77213E30-E8CB-4595-B1B6-5F050E8308FD", attestation.Metadata["sub"])
}
})
}
}
type mockAzureAttestationMetadataProvider struct {
identityEndpointValue string
identityHeaderValue string
clientIDValue string
}
func (m *mockAzureAttestationMetadataProvider) identityEndpoint() string {
return m.identityEndpointValue
}
func (m *mockAzureAttestationMetadataProvider) identityHeader() string {
return m.identityHeaderValue
}
func (m *mockAzureAttestationMetadataProvider) clientID() string {
return m.clientIDValue
}
func azureFunctionsMetadataProvider() *mockAzureAttestationMetadataProvider {
return &mockAzureAttestationMetadataProvider{
identityEndpointValue: wiremock.baseURL() + "/metadata/identity/endpoint/from/env",
identityHeaderValue: "some-identity-header-from-env",
clientIDValue: "managed-client-id-from-env",
}
}
func azureVMMetadataProvider() *mockAzureAttestationMetadataProvider {
return &mockAzureAttestationMetadataProvider{
identityEndpointValue: "",
identityHeaderValue: "",
clientIDValue: "",
}
}
// Running this test locally:
// * Push branch to repository
// * Set PARAMETERS_SECRET
// * Run ci/test_wif.sh
func TestWorkloadIdentityAuthOnCloudVM(t *testing.T) {
account := os.Getenv("SNOWFLAKE_TEST_WIF_ACCOUNT")
host := os.Getenv("SNOWFLAKE_TEST_WIF_HOST")
provider := os.Getenv("SNOWFLAKE_TEST_WIF_PROVIDER")
println("provider = " + provider)
if account == "" || host == "" || provider == "" {
t.Skip("Test can run only on cloud VM with env variables set")
}
testCases := []struct {
name string
skip func() (bool, string)
setupCfg func(*testing.T, *Config)
expectedUsername string
}{
{
name: "provider=" + provider,
setupCfg: func(_ *testing.T, config *Config) {
if provider != "GCP+OIDC" {
config.WorkloadIdentityProvider = provider
} else {
config.WorkloadIdentityProvider = "OIDC"
config.Token = func() string {
metadataURL := defaultGcpMetadataServiceBase + "/computeMetadata/v1/instance/service-accounts/default/identity?audience=snowflakecomputing.com"
cmd := exec.Command("wget", "-O", "-", "--header=Metadata-Flavor: Google", metadataURL)
output, err := cmd.Output()
if err != nil {
t.Fatalf("error executing GCP metadata request: %v", err)
}
token := strings.TrimSpace(string(output))
if token == "" {
t.Fatal("failed to retrieve GCP access token: empty response")
}
return token
}()
}
},
expectedUsername: os.Getenv("SNOWFLAKE_TEST_WIF_USERNAME"),
},
{
name: "provider=" + provider + ",impersonation",
skip: func() (bool, string) {
if provider != "AWS" && provider != "GCP" {
return true, "Impersonation is supported only on AWS and GCP"
}
return false, ""
},
setupCfg: func(t *testing.T, config *Config) {
config.WorkloadIdentityProvider = provider
impersonationPath := os.Getenv("SNOWFLAKE_TEST_WIF_IMPERSONATION_PATH")
assertNotEqualF(t, impersonationPath, "", "SNOWFLAKE_TEST_WIF_IMPERSONATION_PATH is not set")
config.WorkloadIdentityImpersonationPath = strings.Split(impersonationPath, ",")
assertNotEqualF(t, os.Getenv("SNOWFLAKE_TEST_WIF_USERNAME_IMPERSONATION"), "", "SNOWFLAKE_TEST_WIF_USERNAME_IMPERSONATION is not set")
},
expectedUsername: os.Getenv("SNOWFLAKE_TEST_WIF_USERNAME_IMPERSONATION"),
},
{
// AWS WIF supports two attestation methods: GetCallerIdentity (default) and
// GetWebIdentityToken (enabled via WorkloadIdentityAwsUseOutboundToken). This case
// covers the GetWebIdentityToken method against the dedicated TEST_WIF_E2E_AWS_WITH_ISSUER
// Snowflake user (configured with an ISSUER). Since an EC2 instance can only have one IAM
// role, the test impersonates a dedicated role that maps to that user.
name: "provider=" + provider + ",outboundToken",
skip: func() (bool, string) {
if provider != "AWS" {
return true, "GetWebIdentityToken outbound token is supported only on AWS"
}
return false, ""
},
setupCfg: func(_ *testing.T, config *Config) {
config.WorkloadIdentityProvider = provider
config.WorkloadIdentityAwsUseOutboundToken = ConfigBoolTrue
config.WorkloadIdentityImpersonationPath = []string{"arn:aws:iam::376129840140:role/drivers-wif-automated-tests-with-issuer"}
},
expectedUsername: "TEST_WIF_E2E_AWS_WITH_ISSUER",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if tc.skip != nil {
if skip, msg := tc.skip(); skip {
t.Skip(msg)
}
}
config := &Config{
Account: account,
Host: host,
Authenticator: AuthTypeWorkloadIdentityFederation,
}
tc.setupCfg(t, config)
connector := NewConnector(SnowflakeDriver{}, *config)
db := sql.OpenDB(connector)
defer db.Close()
currentUser := runSelectCurrentUser(t, db)
assertEqualE(t, currentUser, tc.expectedUsername)
})
}
}
func TestAwsStsEndpointFor(t *testing.T) {
testcases := []struct {
name string
wifHost string
region string
expectedAuthority string
expectedBaseURL string
expectedOverride bool
expectedError string
}{
// Regional defaults come from the SDK's endpoint rules. The commercial and
// China cases pin that delegating there did not move the endpoint anyone
// already depends on; the rest are partitions whose DNS suffix is not
// amazonaws.com and which a hand-formatted hostname gets wrong.
{name: "regional default us-east-1", wifHost: "", region: "us-east-1", expectedAuthority: "sts.us-east-1.amazonaws.com", expectedBaseURL: "https://sts.us-east-1.amazonaws.com", expectedOverride: false},
{name: "regional default cn-north-1", wifHost: "", region: "cn-north-1", expectedAuthority: "sts.cn-north-1.amazonaws.com.cn", expectedBaseURL: "https://sts.cn-north-1.amazonaws.com.cn", expectedOverride: false},
{name: "regional default us-gov-west-1", wifHost: "", region: "us-gov-west-1", expectedAuthority: "sts.us-gov-west-1.amazonaws.com", expectedBaseURL: "https://sts.us-gov-west-1.amazonaws.com", expectedOverride: false},
{name: "regional default us-iso-east-1", wifHost: "", region: "us-iso-east-1", expectedAuthority: "sts.us-iso-east-1.c2s.ic.gov", expectedBaseURL: "https://sts.us-iso-east-1.c2s.ic.gov", expectedOverride: false},
{name: "regional default us-isob-east-1", wifHost: "", region: "us-isob-east-1", expectedAuthority: "sts.us-isob-east-1.sc2s.sgov.gov", expectedBaseURL: "https://sts.us-isob-east-1.sc2s.sgov.gov", expectedOverride: false},
{name: "regional default eu-isoe-west-1", wifHost: "", region: "eu-isoe-west-1", expectedAuthority: "sts.eu-isoe-west-1.cloud.adc-e.uk", expectedBaseURL: "https://sts.eu-isoe-west-1.cloud.adc-e.uk", expectedOverride: false},
{name: "regional default us-isof-south-1", wifHost: "", region: "us-isof-south-1", expectedAuthority: "sts.us-isof-south-1.csp.hci.ic.gov", expectedBaseURL: "https://sts.us-isof-south-1.csp.hci.ic.gov", expectedOverride: false},
{name: "regional default eusc-de-east-1", wifHost: "", region: "eusc-de-east-1", expectedAuthority: "sts.eusc-de-east-1.amazonaws.eu", expectedBaseURL: "https://sts.eusc-de-east-1.amazonaws.eu", expectedOverride: false},
{name: "bare host", wifHost: "sts.custom.example.com", region: "us-custom-1", expectedAuthority: "sts.custom.example.com", expectedBaseURL: "https://sts.custom.example.com", expectedOverride: true},
{name: "host with port", wifHost: "sts.custom.example.com:8443", region: "us-custom-1", expectedAuthority: "sts.custom.example.com:8443", expectedBaseURL: "https://sts.custom.example.com:8443", expectedOverride: true},
{name: "full URL", wifHost: "https://sts.custom.example.com", region: "us-custom-1", expectedAuthority: "sts.custom.example.com", expectedBaseURL: "https://sts.custom.example.com", expectedOverride: true},
{name: "trailing slashes", wifHost: "https://sts.custom.example.com///", region: "us-custom-1", expectedAuthority: "sts.custom.example.com", expectedBaseURL: "https://sts.custom.example.com", expectedOverride: true},
{name: "http scheme", wifHost: "http://sts.custom.example.com", region: "us-custom-1", expectedAuthority: "sts.custom.example.com", expectedBaseURL: "http://sts.custom.example.com", expectedOverride: true},
{name: "whitespace", wifHost: " sts.custom.example.com ", region: "us-custom-1", expectedAuthority: "sts.custom.example.com", expectedBaseURL: "https://sts.custom.example.com", expectedOverride: true},
{name: "invalid scheme", wifHost: "ftp://sts.custom.example.com", region: "us-custom-1", expectedError: `workloadIdentityHost "ftp://sts.custom.example.com" must use https or http, got scheme "ftp"`},
{name: "with query", wifHost: "https://sts.custom.example.com?Action=Foo", region: "us-custom-1", expectedError: `workloadIdentityHost "https://sts.custom.example.com?Action=Foo" must not contain user info, a query or a fragment`},
{name: "no hostname", wifHost: "https:///sts", region: "us-custom-2", expectedError: `workloadIdentityHost "https:///sts" does not contain a hostname`},
{name: "fragment", wifHost: "https://sts.custom.example.com#frag", region: "us-custom-2", expectedError: `workloadIdentityHost "https://sts.custom.example.com#frag" must not contain user info, a query or a fragment`},
{name: "user info", wifHost: "https://user:pass@sts.custom.example.com", region: "us-custom-2", expectedError: `workloadIdentityHost "https://user:pass@sts.custom.example.com" must not contain user info, a query or a fragment`}, // pragma: allowlist secret
}
for _, tc := range testcases {