-
Notifications
You must be signed in to change notification settings - Fork 337
Expand file tree
/
Copy pathsubscriptions_manager.go
More file actions
465 lines (398 loc) · 14.2 KB
/
Copy pathsubscriptions_manager.go
File metadata and controls
465 lines (398 loc) · 14.2 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package account
import (
"cmp"
"context"
"fmt"
"log"
"math"
"os"
"slices"
"strconv"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions"
"github.com/azure/azure-dev/cli/azd/pkg/auth"
"github.com/azure/azure-dev/cli/azd/pkg/convert"
"github.com/azure/azure-dev/cli/azd/pkg/input"
"go.uber.org/multierr"
)
// SubscriptionResolver resolves subscription metadata for the current account, including both the resource tenant
// and the user access tenant.
type SubscriptionResolver interface {
GetSubscription(ctx context.Context, subscriptionId string) (*Subscription, error)
}
// Typically auth.Manager
type principalInfoProvider interface {
GetLoggedInServicePrincipalTenantID(ctx context.Context) (*string, error)
ClaimsForCurrentUser(ctx context.Context, options *auth.ClaimsForCurrentUserOptions) (auth.TokenClaims, error)
}
// Typically subscriptionsCache
type subCache interface {
Load(ctx context.Context, key string) ([]Subscription, error)
Save(ctx context.Context, key string, save []Subscription) error
Merge(ctx context.Context, key string, save []Subscription) error
Clear(ctx context.Context) error
}
// SubscriptionsManager manages listing, storing and retrieving subscriptions for the current account.
//
// Since the application supports multi-tenancy, subscriptions can be accessed by the user through different tenants.
// To lookup access to a given subscription, LookupTenant can be used to lookup the
// current account's required tenantID to access a given subscription.
type SubscriptionsManager struct {
service *SubscriptionsService
principalInfo principalInfoProvider
cache subCache
console input.Console
}
func NewSubscriptionsManager(
service *SubscriptionsService,
auth *auth.Manager,
console input.Console) (*SubscriptionsManager, error) {
cache, err := newSubCache()
if err != nil {
return nil, err
}
return &SubscriptionsManager{
service: service,
cache: cache,
principalInfo: auth,
console: console,
}, nil
}
// Clears stored cached subscriptions. This can only return an error if a filesystem error other than ErrNotExist occurred.
func (m *SubscriptionsManager) ClearSubscriptions(ctx context.Context) error {
err := m.cache.Clear(ctx)
if err != nil {
return fmt.Errorf("clearing stored subscriptions: %w", err)
}
return nil
}
// Updates stored cached subscriptions.
// Uses merge semantics to preserve tenant-to-subscription mappings for tenants that are temporarily inaccessible.
func (m *SubscriptionsManager) RefreshSubscriptions(ctx context.Context) error {
claims, err := m.principalInfo.ClaimsForCurrentUser(ctx, nil)
if err != nil {
return err
}
uid := claims.LocalAccountId()
subs, err := m.ListSubscriptions(ctx)
if err != nil {
return fmt.Errorf("fetching subscriptions: %w", err)
}
err = m.cache.Merge(ctx, uid, subs)
if err != nil {
return fmt.Errorf("storing subscriptions: %w", err)
}
return nil
}
// Resolve the tenant ID required by the current account to access the given subscription.
//
// - If the account is logged in with a service principal specified, the service principal's tenant ID
// is immediately returned (single-tenant mode).
//
// - Otherwise, the tenant ID is resolved by examining the stored subscriptionID to tenantID cache.
// See SubscriptionCache for details about caching. On cache miss, all tenants and subscriptions are queried from
// azure management services for the current account to build the mapping and populate the cache.
func (m *SubscriptionsManager) LookupTenant(ctx context.Context, subscriptionId string) (tenantId string, err error) {
principalTenantId, err := m.principalInfo.GetLoggedInServicePrincipalTenantID(ctx)
if err != nil {
return "", err
}
if principalTenantId != nil {
return *principalTenantId, nil
}
res, err := m.getSubscriptions(ctx)
if err != nil {
return "", fmt.Errorf("resolving user access to subscription '%s' : %w", subscriptionId, err)
}
for _, sub := range res.subscriptions {
if sub.Id == subscriptionId {
return sub.UserAccessTenantId, nil
}
}
return "", fmt.Errorf(
"failed to resolve user '%s' access to subscription with ID '%s'. "+
"If you recently gained access to this subscription, run `azd auth login` again to reload subscriptions.\n"+
"If you have lost access to a tenant containing this subscription, "+
"you may need to run `azd auth login --tenant-id <tenant-id>` to re-authenticate to that specific tenant. "+
"Otherwise, visit this subscription in Azure Portal using the browser, then run `azd auth login`.",
res.userClaims.DisplayUsername(),
subscriptionId)
}
// GetSubscriptions retrieves subscriptions accessible by the current account with caching semantics.
//
// Unlike ListSubscriptions, GetSubscriptions first examines the subscriptions cache.
// On cache miss, subscriptions are fetched, the cached is updated, before the result is returned.
func (m *SubscriptionsManager) GetSubscriptions(ctx context.Context) ([]Subscription, error) {
res, err := m.getSubscriptions(ctx)
if err != nil {
return nil, err
}
return res.subscriptions, nil
}
type getSubscriptionsResult struct {
subscriptions []Subscription
userClaims auth.TokenClaims
}
func (m *SubscriptionsManager) getSubscriptions(ctx context.Context) (getSubscriptionsResult, error) {
claims, err := m.principalInfo.ClaimsForCurrentUser(ctx, nil)
if err != nil {
return getSubscriptionsResult{}, err
}
uid := claims.LocalAccountId()
subscriptions, err := m.cache.Load(ctx, uid)
if err != nil {
// When running in playback mode with a synthetic subscription, skip the real ARM call
// to list subscriptions. The synthetic subscription is sufficient for the test to proceed,
// and the recording cassette won't contain the /tenants API responses needed by ListSubscriptions.
syntheticId := os.Getenv("AZD_DEBUG_SYNTHETIC_SUBSCRIPTION")
if syntheticId != "" {
subscriptions = []Subscription{{
Id: syntheticId,
Name: "AZD Synthetic Test Subscription",
TenantId: claims.TenantId,
UserAccessTenantId: claims.TenantId,
}}
} else {
subscriptions, err = m.ListSubscriptions(ctx)
if err != nil {
return getSubscriptionsResult{}, fmt.Errorf("listing subscriptions: %w", err)
}
err = m.cache.Save(ctx, uid, subscriptions)
if err != nil {
return getSubscriptionsResult{}, fmt.Errorf("saving subscriptions to cache: %w", err)
}
}
}
// When the integration test framework runs a test in playback mode, it sets AZD_DEBUG_SYNTHETIC_SUBSCRIPTION to the
// ID of the subscription that was used when recording the test. We ensure this subscription is always present in the
// list returned by `getSubscriptions` so that end to end tests can run successfully.
if syntheticId := os.Getenv("AZD_DEBUG_SYNTHETIC_SUBSCRIPTION"); syntheticId != "" {
found := false
for _, sub := range subscriptions {
if sub.Id == syntheticId {
found = true
break
}
}
if !found {
subscriptions = append(subscriptions, Subscription{
Id: syntheticId,
Name: "AZD Synthetic Test Subscription",
TenantId: claims.TenantId,
UserAccessTenantId: claims.TenantId,
})
}
}
return getSubscriptionsResult{
subscriptions: subscriptions,
userClaims: claims,
}, nil
}
// GetSubscription retrieves subscription metadata for the current account, including both the resource tenant
// and the tenant through which the current user can access it.
func (m *SubscriptionsManager) GetSubscription(ctx context.Context, subscriptionId string) (*Subscription, error) {
subscriptions, err := m.GetSubscriptions(ctx)
if err != nil {
return nil, err
}
for _, sub := range subscriptions {
if sub.Id == subscriptionId {
return &sub, nil
}
}
return m.getSubscription(ctx, subscriptionId)
}
type tenantSubsResult struct {
subs []Subscription
err error
}
// ListSubscription lists subscriptions accessible by the current account by calling azure management services.
func (m *SubscriptionsManager) ListSubscriptions(ctx context.Context) ([]Subscription, error) {
msg := "Retrieving subscriptions..."
m.console.ShowSpinner(ctx, msg, input.Step)
defer m.console.StopSpinner(ctx, "", input.StepDone)
principalTenantId, err := m.principalInfo.GetLoggedInServicePrincipalTenantID(ctx)
if err != nil {
return nil, err
}
// If account is a service principal, we can speed up listing by skipping subscription listing across tenants since a
// service principal is tied to a single tenant.
if principalTenantId != nil {
subscriptions, err := m.service.ListSubscriptions(ctx, *principalTenantId)
if err != nil {
return nil, err
}
tenantSubscriptions := []Subscription{}
for _, subscription := range subscriptions {
tenantSubscriptions = append(tenantSubscriptions, toSubscription(*subscription, *principalTenantId))
}
return tenantSubscriptions, nil
}
tenants, err := m.service.ListTenants(ctx)
if err != nil {
return nil, fmt.Errorf("listing tenants: %w", err)
}
listForTenant := func(
jobs <-chan armsubscriptions.TenantIDDescription,
results chan<- tenantSubsResult,
service *SubscriptionsService) {
for tenant := range jobs {
azSubs, err := service.ListSubscriptions(ctx, *tenant.TenantID)
if err != nil {
errorMsg := err.Error()
name := *tenant.TenantID
if tenant.DisplayName != nil {
name = *tenant.DisplayName
}
if strings.Contains(errorMsg, "AADSTS50076") {
idOrDomain := *tenant.TenantID
if tenant.DefaultDomain != nil {
idOrDomain = *tenant.DefaultDomain
}
err = fmt.Errorf(
"%s requires Multi-Factor Authentication (MFA). "+
"To authenticate, login with `azd auth login --tenant-id %s`",
name,
idOrDomain)
} else {
err = fmt.Errorf("failed to load subscriptions from tenant '%s' : %w", name, err)
}
}
results <- tenantSubsResult{toSubscriptions(azSubs, *tenant.TenantID), err}
}
}
numJobs := len(tenants)
jobs := make(chan armsubscriptions.TenantIDDescription, numJobs)
results := make(chan tenantSubsResult, numJobs)
maxWorkers := 25
if workerMax := os.Getenv("AZD_SUBSCRIPTIONS_FETCH_MAX_CONCURRENCY"); workerMax != "" {
if val, err := strconv.ParseInt(workerMax, 10, 0); err == nil {
maxWorkers = int(val)
}
}
numWorkers := int(math.Min(float64(len(tenants)), float64(maxWorkers)))
for range numWorkers {
go listForTenant(jobs, results, m.service)
}
for i := range numJobs {
jobs <- tenants[i]
}
close(jobs)
allSubscriptions := []Subscription{}
errors := []error{}
oneSuccess := false
for range numJobs {
res := <-results
if res.err != nil {
errors = append(errors, res.err)
continue
}
oneSuccess = true
allSubscriptions = append(allSubscriptions, res.subs...)
}
close(results)
slices.SortFunc(allSubscriptions, func(a, b Subscription) int {
return cmp.Compare(a.Name, b.Name)
})
if !oneSuccess && len(tenants) > 0 {
return nil, multierr.Combine(errors...)
}
// If at least one was successful, log errors and continue
for _, err := range errors {
log.Println(err.Error())
}
return allSubscriptions, nil
}
func (m *SubscriptionsManager) GetLocation(ctx context.Context, subscriptionId, locationName string) (Location, error) {
var err error
m.console.ShowSpinner(ctx, "Reading subscription and location from environment...", input.Step)
defer m.console.StopSpinner(ctx, "", input.GetStepResultFormat(err))
allLocations, err := m.listLocations(ctx, subscriptionId)
if err != nil {
return Location{}, err
}
for _, location := range allLocations {
if locationName == location.Name {
return location, nil
}
}
return Location{}, fmt.Errorf("location name %s not found", locationName)
}
func (m *SubscriptionsManager) ListLocations(
ctx context.Context,
subscriptionId string,
) ([]Location, error) {
var err error
msg := "Retrieving locations..."
m.console.ShowSpinner(ctx, msg, input.Step)
defer m.console.StopSpinner(ctx, "", input.GetStepResultFormat(err))
return m.GetLocations(ctx, subscriptionId)
}
// GetLocations lists locations for a subscription without rendering progress UX.
func (m *SubscriptionsManager) GetLocations(
ctx context.Context,
subscriptionId string,
) ([]Location, error) {
return m.listLocations(ctx, subscriptionId)
}
func (m *SubscriptionsManager) listLocations(
ctx context.Context,
subscriptionId string,
) ([]Location, error) {
tenantId, err := m.LookupTenant(ctx, subscriptionId)
if err != nil {
return nil, err
}
return m.service.ListSubscriptionLocations(ctx, subscriptionId, tenantId)
}
func (m *SubscriptionsManager) getSubscription(ctx context.Context, subscriptionId string) (*Subscription, error) {
tenantId, err := m.LookupTenant(ctx, subscriptionId)
if err != nil {
return nil, err
}
azSub, err := m.service.GetSubscription(ctx, subscriptionId, tenantId)
if err != nil {
return nil, err
}
sub := toSubscription(*azSub, tenantId)
return &sub, nil
}
// GetTenantDisplayNames returns a map of tenant ID to display name for all tenants
// accessible by the current account.
func (m *SubscriptionsManager) GetTenantDisplayNames(ctx context.Context) (map[string]string, error) {
tenants, err := m.service.ListTenants(ctx)
if err != nil {
return nil, fmt.Errorf("listing tenants: %w", err)
}
result := make(map[string]string, len(tenants))
for _, t := range tenants {
if t.TenantID != nil {
name := *t.TenantID
if t.DisplayName != nil && *t.DisplayName != "" {
name = *t.DisplayName
}
result[*t.TenantID] = name
}
}
return result, nil
}
func toSubscriptions(azSubs []*armsubscriptions.Subscription, userAccessTenantId string) []Subscription {
if azSubs == nil {
return nil
}
subs := make([]Subscription, 0, len(azSubs))
for _, azSub := range azSubs {
subs = append(subs, toSubscription(*azSub, userAccessTenantId))
}
return subs
}
func toSubscription(subscription armsubscriptions.Subscription, userAccessTenantId string) Subscription {
return Subscription{
Id: *subscription.SubscriptionID,
Name: convert.ToValueWithDefault(subscription.DisplayName, *subscription.SubscriptionID),
TenantId: *subscription.TenantID,
UserAccessTenantId: userAccessTenantId,
}
}