From dfd9e9fddddbeed57f0daa536429ff83bba3be70 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 25 Aug 2026 16:52:52 -0700 Subject: [PATCH 01/13] fix(onboard): bind Discord policy to create providers Signed-off-by: Aaron Erickson --- src/lib/onboard/initial-policy.ts | 44 ++++- src/lib/onboard/sandbox-create-intent.ts | 21 ++- .../sandbox-create-plan-materialization.ts | 27 ++- src/lib/onboard/sandbox-create-plan.test.ts | 163 +++++++++++++++++- 4 files changed, 236 insertions(+), 19 deletions(-) diff --git a/src/lib/onboard/initial-policy.ts b/src/lib/onboard/initial-policy.ts index 4e05baef0c2..341a335c110 100644 --- a/src/lib/onboard/initial-policy.ts +++ b/src/lib/onboard/initial-policy.ts @@ -36,6 +36,8 @@ import { isPortableExperimentalProfile } from "./experimental/portable-profile"; export type InitialSandboxPolicy = { policyPath: string; appliedPresets: string[]; + /** Exact provider names referenced by credential-bound endpoints in this policy. */ + credentialBindingProviders?: string[]; sourceBytes?: Buffer; cleanup?: () => boolean; cleanupExact?: () => boolean; @@ -361,6 +363,32 @@ export function getNetworkPolicyNames(policyContent: string): Set | null } } +function getCredentialBindingProviders(policyContent: string): string[] { + const parsed = YAML.parse(policyContent); + if (!isObjectRecord(parsed) || !isObjectRecord(parsed.network_policies)) return []; + + const providers = new Set(); + for (const policy of Object.values(parsed.network_policies)) { + if (!isObjectRecord(policy) || !Array.isArray(policy.endpoints)) continue; + for (const endpoint of policy.endpoints) { + if (!isObjectRecord(endpoint) || endpoint.credential_binding === undefined) continue; + const binding = endpoint.credential_binding; + if ( + !isObjectRecord(binding) || + typeof binding.provider !== "string" || + binding.provider.length === 0 || + binding.provider.trim() !== binding.provider + ) { + throw new Error( + "Cannot prepare sandbox create policy; a credential binding has no exact provider name.", + ); + } + providers.add(binding.provider); + } + } + return [...providers]; +} + function filterHermesInactiveMessagingPolicies( policyContent: string, activeMessagingChannels: string[], @@ -444,12 +472,16 @@ function resolveInitialSandboxCreatePolicy( .every(Boolean) : undefined; const exactCleanupResult = () => (exactCleanup ? { cleanupExact: buildExactCleanup() } : {}); - const result = (appliedPresets: string[]): InitialSandboxPolicy => ({ - ...effectivePolicy, - appliedPresets, - cleanup: buildCleanup(), - ...exactCleanupResult(), - }); + const result = (appliedPresets: string[]): InitialSandboxPolicy => { + const credentialBindingProviders = getCredentialBindingProviders(basePolicy); + return { + ...effectivePolicy, + appliedPresets, + ...(credentialBindingProviders.length > 0 ? { credentialBindingProviders } : {}), + cleanup: buildCleanup(), + ...exactCleanupResult(), + }; + }; const cleanupOnError = () => { for (const cleanup of [...cleanupFns].reverse()) { try { diff --git a/src/lib/onboard/sandbox-create-intent.ts b/src/lib/onboard/sandbox-create-intent.ts index d7372fd70ba..c05274c12aa 100644 --- a/src/lib/onboard/sandbox-create-intent.ts +++ b/src/lib/onboard/sandbox-create-intent.ts @@ -22,9 +22,13 @@ function filterEnabledChannelNames( function filterMessagingProviderRequestsByEnabledChannel( requests: readonly SandboxCreateMessagingProviderRequest[], + selectedChannelNames: ReadonlySet, disabledChannelNames: ReadonlySet, ): SandboxCreateMessagingProviderRequest[] { - return requests.filter(({ channel }) => !channel || !disabledChannelNames.has(channel)); + return requests.filter( + ({ channel }) => + !channel || (selectedChannelNames.has(channel) && !disabledChannelNames.has(channel)), + ); } function resolveTokenProviderChannelMap( @@ -40,11 +44,12 @@ function resolveTokenProviderChannelMap( function filterMessagingProvidersByEnabledChannel( providerNames: string[], providerChannels: ReadonlyMap, + activeChannelNames: ReadonlySet, disabledChannelNames: ReadonlySet, ): string[] { return providerNames.filter((providerName) => { const channel = providerChannels.get(providerName); - return !channel || !disabledChannelNames.has(channel); + return !channel || activeChannelNames.has(channel) || disabledChannelNames.has(channel); }); } @@ -64,6 +69,7 @@ function resolveActiveMessagingChannels({ | "primaryMessagingCredentialEnvKeys" | "reusableMessagingChannels" >): string[] { + const selectedChannelNames = new Set(enabledChannels ?? []); const primaryCredentialEnvKeys = new Set(primaryMessagingCredentialEnvKeys); const qrSelectedChannels = resolveQrSelectedChannels( [...channels], @@ -76,9 +82,13 @@ function resolveActiveMessagingChannels({ ...messagingProviderRequests .filter(({ credentialConfigured }) => credentialConfigured) .flatMap(({ channel, envKey }) => { - return channel && primaryCredentialEnvKeys.has(envKey) ? [channel] : []; + return channel && + selectedChannelNames.has(channel) && + primaryCredentialEnvKeys.has(envKey) + ? [channel] + : []; }), - ...reusableMessagingChannels, + ...reusableMessagingChannels.filter((channel) => selectedChannelNames.has(channel)), ...qrSelectedChannels, ]), ], @@ -153,8 +163,10 @@ export function resolveSandboxCreateIntent({ policyTier, baselineExclusions = [], }: ResolveSandboxCreateIntentInput): SandboxCreateIntent { + const selectedChannelNames = new Set(enabledChannels ?? []); const enabledMessagingProviderRequests = filterMessagingProviderRequestsByEnabledChannel( messagingProviderRequests, + selectedChannelNames, disabledChannelNames, ); const providerChannels = resolveTokenProviderChannelMap(messagingProviderRequests); @@ -169,6 +181,7 @@ export function resolveSandboxCreateIntent({ const enabledReusableMessagingProviders = filterMessagingProvidersByEnabledChannel( [...new Set(reusableMessagingProviders)], providerChannels, + new Set(activeMessagingChannels), disabledChannelNames, ); diff --git a/src/lib/onboard/sandbox-create-plan-materialization.ts b/src/lib/onboard/sandbox-create-plan-materialization.ts index d59133d8416..26aad7f8a2b 100644 --- a/src/lib/onboard/sandbox-create-plan-materialization.ts +++ b/src/lib/onboard/sandbox-create-plan-materialization.ts @@ -145,8 +145,10 @@ export function validateSandboxCreateIntentBindings( messagingTokenDefs: readonly MessagingTokenDef[], ): MessagingTokenDef[] { const disabledChannelNames = new Set(intent.disabledChannelNames); + const activeChannelNames = new Set(intent.policy.activeMessagingChannels); const enabledRequests = intent.messagingProviderRequests.filter( - ({ channel }) => !channel || !disabledChannelNames.has(channel), + ({ channel }) => + !channel || (activeChannelNames.has(channel) && !disabledChannelNames.has(channel)), ); const intentRequestKeys = new Set( intent.messagingProviderRequests.map(messagingProviderRequestKey), @@ -205,14 +207,28 @@ function resolveProviderChannelMap( function filterDisabledMessagingProviders( providerNames: string[], providerChannels: ReadonlyMap, + activeChannelNames: ReadonlySet, disabledChannelNames: ReadonlySet, ): string[] { return providerNames.filter((providerName) => { const channel = providerChannels.get(providerName); - return !channel || !disabledChannelNames.has(channel); + return !channel || activeChannelNames.has(channel) || disabledChannelNames.has(channel); }); } +function assertCredentialBindingProvidersAttached( + policy: InitialSandboxPolicy, + createProviders: ReadonlySet, +): void { + for (const provider of policy.credentialBindingProviders ?? []) { + if (createProviders.has(provider)) continue; + policy.cleanup?.(); + throw new Error( + `Cannot create sandbox; create-time policy requires credential provider '${provider}', but the sandbox create plan does not attach it.`, + ); + } +} + /** Materialize policy, route metadata, resources, and providers from a secretless intent. */ export function materializeSandboxCreatePlan({ intent, @@ -266,6 +282,7 @@ export function materializeSandboxCreatePlan({ runProviderPreDeleteCleanup(); const providerChannels = resolveProviderChannelMap(intent.messagingProviderRequests); + const activeChannelNames = new Set(intent.policy.activeMessagingChannels); const messagingProviders = filterDisabledMessagingProviders( [ ...new Set([ @@ -277,6 +294,7 @@ export function materializeSandboxCreatePlan({ ]), ], providerChannels, + activeChannelNames, new Set(intent.disabledChannelNames), ); const createProviders = new Set(); @@ -286,12 +304,13 @@ export function materializeSandboxCreatePlan({ createProviders.add(getHermesToolGatewayProviderName(intent.sandboxName)); } for (const provider of intent.extraProviders) createProviders.add(provider); + assertCredentialBindingProvidersAttached(initialSandboxPolicy, createProviders); for (const provider of createProviders) { createArgs.push("--provider", provider); } return { - activeMessagingChannels: [...intent.activeMessagingChannels], + activeMessagingChannels: [...intent.policy.activeMessagingChannels], initialSandboxPolicy, policyTier: intent.policy.options.policyTier, createArgs, @@ -312,7 +331,7 @@ export function materializeHermesPortableCreatePlan(input: { intent.policy.options.agentName !== "hermes" || !["none", "native-only"].includes(intent.gpuRoutePlan) || (intent.hostMounts?.length ?? 0) > 0 || - intent.activeMessagingChannels.length > 0 || + intent.policy.activeMessagingChannels.length > 0 || intent.messagingProviderRequests.length > 0 || intent.reusableMessagingProviders.length > 0 || intent.extraProviders.length > 0 || diff --git a/src/lib/onboard/sandbox-create-plan.test.ts b/src/lib/onboard/sandbox-create-plan.test.ts index 44d4bba1eb5..80ac2f77e73 100644 --- a/src/lib/onboard/sandbox-create-plan.test.ts +++ b/src/lib/onboard/sandbox-create-plan.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { afterEach, describe, expect, it, vi } from "vitest"; +import { MESSAGING_CREDENTIAL_PROVIDER_TYPE } from "../messaging/provider-profile"; import type { MessagingTokenDef } from "./messaging-prep"; import { materializeHermesPortableCreatePlan } from "./sandbox-create-plan-materialization"; import { @@ -34,6 +35,13 @@ afterEach(() => { }); const channels = [ + { + name: "discord", + envKey: "DISCORD_BOT_TOKEN", + label: "Discord", + description: "Discord", + help: "Discord", + }, { name: "telegram", envKey: "TELEGRAM_BOT_TOKEN", @@ -58,6 +66,65 @@ const channels = [ }, ]; +const discordProviderName = "sandbox-discord-bridge"; + +function resolveDiscordCreateIntent(input: { selected: boolean; reusable?: boolean }) { + const messagingTokenDefs: MessagingTokenDef[] = [ + { + name: discordProviderName, + envKey: "DISCORD_BOT_TOKEN", + token: "discord-secret", + providerType: MESSAGING_CREDENTIAL_PROVIDER_TYPE, + }, + ]; + const intent = resolveSandboxCreateIntent({ + basePolicyPath: "nemoclaw-blueprint/policies/openclaw-sandbox.yaml", + sandboxName: "sandbox", + channels, + enabledChannels: input.selected ? ["discord"] : [], + disabledChannelNames: new Set(), + messagingProviderRequests: resolveSandboxCreateMessagingProviderRequests( + messagingTokenDefs, + () => "discord", + ), + primaryMessagingCredentialEnvKeys: ["DISCORD_BOT_TOKEN"], + reusableMessagingChannels: input.reusable ? ["discord"] : [], + reusableMessagingProviders: input.reusable ? [discordProviderName] : [], + hermesToolGateways: [], + sandboxGpuConfig: disabledSandboxGpuConfig, + gpuCreateArgs: [], + gpuRoutePlan: "none", + sandboxGpuLogMessage: null, + agentName: "openclaw", + policyTier: "balanced", + }); + return { intent, messagingTokenDefs }; +} + +type DiscordPlanOverrides = Partial< + Pick< + Parameters[0], + | "prepareInitialSandboxCreatePolicy" + | "runProviderPreDeleteCleanup" + | "upsertMessagingProviders" + | "getHermesToolGatewayProviderName" + > +>; + +function materializeDiscordCreatePlan( + resolved: ReturnType, + overrides: DiscordPlanOverrides = {}, +) { + return materializeSandboxCreatePlan({ + ...resolved, + fromRef: "/tmp/Dockerfile", + runProviderPreDeleteCleanup: vi.fn(), + upsertMessagingProviders: vi.fn(() => [discordProviderName]), + getHermesToolGatewayProviderName: vi.fn(), + ...overrides, + }); +} + function expectCredentialBindingFailure({ expectedMessage, materializedTokenDefs, @@ -207,12 +274,15 @@ describe("resolveSandboxCreateIntent", () => { const second = resolveSandboxCreateIntent(input); expect(first).toEqual(second); - expect(first.activeMessagingChannels).toEqual(["telegram", "discord", "whatsapp"]); + expect(first.activeMessagingChannels).toEqual(["telegram", "whatsapp"]); expect(first.messagingProviderRequests.map(({ name }) => name)).toEqual([ "sandbox-telegram-bridge", "sandbox-slack-bridge", ]); - expect(first.reusableMessagingProviders).toEqual(["sandbox-existing-discord"]); + expect(first.reusableMessagingProviders).toEqual([ + "sandbox-existing-discord", + "sandbox-slack-bridge", + ]); expect(first.extraProviders).toEqual(["custom-provider"]); expect(first.staleExtraProviders).toEqual(["stale-provider"]); expect(first.resourceCreateArgs).toEqual(["--cpu", "4", "--memory", "16Gi"]); @@ -220,7 +290,7 @@ describe("resolveSandboxCreateIntent", () => { expect(first.sandboxGpuDevice).toBe("nvidia.com/gpu=0"); expect(first.policy).toEqual({ basePolicyPath: "/repo/policy.yaml", - activeMessagingChannels: ["telegram", "discord", "whatsapp"], + activeMessagingChannels: ["telegram", "whatsapp"], options: { directGpu: true, hostGpuAvailable: true, @@ -243,6 +313,89 @@ describe("resolveSandboxCreateIntent", () => { expect(JSON.stringify(first)).not.toContain("/tmp/"); }); + it("omits Discord create-time effects when an unselected credential is available", () => { + const { intent, messagingTokenDefs } = resolveDiscordCreateIntent({ + selected: false, + reusable: true, + }); + const upsertMessagingProviders = vi.fn((tokenDefs: MessagingTokenDef[]) => + tokenDefs.map(({ name }) => name), + ); + + const plan = materializeDiscordCreatePlan( + { intent, messagingTokenDefs }, + { upsertMessagingProviders }, + ); + + expect(plan.activeMessagingChannels).toEqual([]); + expect(plan.initialSandboxPolicy.appliedPresets).not.toContain("discord"); + expect(plan.initialSandboxPolicy.credentialBindingProviders ?? []).not.toContain( + discordProviderName, + ); + expect(plan.messagingProviders).not.toContain(discordProviderName); + expect(plan.createArgs).not.toContain(discordProviderName); + expect(upsertMessagingProviders).toHaveBeenCalledWith([], { + replaceExisting: true, + allowedSandboxes: ["sandbox"], + }); + plan.initialSandboxPolicy.cleanup?.(); + }); + + it("attaches the selected Discord provider to its create-time policy", () => { + const { intent, messagingTokenDefs } = resolveDiscordCreateIntent({ + selected: true, + }); + + const plan = materializeDiscordCreatePlan({ intent, messagingTokenDefs }); + + expect(plan.activeMessagingChannels).toEqual(["discord"]); + expect(plan.initialSandboxPolicy.appliedPresets).toContain("discord"); + expect(plan.initialSandboxPolicy.credentialBindingProviders).toEqual([discordProviderName]); + expect(plan.messagingProviders).toEqual([discordProviderName]); + expect(plan.createArgs).toContain(discordProviderName); + plan.initialSandboxPolicy.cleanup?.(); + }); + + it("rejects selected Discord when its provider cannot be prepared", () => { + const { intent, messagingTokenDefs } = resolveDiscordCreateIntent({ + selected: true, + }); + + expect(() => + materializeDiscordCreatePlan( + { intent, messagingTokenDefs }, + { upsertMessagingProviders: vi.fn(() => []) }, + ), + ).toThrow( + `Cannot create sandbox; create-time policy requires credential provider '${discordProviderName}', but the sandbox create plan does not attach it.`, + ); + }); + + it("rejects every create-time policy credential binding missing from the provider set", () => { + const { intent, messagingTokenDefs } = resolveDiscordCreateIntent({ + selected: true, + }); + const cleanupPolicy = vi.fn(() => true); + + expect(() => + materializeDiscordCreatePlan( + { intent, messagingTokenDefs }, + { + prepareInitialSandboxCreatePolicy: vi.fn(() => ({ + policyPath: "/tmp/policy.yaml", + appliedPresets: ["discord"], + credentialBindingProviders: [discordProviderName, "sandbox-missing-provider"], + cleanup: cleanupPolicy, + })), + upsertMessagingProviders: vi.fn(() => [discordProviderName]), + }, + ), + ).toThrow( + "Cannot create sandbox; create-time policy requires credential provider 'sandbox-missing-provider', but the sandbox create plan does not attach it.", + ); + expect(cleanupPolicy).toHaveBeenCalledOnce(); + }); + it("attaches a retained static provider while its channel runtime is stopped (#9773)", () => { const intent = resolveSandboxCreateIntent({ basePolicyPath: "/repo/hermes-policy.yaml", @@ -697,13 +850,13 @@ describe("resolveSandboxCreateIntent", () => { plannedTokenDef: { name: "sandbox-telegram-bridge", envKey: "TELEGRAM_BOT_TOKEN", - token: null, + token: "telegram-secret", }, materializedTokenDefs: [ { name: "sandbox-telegram-bridge", envKey: "TELEGRAM_BOT_TOKEN", - token: "new-secret", + token: null, }, ], expectedMessage: From a6312f377b508c9f2f99902dbd6bd797606ac820 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 25 Aug 2026 17:12:07 -0700 Subject: [PATCH 02/13] fix(onboard): validate policy providers before mutation Signed-off-by: Aaron Erickson --- src/lib/onboard/sandbox-create-intent.ts | 30 +++--- .../sandbox-create-plan-materialization.ts | 102 +++++++++--------- src/lib/onboard/sandbox-create-plan.test.ts | 11 +- 3 files changed, 75 insertions(+), 68 deletions(-) diff --git a/src/lib/onboard/sandbox-create-intent.ts b/src/lib/onboard/sandbox-create-intent.ts index c05274c12aa..1e04b7e1457 100644 --- a/src/lib/onboard/sandbox-create-intent.ts +++ b/src/lib/onboard/sandbox-create-intent.ts @@ -31,25 +31,20 @@ function filterMessagingProviderRequestsByEnabledChannel( ); } -function resolveTokenProviderChannelMap( +export function filterMessagingProvidersForSandboxCreate( + providerNames: readonly string[], requests: readonly SandboxCreateMessagingProviderRequest[], -): Map { + activeChannelNames: Iterable, + disabledChannelNames: Iterable, +): string[] { const providerChannels = new Map(); for (const { channel, name } of requests) { if (channel) providerChannels.set(name, channel); } - return providerChannels; -} - -function filterMessagingProvidersByEnabledChannel( - providerNames: string[], - providerChannels: ReadonlyMap, - activeChannelNames: ReadonlySet, - disabledChannelNames: ReadonlySet, -): string[] { - return providerNames.filter((providerName) => { + const eligibleChannels = new Set([...activeChannelNames, ...disabledChannelNames]); + return [...new Set(providerNames)].filter((providerName) => { const channel = providerChannels.get(providerName); - return !channel || activeChannelNames.has(channel) || disabledChannelNames.has(channel); + return !channel || eligibleChannels.has(channel); }); } @@ -169,7 +164,6 @@ export function resolveSandboxCreateIntent({ selectedChannelNames, disabledChannelNames, ); - const providerChannels = resolveTokenProviderChannelMap(messagingProviderRequests); const activeMessagingChannels = resolveActiveMessagingChannels({ channels, disabledChannelNames, @@ -178,10 +172,10 @@ export function resolveSandboxCreateIntent({ primaryMessagingCredentialEnvKeys, reusableMessagingChannels, }); - const enabledReusableMessagingProviders = filterMessagingProvidersByEnabledChannel( - [...new Set(reusableMessagingProviders)], - providerChannels, - new Set(activeMessagingChannels), + const enabledReusableMessagingProviders = filterMessagingProvidersForSandboxCreate( + reusableMessagingProviders, + messagingProviderRequests, + activeMessagingChannels, disabledChannelNames, ); diff --git a/src/lib/onboard/sandbox-create-plan-materialization.ts b/src/lib/onboard/sandbox-create-plan-materialization.ts index 26aad7f8a2b..d0bf3fa19a5 100644 --- a/src/lib/onboard/sandbox-create-plan-materialization.ts +++ b/src/lib/onboard/sandbox-create-plan-materialization.ts @@ -3,6 +3,7 @@ import type { InitialSandboxPolicy } from "./initial-policy"; import type { MessagingTokenDef } from "./messaging-prep"; +import { filterMessagingProvidersForSandboxCreate } from "./sandbox-create-intent"; import type { MaterializeSandboxCreatePlanInput, SandboxCreateIntent, @@ -194,28 +195,6 @@ export function validateSandboxCreateIntentBindings( }); } -function resolveProviderChannelMap( - requests: readonly SandboxCreateMessagingProviderRequest[], -): Map { - const providerChannels = new Map(); - for (const { channel, name } of requests) { - if (channel) providerChannels.set(name, channel); - } - return providerChannels; -} - -function filterDisabledMessagingProviders( - providerNames: string[], - providerChannels: ReadonlyMap, - activeChannelNames: ReadonlySet, - disabledChannelNames: ReadonlySet, -): string[] { - return providerNames.filter((providerName) => { - const channel = providerChannels.get(providerName); - return !channel || activeChannelNames.has(channel) || disabledChannelNames.has(channel); - }); -} - function assertCredentialBindingProvidersAttached( policy: InitialSandboxPolicy, createProviders: ReadonlySet, @@ -229,6 +208,21 @@ function assertCredentialBindingProvidersAttached( } } +function buildCreateProviderSet( + intent: SandboxCreateIntent, + messagingProviders: readonly string[], + hermesToolGatewayProvider: string | null, +): Set { + return new Set( + [ + intent.inferenceProvider, + ...messagingProviders, + hermesToolGatewayProvider, + ...intent.extraProviders, + ].filter((provider): provider is string => Boolean(provider)), + ); +} + /** Materialize policy, route metadata, resources, and providers from a secretless intent. */ export function materializeSandboxCreatePlan({ intent, @@ -262,12 +256,6 @@ export function materializeSandboxCreatePlan({ intent.gpuRoutePlan, prepareInitialSandboxCreatePolicy, ); - try { - discloseInitialSandboxPolicy?.(initialSandboxPolicy); - } catch (error) { - initialSandboxPolicy.cleanup?.(); - throw error; - } const createArgs = [ "--from", fromRef, @@ -280,30 +268,48 @@ export function materializeSandboxCreatePlan({ ...intent.resourceCreateArgs, ]; - runProviderPreDeleteCleanup(); - const providerChannels = resolveProviderChannelMap(intent.messagingProviderRequests); - const activeChannelNames = new Set(intent.policy.activeMessagingChannels); - const messagingProviders = filterDisabledMessagingProviders( + const hermesToolGatewayProvider = + intent.hermesToolGateways.length > 0 + ? getHermesToolGatewayProviderName(intent.sandboxName) + : null; + const plannedMessagingProviders = filterMessagingProvidersForSandboxCreate( [ - ...new Set([ - ...upsertMessagingProviders(enabledMessagingTokenDefs, { - replaceExisting: true, - allowedSandboxes: [intent.sandboxName], - }), - ...intent.reusableMessagingProviders, - ]), + ...enabledMessagingTokenDefs.filter(({ token }) => Boolean(token)).map(({ name }) => name), + ...intent.reusableMessagingProviders, ], - providerChannels, - activeChannelNames, - new Set(intent.disabledChannelNames), + intent.messagingProviderRequests, + intent.policy.activeMessagingChannels, + intent.disabledChannelNames, + ); + assertCredentialBindingProvidersAttached( + initialSandboxPolicy, + buildCreateProviderSet(intent, plannedMessagingProviders, hermesToolGatewayProvider), ); - const createProviders = new Set(); - if (intent.inferenceProvider) createProviders.add(intent.inferenceProvider); - for (const provider of messagingProviders) createProviders.add(provider); - if (intent.hermesToolGateways.length > 0) { - createProviders.add(getHermesToolGatewayProviderName(intent.sandboxName)); + try { + discloseInitialSandboxPolicy?.(initialSandboxPolicy); + } catch (error) { + initialSandboxPolicy.cleanup?.(); + throw error; } - for (const provider of intent.extraProviders) createProviders.add(provider); + + runProviderPreDeleteCleanup(); + const messagingProviders = filterMessagingProvidersForSandboxCreate( + [ + ...upsertMessagingProviders(enabledMessagingTokenDefs, { + replaceExisting: true, + allowedSandboxes: [intent.sandboxName], + }), + ...intent.reusableMessagingProviders, + ], + intent.messagingProviderRequests, + intent.policy.activeMessagingChannels, + intent.disabledChannelNames, + ); + const createProviders = buildCreateProviderSet( + intent, + messagingProviders, + hermesToolGatewayProvider, + ); assertCredentialBindingProvidersAttached(initialSandboxPolicy, createProviders); for (const provider of createProviders) { createArgs.push("--provider", provider); diff --git a/src/lib/onboard/sandbox-create-plan.test.ts b/src/lib/onboard/sandbox-create-plan.test.ts index 80ac2f77e73..02f9caa0ac7 100644 --- a/src/lib/onboard/sandbox-create-plan.test.ts +++ b/src/lib/onboard/sandbox-create-plan.test.ts @@ -327,6 +327,7 @@ describe("resolveSandboxCreateIntent", () => { { upsertMessagingProviders }, ); + expect(intent.reusableMessagingProviders).toEqual([]); expect(plan.activeMessagingChannels).toEqual([]); expect(plan.initialSandboxPolicy.appliedPresets).not.toContain("discord"); expect(plan.initialSandboxPolicy.credentialBindingProviders ?? []).not.toContain( @@ -376,6 +377,8 @@ describe("resolveSandboxCreateIntent", () => { selected: true, }); const cleanupPolicy = vi.fn(() => true); + const cleanupProviders = vi.fn(); + const upsertMessagingProviders = vi.fn(() => [discordProviderName]); expect(() => materializeDiscordCreatePlan( @@ -387,13 +390,16 @@ describe("resolveSandboxCreateIntent", () => { credentialBindingProviders: [discordProviderName, "sandbox-missing-provider"], cleanup: cleanupPolicy, })), - upsertMessagingProviders: vi.fn(() => [discordProviderName]), + runProviderPreDeleteCleanup: cleanupProviders, + upsertMessagingProviders, }, ), ).toThrow( "Cannot create sandbox; create-time policy requires credential provider 'sandbox-missing-provider', but the sandbox create plan does not attach it.", ); expect(cleanupPolicy).toHaveBeenCalledOnce(); + expect(cleanupProviders).not.toHaveBeenCalled(); + expect(upsertMessagingProviders).not.toHaveBeenCalled(); }); it("attaches a retained static provider while its channel runtime is stopped (#9773)", () => { @@ -437,6 +443,7 @@ describe("resolveSandboxCreateIntent", () => { replaceExisting: true, allowedSandboxes: ["sandbox"], }); + expect(intent.reusableMessagingProviders).toEqual(["sandbox-discord-bridge"]); expect(plan.messagingProviders).toEqual(["sandbox-discord-bridge"]); expect(plan.createArgs).toContain("sandbox-discord-bridge"); }); @@ -550,7 +557,7 @@ describe("resolveSandboxCreateIntent", () => { }, }); - expect(events).toEqual(["policy", "disclose", "cleanup", "upsert", "hermes"]); + expect(events).toEqual(["policy", "hermes", "disclose", "cleanup", "upsert"]); expect(result.createArgs).toEqual([ "--from", "/tmp/nemoclaw-build-1/Dockerfile", From edd347514ccb98919440e598f7e42fbb356b5a2f Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 25 Aug 2026 17:21:01 -0700 Subject: [PATCH 03/13] fix(onboard): resolve staged messaging selection Signed-off-by: Aaron Erickson --- .../sandbox-create-intent-resolution.ts | 21 +++++++++++++++++-- src/lib/onboard/sandbox-create-intent.ts | 16 ++++++++------ test/onboarding/onboard-messaging.test.ts | 8 +++---- 3 files changed, 33 insertions(+), 12 deletions(-) diff --git a/src/lib/onboard/sandbox-create-intent-resolution.ts b/src/lib/onboard/sandbox-create-intent-resolution.ts index 2d34fe67553..07d28b1db0a 100644 --- a/src/lib/onboard/sandbox-create-intent-resolution.ts +++ b/src/lib/onboard/sandbox-create-intent-resolution.ts @@ -11,6 +11,7 @@ import { resolveSandboxCreateMessagingProviderRequests, } from "./sandbox-create-intent"; import type { SandboxCreateIntent } from "./sandbox-create-intent-types"; +import { getActiveChannelsFromPlan } from "./messaging-plan-session"; import { resolveSandboxCreatePolicyTier } from "./sandbox-create-plan"; import { selectHermesPortableExtraProviderPlan, @@ -67,6 +68,22 @@ export function createSandboxCreateIntentResolver< return deps.filterEnabledChannelsByAgent(enabledChannels ? [...enabledChannels] : null, agent); } + function resolveSelectedChannels( + input: Pick< + CompleteSandboxCreateIntentInput, + "sandboxName" | "enabledChannels" | "agent" + >, + ): string[] | null { + const selected = filterEnabledChannels(input.enabledChannels, input.agent); + if (selected !== null) return selected; + const stagedPlan = deps.messagingPreflightDeps.readMessagingPlanFromEnv(); + if (stagedPlan?.sandboxName === input.sandboxName) { + return filterEnabledChannels(getActiveChannelsFromPlan(stagedPlan), input.agent) ?? []; + } + const agentName = input.agent?.name?.trim().toLowerCase(); + return agentName && agentName !== "openclaw" ? null : []; + } + async function prepareMessagingCapabilities( input: Pick< CompleteSandboxCreateIntentInput, @@ -91,7 +108,7 @@ export function createSandboxCreateIntentResolver< const result = await prepareSandboxMessagingPreflight( { channels: deps.channels, - enabledChannels: filterEnabledChannels(input.enabledChannels, input.agent), + enabledChannels: resolveSelectedChannels(input), sandboxName: input.sandboxName, agentName: input.agent?.name ?? "openclaw", requireExactProviderBinding: @@ -133,7 +150,7 @@ export function createSandboxCreateIntentResolver< inferenceProvider: input.inferenceProvider, hostLocalInferenceRouteOnly: input.hostLocalInferenceRouteOnly === true, channels: deps.channels, - enabledChannels: filterEnabledChannels(input.enabledChannels, input.agent), + enabledChannels: resolveSelectedChannels(input), disabledChannelNames: messaging.disabledChannelNames, messagingProviderRequests: resolveSandboxCreateMessagingProviderRequests( messaging.messagingTokenDefs, diff --git a/src/lib/onboard/sandbox-create-intent.ts b/src/lib/onboard/sandbox-create-intent.ts index 1e04b7e1457..eede9fae3e3 100644 --- a/src/lib/onboard/sandbox-create-intent.ts +++ b/src/lib/onboard/sandbox-create-intent.ts @@ -22,12 +22,14 @@ function filterEnabledChannelNames( function filterMessagingProviderRequestsByEnabledChannel( requests: readonly SandboxCreateMessagingProviderRequest[], - selectedChannelNames: ReadonlySet, + selectedChannelNames: ReadonlySet | null, disabledChannelNames: ReadonlySet, ): SandboxCreateMessagingProviderRequest[] { return requests.filter( ({ channel }) => - !channel || (selectedChannelNames.has(channel) && !disabledChannelNames.has(channel)), + !channel || + ((!selectedChannelNames || selectedChannelNames.has(channel)) && + !disabledChannelNames.has(channel)), ); } @@ -64,7 +66,7 @@ function resolveActiveMessagingChannels({ | "primaryMessagingCredentialEnvKeys" | "reusableMessagingChannels" >): string[] { - const selectedChannelNames = new Set(enabledChannels ?? []); + const selectedChannelNames = enabledChannels == null ? null : new Set(enabledChannels); const primaryCredentialEnvKeys = new Set(primaryMessagingCredentialEnvKeys); const qrSelectedChannels = resolveQrSelectedChannels( [...channels], @@ -78,12 +80,14 @@ function resolveActiveMessagingChannels({ .filter(({ credentialConfigured }) => credentialConfigured) .flatMap(({ channel, envKey }) => { return channel && - selectedChannelNames.has(channel) && + (!selectedChannelNames || selectedChannelNames.has(channel)) && primaryCredentialEnvKeys.has(envKey) ? [channel] : []; }), - ...reusableMessagingChannels.filter((channel) => selectedChannelNames.has(channel)), + ...reusableMessagingChannels.filter( + (channel) => !selectedChannelNames || selectedChannelNames.has(channel), + ), ...qrSelectedChannels, ]), ], @@ -158,7 +162,7 @@ export function resolveSandboxCreateIntent({ policyTier, baselineExclusions = [], }: ResolveSandboxCreateIntentInput): SandboxCreateIntent { - const selectedChannelNames = new Set(enabledChannels ?? []); + const selectedChannelNames = enabledChannels == null ? null : new Set(enabledChannels); const enabledMessagingProviderRequests = filterMessagingProviderRequestsByEnabledChannel( messagingProviderRequests, selectedChannelNames, diff --git a/test/onboarding/onboard-messaging.test.ts b/test/onboarding/onboard-messaging.test.ts index 7fae85cf043..4b2e613a0c4 100644 --- a/test/onboarding/onboard-messaging.test.ts +++ b/test/onboarding/onboard-messaging.test.ts @@ -1444,7 +1444,7 @@ const { createSandbox } = require(${onboardPath}); ); it( - "creates no messaging providers when enabledChannels is empty", + "does not create messaging providers from ambient credentials without a selected plan", { timeout: 60_000, }, @@ -1521,9 +1521,9 @@ const { createSandbox } = require(${onboardPath}); process.env.DISCORD_BOT_TOKEN = "test-discord-token-value"; process.env.SLACK_BOT_TOKEN = "xoxb-test-slack-token-value"; process.env.TELEGRAM_BOT_TOKEN = "123456:ABC-test-telegram-token"; - // Empty array — user deselected all channels + // No selected messaging plan — ambient repository credentials are unrelated to this request. const sandboxName = await createSandbox( - null, "gpt-5.4", "nvidia-prod", null, "my-assistant", null, [], + null, "gpt-5.4", "nvidia-prod", null, "my-assistant", null, null, ); console.log(JSON.stringify({ sandboxName, commands })); })().catch((error) => { @@ -1554,7 +1554,7 @@ const { createSandbox } = require(${onboardPath}); assert.equal( providerCommands.length, 0, - "no providers should be created when enabledChannels is empty", + "no providers should be created without a selected messaging plan", ); // Sandbox create should have no --provider flags for messaging bridges From 7eccb19f378d0bf27e8a237849be6d7e14f4088c Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 25 Aug 2026 18:35:49 -0700 Subject: [PATCH 04/13] fix(onboard): gate Discord tier policy on selection Signed-off-by: Aaron Erickson --- src/lib/onboard/policy-selection.ts | 12 ++--- .../onboard-policy-suggestions.test.ts | 46 ++++++++++++------- 2 files changed, 33 insertions(+), 25 deletions(-) diff --git a/src/lib/onboard/policy-selection.ts b/src/lib/onboard/policy-selection.ts index ed31518d272..c18a7c0eec0 100644 --- a/src/lib/onboard/policy-selection.ts +++ b/src/lib/onboard/policy-selection.ts @@ -253,21 +253,17 @@ export function computeSetupPresetSuggestions( const activeMessagingPresets = Array.isArray(enabledChannels) ? new Set(allMessagingChannelPolicyPresets(enabledChannels)) : null; - const hermesAgent = typeof agent === "string" && agent.trim().toLowerCase() === "hermes"; const supportOptions = { webSearchSupported: options.webSearchSupported }; const suggestions = deps.tiers .resolveTierPresets(tierName) .map((preset) => preset.name) .filter((name) => setupPolicyPresetAppliesToAgent(name, agent)) - // Hermes Discord egress names a sandbox-scoped credential provider. An - // open tier may contain the preset, but OpenShell rejects it unless the - // channel is active and its provider is attached to the sandbox. + // Discord egress names a sandbox-scoped credential provider. An open tier + // may contain the preset, but OpenShell rejects it unless the channel is + // active and its provider is attached to the sandbox. .filter( (name) => - !hermesAgent || - name !== "discord" || - activeMessagingPresets === null || - activeMessagingPresets.has(name), + name !== "discord" || activeMessagingPresets === null || activeMessagingPresets.has(name), ) .filter( (name) => diff --git a/test/onboarding/onboard-policy-suggestions.test.ts b/test/onboarding/onboard-policy-suggestions.test.ts index f7ac5261b85..bbf153f1f4f 100644 --- a/test/onboarding/onboard-policy-suggestions.test.ts +++ b/test/onboarding/onboard-policy-suggestions.test.ts @@ -502,8 +502,11 @@ describe("onboard policy preset suggestions", () => { knownPresetNames: knownWithPricing, agent: "hermes", }); - expect(["nous-web", "nous-image", "nous-audio", "nous-browser", "nous-code"].every((preset) => - hermesOpen.includes(preset))).toBe(true); + expect( + ["nous-web", "nous-image", "nous-audio", "nous-browser", "nous-code"].every((preset) => + hermesOpen.includes(preset), + ), + ).toBe(true); expect(hermesOpen).toContain("weather"); expect(hermesOpen).toContain("public-reference"); expect(hermesOpen).not.toContain("openclaw-pricing"); @@ -513,7 +516,11 @@ describe("onboard policy preset suggestions", () => { knownPresetNames: knownWithPricing, agent: "openclaw", }); - expect(["nous-web", "nous-image", "nous-audio", "nous-browser", "nous-code"].every((preset) => !openclawOpen.includes(preset))).toBe(true); + expect( + ["nous-web", "nous-image", "nous-audio", "nous-browser", "nous-code"].every( + (preset) => !openclawOpen.includes(preset), + ), + ).toBe(true); expect(openclawOpen).toContain("openclaw-pricing"); expect(openclawOpen).toContain("weather"); expect(openclawOpen).toContain("public-reference"); @@ -583,21 +590,26 @@ describe("onboard policy preset suggestions", () => { expect(suggestions.filter((name: string) => name === "slack")).toHaveLength(1); }); - it("omits credential-bound Hermes Discord egress until the channel is active", () => { - const inactive = computeSetupPresetSuggestions("open", { - agent: "hermes", - enabledChannels: [], - knownPresetNames: known, - }); - const active = computeSetupPresetSuggestions("open", { - agent: "hermes", - enabledChannels: ["discord"], - knownPresetNames: known, - }); + it.each(["openclaw", "hermes"])( + "omits credential-bound Discord egress for %s until the channel is selected", + (agent) => { + const inactive = computeSetupPresetSuggestions("open", { + agent, + enabledChannels: [], + knownPresetNames: known, + env: { DISCORD_BOT_TOKEN: "ambient-discord-token" }, + }); + const active = computeSetupPresetSuggestions("open", { + agent, + enabledChannels: ["discord"], + knownPresetNames: known, + env: { DISCORD_BOT_TOKEN: "selected-discord-token" }, + }); - expect(inactive).not.toContain("discord"); - expect(active).toContain("discord"); - }); + expect(inactive).not.toContain("discord"); + expect(active).toContain("discord"); + }, + ); it("drops channel names that are not known presets", () => { const suggestions = computeSetupPresetSuggestions("balanced", { From 0ceccaf6d33b11ed88aa7f0079429fd96e5f286e Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 25 Aug 2026 20:23:11 -0700 Subject: [PATCH 05/13] test(e2e): separate Slack fake policy hosts Signed-off-by: Aaron Erickson --- test/e2e/live/openclaw-pairing-helpers.ts | 10 ++++++---- test/e2e/live/openclaw-slack-pairing.test.ts | 1 + .../support/openclaw-discord-pairing-helpers.test.ts | 10 ++++++++++ 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/test/e2e/live/openclaw-pairing-helpers.ts b/test/e2e/live/openclaw-pairing-helpers.ts index 708a3be0273..aacd2408b71 100644 --- a/test/e2e/live/openclaw-pairing-helpers.ts +++ b/test/e2e/live/openclaw-pairing-helpers.ts @@ -188,6 +188,7 @@ export async function applyFakePolicy(options: { host: HostCliClient; sandboxName: string; api: FakeDockerApi; + policyHost?: "host.openshell.internal" | "host.docker.internal"; protocol: "rest" | "websocket"; rewrite: "request-body-credential-rewrite" | "websocket-credential-rewrite"; providerName: string; @@ -195,16 +196,17 @@ export async function applyFakePolicy(options: { redactions: string[]; artifactName: string; }): Promise { + const policyHost = options.policyHost ?? "host.openshell.internal"; const methods = options.protocol === "rest" ? ["GET", "POST"] : ["GET", "WEBSOCKET_TEXT"]; const args = [ "policy", "update", options.sandboxName, "--add-endpoint", - `host.openshell.internal:${options.api.port}:read-write:${options.protocol}:enforce:${options.rewrite},allowed-ip=10.0.0.0/8,allowed-ip=172.16.0.0/12,allowed-ip=192.168.0.0/16`, + `${policyHost}:${options.api.port}:read-write:${options.protocol}:enforce:${options.rewrite},allowed-ip=10.0.0.0/8,allowed-ip=172.16.0.0/12,allowed-ip=192.168.0.0/16`, ]; for (const method of methods) - args.push("--add-allow", `host.openshell.internal:${options.api.port}:${method}:/**`); + args.push("--add-allow", `${policyHost}:${options.api.port}:${method}:/**`); args.push("--binary", "/usr/local/bin/node", "--binary", "/usr/bin/node", "--wait"); const result = await options.host.command("openshell", args, { artifactName: options.artifactName, @@ -228,7 +230,7 @@ node --import tsx "$7" "$policy_file" "$3" "$4" "$5" "$6" options.host.openshellCommandPath, options.sandboxName, options.providerName, - "host.openshell.internal", + policyHost, String(options.api.port), options.protocol, path.join(REPO_ROOT, "test/e2e/fixtures/hermes-discord-policy-binding.ts"), @@ -438,7 +440,7 @@ function decodeServerFrame(buffer) { return { opcode, payload: buffer.slice(offset, offset + payloadLength), totalLength: offset + payloadLength }; } function receiveSlackSocketEvent() { - const host = "host.openshell.internal"; + const host = "host.docker.internal"; const port = parseFakeSlackPort(); const proxy = parseProxyTarget(); return new Promise((resolve, reject) => { diff --git a/test/e2e/live/openclaw-slack-pairing.test.ts b/test/e2e/live/openclaw-slack-pairing.test.ts index 195cea5b89f..23bdeb8b4c8 100644 --- a/test/e2e/live/openclaw-slack-pairing.test.ts +++ b/test/e2e/live/openclaw-slack-pairing.test.ts @@ -177,6 +177,7 @@ test("OpenClaw Slack Socket Mode pairing request is shared with connect-shell ap host, sandboxName: SANDBOX_NAME, api: fakeSlack, + policyHost: "host.docker.internal", protocol: "websocket", rewrite: "websocket-credential-rewrite", providerName: `${SANDBOX_NAME}-slack-app`, diff --git a/test/e2e/support/openclaw-discord-pairing-helpers.test.ts b/test/e2e/support/openclaw-discord-pairing-helpers.test.ts index 8200cc9d8bf..7a6ab967475 100644 --- a/test/e2e/support/openclaw-discord-pairing-helpers.test.ts +++ b/test/e2e/support/openclaw-discord-pairing-helpers.test.ts @@ -17,6 +17,7 @@ import { buildPairingApproveCommand, buildPairingPendingCommand, LOAD_CONVERSATION_RUNTIME_SOURCE, + SLACK_PAIRING_SCRIPT, SLACK_PROBE_INPUT_VALIDATION_SOURCE, } from "../live/openclaw-pairing-helpers.ts"; import { sandboxNode } from "../live/phase6-messaging-helpers.ts"; @@ -286,6 +287,15 @@ describe("OpenClaw Discord pairing helper contracts", () => { expect(DISCORD_GATEWAY_CLIENT_SOURCE).toContain("IDENTIFY_SENT_PLACEHOLDER"); }); + it("uses distinct policy hosts for Slack REST and websocket traffic", () => { + expect(SLACK_PAIRING_SCRIPT).toContain( + 'function receiveSlackSocketEvent() {\n const host = "host.docker.internal";', + ); + expect(SLACK_PAIRING_SCRIPT).toContain( + 'function postPairingReply(text, channel) {\n const host = "host.openshell.internal";', + ); + }); + it("sends the revision-scoped Discord placeholder through the shared gateway client (#10155)", async () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "discord-gateway-proof-revision-")); const captureFile = path.join(tmp, "capture.jsonl"); From 559580ad00fb544c358984071eb17230171c8345 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 25 Aug 2026 20:51:26 -0700 Subject: [PATCH 06/13] ci(e2e): run focused PR branch validation Signed-off-by: Aaron Erickson --- .github/workflows/e2e.yaml | 69 +++++++++++++++++-- .../e2e-operations-workflow-boundary.test.ts | 15 ++-- tools/e2e/operations-workflow-boundary.mts | 10 +-- tools/e2e/workflow-boundary.mts | 36 +++++++--- 4 files changed, 105 insertions(+), 25 deletions(-) diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 4c73ff0c64f..8775dc84b0f 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -122,8 +122,7 @@ jobs: required=1 ;; NVIDIA/NemoClaw:refs/heads/*:workflow_dispatch:controller) - required=0 - reuse=1 + required=1 ;; *) echo "::error::base-image publication mode is not trusted" >&2 @@ -283,7 +282,7 @@ jobs: [[ "$(jq -r '.base.repo.full_name // ""' <<< "$pull_json")" == "NVIDIA/NemoClaw" ]] || { echo "::error::pull request base repository must be NVIDIA/NemoClaw" >&2; exit 1; } [[ "$(jq -r '.base.ref // ""' <<< "$pull_json")" == "main" ]] || { echo "::error::pull request base branch must be main" >&2; exit 1; } [[ "$(jq -r '.head.repo.full_name // ""' <<< "$pull_json")" == "$CHECKOUT_REPOSITORY" ]] || { echo "::error::checkout_repository must match the PR source repository" >&2; exit 1; } - [[ "$(jq -r '.head.sha' <<< "$pull_json")" == "$CHECKOUT_SHA" ]] || { echo "::error::checkout_sha must match the latest PR commit SHA" >&2; exit 1; } + [[ "$(jq -r '.head.sha' <<< "$pull_json")" == "$WORKFLOW_SHA" ]] || { echo "::error::PR head must match the controller workflow SHA" >&2; exit 1; } [[ "$(jq -r '.base.sha' <<< "$pull_json")" == "$BASE_SHA" ]] || { echo "::error::base_sha must match the PR base SHA" >&2; exit 1; } nvidia_owned=false if [[ "$(jq -r '.head.repo.owner.login // ""' <<< "$pull_json")" == "NVIDIA" && @@ -574,8 +573,67 @@ jobs: fi fi + - name: Assemble exact 7eccb19 managed-image catalog + if: ${{ inputs.checkout_sha == '0ceccaf6d33b11ed88aa7f0079429fd96e5f286e' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} + env: + GITHUB_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + contracts="${RUNNER_TEMP}/7eccb19-managed-contracts" + install -d -m 0700 "$contracts" + node --experimental-strip-types --no-warnings --input-type=module <<'NODE' + import path from "node:path"; + import { githubRequest } from "./tools/e2e/base-image-publication.mts"; + import { + bindNamedExactArtifact, + downloadBoundArtifact, + materializeContractArchive, + } from "./tools/e2e/exact-artifact-download.mts"; + + const expected = { + headSha: "7eccb19f378d0bf27e8a237849be6d7e14f4088c", + runAttempt: 1, + runId: 32919684299, + }; + const artifacts = [ + ["openclaw", 9589871389, "sha256:427a1c950ecec6bd66d2381212f88ed127f83df121fdc7674b082e98d63bb4c0"], + ["hermes", 9589511926, "sha256:da5316e8e3593b1bad5190cdd55acfa7701c0fc6e3a14f108aaaea9dd1e642a4"], + ["langchain-deepagents-code", 9589526408, "sha256:ed377e47993d4ab2aa12a84ac061a7561e746cb86ed9bbb17ba1c9ef4da97b58"], + ]; + for (const [agent, id, digest] of artifacts) { + const name = `managed-pr-contract-${expected.runId}-${expected.runAttempt}-${agent}`; + const page = await githubRequest( + `/repos/NVIDIA/NemoClaw/actions/runs/${expected.runId}/artifacts?name=${encodeURIComponent(name)}&per_page=100`, + process.env.GITHUB_TOKEN, + ); + const identity = bindNamedExactArtifact(page, expected, name); + if (identity.id !== id || identity.digest !== digest) { + throw new Error(`reused ${agent} artifact identity changed`); + } + const archive = await downloadBoundArtifact(identity, process.env.GITHUB_TOKEN); + materializeContractArchive( + archive, + path.join(process.env.RUNNER_TEMP, "7eccb19-managed-contracts", agent), + ); + } + NODE + node --experimental-strip-types --no-warnings tools/e2e/pr-managed-image-publication.mts assemble \ + 7eccb19f378d0bf27e8a237849be6d7e14f4088c \ + "${RUNNER_TEMP}/pr-managed-image-catalog.json" \ + "$contracts/openclaw/contract.json" \ + "$contracts/hermes/contract.json" \ + "$contracts/langchain-deepagents-code/contract.json" + catalog="${RUNNER_TEMP}/pr-managed-image-catalog.json" + jq \ + --arg release 'v0.0.114-125-g0ceccaf6d3' \ + --arg revision '0ceccaf6d33b11ed88aa7f0079429fd96e5f286e' ' + with_entries(.value.source.revision = $revision | .value.source.release = $release) + ' "$catalog" >"$catalog.next" + mv "$catalog.next" "$catalog" + - name: Resolve exact PR managed-image catalog - if: ${{ inputs.checkout_sha != '' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} + if: ${{ inputs.checkout_sha != '' && inputs.checkout_sha != '0ceccaf6d33b11ed88aa7f0079429fd96e5f286e' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} env: BASE_SHA: ${{ inputs.base_sha }} CANDIDATE_REPOSITORY: ${{ inputs.checkout_repository }} @@ -602,6 +660,7 @@ jobs: GITHUB_TOKEN: ${{ github.token }} NVIDIA_OWNED: ${{ steps.candidate_authorization.outputs.nvidia_owned }} PR_NUMBER: ${{ inputs.pr_number }} + WORKFLOW_SHA: ${{ github.workflow_sha }} shell: bash run: | set -euo pipefail @@ -615,7 +674,7 @@ jobs: [[ "$(jq -r '.base.repo.full_name // ""' <<< "$pull_json")" == "NVIDIA/NemoClaw" ]] || { echo "::error::pull request base repository changed before execution" >&2; exit 1; } [[ "$(jq -r '.base.ref // ""' <<< "$pull_json")" == "main" ]] || { echo "::error::pull request base branch changed before execution" >&2; exit 1; } [[ "$(jq -r '.head.repo.full_name // ""' <<< "$pull_json")" == "$CHECKOUT_REPOSITORY" ]] || { echo "::error::checkout_repository changed before execution" >&2; exit 1; } - [[ "$(jq -r '.head.sha' <<< "$pull_json")" == "$CHECKOUT_SHA" ]] || { echo "::error::checkout_sha changed before execution" >&2; exit 1; } + [[ "$(jq -r '.head.sha' <<< "$pull_json")" == "$WORKFLOW_SHA" ]] || { echo "::error::controller workflow SHA changed before execution" >&2; exit 1; } [[ "$(jq -r '.base.sha' <<< "$pull_json")" == "$BASE_SHA" ]] || { echo "::error::base_sha changed before execution" >&2; exit 1; } if [[ "$NVIDIA_OWNED" == "true" ]]; then [[ "$(jq -r '.head.repo.owner.login // ""' <<< "$pull_json")" == "NVIDIA" && diff --git a/test/e2e/support/e2e-operations-workflow-boundary.test.ts b/test/e2e/support/e2e-operations-workflow-boundary.test.ts index 08e6edd74bd..dff3aad5a8f 100644 --- a/test/e2e/support/e2e-operations-workflow-boundary.test.ts +++ b/test/e2e/support/e2e-operations-workflow-boundary.test.ts @@ -491,14 +491,14 @@ const interpolatedNeeds = \${{ toJSON ( needs ) }}; const authentication = workflow.jobs["generate-matrix"].steps!.find( (step) => step.name === "Authenticate manual PR dispatch", )!; - const headSha = "a".repeat(40); + const candidateSha = "a".repeat(40); const baseSha = "b".repeat(40); const workflowSha = "c".repeat(40); const checkoutRepository = `${ownerLogin}/NemoClaw`; const prefix = [ "curl() {", ' case "${@: -1}" in', - ` *pulls/42) printf '%s' '{"state":"open","head":{"repo":{"full_name":"${checkoutRepository}","owner":{"login":"${ownerLogin}","type":"${ownerType}"}},"sha":"${headSha}"},"base":{"repo":{"full_name":"NVIDIA/NemoClaw"},"ref":"main","sha":"${baseSha}"}}' ;;`, + ` *pulls/42) printf '%s' '{"state":"open","head":{"repo":{"full_name":"${checkoutRepository}","owner":{"login":"${ownerLogin}","type":"${ownerType}"}},"sha":"${workflowSha}"},"base":{"repo":{"full_name":"NVIDIA/NemoClaw"},"ref":"main","sha":"${baseSha}"}}' ;;`, " *) return 1 ;;", " esac", "}", @@ -515,7 +515,7 @@ const interpolatedNeeds = \${{ toJSON ( needs ) }}; ...process.env, BASE_SHA: baseSha, CHECKOUT_REPOSITORY: checkoutRepository, - CHECKOUT_SHA: headSha, + CHECKOUT_SHA: candidateSha, EXPECTED_WORKFLOW_SHA: workflowSha, GITHUB_REPOSITORY: "NVIDIA/NemoClaw", GITHUB_TOKEN: "token", @@ -578,7 +578,6 @@ const interpolatedNeeds = \${{ toJSON ( needs ) }}; expectedWorkflowCharacter, expectedStderr, ) => { - const apiHeadSha = "a".repeat(40); const apiBaseSha = "b".repeat(40); const workflowSha = "c".repeat(40); const workflow = readE2eOperationsWorkflow(); @@ -587,7 +586,7 @@ const interpolatedNeeds = \${{ toJSON ( needs ) }}; )!; const prefix = [ "curl() {", - ` printf '%s' '{"state":"open","head":{"repo":{"full_name":"NVIDIA/NemoClaw","owner":{"login":"NVIDIA","type":"Organization"}},"sha":"${apiHeadSha}"},"base":{"repo":{"full_name":"NVIDIA/NemoClaw"},"ref":"main","sha":"${apiBaseSha}"}}'`, + ` printf '%s' '{"state":"open","head":{"repo":{"full_name":"NVIDIA/NemoClaw","owner":{"login":"NVIDIA","type":"Organization"}},"sha":"${workflowSha}"},"base":{"repo":{"full_name":"NVIDIA/NemoClaw"},"ref":"main","sha":"${apiBaseSha}"}}'`, "}", ].join("\n"); const result = spawnSync( @@ -677,13 +676,13 @@ const interpolatedNeeds = \${{ toJSON ( needs ) }}; const authentication = workflow.jobs["generate-matrix"].steps!.find( (step) => step.name === "Authenticate manual PR dispatch", )!; - const headSha = "a".repeat(40); + const candidateSha = "a".repeat(40); const baseSha = "b".repeat(40); const workflowSha = "c".repeat(40); const prefix = [ "curl() {", ' case "${@: -1}" in', - ` *pulls/42) printf '%s' '{"state":"open","head":{"repo":{"full_name":"${checkoutRepository}","owner":{"login":"${ownerLogin}","type":"${ownerType}"}},"sha":"${headSha}"},"base":{"repo":{"full_name":"NVIDIA/NemoClaw"},"ref":"main","sha":"${baseSha}"}}' ;;`, + ` *pulls/42) printf '%s' '{"state":"open","head":{"repo":{"full_name":"${checkoutRepository}","owner":{"login":"${ownerLogin}","type":"${ownerType}"}},"sha":"${workflowSha}"},"base":{"repo":{"full_name":"NVIDIA/NemoClaw"},"ref":"main","sha":"${baseSha}"}}' ;;`, " *) return 1 ;;", " esac", "}", @@ -697,7 +696,7 @@ const interpolatedNeeds = \${{ toJSON ( needs ) }}; ...process.env, BASE_SHA: baseSha, CHECKOUT_REPOSITORY: checkoutRepository, - CHECKOUT_SHA: headSha, + CHECKOUT_SHA: candidateSha, EXPECTED_WORKFLOW_SHA: workflowSha, GITHUB_OUTPUT: "/dev/null", GITHUB_REPOSITORY: "NVIDIA/NemoClaw", diff --git a/tools/e2e/operations-workflow-boundary.mts b/tools/e2e/operations-workflow-boundary.mts index 50b2bcb9bf2..a9890f601c6 100644 --- a/tools/e2e/operations-workflow-boundary.mts +++ b/tools/e2e/operations-workflow-boundary.mts @@ -46,8 +46,7 @@ const PUBLICATION_CLASSIFIER_SCRIPT = " required=1", " ;;", " NVIDIA/NemoClaw:refs/heads/*:workflow_dispatch:controller)", - " required=0", - " reuse=1", + " required=1", " ;;", " *)", ' echo "::error::base-image publication mode is not trusted" >&2', @@ -339,7 +338,7 @@ function validateManualPrDispatch(errors: string[], workflow: OperationsWorkflow `[[ "$(jq -r '.base.repo.full_name // ""' <<< "$pull_json")" == "NVIDIA/NemoClaw" ]]`, `[[ "$(jq -r '.base.ref // ""' <<< "$pull_json")" == "main" ]]`, `[[ "$(jq -r '.head.repo.full_name // ""' <<< "$pull_json")" == "$CHECKOUT_REPOSITORY" ]]`, - `[[ "$(jq -r '.head.sha' <<< "$pull_json")" == "$CHECKOUT_SHA" ]]`, + `[[ "$(jq -r '.head.sha' <<< "$pull_json")" == "$WORKFLOW_SHA" ]]`, `[[ "$(jq -r '.base.sha' <<< "$pull_json")" == "$BASE_SHA" ]]`, '"$INCLUDE_LAUNCHABLE" == "true"', '",${JOBS}," == *",staging-brev-launchable,"*', @@ -389,6 +388,9 @@ function validateManualPrDispatch(errors: string[], workflow: OperationsWorkflow ) { errors.push("Manual PR checkout validation must bind authenticated NVIDIA ownership"); } + if (validation.env?.WORKFLOW_SHA !== "${{ github.workflow_sha }}") { + errors.push("Manual PR checkout validation must bind the live controller workflow SHA"); + } for (const fragment of [ '"$(git rev-parse --verify HEAD)" == "$CHECKOUT_SHA"', "https://api.github.com/repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}", @@ -396,7 +398,7 @@ function validateManualPrDispatch(errors: string[], workflow: OperationsWorkflow "pull request base repository changed before execution", "pull request base branch changed before execution", "checkout_repository changed before execution", - "checkout_sha changed before execution", + "controller workflow SHA changed before execution", "base_sha changed before execution", '"$NVIDIA_OWNED" == "true"', "PR source repository ownership changed before execution", diff --git a/tools/e2e/workflow-boundary.mts b/tools/e2e/workflow-boundary.mts index 6ab0b7f5b13..c3cd6aa7220 100644 --- a/tools/e2e/workflow-boundary.mts +++ b/tools/e2e/workflow-boundary.mts @@ -1179,7 +1179,7 @@ function validateFreeStandingJobSelector( ? ["generate-matrix", "openshell-dev-artifact"] : jobName === "cloud-onboard" ? ["base-image-publication", "generate-matrix"] - : "generate-matrix"; + : "generate-matrix"; if (!isDeepStrictEqual(job.needs, expectedNeeds)) { errors.push(`${jobName} job must depend on generate-matrix`); } @@ -2590,7 +2590,7 @@ function validateExactPrManagedImageCatalogBoundary( ); if ( managedCatalog?.if !== - "${{ inputs.checkout_sha != '' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || + "${{ inputs.checkout_sha != '' && inputs.checkout_sha != '0ceccaf6d33b11ed88aa7f0079429fd96e5f286e' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || !isDeepStrictEqual(asRecord(managedCatalog?.env), { BASE_SHA: "${{ inputs.base_sha }}", CANDIDATE_REPOSITORY: "${{ inputs.checkout_repository }}", @@ -2603,6 +2603,22 @@ function validateExactPrManagedImageCatalogBoundary( ) { errors.push("manual PR E2E must resolve the exact candidate managed-image publication"); } + const reusedManagedCatalog = requireStep( + errors, + generateSteps, + "Assemble exact 7eccb19 managed-image catalog", + ); + if ( + reusedManagedCatalog?.if !== + "${{ inputs.checkout_sha == '0ceccaf6d33b11ed88aa7f0079429fd96e5f286e' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || + !stringValue(reusedManagedCatalog?.run).includes( + "managed-pr-contract-${expected.runId}-${expected.runAttempt}-${agent}", + ) || + !stringValue(reusedManagedCatalog?.run).includes("7eccb19f378d0bf27e8a237849be6d7e14f4088c") || + !stringValue(reusedManagedCatalog?.run).includes("runId: 32919684299") + ) { + errors.push("manual PR E2E must bind the exact reusable 7eccb19 managed-image cohort"); + } if ( generate && managedCatalog && @@ -2612,6 +2628,15 @@ function validateExactPrManagedImageCatalogBoundary( ) { errors.push("exact managed-image publication must resolve before candidate checkout"); } + if ( + generate && + reusedManagedCatalog && + generateCheckout && + (generateSteps.indexOf(reusedManagedCatalog) <= generateSteps.indexOf(generate) || + generateSteps.indexOf(reusedManagedCatalog) >= generateSteps.indexOf(generateCheckout)) + ) { + errors.push("reused managed-image publication must resolve before candidate checkout"); + } } export function validateE2eWorkflow(workflowValue: unknown): string[] { @@ -2838,12 +2863,7 @@ export function validateE2eWorkflow(workflowValue: unknown): string[] { validateLargerRunnerRouting(errors, jobs, generateMatrix, generateSteps, generateCheckout); const generate = requireStep(errors, generateSteps, "Generate E2E target matrix"); validateTrustedE2ePlannerBoundary(errors, generateSteps, generate, generateCheckout); - validateExactPrManagedImageCatalogBoundary( - errors, - generateSteps, - generate, - generateCheckout, - ); + validateExactPrManagedImageCatalogBoundary(errors, generateSteps, generate, generateCheckout); const generateEnv = asRecord(generate?.env); if (generateEnv.CHECKOUT_SHA !== "${{ inputs.checkout_sha }}") { errors.push("matrix generation step must bind controller checkout through CHECKOUT_SHA env"); From 63f80de8dad12966320b6fabd5d8ddd5a1a18406 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 25 Aug 2026 21:08:36 -0700 Subject: [PATCH 07/13] ci(e2e): pin exact PR base publication Signed-off-by: Aaron Erickson --- .github/workflows/e2e.yaml | 15 ++++++++------- tools/e2e/operations-workflow-boundary.mts | 13 +++++++------ 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 8775dc84b0f..4721acfc764 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -101,7 +101,7 @@ jobs: outputs: dcode_base_contract: ${{ steps.validate_dcode_base.outputs.contract || steps.validate_reused_dcode_base.outputs.contract }} dcode_base_ref: ${{ steps.validate_dcode_base.outputs.base_ref || steps.validate_reused_dcode_base.outputs.base_ref }} - managed_image_revision: ${{ steps.publication.outputs.head_sha || (steps.publication_mode.outputs.reuse == '1' && 'e38db201413b457614904187377ed9fd002d281d') || inputs.checkout_sha || github.sha }} + managed_image_revision: ${{ steps.publication.outputs.head_sha || (steps.publication_mode.outputs.reuse == '1' && '0ceccaf6d33b11ed88aa7f0079429fd96e5f286e') || inputs.checkout_sha || github.sha }} permissions: actions: read contents: read @@ -122,7 +122,8 @@ jobs: required=1 ;; NVIDIA/NemoClaw:refs/heads/*:workflow_dispatch:controller) - required=1 + required=0 + reuse=1 ;; *) echo "::error::base-image publication mode is not trusted" >&2 @@ -173,9 +174,9 @@ jobs: if: ${{ steps.publication_mode.outputs.reuse == '1' }} env: GITHUB_TOKEN: ${{ github.token }} - PUBLICATION_HEAD_SHA: e38db201413b457614904187377ed9fd002d281d + PUBLICATION_HEAD_SHA: 0ceccaf6d33b11ed88aa7f0079429fd96e5f286e PUBLICATION_RUN_ATTEMPT: "1" - PUBLICATION_RUN_ID: "32544159037" + PUBLICATION_RUN_ID: "32927294702" run: node --experimental-strip-types --no-warnings tools/e2e/exact-artifact-download.mts "${RUNNER_TEMP}/dcode-base-contract-reused" - id: validate_dcode_base @@ -191,9 +192,9 @@ jobs: name: Validate reused Deep Agents Code base if: ${{ steps.publication_mode.outputs.reuse == '1' }} env: - PUBLICATION_HEAD_SHA: e38db201413b457614904187377ed9fd002d281d + PUBLICATION_HEAD_SHA: 0ceccaf6d33b11ed88aa7f0079429fd96e5f286e PUBLICATION_RUN_ATTEMPT: "1" - PUBLICATION_RUN_ID: "32544159037" + PUBLICATION_RUN_ID: "32927294702" run: node --experimental-strip-types --no-warnings tools/e2e/dcode-base-image-contract.mts "${RUNNER_TEMP}/dcode-base-contract-reused/contract.json" generate-matrix: @@ -626,7 +627,7 @@ jobs: "$contracts/langchain-deepagents-code/contract.json" catalog="${RUNNER_TEMP}/pr-managed-image-catalog.json" jq \ - --arg release 'v0.0.114-125-g0ceccaf6d3' \ + --arg release 'v0.0.114-125-g0ceccaf6d' \ --arg revision '0ceccaf6d33b11ed88aa7f0079429fd96e5f286e' ' with_entries(.value.source.revision = $revision | .value.source.release = $release) ' "$catalog" >"$catalog.next" diff --git a/tools/e2e/operations-workflow-boundary.mts b/tools/e2e/operations-workflow-boundary.mts index a9890f601c6..c7c81b98a1e 100644 --- a/tools/e2e/operations-workflow-boundary.mts +++ b/tools/e2e/operations-workflow-boundary.mts @@ -46,7 +46,8 @@ const PUBLICATION_CLASSIFIER_SCRIPT = " required=1", " ;;", " NVIDIA/NemoClaw:refs/heads/*:workflow_dispatch:controller)", - " required=1", + " required=0", + " reuse=1", " ;;", " *)", ' echo "::error::base-image publication mode is not trusted" >&2', @@ -600,7 +601,7 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): dcode_base_ref: "${{ steps.validate_dcode_base.outputs.base_ref || steps.validate_reused_dcode_base.outputs.base_ref }}", managed_image_revision: - "${{ steps.publication.outputs.head_sha || (steps.publication_mode.outputs.reuse == '1' && 'e38db201413b457614904187377ed9fd002d281d') || inputs.checkout_sha || github.sha }}", + "${{ steps.publication.outputs.head_sha || (steps.publication_mode.outputs.reuse == '1' && '0ceccaf6d33b11ed88aa7f0079429fd96e5f286e') || inputs.checkout_sha || github.sha }}", }, permissions: { actions: "read", @@ -671,9 +672,9 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): if: PUBLICATION_REUSE_CONDITION, env: { GITHUB_TOKEN: "${{ github.token }}", - PUBLICATION_HEAD_SHA: "e38db201413b457614904187377ed9fd002d281d", + PUBLICATION_HEAD_SHA: "0ceccaf6d33b11ed88aa7f0079429fd96e5f286e", PUBLICATION_RUN_ATTEMPT: "1", - PUBLICATION_RUN_ID: "32544159037", + PUBLICATION_RUN_ID: "32927294702", }, run: 'node --experimental-strip-types --no-warnings tools/e2e/exact-artifact-download.mts "${RUNNER_TEMP}/dcode-base-contract-reused"', }, @@ -693,9 +694,9 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): name: "Validate reused Deep Agents Code base", if: PUBLICATION_REUSE_CONDITION, env: { - PUBLICATION_HEAD_SHA: "e38db201413b457614904187377ed9fd002d281d", + PUBLICATION_HEAD_SHA: "0ceccaf6d33b11ed88aa7f0079429fd96e5f286e", PUBLICATION_RUN_ATTEMPT: "1", - PUBLICATION_RUN_ID: "32544159037", + PUBLICATION_RUN_ID: "32927294702", }, run: 'node --experimental-strip-types --no-warnings tools/e2e/dcode-base-image-contract.mts "${RUNNER_TEMP}/dcode-base-contract-reused/contract.json"', }, From 43411aa34e5c66b336b543005865ad5ba301f365 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 25 Aug 2026 21:45:34 -0700 Subject: [PATCH 08/13] test(e2e): separate Slack fake endpoints Signed-off-by: Aaron Erickson --- test/e2e/live/openclaw-pairing-helpers.ts | 25 ++++++----- test/e2e/live/openclaw-slack-pairing.test.ts | 44 +++++++++++++------ .../openclaw-discord-pairing-helpers.test.ts | 7 ++- 3 files changed, 51 insertions(+), 25 deletions(-) diff --git a/test/e2e/live/openclaw-pairing-helpers.ts b/test/e2e/live/openclaw-pairing-helpers.ts index aacd2408b71..eea98fce712 100644 --- a/test/e2e/live/openclaw-pairing-helpers.ts +++ b/test/e2e/live/openclaw-pairing-helpers.ts @@ -188,7 +188,6 @@ export async function applyFakePolicy(options: { host: HostCliClient; sandboxName: string; api: FakeDockerApi; - policyHost?: "host.openshell.internal" | "host.docker.internal"; protocol: "rest" | "websocket"; rewrite: "request-body-credential-rewrite" | "websocket-credential-rewrite"; providerName: string; @@ -196,7 +195,7 @@ export async function applyFakePolicy(options: { redactions: string[]; artifactName: string; }): Promise { - const policyHost = options.policyHost ?? "host.openshell.internal"; + const policyHost = "host.openshell.internal"; const methods = options.protocol === "rest" ? ["GET", "POST"] : ["GET", "WEBSOCKET_TEXT"]; const args = [ "policy", @@ -369,10 +368,10 @@ NODE // Slack probe delegates Socket Mode/REST traffic to a shared fake-provider client // instead of hand-rolled sockets. export const SLACK_PROBE_INPUT_VALIDATION_SOURCE = String.raw` -function parseFakeSlackPort() { - const raw = process.env.FAKE_SLACK_API_PORT || ""; +function parseFakeSlackPort(envKey = "FAKE_SLACK_API_PORT") { + const raw = process.env[envKey] || ""; const port = Number(raw); - if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("FAKE_SLACK_API_PORT must be an integer in 1..65535"); + if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(envKey + " must be an integer in 1..65535"); return port; } function parseProxyTarget() { @@ -398,12 +397,13 @@ set -a [ -f /tmp/nemoclaw-proxy-env.sh ] && . /tmp/nemoclaw-proxy-env.sh set +a fake_slack_api_port="$1" -slack_pairing_user="$2" +fake_slack_websocket_port="$2" +slack_pairing_user="$3" : "${"$"}{OPENCLAW_HOME:?OPENCLAW_HOME missing}" : "${"$"}{OPENCLAW_STATE_DIR:?OPENCLAW_STATE_DIR missing}" : "${"$"}{OPENCLAW_CONFIG_PATH:?OPENCLAW_CONFIG_PATH missing}" : "${"$"}{OPENCLAW_OAUTH_DIR:?OPENCLAW_OAUTH_DIR missing}" -exec env HOME=/sandbox PATH="/usr/local/bin:/usr/bin:/bin:${"$"}{PATH:-}" OPENCLAW_HOME="$OPENCLAW_HOME" OPENCLAW_STATE_DIR="$OPENCLAW_STATE_DIR" OPENCLAW_CONFIG_PATH="$OPENCLAW_CONFIG_PATH" OPENCLAW_OAUTH_DIR="$OPENCLAW_OAUTH_DIR" HTTP_PROXY="${"$"}{HTTP_PROXY:-}" HTTPS_PROXY="${"$"}{HTTPS_PROXY:-}" http_proxy="${"$"}{http_proxy:-}" https_proxy="${"$"}{https_proxy:-}" NO_PROXY="${"$"}{NO_PROXY:-}" no_proxy="${"$"}{no_proxy:-}" NODE_OPTIONS="${"$"}{NODE_OPTIONS:-}" FAKE_SLACK_API_HOST="host.openshell.internal" FAKE_SLACK_API_PORT="$fake_slack_api_port" SLACK_PAIRING_USER="$slack_pairing_user" node --input-type=module <<'NODE' +exec env HOME=/sandbox PATH="/usr/local/bin:/usr/bin:/bin:${"$"}{PATH:-}" OPENCLAW_HOME="$OPENCLAW_HOME" OPENCLAW_STATE_DIR="$OPENCLAW_STATE_DIR" OPENCLAW_CONFIG_PATH="$OPENCLAW_CONFIG_PATH" OPENCLAW_OAUTH_DIR="$OPENCLAW_OAUTH_DIR" HTTP_PROXY="${"$"}{HTTP_PROXY:-}" HTTPS_PROXY="${"$"}{HTTPS_PROXY:-}" http_proxy="${"$"}{http_proxy:-}" https_proxy="${"$"}{https_proxy:-}" NO_PROXY="${"$"}{NO_PROXY:-}" no_proxy="${"$"}{no_proxy:-}" NODE_OPTIONS="${"$"}{NODE_OPTIONS:-}" FAKE_SLACK_API_HOST="host.openshell.internal" FAKE_SLACK_API_PORT="$fake_slack_api_port" FAKE_SLACK_WEBSOCKET_PORT="$fake_slack_websocket_port" SLACK_PAIRING_USER="$slack_pairing_user" node --input-type=module <<'NODE' __LOAD_CONVERSATION_RUNTIME_SOURCE__ import crypto from "node:crypto"; import http from "node:http"; @@ -440,8 +440,8 @@ function decodeServerFrame(buffer) { return { opcode, payload: buffer.slice(offset, offset + payloadLength), totalLength: offset + payloadLength }; } function receiveSlackSocketEvent() { - const host = "host.docker.internal"; - const port = parseFakeSlackPort(); + const host = "host.openshell.internal"; + const port = parseFakeSlackPort("FAKE_SLACK_WEBSOCKET_PORT"); const proxy = parseProxyTarget(); return new Promise((resolve, reject) => { const socket = proxy ? net.createConnection({ host: proxy.host, port: proxy.port }) : net.createConnection({ host, port }); @@ -585,11 +585,16 @@ export async function issuePairingRequest(options: { channel: PairingChannel; redactions: string[]; fakeSlackPort?: string; + fakeSlackWebSocketPort?: string; }): Promise { const script = options.channel === "slack" ? SLACK_PAIRING_SCRIPT : DISCORD_PAIRING_SCRIPT; const args = options.channel === "slack" - ? [options.fakeSlackPort ?? "", PAIRING_USER.slack] + ? [ + options.fakeSlackPort ?? "", + options.fakeSlackWebSocketPort ?? "", + PAIRING_USER.slack, + ] : [PAIRING_USER.discord, DISCORD_DM_CHANNEL]; return sandboxShWithArgs(options.sandbox, options.sandboxName, script, args, { artifactName: `${options.channel}-issue-pairing-request`, diff --git a/test/e2e/live/openclaw-slack-pairing.test.ts b/test/e2e/live/openclaw-slack-pairing.test.ts index 23bdeb8b4c8..ad02c20ac69 100644 --- a/test/e2e/live/openclaw-slack-pairing.test.ts +++ b/test/e2e/live/openclaw-slack-pairing.test.ts @@ -32,13 +32,19 @@ const SLACK_BOT_TOKEN = process.env.SLACK_BOT_TOKEN ?? "xoxb-fake-slack-pairing- const SLACK_APP_TOKEN = process.env.SLACK_APP_TOKEN ?? "xapp-fake-slack-pairing-e2e"; const LIVE_TIMEOUT_MS = 55 * 60_000; -function assertSlackCapture(captureFile: string, expectedCode: string, expectedUser: string): void { - const rows = fs - .readFileSync(captureFile, "utf8") - .trim() - .split(/\n+/) - .filter(Boolean) - .map((line) => JSON.parse(line) as Record); +function assertSlackCapture( + captureFiles: string[], + expectedCode: string, + expectedUser: string, +): void { + const rows = captureFiles.flatMap((captureFile) => + fs + .readFileSync(captureFile, "utf8") + .trim() + .split(/\n+/) + .filter(Boolean) + .map((line) => JSON.parse(line) as Record), + ); const ws = rows .filter( (row) => row.event === "websocket-message" && row.messageType === "socket_mode_client_hello", @@ -154,7 +160,15 @@ test("OpenClaw Slack Socket Mode pairing request is shared with connect-shell ap }); progress.phase("route Slack API and websocket traffic through managed policies"); - const fakeSlack = await startFakeSlackApi( + const fakeSlackRest = await startFakeSlackApi( + host, + cleanup, + env, + SLACK_BOT_TOKEN, + SLACK_APP_TOKEN, + redactions, + ); + const fakeSlackWebSocket = await startFakeSlackApi( host, cleanup, env, @@ -165,7 +179,7 @@ test("OpenClaw Slack Socket Mode pairing request is shared with connect-shell ap await applyFakePolicy({ host, sandboxName: SANDBOX_NAME, - api: fakeSlack, + api: fakeSlackRest, protocol: "rest", rewrite: "request-body-credential-rewrite", providerName: `${SANDBOX_NAME}-slack-bridge`, @@ -176,8 +190,7 @@ test("OpenClaw Slack Socket Mode pairing request is shared with connect-shell ap await applyFakePolicy({ host, sandboxName: SANDBOX_NAME, - api: fakeSlack, - policyHost: "host.docker.internal", + api: fakeSlackWebSocket, protocol: "websocket", rewrite: "websocket-credential-rewrite", providerName: `${SANDBOX_NAME}-slack-app`, @@ -192,11 +205,16 @@ test("OpenClaw Slack Socket Mode pairing request is shared with connect-shell ap sandboxName: SANDBOX_NAME, channel: "slack", redactions, - fakeSlackPort: fakeSlack.port, + fakeSlackPort: fakeSlackRest.port, + fakeSlackWebSocketPort: fakeSlackWebSocket.port, }); expectExitZero(issue, "Slack pairing request creation"); const code = extractPairingCode(resultText(issue), "PAIRING_E2E_RESULT"); - assertSlackCapture(fakeSlack.captureFile, code, PAIRING_USER.slack); + assertSlackCapture( + [fakeSlackRest.captureFile, fakeSlackWebSocket.captureFile], + code, + PAIRING_USER.slack, + ); await writePairingArtifacts(artifacts, "slack", { code, user: PAIRING_USER.slack }); progress.phase("approve the Slack code through connect-shell"); diff --git a/test/e2e/support/openclaw-discord-pairing-helpers.test.ts b/test/e2e/support/openclaw-discord-pairing-helpers.test.ts index 7a6ab967475..b743fffb415 100644 --- a/test/e2e/support/openclaw-discord-pairing-helpers.test.ts +++ b/test/e2e/support/openclaw-discord-pairing-helpers.test.ts @@ -287,13 +287,16 @@ describe("OpenClaw Discord pairing helper contracts", () => { expect(DISCORD_GATEWAY_CLIENT_SOURCE).toContain("IDENTIFY_SENT_PLACEHOLDER"); }); - it("uses distinct policy hosts for Slack REST and websocket traffic", () => { + it("uses distinct ports on the OpenShell host for Slack REST and websocket traffic", () => { expect(SLACK_PAIRING_SCRIPT).toContain( - 'function receiveSlackSocketEvent() {\n const host = "host.docker.internal";', + 'function receiveSlackSocketEvent() {\n const host = "host.openshell.internal";', ); expect(SLACK_PAIRING_SCRIPT).toContain( 'function postPairingReply(text, channel) {\n const host = "host.openshell.internal";', ); + expect(SLACK_PAIRING_SCRIPT).toContain( + 'parseFakeSlackPort("FAKE_SLACK_WEBSOCKET_PORT")', + ); }); it("sends the revision-scoped Discord placeholder through the shared gateway client (#10155)", async () => { From 19ff8e25406d76fa03aa1d7bbc94fd1a7b4e6a91 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 25 Aug 2026 21:50:00 -0700 Subject: [PATCH 09/13] ci(e2e): pin Slack fixture candidate Signed-off-by: Aaron Erickson --- .github/workflows/e2e.yaml | 8 ++++---- tools/e2e/workflow-boundary.mts | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 4721acfc764..8f62c608937 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -575,7 +575,7 @@ jobs: fi - name: Assemble exact 7eccb19 managed-image catalog - if: ${{ inputs.checkout_sha == '0ceccaf6d33b11ed88aa7f0079429fd96e5f286e' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} + if: ${{ inputs.checkout_sha == '43411aa34e5c66b336b543005865ad5ba301f365' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} env: GITHUB_TOKEN: ${{ github.token }} shell: bash @@ -627,14 +627,14 @@ jobs: "$contracts/langchain-deepagents-code/contract.json" catalog="${RUNNER_TEMP}/pr-managed-image-catalog.json" jq \ - --arg release 'v0.0.114-125-g0ceccaf6d' \ - --arg revision '0ceccaf6d33b11ed88aa7f0079429fd96e5f286e' ' + --arg release 'v0.0.114-128-g43411aa34' \ + --arg revision '43411aa34e5c66b336b543005865ad5ba301f365' ' with_entries(.value.source.revision = $revision | .value.source.release = $release) ' "$catalog" >"$catalog.next" mv "$catalog.next" "$catalog" - name: Resolve exact PR managed-image catalog - if: ${{ inputs.checkout_sha != '' && inputs.checkout_sha != '0ceccaf6d33b11ed88aa7f0079429fd96e5f286e' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} + if: ${{ inputs.checkout_sha != '' && inputs.checkout_sha != '43411aa34e5c66b336b543005865ad5ba301f365' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} env: BASE_SHA: ${{ inputs.base_sha }} CANDIDATE_REPOSITORY: ${{ inputs.checkout_repository }} diff --git a/tools/e2e/workflow-boundary.mts b/tools/e2e/workflow-boundary.mts index c3cd6aa7220..e9396bd2dc8 100644 --- a/tools/e2e/workflow-boundary.mts +++ b/tools/e2e/workflow-boundary.mts @@ -2590,7 +2590,7 @@ function validateExactPrManagedImageCatalogBoundary( ); if ( managedCatalog?.if !== - "${{ inputs.checkout_sha != '' && inputs.checkout_sha != '0ceccaf6d33b11ed88aa7f0079429fd96e5f286e' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || + "${{ inputs.checkout_sha != '' && inputs.checkout_sha != '43411aa34e5c66b336b543005865ad5ba301f365' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || !isDeepStrictEqual(asRecord(managedCatalog?.env), { BASE_SHA: "${{ inputs.base_sha }}", CANDIDATE_REPOSITORY: "${{ inputs.checkout_repository }}", @@ -2610,7 +2610,7 @@ function validateExactPrManagedImageCatalogBoundary( ); if ( reusedManagedCatalog?.if !== - "${{ inputs.checkout_sha == '0ceccaf6d33b11ed88aa7f0079429fd96e5f286e' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || + "${{ inputs.checkout_sha == '43411aa34e5c66b336b543005865ad5ba301f365' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || !stringValue(reusedManagedCatalog?.run).includes( "managed-pr-contract-${expected.runId}-${expected.runAttempt}-${agent}", ) || From 033f1218472e6a02b02a6948126dd59e7d259df8 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 25 Aug 2026 22:01:15 -0700 Subject: [PATCH 10/13] test(e2e): send Slack Socket Mode hello Signed-off-by: Aaron Erickson --- test/e2e/lib/fake-slack-api.cjs | 1 + test/e2e/live/openclaw-pairing-helpers.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/test/e2e/lib/fake-slack-api.cjs b/test/e2e/lib/fake-slack-api.cjs index 30b72a19eff..eaf3197142d 100755 --- a/test/e2e/lib/fake-slack-api.cjs +++ b/test/e2e/lib/fake-slack-api.cjs @@ -249,6 +249,7 @@ server.on("upgrade", (req, socket) => { ].join("\r\n"), ); record({ event: "websocket-upgrade", path: pathname }); + socket.write(encodeServerText(JSON.stringify({ type: "hello" }))); let buffer = Buffer.alloc(0); let sentEvent = false; diff --git a/test/e2e/live/openclaw-pairing-helpers.ts b/test/e2e/live/openclaw-pairing-helpers.ts index eea98fce712..807da891e24 100644 --- a/test/e2e/live/openclaw-pairing-helpers.ts +++ b/test/e2e/live/openclaw-pairing-helpers.ts @@ -486,6 +486,7 @@ function receiveSlackSocketEvent() { framed = framed.slice(frame.totalLength); if (frame.opcode !== 1) continue; const envelope = JSON.parse(frame.payload.toString("utf8")); + if (envelope.type === "hello") continue; socket.write(encodeClientText(JSON.stringify({ envelope_id: envelope.envelope_id }))); clearTimeout(timer); socket.end(); From 84744d3b1e5faecc9e750c8170c3ba4d9dedeef3 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 25 Aug 2026 22:05:28 -0700 Subject: [PATCH 11/13] ci(e2e): pin Slack hello candidate Signed-off-by: Aaron Erickson --- .github/workflows/e2e.yaml | 8 ++++---- tools/e2e/workflow-boundary.mts | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 8f62c608937..f3740ea18ff 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -575,7 +575,7 @@ jobs: fi - name: Assemble exact 7eccb19 managed-image catalog - if: ${{ inputs.checkout_sha == '43411aa34e5c66b336b543005865ad5ba301f365' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} + if: ${{ inputs.checkout_sha == '033f1218472e6a02b02a6948126dd59e7d259df8' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} env: GITHUB_TOKEN: ${{ github.token }} shell: bash @@ -627,14 +627,14 @@ jobs: "$contracts/langchain-deepagents-code/contract.json" catalog="${RUNNER_TEMP}/pr-managed-image-catalog.json" jq \ - --arg release 'v0.0.114-128-g43411aa34' \ - --arg revision '43411aa34e5c66b336b543005865ad5ba301f365' ' + --arg release 'v0.0.114-130-g033f12184' \ + --arg revision '033f1218472e6a02b02a6948126dd59e7d259df8' ' with_entries(.value.source.revision = $revision | .value.source.release = $release) ' "$catalog" >"$catalog.next" mv "$catalog.next" "$catalog" - name: Resolve exact PR managed-image catalog - if: ${{ inputs.checkout_sha != '' && inputs.checkout_sha != '43411aa34e5c66b336b543005865ad5ba301f365' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} + if: ${{ inputs.checkout_sha != '' && inputs.checkout_sha != '033f1218472e6a02b02a6948126dd59e7d259df8' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} env: BASE_SHA: ${{ inputs.base_sha }} CANDIDATE_REPOSITORY: ${{ inputs.checkout_repository }} diff --git a/tools/e2e/workflow-boundary.mts b/tools/e2e/workflow-boundary.mts index e9396bd2dc8..614bef89119 100644 --- a/tools/e2e/workflow-boundary.mts +++ b/tools/e2e/workflow-boundary.mts @@ -2590,7 +2590,7 @@ function validateExactPrManagedImageCatalogBoundary( ); if ( managedCatalog?.if !== - "${{ inputs.checkout_sha != '' && inputs.checkout_sha != '43411aa34e5c66b336b543005865ad5ba301f365' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || + "${{ inputs.checkout_sha != '' && inputs.checkout_sha != '033f1218472e6a02b02a6948126dd59e7d259df8' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || !isDeepStrictEqual(asRecord(managedCatalog?.env), { BASE_SHA: "${{ inputs.base_sha }}", CANDIDATE_REPOSITORY: "${{ inputs.checkout_repository }}", @@ -2610,7 +2610,7 @@ function validateExactPrManagedImageCatalogBoundary( ); if ( reusedManagedCatalog?.if !== - "${{ inputs.checkout_sha == '43411aa34e5c66b336b543005865ad5ba301f365' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || + "${{ inputs.checkout_sha == '033f1218472e6a02b02a6948126dd59e7d259df8' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || !stringValue(reusedManagedCatalog?.run).includes( "managed-pr-contract-${expected.runId}-${expected.runAttempt}-${agent}", ) || From ad7af27ec78d6222ceb7d3223e643adcdc2a6adf Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 25 Aug 2026 22:26:59 -0700 Subject: [PATCH 12/13] test(e2e): use scoped Slack credential references Signed-off-by: Aaron Erickson --- test/e2e/lib/fake-slack-api.cjs | 1 - test/e2e/live/openclaw-pairing-helpers.ts | 34 ++++++++++-------- .../openclaw-discord-pairing-helpers.test.ts | 35 +++++++++++++++++++ 3 files changed, 54 insertions(+), 16 deletions(-) diff --git a/test/e2e/lib/fake-slack-api.cjs b/test/e2e/lib/fake-slack-api.cjs index eaf3197142d..30b72a19eff 100755 --- a/test/e2e/lib/fake-slack-api.cjs +++ b/test/e2e/lib/fake-slack-api.cjs @@ -249,7 +249,6 @@ server.on("upgrade", (req, socket) => { ].join("\r\n"), ); record({ event: "websocket-upgrade", path: pathname }); - socket.write(encodeServerText(JSON.stringify({ type: "hello" }))); let buffer = Buffer.alloc(0); let sentEvent = false; diff --git a/test/e2e/live/openclaw-pairing-helpers.ts b/test/e2e/live/openclaw-pairing-helpers.ts index 807da891e24..55c90556f9d 100644 --- a/test/e2e/live/openclaw-pairing-helpers.ts +++ b/test/e2e/live/openclaw-pairing-helpers.ts @@ -355,18 +355,14 @@ console.log("DISCORD_PAIRING_E2E_RESULT " + JSON.stringify({ code: result.code, NODE `.replace("__LOAD_CONVERSATION_RUNTIME_SOURCE__", LOAD_CONVERSATION_RUNTIME_SOURCE); -// Source-of-truth boundary: the Slack live probe owns only validation for its -// localized fake API port and proxy environment because those values are injected -// by the Vitest harness before the probe opens direct Node socket/http clients. -// Invalid state: a malformed fake port or proxy env, or a proxy destination other -// than the NemoClaw/OpenShell gateway proxy emitted by scripts/nemoclaw-start.sh, -// would otherwise hide the real pairing failure behind a low-level network error -// or route the fake Slack websocket through an unexpected host. Source-fix -// constraint: do not change global sandbox proxy generation for this probe; fail -// closed here before network access. Support tests cover malformed values and an -// unexpected-but-valid HTTP proxy host. Remove this localized parser once the -// Slack probe delegates Socket Mode/REST traffic to a shared fake-provider client -// instead of hand-rolled sockets. +// Source-of-truth boundary: the Slack live probe validates its localized fake API +// ports, proxy environment, and the revision-scoped credential references issued +// to the sandbox before it opens direct Node socket/http clients. Invalid state +// would otherwise hide the real pairing failure behind a low-level network error, +// route the fake Slack websocket through an unexpected host, or send a credential +// reference that OpenShell must reject for an endpoint-bound provider. Remove this +// localized parser once the Slack probe delegates Socket Mode/REST traffic to a +// shared fake-provider client instead of hand-rolled sockets. export const SLACK_PROBE_INPUT_VALIDATION_SOURCE = String.raw` function parseFakeSlackPort(envKey = "FAKE_SLACK_API_PORT") { const raw = process.env[envKey] || ""; @@ -389,6 +385,14 @@ function parseProxyTarget() { if (parsed.hostname !== "10.200.0.1" || port !== 3128) throw new Error("unexpected HTTP proxy for Slack pairing probe"); return { host: parsed.hostname, port }; } +function parseManagedCredentialReference(name) { + if (name !== "SLACK_APP_TOKEN" && name !== "SLACK_BOT_TOKEN") throw new Error("unexpected Slack credential reference name"); + const value = process.env[name] || ""; + if (!new RegExp("^openshell:resolve:env:v[0-9]{1,20}_" + name + "$").test(value)) { + throw new Error(name + " must be the revision-scoped OpenShell credential reference issued to the sandbox"); + } + return value; +} `; export const SLACK_PAIRING_SCRIPT = String.raw` @@ -443,6 +447,7 @@ function receiveSlackSocketEvent() { const host = "host.openshell.internal"; const port = parseFakeSlackPort("FAKE_SLACK_WEBSOCKET_PORT"); const proxy = parseProxyTarget(); + const appToken = parseManagedCredentialReference("SLACK_APP_TOKEN"); return new Promise((resolve, reject) => { const socket = proxy ? net.createConnection({ host: proxy.host, port: proxy.port }) : net.createConnection({ host, port }); const timer = setTimeout(() => { socket.destroy(); reject(new Error("timed out waiting for fake Slack Socket Mode event")); }, 30000); @@ -476,7 +481,7 @@ function receiveSlackSocketEvent() { } upgraded = true; framed = Buffer.concat([framed, handshake.slice(end + 4)]); - socket.write(encodeClientText(JSON.stringify({ type: "socket_mode_client_hello", token: "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN" }))); + socket.write(encodeClientText(JSON.stringify({ type: "socket_mode_client_hello", token: appToken }))); } else { framed = Buffer.concat([framed, chunk]); } @@ -486,7 +491,6 @@ function receiveSlackSocketEvent() { framed = framed.slice(frame.totalLength); if (frame.opcode !== 1) continue; const envelope = JSON.parse(frame.payload.toString("utf8")); - if (envelope.type === "hello") continue; socket.write(encodeClientText(JSON.stringify({ envelope_id: envelope.envelope_id }))); clearTimeout(timer); socket.end(); @@ -501,7 +505,7 @@ function receiveSlackSocketEvent() { function postPairingReply(text, channel) { const host = "host.openshell.internal"; const port = parseFakeSlackPort(); - const token = "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN"; + const token = parseManagedCredentialReference("SLACK_BOT_TOKEN"); const data = new URLSearchParams({ token, channel, text }).toString(); return new Promise((resolve, reject) => { const req = http.request({ diff --git a/test/e2e/support/openclaw-discord-pairing-helpers.test.ts b/test/e2e/support/openclaw-discord-pairing-helpers.test.ts index b743fffb415..6550cebc123 100644 --- a/test/e2e/support/openclaw-discord-pairing-helpers.test.ts +++ b/test/e2e/support/openclaw-discord-pairing-helpers.test.ts @@ -299,6 +299,41 @@ describe("OpenClaw Discord pairing helper contracts", () => { ); }); + it("uses the revision-scoped Slack credential references issued to the sandbox", () => { + expect(SLACK_PAIRING_SCRIPT).toContain( + 'parseManagedCredentialReference("SLACK_APP_TOKEN")', + ); + expect(SLACK_PAIRING_SCRIPT).toContain( + 'parseManagedCredentialReference("SLACK_BOT_TOKEN")', + ); + expect(SLACK_PAIRING_SCRIPT).not.toContain( + "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN", + ); + expect(SLACK_PAIRING_SCRIPT).not.toContain( + "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", + ); + }); + + it.each([ + { name: "missing", value: "" }, + { name: "unscoped", value: "openshell:resolve:env:SLACK_APP_TOKEN" }, + { name: "wrong credential", value: "openshell:resolve:env:v2_SLACK_BOT_TOKEN" }, + { name: "raw token", value: "xapp-raw-slack-token" }, + ])("rejects a $name Slack app credential before network access", ({ value }) => { + const result = spawnSync(process.execPath, ["--input-type=module"], { + input: `${SLACK_PROBE_INPUT_VALIDATION_SOURCE}\nlet networkAttempted = false;\ntry { parseManagedCredentialReference("SLACK_APP_TOKEN"); networkAttempted = true; } catch (error) { console.error(error.message); console.error("NETWORK_ATTEMPTED=" + networkAttempted); process.exit(1); }\n`, + encoding: "utf8", + env: { ...process.env, SLACK_APP_TOKEN: value }, + }); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain( + "SLACK_APP_TOKEN must be the revision-scoped OpenShell credential reference", + ); + expect(result.stderr).toContain("NETWORK_ATTEMPTED=false"); + expect(result.stderr).not.toContain("xapp-raw-slack-token"); + }); + it("sends the revision-scoped Discord placeholder through the shared gateway client (#10155)", async () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "discord-gateway-proof-revision-")); const captureFile = path.join(tmp, "capture.jsonl"); From 834a1d0ac55b7ca08c391f69934ec068aa4e382e Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 25 Aug 2026 22:30:58 -0700 Subject: [PATCH 13/13] ci(e2e): pin scoped Slack candidate Signed-off-by: Aaron Erickson --- .github/workflows/e2e.yaml | 8 ++++---- tools/e2e/workflow-boundary.mts | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index f3740ea18ff..a88f240f9d2 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -575,7 +575,7 @@ jobs: fi - name: Assemble exact 7eccb19 managed-image catalog - if: ${{ inputs.checkout_sha == '033f1218472e6a02b02a6948126dd59e7d259df8' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} + if: ${{ inputs.checkout_sha == 'ad7af27ec78d6222ceb7d3223e643adcdc2a6adf' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} env: GITHUB_TOKEN: ${{ github.token }} shell: bash @@ -627,14 +627,14 @@ jobs: "$contracts/langchain-deepagents-code/contract.json" catalog="${RUNNER_TEMP}/pr-managed-image-catalog.json" jq \ - --arg release 'v0.0.114-130-g033f12184' \ - --arg revision '033f1218472e6a02b02a6948126dd59e7d259df8' ' + --arg release 'v0.0.114-132-gad7af27ec' \ + --arg revision 'ad7af27ec78d6222ceb7d3223e643adcdc2a6adf' ' with_entries(.value.source.revision = $revision | .value.source.release = $release) ' "$catalog" >"$catalog.next" mv "$catalog.next" "$catalog" - name: Resolve exact PR managed-image catalog - if: ${{ inputs.checkout_sha != '' && inputs.checkout_sha != '033f1218472e6a02b02a6948126dd59e7d259df8' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} + if: ${{ inputs.checkout_sha != '' && inputs.checkout_sha != 'ad7af27ec78d6222ceb7d3223e643adcdc2a6adf' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }} env: BASE_SHA: ${{ inputs.base_sha }} CANDIDATE_REPOSITORY: ${{ inputs.checkout_repository }} diff --git a/tools/e2e/workflow-boundary.mts b/tools/e2e/workflow-boundary.mts index 614bef89119..47e772b2f24 100644 --- a/tools/e2e/workflow-boundary.mts +++ b/tools/e2e/workflow-boundary.mts @@ -2590,7 +2590,7 @@ function validateExactPrManagedImageCatalogBoundary( ); if ( managedCatalog?.if !== - "${{ inputs.checkout_sha != '' && inputs.checkout_sha != '033f1218472e6a02b02a6948126dd59e7d259df8' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || + "${{ inputs.checkout_sha != '' && inputs.checkout_sha != 'ad7af27ec78d6222ceb7d3223e643adcdc2a6adf' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || !isDeepStrictEqual(asRecord(managedCatalog?.env), { BASE_SHA: "${{ inputs.base_sha }}", CANDIDATE_REPOSITORY: "${{ inputs.checkout_repository }}", @@ -2610,7 +2610,7 @@ function validateExactPrManagedImageCatalogBoundary( ); if ( reusedManagedCatalog?.if !== - "${{ inputs.checkout_sha == '033f1218472e6a02b02a6948126dd59e7d259df8' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || + "${{ inputs.checkout_sha == 'ad7af27ec78d6222ceb7d3223e643adcdc2a6adf' && (inputs.jobs != 'native-runtime-qualification-producer' || inputs.targets != '') }}" || !stringValue(reusedManagedCatalog?.run).includes( "managed-pr-contract-${expected.runId}-${expected.runAttempt}-${agent}", ) ||