Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

(#515)

Regan Bell87e27032ab8c
diff --git a/.env.example b/.env.example
index 60c039600..766001511 100644
--- a/.env.example
+++ b/.env.example
@@ -23,3 +23,6 @@ RATE_LIMIT_WINDOW_MS=60000
BUDGET_USD_PER_WINDOW=25
ORG_BUDGET_USD_PER_WINDOW=100
BUDGET_WINDOW_MS=86400000
+
+# Extra root CA (PEM content) trusted for the Postgres connection, for providers that pin a private root. Optional; verification stays on. (core)
+# DATABASE_CA_CERT=
diff --git a/cli/package.json b/cli/package.json
index 2bb3a343b..cf24c1d6e 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@yc-software/qm",
- "version": "0.1.8",
+ "version": "0.1.9",
"license": "MIT",
"description": "Control-plane CLI for portable QM deployments on Docker, Fly, and AWS.",
"type": "module",
diff --git a/cli/src/secrets.ts b/cli/src/secrets.ts
index 2c303ec83..cfa187cc5 100644
--- a/cli/src/secrets.ts
+++ b/cli/src/secrets.ts
@@ -146,6 +146,13 @@ export const FIRST_PARTY_SECRET_SPECS: readonly SecretSpec[] = [
description: "Postgres connection string for durable state.",
managedBy: "terraform",
},
+ {
+ name: "DATABASE_CA_CERT",
+ service: "core",
+ required: false,
+ description:
+ "Extra root CA (PEM content) trusted for the Postgres connection, for providers that pin a private root (e.g. Supabase's pooler). Verification stays on.",
+ },
{
name: "AWS_DEPLOY_GATE_SECRET",
service: "core",
diff --git a/deploy/stacks/acme/.env.example b/deploy/stacks/acme/.env.example
index c58163ded..fe1c0c709 100644
--- a/deploy/stacks/acme/.env.example
+++ b/deploy/stacks/acme/.env.example
@@ -59,6 +59,9 @@ SKILL_SIGNING_SECRET=
# Postgres connection string for durable state. (core)
# Needed when the target is aws.
# DATABASE_URL= # populated by Terraform
+# Extra root CA (PEM content) trusted for the Postgres connection, for providers that pin a private root. Optional; verification stays on. (core)
+# DATABASE_CA_CERT=
+
# HMAC key protecting public AWS deployment-app URLs. (core)
# Needed when env.core.AWS_DEPLOY_APPS_DOMAIN is set.
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index 4ff05eeab..0b702885e 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -244,6 +244,7 @@ const FAMILIES: AgentApiFamily[] = [
(m === "GET" && p === "/v1/deployments") ||
(m === "GET" && /^\/v1\/deployments\/[^/]+$/.test(p)) ||
(m === "GET" && /^\/v1\/deployments\/[^/]+\/fetch$/.test(p)) ||
+ (m === "GET" && /^\/v1\/deployments\/[^/]+\/logs$/.test(p)) ||
(m === "GET" && /^\/v1\/deployments\/[^/]+\/git-url$/.test(p)) ||
(m === "POST" && /^\/v1\/deployments\/[^/]+\/(share|archive|restore|name|display-name)$/.test(p)),
guidance:
@@ -267,6 +268,12 @@ const FAMILIES: AgentApiFamily[] = [
summary:
"read a deployment's rendered content as the asking person — query path defaults to / and maxBytes defaults to 256KB; returns upstream status, contentType, body, and truncation metadata",
},
+ {
+ method: "GET",
+ path: "/v1/deployments/:id/logs",
+ summary:
+ "recent runtime output (entrypoint stdout+stderr) of a running deployment you can reach — query tailLines (default 200, max 2000); returns {logs} (null when the provider keeps none)",
+ },
{
method: "GET",
path: "/v1/deployments/:id/git-url",
diff --git a/src/api/app-deployments.ts b/src/api/app-deployments.ts
index 74f214df6..60bf0ff0c 100644
--- a/src/api/app-deployments.ts
+++ b/src/api/app-deployments.ts
@@ -26,6 +26,7 @@ export function createDeploymentMethods(
| "renameDeployment"
| "setDeploymentDisplayName"
| "reachDeployment"
+ | "deploymentLogsFor"
| "deploymentGitRepoPath"
| "runDeploymentGitPush"
| "deploymentGitUrlFor"
@@ -98,6 +99,16 @@ export function createDeploymentMethods(
if (!(await principalCanReadDeployment(deployment, principalId))) return { status: "denied" };
return deps.deploy.reachDeployment(id, principalId, { bypassAcl: true });
},
+ async deploymentLogsFor(
+ id,
+ principalId,
+ opts,
+ ): Promise<{ status: "ok"; logs: string | null } | { status: "not_found" | "denied" }> {
+ const deployment = await deps.deploy.getDeployment(id);
+ if (!deployment) return { status: "not_found" };
+ if (!(await principalCanReadDeployment(deployment, principalId))) return { status: "denied" };
+ return { status: "ok", logs: await deps.deploy.deploymentLogs(id, opts) };
+ },
deploymentGitRepoPath(id) {
return deps.deploy.gitRepoPath(id);
},
diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.ts
index d77f39bee..c0a398930 100644
--- a/src/api/app-sessions.ts
+++ b/src/api/app-sessions.ts
@@ -1,7 +1,7 @@
import type { PendingApprovalRecord } from "../types.ts";
import { orgId as orgIdOf } from "../config.ts";
import { parseScopeId, scopeId } from "../types.ts";
-import { fileArtifactId } from "../files/file-artifact-store.ts";
+import { fileArtifactId, artifactPath } from "../files/file-artifact-store.ts";
import { transcriptEntries, windowedTranscript } from "../sessions/session-store.ts";
import { SEARCH_HIT_LIMIT, searchSnippet, searchTerms } from "../sessions/entry-search.ts";
import { supportsProcessSessions } from "../sandbox/sandbox.ts";
@@ -117,7 +117,7 @@ export function createSessionMethods(
const name = safeAttachmentName(input.name);
const mimetype = (input.mimetype ?? mimeFromName(name)).split(";")[0]!.trim().toLowerCase() || mimeFromName(name);
const id = fileArtifactId(`upload:${principalId}:${createdInScope}:${Date.now()}:${randomUUID()}`, "in", 0);
- const path = `artifacts/${id}/${name}`;
+ const path = artifactPath(id, name);
const { artifact } = await deps.files.put({
id,
ownerScopeId,
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index fcfb52cc8..cc74593a8 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -454,6 +454,11 @@ export interface App {
renameDeployment(id: string, name: string): Promise<Deployment>;
setDeploymentDisplayName(id: string, displayName: string): Promise<Deployment>;
reachDeployment(id: string, principalId: string, opts?: ReachOptions): Promise<Reach>;
+ deploymentLogsFor(
+ id: string,
+ principalId: string,
+ opts: { tailLines: number },
+ ): Promise<{ status: "ok"; logs: string | null } | { status: "not_found" | "denied" }>;
shareDeployment(
idOrName: string,
grantee: ScopeId,
diff --git a/src/api/routes/deployments.ts b/src/api/routes/deployments.ts
index ffeb8d846..5934fdce3 100644
--- a/src/api/routes/deployments.ts
+++ b/src/api/routes/deployments.ts
@@ -1201,6 +1201,27 @@ function textContentType(contentType: string): boolean {
);
}
+const LOGS_DEFAULT_TAIL_LINES = 200;
+const LOGS_MAX_TAIL_LINES = 2000;
+
+async function deploymentLogs(ctx: ApiCtx): Promise<void> {
+ const { res, app, params, capability, actor, url } = ctx;
+ const viewer = capability?.actorId ?? actor?.p;
+ if (!viewer) return sendJson(res, 401, { error: "capability_required" });
+ const rawTail = url.searchParams.get("tailLines");
+ const tailLines = rawTail === null ? LOGS_DEFAULT_TAIL_LINES : Number(rawTail);
+ if (!Number.isInteger(tailLines) || tailLines < 1 || tailLines > LOGS_MAX_TAIL_LINES) {
+ return sendJson(res, 400, {
+ error: "bad_request",
+ message: `tailLines must be an integer from 1 to ${LOGS_MAX_TAIL_LINES}`,
+ });
+ }
+ const result = await app.deploymentLogsFor(params.id!, viewer, { tailLines });
+ if (result.status !== "ok") return sendJson(res, 404, { error: "not_found" });
+ if (result.logs === null) return sendJson(res, 200, { logs: null, message: "no logs available for this deployment" });
+ return sendJson(res, 200, { logs: result.logs });
+}
+
async function fetchDeployment(ctx: ApiCtx): Promise<void> {
const { res, app, params, capability, actor, url } = ctx;
const viewer = capability?.actorId ?? actor?.p;
@@ -1444,6 +1465,7 @@ export const deploymentRoutes: ReadonlyArray<Route<ApiCtx>> = [
{ method: "GET", path: "/v1/deployments", auth: "either", handle: listDeployments },
{ method: "GET", path: "/v1/deployments/:id", auth: "either", handle: getDeployment },
{ method: "GET", path: "/v1/deployments/:id/fetch", auth: "either", handle: fetchDeployment },
+ { method: "GET", path: "/v1/deployments/:id/logs", auth: "either", handle: deploymentLogs },
{ method: "GET", path: "/v1/deployments/:id/git-url", auth: "either", handle: deploymentGitUrl },
{ method: "GET", path: "/v1/deployments/:id/owner-url", auth: "source", handle: deploymentOwnerUrl },
{ method: "POST", path: "/v1/deployments/:id/share", auth: "either", handle: shareDeployment },
diff --git a/src/config.ts b/src/config.ts
index 43a226617..7c04ebd22 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -29,6 +29,8 @@ export interface Config {
orgId: string;
sessionStore: "memory" | "postgres";
databaseUrl?: string;
+ databaseCaCert?: string;
+ databaseCaCertFile?: string;
harness: "mock" | "pi" | "opencode" | "codex" | "claude";
securityPosture: SecurityPosture;
sandboxBackend: "aws" | "local" | "sprites" | "smolmachines";
@@ -729,6 +731,8 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
orgId: env.ORG_ID ?? DEFAULT_ORG_ID,
sessionStore: env.SESSION_STORE === "postgres" ? "postgres" : "memory",
...(env.DATABASE_URL ? { databaseUrl: env.DATABASE_URL } : {}),
+ ...(env.DATABASE_CA_CERT ? { databaseCaCert: env.DATABASE_CA_CERT } : {}),
+ ...(env.DATABASE_CA_CERT_FILE ? { databaseCaCertFile: env.DATABASE_CA_CERT_FILE } : {}),
harness: harnessEnvStrict(env.HARNESS),
securityPosture: securityPostureEnvStrict(env.HARNESS_SECURITY_POSTURE),
securityScreenBackend,
diff --git a/src/deploy/aws-deploy-provider.ts b/src/deploy/aws-deploy-provider.ts
index 1f3b328a7..9fb941421 100644
--- a/src/deploy/aws-deploy-provider.ts
+++ b/src/deploy/aws-deploy-provider.ts
@@ -651,6 +651,21 @@ export function createAwsDeployProvider(opts: AwsDeployProviderOptions): DeployP
return resolve;
},
+ async logs(d, opts): Promise<string | null> {
+ ensureConfigured();
+ const stored = await store.get(d.id);
+ if (!stored) return null;
+ await ensureRunning(stored.microvmId, stored.endpoint);
+ const lines = Math.max(1, Math.min(2000, Math.floor(opts.tailLines)));
+ const r = await execRaw(
+ stored.microvmId,
+ stored.endpoint,
+ `tail -n ${lines} ${shq(LOG_PATH)} 2>/dev/null || true`,
+ 30,
+ );
+ return r.stdout;
+ },
+
async destroy(d): Promise<void> {
bumpResolveGen(d.id);
const stored = await store.get(d.id);
diff --git a/src/deploy/deploy-provider.ts b/src/deploy/deploy-provider.ts
index 7178d7181..e9b41c035 100644
--- a/src/deploy/deploy-provider.ts
+++ b/src/deploy/deploy-provider.ts
@@ -21,4 +21,6 @@ export interface DeployProvider {
reconcile?(d: Deployment, version: DeploymentVersion, input: DeployReconcileInput): Promise<DeployEndpoint>;
destroy(d: Deployment): Promise<void>;
resolveEndpoint?(d: Deployment, version: DeploymentVersion): Promise<DeployEndpoint | null>;
+ /** Recent output from the running app (entrypoint stdout+stderr), newest last. */
+ logs?(d: Deployment, opts: { tailLines: number }): Promise<string | null>;
}
diff --git a/src/deploy/deploy-service.ts b/src/deploy/deploy-service.ts
index a69284335..674e9badb 100644
--- a/src/deploy/deploy-service.ts
+++ b/src/deploy/deploy-service.ts
@@ -73,6 +73,8 @@ export interface DeployService {
renameDeployment(id: string, name: string): Promise<Deployment>;
setDeploymentDisplayName(id: string, displayName: string): Promise<Deployment>;
reachDeployment(idOrName: string, principalId: string, opts?: ReachOptions): Promise<Reach>;
+ /** Recent app output (entrypoint stdout+stderr) for a deployment, newest last; null when the provider keeps none. */
+ deploymentLogs(idOrName: string, opts: { tailLines: number }): Promise<string | null>;
gitRepoPath(idOrName: string): Promise<string | null>;
pushGit<T>(id: string, runReceivePack: () => Promise<{ result: T; ok: boolean }>): Promise<T>;
reapIdleDeployments(ttlMs: number, now?: number): Promise<number>;
@@ -499,6 +501,13 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
return { status: "ok", endpoint };
},
+ async deploymentLogs(idOrName, opts): Promise<string | null> {
+ if (!deps.provider.logs) return null;
+ const d = (await deps.deployStore.get(idOrName)) ?? (await deps.deployStore.getByName(idOrName));
+ if (!d || d.status !== "running") return null;
+ return deps.provider.logs(d, opts);
+ },
+
async gitRepoPath(idOrName) {
const d = (await deps.deployStore.get(idOrName)) ?? (await deps.deployStore.getByName(idOrName));
return d ? await deps.deployStore.repoUrl(d.id) : null;
diff --git a/src/deploy/docker-deploy-provider.ts b/src/deploy/docker-deploy-provider.ts
index 885b1b2a2..c8fe40527 100644
--- a/src/deploy/docker-deploy-provider.ts
+++ b/src/deploy/docker-deploy-provider.ts
@@ -78,6 +78,13 @@ export function createDockerDeployProvider(opts: DockerDeployProviderOptions = {
return { host: "127.0.0.1", port: hostPort };
},
+ async logs(d: Deployment, opts: { tailLines: number }): Promise<string | null> {
+ const lines = Math.max(1, Math.min(2000, Math.floor(opts.tailLines)));
+ const r = await dexec(["logs", "--tail", String(lines), name(d)]);
+ if (r.code !== 0) return null;
+ return `${r.stdout}${r.stderr}`;
+ },
+
async destroy(d: Deployment): Promise<void> {
await dexec(["rm", "-f", name(d)]);
freePort(name(d));
diff --git a/src/deployment/postdeploy-smoke.ts b/src/deployment/postdeploy-smoke.ts
index 211cf033b..f727872e9 100644
--- a/src/deployment/postdeploy-smoke.ts
+++ b/src/deployment/postdeploy-smoke.ts
@@ -1,3 +1,4 @@
+import { resolvePgCaTrust } from "../persistence/pg-pool.ts";
import { randomUUID } from "node:crypto";
import { pathToFileURL } from "node:url";
import { PORTAL_IDENTITY_HEADER } from "../auth/portal-identity.ts";
@@ -237,6 +238,8 @@ type PostdeployConfig = Pick<
Config,
| "adminGrants"
| "databaseUrl"
+ | "databaseCaCert"
+ | "databaseCaCertFile"
| "flyAppName"
| "orgId"
| "port"
@@ -254,7 +257,13 @@ async function runPostdeploySmoke(config: PostdeployConfig): Promise<void> {
if (!portalIdentitySecret) throw new Error("postdeploy smoke requires PORTAL_IDENTITY_SECRET");
const pg = (await import("pg")).default;
- const client = new pg.Client({ connectionString: databaseUrl });
+ const client = new pg.Client({
+ connectionString: databaseUrl,
+ ...resolvePgCaTrust({
+ ...(config.databaseCaCert ? { cert: config.databaseCaCert } : {}),
+ ...(config.databaseCaCertFile ? { certFile: config.databaseCaCertFile } : {}),
+ }),
+ });
await client.connect();
try {
const unsafe = await client.query(PARALLEL_EXCEPTION_QUERY);
diff --git a/src/files/file-artifact-store.ts b/src/files/file-artifact-store.ts
index b9551ed96..75ced2374 100644
Binary files a/src/files/file-artifact-store.ts and b/src/files/file-artifact-store.ts differ
diff --git a/src/persistence/pg-pool.ts b/src/persistence/pg-pool.ts
index d2ed10295..a0b01771c 100644
--- a/src/persistence/pg-pool.ts
+++ b/src/persistence/pg-pool.ts
@@ -1,3 +1,4 @@
+import { readFileSync } from "node:fs";
import type { Pool, PoolClient } from "pg";
import { swallowAs } from "../util/errors.ts";
import { errMessage } from "../util/errors.ts";
@@ -55,6 +56,41 @@ async function applyDdl(pool: Pool, statements: string[]): Promise<void> {
}
}
+/**
+ * Extra root-CA trust for the Postgres connection, with full verification
+ * semantics kept. Managed providers (Supabase's pooler, RDS, …) often pin a
+ * private root the container's trust store doesn't carry; without a supported
+ * way to add it, operators were left choosing between sslmode=no-verify and
+ * forking the image. DATABASE_CA_CERT carries PEM content (a secret-store
+ * value); DATABASE_CA_CERT_FILE points at a mounted file. Parsed once at the
+ * process boundary (config.ts / a script's own env read), installed here, and
+ * applied to every pg pool and client this process opens — database CA trust
+ * is inherently process-global, like NODE_EXTRA_CA_CERTS.
+ */
+export function resolvePgCaTrust(opts: { cert?: string; certFile?: string }): { ssl?: { ca: string } } {
+ if (opts.cert?.trim()) return { ssl: { ca: opts.cert } };
+ if (opts.certFile?.trim()) {
+ try {
+ return { ssl: { ca: readFileSync(opts.certFile, "utf8") } };
+ } catch (e) {
+ throw new Error(`DATABASE_CA_CERT_FILE is set but unreadable (${opts.certFile}): ${errMessage(e)}`, {
+ cause: e,
+ });
+ }
+ }
+ return {};
+}
+
+let installedCaTrust: { ssl?: { ca: string } } = {};
+
+export function configurePgCaTrust(opts: { cert?: string; certFile?: string }): void {
+ installedCaTrust = resolvePgCaTrust(opts);
+}
+
+export function pgCaOptions(): { ssl?: { ca: string } } {
+ return installedCaTrust;
+}
+
export function createPgPool(connectionString: string, statements: string[]): PgPool {
const schema = statements.map((s) => s.trim()).filter((s) => s.length > 0);
for (const stmt of schema) assertOneStatement(stmt);
@@ -63,7 +99,7 @@ export function createPgPool(connectionString: string, statements: string[]): Pg
if (!poolP) {
poolP = (async () => {
const pg = (await import("pg")).default;
- const p = new pg.Pool({ connectionString });
+ const p = new pg.Pool({ connectionString, ...pgCaOptions() });
p.on("error", (err) => console.error("[pg] idle client error:", errMessage(err)));
try {
await applyDdl(p, schema);
diff --git a/src/policy/command-policy.ts b/src/policy/command-policy.ts
index ed60fa16d..0b2e95670 100644
--- a/src/policy/command-policy.ts
+++ b/src/policy/command-policy.ts
@@ -777,12 +777,90 @@ function executedShellPayloads(input: string): string[] {
return [
...scan.nested,
...scan.commands.flatMap(segmentShellPayloads),
+ ...scan.commands.flatMap(sqlClientPayloads),
...pipedShellPayloads(input),
+ ...pipedSqlPayloads(input),
...hereStringShellPayloads(input),
...simpleVariablePayloads(input),
];
}
+/**
+ * SQL clients whose command-line payloads are executable SQL. scannableCommand
+ * empties quoted strings before rules run, so `psql -c "DROP TABLE users"`
+ * scanned as `psql -c ""` and the destructive-SQL floor rule could never fire
+ * on any spelling people actually type. Extract those payloads as their own
+ * scan lines, the same way executed shell payloads are.
+ */
+const SQL_CLIENT_SPECS: Record<string, { options: string[]; sqlPositionalsAfter?: number }> = {
+ psql: { options: ["-c", "--command"] },
+ pgcli: { options: ["-c", "--command"] },
+ mysql: { options: ["-e", "--execute"] },
+ mariadb: { options: ["-e", "--execute"] },
+ mycli: { options: ["-e", "--execute"] },
+ sqlite3: { options: ["-cmd"], sqlPositionalsAfter: 1 },
+ duckdb: { options: ["-c", "-s", "--command"], sqlPositionalsAfter: 1 },
+ "clickhouse-client": { options: ["-q", "--query"] },
+};
+
+function sqlClientSpec(
+ words: string[],
+): { spec: { options: string[]; sqlPositionalsAfter?: number }; args: string[] } | undefined {
+ const start = commandStart(words);
+ if (start >= words.length) return undefined;
+ const executableWord = words[start]!;
+ const executable = (executableWord.split("/").pop() ?? executableWord).toLowerCase();
+ const spec = SQL_CLIENT_SPECS[executable];
+ return spec ? { spec, args: words.slice(start + 1) } : undefined;
+}
+
+function sqlClientPayloads(words: string[]): string[] {
+ const found = sqlClientSpec(words);
+ if (!found) return [];
+ const { spec, args } = found;
+ const payloads: string[] = [];
+ const positionals: string[] = [];
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i]!;
+ let matched = false;
+ for (const opt of spec.options) {
+ if (arg === opt) {
+ if (args[i + 1] !== undefined) payloads.push(args[++i]!);
+ matched = true;
+ break;
+ }
+ if (arg.startsWith(`${opt}=`)) {
+ payloads.push(arg.slice(opt.length + 1));
+ matched = true;
+ break;
+ }
+ if (opt.length === 2 && !arg.startsWith("--") && arg.startsWith(opt) && arg.length > 2) {
+ payloads.push(arg.slice(2));
+ matched = true;
+ break;
+ }
+ }
+ if (!matched && !arg.startsWith("-")) positionals.push(arg);
+ }
+ if (spec.sqlPositionalsAfter !== undefined) payloads.push(...positionals.slice(spec.sqlPositionalsAfter));
+ return payloads;
+}
+
+function pipedSqlPayloads(input: string): string[] {
+ const payloads: string[] = [];
+ for (const pipeline of shellPipelines(input)) {
+ for (let i = 1; i < pipeline.length; i++) {
+ const consumer = scanShell(pipeline[i]!).commands[0];
+ if (!consumer || !sqlClientSpec(consumer)) continue;
+ const producer = scanShell(pipeline[i - 1]!).commands.at(-1);
+ if (!producer) continue;
+ const payload = literalProducerPayload(producer);
+ if (payload) payloads.push(payload);
+ }
+ }
+ return payloads;
+}
+
function firstMatch(scannable: string, rules: readonly CommandRule[]): CommandEvaluation | null {
for (const rule of rules) {
let re: RegExp;
diff --git a/src/surface-cache/surface-cache.ts b/src/surface-cache/surface-cache.ts
index fa94bc44a..d12f95ad1 100644
--- a/src/surface-cache/surface-cache.ts
+++ b/src/surface-cache/surface-cache.ts
@@ -465,7 +465,7 @@ export function createMemorySurfaceCache(opts: { liveFallback?: LiveFallback } =
for (const msg of m.values()) {
if (!msg.sub || msg.deleted) continue;
if (o.container && msg.container !== o.container) continue;
- const tk = `${msg.container}${msg.sub}`;
+ const tk = `${msg.container}\0${msg.sub}`;
const cur = byThread.get(tk);
if (!cur) {
byThread.set(tk, {
diff --git a/src/tools/primitives.ts b/src/tools/primitives.ts
index ce18b93cb..8d32b4f2b 100644
--- a/src/tools/primitives.ts
+++ b/src/tools/primitives.ts
@@ -40,7 +40,7 @@ import type { AclStore } from "../acl/acl-store.ts";
import type { AuditLog } from "../audit/audit-log.ts";
import { mimeFromName } from "../core/attachments.ts";
import { swallow } from "../util/errors.ts";
-import { fileArtifactId, type FileArtifactStore } from "../files/file-artifact-store.ts";
+import { fileArtifactId, isArtifactPath, type FileArtifactStore } from "../files/file-artifact-store.ts";
import type { ScopedConfigStore } from "../resolution/config-store.ts";
import { MEMORY_FILE, type MemoryService } from "../memory/memory-service.ts";
import type { McpToolService, McpToolDescriptor } from "../mcp/mcp-tool-service.ts";
@@ -475,6 +475,41 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
return cache ? once(call, cache) : call();
}
+ const MAX_SHARED_ARTIFACT_BYTES = 10 * 1024 * 1024;
+
+ async function readGrantedArtifactBytes(ownerScopeId: ScopeId, ownerPath: string): Promise<Buffer | null> {
+ if (!deps.files) return null;
+ const rows = await deps.files.resolveByOwnerPaths([{ ownerScopeId, path: ownerPath }]);
+ // Re-assert the tuple: the (owner_scope_id, path) index isn't unique and
+ // neither implementation orders results.
+ const row = rows.find((r) => r.ownerScopeId === ownerScopeId && r.path === ownerPath);
+ if (!row) return null;
+ const opened = await deps.files.open(row.id);
+ if (!opened) return null;
+ // The advertised size can be absent on some backends (fails open at 0), so
+ // the collector enforces the cap on actual bytes read.
+ if (opened.sizeBytes > MAX_SHARED_ARTIFACT_BYTES) {
+ opened.stream.destroy();
+ throw new Error(
+ `shared file ${ownerPath.split("/").pop()} is ${opened.sizeBytes} bytes — larger than the ${MAX_SHARED_ARTIFACT_BYTES}-byte shared-read limit`,
+ );
+ }
+ const chunks: Buffer[] = [];
+ let total = 0;
+ for await (const chunk of opened.stream) {
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
+ total += buf.length;
+ if (total > MAX_SHARED_ARTIFACT_BYTES) {
+ opened.stream.destroy();
+ throw new Error(
+ `shared file ${ownerPath.split("/").pop()} exceeds the ${MAX_SHARED_ARTIFACT_BYTES}-byte shared-read limit`,
+ );
+ }
+ chunks.push(buf);
+ }
+ return Buffer.concat(chunks);
+ }
+
return {
...(deps.credentialExecServices ? { credentialExecServices: deps.credentialExecServices } : {}),
...(deps.credentialExec ? { credentialExec: deps.credentialExec } : {}),
@@ -595,7 +630,14 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
};
}
const granted = matches[0]!;
- const bytes = await deps.workspace.readBytes(granted.ownerScopeId, granted.ownerPath);
+ // Two producers create grants: the write tool (workspace-backed, real
+ // workspace path) and viewer uploads / inbound attachments (artifact
+ // store only, artifacts/<id>/<name>). The namespace decides which
+ // store serves the read — never a precedence rule, because a
+ // workspace-backed path can also have a stale artifact snapshot.
+ const bytes = isArtifactPath(granted.ownerPath)
+ ? await readGrantedArtifactBytes(granted.ownerScopeId, granted.ownerPath)
+ : await deps.workspace.readBytes(granted.ownerScopeId, granted.ownerPath);
if (bytes === null) return { content: null, sourceScopeId: granted.ownerScopeId };
const asText = tryDecodeUtf8(bytes);
if (asText !== null) return { content: asText, sourceScopeId: granted.ownerScopeId };
diff --git a/src/wiring.ts b/src/wiring.ts
index a0e6f052a..a39708d75 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -34,6 +34,7 @@ import { createGitFetcher, resolvePackAuth, type SkillPackFetcher } from "./skil
import { installSeedSkills } from "./skills/seed.ts";
import { createMemoryMap, createPostgresMapFactory, type DurableMap } from "./persistence/durable-map.ts";
import type { PersistedUiState, UiStateStore } from "./surfaces/ui-state.ts";
+import { configurePgCaTrust } from "./persistence/pg-pool.ts";
import { createPostgresLeaderLease, createNoopLeaderLease, type LeaderLease } from "./persistence/leader-lease.ts";
import {
createMemoryAdvisoryLock,
@@ -385,6 +386,10 @@ export function buildApp(
if (config.databaseUrl && !config.connectorSecretKey) {
throw new Error("CONNECTOR_SECRET_KEY is required with durable storage");
}
+ configurePgCaTrust({
+ ...(config.databaseCaCert ? { cert: config.databaseCaCert } : {}),
+ ...(config.databaseCaCertFile ? { certFile: config.databaseCaCertFile } : {}),
+ });
const reusedConnectorKey = [
["CORE_SIGNING_SECRET", config.signingSecret],
["CAPABILITY_SECRET", config.capabilitySecret],
diff --git a/test/command-policy.test.ts b/test/command-policy.test.ts
index 787d83dad..cff7ce538 100644
--- a/test/command-policy.test.ts
+++ b/test/command-policy.test.ts
@@ -470,3 +470,37 @@ test("an unquoted heredoc's command substitutions still execute and stay gated",
const sneaky = ["cat <<EOF | gh pr create --body-file -", "hello $(rm -rf /tmp/x)", "EOF"].join("\n");
assert.equal(evaluateCommand(sneaky, policy).decision, "require_approval");
});
+
+test("destructive SQL handed to a SQL client fires the floor rule (public #49)", () => {
+ const p = defaultOrgPolicy();
+ for (const cmd of [
+ 'psql -c "DROP TABLE users"',
+ "psql --command='drop table users'",
+ 'psql -d app -c "TRUNCATE TABLE events"',
+ 'mysql -u root -e "DROP TABLE users"',
+ "mariadb --execute='truncate table logs'",
+ 'sqlite3 app.db "DROP TABLE users"',
+ 'duckdb data.db -c "drop table t"',
+ '/usr/bin/psql -c "DROP TABLE users"',
+ 'echo "DROP TABLE users" | psql app',
+ 'printf "TRUNCATE TABLE x" | mysql app',
+ ]) {
+ const r = evaluateCommand(cmd, p);
+ assert.equal(r.decision, "require_approval", `expected gate on: ${cmd}`);
+ assert.equal(r.reason, "destructive SQL", `wrong reason on: ${cmd}`);
+ }
+});
+
+test("SQL-looking text that is only data still passes (no false positives)", () => {
+ const p = defaultOrgPolicy();
+ for (const cmd of [
+ 'git commit -m "drop table users"',
+ 'echo "DROP TABLE users"',
+ 'grep -r "TRUNCATE TABLE" src/',
+ 'psql -c "SELECT * FROM users"',
+ "sqlite3 app.db '.tables'",
+ 'rg "drop table" --type sql',
+ ]) {
+ assert.equal(evaluateCommand(cmd, p).decision, "allow", `false positive on: ${cmd}`);
+ }
+});
diff --git a/test/deploy-logs-route.test.ts b/test/deploy-logs-route.test.ts
new file mode 100644
index 000000000..b0c71ef15
--- /dev/null
+++ b/test/deploy-logs-route.test.ts
@@ -0,0 +1,82 @@
+import { after, before, describe, it } from "node:test";
+import assert from "node:assert/strict";
+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 { CAPABILITY_TTL_MS, CONTROL_PLANE_AUD, mintCapabilityToken } from "../src/auth/capability-token.ts";
+import { scopeId } from "../src/types.ts";
+
+const SECRET = "deploy-logs-route-secret".repeat(2);
+
+describe("deployment logs route", () => {
+ let server: Server;
+ let base: string;
+ let lastTail: number | null = null;
+
+ const capFor = (actorId: string) =>
+ mintCapabilityToken(
+ {
+ actorId,
+ scopeId: scopeId("personal", actorId),
+ aud: CONTROL_PLANE_AUD,
+ exp: Date.now() + CAPABILITY_TTL_MS,
+ },
+ SECRET,
+ );
+
+ const get = async (path: string, actorId?: string) =>
+ fetch(`${base}${path}`, {
+ headers: actorId ? { "x-agent-capability": await capFor(actorId) } : {},
+ });
+
+ before(async () => {
+ const app = {
+ authorizesCapabilityScope: async () => true,
+ deploymentLogsFor: async (id: string, viewer: string, opts: { tailLines: number }) => {
+ lastTail = opts.tailLines;
+ if (id === "missing") return { status: "not_found" as const };
+ if (viewer !== "U1") return { status: "denied" as const };
+ if (id === "silent") return { status: "ok" as const, logs: null };
+ return { status: "ok" as const, logs: "line1\nline2\n" };
+ },
+ } as unknown as App;
+ server = createServer(app, { signingSecret: SECRET });
+ await new Promise<void>((resolve) => server.listen(0, resolve));
+ base = `http://localhost:${(server.address() as AddressInfo).port}`;
+ });
+
+ after(async () => {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+
+ it("requires an identified viewer", async () => {
+ assert.equal((await get("/v1/deployments/mine/logs")).status, 401);
+ });
+
+ it("returns logs to a viewer who can reach the deployment", async () => {
+ const response = await get("/v1/deployments/mine/logs", "U1");
+ assert.equal(response.status, 200);
+ assert.deepEqual(await response.json(), { logs: "line1\nline2\n" });
+ assert.equal(lastTail, 200);
+ });
+
+ it("passes tailLines through and rejects out-of-range values", async () => {
+ assert.equal((await get("/v1/deployments/mine/logs?tailLines=50", "U1")).status, 200);
+ assert.equal(lastTail, 50);
+ assert.equal((await get("/v1/deployments/mine/logs?tailLines=0", "U1")).status, 400);
+ assert.equal((await get("/v1/deployments/mine/logs?tailLines=2001", "U1")).status, 400);
+ assert.equal((await get("/v1/deployments/mine/logs?tailLines=abc", "U1")).status, 400);
+ });
+
+ it("hides denied and missing deployments as not_found", async () => {
+ assert.equal((await get("/v1/deployments/mine/logs", "U2")).status, 404);
+ assert.equal((await get("/v1/deployments/missing/logs", "U1")).status, 404);
+ });
+
+ it("says when the provider keeps no logs", async () => {
+ const response = await get("/v1/deployments/silent/logs", "U1");
+ assert.equal(response.status, 200);
+ assert.deepEqual(await response.json(), { logs: null, message: "no logs available for this deployment" });
+ });
+});
diff --git a/test/file-share.test.ts b/test/file-share.test.ts
index cb3455d29..ebd5cd59f 100644
--- a/test/file-share.test.ts
+++ b/test/file-share.test.ts
@@ -6,6 +6,8 @@ import { join } from "node:path";
import { createToolContext } from "../src/tools/primitives.ts";
import { createLocalWorkspaceStore } from "../src/workspace/workspace-store.ts";
import { createAclStore } from "../src/acl/acl-store.ts";
+import { artifactPath, createMemoryFileArtifactStore, fileArtifactId } from "../src/files/file-artifact-store.ts";
+import { createMemoryDurableByteStore } from "../src/files/durable-byte-store.ts";
import { createAuditLog } from "../src/audit/audit-log.ts";
import { principalEntitledToScope } from "../src/resolution/context-filter.ts";
import { scopeId, type Principal, type WorkspaceLayer } from "../src/types.ts";
@@ -298,3 +300,90 @@ test("write without data or share is rejected; sharing a missing file / from a r
/writable scope/,
);
});
+
+test("a viewer-uploaded artifact (artifacts/<id>/<name>) is readable through its shared handle (public #94)", async () => {
+ const workspace = ws();
+ const acl = createAclStore();
+ const owner = scopeId("personal", "U1");
+ const grantee = scopeId("personal", "U2");
+ const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());
+ const id = fileArtifactId("upload:U1:test:1:x", "in", 0);
+ const path = artifactPath(id, "notes.txt");
+ await files.put({
+ id,
+ ownerScopeId: owner,
+ createdBy: "U1",
+ name: "notes.txt",
+ path,
+ mimetype: "text/plain",
+ data: Buffer.from("hello from the upload"),
+ direction: "in",
+ createdInScope: grantee,
+ });
+ await acl.grant({ ownerScopeId: owner, ref: path, granteeScopeId: grantee, permission: "read", grantedBy: "U1" });
+
+ const handles = await acl.handlesForAudience([person("U2")], grantee, "org:o", principalEntitledToScope);
+ assert.equal(handles.length, 1, "the grant materializes as a handle");
+
+ const ctx = createToolContext({
+ sandbox: memSandbox().sandbox,
+ provision: async () => ({ id: "h", rootDir: "/workspace" }) as SandboxHandle,
+ layers: [{ scopeId: grantee, mountPath: "", mode: "rw" }],
+ commandPolicy: () => ({}) as never,
+ authorizeCommand: () => false,
+ grantedHandles: handles,
+ workspace,
+ files,
+ deploy: {} as never,
+ acl,
+ createdBy: "U2",
+ });
+ const got = await ctx.read(handles[0]!.handlePath);
+ assert.equal(got.content, "hello from the upload");
+ assert.equal(got.sourceScopeId, owner);
+});
+
+test("a workspace-backed share is never served from a stale artifact snapshot", async () => {
+ const workspace = ws();
+ const acl = createAclStore();
+ const owner = scopeId("personal", "U1");
+ const grantee = scopeId("personal", "U2");
+ const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());
+ // artifact snapshot holds version 1 under the real workspace path
+ await files.put({
+ id: fileArtifactId("share:U1:doc.txt", "out", 0),
+ ownerScopeId: owner,
+ createdBy: "U1",
+ name: "doc.txt",
+ path: "doc.txt",
+ mimetype: "text/plain",
+ data: Buffer.from("version 1"),
+ direction: "out",
+ createdInScope: owner,
+ });
+ // workspace holds version 2
+ await workspace.write(owner, "doc.txt", "version 2");
+ await acl.grant({
+ ownerScopeId: owner,
+ ref: "doc.txt",
+ granteeScopeId: grantee,
+ permission: "read",
+ grantedBy: "U1",
+ });
+ const handles = await acl.handlesForAudience([person("U2")], grantee, "org:o", principalEntitledToScope);
+ const ctx = createToolContext({
+ sandbox: memSandbox().sandbox,
+ provision: async () => ({ id: "h", rootDir: "/workspace" }) as SandboxHandle,
+ layers: [{ scopeId: grantee, mountPath: "", mode: "rw" }],
+ commandPolicy: () => ({}) as never,
+ authorizeCommand: () => false,
+ grantedHandles: handles,
+ workspace,
+ files,
+ deploy: {} as never,
+ acl,
+ createdBy: "U2",
+ });
+ const got = await ctx.read(handles[0]!.handlePath);
+ assert.equal(got.content, "version 2", "the live workspace copy wins for workspace-namespace paths");
+});
diff --git a/test/live-slack/gallery.ts b/test/live-slack/gallery.ts
index 697cb66f2..24165b243 100644
Binary files a/test/live-slack/gallery.ts and b/test/live-slack/gallery.ts differ
diff --git a/test/pg-ca-options.test.ts b/test/pg-ca-options.test.ts
new file mode 100644
index 000000000..83f0d25d4
--- /dev/null
+++ b/test/pg-ca-options.test.ts
@@ -0,0 +1,29 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { resolvePgCaTrust } from "../src/persistence/pg-pool.ts";
+
+const PEM = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n";
+
+test("no CA configured → no ssl override (connection string semantics untouched)", () => {
+ assert.deepEqual(resolvePgCaTrust({}), {});
+ assert.deepEqual(resolvePgCaTrust({ cert: " " }), {});
+});
+
+test("PEM content wires into ssl.ca", () => {
+ assert.deepEqual(resolvePgCaTrust({ cert: PEM }), { ssl: { ca: PEM } });
+});
+
+test("a cert file is read; inline PEM wins when both are set", () => {
+ const dir = mkdtempSync(join(tmpdir(), "pgca-"));
+ const file = join(dir, "root.crt");
+ writeFileSync(file, PEM);
+ assert.deepEqual(resolvePgCaTrust({ certFile: file }), { ssl: { ca: PEM } });
+ assert.deepEqual(resolvePgCaTrust({ cert: PEM, certFile: "/nope" }), { ssl: { ca: PEM } });
+});
+
+test("an unreadable cert file fails loudly, not as silent no-verify", () => {
+ assert.throws(() => resolvePgCaTrust({ certFile: "/does/not/exist.crt" }), /unreadable/);
+});