wangzhibo
2026-05-09 53418655c061ac26f66058253f39200aced1ab1d
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
 
import { AuthorityType } from "./AuthorityType.js";
import {
    isOpenIdConfigResponse,
    OpenIdConfigResponse,
} from "./OpenIdConfigResponse.js";
import { UrlString } from "../url/UrlString.js";
import { IUri } from "../url/IUri.js";
import {
    createClientAuthError,
    ClientAuthErrorCodes,
} from "../error/ClientAuthError.js";
import { INetworkModule } from "../network/INetworkModule.js";
import * as Constants from "../utils/Constants.js";
import {
    EndpointMetadata,
    getCloudDiscoveryMetadataFromHardcodedValues,
    getCloudDiscoveryMetadataFromNetworkResponse,
    InstanceDiscoveryMetadataAliases,
} from "./AuthorityMetadata.js";
import {
    createClientConfigurationError,
    ClientConfigurationErrorCodes,
} from "../error/ClientConfigurationError.js";
import { ProtocolMode } from "./ProtocolMode.js";
import { ICacheManager } from "../cache/interface/ICacheManager.js";
import { AuthorityMetadataEntity } from "../cache/entities/AuthorityMetadataEntity.js";
import {
    AuthorityOptions,
    AzureCloudInstance,
    StaticAuthorityOptions,
} from "./AuthorityOptions.js";
import {
    CloudInstanceDiscoveryResponse,
    isCloudInstanceDiscoveryResponse,
} from "./CloudInstanceDiscoveryResponse.js";
import {
    CloudInstanceDiscoveryErrorResponse,
    isCloudInstanceDiscoveryErrorResponse,
} from "./CloudInstanceDiscoveryErrorResponse.js";
import { CloudDiscoveryMetadata } from "./CloudDiscoveryMetadata.js";
import { RegionDiscovery } from "./RegionDiscovery.js";
import { RegionDiscoveryMetadata } from "./RegionDiscoveryMetadata.js";
import { ImdsOptions } from "./ImdsOptions.js";
import type { AzureCloudOptions } from "../config/ClientConfiguration.js";
import { Logger } from "../logger/Logger.js";
import { AuthError } from "../error/AuthError.js";
import { IPerformanceClient } from "../telemetry/performance/IPerformanceClient.js";
import * as PerformanceEvents from "../telemetry/performance/PerformanceEvents.js";
import { invokeAsync } from "../utils/FunctionWrappers.js";
import * as CacheHelpers from "../cache/utils/CacheHelpers.js";
 
/**
 * The authority class validates the authority URIs used by the user, and retrieves the OpenID Configuration Data from the
 * endpoint. It will store the pertinent config data in this object for use during token calls.
 * @internal
 */
export class Authority {
    // Canonical authority url string
    private _canonicalAuthority: UrlString;
    // Canonicaly authority url components
    private _canonicalAuthorityUrlComponents: IUri | null;
    // Network interface to make requests with.
    protected networkInterface: INetworkModule;
    // Cache Manager to cache network responses
    protected cacheManager: ICacheManager;
    // Protocol mode to construct endpoints
    private authorityOptions: AuthorityOptions;
    // Authority metadata
    private metadata: AuthorityMetadataEntity;
    // Region discovery service
    private regionDiscovery: RegionDiscovery;
    // Region discovery metadata
    public regionDiscoveryMetadata: RegionDiscoveryMetadata;
    // Logger object
    private logger: Logger;
    // Performance client
    protected performanceClient: IPerformanceClient;
    // Correlation Id
    protected correlationId: string;
    // Indicates if the authority is fake, for the purpose of a Managed Identity Application
    private managedIdentity: boolean;
    // Reserved tenant domain names that will not be replaced with tenant id
    private static reservedTenantDomains: Set<string> = new Set([
        "{tenant}",
        "{tenantid}",
        Constants.AADAuthority.COMMON,
        Constants.AADAuthority.CONSUMERS,
        Constants.AADAuthority.ORGANIZATIONS,
    ]);
 
    constructor(
        authority: string,
        networkInterface: INetworkModule,
        cacheManager: ICacheManager,
        authorityOptions: AuthorityOptions,
        logger: Logger,
        correlationId: string,
        performanceClient: IPerformanceClient,
        managedIdentity?: boolean
    ) {
        this.canonicalAuthority = authority;
        this._canonicalAuthority.validateAsUri();
        this.networkInterface = networkInterface;
        this.cacheManager = cacheManager;
        this.authorityOptions = authorityOptions;
        this.regionDiscoveryMetadata = {
            region_used: undefined,
            region_source: undefined,
            region_outcome: undefined,
        };
        this.logger = logger;
        this.performanceClient = performanceClient;
        this.correlationId = correlationId;
        this.managedIdentity = managedIdentity || false;
        this.regionDiscovery = new RegionDiscovery(
            networkInterface,
            this.logger,
            this.performanceClient,
            this.correlationId
        );
    }
 
    /**
     * Get {@link AuthorityType}
     * @param authorityUri {@link IUri}
     * @private
     */
    private getAuthorityType(authorityUri: IUri): AuthorityType {
        // CIAM auth url pattern is being standardized as: <tenant>.ciamlogin.com
        if (authorityUri.HostNameAndPort.endsWith(Constants.CIAM_AUTH_URL)) {
            return AuthorityType.Ciam;
        }
 
        const pathSegments = authorityUri.PathSegments;
        if (pathSegments.length) {
            switch (pathSegments[0].toLowerCase()) {
                case Constants.ADFS:
                    return AuthorityType.Adfs;
                case Constants.DSTS:
                    return AuthorityType.Dsts;
                default:
                    break;
            }
        }
        return AuthorityType.Default;
    }
 
