Skip to content

Commit

Permalink
Refactor caching of obo tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
johannbm committed Sep 4, 2023
1 parent 63ea2dc commit fc6d16a
Show file tree
Hide file tree
Showing 7 changed files with 115 additions and 53 deletions.
35 changes: 34 additions & 1 deletion apps/frackend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions apps/frackend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,16 @@
"cookie-parser": "1.4.6",
"express": "4.18.2",
"express-jwt": "8.4.1",
"express-session": "1.17.3",
"http-proxy-middleware": "3.0.0-beta.0",
"jwks-rsa": "3.0.1",
"morgan": "1.10.0",
"node-cache": "5.1.2",
"node-jose": "2.2.0",
"uuid": "9.0.0"
},
"devDependencies": {
"@types/cookie-parser": "1.4.3",
"@types/express": "4.17.17",
"@types/express-session": "1.17.7",
"@types/node": "20.5.7",
"@types/node-jose": "1.1.10",
"@types/uuid": "9.0.2",
Expand Down
6 changes: 3 additions & 3 deletions apps/frackend/src/apiProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createProxyMiddleware } from "http-proxy-middleware";

import config from "./config.js";
import { addOnBehalfOfToken } from "./onbehalfof.js";
import { getOboTokenForRequest } from "./sessionCache";
import { verifyJWTToken } from "./tokenValidation.js";

function setupProxy(
Expand All @@ -22,9 +23,8 @@ function setupProxy(
logger: console,
on: {
proxyReq: (proxyRequest, request) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const accessToken = request?.session[scope]?.accessToken;
const accessToken = getOboTokenForRequest(request, scope)
?.accessToken;
if (accessToken) {
proxyRequest.setHeader("Authorization", `Bearer ${accessToken}`);
} else {
Expand Down
12 changes: 7 additions & 5 deletions apps/frackend/src/onbehalfof.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import jose from "node-jose";
import { v4 as uuidv4 } from "uuid";

import config from "./config.js";
import { getOboTokenForRequest, setOboTokenForRequest } from "./sessionCache";
import { getTokenFromRequestHeader } from "./tokenValidation.js";

const azureAdHeaderConfig = {
Expand All @@ -24,12 +25,12 @@ export async function addOnBehalfOfToken(
next: NextFunction,
scope: string,
) {
const currentSession = request.session[scope];
if (currentSession) {
if (currentSession.expiresAt > Date.now() / 1000 + 10) {
const currentOboToken = getOboTokenForRequest(request, scope);
if (currentOboToken) {
if (currentOboToken.expiresAt > Date.now() / 1000 + 10) {
return next();
}
const token = await getRefreshToken(currentSession.refreshToken, scope);
const token = await getRefreshToken(currentOboToken.refreshToken, scope);
updateSession(request, scope, token);
return next();
}
Expand All @@ -53,11 +54,12 @@ const updateSession = (
scope: string,
result: OnBehalfOfResponse,
) => {
request.session[scope] = {
const oboToken = {
expiresAt: Date.now() / 1000 + result.expires_in,
accessToken: result.access_token,
refreshToken: result.refresh_token,
};
setOboTokenForRequest(request, oboToken, scope);
};

async function getOnBehalfOfToken(request: Request, scope: string) {
Expand Down
6 changes: 4 additions & 2 deletions apps/frackend/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import cookieParser from "cookie-parser";
import express from "express";

import { setupActuators } from "./actuators.js";
import { setupNomApiProxy, setupTeamcatApiProxy } from "./apiProxy.js";
import { setupStaticRoutes } from "./frontendRoute.js";
import { setupSession } from "./session.js";

// Create Express Server
const app = express();
Expand All @@ -12,7 +12,9 @@ const app = express();
app.use(express.urlencoded({ extended: true }));

setupActuators(app);
setupSession(app);

app.set("trust proxy", 1);
app.use(cookieParser());

setupNomApiProxy(app);
setupTeamcatApiProxy(app);
Expand Down
40 changes: 0 additions & 40 deletions apps/frackend/src/session.ts

This file was deleted.

66 changes: 66 additions & 0 deletions apps/frackend/src/sessionCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import * as crypto from "node:crypto";
import { IncomingMessage } from "node:http";

import NodeCache from "node-cache";

export const sessionCache = new NodeCache({
stdTTL: 60 * 60, // 1 hour
});

type SessionCacheValue = {
[scope: string]: OboToken;
};

type OboToken = {
expiresAt: number;
accessToken: string;
refreshToken: string;
};

export function setOboTokenForRequest(
request: IncomingMessage,
oboToken: OboToken,
scope: string,
) {
const hashedAuthHeader = getHashedAuthHeader(request);

if (!hashedAuthHeader) {
return;
}

const cachedValue = sessionCache.get<SessionCacheValue>(hashedAuthHeader);

if (!cachedValue) {
return;
}

cachedValue[scope] = oboToken;

sessionCache.set<SessionCacheValue>(hashedAuthHeader, cachedValue);
}

export function getOboTokenForRequest(request: IncomingMessage, scope: string) {
const hashedAuthHeader = getHashedAuthHeader(request);

if (!hashedAuthHeader) {
return;
}

const cachedValue = sessionCache.get<SessionCacheValue>(hashedAuthHeader);

if (!cachedValue) {
return;
}

return cachedValue[scope];
}

function getHashedAuthHeader(request: IncomingMessage) {
const authToken = request.headers["authorization"];

if (!authToken) {
return;
}

return crypto.createHash("md5").update(authToken).digest("hex");
}

0 comments on commit fc6d16a

Please sign in to comment.