Skip to content

Commit

Permalink
Merge branch 'master' into 1976-chart-unification
Browse files Browse the repository at this point in the history
  • Loading branch information
ciyer authored Aug 19, 2022
2 parents 0996662 + e4b382c commit bd56043
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 51 deletions.
51 changes: 31 additions & 20 deletions server/src/authentication/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { TokenSet } from "openid-client";
import config from "../config";
import logger from "../logger";
import { Authenticator } from "./index";
import { getSessionId } from "./routes";
import { getOrCreateSessionId } from "./routes";


/**
Expand All @@ -37,6 +37,17 @@ function addAuthToken(req: express.Request, accessToken: string) : void {
}


/**
* Add the nonymous header for invoking gateway APIs as an anonymous renku user.
*
* @param req - express response
* @param value - uid for the anonamous user.
*/
function addAnonymousToken(req: express.Request, value: string) : void {
req.headers[config.auth.cookiesAnonymousKey] = value;
}


/**
* Add the invalid credentials header to signal the need to re-authenticate.
*
Expand All @@ -49,29 +60,29 @@ function addAuthInvalid(req: express.Request) : void {

function renkuAuth(authenticator: Authenticator) {
return async (req: express.Request, res: express.Response, next: express.NextFunction): Promise<void> => {
// check session
const sessionId = getSessionId(req);
if (sessionId) {
let tokens: TokenSet;
try {
tokens = await authenticator.getTokens(sessionId, true);
// get or create session
const sessionId = getOrCreateSessionId(req, res);
let tokens: TokenSet;
try {
tokens = await authenticator.getTokens(sessionId, true);
}
catch (error) {
const stringyError = error.toString();
const expired = stringyError.includes("expired") || stringyError.includes("invalid");
if (expired) {
logger.info(`Adding token expirations info for session ${sessionId}`);
addAuthInvalid(req);
}
catch (error) {
const stringyError = error.toString();
const expired = stringyError.includes("expired") || stringyError.includes("invalid");
if (expired) {
logger.info(`Adding token expirations info for session ${sessionId}`);
addAuthInvalid(req);
}
else {
throw error;
}
else {
throw error;
}

if (tokens)
addAuthToken(req, tokens.access_token);
}

if (tokens)
addAuthToken(req, tokens.access_token);
else
addAnonymousToken(req, sessionId);

next();
};
}
Expand Down
25 changes: 7 additions & 18 deletions server/src/authentication/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,36 +35,25 @@ function getOrCreateSessionId(
res: express.Response,
serverPrefix: string = config.server.prefix): string {
const cookiesKey = config.auth.cookiesKey;
let sessionId: string = getSessionId(req);
if (req.cookies[cookiesKey] == null) {
let sessionId: string;
if (req.cookies[cookiesKey] != null) {
sessionId = req.cookies[cookiesKey];
}
else {
sessionId = uuidv4();
res.cookie(cookiesKey, sessionId, { secure: true, httpOnly: true, path: serverPrefix });
}
return sessionId;
}


/**
* Get the session id.
*
* @param req - express request
* @returns session id
*/
function getSessionId(req: express.Request) : string {
const cookiesKey = config.auth.cookiesKey;
if (req.cookies[cookiesKey] == null)
return null;
return req.cookies[cookiesKey];
}


