-
-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathsetup.go
More file actions
919 lines (806 loc) · 31.3 KB
/
Copy pathsetup.go
File metadata and controls
919 lines (806 loc) · 31.3 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
package azure
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
errUtils "github.com/cloudposse/atmos/errors"
"github.com/cloudposse/atmos/pkg/auth/types"
log "github.com/cloudposse/atmos/pkg/logger"
"github.com/cloudposse/atmos/pkg/schema"
)
// SetupFiles sets up Azure credentials files for the given identity.
// BasePath specifies the base directory for Azure files (from provider's files.base_path).
// If empty, uses the default ~/.azure/atmos/{realm} path.
// The realm parameter provides credential isolation between different repositories.
func SetupFiles(providerName, identityName string, creds types.ICredentials, basePath string, realm string) error {
azureCreds, ok := creds.(*types.AzureCredentials)
if !ok {
return nil // No Azure credentials to setup.
}
// Create Azure file manager with configured or default path.
fileManager, err := NewAzureFileManager(basePath, realm)
if err != nil {
return errors.Join(errUtils.ErrAuthenticationFailed, err)
}
// Write credentials file.
if err := fileManager.WriteCredentials(providerName, identityName, azureCreds); err != nil {
return fmt.Errorf("failed to write Azure credentials: %w", err)
}
return nil
}
// SetAuthContextParams contains parameters for SetAuthContext.
type SetAuthContextParams struct {
AuthContext *schema.AuthContext
StackInfo *schema.ConfigAndStacksInfo
ProviderName string
IdentityName string
Credentials types.ICredentials
BasePath string
Realm string
}
// SetAuthContext populates the Azure auth context with Atmos-managed credential paths.
// This enables in-process Azure SDK calls to use Atmos-managed credentials.
func SetAuthContext(params *SetAuthContextParams) error {
if params == nil {
return fmt.Errorf("%w: SetAuthContext parameters cannot be nil", errUtils.ErrInvalidAuthConfig)
}
authContext := params.AuthContext
if authContext == nil {
return nil // No auth context to populate.
}
azureCreds, ok := params.Credentials.(*types.AzureCredentials)
if !ok || azureCreds == nil {
return nil // No Azure credentials to setup.
}
// Validate credentials are not expired.
if azureCreds.IsExpired() {
return fmt.Errorf("%w: Azure credentials are expired", errUtils.ErrAuthenticationFailed)
}
m, err := NewAzureFileManager(params.BasePath, params.Realm)
if err != nil {
return errors.Join(errUtils.ErrAuthenticationFailed, err)
}
credentialsPath := m.GetCredentialsPath(params.ProviderName)
// Start with location from credentials.
location := azureCreds.Location
// Check for component-level location override from merged auth config.
if locationOverride := getComponentLocationOverride(params.StackInfo, params.IdentityName); locationOverride != "" {
location = locationOverride
log.Debug(
"Using component-level location override",
"identity", params.IdentityName,
"location", location,
)
}
// Populate Azure auth context as the single source of truth.
authContext.Azure = &schema.AzureAuthContext{
CredentialsFile: credentialsPath,
Profile: params.IdentityName,
SubscriptionID: azureCreds.SubscriptionID,
TenantID: azureCreds.TenantID,
Location: location,
CloudEnvironment: azureCreds.CloudEnvironment,
// OIDC-specific fields for Terraform ARM_USE_OIDC support.
UseOIDC: azureCreds.IsServicePrincipal,
ClientID: azureCreds.ClientID,
TokenFilePath: azureCreds.TokenFilePath,
}
log.Debug(
"Set Azure auth context",
"profile", params.IdentityName,
"credentials", credentialsPath,
"subscription", azureCreds.SubscriptionID,
"tenant", azureCreds.TenantID,
"location", location,
)
return nil
}
// getComponentLocationOverride extracts location override from component auth config.
func getComponentLocationOverride(stackInfo *schema.ConfigAndStacksInfo, identityName string) string {
if stackInfo == nil || stackInfo.ComponentAuthSection == nil {
return ""
}
identities, ok := stackInfo.ComponentAuthSection["identities"].(map[string]any)
if !ok {
return ""
}
identityCfg, ok := identities[identityName].(map[string]any)
if !ok {
return ""
}
locationOverride, ok := identityCfg["location"].(string)
if !ok {
return ""
}
return locationOverride
}
// SetEnvironmentVariables derives Azure environment variables from AuthContext.
// This populates ComponentEnvSection/ComponentEnvList for spawned processes.
// The auth context is the single source of truth; this function derives from it.
//
// Uses PrepareEnvironment helper to ensure consistent environment setup across all commands.
// This clears conflicting credential env vars and sets Azure subscription/tenant/location.
//
// Parameters:
// - authContext: Runtime auth context containing Azure credentials
// - stackInfo: Stack configuration to populate with environment variables
func SetEnvironmentVariables(authContext *schema.AuthContext, stackInfo *schema.ConfigAndStacksInfo) error {
if authContext == nil || authContext.Azure == nil {
return nil // No auth context to derive from.
}
if stackInfo == nil {
return nil // No stack info to populate.
}
azureAuth := authContext.Azure
// Convert existing environment section to map for PrepareEnvironment.
environMap := make(map[string]string)
if stackInfo.ComponentEnvSection != nil {
for k, v := range stackInfo.ComponentEnvSection {
if str, ok := v.(string); ok {
environMap[k] = str
}
}
}
// Use shared PrepareEnvironment helper to get properly configured environment.
// Pass OIDC fields from auth context for Terraform ARM_USE_OIDC support.
environMap = PrepareEnvironment(PrepareEnvironmentConfig{
Environ: environMap,
SubscriptionID: azureAuth.SubscriptionID,
TenantID: azureAuth.TenantID,
Location: azureAuth.Location,
CloudEnvironment: azureAuth.CloudEnvironment,
UseOIDC: azureAuth.UseOIDC,
ClientID: azureAuth.ClientID,
TokenFilePath: azureAuth.TokenFilePath,
})
// Replace ComponentEnvSection with prepared environment.
// IMPORTANT: We must completely replace, not merge, to ensure deleted keys stay deleted.
stackInfo.ComponentEnvSection = make(map[string]any, len(environMap))
for k, v := range environMap {
stackInfo.ComponentEnvSection[k] = v
}
return nil
}
// UpdateAzureCLIFiles updates Azure CLI files (MSAL cache and azureProfile.json) so Terraform providers can use them.
// This makes Atmos authentication work exactly like `az login`.
// This should be called from PostAuthenticate to ensure CLI compatibility.
// The cloudEnvName selects the Azure cloud environment ("public", "usgovernment", "china").
// If empty, defaults to "public".
func UpdateAzureCLIFiles(creds types.ICredentials, tenantID, subscriptionID, cloudEnvName, realm string) error {
azureCreds, ok := creds.(*types.AzureCredentials)
if !ok {
return nil // Not Azure credentials, nothing to do.
}
// Credentials minted BY the Azure CLI must not be written back into the CLI's
// own cache: az already holds the authoritative entry for this account, and a
// second Account entry (with a home_account_id derived from the target tenant)
// makes az fail with "Found multiple accounts with the same username" for
// guest/B2B users (https://github.com/Azure/azure-cli/issues/20168).
if azureCreds.AuthMethod == types.AzureAuthMethodCLI {
log.Debug("Skipping Azure CLI file update; credentials originated from the Azure CLI")
return nil
}
// Extract user OID and username from token.
userOID, err := extractOIDFromToken(azureCreds.AccessToken)
if err != nil {
log.Debug("Failed to extract OID from token, skipping Azure CLI cache update", "error", err)
return nil // Non-fatal.
}
username := resolveUsername(azureCreds)
// Get home directory.
home, err := os.UserHomeDir()
if err != nil {
log.Debug("Failed to get home directory", "error", err)
return nil
}
// Resolve cloud environment for correct endpoint scopes.
cloudEnv := GetCloudEnvironment(cloudEnvName)
// Update MSAL token cache with management, Graph API, and KeyVault tokens.
updateMSALCacheFromCreds(&msalCredsContext{
Home: home,
UserOID: userOID,
TenantID: tenantID,
Realm: realm,
}, azureCreds, cloudEnv)
// Update azureProfile.json.
if err := updateAzureProfile(home, ProfileUpdateParams{
Username: username,
TenantID: tenantID,
SubscriptionID: subscriptionID,
IsServicePrincipal: azureCreds.IsServicePrincipal,
AzureProfileEnvName: cloudEnv.AzureProfileEnvName,
}); err != nil {
log.Debug("Failed to update Azure profile", "error", err)
// Non-fatal.
}
maybeUpdateServicePrincipalEntries(home, tenantID, azureCreds)
return nil
}
// maybeUpdateServicePrincipalEntries updates service_principal_entries.json for
// service principal auth. This allows Azure CLI commands to work with OIDC
// tokens during the CI workflow. Non-fatal on failure.
func maybeUpdateServicePrincipalEntries(home, tenantID string, azureCreds *types.AzureCredentials) {
if !azureCreds.IsServicePrincipal || azureCreds.ClientID == "" || azureCreds.FederatedToken == "" {
return
}
if err := updateServicePrincipalEntries(home, azureCreds.ClientID, tenantID, azureCreds.FederatedToken); err != nil {
log.Debug("Failed to update service principal entries", "error", err)
}
}
// The msalCredsContext struct carries the cache-location and account context
// for updateMSALCacheFromCreds.
type msalCredsContext struct {
Home string
UserOID string
TenantID string
Realm string
}
// updateMSALCacheFromCreds updates the MSAL token cache using Azure credentials and cloud environment.
func updateMSALCacheFromCreds(ctx *msalCredsContext, azureCreds *types.AzureCredentials, cloudEnv *CloudEnvironment) {
if err := updateMSALCache(&msalCacheUpdate{
Home: ctx.Home,
AccessToken: azureCreds.AccessToken,
Expiration: azureCreds.Expiration,
GraphToken: azureCreds.GraphAPIToken,
GraphExpiration: azureCreds.GraphAPIExpiration,
KeyVaultToken: azureCreds.KeyVaultToken,
KeyVaultExpiration: azureCreds.KeyVaultExpiration,
UserOID: ctx.UserOID,
TenantID: ctx.TenantID,
AuthMethod: azureCreds.AuthMethod,
HomeAccountID: azureCreds.HomeAccountID,
ClientID: azureCreds.ClientID,
IsServicePrincipal: azureCreds.IsServicePrincipal,
LoginEndpoint: cloudEnv.LoginEndpoint,
ManagementScope: strings.Join(append([]string{cloudEnv.ManagementScope}, cloudEnv.LegacyManagementScopes...), " "),
Realm: ctx.Realm,
GraphAPIScope: cloudEnv.GraphAPIScope,
KeyVaultScope: cloudEnv.KeyVaultScope,
}); err != nil {
log.Debug("Failed to update MSAL cache", "error", err)
// Continue to try azureProfile update.
}
}
// msalCacheUpdate holds parameters for updating MSAL cache.
type msalCacheUpdate struct {
Home string
AccessToken string
Expiration string
GraphToken string
GraphExpiration string
KeyVaultToken string
KeyVaultExpiration string
UserOID string
TenantID string
// AuthMethod is the AzureCredentials.AuthMethod that minted these tokens;
// selects the MSAL cache account_source label.
AuthMethod string
// Realm is the Atmos credential-isolation realm (source of refresh tokens).
Realm string
// HomeAccountID is MSAL's "{home-oid}.{home-tenant-id}" for the authenticated
// account, when the provider received it from MSAL. For guest (B2B) users this
// differs from "{UserOID}.{TenantID}" and MUST be used for the cache Account
// entry so az does not see two accounts with the same username.
HomeAccountID string
// ClientID is set for service principal authentication (OIDC).
ClientID string
// IsServicePrincipal indicates this is service principal auth.
// Service principal tokens use a different MSAL cache format:
// - home_account_id is empty (cache key starts with "-")
// - No Account entry is created
// - AppMetadata entry is added
// Reference: https://github.com/AzureAD/microsoft-authentication-library-for-python
IsServicePrincipal bool
// Cloud environment endpoints for sovereign cloud support.
LoginEndpoint string // Azure AD login endpoint (e.g., "login.microsoftonline.com").
ManagementScope string // Management API scope.
GraphAPIScope string // Graph API scope.
KeyVaultScope string // KeyVault API scope.
}
// updateMSALCache updates the Azure CLI MSAL token cache.
func updateMSALCache(params *msalCacheUpdate) error {
msalCachePath := filepath.Join(params.Home, ".azure", "msal_token_cache.json")
// Load existing cache or create new one.
cache, err := loadMSALCache(msalCachePath)
if err != nil {
return err
}
// Initialize cache sections and populate with tokens.
sections := initializeCacheSections(cache)
if params.IsServicePrincipal {
// Service principal uses different MSAL cache format.
addServicePrincipalTokens(sections, params)
} else {
// User authentication uses standard format.
addUserAccountAndTokens(sections, params)
// Copy refresh tokens from the Atmos realm cache so az can self-mint
// any audience and survive access-token expiry.
CopyAtmosRefreshTokensInto(cache, params.Home, params.Realm, params.HomeAccountID)
}
// Write updated cache.
updatedData, err := json.MarshalIndent(cache, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal MSAL cache: %w", err)
}
return writeMSALCacheToFile(msalCachePath, updatedData)
}
// msalCacheSections holds all MSAL cache sections.
type msalCacheSections struct {
accessToken map[string]interface{}
account map[string]interface{}
appMetadata map[string]interface{}
}
// initializeCacheSections ensures all MSAL cache sections exist.
func initializeCacheSections(cache map[string]interface{}) *msalCacheSections {
sections := &msalCacheSections{}
// Ensure AccessToken section exists.
if at, ok := cache[FieldAccessToken].(map[string]interface{}); ok {
sections.accessToken = at
} else {
sections.accessToken = make(map[string]interface{})
cache[FieldAccessToken] = sections.accessToken
}
// Ensure Account section exists.
if acc, ok := cache["Account"].(map[string]interface{}); ok {
sections.account = acc
} else {
sections.account = make(map[string]interface{})
cache["Account"] = sections.account
}
// Ensure AppMetadata section exists (used for service principal auth).
if am, ok := cache["AppMetadata"].(map[string]interface{}); ok {
sections.appMetadata = am
} else {
sections.appMetadata = make(map[string]interface{})
cache["AppMetadata"] = sections.appMetadata
}
return sections
}
// msalIdentifiers holds common MSAL cache identifiers.
type msalIdentifiers struct {
homeAccountID string
environment string
clientID string
realm string
}
// accountSourceForAuthMethod returns the MSAL cache account_source label for an
// auth method, mirroring what az itself records: "authorization_code" for the
// interactive browser flow, "device_code" otherwise.
func accountSourceForAuthMethod(authMethod string) string {
if authMethod == types.AzureAuthMethodInteractive {
return "authorization_code"
}
return "device_code"
}
// addUserAccountAndTokens adds account entry and tokens for user authentication.
func addUserAccountAndTokens(sections *msalCacheSections, params *msalCacheUpdate) {
// Prefer MSAL's own home account ID: for guest (B2B) users the home tenant
// differs from the target tenant, and deriving "{oid}.{target-tenant}" would
// create a second Account entry with the same username, breaking az
// (https://github.com/Azure/azure-cli/issues/20168).
homeAccountID := params.HomeAccountID
if homeAccountID == "" {
homeAccountID = fmt.Sprintf("%s.%s", params.UserOID, params.TenantID)
}
// Create common MSAL identifiers for user auth.
ids := msalIdentifiers{
homeAccountID: homeAccountID,
environment: params.LoginEndpoint,
clientID: "04b07795-8ddb-461a-bbee-02f9e1bf7b46", // Azure CLI public client.
realm: params.TenantID,
}
// Add Account entry (required for azuread provider).
accountKey := fmt.Sprintf("%s-%s-%s", ids.homeAccountID, ids.environment, ids.realm)
accountEntry := map[string]interface{}{
FieldHomeAccountID: ids.homeAccountID,
FieldEnvironment: ids.environment,
FieldRealm: ids.realm,
"local_account_id": params.UserOID,
"username": extractUsernameOrFallback(params.AccessToken),
"authority_type": "MSSTS",
"account_source": accountSourceForAuthMethod(params.AuthMethod),
}
sections.account[accountKey] = accountEntry
// Add management API token.
addTokenToCache(sections.accessToken, &tokenCacheParams{
Token: params.AccessToken,
Expiration: params.Expiration,
Scope: params.ManagementScope,
HomeAccountID: ids.homeAccountID,
Environment: ids.environment,
ClientID: ids.clientID,
Realm: ids.realm,
APIName: "Management API",
})
// Add optional Graph and KeyVault tokens.
addOptionalTokens(sections.accessToken, params, ids)
}
// addServicePrincipalTokens adds tokens for service principal (OIDC) authentication.
// Service principal auth uses a different MSAL cache format per the MSAL Python reference:
// - home_account_id is empty (cache key starts with "-")
// - No Account entry is created
// - AppMetadata entry is added
// Reference: https://github.com/AzureAD/microsoft-authentication-library-for-python/blob/dev/msal/token_cache.py
func addServicePrincipalTokens(sections *msalCacheSections, params *msalCacheUpdate) {
// For service principal, home_account_id is empty.
// This results in cache keys starting with "-".
ids := msalIdentifiers{
homeAccountID: "", // Empty for service principal.
environment: params.LoginEndpoint,
clientID: params.ClientID,
realm: params.TenantID,
}
// Add AppMetadata entry (required for service principal).
// Format: appmetadata-{environment}-{client_id} (lowercase).
appMetadataKey := fmt.Sprintf("appmetadata-%s-%s", strings.ToLower(params.LoginEndpoint), strings.ToLower(params.ClientID))
sections.appMetadata[appMetadataKey] = map[string]interface{}{
FieldEnvironment: params.LoginEndpoint,
"client_id": params.ClientID,
"family_id": "", // Empty for non-FOCI apps.
}
log.Debug("Added AppMetadata entry to MSAL cache", LogFieldKey, appMetadataKey)
// Add management API token.
// For service principal, the cache key format is:
// -{environment}-accesstoken-{client_id}-{realm}-{target} (all lowercase).
addTokenToCache(sections.accessToken, &tokenCacheParams{
Token: params.AccessToken,
Expiration: params.Expiration,
Scope: params.ManagementScope,
HomeAccountID: ids.homeAccountID,
Environment: ids.environment,
ClientID: ids.clientID,
Realm: ids.realm,
APIName: "Management API",
})
// Add optional Graph and KeyVault tokens.
addOptionalTokens(sections.accessToken, params, ids)
}
// addOptionalTokens adds Graph and KeyVault tokens if available.
func addOptionalTokens(accessTokenSection map[string]interface{}, params *msalCacheUpdate, ids msalIdentifiers) {
// Add Microsoft Graph API token if available.
if params.GraphToken != "" {
addTokenToCache(accessTokenSection, &tokenCacheParams{
Token: params.GraphToken,
Expiration: params.GraphExpiration,
Scope: params.GraphAPIScope,
HomeAccountID: ids.homeAccountID,
Environment: ids.environment,
ClientID: ids.clientID,
Realm: ids.realm,
APIName: "Graph API",
})
} else {
log.Debug("No Graph API token available, azuread provider may not work")
}
// Add Azure KeyVault API token if available.
if params.KeyVaultToken != "" {
addTokenToCache(accessTokenSection, &tokenCacheParams{
Token: params.KeyVaultToken,
Expiration: params.KeyVaultExpiration,
Scope: params.KeyVaultScope,
HomeAccountID: ids.homeAccountID,
Environment: ids.environment,
ClientID: ids.clientID,
Realm: ids.realm,
APIName: "KeyVault API",
})
} else {
log.Debug("No KeyVault API token available, KeyVault operations may not work")
}
}
// loadMSALCache loads existing MSAL cache from file or creates a new empty cache.
func loadMSALCache(msalCachePath string) (map[string]interface{}, error) {
data, err := os.ReadFile(msalCachePath)
if err != nil {
if !os.IsNotExist(err) {
return nil, fmt.Errorf("failed to read MSAL cache: %w", err)
}
return make(map[string]interface{}), nil
}
var cache map[string]interface{}
if err := json.Unmarshal(data, &cache); err != nil {
return nil, fmt.Errorf("failed to parse MSAL cache: %w", err)
}
return cache, nil
}
// writeMSALCacheToFile writes MSAL cache data to file with locking.
func writeMSALCacheToFile(msalCachePath string, data []byte) error {
// Ensure .azure directory exists.
azureDir := filepath.Dir(msalCachePath)
if err := os.MkdirAll(azureDir, DirPermissions); err != nil {
return fmt.Errorf("failed to create .azure directory: %w", err)
}
return withFileLock(context.Background(), msalCachePath, func() error {
if err := os.WriteFile(msalCachePath, data, FilePermissions); err != nil {
return fmt.Errorf("failed to write MSAL cache: %w", err)
}
log.Debug("Updated Azure CLI MSAL token cache", "path", msalCachePath)
return nil
})
}
// tokenCacheParams holds parameters for adding a token to MSAL cache.
type tokenCacheParams struct {
Token string
Expiration string
Scope string
HomeAccountID string
Environment string
ClientID string
Realm string
APIName string
}
// addTokenToCache adds a token entry to the MSAL cache section.
func addTokenToCache(accessTokenSection map[string]interface{}, params *tokenCacheParams) {
// Parse token expiration.
expiresAt, err := time.Parse(time.RFC3339, params.Expiration)
if err != nil {
log.Debug("Failed to parse "+params.APIName+" token expiration, skipping cache", "error", err)
return
}
cacheKey := fmt.Sprintf("%s-%s-accesstoken-%s-%s-%s",
params.HomeAccountID, params.Environment, params.ClientID, params.Realm, params.Scope)
cachedAt := time.Now().Unix()
expiresOn := expiresAt.Unix()
tokenEntry := map[string]interface{}{
"credential_type": FieldAccessToken,
"secret": params.Token,
"home_account_id": params.HomeAccountID,
"environment": params.Environment,
"client_id": params.ClientID,
"target": params.Scope,
"realm": params.Realm,
"token_type": "Bearer",
"cached_at": fmt.Sprintf(IntFormat, cachedAt),
"expires_on": fmt.Sprintf(IntFormat, expiresOn),
"extended_expires_on": fmt.Sprintf(IntFormat, expiresOn),
}
accessTokenSection[cacheKey] = tokenEntry
log.Debug("Added "+params.APIName+" token to MSAL cache", "key", cacheKey)
}
// ProfileUpdateParams contains the parameters for updating an Azure profile subscription entry.
type ProfileUpdateParams struct {
Username string
TenantID string
SubscriptionID string
IsServicePrincipal bool
AzureProfileEnvName string
}
// updateAzureProfile updates the azureProfile.json file with the current subscription.
func updateAzureProfile(home string, params ProfileUpdateParams) error {
profilePath := filepath.Join(home, ".azure", "azureProfile.json")
azureDir := filepath.Dir(profilePath)
if err := os.MkdirAll(azureDir, DirPermissions); err != nil {
return fmt.Errorf("failed to create .azure directory: %w", err)
}
return withFileLock(context.Background(), profilePath, func() error {
// Load existing profile or create new one.
var profile map[string]interface{}
data, err := os.ReadFile(profilePath)
if err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("failed to read Azure profile: %w", err)
}
profile = map[string]interface{}{
"installationId": "",
"subscriptions": []interface{}{},
}
} else {
// Strip UTF-8 BOM if present (Azure CLI sometimes writes files with BOM).
data = stripBOM(data)
if err := json.Unmarshal(data, &profile); err != nil {
return fmt.Errorf("failed to parse Azure profile: %w", err)
}
}
profile["subscriptions"] = UpdateSubscriptionsInProfile(profile, params)
updatedData, err := json.MarshalIndent(profile, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal Azure profile: %w", err)
}
if err := os.WriteFile(profilePath, updatedData, FilePermissions); err != nil {
return fmt.Errorf("failed to write Azure profile: %w", err)
}
log.Debug("Updated Azure profile", "path", profilePath, "subscription", params.SubscriptionID)
return nil
})
}
// UpdateSubscriptionsInProfile updates the subscriptions array in an Azure profile.
// It sets the specified subscription as default and marks all others as not default.
func UpdateSubscriptionsInProfile(profile map[string]interface{}, params ProfileUpdateParams) []interface{} {
// Get subscriptions array.
subscriptionsRaw, ok := profile["subscriptions"].([]interface{})
if !ok {
subscriptionsRaw = []interface{}{}
}
// Determine user type based on authentication method.
userType := "user"
if params.IsServicePrincipal {
userType = "servicePrincipal"
}
// Find or create subscription entry.
var found bool
for i, subRaw := range subscriptionsRaw {
sub, ok := subRaw.(map[string]interface{})
if !ok {
continue
}
subID, _ := sub["id"].(string)
if subID == params.SubscriptionID {
// Update existing subscription.
sub["tenantId"] = params.TenantID
sub["isDefault"] = true
sub["state"] = "Enabled"
sub[FieldUser] = map[string]interface{}{
"name": params.Username,
"type": userType,
}
sub["environmentName"] = params.AzureProfileEnvName
subscriptionsRaw[i] = sub
found = true
} else {
// Mark other subscriptions as not default.
sub["isDefault"] = false
subscriptionsRaw[i] = sub
}
}
// Add new subscription if not found.
if !found && params.SubscriptionID != "" {
newSub := map[string]interface{}{
"id": params.SubscriptionID,
"name": params.SubscriptionID,
"tenantId": params.TenantID,
"isDefault": true,
"state": "Enabled",
"environmentName": params.AzureProfileEnvName,
FieldUser: map[string]interface{}{
"name": params.Username,
"type": userType,
},
}
subscriptionsRaw = append(subscriptionsRaw, newSub)
}
return subscriptionsRaw
}
// updateServicePrincipalEntries updates the service_principal_entries.json file for Azure CLI.
// This enables Azure CLI commands to work with OIDC tokens during CI workflows.
// Field names match Azure CLI's ServicePrincipalStore: client_id, tenant, client_assertion.
// Reference: https://github.com/Azure/azure-cli/blob/main/src/azure-cli-core/azure/cli/core/auth/identity.py
func updateServicePrincipalEntries(home, clientID, tenantID, federatedToken string) error {
entriesPath := filepath.Join(home, ".azure", "service_principal_entries.json")
azureDir := filepath.Dir(entriesPath)
if err := os.MkdirAll(azureDir, DirPermissions); err != nil {
return fmt.Errorf("failed to create .azure directory: %w", err)
}
return withFileLock(context.Background(), entriesPath, func() error {
// Load existing entries or create a new array.
var entries []map[string]interface{}
data, err := os.ReadFile(entriesPath)
if err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("failed to read service principal entries: %w", err)
}
entries = []map[string]interface{}{}
} else {
// Strip UTF-8 BOM if present.
data = stripBOM(data)
if err := json.Unmarshal(data, &entries); err != nil {
// If file is corrupted, start fresh.
log.Debug("Failed to parse service principal entries, creating new file", "error", err)
entries = []map[string]interface{}{}
}
}
// Azure CLI looks up entries by client_id field.
var found bool
for i, entry := range entries {
if cid, ok := entry["client_id"].(string); ok && cid == clientID {
entries[i] = createServicePrincipalEntry(clientID, tenantID, federatedToken)
found = true
break
}
}
if !found {
entries = append(entries, createServicePrincipalEntry(clientID, tenantID, federatedToken))
}
updatedData, err := json.MarshalIndent(entries, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal service principal entries: %w", err)
}
if err := os.WriteFile(entriesPath, updatedData, FilePermissions); err != nil {
return fmt.Errorf("failed to write service principal entries: %w", err)
}
log.Debug("Updated Azure CLI service principal entries", "path", entriesPath, "client_id", clientID)
return nil
})
}
// createServicePrincipalEntry creates a service principal entry for OIDC authentication.
// Field names match Azure CLI's ServicePrincipalStore constants:
// - _CLIENT_ID = 'client_id'
// - _TENANT = 'tenant'
// - _CLIENT_ASSERTION = 'client_assertion'
func createServicePrincipalEntry(clientID, tenantID, federatedToken string) map[string]interface{} {
return map[string]interface{}{
"client_id": clientID,
"tenant": tenantID,
"client_assertion": federatedToken,
}
}
// extractOIDFromToken extracts the user OID from a JWT token.
func extractOIDFromToken(token string) (string, error) {
claims, err := extractJWTClaims(token)
if err != nil {
return "", err
}
oid, ok := claims["oid"].(string)
if !ok {
return "", errUtils.ErrAzureOIDClaimNotFound
}
return oid, nil
}
// extractUsernameFromToken extracts the username from a JWT token.
func extractUsernameFromToken(token string) (string, error) {
claims, err := extractJWTClaims(token)
if err != nil {
return "", err
}
// Try upn first, then unique_name, then email.
if upn, ok := claims["upn"].(string); ok && upn != "" {
return upn, nil
}
if uniqueName, ok := claims["unique_name"].(string); ok && uniqueName != "" {
return uniqueName, nil
}
if email, ok := claims["email"].(string); ok && email != "" {
return email, nil
}
return "", errUtils.ErrAzureUsernameClaimNotFound
}
// resolveUsername extracts username from credentials with service-principal-aware fallback.
func resolveUsername(azureCreds *types.AzureCredentials) string {
username, err := extractUsernameFromToken(azureCreds.AccessToken)
if err != nil {
log.Debug("Failed to extract username from token, using fallback", "error", err)
if azureCreds.IsServicePrincipal && azureCreds.ClientID != "" {
return azureCreds.ClientID
}
return "user@unknown"
}
return username
}
// extractUsernameOrFallback extracts username from token or returns fallback.
func extractUsernameOrFallback(token string) string {
username, err := extractUsernameFromToken(token)
if err != nil {
return "user@unknown"
}
return username
}
// extractJWTClaims decodes a JWT token and returns the claims.
func extractJWTClaims(token string) (map[string]interface{}, error) {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return nil, errUtils.ErrAzureInvalidJWTFormat
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, fmt.Errorf("failed to decode JWT payload: %w", err)
}
var claims map[string]interface{}
if err := json.Unmarshal(payload, &claims); err != nil {
return nil, fmt.Errorf("failed to parse JWT claims: %w", err)
}
return claims, nil
}
// stripBOM removes UTF-8 BOM (Byte Order Mark) from the beginning of data.
// Azure CLI sometimes writes JSON files with BOM which causes JSON parsing to fail.
func stripBOM(data []byte) []byte {
// UTF-8 BOM is EF BB BF.
if len(data) >= 3 && data[0] == BomMarker && data[1] == BomSecondByte && data[2] == BomThirdByte {
return data[3:]
}
return data
}