Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Add optional trusted OIDC portal entry (#1163)

Regan Belle4b35024d5d7
diff --git a/plugins/portal/README.md b/plugins/portal/README.md
index 2a10fb838..e22e0148f 100644
--- a/plugins/portal/README.md
+++ b/plugins/portal/README.md
@@ -32,6 +32,25 @@ surfaces, and it does **not** import the core.
synthesizing the surface cookie for compatibility and attaching a short-lived signed portal
identity. Surfaces pass that identity to core, which verifies it before any user-scoped action.
+## Additional trusted entry (PoC)
+
+An optional OIDC entry route at `/auth/trusted/login` operates alongside the
+existing `/auth/login` provider. Configure `PORTAL_TRUSTED_OIDC` as JSON with
+`issuer`, `authEndpoint`, `tokenEndpoint`, `userinfoEndpoint`, `jwksUri`, and
+`clientId`; supply its distinct `PORTAL_TRUSTED_OIDC_CLIENT_SECRET` separately.
+Register the exact `${PORTAL_PUBLIC_URL}/auth/trusted/callback` URL at that provider.
+Endpoints must use HTTPS in production. This is an operator-configured trust
+relationship: the additional provider must enforce the destination company's
+admission policy before issuing tokens. Primary-provider email and workspace
+restrictions do not apply to this separate route.
+
+The route verifies OIDC signature, issuer, audience, nonce, PKCE and subject binding,
+and consumes login state through core's durable replay store. Principals are scoped
+to the issuer and subject, without automatic linking to email or Slack identities.
+No administrator role is assigned. Company login and Slack integration retain their
+existing configuration. Deployment CLI secret wiring, account linking, and live
+qualification are pending; this is not a released deployment feature.
+
## Operator admin login without email
Run `qm admin-login` with the deployment's configuration and secrets to generate
diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.ts
index 152a395a2..0d59cfe1a 100644
--- a/plugins/portal/src/index.ts
+++ b/plugins/portal/src/index.ts
@@ -2,6 +2,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:ht
import { pathToFileURL } from "node:url";
import { ADMIN_LOGIN_SCRIPT, ADMIN_LOGIN_SCRIPT_HASH, openAdminLogin } from "./admin-login.ts";
import { LRUCache } from "lru-cache";
+import { createTrustedEntry, trustedEntryConfig } from "./trusted-entry.ts";
import {
deriveKey,
seal,
@@ -203,6 +204,12 @@ const DEV_SECRET = "dev-only-insecure-portal-session-secret";
const sessionKey = deriveKey(SESSION_SECRET ?? DEV_SECRET, "portal.session.v1");
const tmpKey = deriveKey(SESSION_SECRET ?? DEV_SECRET, "portal.tmp.v1");
const impersonateKey = deriveKey(SESSION_SECRET ?? DEV_SECRET, "portal.impersonate.v1");
+const trustedOidc = trustedEntryConfig(process.env, PUBLIC_URL);
+const trustedEntry = trustedOidc
+ ? createTrustedEntry(trustedOidc, SESSION_SECRET ?? DEV_SECRET, (key, expiresAt) =>
+ claimOnce(coreClaimStore(CORE, CORE_SIGNING_SECRET, "portal"), key, expiresAt),
+ )
+ : null;
const IMPERSONATE_TTL_S = Number(process.env.PORTAL_IMPERSONATE_TTL_S ?? 3600);
const TMP_TTL_S = 600;
@@ -491,7 +498,10 @@ ${CARD_STYLE}
</html>`;
}
-export function signInErrorHtml(detail: string): string {
+export function signInErrorHtml(
+ detail: string,
+ retryPath: "/auth/login" | "/auth/trusted/login" = "/auth/login",
+): string {
return cardPage({
title: "Sign-in failed",
heading: "We couldn't sign you in",
@@ -499,9 +509,9 @@ export function signInErrorHtml(detail: string): string {
icon: ALERT_ICON,
warn: true,
extra: `<p class="reason"><strong>Details</strong>${escapeHtml(detail)}</p>`,
- actions: `<a class="btn primary" href="/auth/login">Try signing in again</a>
+ actions: `<a class="btn primary" href="${retryPath}">Try signing in again</a>
<a class="btn ghost" href="/">Back to start</a>`,
- help: "Still stuck? Make sure you're a member of the approved workspace, then contact your admin.",
+ help: "Still stuck? Check that your account has access, then contact your admin.",
});
}
@@ -897,6 +907,7 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>
if (pathname === "/auth/login" && method === "GET") return authLogin(req, res, url);
if (pathname === "/auth/callback" && method === "GET") return authCallback(req, res, url);
+ if (pathname.startsWith("/auth/trusted/") && method === "GET") return trustedAuth(req, res, url);
if (pathname === "/auth/admin-login") return adminLogin(req, res);
if (pathname === "/auth/logout" && method === "POST") {
if (!sameOriginRequest(req)) return json(res, 403, { error: "forbidden" });
@@ -1244,6 +1255,35 @@ async function adminLogin(req: IncomingMessage, res: ServerResponse): Promise<vo
res.end();
}
+async function trustedAuth(req: IncomingMessage, res: ServerResponse, url: URL): Promise<void> {
+ if (!trustedEntry) return json(res, 404, { error: "not_found" });
+ const cookieName = "portal_trusted_tmp";
+ const path = "/auth/trusted";
+ if (url.pathname === `${path}/login`) {
+ const login = trustedEntry.start(sanitizeReturnTo(url.searchParams.get("returnTo"), PUBLIC_URL, APPS_DOMAIN));
+ setSession(res, [setCookie(cookieName, login.cookie, { path, maxAge: login.ttl, secure: SECURE_COOKIES })]);
+ res.writeHead(302, { location: login.location, "cache-control": "no-store" });
+ return void res.end();
+ }
+ if (url.pathname !== `${path}/callback`) return json(res, 404, { error: "not_found" });
+ setSession(res, [clearCookie(cookieName, path, SECURE_COOKIES)]);
+ try {
+ const identity = await trustedEntry.finish(readCookie(req.headers.cookie, cookieName), url);
+ setAuthenticatedSession(res, identity.sub, identity.name);
+ res.writeHead(302, {
+ location: sanitizeReturnTo(identity.returnTo, PUBLIC_URL, APPS_DOMAIN),
+ "cache-control": "no-store",
+ });
+ res.end();
+ } catch {
+ sendHtml(
+ res,
+ 400,
+ signInErrorHtml("Trusted sign-in failed. Please start again from your provider.", "/auth/trusted/login"),
+ );
+ }
+}
+
function setAuthenticatedSession(res: ServerResponse, sub: string, name = ""): void {
const now = Math.floor(Date.now() / 1000);
const session: SessionClaims = {
@@ -1257,6 +1297,7 @@ function setAuthenticatedSession(res: ServerResponse, sub: string, name = ""): v
};
setSession(res, [
...sessionCookieSet(seal(session, sessionKey)),
+ clearCookie("portal_trusted_tmp", "/auth/trusted", SECURE_COOKIES),
clearCookie("portal_oidc_tmp", "/auth", SECURE_COOKIES),
clearCookie("portal_impersonate", "/", SECURE_COOKIES),
]);
diff --git a/plugins/portal/src/trusted-entry.ts b/plugins/portal/src/trusted-entry.ts
new file mode 100644
index 000000000..f4e2e08ab
--- /dev/null
+++ b/plugins/portal/src/trusted-entry.ts
@@ -0,0 +1,93 @@
+import { createHash } from "node:crypto";
+import { buildAuthorizeUrl, exchangeCode, fetchUserinfo, pkcePair, verifyIdToken, type OidcConfig } from "./oidc.ts";
+import { deriveKey, openTmp, randomToken, safeEqual, seal, type TmpClaims } from "./session.ts";
+
+export function trustedEntryConfig(env: NodeJS.ProcessEnv, publicUrl: string): OidcConfig | null {
+ const raw = env.PORTAL_TRUSTED_OIDC;
+ const secret = env.PORTAL_TRUSTED_OIDC_CLIENT_SECRET;
+ if (!raw && !secret) return null;
+ if (!raw || !secret || secret.length < 32)
+ throw new Error("Trusted entry requires configuration and a separate client secret of at least 32 characters");
+ if ([env.OIDC_CLIENT_SECRET, env.PORTAL_SESSION_SECRET, env.CORE_SIGNING_SECRET].includes(secret))
+ throw new Error("Trusted entry requires a distinct client secret");
+ const parsed: unknown = JSON.parse(raw);
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
+ throw new Error("Invalid trusted OIDC configuration");
+ const obj = parsed as Record<string, unknown>;
+ for (const field of ["issuer", "authEndpoint", "tokenEndpoint", "userinfoEndpoint", "jwksUri"]) {
+ if (typeof obj[field] !== "string") throw new Error(`Trusted OIDC requires ${field}`);
+ const url = new URL(obj[field]);
+ const local =
+ env.NODE_ENV !== "production" &&
+ url.protocol === "http:" &&
+ ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
+ if ((!local && url.protocol !== "https:") || url.username || url.password || url.hash || url.search)
+ throw new Error(`Invalid trusted OIDC ${field}`);
+ }
+ if (typeof obj.clientId !== "string" || !obj.clientId.trim()) throw new Error("Trusted OIDC requires clientId");
+ return {
+ issuer: obj.issuer as string,
+ authEndpoint: obj.authEndpoint as string,
+ tokenEndpoint: obj.tokenEndpoint as string,
+ userinfoEndpoint: obj.userinfoEndpoint as string,
+ jwksUri: obj.jwksUri as string,
+ clientId: obj.clientId,
+ clientSecret: secret,
+ redirectUri: `${publicUrl}/auth/trusted/callback`,
+ scopes: "openid profile",
+ prompt: "login",
+ };
+}
+
+export function trustedPrincipal(issuer: string, sub: string): string {
+ if (!sub || sub.length > 255) throw new Error("Invalid trusted subject");
+ return `oidc:${createHash("sha256").update(issuer).digest("hex")}:${Buffer.from(sub).toString("base64url")}`;
+}
+
+export function createTrustedEntry(
+ cfg: OidcConfig,
+ sessionSecret: string,
+ claim: (key: string, expiresAt: number) => Promise<boolean>,
+ fetchImpl: typeof fetch = fetch,
+) {
+ const key = deriveKey(sessionSecret, "trusted-entry-tmp");
+ const ttl = 600;
+ return {
+ start(returnTo: string) {
+ const { verifier, challenge } = pkcePair();
+ const now = Math.floor(Date.now() / 1000);
+ const tmp: TmpClaims = {
+ k: "tmp",
+ state: randomToken(),
+ nonce: randomToken(),
+ pkceVerifier: verifier,
+ returnTo,
+ iat: now,
+ exp: now + ttl,
+ };
+ return {
+ cookie: seal(tmp, key),
+ location: buildAuthorizeUrl(cfg, { state: tmp.state, nonce: tmp.nonce, challenge }),
+ ttl,
+ };
+ },
+ async finish(cookie: string | null, url: URL) {
+ const tmp = openTmp(cookie, key, Date.now());
+ const state = url.searchParams.get("state");
+ const code = url.searchParams.get("code");
+ if (url.searchParams.has("error") || !tmp || !state || !code || !safeEqual(state, tmp.state))
+ throw new Error("Invalid trusted login state");
+ if (!(await claim(`trusted-entry:${tmp.state}`, tmp.exp * 1000))) throw new Error("Trusted login already used");
+ const { accessToken, idToken } = await exchangeCode(cfg, { code, codeVerifier: tmp.pkceVerifier }, fetchImpl);
+ const claims = await verifyIdToken(cfg, idToken, tmp.nonce, fetchImpl);
+ const info = await fetchUserinfo(cfg, accessToken, fetchImpl);
+ if (typeof claims.sub !== "string" || claims.sub !== info.sub)
+ throw new Error("Trusted identity subject mismatch");
+ return {
+ sub: trustedPrincipal(cfg.issuer, claims.sub),
+ name: typeof info.name === "string" ? info.name.trim().slice(0, 200) : "",
+ returnTo: tmp.returnTo,
+ };
+ },
+ };
+}
diff --git a/plugins/portal/test/trusted-entry-routes.test.ts b/plugins/portal/test/trusted-entry-routes.test.ts
new file mode 100644
index 000000000..bf3b27d51
--- /dev/null
+++ b/plugins/portal/test/trusted-entry-routes.test.ts
@@ -0,0 +1,146 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { createHash } from "node:crypto";
+import { exportJWK, generateKeyPair, SignJWT } from "jose";
+import { deriveKey, openSession } from "../src/session.ts";
+
+const claims = new Set<string>();
+let claimAvailable = true;
+const codes = new Map<string, { nonce: string; challenge: string }>();
+const { privateKey, publicKey } = await generateKeyPair("ES256", { extractable: true });
+let issuer = "";
+const upstream = createServer((req, res) => {
+ void (async () => {
+ const url = new URL(req.url!, issuer);
+ res.setHeader("content-type", "application/json");
+ if (url.pathname === "/jwks")
+ return res.end(JSON.stringify({ keys: [{ ...(await exportJWK(publicKey)), kid: "test" }] }));
+ if (url.pathname === "/token") {
+ let body = "";
+ for await (const chunk of req) body += chunk;
+ const params = new URLSearchParams(body);
+ const code = codes.get(params.get("code")!);
+ codes.delete(params.get("code")!);
+ assert.equal(
+ req.headers.authorization,
+ `Basic ${Buffer.from("trusted-client:trusted-client-secret-of-at-least-32-characters").toString("base64")}`,
+ );
+ assert.ok(code);
+ assert.equal(code.challenge, createHash("sha256").update(params.get("code_verifier")!).digest("base64url"));
+ const id = await new SignJWT({ nonce: code.nonce })
+ .setProtectedHeader({ alg: "ES256", kid: "test" })
+ .setIssuer(issuer)
+ .setAudience("trusted-client")
+ .setSubject("person-7")
+ .setIssuedAt()
+ .setExpirationTime("1m")
+ .sign(privateKey);
+ return res.end(JSON.stringify({ access_token: "profile-access", id_token: id }));
+ }
+ if (url.pathname === "/userinfo")
+ return res.end(JSON.stringify({ sub: "person-7", name: "Test Founder", email: "[email protected]" }));
+ if (url.pathname === "/v1/auth/broker/claim") {
+ if (!claimAvailable) {
+ res.statusCode = 503;
+ return res.end("{}");
+ }
+ let body = "";
+ for await (const chunk of req) body += chunk;
+ const { ids } = JSON.parse(body) as { ids: string[] };
+ const id = ids.find((id) => !claims.has(id));
+ if (id) claims.add(id);
+ return res.end(JSON.stringify({ claimed: id ?? null }));
+ }
+ return res.end("{}");
+ })().catch((error) => {
+ res.statusCode = 500;
+ res.end(JSON.stringify({ error: String(error) }));
+ });
+});
+await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));
+issuer = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`;
+const sessionSecret = "trusted-route-test-session-secret";
+Object.assign(process.env, {
+ NODE_ENV: "test",
+ PORTAL_PUBLIC_URL: "http://127.0.0.1:19998",
+ PORTAL_SESSION_SECRET: sessionSecret,
+ CORE_ORG_ID: "test-company",
+ CORE_API_URL: issuer,
+ CORE_SIGNING_SECRET: "test-core-secret",
+ WEB_UI_UPSTREAM: issuer,
+ ADMIN_UPSTREAM: issuer,
+ OIDC_AUTH_ENDPOINT: "https://primary.example.test/authorize",
+ OIDC_CLIENT_ID: "primary-client",
+ PORTAL_LOCAL_AUTH_BYPASS: "0",
+ PORTAL_TRUSTED_OIDC: JSON.stringify({
+ issuer,
+ authEndpoint: `${issuer}/authorize`,
+ tokenEndpoint: `${issuer}/token`,
+ userinfoEndpoint: `${issuer}/userinfo`,
+ jwksUri: `${issuer}/jwks`,
+ clientId: "trusted-client",
+ }),
+ PORTAL_TRUSTED_OIDC_CLIENT_SECRET: "trusted-client-secret-of-at-least-32-characters",
+});
+const { server } = await import("../src/index.ts");
+await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+test.after(() => {
+ server.close();
+ upstream.close();
+});
+
+async function start() {
+ const response = await fetch(`${base}/auth/trusted/login?returnTo=https://evil.example`, { redirect: "manual" });
+ assert.equal(response.status, 302);
+ const url = new URL(response.headers.get("location")!);
+ const code = `code-${codes.size}-${Math.random()}`;
+ codes.set(code, { nonce: url.searchParams.get("nonce")!, challenge: url.searchParams.get("code_challenge")! });
+ return {
+ callback: `${base}/auth/trusted/callback?code=${code}&state=${url.searchParams.get("state")}`,
+ cookie: response.headers.getSetCookie()[0]!.split(";")[0]!,
+ };
+}
+
+test("primary login still selects the original provider", async () => {
+ const response = await fetch(`${base}/auth/login`, { redirect: "manual" });
+ const url = new URL(response.headers.get("location")!);
+ assert.equal(url.origin, "https://primary.example.test");
+ assert.equal(url.searchParams.get("client_id"), "primary-client");
+ assert.match(response.headers.getSetCookie()[0]!, /^portal_oidc_tmp=/);
+});
+
+test("trusted route issues an ordinary scoped session, clears transient cookies, and rejects replay", async () => {
+ const login = await start();
+ const response = await fetch(login.callback, { redirect: "manual", headers: { cookie: login.cookie } });
+ assert.equal(response.status, 302);
+ assert.equal(response.headers.get("location"), "/");
+ const cookies = response.headers.getSetCookie();
+ assert.ok(cookies.some((cookie) => cookie.startsWith("portal_trusted_tmp=") && cookie.includes("Max-Age=0")));
+ const sessionCookie = cookies
+ .find((cookie) => cookie.startsWith("portal_session="))!
+ .split(";")[0]!
+ .slice("portal_session=".length);
+ const session = openSession(sessionCookie, deriveKey(sessionSecret, "portal.session.v1"), Date.now(), "test-company");
+ assert.ok(session);
+ assert.match(session.sub, /^oidc:/);
+ assert.notEqual(session.sub, "[email protected]");
+ const replay = await fetch(login.callback, { redirect: "manual", headers: { cookie: login.cookie } });
+ assert.equal(replay.status, 400);
+ assert.ok(!replay.headers.getSetCookie().some((cookie) => cookie.startsWith("portal_session=")));
+});
+
+test("durable claim service failure cannot issue a session", async () => {
+ const login = await start();
+ claimAvailable = false;
+ try {
+ const response = await fetch(login.callback, { redirect: "manual", headers: { cookie: login.cookie } });
+ assert.equal(response.status, 400);
+ assert.match(await response.text(), /href="\/auth\/trusted\/login"/);
+ assert.ok(!response.headers.getSetCookie().some((cookie) => cookie.startsWith("portal_session=")));
+ } finally {
+ claimAvailable = true;
+ }
+});
diff --git a/plugins/portal/test/trusted-entry.test.ts b/plugins/portal/test/trusted-entry.test.ts
new file mode 100644
index 000000000..845895da7
--- /dev/null
+++ b/plugins/portal/test/trusted-entry.test.ts
@@ -0,0 +1,78 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { createTrustedEntry, trustedEntryConfig, trustedPrincipal } from "../src/trusted-entry.ts";
+
+const config = {
+ issuer: "https://identity.example.com",
+ authEndpoint: "https://identity.example.com/auth",
+ tokenEndpoint: "https://identity.example.com/token",
+ userinfoEndpoint: "https://identity.example.com/me",
+ jwksUri: "https://identity.example.com/jwks",
+ clientId: "company-client",
+};
+const env = {
+ PORTAL_TRUSTED_OIDC: JSON.stringify(config),
+ PORTAL_TRUSTED_OIDC_CLIENT_SECRET: "separate-client-secret-of-32-characters",
+ NODE_ENV: "production",
+};
+
+test("trusted entry is opt-in and cannot inherit primary provider credentials", () => {
+ assert.equal(trustedEntryConfig({}, "https://portal.example.com"), null);
+ for (const invalid of [
+ { PORTAL_TRUSTED_OIDC: env.PORTAL_TRUSTED_OIDC },
+ { PORTAL_TRUSTED_OIDC_CLIENT_SECRET: env.PORTAL_TRUSTED_OIDC_CLIENT_SECRET },
+ { ...env, OIDC_CLIENT_SECRET: env.PORTAL_TRUSTED_OIDC_CLIENT_SECRET },
+ ])
+ assert.throws(() => trustedEntryConfig(invalid, "https://portal.example.com"));
+ const parsed = trustedEntryConfig(env, "https://portal.example.com")!;
+ assert.equal(parsed.redirectUri, "https://portal.example.com/auth/trusted/callback");
+ assert.equal(parsed.scopes, "openid profile");
+ assert.equal(parsed.prompt, "login");
+});
+
+test("trusted provider refuses insecure endpoints in production", () => {
+ for (const field of ["issuer", "authEndpoint", "tokenEndpoint", "userinfoEndpoint", "jwksUri"]) {
+ for (const url of ["http://127.0.0.1:3000", "https://user:[email protected]", "https://example.com/#fragment"])
+ assert.throws(() =>
+ trustedEntryConfig(
+ { ...env, PORTAL_TRUSTED_OIDC: JSON.stringify({ ...config, [field]: url }) },
+ "https://portal.example.com",
+ ),
+ );
+ }
+});
+
+test("subjects cannot implicitly alias primary email or Slack identities", () => {
+ const principal = trustedPrincipal(config.issuer, "[email protected]");
+ assert.notEqual(principal, "[email protected]");
+ assert.notEqual(principal, trustedPrincipal("https://another.example.com", "[email protected]"));
+ assert.notEqual(principal, trustedPrincipal(config.issuer, "U123456"));
+ assert.throws(() => trustedPrincipal(config.issuer, ""));
+});
+
+test("state and cookie binding are checked before claims or network access", async () => {
+ let claims = 0;
+ const entry = createTrustedEntry(
+ trustedEntryConfig(env, "https://portal.example.com")!,
+ "test-session-secret",
+ async () => {
+ claims++;
+ return true;
+ },
+ async () => {
+ throw new Error("Network should not be called");
+ },
+ );
+ const start = entry.start("/");
+ const url = new URL("https://portal.example.com/auth/trusted/callback?code=test&state=wrong");
+ await assert.rejects(entry.finish(start.cookie, url), /Invalid trusted login state/);
+ url.searchParams.set("state", new URL(start.location).searchParams.get("state")!);
+ await assert.rejects(entry.finish(null, url), /Invalid trusted login state/);
+ const other = createTrustedEntry(
+ trustedEntryConfig(env, "https://portal.example.com")!,
+ "different-session-secret",
+ async () => true,
+ );
+ await assert.rejects(other.finish(start.cookie, url), /Invalid trusted login state/);
+ assert.equal(claims, 0);
+});