Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Send portal identity when starting self-connect (#2244)

Joshua France7be7cc79e795
diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.ts
index 78b2c6264..046f9222c 100644
--- a/plugins/portal/src/index.ts
+++ b/plugins/portal/src/index.ts
@@ -259,17 +259,17 @@ const ADMIN_PROBE_ATTEMPTS = 2;
const ADMIN_PROBE_RETRY_DELAY_MS = 250;
const adminCache = new LRUCache<string, boolean>({ max: 10_000, ttl: ADMIN_TTL_MS });
+function portalIdentityHeaders(sub: string): Record<string, string> {
+ return PORTAL_IDENTITY_SECRET
+ ? { [PORTAL_IDENTITY_HEADER]: mintPortalIdentity({ p: sub, exp: Date.now() + 60_000 }, PORTAL_IDENTITY_SECRET) }
+ : {};
+}
+
async function adminProbeAttempt(sub: string): Promise<boolean | null> {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), ADMIN_PROBE_TIMEOUT_MS);
try {
- const headers: Record<string, string> = { cookie: `admin=${encodeURIComponent(sub)}` };
- if (PORTAL_IDENTITY_SECRET) {
- headers[PORTAL_IDENTITY_HEADER] = mintPortalIdentity(
- { p: sub, exp: Date.now() + 60_000 },
- PORTAL_IDENTITY_SECRET,
- );
- }
+ const headers = { cookie: `admin=${encodeURIComponent(sub)}`, ...portalIdentityHeaders(sub) };
const r = await fetch(`${UPSTREAMS.admin}/api/whoami`, { headers, signal: ctrl.signal });
if (!r.ok) {
console.warn(`[portal] admin probe returned HTTP ${r.status}`);
@@ -782,8 +782,11 @@ async function handleSelfConnect(res: ServerResponse, o: { provider: string; ses
CORE_SIGNING_SECRET,
);
try {
- const r = await fetch(`${CORE}${path}`, { headers: signedHeaders(CORE_SIGNING_SECRET, "GET", path) });
+ const r = await fetch(`${CORE}${path}`, {
+ headers: { ...signedHeaders(CORE_SIGNING_SECRET, "GET", path), ...portalIdentityHeaders(o.session.sub) },
+ });
const data = (await r.json().catch(() => ({}))) as { authorizeUrl?: string; message?: string };
+ if (!r.ok) console.warn(`[portal] self-connect start returned HTTP ${r.status}: ${data.message ?? "no message"}`);
if (data.authorizeUrl) {
res.writeHead(302, { location: data.authorizeUrl, "cache-control": "no-store" });
return void res.end();
@@ -793,7 +796,8 @@ async function handleSelfConnect(res: ServerResponse, o: { provider: string; ses
200,
connectErrorHtml(data.message ?? "We couldn't start the connection. This app may not be configured."),
);
- } catch {
+ } catch (error) {
+ console.warn(`[portal] self-connect start failed: ${errMessage(error)}`);
return sendHtml(
res,
502,
@@ -812,9 +816,7 @@ async function coreImpersonate(
const headers = {
...signedHeaders(CORE_SIGNING_SECRET, "POST", path, body),
"x-admin-actor": `${admin}@${ORG}`,
- ...(PORTAL_IDENTITY_SECRET
- ? { [PORTAL_IDENTITY_HEADER]: mintPortalIdentity({ p: admin, exp: Date.now() + 60_000 }, PORTAL_IDENTITY_SECRET) }
- : {}),
+ ...portalIdentityHeaders(admin),
};
try {
const r = await fetch(`${CORE}${path}`, { method: "POST", headers, body });
@@ -1070,10 +1072,7 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>
method: "POST",
headers: {
...signedHeaders(CORE_SIGNING_SECRET, "POST", path, body),
- [PORTAL_IDENTITY_HEADER]: mintPortalIdentity(
- { p: session.sub, exp: Date.now() + 60_000 },
- PORTAL_IDENTITY_SECRET,
- ),
+ ...portalIdentityHeaders(session.sub),
},
body,
signal: AbortSignal.timeout(4_000),
diff --git a/plugins/portal/test/self-connect-identity.test.ts b/plugins/portal/test/self-connect-identity.test.ts
new file mode 100644
index 000000000..fd754922f
--- /dev/null
+++ b/plugins/portal/test/self-connect-identity.test.ts
@@ -0,0 +1,50 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { deriveKey, seal } from "../src/session.ts";
+import { PORTAL_IDENTITY_HEADER, verifyPortalIdentity } from "../../chassis/src/portal-identity.ts";
+
+const identitySecret = "self-connect-portal-identity-secret-32+";
+const core = createServer((req, res) => {
+ const url = new URL(req.url ?? "/", "http://core.test");
+ res.setHeader("content-type", "application/json");
+ if (!/^\/v1\/connectors\/oauth\/[^/]+\/start$/.test(url.pathname)) return void res.end("{}");
+ const header = req.headers[PORTAL_IDENTITY_HEADER];
+ const actor = typeof header === "string" ? verifyPortalIdentity(header, identitySecret, Date.now()) : null;
+ if (!actor || actor.p !== url.searchParams.get("principalId")) {
+ res.statusCode = 401;
+ return void res.end(JSON.stringify({ error: "unauthorized", message: "portal identity required" }));
+ }
+ res.end(JSON.stringify({ authorizeUrl: "https://identity.provider.test/authorize?x=1" }));
+});
+await new Promise<void>((resolve) => core.listen(0, "127.0.0.1", resolve));
+const sessionSecret = "self-connect-session-secret-at-least-32";
+Object.assign(process.env, {
+ PORTAL_PUBLIC_URL: "http://portal.test",
+ PORTAL_SESSION_SECRET: sessionSecret,
+ CORE_SIGNING_SECRET: "self-connect-core-signing-secret-32chars",
+ PORTAL_IDENTITY_SECRET: identitySecret,
+ CORE_API_URL: `http://127.0.0.1:${(core.address() as AddressInfo).port}`,
+});
+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();
+ core.close();
+});
+
+test("self-connect carries the signed portal identity that core requires under requireSignedPortalIdentity", async () => {
+ const now = Math.floor(Date.now() / 1000);
+ const session = seal(
+ { k: "session", sub: "eve@acme", org: "acme", iat: now, exp: now + 3600 },
+ deriveKey(sessionSecret, "portal.session.v1"),
+ );
+ const r = await fetch(`${base}/connect/doordash/self-connect`, {
+ headers: { cookie: `portal_session=${encodeURIComponent(session)}` },
+ redirect: "manual",
+ });
+ assert.equal(r.status, 302);
+ assert.equal(r.headers.get("location"), "https://identity.provider.test/authorize?x=1");
+});