    // See above for AuthorityType
    public get authorityType(): AuthorityType {
        return this.getAuthorityType(this.canonicalAuthorityUrlComponents);
    }
 
    /**
     * ProtocolMode enum representing the way endpoints are constructed.
     */
    public get protocolMode(): ProtocolMode {
        return this.authorityOptions.protocolMode;
    }
 
    /**
     * Returns authorityOptions which can be used to reinstantiate a new authority instance
     */
    public get options(): AuthorityOptions {
        return this.authorityOptions;
    }
 
    /**
     * A URL that is the authority set by the developer
     */
    public get canonicalAuthority(): string {
        return this._canonicalAuthority.urlString;
    }
 
    /**
     * Sets canonical authority.
     */
    public set canonicalAuthority(url: string) {
        this._canonicalAuthority = new UrlString(url);
        this._canonicalAuthority.validateAsUri();
        this._canonicalAuthorityUrlComponents = null;
    }
 
    /**
     * Get authority components.
     */
    public get canonicalAuthorityUrlComponents(): IUri {
        if (!this._canonicalAuthorityUrlComponents) {
            this._canonicalAuthorityUrlComponents =
                this._canonicalAuthority.getUrlComponents();
        }
 
        return this._canonicalAuthorityUrlComponents;
    }
 
    /**
     * Get hostname and port i.e. login.microsoftonline.com
     */
    public get hostnameAndPort(): string {
        return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase();
    }
 
    /**
     * Get tenant for authority.
     */
    public get tenant(): string {
        return this.canonicalAuthorityUrlComponents.PathSegments[0];
    }
 
    /**
     * OAuth /authorize endpoint for requests
     */
    public get authorizationEndpoint(): string {
        if (this.discoveryComplete()) {
            return this.replacePath(this.metadata.authorization_endpoint);
        } else {
            throw createClientAuthError(
                ClientAuthErrorCodes.endpointResolutionError
            );
        }
    }
 
    /**
     * OAuth /token endpoint for requests
     */
    public get tokenEndpoint(): string {
        if (this.discoveryComplete()) {
            return this.replacePath(this.metadata.token_endpoint);
        } else {
            throw createClientAuthError(
                ClientAuthErrorCodes.endpointResolutionError
            );
        }
    }
 
    public get deviceCodeEndpoint(): string {
        if (this.discoveryComplete()) {
            return this.replacePath(
                this.metadata.token_endpoint.replace("/token", "/devicecode")
            );
        } else {
            throw createClientAuthError(
                ClientAuthErrorCodes.endpointResolutionError
            );
        }
    }
 
    /**
     * OAuth logout endpoint for requests
     */
    public get endSessionEndpoint(): string {
        if (this.discoveryComplete()) {
            // ROPC policies may not have end_session_endpoint set
            if (!this.metadata.end_session_endpoint) {
                throw createClientAuthError(
                    ClientAuthErrorCodes.endSessionEndpointNotSupported
                );
            }
            return this.replacePath(this.metadata.end_session_endpoint);
        } else {
            throw createClientAuthError(
                ClientAuthErrorCodes.endpointResolutionError
            );
        }
    }
 
    /**
     * OAuth issuer for requests
     */
    public get selfSignedJwtAudience(): string {
        if (this.discoveryComplete()) {
            return this.replacePath(this.metadata.issuer);
        } else {
            throw createClientAuthError(
                ClientAuthErrorCodes.endpointResolutionError
            );
        }
    }
 
    /**
     * Jwks_uri for token signing keys
     */
    public get jwksUri(): string {
        if (this.discoveryComplete()) {
            return this.replacePath(this.metadata.jwks_uri);
        } else {
            throw createClientAuthError(
                ClientAuthErrorCodes.endpointResolutionError
            );
        }
    }
 
    /**
     * Returns a flag indicating that tenant name can be replaced in authority {@link IUri}
     * @param authorityUri {@link IUri}
     * @private
     */
    private canReplaceTenant(authorityUri: IUri): boolean {
        return (
            authorityUri.PathSegments.length === 1 &&
            !Authority.reservedTenantDomains.has(
                authorityUri.PathSegments[0]
            ) &&
            this.getAuthorityType(authorityUri) === AuthorityType.Default &&
            this.protocolMode !== ProtocolMode.OIDC
        );
    }
 
    /**
     * Replaces tenant in url path with current tenant. Defaults to common.
     * @param urlString
     */
    private replaceTenant(urlString: string): string {
        return urlString.replace(/{tenant}|{tenantid}/g, this.tenant);
    }
 
