Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Git credential broker: enforce the published-app token binding through the gate (#1794)

Regan Bell87eae257a6c1
diff --git a/src/api/credential-broker.ts b/src/api/credential-broker.ts
index 6a48b3d80..32139beae 100644
--- a/src/api/credential-broker.ts
+++ b/src/api/credential-broker.ts
@@ -87,6 +87,36 @@ export function brokerCredentialAuthHeader(rec: DecryptedServiceCredential): [st
return [injHeader, `${injScheme}${rec.secret}`];
}
+type CredentialGrant =
+ | { rec: DecryptedServiceCredential }
+ | { rec?: undefined; status: number; code: string; message: string; host: string };
+
+export async function grantedCredential(
+ claims: CapabilityClaims,
+ slug: string,
+ reader: ServiceCredentialReader,
+ orgScopeId: ScopeId,
+): Promise<CredentialGrant> {
+ if (!Array.isArray(claims.credentials) || !claims.credentials.includes(slug))
+ return { status: 403, code: "not_entitled", message: "this session is not entitled to that credential", host: "" };
+ const rec = await reader.getServiceCredentialSecret(orgScopeId, slug);
+ if (!rec || !rec.enabled || rec.delivery === "env")
+ return {
+ status: 404,
+ code: "credential_unavailable",
+ message: "credential not found or disabled",
+ host: rec?.host ?? "",
+ };
+ if (claims.deployment && !rec.deployments)
+ return {
+ status: 403,
+ code: "not_available_to_deployments",
+ message: "this credential is switched off for published apps",
+ host: rec.host,
+ };
+ return { rec };
+}
+
export async function brokerCredentialCall(opts: {
claims: CapabilityClaims;
body: BrokerRequest;
@@ -124,16 +154,9 @@ export async function brokerCredentialCall(opts: {
if (!slug || !rawUrl) {
return { status: 400, json: { error: "bad_request", message: "credential (slug) and url are required" } };
}
- if (!Array.isArray(claims.credentials) || !claims.credentials.includes(slug)) {
- return deny(403, "not_entitled", "this session is not entitled to that credential", "");
- }
- const rec: DecryptedServiceCredential | null = await reader.getServiceCredentialSecret(orgScopeId, slug);
- if (!rec || !rec.enabled || rec.delivery === "env") {
- return deny(404, "credential_unavailable", "credential not found or disabled", rec?.host ?? "");
- }
- if (claims.deployment && !rec.deployments) {
- return deny(403, "not_available_to_deployments", "this credential is switched off for published apps", rec.host);
- }
+ const grant = await grantedCredential(claims, slug, reader, orgScopeId);
+ if (!grant.rec) return deny(grant.status, grant.code, grant.message, grant.host);
+ const { rec } = grant;
if (credentialInjectionError(rec.injection)) {
return deny(503, "invalid_injection", "credential injection configuration is invalid", rec.host);
}
diff --git a/src/api/git-http-broker.ts b/src/api/git-http-broker.ts
index 5a7b334d6..b13ab2a43 100644
--- a/src/api/git-http-broker.ts
+++ b/src/api/git-http-broker.ts
@@ -1,12 +1,10 @@
-import { externalSlackCapabilityAllowed } from "./external-slack-capability.ts";
import { orgId as configOrgId } from "../config.ts";
import { Readable } from "node:stream";
-import { CREDENTIAL_BROKER_AUD, verifyCapabilityToken, type CapabilityClaims } from "../auth/capability-token.ts";
+import type { CapabilityClaims } from "../auth/capability-token.ts";
import { scopeId as makeScopeId } from "../types.ts";
import { type DecryptedServiceCredential, isValidCredentialSlug, isComposioHost } from "../credentials/keychain.ts";
-import { brokerCredentialAuthHeader, brokerPathAllowed } from "./credential-broker.ts";
-import { CAPABILITY_HEADER } from "./contract.ts";
-import { headerValue, pipeToResponse, sendJson } from "./http.ts";
+import { brokerCredentialAuthHeader, brokerPathAllowed, grantedCredential } from "./credential-broker.ts";
+import { pipeToResponse, sendJson } from "./http.ts";
import type { BaseCtx } from "./routes/route.ts";
import { proxyHeaders } from "../util/http-proxy.ts";
@@ -74,14 +72,7 @@ function responseHeaders(headers: Record<string, string> | undefined): Record<st
return proxyHeaders(headers ?? {}, ["content-encoding", "content-length"]);
}
-function capabilityFrom(ctx: BaseCtx): Promise<CapabilityClaims | null> {
- const token = headerValue(ctx.req, CAPABILITY_HEADER);
- const capSecret = ctx.deps.capabilitySecret ?? ctx.secret;
- return token && capSecret ? verifyCapabilityToken(token, capSecret) : Promise.resolve(null);
-}
-
-function recordDenied(ctx: BaseCtx, claims: CapabilityClaims | null, slug: string, host: string, code: string): void {
- if (!claims) return;
+function recordDenied(ctx: BaseCtx, claims: CapabilityClaims, slug: string, host: string, code: string): void {
ctx.deps.credentialUsage?.record({
slug,
host,
@@ -102,7 +93,7 @@ function recordDenied(ctx: BaseCtx, claims: CapabilityClaims | null, slug: strin
function sendDenied(
ctx: BaseCtx,
- claims: CapabilityClaims | null,
+ claims: CapabilityClaims,
status: number,
code: string,
message: string,
@@ -129,52 +120,11 @@ export async function brokerGitHttp(ctx: BaseCtx): Promise<void> {
}
if (!ctx.deps.serviceCreds) return sendJson(ctx.res, 404, { error: "not_found" });
- const claims = await capabilityFrom(ctx);
- if (!claims)
- return sendJson(ctx.res, 401, { error: "unauthorized", message: "credential-broker capability token required" });
- if (ctx.deps.identity) {
- await ctx.deps.identity.refresh();
- if (ctx.deps.identity.classify(claims.actorId).type !== "internal") {
- return sendJson(ctx.res, 401, { error: "unauthorized", message: "principal is no longer active" });
- }
- }
- if (claims.aud !== CREDENTIAL_BROKER_AUD) {
- return sendJson(ctx.res, 403, {
- error: "forbidden",
- message: "git credential broker requires a credential-broker capability token",
- });
- }
- if (
- !(claims.externalSlack
- ? await externalSlackCapabilityAllowed(claims, ctx.deps)
- : await ctx.app.authorizesCapabilityScope({
- actorId: claims.actorId,
- scopeId: claims.scopeId,
- ...(claims.scopeVersion ? { scopeVersion: claims.scopeVersion } : {}),
- ...(claims.botActor ? { botActor: true } : {}),
- ...(claims.liveActor ? { liveActor: true } : {}),
- ...(claims.members ? { members: claims.members } : {}),
- }))
- ) {
- return sendJson(ctx.res, 403, { error: "forbidden", message: "capability scope membership has been revoked" });
- }
- if (!Array.isArray(claims.credentials) || !claims.credentials.includes(slug)) {
- return sendDenied(ctx, claims, 403, "not_entitled", "this session is not entitled to that credential", slug, "");
- }
-
- const orgScope = makeScopeId("org", configOrgId());
- const rec = await ctx.deps.serviceCreds.getServiceCredentialSecret(orgScope, slug);
- if (!rec || !rec.enabled || rec.delivery === "env") {
- return sendDenied(
- ctx,
- claims,
- 404,
- "credential_unavailable",
- "credential not found or disabled",
- slug,
- rec?.host ?? "",
- );
- }
+ const claims = ctx.capability;
+ if (!claims) return sendJson(ctx.res, 401, { error: "unauthorized" });
+ const grant = await grantedCredential(claims, slug, ctx.deps.serviceCreds, makeScopeId("org", configOrgId()));
+ if (!grant.rec) return sendDenied(ctx, claims, grant.status, grant.code, grant.message, slug, grant.host);
+ const { rec } = grant;
const methods = (rec.allowedMethods && rec.allowedMethods.length ? rec.allowedMethods : ["GET"]).map((m) =>
m.toUpperCase(),
);
diff --git a/src/api/routes/index.ts b/src/api/routes/index.ts
index e3886281c..598ee3e06 100644
--- a/src/api/routes/index.ts
+++ b/src/api/routes/index.ts
@@ -68,11 +68,6 @@ export const rawRoutes: ReadonlyArray<Route<BaseCtx>> = [
},
},
...slackEventRawRoutes,
- {
- match: (m, p) => (m === "GET" || m === "POST") && p.startsWith(GIT_HTTP_BROKER_PREFIX),
- auth: { aud: "credential-broker" },
- handle: brokerGitHttp,
- },
{ match: (_m, p) => p.startsWith(GIT_HTTP_BROKER_PREFIX), auth: { aud: "credential-broker" }, handle: brokerGitHttp },
...connectorRawRoutes,
...deploymentRawRoutes,
diff --git a/src/api/routes/route.ts b/src/api/routes/route.ts
index 6862dd6ab..542b08740 100644
--- a/src/api/routes/route.ts
+++ b/src/api/routes/route.ts
@@ -20,6 +20,7 @@ export interface BaseCtx {
pathname: string;
method: string;
params: Record<string, string>;
+ capability?: CapabilityClaims | null;
}
export interface ApiCtx extends BaseCtx {
diff --git a/src/api/server.ts b/src/api/server.ts
index 9291420da..948facbda 100644
--- a/src/api/server.ts
+++ b/src/api/server.ts
@@ -178,83 +178,101 @@ declare module "fastify" {
const rawBodies = new WeakMap<IncomingMessage, string>();
+async function verifyCapability(
+ req: IncomingMessage,
+ res: ServerResponse,
+ { app, deps, secret }: Wiring,
+ method: string,
+ pathname: string,
+ requiredAud: string | null,
+): Promise<CapabilityClaims | null> {
+ const capToken = capabilityFromHeaders(req);
+ if (!capToken) {
+ sendJson(res, 401, { error: "unauthorized", message: `${requiredAud} capability token required` });
+ return null;
+ }
+ const capSecret = deps.capabilitySecret ?? secret;
+ const capability = capSecret ? await verifyCapabilityToken(capToken, capSecret) : null;
+ if (!capability) {
+ sendJson(res, 401, { error: "unauthorized", message: "invalid or expired capability token" });
+ return null;
+ }
+ if (
+ capability.externalSlack &&
+ !(
+ capability.aud === "credential-broker" &&
+ ((method === "POST" && pathname === "/v1/credentials/broker") ||
+ ((method === "GET" || method === "POST") && pathname.startsWith("/v1/credentials/git/")))
+ )
+ ) {
+ sendJson(res, 403, { error: "forbidden", message: "This operation requires a private conversation." });
+ return null;
+ }
+ if (deps.identity) {
+ await deps.identity.refresh();
+ if (deps.identity.classify(capability.actorId).type !== "internal") {
+ sendJson(res, 401, { error: "unauthorized", message: "principal is no longer active" });
+ return null;
+ }
+ }
+ if (capability.deployment !== undefined) {
+ const deployment = await app.getDeployment(capability.deployment);
+ if (
+ !deployment ||
+ deployment.id !== capability.deployment ||
+ deployment.status !== "running" ||
+ deployment.createdBy !== capability.actorId
+ ) {
+ sendJson(res, 401, { error: "unauthorized", message: "the published app behind this token is not running" });
+ return null;
+ }
+ }
+ if (
+ !(capability.externalSlack
+ ? await externalSlackCapabilityAllowed(capability, deps)
+ : await app.authorizesCapabilityScope({
+ actorId: capability.actorId,
+ scopeId: capability.scopeId,
+ ...(capability.scopeVersion ? { scopeVersion: capability.scopeVersion } : {}),
+ ...(capability.botActor ? { botActor: true } : {}),
+ ...(capability.liveActor ? { liveActor: true } : {}),
+ ...(capability.members ? { members: capability.members } : {}),
+ }))
+ ) {
+ sendJson(res, 403, { error: "forbidden", message: "capability scope membership has been revoked" });
+ return null;
+ }
+ if (requiredAud && capability.aud !== requiredAud) {
+ sendJson(res, 403, {
+ error: "forbidden",
+ message: `this route requires a capability token with audience "${requiredAud}"`,
+ });
+ return null;
+ }
+ return capability;
+}
+
async function gate(
req: IncomingMessage,
res: ServerResponse,
- { app, deps, secret, auth, requirePortalIdentity, allowUnsignedSourceAuth }: Wiring,
+ wiring: Wiring,
method: string,
pathname: string,
url: URL,
raw: string,
routeAuth: RouteAuth | undefined,
): Promise<GateResult | null> {
+ const { deps, secret, auth, requirePortalIdentity, allowUnsignedSourceAuth } = wiring;
const isPublicRoute = routeAuth === "public";
const requiredAud = typeof routeAuth === "object" ? routeAuth.aud : null;
let capability: CapabilityClaims | null = null;
const capToken = capabilityFromHeaders(req);
if (isPublicRoute) {
void isPublicRoute;
- } else if (capToken) {
- const capSecret = deps.capabilitySecret ?? secret;
- capability = capSecret ? await verifyCapabilityToken(capToken, capSecret) : null;
- if (!capability) {
- sendJson(res, 401, { error: "unauthorized", message: "invalid or expired capability token" });
- return null;
- }
- if (
- capability.externalSlack &&
- !(
- capability.aud === "credential-broker" &&
- ((method === "POST" && pathname === "/v1/credentials/broker") ||
- ((method === "GET" || method === "POST") && pathname.startsWith("/v1/credentials/git/")))
- )
- ) {
- sendJson(res, 403, { error: "forbidden", message: "This operation requires a private conversation." });
- return null;
- }
- if (deps.identity) {
- await deps.identity.refresh();
- if (deps.identity.classify(capability.actorId).type !== "internal") {
- sendJson(res, 401, { error: "unauthorized", message: "principal is no longer active" });
- return null;
- }
- }
- if (capability.deployment !== undefined) {
- const deployment = await app.getDeployment(capability.deployment);
- if (
- !deployment ||
- deployment.id !== capability.deployment ||
- deployment.status !== "running" ||
- deployment.createdBy !== capability.actorId
- ) {
- sendJson(res, 401, { error: "unauthorized", message: "the published app behind this token is not running" });
- return null;
- }
- }
- if (
- !(capability.externalSlack
- ? await externalSlackCapabilityAllowed(capability, deps)
- : await app.authorizesCapabilityScope({
- actorId: capability.actorId,
- scopeId: capability.scopeId,
- ...(capability.scopeVersion ? { scopeVersion: capability.scopeVersion } : {}),
- ...(capability.botActor ? { botActor: true } : {}),
- ...(capability.liveActor ? { liveActor: true } : {}),
- ...(capability.members ? { members: capability.members } : {}),
- }))
- ) {
- sendJson(res, 403, { error: "forbidden", message: "capability scope membership has been revoked" });
- return null;
- }
- if (requiredAud) {
- if (capability.aud !== requiredAud) {
- sendJson(res, 403, {
- error: "forbidden",
- message: `this route requires a capability token with audience "${requiredAud}"`,
- });
- return null;
- }
- } else if (routeAuth === "either") {
+ } else if (requiredAud || capToken) {
+ capability = await verifyCapability(req, res, wiring, method, pathname, requiredAud);
+ if (!capability) return null;
+ if (routeAuth === "either") {
if (capability.aud !== undefined && capability.aud !== CONTROL_PLANE_AUD) {
sendJson(res, 403, { error: "forbidden", message: "capability token audience not valid for this route" });
return null;
@@ -266,13 +284,10 @@ async function gate(
return null;
}
}
- } else {
+ } else if (!requiredAud) {
sendJson(res, 403, { error: "forbidden", message: "capability token not valid for this route" });
return null;
}
- } else if (requiredAud) {
- sendJson(res, 401, { error: "unauthorized", message: `${requiredAud} capability token required` });
- return null;
} else if (
!(await verifyOrReject(
req,
@@ -557,6 +572,11 @@ function buildServer(app: App, deps: ServerOptions, allowUnsignedSourceAuth: boo
const raw = findRoute(rawRoutes, base.method, base.pathname);
if (raw) {
if ("path" in raw.route) requestNames.set(req, raw.route.path);
+ const routeAuth = raw.route.auth;
+ if (typeof routeAuth === "object") {
+ base.capability = await verifyCapability(req, res, wiring, base.method, base.pathname, routeAuth.aud);
+ if (!base.capability) return void req.resume();
+ }
await run(raw.route, raw.params, base);
return;
}
diff --git a/test/deployment-token-gate.test.ts b/test/deployment-token-gate.test.ts
index 4b5af295c..f1fa93095 100644
--- a/test/deployment-token-gate.test.ts
+++ b/test/deployment-token-gate.test.ts
@@ -1,10 +1,13 @@
import { after, before, describe, it } from "node:test";
import assert from "node:assert/strict";
+import { Readable } from "node:stream";
import type { Server } from "node:http";
import type { AddressInfo } from "node:net";
import { createServer } from "../src/api/server.ts";
import type { App } from "../src/api/app.ts";
+import type { ServerDeps } from "../src/api/deps.ts";
import {
+ CONTROL_PLANE_AUD,
CREDENTIAL_BROKER_AUD,
DEPLOYMENT_CREDENTIAL_TTL_MS,
mintCapabilityToken,
@@ -14,9 +17,13 @@ import { personalScope } from "../src/types.ts";
const SECRET = "deployment-token-gate-secret".repeat(2);
-describe("a published app's broker token follows the app it was minted for", () => {
+describe("a published app's broker token follows the app it was minted for, on every broker route", () => {
let server: Server;
let base: string;
+ let deploymentsAllowed = true;
+ let scopeAuthorized = true;
+ let offboarded = false;
+ const authorized: unknown[] = [];
const deployments = new Map<string, Deployment>();
const running = (id: string, createdBy = "publisher"): Deployment => ({
id,
@@ -28,12 +35,12 @@ describe("a published app's broker token follows the app it was minted for", ()
versions: [],
});
- const tokenFor = (deployment: string, actorId = "publisher") =>
+ const tokenFor = (deployment: string, actorId = "publisher", aud = CREDENTIAL_BROKER_AUD) =>
mintCapabilityToken(
{
actorId,
scopeId: personalScope(actorId),
- aud: CREDENTIAL_BROKER_AUD,
+ aud,
credentials: ["sample-api"],
deployment,
exp: Date.now() + DEPLOYMENT_CREDENTIAL_TTL_MS,
@@ -41,19 +48,52 @@ describe("a published app's broker token follows the app it was minted for", ()
SECRET,
);
- const broker = async (token: string) =>
- fetch(`${base}/v1/credentials/broker`, {
- method: "POST",
- headers: { "x-agent-capability": token, "content-type": "application/json" },
- body: JSON.stringify({ credential: "sample-api", url: "https://relay.example/sample-api/me" }),
- });
+ const routes = {
+ broker: (token: string) =>
+ fetch(`${base}/v1/credentials/broker`, {
+ method: "POST",
+ headers: { "x-agent-capability": token, "content-type": "application/json" },
+ body: JSON.stringify({ credential: "sample-api", url: "https://relay.example/sample-api/me" }),
+ }),
+ git: (token: string) =>
+ fetch(`${base}/v1/credentials/git/sample-api/sample-api/repo.git/info/refs?service=git-upload-pack`, {
+ headers: { "x-agent-capability": token },
+ }),
+ };
+ const statuses = async (token: () => Promise<string>) => ({
+ broker: (await routes.broker(await token())).status,
+ git: (await routes.git(await token())).status,
+ });
before(async () => {
const app = {
- authorizesCapabilityScope: async () => true,
+ authorizesCapabilityScope: async (claims: unknown) => {
+ authorized.push(claims);
+ return scopeAuthorized;
+ },
getDeployment: async (id: string) => deployments.get(id) ?? null,
} as unknown as App;
- server = createServer(app, { signingSecret: SECRET });
+ const deps = {
+ identity: {
+ refresh: async () => {},
+ classify: () => ({ type: offboarded ? "offboarded" : "internal" }),
+ },
+ serviceCreds: {
+ getServiceCredentialSecret: async () => ({
+ slug: "sample-api",
+ name: "Sample",
+ secret: "s3cret",
+ host: "relay.example",
+ allowedMethods: ["GET", "POST"],
+ allowedPathPrefixes: ["/sample-api"],
+ enabled: true,
+ deployments: deploymentsAllowed,
+ }),
+ },
+ brokerFetch: async () => ({ status: 200, text: async () => "{}" }),
+ gitHttpFetch: async () => ({ status: 200, headers: {}, body: Readable.from(["0000"]) }),
+ } as unknown as Partial<ServerDeps>;
+ server = createServer(app, { signingSecret: SECRET, ...deps });
await new Promise<void>((resolve) => server.listen(0, resolve));
base = `http://localhost:${(server.address() as AddressInfo).port}`;
});
@@ -62,21 +102,79 @@ describe("a published app's broker token follows the app it was minted for", ()
await new Promise<void>((resolve) => server.close(() => resolve()));
});
- it("passes the gate while the app is running and reaches the broker route", async () => {
+ it("reaches upstream while the app is running and the credential is on for apps", async () => {
deployments.set("d1", running("d1"));
- const response = await broker(await tokenFor("d1"));
- assert.notEqual(response.status, 401);
- assert.notEqual(response.status, 403);
+ assert.deepEqual(await statuses(() => tokenFor("d1")), { broker: 200, git: 200 });
});
it("is refused once the app is stopped, archived or gone, and for a token whose actor is not the publisher", async () => {
+ const refused = { broker: 401, git: 401 };
deployments.set("d1", { ...running("d1"), status: "stopped" });
- assert.equal((await broker(await tokenFor("d1"))).status, 401);
+ assert.deepEqual(await statuses(() => tokenFor("d1")), refused);
deployments.set("d1", { ...running("d1"), status: "archived" });
- assert.equal((await broker(await tokenFor("d1"))).status, 401);
+ assert.deepEqual(await statuses(() => tokenFor("d1")), refused);
deployments.delete("d1");
- assert.equal((await broker(await tokenFor("d1"))).status, 401);
+ assert.deepEqual(await statuses(() => tokenFor("d1")), refused);
deployments.set("d2", running("d2", "someone-else"));
- assert.equal((await broker(await tokenFor("d2", "publisher"))).status, 401);
+ assert.deepEqual(await statuses(() => tokenFor("d2", "publisher")), refused);
+ });
+
+ it("is refused when an admin switches the credential off for published apps", async () => {
+ deployments.set("d1", running("d1"));
+ deploymentsAllowed = false;
+ try {
+ assert.deepEqual(await statuses(() => tokenFor("d1")), { broker: 403, git: 403 });
+ } finally {
+ deploymentsAllowed = true;
+ }
+ });
+
+ it("is refused without a token, with the wrong audience, and after scope membership is revoked", async () => {
+ deployments.set("d1", running("d1"));
+ assert.equal((await fetch(`${base}/v1/credentials/git/sample-api/sample-api/repo.git/info/refs`)).status, 401);
+ assert.deepEqual(await statuses(() => tokenFor("d1", "publisher", CONTROL_PLANE_AUD)), { broker: 403, git: 403 });
+ scopeAuthorized = false;
+ try {
+ assert.deepEqual(await statuses(() => tokenFor("d1")), { broker: 403, git: 403 });
+ } finally {
+ scopeAuthorized = true;
+ }
+ });
+
+ it("is refused once the publisher is offboarded", async () => {
+ deployments.set("d1", running("d1"));
+ offboarded = true;
+ try {
+ assert.deepEqual(await statuses(() => tokenFor("d1")), { broker: 401, git: 401 });
+ } finally {
+ offboarded = false;
+ }
+ });
+
+ it("checks scope membership with the token's bot and member claims on both routes", async () => {
+ const token = () =>
+ mintCapabilityToken(
+ {
+ actorId: "B1",
+ scopeId: "channel:C1",
+ aud: CREDENTIAL_BROKER_AUD,
+ credentials: ["sample-api"],
+ botActor: true,
+ liveActor: true,
+ members: [{ id: "B1", type: "internal" }],
+ exp: Date.now() + DEPLOYMENT_CREDENTIAL_TTL_MS,
+ },
+ SECRET,
+ );
+ authorized.length = 0;
+ assert.deepEqual(await statuses(token), { broker: 200, git: 200 });
+ const expected = {
+ actorId: "B1",
+ scopeId: "channel:C1",
+ botActor: true,
+ liveActor: true,
+ members: [{ id: "B1", type: "internal" }],
+ };
+ assert.deepEqual(authorized, [expected, expected]);
});
});
diff --git a/test/external-slack-core.test.ts b/test/external-slack-core.test.ts
index b39e9e2ca..c8155a746 100644
--- a/test/external-slack-core.test.ts
+++ b/test/external-slack-core.test.ts
@@ -1,6 +1,7 @@
import { externalSlackNamespace } from "../src/slack/external-access.ts";
import "./support/auto-fake-sprites.ts";
import { test } from "node:test";
+import { Readable } from "node:stream";
import assert from "node:assert/strict";
import { buildApp } from "../src/wiring.ts";
import { testConfig, TEST_CAPABILITY_SECRET } from "./support/test-config.ts";
@@ -280,6 +281,10 @@ test("external sandbox API token cannot reach private APIs, while its safe broke
forwarded++;
return { status: 200, contentType: "application/json", text: async () => '{"public":"ok"}' };
},
+ gitHttpFetch: async () => {
+ forwarded++;
+ return { status: 200, headers: {}, body: Readable.from(["0000"]) };
+ },
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
t.after(() => new Promise<void>((resolve) => server.close(() => resolve())));
@@ -309,14 +314,19 @@ test("external sandbox API token cannot reach private APIs, while its safe broke
headers: { "x-agent-capability": token, "content-type": "application/json" },
body: JSON.stringify({ credential: "safe", url: "https://public.example/data", method: "GET" }),
});
+ const git = (token: string) =>
+ fetch(`${base}/v1/credentials/git/safe/repo.git/info/refs`, { headers: { "x-agent-capability": token } });
assert.equal((await call(control)).status, 403);
+ assert.equal((await git(control)).status, 403);
const success = await call(broker);
assert.equal(success.status, 200, await success.text());
- assert.equal(forwarded, 1);
+ assert.equal((await git(broker)).status, 200);
+ assert.equal(forwarded, 2);
externalSlackPolicies.batch = { ...policy, serviceCredentials: [] };
try {
assert.equal((await call(broker)).status, 403);
- assert.equal(forwarded, 1);
+ assert.equal((await git(broker)).status, 403);
+ assert.equal(forwarded, 2);
} finally {
externalSlackPolicies.batch = policy;
}
diff --git a/test/git-http-broker.test.ts b/test/git-http-broker.test.ts
index c79363e64..a7974464b 100644
--- a/test/git-http-broker.test.ts
+++ b/test/git-http-broker.test.ts
@@ -4,23 +4,10 @@ import { Readable, PassThrough } from "node:stream";
import { finished } from "node:stream/promises";
import type { IncomingMessage, ServerResponse } from "node:http";
import { brokerGitHttp } from "../src/api/git-http-broker.ts";
-import {
- CAPABILITY_TTL_MS,
- CREDENTIAL_BROKER_AUD,
- CONTROL_PLANE_AUD,
- mintCapabilityToken,
-} from "../src/auth/capability-token.ts";
+import { CAPABILITY_TTL_MS, CREDENTIAL_BROKER_AUD } from "../src/auth/capability-token.ts";
import type { BaseCtx } from "../src/api/routes/route.ts";
import type { ServerDeps } from "../src/api/deps.ts";
-const SECRET = "git-http-broker-test";
-
-const token = (credentials: string[], aud: string = CREDENTIAL_BROKER_AUD) =>
- mintCapabilityToken(
- { actorId: "U1", scopeId: "personal:U1", aud, credentials, exp: Date.now() + CAPABILITY_TTL_MS },
- SECRET,
- );
-
function req(headers: Record<string, string>, body = ""): IncomingMessage {
const r = Readable.from(body ? [body] : []) as IncomingMessage;
r.headers = headers;
@@ -47,39 +34,39 @@ async function text(r: PassThrough): Promise<string> {
return Buffer.concat(chunks).toString("utf8");
}
-async function ctx(
- path: string,
- method: string,
- deps: ServerDeps,
- body = "",
-): Promise<BaseCtx & { res: ReturnType<typeof res> }> {
+function ctx(path: string, method: string, deps: ServerDeps, body = ""): BaseCtx & { res: ReturnType<typeof res> } {
const url = new URL(path, "http://core.test");
const out = res();
return {
req: req(
{
- "x-agent-capability": await token(["gitlab"]),
"content-type": "application/x-git-receive-pack-request",
"git-protocol": "version=2",
},
body,
),
res: out,
- app: { authorizesCapabilityScope: async () => true } as unknown as BaseCtx["app"],
+ app: {} as BaseCtx["app"],
deps,
- secret: SECRET,
+ secret: "git-http-broker-test",
auth: null,
allowUnsignedSourceAuth: false,
url,
pathname: url.pathname,
method,
params: {},
+ capability: {
+ actorId: "U1",
+ scopeId: "personal:U1",
+ aud: CREDENTIAL_BROKER_AUD,
+ credentials: ["gitlab"],
+ exp: Date.now() + CAPABILITY_TTL_MS,
+ },
};
}
test("git HTTP broker streams a smart-HTTP request through the pinned service credential", async () => {
let seen: { url: string; method: string; headers: Record<string, string>; body: string } | undefined;
- let authorized: unknown;
const deps: ServerDeps = {
control: {} as ServerDeps["control"],
serviceCreds: {
@@ -106,35 +93,11 @@ test("git HTTP broker streams a smart-HTTP request through the pinned service cr
};
},
};
- const c = await ctx("/v1/credentials/git/gitlab/acme/repo.git/git-receive-pack", "POST", deps, "PACK");
- c.req.headers["x-agent-capability"] = await mintCapabilityToken(
- {
- actorId: "B-LEGACY",
- scopeId: "channel:C1",
- aud: CREDENTIAL_BROKER_AUD,
- credentials: ["gitlab"],
- botActor: true,
- liveActor: true,
- members: [{ id: "B-LEGACY", type: "internal" }],
- exp: Date.now() + CAPABILITY_TTL_MS,
- },
- SECRET,
- );
- c.app.authorizesCapabilityScope = async (claims) => {
- authorized = claims;
- return true;
- };
+ const c = ctx("/v1/credentials/git/gitlab/acme/repo.git/git-receive-pack", "POST", deps, "PACK");
await brokerGitHttp(c);
assert.equal(await text(c.res), "0000");
assert.equal(c.res.statusCode, 200);
- assert.deepEqual(authorized, {
- actorId: "B-LEGACY",
- scopeId: "channel:C1",
- botActor: true,
- liveActor: true,
- members: [{ id: "B-LEGACY", type: "internal" }],
- });
assert.equal(c.res.capturedHeaders?.["content-type"], "application/x-git-receive-pack-result");
assert.deepEqual(seen, {
url: "https://gitlab.example/acme/repo.git/git-receive-pack",
@@ -148,60 +111,6 @@ test("git HTTP broker streams a smart-HTTP request through the pinned service cr
});
});
-test("git HTTP broker rejects the wrong audience before contacting upstream", async () => {
- const deps: ServerDeps = {
- control: {} as ServerDeps["control"],
- serviceCreds: {
- getServiceCredentialSecret: async () => {
- throw new Error("must not fetch credential");
- },
- } as unknown as ServerDeps["serviceCreds"],
- };
- const c = await ctx("/v1/credentials/git/gitlab/acme/repo.git/info/refs", "GET", deps);
- c.req.headers["x-agent-capability"] = await token(["gitlab"], CONTROL_PLANE_AUD);
- await brokerGitHttp(c);
-
- assert.equal(c.res.statusCode, 403);
- assert.match(await text(c.res), /credential-broker/);
-});
-
-test("git HTTP broker rejects a token whose principal is no longer active", async () => {
- const deps: ServerDeps = {
- control: {} as ServerDeps["control"],
- identity: {
- refresh: async () => {},
- classify: () => ({ type: "offboarded" }),
- } as unknown as ServerDeps["identity"],
- serviceCreds: {
- getServiceCredentialSecret: async () => {
- throw new Error("must not fetch credential");
- },
- } as unknown as ServerDeps["serviceCreds"],
- };
- const c = await ctx("/v1/credentials/git/gitlab/acme/repo.git/info/refs", "GET", deps);
- await brokerGitHttp(c);
-
- assert.equal(c.res.statusCode, 401);
- assert.match(await text(c.res), /no longer active/);
-});
-
-test("git HTTP broker rejects a capability whose current scope membership was revoked", async () => {
- const deps: ServerDeps = {
- control: {} as ServerDeps["control"],
- serviceCreds: {
- getServiceCredentialSecret: async () => {
- throw new Error("must not fetch credential");
- },
- } as unknown as ServerDeps["serviceCreds"],
- };
- const c = await ctx("/v1/credentials/git/gitlab/acme/repo.git/info/refs", "GET", deps);
- c.app.authorizesCapabilityScope = async () => false;
- await brokerGitHttp(c);
-
- assert.equal(c.res.statusCode, 403);
- assert.match(await text(c.res), /membership has been revoked/);
-});
-
test("git HTTP broker refuses an env-delivery record like a missing credential", async () => {
let fetched = false;
const deps: ServerDeps = {
@@ -222,7 +131,7 @@ test("git HTTP broker refuses an env-delivery record like a missing credential",
return { status: 200, headers: {}, body: Readable.from(["0000"]) };
},
};
- const c = await ctx("/v1/credentials/git/gitlab/acme/repo.git/info/refs?service=git-upload-pack", "GET", deps);
+ const c = ctx("/v1/credentials/git/gitlab/acme/repo.git/info/refs?service=git-upload-pack", "GET", deps);
await brokerGitHttp(c);
assert.equal(c.res.statusCode, 404);
assert.equal(fetched, false, "no upstream git fetch happens");
@@ -254,7 +163,7 @@ test("git HTTP broker refuses encoded parent traversal past the repo path", asyn
return { status: 200, headers: {}, body: Readable.from(["0000"]) };
},
};
- const c = await ctx(path, "GET", deps);
+ const c = ctx(path, "GET", deps);
await brokerGitHttp(c);
assert.equal(c.res.statusCode, 403, path);
assert.match(await text(c.res), /path_not_allowed/);
@@ -283,7 +192,7 @@ test("git HTTP broker cannot use a Composio key for project-wide discovery or ex
throw new Error("must not contact upstream");
},
} as unknown as ServerDeps;
- const c = await ctx("/v1/credentials/git/gitlab/api/v3.1/connected_accounts", method, deps);
+ const c = ctx("/v1/credentials/git/gitlab/api/v3.1/connected_accounts", method, deps);
await brokerGitHttp(c);
await text(c.res);
assert.equal(c.res.statusCode, 403);
diff --git a/test/route-auth-conformance.test.ts b/test/route-auth-conformance.test.ts
index ab7ad6405..ee431fa5c 100644
--- a/test/route-auth-conformance.test.ts
+++ b/test/route-auth-conformance.test.ts
@@ -71,7 +71,7 @@ test("every pinned dedicated-audience route actually resolves in the table", ()
}
});
-test("raw routes keep their declared auth contracts (they self-enforce, so the declaration is the pin)", () => {
+test("raw routes keep their declared auth contracts (front enforces capability audiences, handlers enforce the rest)", () => {
const pins: Array<[string, string, RouteAuth]> = [
["GET", "/healthz", "public"],
["GET", "/readyz", "public"],