Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions change/@azure-msal-common-validate-authority-inputs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "patch",
"comment": "Validate authority and region inputs and honor instance-aware configuration during authorization code redemption [#8959](https://github.com/AzureAD/microsoft-authentication-library-for-js/pull/8959)",
"packageName": "@azure/msal-common",
"email": "nugetaad@microsoft.com",
"dependentChangeType": "patch"
}
7 changes: 7 additions & 0 deletions change/@azure-msal-node-sanitize-code-response.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "patch",
"comment": "Sanitize authorization code response payloads consistently across Node clients [#8959](https://github.com/AzureAD/microsoft-authentication-library-for-js/pull/8959)",
"packageName": "@azure/msal-node",
"email": "nugetaad@microsoft.com",
"dependentChangeType": "patch"
}
11 changes: 9 additions & 2 deletions lib/msal-common/src/authority/Authority.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ import {
isCloudInstanceDiscoveryErrorResponse,
} from "./CloudInstanceDiscoveryErrorResponse.js";
import { CloudDiscoveryMetadata } from "./CloudDiscoveryMetadata.js";
import { RegionDiscovery } from "./RegionDiscovery.js";
import { RegionDiscovery, isValidRegion } from "./RegionDiscovery.js";
import { RegionDiscoveryMetadata } from "./RegionDiscoveryMetadata.js";
import { ImdsOptions } from "./ImdsOptions.js";
import type { AzureCloudOptions } from "../config/ClientConfiguration.js";
Expand Down Expand Up @@ -1439,6 +1439,13 @@ export class Authority {
correlationId: string,
queryString?: string
): string {
if (!isValidRegion(region)) {
throw createClientConfigurationError(
ClientConfigurationErrorCodes.urlParseError,
correlationId
);
}

// Create and validate a Url string object with the initial authority string
const authorityUrlInstance = new UrlString(host, correlationId);
authorityUrlInstance.validateAsUri();
Expand All @@ -1454,7 +1461,7 @@ export class Authority {
// Include the query string portion of the url
const url = UrlString.constructAuthorityUriFromObject(
{
...authorityUrlInstance.getUrlComponents(),
...authorityUrlParts,
HostNameAndPort: hostNameAndPort,
},
correlationId
Expand Down
27 changes: 24 additions & 3 deletions lib/msal-common/src/authority/RegionDiscovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,20 @@ import * as PerformanceEvents from "../telemetry/performance/PerformanceEvents.j
import { invokeAsync } from "../utils/FunctionWrappers.js";
import { Logger } from "../logger/Logger.js";

const REGION_NAME_PATTERN = /^[a-z][a-z0-9-]*$/i;
Comment thread
tnorling marked this conversation as resolved.
Resolved

/**
* Whether a region can safely be used as a single DNS label.
*/
export function isValidRegion(region: string): boolean {
return (
typeof region === "string" &&
Comment thread
tnorling marked this conversation as resolved.
Resolved
region.length <= 63 &&

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why 63? Seems kind of random and arbitrary, a comment explaining this would help

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The region becomes a DNS label, whose maximum length is 63 octets under RFC 1035 §2.3.4. Since we allow only ASCII, that equals 63 characters. Added a named constant and a comment explaining the limit.

REGION_NAME_PATTERN.test(region) &&
!region.endsWith("-")
Comment thread
tnorling marked this conversation as resolved.
Resolved
);
}

export class RegionDiscovery {
// Network interface to make requests with.
protected networkInterface: INetworkModule;
Expand Down Expand Up @@ -125,13 +139,20 @@ export class RegionDiscovery {
Constants.RegionDiscoverySources.ENVIRONMENT_VARIABLE;
}

// If no region was auto detected from the environment or from the IMDS endpoint, mark the attempt as a FAILED_AUTO_DETECTION
if (!autodetectedRegionName) {
// Untrusted discovery values must be a single DNS label before becoming a host prefix.
if (!autodetectedRegionName || !isValidRegion(autodetectedRegionName)) {
if (autodetectedRegionName) {
this.logger.warning(
"Region discovery returned an invalid region. Using the global authority.",
this.correlationId
);
}
regionDiscoveryMetadata.region_source =
Constants.RegionDiscoverySources.FAILED_AUTO_DETECTION;
return null;
}

return autodetectedRegionName || null;
return autodetectedRegionName;
}

/**
Expand Down
5 changes: 4 additions & 1 deletion lib/msal-common/src/client/AuthorizationCodeClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,10 @@ export class AuthorizationCodeClient {
}

// Check for new cloud instance
if (authCodePayload && authCodePayload.cloud_instance_host_name) {
if (
this.config.authOptions.instanceAware === true &&
authCodePayload?.cloud_instance_host_name
Comment thread
konstantin-msft marked this conversation as resolved.
Resolved
) {
await invokeAsync(
this.updateTokenEndpointAuthority.bind(this),
PerformanceEvents.UpdateTokenEndpointAuthority,
Expand Down
34 changes: 34 additions & 0 deletions lib/msal-common/src/url/UrlString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ import { StringUtils } from "../utils/StringUtils.js";
import { IUri } from "./IUri.js";
import * as Constants from "../utils/Constants.js";

const UNSAFE_AUTHORITY = /[\x00-\x20\x7f\\@]/;
Comment thread
tnorling marked this conversation as resolved.
Resolved
const DEFAULT_PORTS: Record<string, string> = {
"https:": ":443",
"http:": ":80",
};

/**
* Url object class which can perform various transformations on url strings.
*/
Expand Down Expand Up @@ -169,6 +175,34 @@ export class UrlString {
QueryString: match[7],
} as IUri;

let parsedUrl: URL;
try {
parsedUrl = new URL(this.urlString);
} catch {
throw createClientConfigurationError(
ClientConfigurationErrorCodes.urlParseError,
this.correlationId
);
}

const host = urlComponents.HostNameAndPort?.toLowerCase();
const schemeAndAuthority = `${urlComponents.Protocol}//${host}`;
const defaultPort = DEFAULT_PORTS[parsedUrl.protocol] ?? "";
const hostMatches =
Comment thread
tnorling marked this conversation as resolved.
Resolved
host === parsedUrl.host ||
host === `${parsedUrl.host}${defaultPort}` ||
(/^\[[0-9a-f:.]+\](?::[0-9]+)?$/i.test(host ?? "") &&

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here as well

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed this regex instead. The earlier new URL() call already validates IPv6 syntax, so checking for an opening bracket is sufficient to select the IPv6 normalization branch. Added a comment that explains that

new URL(`${urlComponents.Protocol}//${host}`).host ===
parsedUrl.host);

// Check authority ambiguity without restricting resource paths, queries, or fragments.
if (UNSAFE_AUTHORITY.test(schemeAndAuthority) || !hostMatches) {
throw createClientConfigurationError(
ClientConfigurationErrorCodes.urlParseError,
this.correlationId
);
}

let pathSegments = urlComponents.AbsolutePath.split("/");
pathSegments = pathSegments.filter((val) => val && val.length > 0); // remove empty elements
urlComponents.PathSegments = pathSegments;
Expand Down
94 changes: 94 additions & 0 deletions lib/msal-common/test/authority/Authority.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -953,6 +953,57 @@ describe("Authority.ts Class Unit Tests", () => {
sendPostRequestAsync: <T>(): Promise<T> => Promise.resolve({} as T),
});

it.each([
{ source: "environment", expectedCalls: 0 },
{ source: "imds", expectedCalls: 1 },
{ source: "imds-retry", expectedCalls: 3 },
])(
"discards invalid region values from $source",
async ({ source, expectedCalls }) => {
const invalidRegion = "example.com\\";
let calls = 0;
const networkInterface = buildNetworkInterface(() => {
calls++;
if (source === "imds-retry" && calls === 1) {
return { status: Constants.HTTP_BAD_REQUEST };
}
if (source === "imds-retry" && calls === 2) {
return {
status: Constants.HTTP_BAD_REQUEST,
body: { "newest-versions": ["2026-01-01"] },
};
}
return {
status: Constants.HTTP_SUCCESS,
body: { location: invalidRegion },
};
});
const warningSpy = jest.spyOn(logger, "warning");
const regionDiscovery = new RegionDiscovery(
networkInterface,
logger,
new StubPerformanceClient(),
correlationId
);
const metadata: RegionDiscoveryMetadata = {};

await expect(
regionDiscovery.detectRegion(
source === "environment" ? invalidRegion : undefined,
metadata
)
).resolves.toBeNull();
expect(metadata.region_source).toBe(
Constants.RegionDiscoverySources.FAILED_AUTO_DETECTION
);
expect(warningSpy).toHaveBeenCalledWith(
"Region discovery returned an invalid region. Using the global authority.",
correlationId
);
expect(calls).toBe(expectedCalls);
}
);

it("calls the IMDS /compute JSON endpoint and reads the location field", async () => {
let requestedUrl = "";
const networkInterface = buildNetworkInterface((url) => {
Expand Down Expand Up @@ -3285,6 +3336,49 @@ describe("Authority.ts Class Unit Tests", () => {
});

describe("replaceWithRegionalInformation", () => {
it.each([
"",
"example.com\\",
"example.com/",
"example.com@",
"example.com",
"westus%2eexample",
"westus:443",
"westus?query",
"westus#fragment",
"westus\n",
"-westus",
"westus-",
"a".repeat(64),
])("rejects invalid configured region %p", (region) => {
expect(() =>
Authority.replaceWithRegionalInformation(
DEFAULT_OPENID_CONFIG_RESPONSE.body,
region,
TEST_CONFIG.CORRELATION_ID
)
).toThrow(
createClientConfigurationError(
ClientConfigurationErrorCodes.urlParseError,
TEST_CONFIG.CORRELATION_ID
)
);
});

it.each(["westus2", "USGov-Virginia", "a", "a".repeat(63)])(
"accepts a single DNS label as region %p",
(region) => {
const endpoint = Authority.buildRegionalAuthorityString(
"https://login.microsoftonline.com/tenant/oauth2/v2.0/token",
region,
""
);
expect(new URL(endpoint).hostname).toBe(
`${region.toLowerCase()}.login.microsoft.com`
);
}
);

it("replaces authorization_endpoint", () => {
const originResponse: OpenIdConfigResponse = {
...DEFAULT_OPENID_CONFIG_RESPONSE.body,
Expand Down
Loading
Loading