    /**
     * Replaces path such as tenant or policy with the current tenant or policy.
     * @param urlString
     */
    private replacePath(urlString: string): string {
        let endpoint = urlString;
        const cachedAuthorityUrl = new UrlString(
            this.metadata.canonical_authority
        );
        const cachedAuthorityUrlComponents =
            cachedAuthorityUrl.getUrlComponents();
        const cachedAuthorityParts = cachedAuthorityUrlComponents.PathSegments;
        const currentAuthorityParts =
            this.canonicalAuthorityUrlComponents.PathSegments;
 
        currentAuthorityParts.forEach((currentPart, index) => {
            let cachedPart = cachedAuthorityParts[index];
            if (
                index === 0 &&
                this.canReplaceTenant(cachedAuthorityUrlComponents)
            ) {
                const tenantId = new UrlString(
                    this.metadata.authorization_endpoint
                ).getUrlComponents().PathSegments[0];
                /**
                 * Check if AAD canonical authority contains tenant domain name, for example "testdomain.onmicrosoft.com",
                 * by comparing its first path segment to the corresponding authorization endpoint path segment, which is
                 * always resolved with tenant id by OIDC.
                 */
                if (cachedPart !== tenantId) {
                    this.logger.verbose(
                        `Replacing tenant domain name '${cachedPart}' with id '${tenantId}'`,
                        this.correlationId
                    );
                    cachedPart = tenantId;
                }
            }
            if (currentPart !== cachedPart) {
                endpoint = endpoint.replace(
                    `/${cachedPart}/`,
                    `/${currentPart}/`
                );
            }
        });
 
        return this.replaceTenant(endpoint);
    }
 
    /**
     * The default open id configuration endpoint for any canonical authority.
     */
    protected get defaultOpenIdConfigurationEndpoint(): string {
        const canonicalAuthorityHost = this.hostnameAndPort;
        if (
            this.canonicalAuthority.endsWith("v2.0/") ||
            this.authorityType === AuthorityType.Adfs ||
            (this.protocolMode === ProtocolMode.OIDC &&
                !this.isAliasOfKnownMicrosoftAuthority(canonicalAuthorityHost))
        ) {
            return `${this.canonicalAuthority}.well-known/openid-configuration`;
        }
        return `${this.canonicalAuthority}v2.0/.well-known/openid-configuration`;
    }
 
    /**
     * Boolean that returns whether or not tenant discovery has been completed.
     */
    discoveryComplete(): boolean {
        return !!this.metadata;
    }
 
    /**
     * Perform endpoint discovery to discover aliases, preferred_cache, preferred_network
     * and the /authorize, /token and logout endpoints.
     */
    public async resolveEndpointsAsync(): Promise<void> {
        const metadataEntity = this.getCurrentMetadataEntity();
 
        const cloudDiscoverySource = await invokeAsync(
            this.updateCloudDiscoveryMetadata.bind(this),
            PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata,
            this.logger,
            this.performanceClient,
            this.correlationId
        )(metadataEntity);
        this.canonicalAuthority = this.canonicalAuthority.replace(
            this.hostnameAndPort,
            metadataEntity.preferred_network
        );
        const endpointSource = await invokeAsync(
            this.updateEndpointMetadata.bind(this),
            PerformanceEvents.AuthorityUpdateEndpointMetadata,
            this.logger,
            this.performanceClient,
            this.correlationId
        )(metadataEntity);
        this.updateCachedMetadata(metadataEntity, cloudDiscoverySource, {
            source: endpointSource,
        });
        this.performanceClient?.addFields(
            {
                cloudDiscoverySource: cloudDiscoverySource,
                authorityEndpointSource: endpointSource,
            },
            this.correlationId
        );
    }
 
    /**
     * Returns metadata entity from cache if it exists, otherwiser returns a new metadata entity built
     * from the configured canonical authority
     * @returns
     */
    private getCurrentMetadataEntity(): AuthorityMetadataEntity {
        let metadataEntity: AuthorityMetadataEntity | null =
            this.cacheManager.getAuthorityMetadataByAlias(
                this.hostnameAndPort,
                this.correlationId
            );
 
        if (!metadataEntity) {
            metadataEntity = {
                aliases: [],
                preferred_cache: this.hostnameAndPort,
                preferred_network: this.hostnameAndPort,
                canonical_authority: this.canonicalAuthority,
                authorization_endpoint: "",
                token_endpoint: "",
                end_session_endpoint: "",
                issuer: "",
                aliasesFromNetwork: false,
                endpointsFromNetwork: false,
                expiresAt: CacheHelpers.generateAuthorityMetadataExpiresAt(),
                jwks_uri: "",
            };
        }
        return metadataEntity;
    }
 
    /**
     * Updates cached metadata based on metadata source and sets the instance's metadata
     * property to the same value
     * @param metadataEntity
     * @param cloudDiscoverySource
     * @param endpointMetadataResult
     */
    private updateCachedMetadata(
        metadataEntity: AuthorityMetadataEntity,
        cloudDiscoverySource: Constants.AuthorityMetadataSource | null,
        endpointMetadataResult: {
            source: Constants.AuthorityMetadataSource;
            metadata?: OpenIdConfigResponse;
        } | null
    ): void {
        if (
            cloudDiscoverySource !== Constants.AuthorityMetadataSource.CACHE &&
            endpointMetadataResult?.source !==
                Constants.AuthorityMetadataSource.CACHE
        ) {
            // Reset the expiration time unless both values came from a successful cache lookup
            metadataEntity.expiresAt =
                CacheHelpers.generateAuthorityMetadataExpiresAt();
            metadataEntity.canonical_authority = this.canonicalAuthority;
        }
 
        const cacheKey = this.cacheManager.generateAuthorityMetadataCacheKey(
            metadataEntity.preferred_cache,
            this.correlationId
        );
        this.cacheManager.setAuthorityMetadata(
            cacheKey,
            metadataEntity,
            this.correlationId
        );
        this.metadata = metadataEntity;
    }
 
