Skip to content

Commit

Permalink
debug tests
Browse files Browse the repository at this point in the history
  • Loading branch information
KarishmaGhiya committed Aug 6, 2021
1 parent d5bcd10 commit 6baa62a
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 87 deletions.
2 changes: 1 addition & 1 deletion sdk/identity/identity/test/authTestUtils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

import { assert } from "chai";
import assert from "assert";
import { AuthenticationError } from "../src";
import { DefaultAuthorityHost } from "../src/constants";

Expand Down
153 changes: 79 additions & 74 deletions sdk/identity/identity/test/internal/node/applicationCredential.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,122 +2,127 @@
// Licensed under the MIT license.

import assert from "assert";
import { RestError } from "@azure/core-http";
import { AuthenticationError, ApplicationCredential } from "../../../src";
import { MockAuthHttpClient, assertRejects } from "../../authTestUtils";
import { OAuthErrorResponse } from "../../../src/client/errors";
import Sinon from "sinon";
import { RestError } from "@azure/core-rest-pipeline";
import { ApplicationCredential } from "../../../src";
import { prepareIdentityTests } from "../../httpRequests";
import {
createResponse,
IdentityTestContext,
SendCredentialRequests
} from "../../httpRequestsCommon";

describe.skip("ApplicationCredential (internal)", function() {
// interface AuthRequestDetails {
// requests: WebResource[];
// token: AccessToken | null;
// }

describe("ApplicationCredential (internal)", function() {
let envCopy: string = "";
let sandbox: Sinon.SinonSandbox;
let testContext: IdentityTestContext;
let sendCredentialRequests: SendCredentialRequests;

beforeEach(() => {
beforeEach(async () => {
envCopy = JSON.stringify(process.env);
delete process.env.MSI_ENDPOINT;
delete process.env.MSI_SECRET;
sandbox = Sinon.createSandbox();
testContext = await prepareIdentityTests({});
sendCredentialRequests = testContext.sendCredentialRequests;
});
afterEach(() => {
afterEach(async () => {
const env = JSON.parse(envCopy);
process.env.MSI_ENDPOINT = env.MSI_ENDPOINT;
process.env.MSI_SECRET = env.MSI_SECRET;
sandbox.restore();
await testContext.restore();
});

it("returns error when no MSI is available", async function() {
process.env.AZURE_CLIENT_ID = "errclient";

const imdsError: RestError = new RestError("Request Timeout", "REQUEST_SEND_ERROR", 408);
const mockHttpClient = new MockAuthHttpClient({
authResponse: [{ error: imdsError }]
});

const credential = new ApplicationCredential({
...mockHttpClient.tokenCredentialOptions
const { error } = await sendCredentialRequests({
scopes: ["scopes"],
credential: new ApplicationCredential(),
insecureResponses: [
{
error: new RestError("Request Timeout", { code: "REQUEST_SEND_ERROR", statusCode: 408 })
}
]
});
await assertRejects(
credential.getToken("scopes"),
(error: AuthenticationError) => error.message.indexOf("No MSI credential available") > -1
assert.ok(
error!.message!.indexOf("No MSI credential available") > -1,
"Failed to match the expected error"
);
});

it("an unexpected error bubbles all the way up", async function() {
process.env.AZURE_CLIENT_ID = "errclient";

const errResponse: OAuthErrorResponse = {
error: "ApplicationCredential authentication failed.",
error_description: ""
};
const errorMessage = "ManagedIdentityCredential authentication failed.";

const mockHttpClient = new MockAuthHttpClient({
authResponse: [{ status: 200 }, { status: 500, parsedBody: errResponse }]
const { error } = await sendCredentialRequests({
scopes: ["scopes"],
credential: new ApplicationCredential(),
insecureResponses: [
createResponse(200), // IMDS Endpoint ping
{ error: new RestError(errorMessage, { statusCode: 500 }) }
]
});

const credential = new ApplicationCredential({
...mockHttpClient.tokenCredentialOptions
});
await assertRejects(
credential.getToken("scopes"),
(error: AuthenticationError) => error.message.indexOf(errResponse.error) > -1
);
assert.ok(error?.message.startsWith(errorMessage));
});

it("returns expected error when the network was unreachable", async function() {
process.env.AZURE_CLIENT_ID = "errclient";

const netError: RestError = new RestError("Request Timeout", "ENETUNREACH", 408);
const mockHttpClient = new MockAuthHttpClient({
authResponse: [{ status: 200 }, { error: netError }]
const netError: RestError = new RestError("Request Timeout", {
code: "ENETUNREACH",
statusCode: 408
});
console.dir(mockHttpClient.tokenCredentialOptions);
const credential = new ApplicationCredential({
...mockHttpClient.tokenCredentialOptions

const { error } = await sendCredentialRequests({
scopes: ["scopes"],
credential: new ApplicationCredential(),
insecureResponses: [
createResponse(200), // IMDS Endpoint ping
{ error: netError }
]
});
await assertRejects(
credential.getToken("scopes"),
(error: AuthenticationError) => error.message.indexOf("Network unreachable.") > -1
);
assert.ok(error!.message!.indexOf("Network unreachable.") > -1);
});

it("sends an authorization request correctly in an App Service environment", async () => {
// Trigger App Service behavior by setting environment variables
process.env.MSI_ENDPOINT = "https://endpoint";
process.env.MSI_SECRET = "secret";

const mockHttpClient = new MockAuthHttpClient({
authResponse: {
status: 200,
parsedBody: {
token: "token",
const authDetails = await sendCredentialRequests({
scopes: ["https://service/.default"],
credential: new ApplicationCredential(),
secureResponses: [
createResponse(200, {
access_token: "token",
expires_on: "06/20/2019 02:57:58 +00:00"
}
}
})
]
});
const credential = new ApplicationCredential({ ...mockHttpClient.tokenCredentialOptions });
const token = await credential.getToken(["https://service/.default"]);
const authDetails = { token, requests: mockHttpClient.requests };

const authRequest = authDetails.requests[0];
assert.ok(authRequest.query, "No query string parameters on request");
if (authRequest.query) {
assert.equal(authRequest.method, "GET");
assert.equal(authRequest.query["clientid"], "client");
assert.equal(decodeURIComponent(authRequest.query["resource"]), "https://service");
assert.ok(
authRequest.url.startsWith(process.env.MSI_ENDPOINT),
"URL does not start with expected host and path"
);
assert.equal(authRequest.headers.get("secret"), process.env.MSI_SECRET);
assert.ok(
authRequest.url.indexOf(`api-version=2017-09-01`) > -1,
"URL does not have expected version"
);
if (authDetails.token) {
assert.equal(authDetails.token.expiresOnTimestamp, 1560999478000);
} else {
assert.fail("No token was returned!");
}
const query = new URLSearchParams(authRequest.url.split("?")[1]);

assert.equal(authRequest.method, "GET");
assert.equal(query.get("clientid"), "client");
assert.equal(decodeURIComponent(query.get("resource")!), "https://service");
assert.ok(
authRequest.url.startsWith(process.env.MSI_ENDPOINT),
"URL does not start with expected host and path"
);
assert.equal(authRequest.headers.secret, process.env.MSI_SECRET);
assert.ok(
authRequest.url.indexOf(`api-version=2017-09-01`) > -1,
"URL does not have expected version"
);
if (authDetails.result?.token) {
assert.equal(authDetails.result.expiresOnTimestamp, 1560999478000);
} else {
assert.fail("No token was returned!");
}
});
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

import { assert } from "chai";
import assert from "assert";
import { join } from "path";
import { tmpdir } from "os";
import { mkdtempSync, rmdirSync, unlinkSync, writeFileSync } from "fs";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,9 @@
/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */

import assert from "assert";
import {
AuthenticationError,
CredentialUnavailableError,
ApplicationCredential
} from "../../../src";
import { CredentialUnavailableError, ApplicationCredential } from "../../../src";
import { MsalTestCleanup, msalNodeTestSetup, testTracing } from "../../msalTestUtils";
import { assertRejects } from "../../authTestUtils";
import { getError } from "../../authTestUtils";
import { Context } from "mocha";

describe("ApplicationCredential", function() {
Expand Down Expand Up @@ -102,10 +98,8 @@ describe("ApplicationCredential", function() {

const credential = new ApplicationCredential();

await assertRejects(
credential.getToken(scope),
(error: AuthenticationError) =>
error.errorResponse.error.indexOf("EnvironmentCredential authentication failed.") > -1
);
const error = await getError(credential.getToken(scope));
assert.equal(error.name, "AuthenticationError");
assert.ok(error.message.indexOf("EnvironmentCredential authentication failed.") > -1);
});
});

0 comments on commit 6baa62a

Please sign in to comment.