Skip to content

Commit

Permalink
chore: implement logs behind debug flag
Browse files Browse the repository at this point in the history
  • Loading branch information
matthew2564 committed Oct 18, 2024
1 parent 5fbdc82 commit d4d3b0a
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 21 deletions.
29 changes: 29 additions & 0 deletions src/common/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,32 @@ export const writeLogMessage = (event: APIGatewayTokenAuthorizerEvent, log: ILog
}
return log;
};

export enum LogLevel {
DEBUG = "DEBUG",
INFO = "INFO",
WARN = "WARN",
ERROR = "ERROR",
}

export const envLogger = (level: LogLevel, ...messages: string[]) => {
if (process.env.DEBUG === "true") {
switch (level) {
case LogLevel.DEBUG:
console.debug(messages);
break;
case LogLevel.INFO:
console.info(messages);
break;
case LogLevel.WARN:
console.warn(messages);
break;
case LogLevel.ERROR:
console.error(messages);
break;
default:
console.log(messages);
return;
}
}
};
22 changes: 9 additions & 13 deletions src/functions/authorizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { generatePolicy as generateFunctionalPolicy } from "./functionalPolicyFa
import { getValidJwt } from "../services/tokens";
import { JWT_MESSAGE } from "../models/enums";
import { ILogEvent } from "../models/ILogEvent";
import { writeLogMessage } from "../common/Logger";
import { envLogger, LogLevel, writeLogMessage } from "../common/Logger";
import newPolicyDocument from "./newPolicyDocument";
import { Jwt, JwtPayload } from "jsonwebtoken";

Expand All @@ -20,42 +20,36 @@ import { Jwt, JwtPayload } from "jsonwebtoken";
export const authorizer = async (event: APIGatewayTokenAuthorizerEvent, context: Context): Promise<APIGatewayAuthorizerResult> => {
const logEvent: ILogEvent = {};

console.log("Invoked authoriser");
envLogger(LogLevel.DEBUG, "Invoked authoriser");

if (!process.env.AZURE_TENANT_ID || !process.env.AZURE_CLIENT_ID) {
writeLogMessage(event, logEvent, JWT_MESSAGE.INVALID_ID_SETUP);
console.error("Missing AZURE_TENANT_ID or AZURE_CLIENT_ID");
return unauthorisedPolicy();
}

console.log("AZURE_TENANT_ID and AZURE_CLIENT_ID are set");
envLogger(LogLevel.DEBUG, "AZURE_TENANT_ID and AZURE_CLIENT_ID are set");

try {
console.log("Init log event");

initialiseLogEvent(event);

console.log("Getting valid JWT");
envLogger(LogLevel.INFO, "Getting valid JWT");
const jwt = await getValidJwt(event.authorizationToken, logEvent, process.env.AZURE_TENANT_ID, process.env.AZURE_CLIENT_ID);

console.log("Generating role policy");
envLogger(LogLevel.INFO, "Generating role policy");
const policy = generateRolePolicy(jwt, logEvent) ?? generateFunctionalPolicy(jwt, logEvent);

if (policy !== undefined) {
console.log("Role policy generated");
envLogger(LogLevel.INFO, "Role policy generated");
return policy;
}

console.warn("Reporting no valid roles");
reportNoValidRoles(jwt, event, context, logEvent);
writeLogMessage(event, logEvent, JWT_MESSAGE.INVALID_ROLES);

console.warn("TRY - Returning unauth policy");
return unauthorisedPolicy();
} catch (error: any) {
console.error("Catch - Error occurred", error);
envLogger(LogLevel.ERROR, "Catch - Error occurred", error);
writeLogMessage(event, logEvent, error);
console.error("Catch - Returning unauth policy");
return unauthorisedPolicy();
}
};
Expand Down Expand Up @@ -83,6 +77,8 @@ const reportNoValidRoles = (jwt: Jwt, event: APIGatewayTokenAuthorizerEvent, con
* @param event
*/
const initialiseLogEvent = (event: APIGatewayTokenAuthorizerEvent): ILogEvent => {
envLogger(LogLevel.DEBUG, "Init log event");

return {
requestUrl: event.methodArn,
timeOfRequest: new Date().toISOString(),
Expand Down
12 changes: 7 additions & 5 deletions src/services/azure.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { KeyResponse } from "../models/KeyResponse";
import { envLogger, LogLevel } from "../common/Logger";

const cache: Map<string, Map<string, string>> = new Map();

export const getCertificateChain = async (tenantId: string, keyId: string): Promise<string> => {
const cacheKeys = cache.get(tenantId);

console.log(`Cache ${cacheKeys ? 'hit' : 'not hit'}`);
envLogger(LogLevel.DEBUG, `Cache ${cacheKeys ? "hit" : "not hit"}`);

const keys: Map<string, string> = cacheKeys ?? await getKeys(tenantId);
console.log("Public Keys Read");
const keys: Map<string, string> = cacheKeys ?? (await getKeys(tenantId));

envLogger(LogLevel.DEBUG, "Public keys read");

if (!cache.has(tenantId)) {
cache.set(tenantId, keys);
Expand Down Expand Up @@ -37,11 +39,11 @@ const getKeys = async (tenantId: string): Promise<Map<string, string>> => {
map.set(keyId, certificateChain);
}

console.log("Key Map Created");
envLogger(LogLevel.DEBUG, "Key Map Created");
return map;
};

export const fetchKeys = (tenantId: string) => {
console.log("Fetching keys from https://login.microsoftonline.com/${tenantId}/discovery/keys");
envLogger(LogLevel.DEBUG, `Fetching keys from https://login.microsoftonline.com/${tenantId}/discovery/keys`);
return fetch(`https://login.microsoftonline.com/${tenantId}/discovery/keys`);
};
5 changes: 3 additions & 2 deletions src/services/signature-check.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import * as JWT from "jsonwebtoken";
import { getCertificateChain } from "./azure";
import { envLogger, LogLevel } from "../common/Logger";

export const checkSignature = async (encodedToken: string, decodedToken: JWT.Jwt, tenantId: string, clientId: string): Promise<void> => {
// tid = tenant ID, kid = key ID
console.log("Getting cert chain");
envLogger(LogLevel.DEBUG, "Getting cert chain");
const certificate = await getCertificateChain(tenantId, decodedToken.header.kid as string);

console.log("Verifying token");
envLogger(LogLevel.INFO, "Verifying token");
JWT.verify(encodedToken, certificate, {
audience: clientId.split(","),
issuer: [`https://sts.windows.net/${tenantId}/`, `https://login.microsoftonline.com/${tenantId}/v2.0`],
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/services/azure.unitTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@ describe("getCertificateChain()", () => {
it("should throw an error if no key matches the given key ID", async (): Promise<void> => {
fetchSpy("somethingElse", "mySuperSecurePublicKey");

await expect(azure.getCertificateChain("tenantId", "keyToTheKingdom")).rejects.toThrow("no public key");
await expect(azure.getCertificateChain("tenantId", "otherKeyToTheKingdom")).rejects.toThrow("no public key");
});
});

0 comments on commit d4d3b0a

Please sign in to comment.