    /**
     * Update AuthorityMetadataEntity with new endpoints and return where the information came from
     * @param metadataEntity
     */
    private async updateEndpointMetadata(
        metadataEntity: AuthorityMetadataEntity
    ): Promise<Constants.AuthorityMetadataSource> {
        const localMetadata =
            this.updateEndpointMetadataFromLocalSources(metadataEntity);
 
        // Further update may be required for hardcoded metadata if regional metadata is preferred
        if (localMetadata) {
            if (
                localMetadata.source ===
                Constants.AuthorityMetadataSource.HARDCODED_VALUES
            ) {
                // If the user prefers to use an azure region replace the global endpoints with regional information.
                if (
                    this.authorityOptions.azureRegionConfiguration?.azureRegion
                ) {
                    if (localMetadata.metadata) {
                        const hardcodedMetadata = await invokeAsync(
                            this.updateMetadataWithRegionalInformation.bind(
                                this
                            ),
                            PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation,
                            this.logger,
                            this.performanceClient,
                            this.correlationId
                        )(localMetadata.metadata);
                        CacheHelpers.updateAuthorityEndpointMetadata(
                            metadataEntity,
                            hardcodedMetadata,
                            false
                        );
                        metadataEntity.canonical_authority =
                            this.canonicalAuthority;
                    }
                }
            }
            return localMetadata.source;
        }
 
        // Get metadata from network if local sources aren't available
        let metadata = await invokeAsync(
            this.getEndpointMetadataFromNetwork.bind(this),
            PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork,
            this.logger,
            this.performanceClient,
            this.correlationId
        )();
        if (metadata) {
            // If the user prefers to use an azure region replace the global endpoints with regional information.
            if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
                metadata = await invokeAsync(
                    this.updateMetadataWithRegionalInformation.bind(this),
                    PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation,
                    this.logger,
                    this.performanceClient,
                    this.correlationId
                )(metadata);
            }
 
            CacheHelpers.updateAuthorityEndpointMetadata(
                metadataEntity,
                metadata,
                true
            );
            return Constants.AuthorityMetadataSource.NETWORK;
        } else {
            // Metadata could not be obtained from the config, cache, network or hardcoded values
            throw createClientAuthError(
                ClientAuthErrorCodes.openIdConfigError,
                this.defaultOpenIdConfigurationEndpoint
            );
        }
    }
 
    /**
     * Updates endpoint metadata from local sources and returns where the information was retrieved from and the metadata config
     * response if the source is hardcoded metadata
     * @param metadataEntity
     * @returns
     */
    private updateEndpointMetadataFromLocalSources(
        metadataEntity: AuthorityMetadataEntity
    ): {
        source: Constants.AuthorityMetadataSource;
        metadata?: OpenIdConfigResponse;
    } | null {
        this.logger.verbose(
            "Attempting to get endpoint metadata from authority configuration",
            this.correlationId
        );
        const configMetadata = this.getEndpointMetadataFromConfig();
        if (configMetadata) {
            this.logger.verbose(
                "Found endpoint metadata in authority configuration",
                this.correlationId
            );
            CacheHelpers.updateAuthorityEndpointMetadata(
                metadataEntity,
                configMetadata,
                false
            );
            return {
                source: Constants.AuthorityMetadataSource.CONFIG,
            };
        }
 
        this.logger.verbose(
            "Did not find endpoint metadata in the config... Attempting to get endpoint metadata from the hardcoded values.",
            this.correlationId
        );
 
        const hardcodedMetadata = this.getEndpointMetadataFromHardcodedValues();
        if (hardcodedMetadata) {
            CacheHelpers.updateAuthorityEndpointMetadata(
                metadataEntity,
                hardcodedMetadata,
                false
            );
            return {
                source: Constants.AuthorityMetadataSource.HARDCODED_VALUES,
                metadata: hardcodedMetadata,
            };
        } else {
            this.logger.verbose(
                "Did not find endpoint metadata in hardcoded values... Attempting to get endpoint metadata from the network metadata cache.",
                this.correlationId
            );
        }
 
        // Check cached metadata entity expiration status
        const metadataEntityExpired =
            CacheHelpers.isAuthorityMetadataExpired(metadataEntity);
        if (
            this.isAuthoritySameType(metadataEntity) &&
            metadataEntity.endpointsFromNetwork &&
            !metadataEntityExpired
        ) {
            // No need to update
            this.logger.verbose("Found endpoint metadata in the cache.", "");
            return { source: Constants.AuthorityMetadataSource.CACHE };
        } else if (metadataEntityExpired) {
            this.logger.verbose("The metadata entity is expired.", "");
        }
 
        return null;
    }
 
    /**
     * Compares the number of url components after the domain to determine if the cached
     * authority metadata can be used for the requested authority. Protects against same domain different
     * authority such as login.microsoftonline.com/tenant and login.microsoftonline.com/tfp/tenant/policy
     * @param metadataEntity
     */
    private isAuthoritySameType(
        metadataEntity: AuthorityMetadataEntity
    ): boolean {
        const cachedAuthorityUrl = new UrlString(
            metadataEntity.canonical_authority
        );
        const cachedParts = cachedAuthorityUrl.getUrlComponents().PathSegments;
 
        return (
            cachedParts.length ===
            this.canonicalAuthorityUrlComponents.PathSegments.length
        );
    }
 
    /**
     * Parse authorityMetadata config option
     */
    private getEndpointMetadataFromConfig(): OpenIdConfigResponse | null {
        if (this.authorityOptions.authorityMetadata) {
            try {
                return JSON.parse(
                    this.authorityOptions.authorityMetadata
                ) as OpenIdConfigResponse;
            } catch (e) {
                throw createClientConfigurationError(
                    ClientConfigurationErrorCodes.invalidAuthorityMetadata
                );
            }
        }
 
        return null;
    }
 
    /**
     * Gets OAuth endpoints from the given OpenID configuration endpoint.
     *
     * @param hasHardcodedMetadata boolean
     */
    private async getEndpointMetadataFromNetwork(): Promise<OpenIdConfigResponse | null> {
        const options: ImdsOptions = {};
 
        /*
         * TODO: Add a timeout if the authority exists in our library's
         * hardcoded list of metadata
         */
 
        const openIdConfigurationEndpoint =
            this.defaultOpenIdConfigurationEndpoint;
        this.logger.verbose(
            `Authority.getEndpointMetadataFromNetwork: attempting to retrieve OAuth endpoints from '${openIdConfigurationEndpoint}'`,
            this.correlationId
        );
 
        try {
            const response =
                await this.networkInterface.sendGetRequestAsync<OpenIdConfigResponse>(
                    openIdConfigurationEndpoint,
                    options
                );
            const isValidResponse = isOpenIdConfigResponse(response.body);
            if (isValidResponse) {
                return response.body;
            } else {
                this.logger.verbose(
                    `Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration`,
                    this.correlationId
                );
                return null;
            }
        } catch (e) {
            this.logger.verbose(
                `Authority.getEndpointMetadataFromNetwork: '${e}'`,
                this.correlationId
            );
            return null;
        }
    }
 
    /**
     * Get OAuth endpoints for common authorities.
     */
    private getEndpointMetadataFromHardcodedValues(): OpenIdConfigResponse | null {
        if (this.hostnameAndPort in EndpointMetadata) {
            return EndpointMetadata[this.hostnameAndPort];
        }
 
        return null;
    }
 
    /**
     * Update the retrieved metadata with regional information.
     * User selected Azure region will be used if configured.
     */
    private async updateMetadataWithRegionalInformation(
        metadata: OpenIdConfigResponse
    ): Promise<OpenIdConfigResponse> {
        const userConfiguredAzureRegion =
            this.authorityOptions.azureRegionConfiguration?.azureRegion;
 
        if (userConfiguredAzureRegion) {
            if (
                userConfiguredAzureRegion !==
                Constants.AZURE_REGION_AUTO_DISCOVER_FLAG
            ) {
                this.regionDiscoveryMetadata.region_outcome =
                    Constants.RegionDiscoveryOutcomes.CONFIGURED_NO_AUTO_DETECTION;
                this.regionDiscoveryMetadata.region_used =
                    userConfiguredAzureRegion;
                return Authority.replaceWithRegionalInformation(
                    metadata,
                    userConfiguredAzureRegion
                );
            }
 
            const autodetectedRegionName = await invokeAsync(
                this.regionDiscovery.detectRegion.bind(this.regionDiscovery),
                PerformanceEvents.RegionDiscoveryDetectRegion,
                this.logger,
                this.performanceClient,
                this.correlationId
            )(
                this.authorityOptions.azureRegionConfiguration
                    ?.environmentRegion,
                this.regionDiscoveryMetadata
            );
 
            if (autodetectedRegionName) {
                this.regionDiscoveryMetadata.region_outcome =
                    Constants.RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_SUCCESSFUL;
                this.regionDiscoveryMetadata.region_used =
                    autodetectedRegionName;
                return Authority.replaceWithRegionalInformation(
                    metadata,
                    autodetectedRegionName
                );
            }
 
            this.regionDiscoveryMetadata.region_outcome =
                Constants.RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_FAILED;
        }
 
        return metadata;
    }
 
    /**
     * Updates the AuthorityMetadataEntity with new aliases, preferred_network and preferred_cache
     * and returns where the information was retrieved from
     * @param metadataEntity
     * @returns AuthorityMetadataSource
     */
    private async updateCloudDiscoveryMetadata(
        metadataEntity: AuthorityMetadataEntity
    ): Promise<Constants.AuthorityMetadataSource> {
        const localMetadataSource =
            this.updateCloudDiscoveryMetadataFromLocalSources(metadataEntity);
        if (localMetadataSource) {
            return localMetadataSource;
        }
 
        // Fallback to network as metadata source
        const metadata = await invokeAsync(
            this.getCloudDiscoveryMetadataFromNetwork.bind(this),
            PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork,
            this.logger,
            this.performanceClient,
            this.correlationId
        )();
 
        if (metadata) {
            CacheHelpers.updateCloudDiscoveryMetadata(
                metadataEntity,
                metadata,
                true
            );
            return Constants.AuthorityMetadataSource.NETWORK;
        }
 
        // Metadata could not be obtained from the config, cache, network or hardcoded values
        throw createClientConfigurationError(
            ClientConfigurationErrorCodes.untrustedAuthority
        );
    }
 
    private updateCloudDiscoveryMetadataFromLocalSources(
        metadataEntity: AuthorityMetadataEntity
    ): Constants.AuthorityMetadataSource | null {
        this.logger.verbose(
            "Attempting to get cloud discovery metadata  from authority configuration",
            this.correlationId
        );
        this.logger.verbosePii(
            `Known Authorities: '${
                this.authorityOptions.knownAuthorities ||
                Constants.NOT_APPLICABLE
            }'`,
            this.correlationId
        );
        this.logger.verbosePii(
            `Authority Metadata: '${
                this.authorityOptions.authorityMetadata ||
                Constants.NOT_APPLICABLE
            }'`,
            this.correlationId
        );
        this.logger.verbosePii(
            `Canonical Authority: '${
                metadataEntity.canonical_authority || Constants.NOT_APPLICABLE
            }'`,
            this.correlationId
        );
        const metadata = this.getCloudDiscoveryMetadataFromConfig();
        if (metadata) {
            this.logger.verbose(
                "Found cloud discovery metadata in authority configuration",
                this.correlationId
            );
            CacheHelpers.updateCloudDiscoveryMetadata(
                metadataEntity,
                metadata,
                false
            );
            return Constants.AuthorityMetadataSource.CONFIG;
        }
 
        // If the cached metadata came from config but that config was not passed to this instance, we must go to hardcoded values
        this.logger.verbose(
            "Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the hardcoded values.",
            this.correlationId
        );
 
        const hardcodedMetadata = getCloudDiscoveryMetadataFromHardcodedValues(
            this.hostnameAndPort
        );
        if (hardcodedMetadata) {
            this.logger.verbose(
                "Found cloud discovery metadata from hardcoded values.",
                this.correlationId
            );
            CacheHelpers.updateCloudDiscoveryMetadata(
                metadataEntity,
                hardcodedMetadata,
                false
            );
            return Constants.AuthorityMetadataSource.HARDCODED_VALUES;
        }
 
        this.logger.verbose(
            "Did not find cloud discovery metadata in hardcoded values... Attempting to get cloud discovery metadata from the network metadata cache.",
            this.correlationId
        );
 
        const metadataEntityExpired =
            CacheHelpers.isAuthorityMetadataExpired(metadataEntity);
        if (
            this.isAuthoritySameType(metadataEntity) &&
            metadataEntity.aliasesFromNetwork &&
            !metadataEntityExpired
        ) {
            this.logger.verbose(
                "Found cloud discovery metadata in the cache.",
                ""
            );
            // No need to update
            return Constants.AuthorityMetadataSource.CACHE;
        } else if (metadataEntityExpired) {
            this.logger.verbose("The metadata entity is expired.", "");
        }
 
        return null;
    }
 
    /**
     * Parse cloudDiscoveryMetadata config or check knownAuthorities
     */
    private getCloudDiscoveryMetadataFromConfig(): CloudDiscoveryMetadata | null {
        // CIAM does not support cloud discovery metadata
        if (this.authorityType === AuthorityType.Ciam) {
            this.logger.verbose(
                "CIAM authorities do not support cloud discovery metadata, generate the aliases from authority host.",
                this.correlationId
            );
            return Authority.createCloudDiscoveryMetadataFromHost(
                this.hostnameAndPort
            );
        }
 
        // Check if network response was provided in config
        if (this.authorityOptions.cloudDiscoveryMetadata) {
            this.logger.verbose(
                "The cloud discovery metadata has been provided as a network response, in the config.",
                this.correlationId
            );
            try {
                this.logger.verbose(
                    "Attempting to parse the cloud discovery metadata.",
                    this.correlationId
                );
                const parsedResponse = JSON.parse(
                    this.authorityOptions.cloudDiscoveryMetadata
                ) as CloudInstanceDiscoveryResponse;
                const metadata = getCloudDiscoveryMetadataFromNetworkResponse(
                    parsedResponse.metadata,
                    this.hostnameAndPort
                );
                this.logger.verbose("Parsed the cloud discovery metadata.", "");
                if (metadata) {
                    this.logger.verbose(
                        "There is returnable metadata attached to the parsed cloud discovery metadata.",
                        this.correlationId
                    );
                    return metadata;
                } else {
                    this.logger.verbose(
                        "There is no metadata attached to the parsed cloud discovery metadata.",
                        this.correlationId
                    );
                }
            } catch (e) {
                this.logger.verbose(
                    "Unable to parse the cloud discovery metadata. Throwing Invalid Cloud Discovery Metadata Error.",
                    this.correlationId
                );
                throw createClientConfigurationError(
                    ClientConfigurationErrorCodes.invalidCloudDiscoveryMetadata
                );
            }
        }
 
        // If cloudDiscoveryMetadata is empty or does not contain the host, check knownAuthorities
        if (this.isInKnownAuthorities()) {
            this.logger.verbose(
                "The host is included in knownAuthorities. Creating new cloud discovery metadata from the host.",
                this.correlationId
            );
            return Authority.createCloudDiscoveryMetadataFromHost(
                this.hostnameAndPort
            );
        }
 
        return null;
    }
 
    /**
     * Called to get metadata from network if CloudDiscoveryMetadata was not populated by config
     *
     * @param hasHardcodedMetadata boolean
     */
    private async getCloudDiscoveryMetadataFromNetwork(): Promise<CloudDiscoveryMetadata | null> {
        const instanceDiscoveryEndpoint = `${Constants.AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`;
        const options: ImdsOptions = {};
 
        /*
         * TODO: Add a timeout if the authority exists in our library's
         * hardcoded list of metadata
         */
 
        let match = null;
        try {
            const response = await this.networkInterface.sendGetRequestAsync<
                | CloudInstanceDiscoveryResponse
                | CloudInstanceDiscoveryErrorResponse
            >(instanceDiscoveryEndpoint, options);
            let typedResponseBody:
                | CloudInstanceDiscoveryResponse
                | CloudInstanceDiscoveryErrorResponse;
            let metadata: Array<CloudDiscoveryMetadata>;
            if (isCloudInstanceDiscoveryResponse(response.body)) {
                typedResponseBody =
                    response.body as CloudInstanceDiscoveryResponse;
                metadata = typedResponseBody.metadata;
 
                this.logger.verbosePii(
                    `tenant_discovery_endpoint is: '${typedResponseBody.tenant_discovery_endpoint}'`,
                    this.correlationId
                );
            } else if (isCloudInstanceDiscoveryErrorResponse(response.body)) {
                this.logger.warning(
                    `A CloudInstanceDiscoveryErrorResponse was returned. The cloud instance discovery network request's status code is: '${response.status}'`,
                    this.correlationId
                );
 
                typedResponseBody =
                    response.body as CloudInstanceDiscoveryErrorResponse;
                if (typedResponseBody.error === Constants.INVALID_INSTANCE) {
                    this.logger.error(
                        "The CloudInstanceDiscoveryErrorResponse error is invalid_instance.",
                        this.correlationId
                    );
                    return null;
                }
 
                this.logger.warning(
                    `The CloudInstanceDiscoveryErrorResponse error is '${typedResponseBody.error}'`,
                    this.correlationId
                );
                this.logger.warning(
                    `The CloudInstanceDiscoveryErrorResponse error description is '${typedResponseBody.error_description}'`,
                    this.correlationId
                );
 
                this.logger.warning(
                    "Setting the value of the CloudInstanceDiscoveryMetadata (returned from the network, correlationId) to []",
                    this.correlationId
                );
                metadata = [];
            } else {
                this.logger.error(
                    "AAD did not return a CloudInstanceDiscoveryResponse or CloudInstanceDiscoveryErrorResponse",
                    this.correlationId
                );
                return null;
            }
 
            this.logger.verbose(
                "Attempting to find a match between the developer's authority and the CloudInstanceDiscoveryMetadata returned from the network request.",
                this.correlationId
            );
            match = getCloudDiscoveryMetadataFromNetworkResponse(
                metadata,
                this.hostnameAndPort
            );
        } catch (error) {
            if (error instanceof AuthError) {
                this.logger.error(
                    `There was a network error while attempting to get the cloud discovery instance metadata.\nError: '${error.errorCode}'\nError Description: '${error.errorMessage}'`,
                    this.correlationId
                );
            } else {
                const typedError = error as Error;
                this.logger.error(
                    `A non-MSALJS error was thrown while attempting to get the cloud instance discovery metadata.\nError: '${typedError.name}'\nError Description: '${typedError.message}'`,
                    this.correlationId
                );
            }
 
            return null;
        }
 
        // Custom Domain scenario, host is trusted because Instance Discovery call succeeded
        if (!match) {
            this.logger.warning(
                "The developer's authority was not found within the CloudInstanceDiscoveryMetadata returned from the network request.",
                this.correlationId
            );
            this.logger.verbose(
                "Creating custom Authority for custom domain scenario.",
                this.correlationId
            );
 
            match = Authority.createCloudDiscoveryMetadataFromHost(
                this.hostnameAndPort
            );
        }
        return match;
    }
 
    /**
     * Helper function to determine if this host is included in the knownAuthorities config option
     */
    private isInKnownAuthorities(): boolean {
        const matches = this.authorityOptions.knownAuthorities.filter(
            (authority) => {
                return (
                    authority &&
                    UrlString.getDomainFromUrl(authority).toLowerCase() ===
                        this.hostnameAndPort
                );
            }
        );
        return matches.length > 0;
    }
 
    /**
     * helper function to populate the authority based on azureCloudOptions
     * @param authorityString
     * @param azureCloudOptions
     */
    static generateAuthority(
        authorityString: string,
        azureCloudOptions?: AzureCloudOptions
    ): string {
        let authorityAzureCloudInstance;
 
        if (
            azureCloudOptions &&
            azureCloudOptions.azureCloudInstance !== AzureCloudInstance.None
        ) {
            const tenant = azureCloudOptions.tenant
                ? azureCloudOptions.tenant
                : Constants.DEFAULT_COMMON_TENANT;
            authorityAzureCloudInstance = `${azureCloudOptions.azureCloudInstance}/${tenant}/`;
        }
 
        return authorityAzureCloudInstance
            ? authorityAzureCloudInstance
            : authorityString;
    }
 
    /**
     * Creates cloud discovery metadata object from a given host
     * @param host
     */
    static createCloudDiscoveryMetadataFromHost(
        host: string
    ): CloudDiscoveryMetadata {
        return {
            preferred_network: host,
            preferred_cache: host,
            aliases: [host],
        };
    }
 
    /**
     * helper function to generate environment from authority object
     */
    getPreferredCache(): string {
        if (this.managedIdentity) {
            return Constants.DEFAULT_AUTHORITY_HOST;
        } else if (this.discoveryComplete()) {
            return this.metadata.preferred_cache;
        } else {
            throw createClientAuthError(
                ClientAuthErrorCodes.endpointResolutionError
            );
        }
    }
 
    /**
     * Returns whether or not the provided host is an alias of this authority instance
     * @param host
     */
    isAlias(host: string): boolean {
        return this.metadata.aliases.indexOf(host) > -1;
    }
 
    /**
     * Returns whether or not the provided host is an alias of a known Microsoft authority for purposes of endpoint discovery
     * @param host
     */
    isAliasOfKnownMicrosoftAuthority(host: string): boolean {
        return InstanceDiscoveryMetadataAliases.has(host);
    }
 
    /**
     * Checks whether the provided host is that of a public cloud authority
     *
     * @param authority string
     * @returns bool
     */
    static isPublicCloudAuthority(host: string): boolean {
        return Constants.KNOWN_PUBLIC_CLOUDS.indexOf(host) >= 0;
    }
 
    /**
     * Rebuild the authority string with the region
     *
     * @param host string
     * @param region string
     */
    static buildRegionalAuthorityString(
        host: string,
        region: string,
        queryString?: string
    ): string {
        // Create and validate a Url string object with the initial authority string
        const authorityUrlInstance = new UrlString(host);
        authorityUrlInstance.validateAsUri();
 
        const authorityUrlParts = authorityUrlInstance.getUrlComponents();
 
        let hostNameAndPort = `${region}.${authorityUrlParts.HostNameAndPort}`;
 
        if (this.isPublicCloudAuthority(authorityUrlParts.HostNameAndPort)) {
            hostNameAndPort = `${region}.${Constants.REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`;
        }
 
        // Include the query string portion of the url
        const url = UrlString.constructAuthorityUriFromObject({
            ...authorityUrlInstance.getUrlComponents(),
            HostNameAndPort: hostNameAndPort,
        }).urlString;
 
        // Add the query string if a query string was provided
        if (queryString) return `${url}?${queryString}`;
 
        return url;
    }
 
    /**
     * Replace the endpoints in the metadata object with their regional equivalents.
     *
     * @param metadata OpenIdConfigResponse
     * @param azureRegion string
     */
    static replaceWithRegionalInformation(
        metadata: OpenIdConfigResponse,
        azureRegion: string
    ): OpenIdConfigResponse {
        const regionalMetadata = { ...metadata };
        regionalMetadata.authorization_endpoint =
            Authority.buildRegionalAuthorityString(
                regionalMetadata.authorization_endpoint,
                azureRegion
            );
 
        regionalMetadata.token_endpoint =
            Authority.buildRegionalAuthorityString(
                regionalMetadata.token_endpoint,
                azureRegion
            );
 
        if (regionalMetadata.end_session_endpoint) {
            regionalMetadata.end_session_endpoint =
                Authority.buildRegionalAuthorityString(
                    regionalMetadata.end_session_endpoint,
                    azureRegion
                );
        }
 
        return regionalMetadata;
    }
 
    /**
     * Transform CIAM_AUTHORIY as per the below rules:
     * If no path segments found and it is a CIAM authority (hostname ends with .ciamlogin.com), then transform it
     *
     * NOTE: The transformation path should go away once STS supports CIAM with the format: `tenantIdorDomain.ciamlogin.com`
     * `ciamlogin.com` can also change in the future and we should accommodate the same
     *
     * @param authority
     */
    static transformCIAMAuthority(authority: string): string {
        let ciamAuthority = authority;
        const authorityUrl = new UrlString(authority);
        const authorityUrlComponents = authorityUrl.getUrlComponents();
 
        // check if transformation is needed
        if (
            authorityUrlComponents.PathSegments.length === 0 &&
            authorityUrlComponents.HostNameAndPort.endsWith(
                Constants.CIAM_AUTH_URL
            )
        ) {
            const tenantIdOrDomain =
                authorityUrlComponents.HostNameAndPort.split(".")[0];
            ciamAuthority = `${ciamAuthority}${tenantIdOrDomain}${Constants.AAD_TENANT_DOMAIN_SUFFIX}`;
        }
 
        return ciamAuthority;
    }
}
 
