Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Tighten Slack account policy handling (#1923)

Joshua Francecb5bf31bcb3f
diff --git a/docs/external-slack.md b/docs/external-slack.md
index 26b511743..96130e9da 100644
--- a/docs/external-slack.md
+++ b/docs/external-slack.md
@@ -11,6 +11,7 @@ Add `externalAccess` to the selected `SLACK_ACCOUNTS` entry:
"appToken": "<Socket Mode token>",
"externalAccess": {
"companyDomains": ["company.example"],
+ "companyTeamIds": ["TCOMPANY"],
"serviceCredentials": ["public-search"]
}
}
@@ -20,7 +21,9 @@ For the default Slack account, set `SLACK_EXTERNAL_ACCESS` to the JSON value of
## Identity and public work
-Slack's authenticated user profile must contain an email whose exact domain is in `companyDomains`. Case is normalized. Subdomains are not implicitly included. Workspace membership, guest status, and Slack Connect status do not establish company identity. Missing emails, non-company emails, deleted users, and bots cannot initiate work. `allowFrom`, if configured, can further restrict access.
+Set `companyTeamIds` to Slack workspace IDs administered by your company. This required, non-empty list identifies the workspaces trusted to establish employee identity; do not include the partner workspace. Existing external-access configurations must add this list before restarting.
+
+The user's Slack `team_id` must be in `companyTeamIds`, and their profile must contain an email whose exact domain is in `companyDomains`. Email case is normalized; workspace IDs are matched exactly. Subdomains are not implicitly included. Company members connecting from those workspaces through Slack Connect are supported. Accounts belonging to the partner workspace, missing workspace IDs or emails, non-company emails, restricted guests, deleted users, and bots cannot initiate work, including DMs. `allowFrom`, if configured, can further restrict access.
Every non-DM conversation in an opted-in workspace has an external audience, including private channels and group DMs with an apparently staff-only roster. Its computer and conversation use a workspace-and-policy namespace. Enabling this policy, or changing its allowlists, starts a fresh restricted namespace rather than exposing an older computer or retained private context.
@@ -33,7 +36,7 @@ The channel agent can answer and execute code using its own restricted computer.
When the request needs personal context or a private service, the agent finishes the channel turn with a self-only continuation directive. The platform:
1. Loads the originating request, not a model-selected recipient.
-2. Rechecks the employee's current Slack profile on the originating account.
+2. Rechecks the employee's company workspace membership and email against the current policy on the originating account.
3. Opens that employee's DM and acknowledges the move in the source thread.
4. Queues a normal personal-context turn with the original request, relevant channel history, and incoming attachments.
5. Delivers results and approvals privately. There is no automatic result bridge back to the channel.
@@ -45,5 +48,6 @@ This is a general continuation mechanism, not a calendar-specific workflow. Exis
- Explicit mentions, genuine replies in an engaged thread, and employee DMs are supported. Passive ambient ingestion is disabled for opted-in accounts so it cannot start an unclassified alternate turn.
- Existing shared-scope approvals and legacy personal-agent bridges are not resumed in an opted-in workspace. Start a fresh request so it receives the current boundary.
- Old shared replies without the restricted namespace are not released into an opted-in workspace during delivery recovery. Unprovenanced historical shared Slack requests are refused when an external policy is configured.
-- Restricted sessions cannot be resumed through a surface that omits their authenticated workspace policy. Normal private DMs are unaffected.
+- Recovered DM run results also require the current external-account policy. Results admitted before this policy configuration or under a previous policy are not delivered.
+- Restricted sessions cannot be resumed through a surface that omits their authenticated workspace policy. External-account DMs also require admission under the current policy; after a policy change, start a fresh request. DMs on other accounts are unaffected.
- Configuration is deployment-level; there is no new admin UI in this change.
diff --git a/src/delivery/run-result-delivery.ts b/src/delivery/run-result-delivery.ts
index 63037d8e6..171989a0b 100644
--- a/src/delivery/run-result-delivery.ts
+++ b/src/delivery/run-result-delivery.ts
@@ -54,6 +54,9 @@ export function runResultDelivery(
...(run.request.slackSource
? { slackAccountId: run.request.slackSource.accountId, slackTeamId: run.request.slackSource.teamId }
: {}),
+ ...(run.request.slackSource?.externalPolicyNamespace
+ ? { slackPolicyNamespace: run.request.slackSource.externalPolicyNamespace }
+ : {}),
...(editRef ? { editRef } : {}),
...(taskList.length ? { taskList: taskList.map(({ id, title, status }) => ({ id, title, status })) } : {}),
...(webTranscript ? { webTranscript } : {}),
diff --git a/src/resolution/external-slack.ts b/src/resolution/external-slack.ts
index a197f113e..97478422c 100644
--- a/src/resolution/external-slack.ts
+++ b/src/resolution/external-slack.ts
@@ -24,14 +24,24 @@ export function externalSlackRequestAllowed(
externalSlackNamespace(supplied.teamId, current) ===
externalSlackNamespace(supplied.teamId, {
companyDomains: supplied.companyDomains,
+ companyTeamIds: supplied.companyTeamIds,
serviceCredentials: supplied.serviceCredentials,
}) &&
ref.startsWith(`${externalSlackNamespace(supplied.teamId, current)}:`)
);
}
if (ref.includes("external-slack:")) return false;
+ if (request.slackSource) {
+ const source = request.slackSource;
+ const policy = policies[source.accountId];
+ return (
+ !policy ||
+ (request.conversation.kind === "dm" &&
+ source.externalPolicyNamespace === externalSlackNamespace(source.teamId, policy))
+ );
+ }
+ if (ref.startsWith("slack-account:")) return false;
if (request.conversation.kind === "dm") return true;
- if (request.slackSource) return !policies[request.slackSource.accountId];
return !(Object.keys(policies).length && (request.surface === "slack" || historicalSlack));
}
diff --git a/src/slack/deliveries.ts b/src/slack/deliveries.ts
index ed6116a4b..deeeafba4 100644
--- a/src/slack/deliveries.ts
+++ b/src/slack/deliveries.ts
@@ -57,7 +57,7 @@ function mergeSlackApiMs(body: unknown, slackApiMs: number | undefined): unknown
export function createDeliveryPoller(deps: {
clientForAccount?: (accountId: string, teamId?: string) => any;
- externalAccount?: (accountId: string) => boolean;
+ externalNamespace?: (accountId: string) => string | undefined;
continuePrivate?: (runId: string, task: string) => Promise<void>;
core: SlackCoreClient;
webUiPublicUrl?: string;
@@ -200,15 +200,17 @@ export function createDeliveryPoller(deps: {
const destinationClient = deliveryClient(defaultClient, d.destination);
if (!destinationClient) return;
const client = destinationClient;
+ const runId = d.idempotencyKey?.startsWith("run:") ? d.idempotencyKey.slice("run:".length) : undefined;
+ const namespace = deps.externalNamespace?.(d.destination.slackAccountId ?? "default");
if (
- deps.externalAccount?.(d.destination.slackAccountId ?? "default") &&
- !parseDeliveryTarget(d.destination.target).channel.startsWith("D") &&
- !d.provenance?.sourceThreadRef.startsWith("external-slack:")
+ namespace &&
+ (parseDeliveryTarget(d.destination.target).channel.startsWith("D")
+ ? runId && d.destination.slackPolicyNamespace !== namespace
+ : !d.provenance?.sourceThreadRef.startsWith(`${namespace}:`))
) {
await ackDelivery(d.id);
return;
}
- const runId = d.idempotencyKey?.startsWith("run:") ? d.idempotencyKey.slice("run:".length) : undefined;
if (runId && inFlightRuns.has(runId)) return;
if (runId && typeof d.createdAt === "number" && Date.now() - d.createdAt < RUN_RECOVERY_GRACE_MS) return;
let slackApiMs: number | undefined;
diff --git a/src/slack/external-access.ts b/src/slack/external-access.ts
index 65593009b..64b2a11ff 100644
--- a/src/slack/external-access.ts
+++ b/src/slack/external-access.ts
@@ -3,6 +3,7 @@ import type { SlackUser, ActorAssertion } from "./identity.ts";
export interface ExternalSlackAccess {
companyDomains: string[];
+ companyTeamIds: string[];
serviceCredentials: string[];
}
@@ -12,6 +13,7 @@ export function parseExternalSlackAccess(value: unknown): ExternalSlackAccess |
throw new Error("externalAccess must be an object");
const raw = value as Record<string, unknown>;
const domains = raw.companyDomains;
+ const teams = raw.companyTeamIds;
const services = raw.serviceCredentials ?? [];
if (
!Array.isArray(domains) ||
@@ -19,10 +21,13 @@ export function parseExternalSlackAccess(value: unknown): ExternalSlackAccess |
domains.some((d) => typeof d !== "string" || !/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}$/i.test(d))
)
throw new Error("externalAccess.companyDomains must contain exact company email domains");
+ if (!Array.isArray(teams) || !teams.length || teams.some((t) => typeof t !== "string" || !/^T[A-Z0-9]+$/.test(t)))
+ throw new Error("externalAccess.companyTeamIds must contain company Slack workspace IDs");
if (!Array.isArray(services) || services.some((s) => typeof s !== "string" || !/^[a-z0-9][a-z0-9_-]*$/.test(s)))
throw new Error("externalAccess.serviceCredentials must contain credential slugs");
return {
companyDomains: [...new Set(domains.map((d: string) => d.toLowerCase()))].sort(),
+ companyTeamIds: [...new Set(teams as string[])].sort(),
serviceCredentials: [...new Set(services as string[])].sort(),
};
}
@@ -34,6 +39,10 @@ export function companySlackActor(user: SlackUser | undefined, policy: ExternalS
user?.id &&
!user.deleted &&
!user.is_bot &&
+ !user.is_restricted &&
+ !user.is_ultra_restricted &&
+ user.team_id &&
+ policy.companyTeamIds?.includes(user.team_id) &&
parts.length === 2 &&
parts[0] &&
policy.companyDomains.includes(parts[1]!),
diff --git a/src/slack/index.ts b/src/slack/index.ts
index 88df5e36c..882fdb9d9 100644
--- a/src/slack/index.ts
+++ b/src/slack/index.ts
@@ -1,5 +1,5 @@
import { continueInPrivate } from "./private-continuation.ts";
-import { type ExternalSlackAccess } from "./external-access.ts";
+import { externalSlackNamespace, type ExternalSlackAccess } from "./external-access.ts";
import { registerKeychainApprovalActions } from "./keychain-approvals.ts";
import { registerDeployAccessActions } from "./deploy-access.ts";
import { SlackPluginStartCleanupError } from "../surfaces/slack-runtime.ts";
@@ -441,7 +441,10 @@ export async function startSlackPlugin(
if (!account || (teamId && account.teamId !== teamId)) return undefined;
return account.client;
},
- externalAccount: (id) => !!slackAccountClients.get(id)?.policy,
+ externalNamespace: (id) => {
+ const account = slackAccountClients.get(id);
+ return account?.policy ? externalSlackNamespace(account.teamId, account.policy) : undefined;
+ },
continuePrivate: (runId, task) => continueInPrivate(core, runId, task, (id) => slackAccountClients.get(id)),
core,
flow,
diff --git a/src/slack/private-continuation.ts b/src/slack/private-continuation.ts
index d69eabdcf..516d6d904 100644
--- a/src/slack/private-continuation.ts
+++ b/src/slack/private-continuation.ts
@@ -4,7 +4,7 @@ import { toSlackMrkdwn } from "./mrkdwn.ts";
import { userFacingFailureClause } from "../core/failure-copy.ts";
import type { SlackCoreClient } from "../api/slack-core-client.ts";
import type { ExternalSlackAccess } from "./external-access.ts";
-import { companySlackActor } from "./external-access.ts";
+import { companySlackActor, externalSlackNamespace } from "./external-access.ts";
import { dmThreadRef } from "./message-gating.ts";
import { encodeDeliveryTarget, parseDeliveryTarget, postWithVerify, slackReplyArgs } from "./delivery.ts";
@@ -48,7 +48,12 @@ export async function continueInPrivate(
);
const result = await core.submitTurn({
actor,
- slackSource: { accountId: origin.accountId, teamId: origin.teamId, userId: origin.userId },
+ slackSource: {
+ accountId: origin.accountId,
+ teamId: origin.teamId,
+ userId: origin.userId,
+ externalPolicyNamespace: externalSlackNamespace(origin.teamId, policy),
+ },
conversation: {
kind: "dm",
threadRef: `slack-account:${origin.teamId}:${dmThreadRef(dm)}`,
diff --git a/src/slack/turn-handler.ts b/src/slack/turn-handler.ts
index 82bd37ec9..cad339348 100644
--- a/src/slack/turn-handler.ts
+++ b/src/slack/turn-handler.ts
@@ -534,7 +534,16 @@ export function createTurnHandler(deps: {
const turn: Omit<CoreTurnBody, "approval"> = {
actor,
...(inc.userId
- ? { slackSource: { accountId: deps.accountId ?? "default", teamId: ids.ownTeamId, userId: inc.userId } }
+ ? {
+ slackSource: {
+ accountId: deps.accountId ?? "default",
+ teamId: ids.ownTeamId,
+ userId: inc.userId,
+ ...(deps.externalAccess
+ ? { externalPolicyNamespace: externalSlackNamespace(ids.ownTeamId, deps.externalAccess) }
+ : {}),
+ },
+ }
: {}),
...(deps.externalAccess && inc.kind === "channel" && inc.userId
? {
diff --git a/src/types.ts b/src/types.ts
index 8a14d3999..4c93ba989 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -207,6 +207,7 @@ export interface TriggerBase {
export interface Destination {
slackAccountId?: string;
slackTeamId?: string;
+ slackPolicyNamespace?: string;
keychainAskId?: string;
deploymentAccess?: { deploymentId: string; requesterId: string };
commandApprovalId?: string;
@@ -656,12 +657,13 @@ export interface ClientToolResult {
}
export interface TurnRequest {
- slackSource?: { accountId: string; teamId: string; userId: string };
+ slackSource?: { accountId: string; teamId: string; userId: string; externalPolicyNamespace?: string };
externalSlack?: {
accountId: string;
teamId: string;
userId: string;
companyDomains: string[];
+ companyTeamIds: string[];
serviceCredentials: string[];
};
sessionSenderId?: string;
diff --git a/test/external-slack-core.test.ts b/test/external-slack-core.test.ts
index c8155a746..c2e665e1d 100644
--- a/test/external-slack-core.test.ts
+++ b/test/external-slack-core.test.ts
@@ -11,7 +11,7 @@ import { externalTools } from "../src/core/orchestrator/external-tools.ts";
import type { ToolContext } from "../src/tools/primitives.ts";
import type { TurnRequest } from "../src/types.ts";
-const policy = { companyDomains: ["example.com"], serviceCredentials: ["safe"] };
+const policy = { companyDomains: ["example.com"], companyTeamIds: ["TCOMPANY"], serviceCredentials: ["safe"] };
const externalSlackPolicies = { batch: policy };
const namespace = externalSlackNamespace("T1", policy);
function request(text: string): TurnRequest {
@@ -24,6 +24,7 @@ function request(text: string): TurnRequest {
teamId: "T1",
userId: "U1",
companyDomains: ["example.com"],
+ companyTeamIds: ["TCOMPANY"],
serviceCredentials: ["safe"],
},
conversation: {
@@ -120,6 +121,13 @@ test("external Slack strips private and org preloads before the prompt, but keep
const missing = request("!sysprompt");
delete missing.externalSlack;
assert.equal((await b.app.turn(missing)).status, "refused");
+ const privateRequest = {
+ ...missing,
+ slackSource: { accountId: "batch", teamId: "T1", userId: "U1" },
+ conversation: { kind: "dm" as const, threadRef: "slack-account:T1:dm:D1" },
+ };
+ assert.equal((await b.app.turn(privateRequest)).status, "refused");
+ assert.equal((await b.app.turn({ ...privateRequest, slackSource: undefined })).status, "refused");
});
test("external native tool ceiling cannot delegate, switch sandboxes, read confidential data or invoke MCP", async () => {
@@ -217,6 +225,7 @@ test("external policy changes invalidate retained requests while untouched works
assert.equal(externalSlackRequestAllowed(req, externalSlackPolicies), true);
assert.equal(externalSlackRequestAllowed(req, {}), false);
assert.equal(externalSlackRequestAllowed(req, { batch: { ...policy, serviceCredentials: [] } }), false);
+ assert.equal(externalSlackRequestAllowed(req, { batch: { ...policy, companyTeamIds: ["TOTHER"] } }), false);
const legacy = {
...req,
externalSlack: undefined,
@@ -237,6 +246,26 @@ test("external policy changes invalidate retained requests while untouched works
);
});
+test("external account DMs require admission under the current policy", async () => {
+ const { externalSlackRequestAllowed } = await import("../src/resolution/external-slack.ts");
+ const dm = {
+ surface: "slack",
+ conversation: { kind: "dm" as const, threadRef: "slack-account:T1:dm:D1" },
+ slackSource: { accountId: "batch", teamId: "T1", userId: "U1" },
+ };
+ assert.equal(externalSlackRequestAllowed(dm, externalSlackPolicies), false);
+ assert.equal(externalSlackRequestAllowed({ ...dm, slackSource: undefined }, externalSlackPolicies), false);
+ const current = { ...dm, slackSource: { ...dm.slackSource, externalPolicyNamespace: namespace } };
+ assert.equal(externalSlackRequestAllowed(current, externalSlackPolicies), true);
+ for (const changed of [
+ { ...policy, companyTeamIds: ["TOTHER"] },
+ { ...policy, companyDomains: ["other.example"] },
+ { ...policy, serviceCredentials: [] },
+ ])
+ assert.equal(externalSlackRequestAllowed(current, { batch: changed }), false);
+ assert.equal(externalSlackRequestAllowed(dm, {}), true);
+});
+
test("external sandbox API token cannot reach private APIs, while its safe broker token works", async (t) => {
const { createServer } = await import("../src/api/server.ts");
const { mintCapabilityToken } = await import("../src/auth/capability-token.ts");
diff --git a/test/external-slack-policy.test.ts b/test/external-slack-policy.test.ts
index 830f9a0ce..4d242f9b1 100644
--- a/test/external-slack-policy.test.ts
+++ b/test/external-slack-policy.test.ts
@@ -11,20 +11,26 @@ import { continueInPrivate, PRIVATE_CONTINUATION_ACK } from "../src/slack/privat
import { createDeliveryPoller } from "../src/slack/deliveries.ts";
import type { SlackCoreClient } from "../src/api/slack-core-client.ts";
import type { TurnRequest } from "../src/types.ts";
+import { createDirectory } from "../src/slack/directory.ts";
+import { createTurnHandler } from "../src/slack/turn-handler.ts";
-const policy = { companyDomains: ["company.example"], serviceCredentials: ["public-search"] };
-const employee = { id: "UEMPLOYEE", team_id: "TPARTNER", profile: { email: " [email protected] " } };
+const policy = {
+ companyDomains: ["company.example"],
+ companyTeamIds: ["TCOMPANY"],
+ serviceCredentials: ["public-search"],
+};
+const employee = { id: "UEMPLOYEE", team_id: "TCOMPANY", profile: { email: " [email protected] " } };
-test("external workspace identity uses exact email domain, not Slack membership or guest status", () => {
+test("external workspace identity requires company workspace membership and an exact email domain", () => {
assert.equal(companySlackActor(employee, policy).externalId, "[email protected]");
- assert.equal(
- companySlackActor({ ...employee, is_restricted: true, is_stranger: true, team_id: "TOTHER" }, policy)
- .isExternalGuest,
- false,
- );
+ assert.equal(companySlackActor({ ...employee, is_stranger: true }, policy).isExternalGuest, false);
for (const user of [
undefined,
{ id: "UNOEMAIL", team_id: "TPARTNER" },
+ { ...employee, team_id: "TPARTNER" },
+ { ...employee, team_id: undefined },
+ { ...employee, is_restricted: true },
+ { ...employee, is_ultra_restricted: true },
{ ...employee, deleted: true },
{ ...employee, is_bot: true },
...["[email protected]", "[email protected]", "[email protected]", "e@@company.example"].map(
@@ -32,6 +38,7 @@ test("external workspace identity uses exact email domain, not Slack membership
),
])
assert.equal(companySlackActor(user, policy).isExternalGuest, true);
+ assert.equal(companySlackActor(employee, { ...policy, companyTeamIds: [] }).isExternalGuest, true);
});
test("external access is opt-in per workspace and rejects malformed allowlists", () => {
@@ -63,13 +70,95 @@ test("external access is opt-in per workspace and rejects malformed allowlists",
{},
{ companyDomains: [] },
{ companyDomains: ["*.company.example"] },
+ { companyDomains: policy.companyDomains },
+ { ...policy, companyTeamIds: [] },
+ { ...policy, companyTeamIds: "TCOMPANY" },
+ { ...policy, companyTeamIds: [""] },
+ { ...policy, companyTeamIds: [" company "] },
+ { ...policy, companyTeamIds: [42] },
{ ...policy, serviceCredentials: "all" },
])
assert.throws(() => parseExternalSlackAccess(value));
- assert.deepEqual(parseExternalSlackAccess({ companyDomains: ["COMPANY.EXAMPLE", "company.example"] }), {
- companyDomains: ["company.example"],
- serviceCredentials: [],
- });
+ assert.deepEqual(
+ parseExternalSlackAccess({
+ companyDomains: ["COMPANY.EXAMPLE", "company.example"],
+ companyTeamIds: ["TCOMPANY", "TANOTHER", "TCOMPANY"],
+ }),
+ {
+ companyDomains: ["company.example"],
+ companyTeamIds: ["TANOTHER", "TCOMPANY"],
+ serviceCredentials: [],
+ },
+ );
+});
+
+test("external account directory lookups admit only company workspace DMs", async () => {
+ for (const [snapshot, teamId] of [
+ [false, "TPARTNER"],
+ [true, "TPARTNER"],
+ [false, "TCOMPANY"],
+ [true, "TCOMPANY"],
+ ] as const) {
+ const user = { ...employee, team_id: teamId };
+ const trusted = teamId === "TCOMPANY";
+ const turns: Omit<TurnRequest, "surface">[] = [];
+ const personalScopes: string[] = [];
+ const ids = {
+ ownTeamId: "TPARTNER",
+ botUserId: "BOT",
+ ownBotId: "B1",
+ botHandle: "bot",
+ ownWorkspaceUrl: "",
+ identityMode: "email" as const,
+ };
+ const client = {
+ async *paginate() {
+ yield { members: snapshot ? [user] : [] };
+ },
+ users: { info: async () => ({ user }) },
+ };
+ const directory = createDirectory({
+ core: {} as SlackCoreClient,
+ ids,
+ externalAccess: policy,
+ coreSingleton: false,
+ });
+ const actor = (await directory.classifyUserCached(client, user.id)).actor;
+ assert.equal(actor.isExternalGuest, !trusted);
+ assert.equal(actor.externalId, trusted ? "[email protected]" : employee.id);
+ const handler = createTurnHandler({
+ externalAccess: policy,
+ directory,
+ ids,
+ core: {},
+ mirror: { mirrorMessageEvent: async () => {} },
+ flow: {
+ callCore: async (turn: Omit<TurnRequest, "surface">) => {
+ turns.push(turn);
+ return { status: "silent" };
+ },
+ },
+ ackEmoji: { requestAckEmoji: async () => undefined, ackPickCandidates: () => [] },
+ ensureHeader: (_client: unknown, _channel: string, scope: string) => personalScopes.push(scope),
+ } as unknown as Parameters<typeof createTurnHandler>[0]);
+ await handler.handleIncoming(
+ {
+ kind: "dm",
+ channel: "DPRIVATE",
+ userId: user.id,
+ rawText: "hello",
+ files: [],
+ ts: "1.0",
+ },
+ client,
+ );
+ assert.equal(turns.length, trusted ? 1 : 0);
+ assert.deepEqual(personalScopes, trusted ? ["personal:[email protected]"] : []);
+ if (trusted) {
+ assert.equal(turns[0]?.slackSource?.externalPolicyNamespace, externalSlackNamespace("TPARTNER", policy));
+ assert.equal(turns[0]?.externalSlack, undefined);
+ }
+ }
});
test("scope namespace changes when workspace or authorization policy changes", () => {
@@ -77,6 +166,7 @@ test("scope namespace changes when workspace or authorization policy changes", (
assert.match(original, /^external-slack:TPARTNER:/);
assert.notEqual(original, externalSlackNamespace("TOTHER", policy));
assert.notEqual(original, externalSlackNamespace("TPARTNER", { ...policy, serviceCredentials: [] }));
+ assert.notEqual(original, externalSlackNamespace("TPARTNER", { ...policy, companyTeamIds: ["TOTHER"] }));
});
test("private continuation directive is self-only and strips incomplete directives", () => {
@@ -155,6 +245,7 @@ test("handoff preserves request and participant list, runs in requester DM, and
assert.equal(request.actor.externalId, f.source.actor.externalId);
assert.equal(request.conversation.kind, "dm");
assert.equal(request.externalSlack, undefined);
+ assert.equal(request.slackSource?.externalPolicyNamespace, externalSlackNamespace("TPARTNER", policy));
assert.equal(request.deliveryTarget, "DPRIVATE");
assert.match(request.conversation.threadRef, /^slack-account:TPARTNER:/);
assert.match(request.text, /Invite Alex and Morgan/);
@@ -167,10 +258,12 @@ test("handoff preserves request and participant list, runs in requester DM, and
});
test("handoff fails closed on revoked identity, wrong workspace, and missing DM", async () => {
- for (const scenario of ["revoked", "workspace", "no-dm"]) {
+ for (const scenario of ["revoked", "home-workspace", "workspace", "no-dm"]) {
const f = handoffFixture();
if (scenario === "revoked")
f.client.users.info = async () => ({ user: { ...employee, profile: { email: "[email protected]" } } });
+ if (scenario === "home-workspace")
+ f.client.users.info = async () => ({ user: { ...employee, team_id: "TPARTNER" } });
if (scenario === "no-dm") f.client.conversations.open = async () => ({ channel: { id: "CNOTADM" } });
await assert.rejects(
continueInPrivate(f.core, "source", "private task", () => ({
@@ -208,7 +301,12 @@ test("delivery recovery routes private result only through its originating accou
idempotencyKey: "run:dm-run",
text: "Synthetic private result",
createdAt: Date.now() - 30_000,
- destination: { type: "slack", target: "DPRIVATE", slackAccountId: "partner" },
+ destination: {
+ type: "slack",
+ target: "DPRIVATE",
+ slackAccountId: "partner",
+ slackPolicyNamespace: externalSlackNamespace("TPARTNER", policy),
+ },
},
];
},
@@ -227,6 +325,7 @@ test("delivery recovery routes private result only through its originating accou
assert.equal(id, "partner");
return client;
},
+ externalNamespace: () => externalSlackNamespace("TPARTNER", policy),
});
await poller.pollDeliveries({
chat: {
@@ -274,8 +373,13 @@ test("external workspace refuses legacy personal-agent approval before reading i
assert.equal(acknowledged, true);
});
-test("external account poller neither claims default identity nor releases pre-policy shared answers", async () => {
- for (const hasDefault of [false, true]) {
+test("external account poller neither claims default identity nor releases pre-policy answers", async () => {
+ for (const [hasDefault, target, slackPolicyNamespace] of [
+ [false, "CSHARED", undefined],
+ [true, "CSHARED", undefined],
+ [true, "DPRIVATE", undefined],
+ [true, "DPRIVATE", externalSlackNamespace("TPARTNER", { ...policy, companyTeamIds: ["TOTHER"] })],
+ ] as const) {
let pending = true;
const acks: string[] = [];
const core = {
@@ -289,7 +393,7 @@ test("external account poller neither claims default identity nor releases pre-p
idempotencyKey: "run:legacy",
text: "Synthetic pre-policy private answer",
createdAt: 1,
- destination: { type: "slack", target: "CSHARED" },
+ destination: { type: "slack", target, slackPolicyNamespace },
},
];
},
@@ -313,7 +417,7 @@ test("external account poller neither claims default identity nor releases pre-p
assert.equal(id, "default");
return hasDefault ? client : undefined;
},
- externalAccount: () => true,
+ externalNamespace: () => externalSlackNamespace("TPARTNER", policy),
});
await poller.pollDeliveries(client);
assert.deepEqual(acks, hasDefault ? ["legacy"] : []);
diff --git a/test/run-result-delivery.test.ts b/test/run-result-delivery.test.ts
index 5b9c62b89..133e7ce9a 100644
--- a/test/run-result-delivery.test.ts
+++ b/test/run-result-delivery.test.ts
@@ -69,6 +69,25 @@ test("runResultDelivery carries the reply's attachments so recovery can replay t
assert.equal(d?.text, "here's the file");
});
+test("runResultDelivery retains the Slack policy used for private admission", () => {
+ const request = {
+ ...turn("hi", "DPRIVATE"),
+ slackSource: {
+ accountId: "partner",
+ teamId: "TPARTNER",
+ userId: "U1",
+ externalPolicyNamespace: "external-slack:TPARTNER:policy",
+ },
+ };
+ assert.deepEqual(runResultDelivery(run({ request }))?.destination, {
+ type: "slack",
+ target: "DPRIVATE",
+ slackAccountId: "partner",
+ slackTeamId: "TPARTNER",
+ slackPolicyNamespace: request.slackSource.externalPolicyNamespace,
+ });
+});
+
test("runResultDelivery recovers an attachments-only reply (empty text, files still land)", () => {
const atts = [{ name: "report.csv", mimetype: "text/csv", sizeBytes: 42, blobId: "blob-1" }];
const d = runResultDelivery(run({ result: { status: "ok", attachments: atts } }));
diff --git a/test/session-syscalls.test.ts b/test/session-syscalls.test.ts
index e845c475f..fa50c5cc4 100644
--- a/test/session-syscalls.test.ts
+++ b/test/session-syscalls.test.ts
@@ -1661,7 +1661,7 @@ for (const surface of ["slack", "web"] as const) {
test("children of a Slack group turn keep its source so external-workspace policy admits them", async () => {
const { externalSlackRequestAllowed } = await import("../src/resolution/external-slack.ts");
const { externalSlackNamespace } = await import("../src/slack/external-access.ts");
- const access = { companyDomains: ["partner.example"], serviceCredentials: ["search"] };
+ const access = { companyDomains: ["partner.example"], companyTeamIds: ["TCOMPANY"], serviceCredentials: ["search"] };
const policies = { ext: access };
const admitted = (request: OrchestratorInput) =>
externalSlackRequestAllowed({ ...request, surface: request.surface ?? "" }, policies);