Multiplayer agent harness for work.
Let app owners approve or decline access requests from Slack (#1551)
Joshua Franceaa459f41c95b
diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.tsindex 495e8fa4f..e6a1ca3d8 100644--- a/src/api/app-sessions.ts+++ b/src/api/app-sessions.ts@@ -1,3 +1,4 @@+import { notifyDeploymentShared } from "../deploy/share-notice.ts";import { sessionTreeRoot, sessionTreeRunCount, SUBAGENT_TREE_RUN_CAP } from "../sessions/session-syscalls.ts";import { isSessionStatus } from "../sessions/session-status.ts";import type { PendingApprovalRecord } from "../types.ts";@@ -11,7 +12,7 @@ import { swallowAs } from "../util/errors.ts";import { SEARCH_HIT_LIMIT, entrySearchText, searchSnippet, searchTerms } from "../sessions/entry-search.ts";import { supportsProcessSessions } from "../sandbox/sandbox.ts";import { processIsGone } from "../sandbox/process-poll.ts";-import { cronRef, deployRef, encodeRef, fileRef, skillRef } from "../acl/resource-ref.ts";+import { cronRef, deployRef, encodeRef, fileRef, parseRef, skillRef } from "../acl/resource-ref.ts";import { samePerson } from "../directory/person.ts";import { AdminError } from "../admin/admin-service.ts";import { type ArtifactHome } from "./artifact-share.ts";@@ -963,6 +964,15 @@ export function createSessionMethods(resource: g.ref,scopeLabel: g.granteeScopeId,});+ const ref = parseRef(g.ref);+ if (ref.kind === "deploy")+ await notifyDeploymentShared(+ deps,+ deps.deploy.getDeployment(ref.id),+ g.granteeScopeId,+ g.permission,+ g.grantedBy,+ );},async revokeGrant(ownerScopeId, ref, granteeScopeId, revokedBy) {await deps.acl.revoke(ownerScopeId, ref, granteeScopeId, revokedBy, await artifactAuthor(ownerScopeId, ref));diff --git a/src/api/app-types.ts b/src/api/app-types.tsindex 32752f3fe..6d49876da 100644--- a/src/api/app-types.ts+++ b/src/api/app-types.ts@@ -633,6 +633,7 @@ export interface AppDeps {emailAuthMembers?: DirectoryMember[];projects?: ProjectStore;deploy: DeployService;+ deployAppsDomain?: string;deploymentLayer?: DeploymentLayerRuntime;files: FileArtifactStore;approvals?: DurableMap<PendingApprovalRecord>;diff --git a/src/api/routes/deployments.ts b/src/api/routes/deployments.tsindex 3e197f07b..d06bc77d8 100644--- a/src/api/routes/deployments.ts+++ b/src/api/routes/deployments.ts@@ -926,7 +926,10 @@ export async function proxyDeploymentSubdomain(ctx: BaseCtx): Promise<boolean> {const day = Math.floor(Date.now() / 86_400_000);try {await app.enqueueDelivery({- destination: principalDestination(ownerId, sub),+ destination: {+ ...principalDestination(ownerId, sub),+ deploymentAccess: { deploymentId: d.id, requesterId: sub },+ },text:`${sub} is asking for access to your app "${label}" (https://${rawHost}/). ` +`They signed in but the app isn't shared with them. To grant it, share the deployment with personal:${sub}.`,diff --git a/src/api/slack-core-client.ts b/src/api/slack-core-client.tsindex 672758b3a..0b9954ad3 100644--- a/src/api/slack-core-client.ts+++ b/src/api/slack-core-client.ts@@ -1,3 +1,6 @@+import { decideDeploymentAccess } from "../slack/deploy-access.ts";+import type { IdentityService } from "../identity/identity-service.ts";+import type { ActorAssertion } from "../types.ts";import type { KeychainApprovals } from "../credentials/keychain-approval.ts";import { createTaskAcknowledgements, type TaskAckState, type TaskAcknowledgements } from "../slack/task-ack.ts";import { orgId as configOrgId } from "../config.ts";@@ -89,6 +92,7 @@ interface DirectoryPush {}export interface SlackCoreClient {+ decideDeploymentAccess(value: string, actor: ActorAssertion, approve: boolean): Promise<string>;keychainApprovals?: KeychainApprovals;taskAcknowledgements?: TaskAcknowledgements;externalSlackParticipants(): Promise<boolean>;@@ -156,6 +160,7 @@ type AckPickInput = {export type { SurfaceContextRequest };export interface SlackCoreClientDeps {+ identity: IdentityService;keychainApprovals?: KeychainApprovals;taskAcknowledgements?: DurableMap<TaskAckState>;app: App;@@ -231,6 +236,8 @@ export function createSlackCoreClient(deps: SlackCoreClientDeps): SlackCoreClien});return {+ decideDeploymentAccess: (value, actor, approve) =>+ decideDeploymentAccess(deps.app, deps.identity, value, actor, approve),...(deps.keychainApprovals ? { keychainApprovals: deps.keychainApprovals } : {}),...(deps.taskAcknowledgements? { taskAcknowledgements: createTaskAcknowledgements(deps.taskAcknowledgements, lease, deps) }diff --git a/src/deploy/deploy-service.ts b/src/deploy/deploy-service.tsindex 955a3e940..587d7d892 100644--- a/src/deploy/deploy-service.ts+++ b/src/deploy/deploy-service.ts@@ -1,3 +1,5 @@+import { notifyDeploymentShared } from "./share-notice.ts";+import type { DeliveryStore } from "../delivery/delivery-store.ts";import { EMBED_ANCESTORS_HINT, parseEmbedAncestors } from "./embed-ancestors.ts";import { mkdir, writeFile } from "node:fs/promises";import { join, dirname, resolve, relative, isAbsolute } from "node:path";@@ -112,6 +114,9 @@ export interface DeploymentGrantee {}export interface DeployServiceDeps {+ deliveries?: DeliveryStore;+ deployAppsDomain?: string;+ publicWebUrl?: string;deployStore: DeployStore;provider: DeployProvider;deployDir: string;@@ -281,6 +286,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {d: Deployment,da: NonNullable<DeployOrUpdateInput["defaultAudience"]>,isCreate: boolean,+ explicitShares?: DeployOrUpdateInput["share"],): Promise<void> {if (!isCreate && !da.force && d.createdInScope && da.contextScopeId !== d.createdInScope) return;const ref = deploymentRef(d.id);@@ -311,6 +317,8 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {permission: "read",grantedBy: owner,});+ if (!explicitShares?.some((s) => s.scope === grantee))+ await notifyDeploymentShared(deps, d, grantee, "read", owner);deps.auditLog.record({at: Date.now(),principalId: owner,@@ -340,6 +348,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {grantedBy: createdBy,};await deps.acl.grant(grant);+ await notifyDeploymentShared(deps, d, grant.granteeScopeId, grant.permission, createdBy);deps.auditLog.record({at: Date.now(),principalId: createdBy,@@ -693,7 +702,12 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {...(input.stampEnv ? { stampEnv: input.stampEnv } : {}),});if (input.defaultAudience)- await reconcileDefaultAudience((await deps.deployStore.get(existing.id))!, input.defaultAudience, false);+ await reconcileDefaultAudience(+ (await deps.deployStore.get(existing.id))!,+ input.defaultAudience,+ false,+ input.share,+ );} else if (input.alwaysOn !== undefined) await this.setDeploymentAlwaysOn(existing.id, input.alwaysOn);if (input.embedAncestors !== undefined)await this.setDeploymentEmbedAncestors(existing.id, input.embedAncestors);@@ -756,7 +770,12 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {isCreate = true;}if (input.defaultAudience)- await reconcileDefaultAudience((await deps.deployStore.get(d.id))!, input.defaultAudience, isCreate);+ await reconcileDefaultAudience(+ (await deps.deployStore.get(d.id))!,+ input.defaultAudience,+ isCreate,+ input.share,+ );if (input.embedAncestors !== undefined) await this.setDeploymentEmbedAncestors(d.id, input.embedAncestors);if (input.share?.length) await issueShares((await deps.deployStore.get(d.id))!, createdBy, input.share);return (await deps.deployStore.get(d.id))!;@@ -806,6 +825,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {scopeLabel: grantee,});}+ await notifyDeploymentShared(deps, d, grantee, permission, actor.createdBy);return (await grantsOn(d)).map((g) => ({ scope: g.granteeScopeId, permission: g.permission }));},diff --git a/src/deploy/share-notice.ts b/src/deploy/share-notice.tsnew file mode 100644index 000000000..67702c47d--- /dev/null+++ b/src/deploy/share-notice.ts@@ -0,0 +1,40 @@+import type { DeliveryStore } from "../delivery/delivery-store.ts";+import { samePerson } from "../directory/person.ts";+import { principalDestination } from "../reach/reach.ts";+import { parseScopeId, type Permission, type ScopeId } from "../types.ts";+import { swallow } from "../util/errors.ts";+import { publicUrlOf, type Deployment } from "./deploy-store.ts";++export async function notifyDeploymentShared(+ deps: { deliveries?: Pick<DeliveryStore, "enqueue">; publicWebUrl?: string; deployAppsDomain?: string },+ deployment: Deployment | Promise<Deployment | null>,+ scope: ScopeId,+ permission: Permission | null,+ by: string,+): Promise<void> {+ try {+ const d = await deployment;+ const grantee = parseScopeId(scope);+ if (+ !d ||+ !deps.deliveries ||+ !permission ||+ grantee.kind !== "personal" ||+ !grantee.ref ||+ samePerson(grantee.ref, by)+ )+ return;+ const slug = d.name ?? d.id;+ const url = deps.deployAppsDomain+ ? `https://${slug}.${deps.deployAppsDomain}/`+ : (publicUrlOf(d.endpoint) ??+ (deps.publicWebUrl ? `${deps.publicWebUrl.replace(/\/+$/, "")}/d/${slug}/` : undefined));+ await deps.deliveries.enqueue({+ destination: principalDestination(grantee.ref, by),+ text: `${by} gave you access to the app "${d.displayName ?? slug}"${permission === "write" ? " (you can also manage it)" : ""}.${url ? ` Open it: ${url}` : ""}`,+ idempotencyKey: `deploy-shared:${d.id}:${grantee.ref.toLowerCase()}:${permission}:${Math.floor(Date.now() / 86_400_000)}`,+ });+ } catch (error) {+ swallow("deploy: share notice", error);+ }+}diff --git a/src/slack/deliveries.ts b/src/slack/deliveries.tsindex 8389c1614..6383885ea 100644--- a/src/slack/deliveries.ts+++ b/src/slack/deliveries.ts@@ -1,3 +1,4 @@+import { deployAccessMessage } from "./deploy-access.ts";import { keychainApprovalMessage, keychainApprovalOrigin } from "./keychain-approvals.ts";import { errMessage, swallow, swallowAs } from "../util/errors.ts";import { performance } from "node:perf_hooks";@@ -366,9 +367,14 @@ export function createDeliveryPoller(deps: {d.destination.keychainAskId && core.keychainApprovals? await core.keychainApprovals.get(d.destination.keychainAskId, d.destination.target): null;- const card = approval- ? keychainApprovalMessage(approval, await keychainApprovalOrigin(approval, client, deps.webUiPublicUrl))- : null;+ let card: { text: string; blocks: Array<Record<string, unknown>> } | null = null;+ if (approval)+ card = keychainApprovalMessage(+ approval,+ await keychainApprovalOrigin(approval, client, deps.webUiPublicUrl),+ );+ else if (d.destination.deploymentAccess)+ card = deployAccessMessage(d.destination.deploymentAccess, d.text);const text = card?.text ?? toSlackMrkdwn(stripReactionDirectives(d.text));if (!text.trim() && !d.attachments?.length) return undefined;const channel = await openConversationFor(client, [d.destination.target]);diff --git a/src/slack/deploy-access.ts b/src/slack/deploy-access.tsnew file mode 100644index 000000000..96241d862--- /dev/null+++ b/src/slack/deploy-access.ts@@ -0,0 +1,122 @@+import type { App } from "../api/app-types.ts";+import type { SlackCoreClient } from "../api/slack-core-client.ts";+import type { IdentityService } from "../identity/identity-service.ts";+import { principalDestination } from "../reach/reach.ts";+import { parseScopeId, scopeId, type ActorAssertion, type Destination } from "../types.ts";+import type { Directory } from "./directory.ts";+import { parseBlockAction, parseInteractionBody } from "./payloads.ts";+import { updateSlackMessage } from "./messaging.ts";+import { errMessage, swallowAs } from "../util/errors.ts";++const ACTIONS = ["deploy_access_approve", "deploy_access_decline"] as const;+type Request = NonNullable<Destination["deploymentAccess"]>;++export function parseDeployAccess(value: string): Request {+ if (value.length > 2000) throw new Error("Invalid access request.");+ const r = JSON.parse(value) as Request;+ if (+ !r ||+ Object.keys(r).length !== 2 ||+ typeof r.deploymentId !== "string" ||+ !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(r.deploymentId) ||+ typeof r.requesterId !== "string" ||+ !/^[^\s\p{Cc}<>|:]{1,320}$/u.test(r.requesterId)+ )+ throw new Error("Invalid access request.");+ return r;+}++export function deployAccessMessage(+ request: Request,+ text: string,+): { text: string; blocks: Array<Record<string, unknown>> } {+ const value = JSON.stringify(request);+ parseDeployAccess(value);+ return {+ text,+ blocks: [+ { type: "section", text: { type: "plain_text", text: text.slice(0, 3000) } },+ {+ type: "actions",+ elements: ACTIONS.map((action_id, i) => ({+ type: "button",+ action_id,+ value,+ text: { type: "plain_text", text: i === 0 ? "Approve" : "Decline" },+ style: i === 0 ? "primary" : "danger",+ })),+ },+ ],+ };+}++export async function decideDeploymentAccess(+ app: App,+ identity: IdentityService,+ value: string,+ assertion: ActorAssertion,+ approve: boolean,+): Promise<string> {+ const { deploymentId, requesterId } = parseDeployAccess(value);+ await identity.refresh(true);+ const actor = identity.resolve(assertion);+ if (!identity.isInternal(actor)) throw new Error("Only the app's owner can decide this request.");+ const home = await app.getArtifactHome("deploy", deploymentId);+ if (+ !home ||+ !(await (parseScopeId(home.ownerScopeId).kind === "personal"+ ? app.belongsToScope(actor.id, home.ownerScopeId)+ : app.canManageArtifactHome(home.ownerScopeId, home.createdBy, actor.id)))+ )+ throw new Error("Only the app's owner can decide this request.");+ const d = await app.getDeployment(deploymentId);+ if (!d) throw new Error("That app no longer exists.");+ const label = d.displayName ?? d.name ?? d.id;+ if (approve) {+ const grantee = scopeId("personal", requesterId);+ const existing = (await app.deploymentGrantees(deploymentId)).find(+ (g) => g.scope === grantee && g.permission === "write",+ );+ await app.grant({+ ownerScopeId: home.ownerScopeId,+ ref: home.grantRef,+ granteeScopeId: grantee,+ permission: existing?.permission ?? "read",+ grantedBy: actor.id,+ });+ return `Approved. ${requesterId} can now open "${label}".`;+ }+ await app.enqueueDelivery({+ destination: principalDestination(requesterId, actor.id),+ text: `${actor.id} declined your request for access to "${label}".`,+ idempotencyKey: `deploy-declined:${deploymentId}:${requesterId.toLowerCase()}:${Math.floor(Date.now() / 86_400_000)}`,+ });+ return `Declined. ${requesterId} was told.`;+}++export function registerDeployAccessActions(+ app: { action(pattern: RegExp, handler: (args: any) => Promise<void>): void },+ deps: { core: SlackCoreClient; directory: Directory },+): void {+ app.action(/^deploy_access_/, async ({ ack, body, action, client }) => {+ await ack();+ const parsed = parseBlockAction(action, ACTIONS);+ const { clickerId, channel, messageTs } = parseInteractionBody(body);+ if (!parsed || !clickerId || !channel || !messageTs) return;+ try {+ const actor = await deps.directory.classifyActor(client, clickerId);+ const text = await deps.core.decideDeploymentAccess(parsed.value, actor, parsed.actionId === ACTIONS[0]);+ await updateSlackMessage(client, channel, messageTs, text, [+ { type: "section", text: { type: "plain_text", text } },+ ]);+ } catch (error) {+ await client.chat+ .postEphemeral({+ channel,+ user: clickerId,+ text: `Couldn't complete that: ${errMessage(error)} You can try the button again.`,+ })+ .catch(swallowAs("slack: app access decision failure", undefined));+ }+ });+}diff --git a/src/slack/index.ts b/src/slack/index.tsindex 80d18a897..3eecae186 100644--- a/src/slack/index.ts+++ b/src/slack/index.ts@@ -1,4 +1,5 @@import { registerKeychainApprovalActions } from "./keychain-approvals.ts";+import { registerDeployAccessActions } from "./deploy-access.ts";import { SlackPluginStartCleanupError } from "../surfaces/slack-runtime.ts";import { createSlackRateLimitNotice } from "./rate-limit-notice.ts";import { createSlackHistoryReader } from "./history.ts";@@ -254,6 +255,7 @@ export async function startSlackPlugin(});const approvals = createApprovals({ core, flow, directory, threads, ids });registerKeychainApprovalActions(app, { core, directory, webUiPublicUrl: cfg.webUiPublicUrl });+ registerDeployAccessActions(app, { core, directory });const ensureHeader = createSurfaceHeaderEnsurer({headerFacts: (scope) => core.surfaceHeaderFacts(scope as Parameters<typeof core.surfaceHeaderFacts>[0]),channelPinEnabled: (scope) =>diff --git a/src/types.ts b/src/types.tsindex 2d3fe67e5..371d44a26 100644--- a/src/types.ts+++ b/src/types.ts@@ -200,6 +200,7 @@ export interface TriggerBase {export interface Destination {keychainAskId?: string;+ deploymentAccess?: { deploymentId: string; requesterId: string };type: string;target: string;audienceScopeId?: ScopeId;diff --git a/src/wiring.ts b/src/wiring.tsindex 3a87636bb..b50887726 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -1667,7 +1667,14 @@ export function buildApp(membership.managesArtifactHome = managesArtifactHome;const deployGitSecret = config.signingSecret;const deployGitBase = config.apiBaseUrl;+ const deliveries = withWebTranscriptDeliveries(+ config.databaseUrl ? createPostgresDeliveryStore(config.databaseUrl) : createDeliveryStore(),+ sessions,+ );const deployService = createDeployService({+ deliveries,+ deployAppsDomain: config.awsDeploy.appsDomain,+ publicWebUrl: config.publicWebUrl,appPublished: productAnalytics.appPublished,deployStore,provider: deployProvider,@@ -1771,10 +1778,6 @@ export function buildApp(`UPDATE webhooks SET json = jsonb_set(json, '{enabled}', 'false'::jsonb) WHERE (json ->> 'enabled')::boolean`,],});- const deliveries = withWebTranscriptDeliveries(- config.databaseUrl ? createPostgresDeliveryStore(config.databaseUrl) : createDeliveryStore(),- sessions,- );let securityScreener = overrides.securityScreener;if (!securityScreener && config.securityScreenBackend === "proxy") {securityScreener = createSecurityScreenProxy({@@ -2081,6 +2084,7 @@ export function buildApp(projects,environments,deploy: deployService,+ deployAppsDomain: config.awsDeploy.appsDomain,deploymentLayer,...(processes ? { processes } : {}),monitors,@@ -2114,6 +2118,7 @@ export function buildApp(requestFire: (loopId) => void loopFire.fire(loopId, `loop:${loopId}:slack-event:${Date.now()}`).catch(() => {}),});const slackCore = createSlackCoreClient({+ identity,...(keychain? {keychainApprovals: createKeychainApprovals({diff --git a/test/deploy-access.test.ts b/test/deploy-access.test.tsnew file mode 100644index 000000000..60260acdd--- /dev/null+++ b/test/deploy-access.test.ts@@ -0,0 +1,271 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createApp } from "../src/api/app.ts";+import { createDeployStore } from "../src/deploy/deploy-store.ts";+import { createDeployService } from "../src/deploy/deploy-service.ts";+import { createAuditLog } from "../src/audit/audit-log.ts";+import { createAclStore } from "../src/acl/acl-store.ts";+import { createDirectoryStore } from "../src/directory/directory-store.ts";+import { createIdentityService } from "../src/identity/identity-service.ts";+import { createMemorySessionStore } from "../src/sessions/memory-session-store.ts";+import { createDeliveryStore } from "../src/delivery/delivery-store.ts";+import { createControlService } from "../src/api/control-service.ts";+import {+ decideDeploymentAccess,+ deployAccessMessage,+ parseDeployAccess,+ registerDeployAccessActions,+} from "../src/slack/deploy-access.ts";+import type { CapabilityClaims } from "../src/auth/capability-token.ts";+import { scopeId, type ActorAssertion, type Permission } from "../src/types.ts";++const owner = "[email protected]";+const requester = "[email protected]";+const person = (id: string) => scopeId("personal", id);+const publishInput = (id = owner, name = "mysite") => ({+ ownerScopeId: person(id),+ createdBy: id,+ entrypoint: "x",+ files: [],+ name,+});+const request = { deploymentId: "00000000-0000-4000-8000-000000000001", requesterId: requester };++async function fixture(t: { after(fn: () => void): void }) {+ const dir = mkdtempSync(join(tmpdir(), "deploy-access-"));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const acl = createAclStore();+ const auditLog = createAuditLog();+ const deliveries = createDeliveryStore();+ const deploy = createDeployService({+ deliveries,+ deployAppsDomain: "apps.example.com",+ deployStore: createDeployStore(),+ acl,+ auditLog,+ deployDir: dir,+ provider: {+ profile: { managedScaleToZero: false },+ apply: async () => ({ host: "h", port: 1 }),+ destroy: async () => {},+ },+ });+ const identity = createIdentityService();+ const directory = createDirectoryStore();+ const app = createApp({+ deploy,+ acl,+ identity,+ deliveries,+ auditLog,+ directory,+ sessions: createMemorySessionStore(),+ deployAppsDomain: "apps.example.com",+ } as unknown as Parameters<typeof createApp>[0]);+ const d = await app.deploy(publishInput());+ const value = JSON.stringify({ deploymentId: d.id, requesterId: requester });+ const share = (permission: Permission | null, scope = person(requester)) =>+ app.shareDeployment(d.id, scope, permission, { createdBy: owner });+ return {+ share,+ grants: () => app.deploymentGrantees(d.id),+ notices: () => deliveries.pending("principal"),+ app,+ deploy,+ identity,+ deliveries,+ directory,+ d,+ value,+ auditLog,+ decide: (id = owner, approve = true, extra: Partial<ActorAssertion> = {}) =>+ decideDeploymentAccess(app, identity, value, { externalId: id, ...extra }, approve),+ };+}++test("card is plain text with only deployment and requester in bounded JSON buttons", () => {+ const text = '<@everyone> asks to open "A & B"';+ const card = deployAccessMessage(request, text);+ assert.equal(card.text, text);+ assert.deepEqual(card.blocks[0], { type: "section", text: { type: "plain_text", text } });+ const buttons = card.blocks[1]!.elements as Array<{ action_id: string; value: string }>;+ assert.deepEqual(+ buttons.map((b) => b.action_id),+ ["deploy_access_approve", "deploy_access_decline"],+ );+ for (const b of buttons) {+ assert.ok(b.value.length <= 2000);+ assert.deepEqual(parseDeployAccess(b.value), request);+ }+});++test("malformed or scope-injecting button payloads are rejected", () => {+ for (const value of [+ "",+ "null",+ "[]",+ "x".repeat(2001),+ "{}",+ JSON.stringify({ ...request, permission: "write" }),+ JSON.stringify({ ...request, deploymentId: "mysite" }),+ JSON.stringify({ ...request, requesterId: "personal:bob" }),+ JSON.stringify({ ...request, requesterId: "<@everyone>" }),+ JSON.stringify({ ...request, requesterId: "bob\n" }),+ JSON.stringify({ ...request, requesterId: 42 }),+ JSON.stringify({ ...request, requesterId: "x".repeat(321) }),+ ])+ assert.throws(() => parseDeployAccess(value));+});++test("approve is audited and idempotent, preserves manage access, and respects transfers/revokes", async (t) => {+ const f = await fixture(t);+ assert.match(await f.decide(), /^Approved\./);+ await f.decide();+ assert.deepEqual(await f.grants(), [{ scope: person(requester), permission: "read" }]);+ const notices = await f.notices();+ assert.equal(notices.length, 1);+ assert.equal(notices[0]!.destination.target, requester);+ assert.match(notices[0]!.text, /gave you access.*https:\/\/mysite.apps.example.com\//);+ assert.ok((await f.auditLog.events()).some((e) => e.action === "grant"));+ await f.share(null);+ assert.deepEqual(await f.grants(), []);+ await assert.rejects(f.decide(requester), /owner/);+ await f.decide();+ assert.equal((await f.grants()).length, 1);+ assert.equal((await f.notices()).length, 1);+ await f.share("write");+ await f.decide();+ assert.deepEqual(await f.grants(), [{ scope: person(requester), permission: "write" }]);+ assert.equal((await f.notices()).length, 2);+ await f.app.moveArtifactHome("deploy", f.d.id, person(requester), owner);+ await assert.rejects(f.decide(), /owner/);+ await assert.rejects(f.decide(owner, false), /owner/);+});++test("requester, stranger, guest and deactivated owner cannot approve or decline", async (t) => {+ const f = await fixture(t);+ for (const approve of [true, false]) {+ for (const id of [requester, "[email protected]"]) await assert.rejects(f.decide(id, approve), /owner/);+ await assert.rejects(f.decide(owner, approve, { isExternalGuest: true }), /owner/);+ }+ await f.identity.deactivate(owner);+ await assert.rejects(f.decide(), /owner/);+ await assert.rejects(f.decide(owner, false), /owner/);+ assert.deepEqual(await f.grants(), []);+ assert.deepEqual(await f.notices(), []);+});++test("tampering the deployment ID cannot authorize another owner's app", async (t) => {+ const f = await fixture(t);+ const other = await f.app.deploy(publishInput(requester, "other"));+ const value = JSON.stringify({ ...request, deploymentId: other.id });+ for (const approve of [true, false])+ await assert.rejects(decideDeploymentAccess(f.app, f.identity, value, { externalId: owner }, approve), /owner/);+});++test("decline only notifies and leaves access unchanged; duplicate clicks dedupe", async (t) => {+ const f = await fixture(t);+ assert.match(await f.decide(owner, false), /^Declined\./);+ await f.decide(owner, false);+ assert.deepEqual(await f.grants(), []);+ const notices = await f.notices();+ assert.equal(notices.length, 1);+ assert.match(notices[0]!.text, /declined your request/);+});++test("direct share paths notify only after successful grants; org, self and revoke stay silent", async (t) => {+ const f = await fixture(t);+ await f.share(null);+ await f.share("read", person(owner));+ await f.share("read", scopeId("org", "acme"));+ const control = createControlService(f.app);+ const cap = (actorId: string) => ({ actorId, scopeId: person(actorId), liveActor: true }) as CapabilityClaims;+ const request = { type: "deploy" as const, id: f.d.id, scope: person(requester) };+ assert.equal((await control.shareArtifact(request, cap(requester))).ok, false);+ assert.deepEqual(await f.notices(), []);+ assert.equal((await control.shareArtifact(request, cap(owner))).ok, true);+ await f.share("read");+ assert.equal((await f.notices()).length, 1);+ f.deliveries.enqueue = async () => {+ throw new Error("outbox unavailable");+ };+ assert.equal((await f.share("write")).find((g) => g.scope === person(requester))?.permission, "write");+});++test("button dispatch classifies the clicker, settles the card, and keeps failed cards actionable", async (t) => {+ const f = await fixture(t);+ let handler!: (a: any) => Promise<void>;+ let acked = 0;+ const updates: any[] = [];+ const errors: any[] = [];+ registerDeployAccessActions(+ {+ action: (_p, h) => {+ handler = h;+ },+ },+ {+ directory: { classifyActor: async (_c: unknown, id: string) => ({ externalId: id }) } as never,+ core: {+ decideDeploymentAccess: (value: string, actor: ActorAssertion, approve: boolean) =>+ decideDeploymentAccess(f.app, f.identity, value, actor, approve),+ } as never,+ },+ );+ const click = (id: string) =>+ handler({+ ack: async () => void acked++,+ body: { user: { id }, channel: { id: "D1" }, message: { ts: "1.1" } },+ action: { action_id: "deploy_access_approve", value: f.value },+ client: {+ chat: {+ update: async (d: any) => void updates.push(d),+ postEphemeral: async (d: any) => void errors.push(d),+ },+ },+ });+ await click(requester);+ assert.equal(updates.length, 0);+ assert.equal(errors.length, 1);+ await click(owner);+ assert.equal(acked, 2);+ assert.match(updates[0].text, /^Approved\./);+ assert.equal(+ updates[0].blocks.some((b: any) => b.type === "actions"),+ false,+ );+});++test("shared-home members can approve and decline, outsiders cannot", async (t) => {+ const f = await fixture(t);+ await f.directory.upsertGroup("G1", [owner, "[email protected]"]);+ await f.app.moveArtifactHome("deploy", f.d.id, scopeId("group", "G1"), owner);+ assert.match(await f.decide("[email protected]", false), /^Declined\./);+ assert.match(await f.decide("[email protected]"), /^Approved\./);+ await assert.rejects(f.decide(requester, false), /owner/);+});++test("publish audiences notify once with final permissions, including subsequent direct shares", async (t) => {+ const f = await fixture(t);+ const d = await f.deploy.deployOrUpdate({+ ...publishInput(owner, "published"),+ share: [{ scope: person(requester), permission: "write" }],+ defaultAudience: {+ contextScopeId: person(owner),+ granteeScopeIds: [person(requester), person("[email protected]")],+ snapshotAt: Date.now(),+ },+ });+ const notices = await f.notices();+ assert.equal(notices.length, 2);+ const toRequester = notices.filter((n) => n.destination.target === requester);+ assert.equal(toRequester.length, 1);+ assert.match(toRequester[0]!.text, /manage it.*https:\/\/published.apps.example.com\//);+ const value = JSON.stringify({ deploymentId: d.id, requesterId: requester });+ await decideDeploymentAccess(f.app, f.identity, value, { externalId: owner }, true);+ await f.app.shareDeployment(d.id, person(requester), "write", { createdBy: owner });+ assert.equal((await f.notices()).length, 2);+});diff --git a/test/deploy-subdomain-signin.test.ts b/test/deploy-subdomain-signin.test.tsindex a9cd45238..e88ad0d57 100644--- a/test/deploy-subdomain-signin.test.ts+++ b/test/deploy-subdomain-signin.test.ts@@ -291,6 +291,7 @@ test("subdomain ingress: portal sign-in admits the owner, denies strangers, bountarget: "[email protected]",audienceScopeId: "personal:[email protected]",onBehalfOf: "[email protected]",+ deploymentAccess: { deploymentId: (await app.getDeployment("mysite"))!.id, requesterId: "[email protected]" },});const signedOutAsk = await httpPost(port, "/__claw__/request-access", { Host: host });diff --git a/test/live-slack/README.md b/test/live-slack/README.mdindex 4ed23b91c..091d9d0cb 100644--- a/test/live-slack/README.md+++ b/test/live-slack/README.md@@ -75,6 +75,24 @@ can't: event redelivery (dedupe/idempotency), mid-session scope revocation, andrate limiting. Scenarios that mutate workspace-global twin config use the `exclusive` lane(run alone, after the other lanes) and restore what they touched.+### App access requests (`@deploy-access`)++`scenarios-deploy-access.ts` drives the published-app access flow end to end on a twin:+a stranger hits an app's subdomain, clicks _Request access_, the owner gets a DM card with+Approve/Decline, a click (a signed `block_actions` POST to the receiver, as Slack would+send) grants view access and DMs the requester, and the requester then reaches the app+through the gateway. They carry the `apps-gateway` capability tag and skip unless the+instance has the gateway configured:++```sh+export DEPLOY_APPS_DOMAIN=apps.e2e.test AWS_DEPLOY_GATE_SECRET=$(openssl rand -hex 16) \+ DEPLOY_APPS_SESSION_SECRET=$(openssl rand -hex 16) DEPLOY_APPS_LOGIN_URL=http://localhost:8181+```++The default `docker` deploy provider needs a `docker` on PATH; a shim that runs each+published entrypoint as a host process is enough (the scenarios publish a one-file+`node server.mjs`).+## Tiers, triggers, quarantine- **Tiers via tags.** `@core` is the fast high-signal subset run on every push to main;diff --git a/test/live-slack/run.ts b/test/live-slack/run.tsindex 8d0fb3187..406ec9020 100644--- a/test/live-slack/run.ts+++ b/test/live-slack/run.ts@@ -200,6 +200,16 @@ function selectScenarios(env: Env): { selected: Scenario[]; skipped: ScenarioRes});continue;}+ if (tags.includes("apps-gateway") && !(process.env.DEPLOY_APPS_DOMAIN && process.env.DEPLOY_APPS_SESSION_SECRET)) {+ skipped.push({+ name: s.name,+ status: "skip",+ attempts: 0,+ durationMs: 0,+ skipReason: "instance has no apps gateway (needs DEPLOY_APPS_DOMAIN + DEPLOY_APPS_SESSION_SECRET)",+ });+ continue;+ }if (tags.includes("no-twin") && env.twin) {skipped.push({name: s.name,diff --git a/test/live-slack/scenarios-deploy-access.ts b/test/live-slack/scenarios-deploy-access.tsnew file mode 100644index 000000000..839f7e6a5--- /dev/null+++ b/test/live-slack/scenarios-deploy-access.ts@@ -0,0 +1,191 @@+import { request as httpRequest } from "node:http";+import { text } from "node:stream/consumers";+import { createHmac } from "node:crypto";+import { assert, type Actor, type Env, type Scenario } from "./harness.ts";+import { sleep, type SlackMessage } from "./slack.ts";+import { signedRequestHeaders } from "../../src/auth/source-auth-sign.ts";+import { mintPortalIdentity, PORTAL_IDENTITY_HEADER } from "../../src/auth/portal-identity.ts";++const CORE = () => (process.env.CORE_API_URL ?? "http://localhost:8181").replace(/\/+$/, "");+const SECRET = () => process.env.CORE_SIGNING_SECRET ?? "";+const APPS_DOMAIN = () => process.env.DEPLOY_APPS_DOMAIN ?? "";+const SESSION_SECRET = () => process.env.DEPLOY_APPS_SESSION_SECRET ?? "";+const EVENTS_URL = () =>+ process.env.SLACK_EVENTS_TARGET_URL ?? `http://127.0.0.1:${process.env.SLACK_EVENTS_PORT ?? "8182"}/slack/events`;++const APP_SOURCE = (marker: string) =>+ `import { createServer } from "node:http";\ncreateServer((req, res) => { res.writeHead(200, { "content-type": "text/plain" }); res.end("hello from ${marker}"); }).listen(Number(process.env.PORT), "127.0.0.1");\n`;++async function principalOf(env: Env, actor: Actor): Promise<string> {+ const r = await env.core+ .resolveDirectory(actor.handle)+ .catch(() => ({ members: [] as Array<{ principalId: string }> }));+ return r.members[0]?.principalId ?? actor.userId;+}++function portalSession(sub: string): string {+ const key = createHmac("sha256", SESSION_SECRET()).update("portal.session.v1").digest();+ const now = Math.floor(Date.now() / 1000);+ const body = Buffer.from(JSON.stringify({ k: "session", sub, org: "acme", iat: now, exp: now + 3600 })).toString(+ "base64url",+ );+ return `${body}.${createHmac("sha256", key).update(body).digest("base64url")}`;+}++function gateway(slug: string, sub: string, request = false): Promise<{ status: number; body: string }> {+ return new Promise((resolve, reject) => {+ const req = httpRequest(+ `${CORE()}${request ? "/__claw__/request-access" : "/"}`,+ {+ method: request ? "POST" : "GET",+ headers: {+ Host: `${slug}.${APPS_DOMAIN()}`,+ Accept: "text/html",+ Cookie: `portal_session=${portalSession(sub)}`,+ },+ },+ (res) => {+ text(res).then((body) => resolve({ status: res.statusCode ?? 0, body }), reject);+ },+ );+ req.setTimeout(45_000, () => req.destroy(new Error("gateway timeout")));+ req.on("error", reject);+ req.end();+ });+}++async function publishApp(owner: string, slug: string, marker: string): Promise<void> {+ const path = `/v1/deployments?_nonce=${crypto.randomUUID()}`;+ const body = JSON.stringify({+ ownerScopeId: `personal:${owner}`,+ createdBy: owner,+ name: slug,+ entrypoint: "node server.mjs",+ files: [{ path: "server.mjs", data: APP_SOURCE(marker) }],+ });+ const headers = signedRequestHeaders(SECRET(), "POST", path, body, {+ "content-type": "application/json",+ [PORTAL_IDENTITY_HEADER]: await mintPortalIdentity({ p: owner, exp: Date.now() + 60_000 }, SECRET()),+ });+ const res = await fetch(`${CORE()}${path}`, { method: "POST", headers, body, signal: AbortSignal.timeout(60_000) });+ assert.equal(res.status, 200, `publish failed: ${(await res.text()).slice(0, 300)}`);+}++async function waitFor<T>(label: string, fn: () => Promise<T | undefined>, timeoutMs = 90_000): Promise<T> {+ const deadline = Date.now() + timeoutMs;+ let last: unknown;+ while (Date.now() < deadline) {+ try {+ const v = await fn();+ if (v !== undefined) return v;+ } catch (e) {+ last = e;+ }+ await sleep(2000);+ }+ throw new Error(`timed out waiting for ${label}${last ? ` (last error: ${String(last)})` : ""}`);+}++function actionsOf(m: SlackMessage): Array<{ action_id: string; value: string; block_id?: string }> {+ const block = (m.blocks ?? []).find((b) => b.type === "actions") as+ { block_id?: string; elements?: Array<{ action_id: string; value: string }> } | undefined;+ return (block?.elements ?? []).map((e) => ({ ...e, block_id: block?.block_id }));+}++async function click(env: Env, clicker: Actor, channel: string, card: SlackMessage, actionId: string): Promise<number> {+ const action = actionsOf(card).find((a) => a.action_id === actionId);+ assert.ok(action, `card has no ${actionId} button: ${JSON.stringify(card.blocks).slice(0, 300)}`);+ const body = JSON.stringify({+ type: "block_actions",+ team: { id: env.teamId, domain: "e2e" },+ user: { id: clicker.userId, username: clicker.handle, team_id: env.teamId },+ api_app_id: "AE2E",+ container: { type: "message", message_ts: card.ts, channel_id: channel, is_ephemeral: false },+ channel: { id: channel, name: "directmessage" },+ message: { type: "message", ts: card.ts, text: card.text, user: env.botUserId },+ actions: [{ ...action, type: "button", action_ts: `${Date.now() / 1000}` }],+ });+ const ts = String(Math.floor(Date.now() / 1000));+ const signature = `v0=${createHmac("sha256", process.env.SLACK_SIGNING_SECRET ?? "")+ .update(`v0:${ts}:${body}`)+ .digest("hex")}`;+ const res = await fetch(EVENTS_URL(), {+ method: "POST",+ headers: { "Content-Type": "application/json", "X-Slack-Request-Timestamp": ts, "X-Slack-Signature": signature },+ body,+ signal: AbortSignal.timeout(15_000),+ });+ return res.status;+}++async function waitReachable(slug: string, sub: string, marker: string, label: string): Promise<void> {+ await waitFor(+ `${label} to reach the app`,+ async () => {+ const res = await gateway(slug, sub);+ return res.status === 200 && res.body.includes(`hello from ${marker}`) ? res : undefined;+ },+ 45_000,+ );+}++async function requestAccessAs(slug: string, requester: string): Promise<void> {+ const denied = await gateway(slug, requester);+ assert.equal(denied.status, 403, `stranger should be denied, got ${denied.status}: ${denied.body.slice(0, 200)}`);+ assert.match(denied.body, /Request access/);+ const asked = await gateway(slug, requester, true);+ assert.equal(asked.status, 200, `request-access failed: ${asked.body.slice(0, 200)}`);+}++export const deployAccessScenarios: Scenario[] = [true, false].map((approve) => ({+ name: approve ? "deploy-access-approve-button-grants-and-notifies" : "deploy-access-decline-button-tells-requester",+ lane: "parallel",+ tags: ["twin", "apps-gateway", "deploy-access"],+ actors: ["alice", "bob", "carol"],+ timeoutMs: 4 * 60_000,+ async run(ctx) {+ const env = ctx.env;+ const owner = env.actors.get(approve ? "alice" : "carol")!;+ const requester = env.actors.get("bob")!;+ const stranger = env.actors.get(approve ? "carol" : "alice")!;+ const [ownerId, requesterId] = await Promise.all([principalOf(env, owner), principalOf(env, requester)]);+ const marker = ctx.marker(approve ? "approve" : "decline");+ const slug = `access-${crypto.randomUUID().slice(0, 8)}`;+ await publishApp(ownerId, slug, marker);+ await waitReachable(slug, ownerId, marker, "the owner");+ const ownerDm = await owner.client.openDm(env.botUserId);+ const requesterDm = await requester.client.openDm(env.botUserId);+ const since = String(Date.now() / 1000 - 1);+ await requestAccessAs(slug, requesterId);+ const card = await waitFor("owner request card", async () =>+ (await owner.client.history(ownerDm, since)).find(+ (m) => m.user === env.botUserId && (m.text ?? "").includes(slug) && actionsOf(m).length === 2,+ ),+ );+ assert.ok(card.text?.includes(requesterId));+ const action = approve ? "deploy_access_approve" : "deploy_access_decline";+ assert.equal(await click(env, stranger, ownerDm, card, action), 200);+ await sleep(3000);+ assert.equal((await gateway(slug, requesterId)).status, 403, "a stranger's click must grant nothing");+ const unchanged = (await owner.client.history(ownerDm, since)).find((m) => m.ts === card.ts);+ assert.equal(actionsOf(unchanged!).length, 2, "a stranger cannot decide the card");+ assert.equal(await click(env, owner, ownerDm, card, action), 200);+ const settled = await waitFor("card to settle", async () => {+ const m = (await owner.client.history(ownerDm, since)).find((m) => m.ts === card.ts);+ return m && (m.text ?? "").startsWith(approve ? "Approved." : "Declined.") ? m : undefined;+ });+ assert.equal(actionsOf(settled).length, 0);+ const notice = await waitFor("requester notification", async () =>+ (await requester.client.history(requesterDm, since)).find(+ (m) =>+ m.user === env.botUserId &&+ (m.text ?? "").includes(slug) &&+ (m.text ?? "").includes(approve ? "gave you access" : "declined your request"),+ ),+ );+ if (approve) {+ assert.ok(notice.text?.includes(`https://${slug}.${APPS_DOMAIN()}/`));+ await waitReachable(slug, requesterId, marker, "the requester");+ } else assert.equal((await gateway(slug, requesterId)).status, 403, "decline grants nothing");+ },+}));diff --git a/test/live-slack/scenarios.ts b/test/live-slack/scenarios.tsindex 9adbb308a..eccb8d1df 100644--- a/test/live-slack/scenarios.ts+++ b/test/live-slack/scenarios.ts@@ -5,6 +5,7 @@ import { sleep, type SlackMessage } from "./slack.ts";import { assertRuntimeHandoff } from "./runtime-handoff.ts";import { multiUserScenarios } from "./scenarios-multiuser.ts";import { twinScenarios } from "./scenarios-twin.ts";+import { deployAccessScenarios } from "./scenarios-deploy-access.ts";const RAW_MARKDOWN_ARTIFACTS: Array<[string, RegExp]> = [["**bold**", /\*\*[^*\n]+\*\*/],@@ -526,4 +527,5 @@ export const scenarios: Scenario[] = [},...multiUserScenarios,...twinScenarios,+ ...deployAccessScenarios,];diff --git a/test/live-slack/slack.ts b/test/live-slack/slack.tsindex 38374fde2..6ee09386b 100644--- a/test/live-slack/slack.ts+++ b/test/live-slack/slack.ts@@ -8,6 +8,7 @@ export interface SlackMessage {thread_ts?: string;files?: Array<{ id?: string; name?: string; title?: string }>;subtype?: string;+ blocks?: Array<Record<string, unknown>>;}function apiUrlOf(raw: string): string {diff --git a/test/slack-deliveries.test.ts b/test/slack-deliveries.test.tsindex c85d2a39e..74399364f 100644--- a/test/slack-deliveries.test.ts+++ b/test/slack-deliveries.test.ts@@ -276,3 +276,14 @@ for (const type of ["group", "principal"]) {assert.equal(blocks.filter((block) => block.type === "context").length, 1);});}++test("principal delivery metadata renders an actionable deployment card", async () => {+ const request = { deploymentId: "00000000-0000-4000-8000-000000000001", requesterId: "[email protected]" };+ const { posts } = await deliver(+ JSON.parse(JSON.stringify({ type: "principal", target: "U1", deploymentAccess: request })),+ );+ const blocks = posts[0]!.blocks as Array<{ type: string; elements?: Array<{ value: string }> }>;+ const actions = blocks.find((b) => b.type === "actions")!;+ assert.equal(actions.elements!.length, 2);+ assert.deepEqual(JSON.parse(actions.elements![0]!.value), request);+});diff --git a/test/slack-index.integration.test.ts b/test/slack-index.integration.test.tsindex 14d1d535b..525f5c90e 100644--- a/test/slack-index.integration.test.ts+++ b/test/slack-index.integration.test.ts@@ -226,6 +226,9 @@ mock.module("@slack/web-api", {const { slackPluginConfigFromEnv, startSlackPlugin } = await import("../src/slack/index.ts");class FakeCore implements SlackCoreClient {+ async decideDeploymentAccess(): Promise<string> {+ throw new Error("not used");+ }async inboxSlackMessage(): Promise<void> {}readonly turns: any[] = [];readonly ingests: any[][] = [];