Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Serve isolated app origins through the portal ingress (#1220)

Regan Bell3f37aace512e
diff --git a/cli/src/backends/aws.ts b/cli/src/backends/aws.ts
index bc36f3a76..c3f6e2d0a 100644
--- a/cli/src/backends/aws.ts
+++ b/cli/src/backends/aws.ts
@@ -3295,6 +3295,21 @@ function assertCloudFrontLayerTarget(config: QmConfig, url: URL, target: string)
}
}
+function awsPortalAppsDomain(config: QmConfig): string | undefined {
+ if (!config.aws?.services.portal) return undefined;
+ const domain = config.env.portal?.PORTAL_APPS_DOMAIN?.trim().toLowerCase().replace(/\.$/, "");
+ if (!domain) return undefined;
+ const coreDomain = (config.env.core?.DEPLOY_APPS_DOMAIN || config.env.core?.AWS_DEPLOY_APPS_DOMAIN)
+ ?.trim()
+ .toLowerCase()
+ .replace(/\.$/, "");
+ const company = new URL(config.publicUrl).hostname.toLowerCase();
+ if (!validAlbHostname(domain) || domain !== coreDomain || !domain.endsWith(`.${company}`)) {
+ throw new Error("portal apps domain must match core and remain beneath the company public hostname");
+ }
+ return domain;
+}
+
function awsCoreHostnames(config: QmConfig): string[] {
const hosts: string[] = [];
const normalize = (value: string, source: string): string => {
@@ -3318,7 +3333,7 @@ function awsCoreHostnames(config: QmConfig): string[] {
if (apiHost !== new URL(config.publicUrl).hostname.toLowerCase().replace(/\.$/, "")) hosts.push(apiHost);
}
const apps = config.env.core?.DEPLOY_APPS_DOMAIN?.trim() || config.env.core?.AWS_DEPLOY_APPS_DOMAIN?.trim();
- if (apps)
+ if (apps && apps.trim().toLowerCase().replace(/\.$/, "") !== awsPortalAppsDomain(config))
hosts.push(`*.${normalize(apps, "the apps domain (env.core.DEPLOY_APPS_DOMAIN or AWS_DEPLOY_APPS_DOMAIN)")}`);
return [...new Set(hosts)];
}
@@ -3448,17 +3463,42 @@ export function assertAwsPublicRouting(
let nonDefault = rules.filter((rule) => !rule.IsDefault);
if (aws.sharedAlb) {
const hostname = new URL(config.publicUrl).hostname.toLowerCase();
+ const portalAppsDomain = awsPortalAppsDomain(config);
+ const expectedHosts = [hostname, ...(portalAppsDomain ? [`*.${portalAppsDomain}`] : [])];
+ const overlaps = (a: string, b: string): boolean => {
+ if (a === b) return true;
+ if (a.startsWith("*.")) return b.endsWith(a.slice(1));
+ if (b.startsWith("*.")) return a.endsWith(b.slice(1));
+ return false;
+ };
const ownRule = productionRules.get("portal");
for (const rule of nonDefault) {
const hosts = rule.Conditions?.filter((condition) => condition.Field === "host-header");
- const values = hosts?.[0]?.HostHeaderConfig?.Values ?? hosts?.[0]?.Values ?? [];
- if (hosts?.length !== 1 || !values.length || values.some((value) => !validAlbHostname(value))) {
- throw new Error("shared ALB rules require explicit non-wildcard hostnames");
+ const values = (hosts?.[0]?.HostHeaderConfig?.Values ?? hosts?.[0]?.Values ?? []).map((value) =>
+ value.toLowerCase(),
+ );
+ const companyHosts = values.filter((value) => validAlbHostname(value));
+ if (
+ hosts?.length !== 1 ||
+ companyHosts.length !== 1 ||
+ values.some(
+ (value) =>
+ !validAlbHostname(value) &&
+ !(
+ value.startsWith("*.") &&
+ validAlbHostname(value.slice(2)) &&
+ value.slice(2).endsWith(`.${companyHosts[0]}`)
+ ),
+ )
+ ) {
+ throw new Error("shared ALB rules require one company hostname and company-contained app wildcards");
}
- const matchesHost = values.some((value) => value.toLowerCase() === hostname);
+ const matchesHost = values.some((value) =>
+ expectedHosts.some((expected) => overlaps(value, expected) || overlaps(expected, value)),
+ );
if (rule.RuleArn === ownRule) {
- if (!matchesHost || values.length !== 1)
- throw new Error("shared ALB portal rule must match only this company hostname");
+ if (values.length !== expectedHosts.length || expectedHosts.some((value) => !values.includes(value)))
+ throw new Error("shared ALB portal rule must match only this company and its configured app hostname");
} else {
const referencesOwnTarget = rule.Actions?.some(
(action) =>
diff --git a/cli/test/aws.test.ts b/cli/test/aws.test.ts
index cbdbfac58..c34341445 100644
--- a/cli/test/aws.test.ts
+++ b/cli/test/aws.test.ts
@@ -60,7 +60,9 @@ function fakeAws(
ingress: {
blueGreen?: boolean;
sharedHost?: string;
+ sharedAppsHost?: string;
siblingHost?: string;
+ siblingAppsHost?: string;
siblingOwnTarget?: boolean;
coreHosts?: string[];
targetGroups?: Partial<Record<"core" | "portal", string>>;
@@ -127,14 +129,24 @@ function fakeAws(
if (ingress.sharedHost) {
(baseRules[0]!.Conditions as unknown[]).push({
Field: "host-header",
- HostHeaderConfig: { Values: [ingress.sharedHost] },
+ HostHeaderConfig: { Values: [ingress.sharedHost, ...(ingress.sharedAppsHost ? [ingress.sharedAppsHost] : [])] },
});
groups.push({ TargetGroupArn: "other-target", TargetGroupName: "other-target" });
baseRules.push({
RuleArn: "other-rule",
IsDefault: false,
Actions: [{ Type: "forward", TargetGroupArn: ingress.siblingOwnTarget ? targetArn : "other-target" }],
- Conditions: [{ Field: "host-header", HostHeaderConfig: { Values: [ingress.siblingHost ?? "other.example"] } }],
+ Conditions: [
+ {
+ Field: "host-header",
+ HostHeaderConfig: {
+ Values: [
+ ingress.siblingHost ?? "other.example",
+ ...(ingress.siblingAppsHost ? [ingress.siblingAppsHost] : []),
+ ],
+ },
+ },
+ ],
});
}
writeFileSync(log, "");
@@ -5088,18 +5100,43 @@ test("shared ALB validates company routes while rejecting sibling overlap", () =
],
]);
const hostname = new URL(company.publicUrl).hostname;
- for (const variant of ["valid", "same-host", "wildcard", "own-target", "wrong-host"]) {
+ for (const variant of [
+ "valid",
+ "same-host",
+ "wildcard",
+ "own-target",
+ "wrong-host",
+ "apps",
+ "apps-missing",
+ "apps-wrong",
+ "sibling-apps",
+ ]) {
+ const appDomain = `apps.${hostname}`;
+ const selected = variant.startsWith("apps")
+ ? {
+ ...company,
+ env: {
+ ...company.env,
+ core: { ...company.env.core, DEPLOY_APPS_DOMAIN: appDomain },
+ portal: { ...company.env.portal, PORTAL_APPS_DOMAIN: appDomain },
+ },
+ }
+ : company;
const dir = mkdtempSync(join(tmpdir(), "qm-shared-alb-"));
const fake = fakeAws(dir, "", "portal", {
blueGreen: true,
sharedHost: variant === "wrong-host" ? "wrong.example" : hostname,
+ ...(variant === "apps" ? { sharedAppsHost: `*.${appDomain}` } : {}),
+ ...(variant === "apps-wrong" ? { sharedAppsHost: `*.wrong.${hostname}` } : {}),
+ ...(variant === "sibling-apps" ? { siblingAppsHost: "*.apps.other.example" } : {}),
siblingHost:
({ "same-host": hostname, wildcard: "*.example" } as Record<string, string>)[variant] ?? "other.example",
siblingOwnTarget: variant === "own-target",
});
try {
- if (variant === "valid") assert.equal(assertAwsPublicRouting(company, services).get("portal"), primary);
- else assert.throws(() => assertAwsPublicRouting(company, services), /shared ALB/);
+ if (["valid", "apps", "sibling-apps"].includes(variant))
+ assert.equal(assertAwsPublicRouting(selected, services).get("portal"), primary);
+ else assert.throws(() => assertAwsPublicRouting(selected, services), /shared ALB/);
assert.throws(
() => assertAwsPublicRouting({ ...company, aws: { ...company.aws, sharedAlb: false } }, services),
/unknown services/,
diff --git a/plugins/portal/README.md b/plugins/portal/README.md
index 83f11f5aa..7e0f998eb 100644
--- a/plugins/portal/README.md
+++ b/plugins/portal/README.md
@@ -13,6 +13,17 @@ surfaces, which all stay **private** (no public `[http_service]` of their own):
User deployments are never served on this authenticated origin; they use the dedicated apps domain.
+Set `PORTAL_APPS_DOMAIN` to a child domain of the company portal, with matching
+core `DEPLOY_APPS_DOMAIN`, gateway/session secrets, wildcard DNS and TLS. App
+hostnames can point at the same portal ingress: portal forwards them to core's
+deployment gateway before its own routes. Core authorizes each app request and
+removes gateway cookies before forwarding to the app. Each app has a separate
+browser origin; cross-origin browser writes are rejected. Keep the session cookie
+domain within the company, never a parent shared with other companies.
+For companies using the additional trusted OIDC entry, set core
+`DEPLOY_APPS_LOGIN_PATH=/auth/trusted/login` so app sign-in uses that identity
+provider. The default remains `/auth/login`.
+
It is a thin `node:http` server (native TS type-stripping), like the other
surfaces, and it does **not** import the core.
diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.ts
index b289cd237..ff441b95d 100644
--- a/plugins/portal/src/index.ts
+++ b/plugins/portal/src/index.ts
@@ -35,6 +35,7 @@ import {
proxyToSurface,
proxyToDeployment,
proxyToUpstream,
+ proxyToAppHost,
FORWARD_AGENT_API_HEADERS,
FORWARD_DEPLOYMENT_LAYER_HEADERS,
FORWARD_OAUTH_HEADERS,
@@ -908,6 +909,14 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>
res.setHeader("x-content-type-options", "nosniff");
res.setHeader("x-frame-options", "DENY");
+ const requestHost = (req.headers.host ?? "").toLowerCase().split(":")[0]!;
+ const appSuffix = APPS_DOMAIN ? `.${APPS_DOMAIN.toLowerCase()}` : undefined;
+ if (appSuffix && (requestHost.endsWith(appSuffix) || requestHost === APPS_DOMAIN?.toLowerCase())) {
+ const label = requestHost.slice(0, -appSuffix.length);
+ if (!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) return json(res, 404, { error: "not_found" });
+ return proxyToAppHost(req, res, CORE);
+ }
+
void refreshSurfaceConfig();
if (method === "GET" && pathname === "/healthz") return json(res, 200, { ok: true });
diff --git a/plugins/portal/src/proxy.ts b/plugins/portal/src/proxy.ts
index cebee5f45..5229a7b83 100644
--- a/plugins/portal/src/proxy.ts
+++ b/plugins/portal/src/proxy.ts
@@ -53,7 +53,7 @@ function relay(
hostname: string;
port?: string;
path: string;
- headers: Record<string, string>;
+ headers: Record<string, string | string[]>;
honorFramePolicy?: boolean;
forwardCookies?: boolean;
},
@@ -237,3 +237,35 @@ export function proxyToUpstream(
}
export const FORWARD_BROKER_HEADERS = ["accept", "accept-language", "user-agent", "content-type", "content-length"];
+
+export function proxyToAppHost(req: IncomingMessage, res: ServerResponse, coreBase: string): void {
+ const upstream = new URL(coreBase);
+ const blocked = new Set([
+ ...DROP_RESPONSE_HEADERS,
+ "x-signature",
+ "x-timestamp",
+ "x-as-principal",
+ "x-admin-actor",
+ "x-agent-capability",
+ PORTAL_IDENTITY_HEADER,
+ "x-qm-app-host",
+ "forwarded",
+ "x-forwarded-host",
+ "x-forwarded-proto",
+ "x-forwarded-for",
+ ...(req.headers.connection ?? "").split(",").map((name) => name.trim().toLowerCase()),
+ ]);
+ const headers: Record<string, string | string[]> = { "x-qm-app-host": "1" };
+ for (const [name, value] of Object.entries(req.headers)) {
+ if (value !== undefined && !blocked.has(name)) headers[name] = value;
+ }
+ res.removeHeader("x-frame-options");
+ relay(req, res, {
+ protocol: upstream.protocol,
+ hostname: upstream.hostname,
+ port: requestPort(upstream),
+ path: req.url ?? "/",
+ headers,
+ forwardCookies: true,
+ });
+}
diff --git a/plugins/portal/test/app-host-proxy.test.ts b/plugins/portal/test/app-host-proxy.test.ts
new file mode 100644
index 000000000..86211ea8f
--- /dev/null
+++ b/plugins/portal/test/app-host-proxy.test.ts
@@ -0,0 +1,70 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { createServer, request } from "node:http";
+import type { AddressInfo } from "node:net";
+import { proxyToAppHost } from "../src/proxy.ts";
+
+const upstream = createServer(async (req, res) => {
+ const chunks: Buffer[] = [];
+ for await (const chunk of req) chunks.push(chunk);
+ res.writeHead(201, { "content-type": "application/json", "set-cookie": ["a=1", "b=2"] });
+ res.write(JSON.stringify({ headers: req.headers, body: Buffer.concat(chunks).toString(), url: req.url }));
+ res.end();
+});
+await new Promise<void>((resolve) => upstream.listen(0, resolve));
+const upstreamUrl = `http://localhost:${(upstream.address() as AddressInfo).port}`;
+const portal = createServer((req, res) => proxyToAppHost(req, res, upstreamUrl));
+await new Promise<void>((resolve) => portal.listen(0, resolve));
+test.after(() => {
+ upstream.close();
+ portal.close();
+});
+
+test("app proxy preserves uploads and app headers while stripping identity and hop headers", async () => {
+ const result = await new Promise<{ status: number; cookies: string[]; body: string }>((resolve, reject) => {
+ const req = request(
+ {
+ hostname: "localhost",
+ port: (portal.address() as AddressInfo).port,
+ method: "POST",
+ path: "/api/write?x=1",
+ headers: {
+ host: "counter.apps.company.example.com",
+ "content-length": "7",
+ "content-type": "text/plain",
+ authorization: "Bearer app-token",
+ "if-match": '"version-2"',
+ "x-app-key": "app-key",
+ "x-signature": "forged",
+ "x-as-principal": "admin",
+ "x-agent-capability": "forged",
+ connection: "x-remove-me",
+ "x-remove-me": "secret",
+ cookie: "portal_session=test",
+ },
+ },
+ (res) => {
+ let body = "";
+ res.on("data", (chunk) => {
+ body += chunk;
+ });
+ res.on("end", () => resolve({ status: res.statusCode!, cookies: res.headers["set-cookie"]!, body }));
+ },
+ );
+ req.on("error", reject);
+ req.end("payload");
+ });
+ assert.equal(result.status, 201);
+ assert.deepEqual(result.cookies, ["a=1", "b=2"]);
+ const body = JSON.parse(result.body);
+ assert.equal(body.body, "payload");
+ assert.equal(body.url, "/api/write?x=1");
+ assert.equal(body.headers["content-length"], "7");
+ assert.equal(body.headers.authorization, "Bearer app-token");
+ assert.equal(body.headers["if-match"], '"version-2"');
+ assert.equal(body.headers["x-app-key"], "app-key");
+ assert.equal(body.headers.cookie, "portal_session=test");
+ assert.equal(body.headers["x-qm-app-host"], "1");
+ for (const header of ["x-signature", "x-as-principal", "x-agent-capability", "x-remove-me"])
+ assert.equal(body.headers[header], undefined);
+});
diff --git a/plugins/portal/test/apps-subdomain-signin.test.ts b/plugins/portal/test/apps-subdomain-signin.test.ts
index 9c3f8ee29..cd30a8ec9 100644
--- a/plugins/portal/test/apps-subdomain-signin.test.ts
+++ b/plugins/portal/test/apps-subdomain-signin.test.ts
@@ -1,11 +1,13 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { createServer, type IncomingMessage } from "node:http";
+import { createServer, request, type IncomingMessage } from "node:http";
import type { AddressInfo } from "node:net";
const upstream = createServer((req: IncomingMessage, res) => {
- res.writeHead(200, { "content-type": "application/json" });
- res.end(JSON.stringify({ url: req.url, cookie: req.headers.cookie ?? null }));
+ res.writeHead(200, { "content-type": "application/json", "set-cookie": ["app_pref=ok", "dpl_owner=test"] });
+ res.end(
+ JSON.stringify({ url: req.url, cookie: req.headers.cookie ?? null, headers: req.headers, method: req.method }),
+ );
});
await new Promise<void>((r) => upstream.listen(0, r));
const upstreamUrl = `http://localhost:${(upstream.address() as AddressInfo).port}`;
@@ -25,6 +27,62 @@ const { server, hostIsWithinDomain } = await import("../src/index.ts");
await new Promise<void>((r) => server.listen(0, r));
const base = `http://localhost:${(server.address() as AddressInfo).port}`;
+function appRequest(path: string, host: string): Promise<Response> {
+ return new Promise((resolve, reject) => {
+ const req = request(
+ `${base}${path}`,
+ {
+ headers: {
+ host,
+ cookie: "portal_session=test",
+ "x-as-principal": "admin",
+ "x-signature": "forged",
+ "x-portal-identity": "forged",
+ "sec-fetch-dest": "iframe",
+ },
+ },
+ (res) => {
+ const chunks: Buffer[] = [];
+ res.on("data", (chunk) => chunks.push(chunk));
+ res.on("end", () => {
+ const headers = new Headers();
+ for (const [name, values] of Object.entries(res.headers)) {
+ if (values === undefined) continue;
+ for (const value of Array.isArray(values) ? values : [values]) headers.append(name, value);
+ }
+ resolve(new Response(Buffer.concat(chunks), { status: res.statusCode, headers }));
+ });
+ },
+ );
+ req.on("error", reject);
+ req.end();
+ });
+}
+
+test("app host requests preserve gateway auth without entering portal routes", async () => {
+ for (const path of ["/app.js?x=1", "/auth/login", "/healthz", "/api/private", "/v1/status"]) {
+ const response = await appRequest(path, "contracts.apps.qm.example.com");
+ assert.equal(response.status, 200);
+ const data = (await response.json()) as { url: string; cookie: string; headers: Record<string, string> };
+ assert.equal(data.url, path);
+ assert.equal(data.headers.host, "contracts.apps.qm.example.com");
+ assert.equal(data.cookie, "portal_session=test");
+ assert.equal(data.headers["x-qm-app-host"], "1");
+ assert.equal(data.headers["sec-fetch-dest"], "iframe");
+ assert.equal(data.headers["x-as-principal"], undefined);
+ assert.equal(data.headers["x-signature"], undefined);
+ assert.equal(data.headers["x-portal-identity"], undefined);
+ assert.equal(response.headers.get("x-frame-options"), null);
+ assert.deepEqual(response.headers.getSetCookie(), ["app_pref=ok", "dpl_owner=test"]);
+ }
+});
+
+test("nested and bare app hosts do not enter portal routes", async () => {
+ for (const host of ["apps.qm.example.com", "a.b.apps.qm.example.com"]) {
+ assert.equal((await appRequest("/auth/login", host)).status, 404);
+ }
+});
+
test.after(() => {
server.close();
upstream.close();
diff --git a/src/api/deps.ts b/src/api/deps.ts
index cf5a50573..95295537e 100644
--- a/src/api/deps.ts
+++ b/src/api/deps.ts
@@ -169,6 +169,7 @@ export interface ServerDeps {
deployGateSecret?: string;
deployAppsSessionSecret?: string;
deployAppsLoginUrl?: string;
+ deployAppsLoginPath?: "/auth/login" | "/auth/trusted/login";
scheduler?: Scheduler;
webhookReceiver?: WebhookReceiver;
identity?: IdentityService;
diff --git a/src/api/routes/deployments.ts b/src/api/routes/deployments.ts
index c141cb807..3ac07ff1c 100644
--- a/src/api/routes/deployments.ts
+++ b/src/api/routes/deployments.ts
@@ -150,6 +150,7 @@ async function proxyAdminDeployment(ctx: BaseCtx): Promise<void> {
}
const GATEWAY_AUTH_HEADERS = [
+ "x-qm-app-host",
"x-signature",
"x-timestamp",
"x-as-principal",
@@ -772,15 +773,32 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {
const { req, res, app, deps, url, pathname } = ctx;
const appsDomain = deps.deployAppsDomain;
const gateSecret = deps.deployGateSecret;
- if (!appsDomain || !gateSecret) return false;
+ const fromAppHost = req.headers["x-qm-app-host"] === "1";
+ if (!appsDomain || !gateSecret) {
+ if (!fromAppHost) return false;
+ sendJson(res, 503, { error: "unavailable", message: "app gateway is not configured" });
+ return true;
+ }
const rawHost = (req.headers.host ?? "").split(":")[0]!.toLowerCase();
const suffix = `.${appsDomain.toLowerCase()}`;
- if (!rawHost || !rawHost.endsWith(suffix)) return false;
+ if (!rawHost || !rawHost.endsWith(suffix)) {
+ if (!fromAppHost) return false;
+ sendJson(res, 404, { error: "not_found" });
+ return true;
+ }
const slug = rawHost.slice(0, -suffix.length);
- if (!slug || slug.includes(".")) {
+ if (!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(slug)) {
sendJson(res, 404, { error: "not_found" });
return true;
}
+ if (!["GET", "HEAD", "OPTIONS"].includes(ctx.method)) {
+ const origin = req.headers.origin;
+ const site = req.headers["sec-fetch-site"];
+ if ((origin !== undefined && origin !== `https://${rawHost}`) || (site !== undefined && site !== "same-origin")) {
+ sendJson(res, 403, { error: "forbidden", message: "cross-origin app request refused" });
+ return true;
+ }
+ }
const safePathname =
pathname.startsWith("/") && !pathname.startsWith("//") && !/[\\\x00-\x1f]/.test(pathname) ? pathname : "/";
const staleAccess = url.searchParams.has("access");
@@ -871,7 +889,7 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {
if (!sub) {
const qs = url.searchParams.toString();
const returnTo = `https://${rawHost}${safePathname}?${qs ? `${qs}&` : ""}dpl_signin=1`;
- const signIn = `${loginUrl}/auth/login?returnTo=${encodeURIComponent(returnTo)}`;
+ const signIn = `${loginUrl}${deps.deployAppsLoginPath ?? "/auth/login"}?returnTo=${encodeURIComponent(returnTo)}`;
if (!wantsHtml) {
sendJson(res, 401, { error: "unauthorized", message: "sign-in required", loginUrl: signIn });
} else if (signInAttempted) {
diff --git a/src/config.ts b/src/config.ts
index b19174fdf..858c42723 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -150,6 +150,7 @@ export interface Config {
deployDialTimeoutMs: number;
deployAppsSessionSecret?: string;
deployAppsLoginUrl?: string;
+ deployAppsLoginPath?: "/auth/login" | "/auth/trusted/login";
deepIdleMachineMs: number;
devIdleMachineMs: number;
cronFireConcurrency: number;
@@ -620,7 +621,11 @@ interface AwsDeployEnv {
function deployAppsEnv(
env: NodeJS.ProcessEnv,
defaultLoginUrl: string | undefined,
-): { deployAppsSessionSecret?: string; deployAppsLoginUrl?: string } {
+): {
+ deployAppsSessionSecret?: string;
+ deployAppsLoginUrl?: string;
+ deployAppsLoginPath?: "/auth/login" | "/auth/trusted/login";
+} {
const explicit = env.DEPLOY_APPS_SESSION_SECRET;
const shared = env.PORTAL_SESSION_SECRET;
const loginUrl = env.DEPLOY_APPS_LOGIN_URL ?? (explicit || shared ? defaultLoginUrl : undefined);
@@ -631,8 +636,16 @@ function deployAppsEnv(
throw new Error("DEPLOY_APPS_SESSION_SECRET needs a sign-in address — set DEPLOY_APPS_LOGIN_URL or PUBLIC_WEB_URL");
}
const secret = explicit ?? (loginUrl ? shared : undefined);
+ const loginPath = env.DEPLOY_APPS_LOGIN_PATH ?? "/auth/login";
+ if (loginPath !== "/auth/login" && loginPath !== "/auth/trusted/login") {
+ throw new Error("DEPLOY_APPS_LOGIN_PATH must be /auth/login or /auth/trusted/login");
+ }
if (!secret || !loginUrl) return {};
- return { deployAppsSessionSecret: secret, deployAppsLoginUrl: loginUrl.replace(/\/$/, "") };
+ return {
+ deployAppsSessionSecret: secret,
+ deployAppsLoginUrl: loginUrl.replace(/\/$/, ""),
+ deployAppsLoginPath: loginPath,
+ };
}
const SHARED_PLATFORM_SUFFIXES = [
diff --git a/src/wiring.ts b/src/wiring.ts
index 0d0372565..d49d05567 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -2378,6 +2378,7 @@ export function serverDeps(
...(config.awsDeploy.gateSecret ? { deployGateSecret: config.awsDeploy.gateSecret } : {}),
...(config.deployAppsSessionSecret ? { deployAppsSessionSecret: config.deployAppsSessionSecret } : {}),
...(config.deployAppsLoginUrl ? { deployAppsLoginUrl: config.deployAppsLoginUrl } : {}),
+ ...(config.deployAppsLoginPath ? { deployAppsLoginPath: config.deployAppsLoginPath } : {}),
scheduler: built.scheduler,
webhookReceiver: built.webhookReceiver,
identity: built.identity,
diff --git a/test/config.test.ts b/test/config.test.ts
index 2c22469f6..7e88d6c40 100644
--- a/test/config.test.ts
+++ b/test/config.test.ts
@@ -633,6 +633,16 @@ test("the deploy-apps sign-in address defaults to the public web URL", () => {
});
assert.equal(derived.deployAppsLoginUrl, "https://qm.example.com");
assert.equal(derived.deployAppsSessionSecret, "s");
+ assert.equal(derived.deployAppsLoginPath, "/auth/login");
+ assert.equal(
+ loadConfig({
+ DEPLOY_APPS_SESSION_SECRET: "s",
+ PUBLIC_WEB_URL: "https://qm.example.com",
+ DEPLOY_APPS_LOGIN_PATH: "/auth/trusted/login",
+ }).deployAppsLoginPath,
+ "/auth/trusted/login",
+ );
+ assert.throws(() => loadConfig({ DEPLOY_APPS_LOGIN_PATH: "//evil.example" }), /DEPLOY_APPS_LOGIN_PATH/);
const explicit = loadConfig({
DEPLOY_APPS_SESSION_SECRET: "s",
DEPLOY_APPS_LOGIN_URL: "https://portal.example.com/",
diff --git a/test/deploy-subdomain-signin.test.ts b/test/deploy-subdomain-signin.test.ts
index 0bede0546..a9cd45238 100644
--- a/test/deploy-subdomain-signin.test.ts
+++ b/test/deploy-subdomain-signin.test.ts
@@ -57,6 +57,26 @@ test("portalSessionSub: verifies, and rejects tampering, expiry, wrong kind, wro
assert.equal(portalSessionSub(`portal_session=${body}.${sig}`, SESSION_SECRET), null, "non-session claims");
});
+test("forwarded app hosts fail closed before core routes when gateway configuration is absent", async () => {
+ for (const config of [
+ {},
+ { deployAppsDomain: "apps.example.com" },
+ { deployAppsDomain: "apps.example.com", deployGateSecret: "gate" },
+ ]) {
+ const server = createInsecureTestServer({} as Parameters<typeof createInsecureTestServer>[0], config);
+ server.listen(0);
+ try {
+ const result = await httpGet((server.address() as AddressInfo).port, "/healthz", {
+ Host: "app.other.example.com",
+ "x-qm-app-host": "1",
+ });
+ assert.equal(result.status, "deployGateSecret" in config ? 404 : 503);
+ } finally {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+ }
+});
+
function httpGet(
port: number,
path: string,
@@ -73,6 +93,30 @@ function httpGet(
});
}
+test("app sign-in uses the configured trusted entry and preserves the app return address", async () => {
+ const server = createInsecureTestServer({} as Parameters<typeof createInsecureTestServer>[0], {
+ deployAppsDomain: "apps.example.com",
+ deployGateSecret: "gate",
+ deployAppsSessionSecret: SESSION_SECRET,
+ deployAppsLoginUrl: LOGIN_URL,
+ deployAppsLoginPath: "/auth/trusted/login",
+ });
+ server.listen(0);
+ try {
+ const result = await httpGet((server.address() as AddressInfo).port, "/counter?x=1", {
+ Host: "counter.apps.example.com",
+ Accept: "text/html",
+ });
+ assert.equal(result.status, 302);
+ const redirect = new URL(result.headers.location as string);
+ assert.equal(redirect.origin, LOGIN_URL);
+ assert.equal(redirect.pathname, "/auth/trusted/login");
+ assert.equal(redirect.searchParams.get("returnTo"), "https://counter.apps.example.com/counter?x=1&dpl_signin=1");
+ } finally {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ }
+});
+
function httpPost(
port: number,
path: string,
@@ -181,6 +225,29 @@ test("subdomain ingress: portal sign-in admits the owner, denies strangers, boun
assert.equal(owner.body, "UPSTREAM OK");
assert.equal(upstreamCookie, undefined, "the portal session cookie never reaches the app");
assert.equal(upstreamUrl, "/consultants?x=1", "the app sees the clean URL");
+ for (const origin of ["https://sibling.apps.example.com", "https://portal.example.com", "null"]) {
+ const denied = await httpPost(port, "/api/update", {
+ Host: host,
+ Cookie: `portal_session=${mintPortalSession("[email protected]")}`,
+ Origin: origin,
+ });
+ assert.equal(denied.status, 403);
+ }
+ const sameApp = await httpPost(port, "/api/update", {
+ Host: host,
+ Cookie: `portal_session=${mintPortalSession("[email protected]")}`,
+ Origin: `https://${host}`,
+ "Sec-Fetch-Site": "same-origin",
+ });
+ assert.equal(sameApp.status, 200);
+ for (const site of ["same-site", "cross-site"]) {
+ const denied = await httpPost(port, "/api/update", {
+ Host: host,
+ Cookie: `portal_session=${mintPortalSession("[email protected]")}`,
+ "Sec-Fetch-Site": site,
+ });
+ assert.equal(denied.status, 403);
+ }
const ownerSetCookies = ([] as string[]).concat(owner.headers["set-cookie"] ?? []);
assert.deepEqual(
ownerSetCookies,