diff --git a/.env.template b/.env.template index 137c9d12..7c300da0 100644 --- a/.env.template +++ b/.env.template @@ -1,6 +1,7 @@ # OpenID Connect Configuration for Onboarding API OIDC_ISSUER= OIDC_CLIENT_ID= +OIDC_CLIENT_ID_MCP= OIDC_SCOPES= OIDC_REDIRECT_URI=http://localhost:5173 @@ -15,6 +16,7 @@ API_BACKEND_URL= # Replace this value with a strong, randomly generated string (at least 32 characters). # Example for generation in Node.js: require('crypto').randomBytes(32).toString('hex') COOKIE_SECRET= +SESSION_SECRET= FEEDBACK_SLACK_URL= FEEDBACK_URL_LINK= diff --git a/package-lock.json b/package-lock.json index 63a17bcc..83d945d2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,6 +15,7 @@ "@fastify/http-proxy": "^11.1.2", "@fastify/secure-session": "^8.2.0", "@fastify/sensible": "^6.0.3", + "@fastify/session": "^11.1.0", "@fastify/static": "^8.1.1", "@fastify/vite": "^8.1.3", "@hookform/resolvers": "^5.0.0", @@ -1491,6 +1492,26 @@ "vary": "^1.1.2" } }, + "node_modules/@fastify/session": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/@fastify/session/-/session-11.1.0.tgz", + "integrity": "sha512-OxAX79PtVyTKxfmHT8e0jDFliw/2EmhOxe1Mj35jhL20j8CEpj5Li2zOVi5PqHc5Y+7N2w0tOmtM8mB6NjAIGw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT", + "dependencies": { + "fastify-plugin": "^5.0.1", + "safe-stable-stringify": "^2.4.3" + } + }, "node_modules/@fastify/static": { "version": "8.2.0", "resolved": "https://registry.npmjs.org/@fastify/static/-/static-8.2.0.tgz", @@ -4835,9 +4856,9 @@ } }, "node_modules/bare-module-resolve": { - "version": "1.10.2", - "resolved": "https://registry.npmjs.org/bare-module-resolve/-/bare-module-resolve-1.10.2.tgz", - "integrity": "sha512-C9COe/GhWfVXKytW3DElTkiBU+Gb2OXeaVkdGdRB/lp26TVLESHkTGS876iceAGdvtPgohfp9nX8vXHGvN3++Q==", + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/bare-module-resolve/-/bare-module-resolve-1.11.1.tgz", + "integrity": "sha512-DCxeT9i8sTs3vUMA3w321OX/oXtNEu5EjObQOnTmCdNp5RXHBAvAaBDHvAi9ta0q/948QPz+co6SsGi6aQMYRg==", "license": "Apache-2.0", "dependencies": { "bare-semver": "^1.0.0" diff --git a/package.json b/package.json index 4217a74a..7d63cb5e 100644 --- a/package.json +++ b/package.json @@ -24,8 +24,9 @@ "@fastify/cookie": "^11.0.2", "@fastify/env": "^5.0.2", "@fastify/http-proxy": "^11.1.2", - "@fastify/secure-session": "^8.2.0", "@fastify/sensible": "^6.0.3", + "@fastify/secure-session": "^8.2.0", + "@fastify/session": "^11.1.0", "@fastify/static": "^8.1.1", "@fastify/vite": "^8.1.3", "@hookform/resolvers": "^5.0.0", @@ -83,4 +84,4 @@ "vite": "^6.3.4", "vitest": "^3.1.4" } -} +} \ No newline at end of file diff --git a/public/locales/en.json b/public/locales/en.json index 1000af79..8c396583 100644 --- a/public/locales/en.json +++ b/public/locales/en.json @@ -252,9 +252,6 @@ }, "learnButton": "Learn how to do this in code" }, - "App": { - "loading": "Loading..." - }, "Providers": { "headerProviders": "Providers", "tableHeaderVersion": "Version", diff --git a/server/app.js b/server/app.js index ba1284a0..dcae9811 100644 --- a/server/app.js +++ b/server/app.js @@ -2,14 +2,18 @@ import path, { join, dirname } from "node:path"; import { fileURLToPath } from "node:url"; import AutoLoad from "@fastify/autoload"; import envPlugin from "./config/env.js"; +import encryptedSession from "./encrypted-session.js"; export const options = {}; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); -export default async function(fastify, opts) { +export default async function (fastify, opts) { await fastify.register(envPlugin); + fastify.register(encryptedSession, { + ...opts, + }); await fastify.register(AutoLoad, { dir: join(__dirname, "plugins"), @@ -20,4 +24,6 @@ export default async function(fastify, opts) { dir: join(__dirname, "routes"), options: { ...opts }, }); -} + + +} \ No newline at end of file diff --git a/server/config/env.js b/server/config/env.js index 58d62169..30cdb0f5 100644 --- a/server/config/env.js +++ b/server/config/env.js @@ -1,23 +1,35 @@ -import fastifyPlugin from "fastify-plugin"; -import fastifyEnv from "@fastify/env"; +import fastifyPlugin from 'fastify-plugin'; +import fastifyEnv from '@fastify/env'; const schema = { - type: "object", - required: ["OIDC_ISSUER", "OIDC_CLIENT_ID", "OIDC_REDIRECT_URI", "OIDC_SCOPES", "POST_LOGIN_REDIRECT", "COOKIE_SECRET", "API_BACKEND_URL"], + type: 'object', + required: [ + 'OIDC_ISSUER', + 'OIDC_CLIENT_ID', + 'OIDC_CLIENT_ID_MCP', + 'OIDC_REDIRECT_URI', + 'OIDC_SCOPES', + 'POST_LOGIN_REDIRECT', + 'COOKIE_SECRET', + 'SESSION_SECRET', + 'API_BACKEND_URL', + ], properties: { // Application variables (.env) - OIDC_ISSUER: { type: "string" }, - OIDC_CLIENT_ID: { type: "string" }, - OIDC_REDIRECT_URI: { type: "string" }, - OIDC_SCOPES: { type: "string" }, - POST_LOGIN_REDIRECT: { type: "string" }, - COOKIE_SECRET: { type: "string" }, - API_BACKEND_URL: { type: "string" }, - FEEDBACK_SLACK_URL: { type: "string" }, - FEEDBACK_URL_LINK: { type: "string" }, + OIDC_ISSUER: { type: 'string' }, + OIDC_CLIENT_ID: { type: 'string' }, + OIDC_CLIENT_ID_MCP: { type: 'string' }, + OIDC_REDIRECT_URI: { type: 'string' }, + OIDC_SCOPES: { type: 'string' }, + POST_LOGIN_REDIRECT: { type: 'string' }, + COOKIE_SECRET: { type: 'string' }, + SESSION_SECRET: { type: 'string' }, + API_BACKEND_URL: { type: 'string' }, + FEEDBACK_SLACK_URL: { type: 'string' }, + FEEDBACK_URL_LINK: { type: 'string' }, // System variables - NODE_ENV: { type: "string", enum: ["development", "production"] }, + NODE_ENV: { type: 'string', enum: ['development', 'production'] }, }, }; diff --git a/server/encrypted-session.js b/server/encrypted-session.js new file mode 100644 index 00000000..0da849c4 --- /dev/null +++ b/server/encrypted-session.js @@ -0,0 +1,241 @@ +import secureSession from "@fastify/secure-session"; +import fp from "fastify-plugin"; +import fastifyCookie from "@fastify/cookie"; +import fastifySession from '@fastify/session'; +import crypto from "node:crypto" + + +// name of the request decorator this plugin exposes. Using request.encryptedSession can be used with set, get, clear delete +// functions and the encryption will then be handled in this plugin. +export const REQUEST_DECORATOR = "encryptedSession"; +// name of the request decorator of the secure-session library that stores its session data in an encrypted cookie on user side. +export const ENCRYPTED_COOKIE_REQUEST_DECORATOR = "encryptedSessionInternal"; +// name of the request decorator of the session library that is used as underlying store for this library. +export const UNDERLYING_SESSION_NAME_REQUEST_DECORATOR = "underlyingSessionNotPerUserEncrypted"; + +// name of the secure-session cookie that stores the encryption key on user side. +export const ENCRYPTION_KEY_COOKIE_NAME = "session_encryption_key"; +// the key used to store the encryption key in the secure-session cookie on user side. +export const ENCRYPTED_COOKIE_KEY_ENCRYPTION_KEY = "encryptionKey"; +// name of the cookie that stores the session identifier on user side. +export const SESSION_COOKIE_NAME = "session-cookie"; + +async function encryptedSession(fastify) { + const { COOKIE_SECRET, SESSION_SECRET, NODE_ENV } = fastify.config; + + await fastify.register(fastifyCookie); + + fastify.register(secureSession, { + secret: Buffer.from(COOKIE_SECRET, "hex"), + cookieName: ENCRYPTION_KEY_COOKIE_NAME, + sessionName: ENCRYPTED_COOKIE_REQUEST_DECORATOR, + cookie: { + path: "/", + httpOnly: true, + sameSite: "lax", + secure: NODE_ENV === "production", + maxAge: 60 * 60 * 24 * 7, // 7 days + }, + }); + fastify.register(fastifySession, { + secret: SESSION_SECRET, + cookieName: SESSION_COOKIE_NAME, + // sessionName: UNDERLYING_SESSION_NAME, //NOT POSSIBLE to change the name it is decorated on the request object + cookie: { + path: "/", + httpOnly: true, + sameSite: "lax", + secure: NODE_ENV === "production", + maxAge: 60 * 60 * 24 * 7, // 7 days + }, + }); + + fastify.addHook('onRequest', (request, _reply, next) => { + const userEncryptionKey = getUserEncryptionKeyFromUserCookie(request); + if (!userEncryptionKey) { + request.log.info({ "plugin": "encrypted-session" }, "user-side encryption key not found, creating new one"); + + let newEncryptionKey = generateSecureEncryptionKey(); + setUserEncryptionKeyIntoUserCookie(request, newEncryptionKey); + request[REQUEST_DECORATOR] = createStore() + newEncryptionKey = undefined + } else { + request.log.info({ "plugin": "encrypted-session" }, "user-side encryption key found, using existing one"); + + const loadedEncryptionKey = Buffer.from(userEncryptionKey, "base64"); + + const encryptedStore = request.session.get("encryptedStore"); + if (encryptedStore) { + try { + const { cipherText, iv, tag } = encryptedStore; + + const decryptedCypherText = decryptSymetric(cipherText, iv, tag, loadedEncryptionKey); + const decryptedStore = JSON.parse(decryptedCypherText); + request[REQUEST_DECORATOR] = createStore(decryptedStore); + } catch (error) { + request.log.error({ "plugin": "encrypted-session" }, "Failed to parse encrypted session store", error); + request[REQUEST_DECORATOR] = createStore(); + } + } else { + // we could not parse the encrypted store, so we create a new one and it would overwrite the previously stored store. + request.log.info({ "plugin": "encrypted-session" }, "No encrypted store found, creating new empty store"); + request[REQUEST_DECORATOR] = createStore(); + } + } + + next() + }) + + //TODO maybe move to onResponse after res is send. Lifecycle Doc https://fastify.dev/docs/latest/Reference/Lifecycle/ + // onSend is called before the response is send. Here we take encrypt the Session object and store it in the fastify-session. + // Then we also want to make sure the unencrypted object is removed from memory + fastify.addHook('onSend', async (request, reply, _payload) => { + const encryptionKey = Buffer.from(getUserEncryptionKeyFromUserCookie(request), "base64"); + if (!encryptionKey) { + // if no encryption key is found in the secure session, we cannot encrypt the store. This should not happen since an encrption key is generated when the request arrived + request.log.error({ "plugin": "encrypted-session" }, "No encryption key found in secure session, cannot encrypt store"); + throw new Error("No encryption key found in secure session, cannot encrypt store"); + } + + //we store everything in one value in the session, that might be problematic for future redis with expiration times per key. we might want to split this + const stringifiedData = request[REQUEST_DECORATOR].stringify(); + const { cipherText, iv, tag } = encryptSymetric(stringifiedData, encryptionKey); + + //remove unencrypted data from memory + delete request[REQUEST_DECORATOR]; + request[REQUEST_DECORATOR] = null; + + request.session.set("encryptedStore", { + cipherText, + iv, + tag, + }); + await request.session.save() + request.log.info("store encrypted and set into request.session.encryptedStore"); + }) + + function getUserEncryptionKeyFromUserCookie(request) { + return request[ENCRYPTED_COOKIE_REQUEST_DECORATOR].get(ENCRYPTED_COOKIE_KEY_ENCRYPTION_KEY) + } + + function setUserEncryptionKeyIntoUserCookie(request, key) { + request[ENCRYPTED_COOKIE_REQUEST_DECORATOR].set(ENCRYPTED_COOKIE_KEY_ENCRYPTION_KEY, key.toString('base64')); + } +} + +export default fp(encryptedSession); + +// use a closure to encapsulate the session data so noone can reference it and we are the only ones keeping a reference +function createStore(previousValue) { + let unencryptedStore = {}; // Private variable + if (previousValue) { + unencryptedStore = previousValue; + } + return { + set(key, value) { + unencryptedStore[key] = value; + }, + get(key) { + return unencryptedStore[key]; + }, + delete(key) { + delete unencryptedStore[key]; + }, + stringify() { + return JSON.stringify(unencryptedStore); + }, + clear() { + unencryptedStore = {}; // Clear all data + }, + }; +} + +// generates a secure encryption key for aes-256-gcm. +// Returns a buffer of 32 bytes (256 bits). +function generateSecureEncryptionKey() { + // Generates a secure random encryption key of 32 bytes (256 bits) + return crypto.randomBytes(32); +} + +// uses authenticated symetric encryption (aes-256-gcm) to encrypt the plaintext with the key. +// If no adequate key is given, it throws an error +// The key needs to be 32bytes (256bits) as type buffer. Needs to be cryptographically secure random generated e.g. with `crypto.randomBytes(32)` +// it outputs cipherText (bas64 encoded string), the initialisation vector (iv) (hex string) and the authentication tag (hex string). +function encryptSymetric(plaintext, key) { + if (key == undefined) { + throw new Error("Key must be provided"); + } + if (key.length < 32) { + throw new Error("Key must be at least 32 byte = 256 bits long"); + } + + if (!(key instanceof Buffer)) { + throw new Error("Key must be a Buffer"); + } + + if (plaintext == undefined) { + throw new Error("Plaintext must be provided"); + } + + if (typeof plaintext !== "string") { + throw new Error("Plaintext must be a string utf8 encoded"); + } + + if (!crypto.getCiphers().includes("aes-256-gcm")) { + throw new Error("Cipher suite aes-256-gcm is not available"); + } + + // initialisation vector. Needs to be stored along the cipherText. + // MUST NOT be reused and MUST be randomly generated for EVERY encryption operation. Otherwise using the same key would be insecure. + const iv = crypto.randomBytes(12); + + const cipher = crypto.createCipheriv("aes-256-gcm", key, iv); + let cipherText = cipher.update(plaintext, 'utf8', 'base64'); + cipherText += cipher.final('base64'); + + // the authentication tag is used to verify the integrity of the ciphertext (that it has not been tampered with). + // stored alongside the ciphertext and iv as it can only be changed with the secret key + const tag = cipher.getAuthTag(); + + return { + cipherText, + iv: iv.toString('base64'), + tag: tag.toString('base64'), + } +} + +// uses authenticated symetric encryption (aes-256-gcm) to decrypt the ciphertext with the key. +// requires the ciphertext, the initialisation vector (iv)(hex string), the authentication tag (tag) (hex string) and the key (buffer) to be provided. +//it thows an error if the decryption or tag verification fails +function decryptSymetric(cipherText, iv, tag, key) { + if (key == undefined) { + throw new Error("Key must be provided"); + } + if (key.length < 32) { + throw new Error("Key must be at least 32 byte = 256 bits long"); + } + + if (!(key instanceof Buffer)) { + throw new Error("Key must be a Buffer"); + } + + if (cipherText == undefined) { + throw new Error("Ciphertext must be provided"); + } + + if (typeof cipherText !== "string") { + throw new Error("Ciphertext must be a string utf8 encoded"); + } + + if (!crypto.getCiphers().includes("aes-256-gcm")) { + throw new Error("Cipher suite aes-256-gcm is not available"); + } + + const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(iv, 'base64')); + decipher.setAuthTag(Buffer.from(tag, 'base64')); + + let decrypted = decipher.update(cipherText, 'base64', 'utf8'); + decrypted += decipher.final('utf8'); + + return decrypted; +} \ No newline at end of file diff --git a/server/plugins/auth-utils.js b/server/plugins/auth-utils.js index a90689ad..78b6e58b 100644 --- a/server/plugins/auth-utils.js +++ b/server/plugins/auth-utils.js @@ -20,6 +20,12 @@ async function getRemoteOpenIdConfiguration(issuerBaseUrl) { return res.json(); } +function isAllowedRedirectTo(value) { + if (!value) return true; + const first = value.charAt(0); + return first === "/" || first === "#"; +} + async function authUtilsPlugin(fastify) { fastify.decorate("discoverIssuerConfiguration", async (issuerBaseUrl) => { @@ -76,18 +82,25 @@ async function authUtilsPlugin(fastify) { fastify.decorate("prepareOidcLoginRedirect", (request, oidcConfig, authorizationEndpoint) => { request.log.info("Preparing OIDC login redirect."); + const { redirectTo } = request.query; + if (!isAllowedRedirectTo(redirectTo)) { + request.log.error(`Invalid redirectTo: "${redirectTo}".`); + throw new AuthenticationError("Invalid redirectTo."); + } + request.encryptedSession.set("postLoginRedirectRoute", redirectTo); + const { clientId, redirectUri, scopes } = oidcConfig; const state = crypto.randomBytes(16).toString("hex"); const codeVerifier = crypto.randomBytes(32).toString("base64url"); const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url"); - request.session.set("oauthState", state); - request.session.set("codeVerifier", codeVerifier); + request.encryptedSession.set("oauthState", state); + request.encryptedSession.set("codeVerifier", codeVerifier); request.log.info({ stateSet: Boolean(state), verifierSet: Boolean(codeVerifier), - }, "OAuth state and code verifier set in session."); + }, "OAuth state and code verifier set in encryptedSession."); const url = new URL(authorizationEndpoint); url.searchParams.set("response_type", "code"); @@ -113,7 +126,7 @@ async function authUtilsPlugin(fastify) { request.log.error("Missing authorization code in callback."); throw new AuthenticationError("Missing code in callback."); } - if (state !== request.session.get("oauthState")) { + if (state !== request.encryptedSession.get("oauthState")) { request.log.error("Invalid state in callback."); throw new AuthenticationError("Invalid state in callback."); } @@ -123,7 +136,7 @@ async function authUtilsPlugin(fastify) { code, redirect_uri: redirectUri, client_id: clientId, - code_verifier: request.session.get("codeVerifier"), + code_verifier: request.encryptedSession.get("codeVerifier"), }); const response = await fetch(tokenEndpoint, { @@ -143,6 +156,7 @@ async function authUtilsPlugin(fastify) { refreshToken: tokens.refresh_token, expiresAt: null, userInfo: extractUserInfoFromIdToken(request, tokens.id_token), + postLoginRedirectRoute: request.encryptedSession.get("postLoginRedirectRoute") || "", }; if (tokens.expires_in && typeof tokens.expires_in === "number") { diff --git a/server/plugins/http-proxy.js b/server/plugins/http-proxy.js index d793131f..e0700a0e 100644 --- a/server/plugins/http-proxy.js +++ b/server/plugins/http-proxy.js @@ -1,6 +1,5 @@ import fp from "fastify-plugin"; import httpProxy from "@fastify/http-proxy"; -import { COOKIE_NAME_ONBOARDING } from "./secure-session.js"; import { AuthenticationError } from "./auth-utils.js"; function proxyPlugin(fastify) { @@ -13,18 +12,24 @@ function proxyPlugin(fastify) { preHandler: async (request, reply) => { request.log.info("Entering HTTP proxy preHandler."); + const useCrate = request.headers["x-use-crate"]; + + const keyAccessToken = useCrate ? "onboarding_accessToken" : "mcp_accessToken"; + const keyTokenExpiresAt = useCrate ? "onboarding_tokenExpiresAt" : "mcp_tokenExpiresAt"; + const keyRefreshToken = useCrate ? "onboarding_refreshToken" : "mcp_refreshToken"; + // Check if there is an access token - const accessToken = request.session.get("accessToken"); + const accessToken = request.encryptedSession.get(keyAccessToken); if (!accessToken) { request.log.error("Missing access token."); return reply.unauthorized("Missing access token."); } // Check if the access token is expired or about to expire - const expiresAt = request.session.get("tokenExpiresAt"); + const expiresAt = request.encryptedSession.get(keyTokenExpiresAt); const now = Date.now(); - const REFRESH_BUFFER_SECONDS = 20; // to allow for network latency - if (!expiresAt || now < expiresAt - REFRESH_BUFFER_SECONDS) { + const REFRESH_BUFFER_MILLISECONDS = 20 * 1000; // to allow for network latency + if (!expiresAt || now < expiresAt - REFRESH_BUFFER_MILLISECONDS) { request.log.info("Access token is still valid; no refresh needed."); return; } @@ -32,11 +37,10 @@ function proxyPlugin(fastify) { request.log.info({ expiresAt: new Date(expiresAt).toISOString() }, "Access token is expired or about to expire; attempting refresh."); // Check if there is a refresh token - const refreshToken = request.session.get("refreshToken"); + const refreshToken = request.encryptedSession.get(keyRefreshToken); if (!refreshToken) { - request.log.error("Missing refresh token; deleting session."); - request.session.delete(); - reply.clearCookie(COOKIE_NAME_ONBOARDING, { path: "/" }); + request.log.error("Missing refresh token; deleting encryptedSession."); + request.encryptedSession.clear();//TODO: also clear user encrpytion key? return reply.unauthorized("Session expired without token refresh capability."); } @@ -50,24 +54,23 @@ function proxyPlugin(fastify) { }, issuerConfiguration.tokenEndpoint); if (!refreshedTokenData || !refreshedTokenData.accessToken) { request.log.error("Token refresh failed (no access token); deleting session."); - request.session.delete(); - reply.clearCookie(COOKIE_NAME_ONBOARDING, { path: "/" }); + request.encryptedSession.clear();//TODO: also clear user encrpytion key? return reply.unauthorized("Session expired and token refresh failed."); } request.log.info("Token refresh successful; updating the session."); - request.session.set("accessToken", refreshedTokenData.accessToken); + request.encryptedSession.set(keyAccessToken, refreshedTokenData.accessToken); if (refreshedTokenData.refreshToken) { - request.session.set("refreshToken", refreshedTokenData.refreshToken); + request.encryptedSession.set(keyRefreshToken, refreshedTokenData.refreshToken); } else { - request.session.delete("refreshToken"); + request.encryptedSession.delete(keyRefreshToken); } if (refreshedTokenData.expiresIn) { const newExpiresAt = Date.now() + (refreshedTokenData.expiresIn * 1000); - request.session.set("tokenExpiresAt", newExpiresAt); + request.encryptedSession.set(keyTokenExpiresAt, newExpiresAt); } else { - request.session.delete("tokenExpiresAt"); + request.encryptedSession.delete(keyTokenExpiresAt); } request.log.info("Token refresh successful and session updated; continuing with the HTTP request."); @@ -81,10 +84,15 @@ function proxyPlugin(fastify) { } }, replyOptions: { - rewriteRequestHeaders: (req, headers) => ({ - ...headers, - authorization: req.session.get("accessToken") - }), + rewriteRequestHeaders: (req, headers) => { + const useCrate = req.headers["x-use-crate"]; + const accessToken = useCrate ? req.encryptedSession.get("onboarding_accessToken") : `${req.encryptedSession.get("onboarding_accessToken")},${req.encryptedSession.get("mcp_accessToken")}`; + + return { + ...headers, + authorization: accessToken, + } + }, }, }); } diff --git a/server/plugins/secure-session.js b/server/plugins/secure-session.js deleted file mode 100644 index d9191408..00000000 --- a/server/plugins/secure-session.js +++ /dev/null @@ -1,26 +0,0 @@ -import secureSession from "@fastify/secure-session"; -import fp from "fastify-plugin"; -import fastifyCookie from "@fastify/cookie"; - - -export const COOKIE_NAME_ONBOARDING = "onboarding"; - -async function secureSessionPlugin(fastify) { - const { COOKIE_SECRET, NODE_ENV } = fastify.config; - - await fastify.register(fastifyCookie); - - fastify.register(secureSession, { - secret: Buffer.from(COOKIE_SECRET, "hex"), - cookieName: COOKIE_NAME_ONBOARDING, - cookie: { - path: "/", - httpOnly: true, - sameSite: "lax", - secure: NODE_ENV === "production", - maxAge: 60 * 60 * 24 * 7, // 7 days - }, - }); -} - -export default fp(secureSessionPlugin); diff --git a/server/routes/auth-mcp.js b/server/routes/auth-mcp.js new file mode 100644 index 00000000..67809cc3 --- /dev/null +++ b/server/routes/auth-mcp.js @@ -0,0 +1,58 @@ +import fp from "fastify-plugin"; +import { AuthenticationError } from "../plugins/auth-utils.js"; + + +async function authPlugin(fastify) { + const { OIDC_ISSUER, OIDC_CLIENT_ID_MCP, OIDC_REDIRECT_URI, OIDC_SCOPES, POST_LOGIN_REDIRECT } = fastify.config; + + // Make MCP issuer configuration globally available + // TODO: This is a temporary solution until we have a proper way to manage multiple issuers + const mcpIssuerConfiguration = await fastify.discoverIssuerConfiguration(OIDC_ISSUER); + fastify.decorate("mcpIssuerConfiguration", mcpIssuerConfiguration); + + fastify.get("/auth/mcp/login", async (req, reply) => { + const redirectUri = fastify.prepareOidcLoginRedirect(req, { + clientId: OIDC_CLIENT_ID_MCP, + redirectUri: OIDC_REDIRECT_URI, + scopes: OIDC_SCOPES, + }, mcpIssuerConfiguration.authorizationEndpoint); + + reply.redirect(redirectUri); + }); + + fastify.get("/auth/mcp/callback", async (req, reply) => { + try { + const callbackResult = await fastify.handleOidcCallback(req, { + clientId: OIDC_CLIENT_ID_MCP, + redirectUri: OIDC_REDIRECT_URI, + }, mcpIssuerConfiguration.tokenEndpoint); + + req.encryptedSession.set("mcp_accessToken", callbackResult.accessToken); + req.encryptedSession.set("mcp_refreshToken", callbackResult.refreshToken); + + if (callbackResult.expiresAt) { + req.encryptedSession.set("mcp_tokenExpiresAt", callbackResult.expiresAt); + } else { + req.encryptedSession.delete("mcp_tokenExpiresAt"); + } + + reply.redirect(POST_LOGIN_REDIRECT + callbackResult.postLoginRedirectRoute); + } catch (error) { + if (error instanceof AuthenticationError) { + req.log.error("AuthenticationError during OIDC callback: %s", error); + return reply.serviceUnavailable("Error during OIDC callback."); + } else { + throw error; + } + } + }); + + fastify.get("/auth/mcp/me", async (req, reply) => { + const accessToken = req.encryptedSession.get("mcp_accessToken"); + + const isAuthenticated = Boolean(accessToken); + reply.send({ isAuthenticated }); + }); +} + +export default fp(authPlugin); diff --git a/server/routes/auth.js b/server/routes/auth-onboarding.js similarity index 62% rename from server/routes/auth.js rename to server/routes/auth-onboarding.js index 2bfcfcef..378574ae 100644 --- a/server/routes/auth.js +++ b/server/routes/auth-onboarding.js @@ -1,5 +1,4 @@ import fp from "fastify-plugin"; -import { COOKIE_NAME_ONBOARDING } from "../plugins/secure-session.js"; import { AuthenticationError } from "../plugins/auth-utils.js"; @@ -12,7 +11,7 @@ async function authPlugin(fastify) { fastify.decorate("issuerConfiguration", issuerConfiguration); - fastify.get("/auth/login", async (req, reply) => { + fastify.get("/auth/onboarding/login", async (req, reply) => { const redirectUri = fastify.prepareOidcLoginRedirect(req, { clientId: OIDC_CLIENT_ID, redirectUri: OIDC_REDIRECT_URI, @@ -23,22 +22,24 @@ async function authPlugin(fastify) { }); - fastify.get("/auth/callback", async (req, reply) => { + fastify.get("/auth/onboarding/callback", async (req, reply) => { try { const callbackResult = await fastify.handleOidcCallback(req, { clientId: OIDC_CLIENT_ID, redirectUri: OIDC_REDIRECT_URI, }, issuerConfiguration.tokenEndpoint); - req.session.set("accessToken", callbackResult.accessToken); - req.session.set("refreshToken", callbackResult.refreshToken); - req.session.set("userInfo", callbackResult.userInfo); + req.encryptedSession.set("onboarding_accessToken", callbackResult.accessToken); + req.encryptedSession.set("onboarding_refreshToken", callbackResult.refreshToken); + req.encryptedSession.set("onboarding_userInfo", callbackResult.userInfo); if (callbackResult.expiresAt) { - req.session.set("tokenExpiresAt", callbackResult.expiresAt); + req.encryptedSession.set("onboarding_tokenExpiresAt", callbackResult.expiresAt); } else { - req.session.delete("tokenExpiresAt"); + req.encryptedSession.delete("onboarding_tokenExpiresAt"); } + + reply.redirect(POST_LOGIN_REDIRECT + callbackResult.postLoginRedirectRoute); } catch (error) { if (error instanceof AuthenticationError) { req.log.error("AuthenticationError during OIDC callback: %s", error); @@ -47,25 +48,21 @@ async function authPlugin(fastify) { throw error; } } - - reply.redirect(POST_LOGIN_REDIRECT); }); - fastify.get("/auth/me", async (req, reply) => { - const accessToken = req.session.get("accessToken"); - const userInfo = req.session.get("userInfo"); + fastify.get("/auth/onboarding/me", async (req, reply) => { + const accessToken = req.encryptedSession.get("onboarding_accessToken"); + const userInfo = req.encryptedSession.get("onboarding_userInfo"); const isAuthenticated = Boolean(accessToken); const user = isAuthenticated ? userInfo : null; reply.send({ isAuthenticated, user }); }); - - fastify.post("/auth/logout", async (_req, reply) => { + fastify.post("/auth/logout", async (req, reply) => { // TODO: Idp sign out flow - //_req.session.delete(); // remove payload - reply.clearCookie(COOKIE_NAME_ONBOARDING, { path: "/" }); + req.encryptedSession.clear(); reply.send({ message: "Logged out" }); }); } diff --git a/src/App.tsx b/src/App.tsx index 06e8f725..8bdcca23 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,14 +1,13 @@ import AppRouter from './AppRouter'; -import { useAuth } from './spaces/onboarding/auth/AuthContext.tsx'; +import { useAuthOnboarding } from './spaces/onboarding/auth/AuthContextOnboarding.tsx'; import '@ui5/webcomponents-icons/dist/AllIcons.d.ts'; import { useEffect } from 'react'; import { useFrontendConfig } from './context/FrontendConfigContext.tsx'; -import { useTranslation } from 'react-i18next'; import LoginView from './views/Login.tsx'; +import { BusyIndicator } from '@ui5/webcomponents-react'; function App() { - const auth = useAuth(); - const { t } = useTranslation(); + const auth = useAuthOnboarding(); const frontendConfig = useFrontendConfig(); useEffect(() => { @@ -18,7 +17,7 @@ function App() { }, []); if (auth.isLoading) { - return