/**
 * Extract tenantId from authority
 */
export function getTenantFromAuthorityString(
    authority: string
): string | undefined {
    const authorityUrl = new UrlString(authority);
    const authorityUrlComponents = authorityUrl.getUrlComponents();
    /**
     * For credential matching purposes, tenantId is the last path segment of the authority URL:
     *  AAD Authority - domain/tenantId -> Credentials are cached with realm = tenantId
     *  B2C Authority - domain/{tenantId}?/.../policy -> Credentials are cached with realm = policy
     *  tenantId is downcased because B2C policies can have mixed case but tfp claim is downcased
     *
     * Note that we may not have any path segments in certain OIDC scenarios.
     */
    const tenantId =
        authorityUrlComponents.PathSegments.slice(-1)[0]?.toLowerCase();
 
    switch (tenantId) {
        case Constants.AADAuthority.COMMON:
        case Constants.AADAuthority.ORGANIZATIONS:
        case Constants.AADAuthority.CONSUMERS:
            return undefined;
        default:
            return tenantId;
    }
}
 
export function formatAuthorityUri(authorityUri: string): string {
    return authorityUri.endsWith(Constants.FORWARD_SLASH)
        ? authorityUri
        : `${authorityUri}${Constants.FORWARD_SLASH}`;
}
 
export function buildStaticAuthorityOptions(
    authOptions: Partial<AuthorityOptions>
): StaticAuthorityOptions {
    const rawCloudDiscoveryMetadata = authOptions.cloudDiscoveryMetadata;
    let cloudDiscoveryMetadata: CloudInstanceDiscoveryResponse | undefined =
        undefined;
    if (rawCloudDiscoveryMetadata) {
        try {
            cloudDiscoveryMetadata = JSON.parse(rawCloudDiscoveryMetadata);
        } catch (e) {
            throw createClientConfigurationError(
                ClientConfigurationErrorCodes.invalidCloudDiscoveryMetadata
            );
        }
    }
    return {
        canonicalAuthority: authOptions.authority
            ? formatAuthorityUri(authOptions.authority)
            : undefined,
        knownAuthorities: authOptions.knownAuthorities,
        cloudDiscoveryMetadata: cloudDiscoveryMetadata,
    };
}