/**
* Extract and return the search string (i.e. the query parameters in the form `?anyvalue`).
*
* @param req - express request containing the url
* @returns search string
*/
function getStringyParams(req: express.Request) : string {
function getStringyParams(req: express.Request): string {
const fullUrl = req.url.toLowerCase().startsWith("http") ?
req.url :
config.server.url + req.url;
Expand Down Expand Up @@ -129,4 +118,4 @@ function registerAuthenticationRoutes(app: express.Application, authenticator: A
}


export { registerAuthenticationRoutes, getSessionId };
export { registerAuthenticationRoutes, getOrCreateSessionId };
12 changes: 8 additions & 4 deletions server/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ const SERVER = {
port: convertType(process.env.SERVER_PORT) || 8080,
prefix: process.env.SERVER_PREFIX || "/ui-server",
logLevel: process.env.SERVER_LOG_LEVEL || "info",
serverUiVersion: process.env.UI_SERVER_VERSION || "unknown"
serverUiVersion: process.env.UI_SERVER_VERSION || "unknown",
proxyTimeout: 600 * 1000 // in milliseconds
};

const DEPLOYMENT = {
Expand All @@ -36,12 +37,12 @@ const DEPLOYMENT = {
};

const SENTRY = {
enabled: [ true, "true" ].includes(process.env.SENTRY_ENABLED),
enabled: [true, "true"].includes(process.env.SENTRY_ENABLED),
url: process.env.SENTRY_URL || undefined,
namespace: process.env.SENTRY_NAMESPACE || undefined,
telepresence: !!process.env.TELEPRESENCE,
sampleRate: parseFloat(process.env.SENTRY_TRACE_RATE) || 0,
debugMode: [ true, "true" ].includes(process.env.SENTRY_DEBUG)
debugMode: [true, "true"].includes(process.env.SENTRY_DEBUG)
};

const AUTHENTICATION = {
Expand All @@ -50,6 +51,8 @@ const AUTHENTICATION = {
clientSecret: process.env.AUTH_CLIENT_SECRET,
tokenExpirationTolerance: convertType(process.env.AUTH_TOKEN_TOLERANCE) || 10,
cookiesKey: "ui-server-session",
cookiesAnonymousKey: "anon-id",
anonPrefix: "anon-", // ? this MUST start with a letter to prevent k8s limitations
authHeaderField: "Authorization",
authHeaderPrefix: "bearer ",
invalidHeaderField: "ui-server-auth",
Expand Down Expand Up @@ -81,6 +84,7 @@ const config = {
redis: REDIS,
routes: ROUTES,
data: DATA,
sentry: SENTRY };
sentry: SENTRY
};

export default config;
23 changes: 14 additions & 9 deletions server/src/routes/apis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import config from "../config";
import logger from "../logger";
import { Authenticator } from "../authentication";
import { CheckURLResponse } from "./apis.interfaces";
import { getCookieValueByName } from "../utils";
import { renkuAuth } from "../authentication/middleware";
import { validateCSP } from "../utils/url";
import { Storage, StorageGetOptions, TypeData } from "../storage";
Expand All @@ -35,8 +34,8 @@ const proxyMiddleware = createProxyMiddleware({
// set gateway as target
target: config.deployment.gatewayUrl,
changeOrigin: true,
proxyTimeout: 600000,
timeout: 600000,
proxyTimeout: config.server.proxyTimeout,
timeout: config.server.proxyTimeout,
pathRewrite: (path): string => {
// remove basic ui-server routing
const rewrittenPath = path.substring((config.server.prefix + config.routes.api).length);
Expand All @@ -45,16 +44,22 @@ const proxyMiddleware = createProxyMiddleware({
},
onProxyReq: (clientReq) => {
// remove unnecessary cookies to avoid gateway conflicts with auth tokens
const cookies = clientReq.getHeader("cookie") as string;
const anonId = getCookieValueByName(cookies, "anon-id");
clientReq.removeHeader("cookie");
if (anonId)
clientReq.setHeader("cookie", `anon-id=${anonId}`);
const cookie = clientReq.getHeader("cookie") as string;
if (cookie)
clientReq.removeHeader("cookie");
// add anon-id to cookies when the proper header is set.
const anonId = clientReq.getHeader(config.auth.cookiesAnonymousKey);
if (anonId) {
// ? the anon-id MUST start with a letter to prevent k8s limitations
const fullAnonId = config.auth.anonPrefix + config.auth.cookiesAnonymousKey;
clientReq.setHeader("cookie", `${config.auth.cookiesAnonymousKey}=${fullAnonId}`);
}
},
onProxyRes: (clientRes, req: express.Request, res: express.Response) => {
// Add CORS for sentry
res.setHeader("Access-Control-Allow-Headers", "sentry-trace");

// handle auth expiration -- we change the response status to avoid browser caching
const expHeader = req.get(config.auth.invalidHeaderField);
if (expHeader != null) {
clientRes.headers[config.auth.invalidHeaderField] = expHeader;
Expand Down Expand Up @@ -133,7 +138,7 @@ function registerApiRoutes(app: express.Application,
const options: StorageGetOptions = {
type: TypeData.Collections,
start: 0,
stop: (parseFloat(req.params["length"]) || 0 ) - 1
stop: (parseFloat(req.params["length"]) || 0) - 1
};

if (userId)
Expand Down

0 comments on commit bd56043

Please sign in to comment.