From 59972b1df938f11c4ef20a3d89f66120b98b2a82 Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 23 Jun 2026 00:16:20 +0700 Subject: [PATCH 01/12] feat(messaging): onboard Mattermost for OpenClaw --- agents/openclaw/manifest.yaml | 1 + ci/test-file-size-budget.json | 2 +- .../policies/templates/mattermost.yaml | 37 +++ src/lib/actions/sandbox/policy-channel.ts | 60 +++-- src/lib/agent/defs.test.ts | 1 + src/lib/messaging-channel-config.test.ts | 10 + .../messaging/applier/host-state-applier.ts | 5 + src/lib/messaging/applier/policy.ts | 26 +- .../messaging/applier/setup-applier.test.ts | 44 ++++ src/lib/messaging/applier/types.ts | 7 + src/lib/messaging/channels/built-ins.ts | 3 + src/lib/messaging/channels/manifests.test.ts | 129 ++++++++++ .../channels/mattermost/hooks/index.ts | 4 + .../mattermost/hooks/reachability.test.ts | 164 +++++++++++++ .../channels/mattermost/hooks/reachability.ts | 197 +++++++++++++++ .../messaging/channels/mattermost/manifest.ts | 215 ++++++++++++++++ .../mattermost/template-resolver.test.ts | 83 +++++++ .../channels/mattermost/template-resolver.ts | 103 ++++++++ src/lib/messaging/channels/metadata.test.ts | 12 + src/lib/messaging/channels/metadata.ts | 2 +- .../messaging/channels/template-resolver.ts | 2 + .../compiler/engines/policy-resolver.ts | 15 ++ .../engines/policy-template-renderer.test.ts | 101 ++++++++ .../engines/policy-template-renderer.ts | 231 ++++++++++++++++++ .../compiler/manifest-compiler.test.ts | 127 ++++++++-- .../messaging/compiler/manifest-compiler.ts | 2 +- .../messaging/compiler/workflow-planner.ts | 9 + src/lib/messaging/diagnostics.test.ts | 5 + src/lib/messaging/diagnostics.ts | 19 +- src/lib/messaging/hooks/builtins.ts | 6 + src/lib/messaging/hooks/hook-runner.test.ts | 1 + src/lib/messaging/manifest/types.ts | 22 ++ src/lib/messaging/persistence.ts | 2 +- src/lib/onboard.ts | 17 +- src/lib/onboard/messaging-policy-templates.ts | 42 ++++ src/lib/onboard/messaging-prep.test.ts | 1 + src/lib/sandbox/channels.test.ts | 38 ++- test/channels-add-generated-policy.test.ts | 196 +++++++++++++++ test/channels-add-preset.test.ts | 41 +--- test/sandbox-provider-cleanup.test.ts | 1 + 40 files changed, 1899 insertions(+), 84 deletions(-) create mode 100644 nemoclaw-blueprint/policies/templates/mattermost.yaml create mode 100644 src/lib/messaging/channels/mattermost/hooks/index.ts create mode 100644 src/lib/messaging/channels/mattermost/hooks/reachability.test.ts create mode 100644 src/lib/messaging/channels/mattermost/hooks/reachability.ts create mode 100644 src/lib/messaging/channels/mattermost/manifest.ts create mode 100644 src/lib/messaging/channels/mattermost/template-resolver.test.ts create mode 100644 src/lib/messaging/channels/mattermost/template-resolver.ts create mode 100644 src/lib/messaging/compiler/engines/policy-template-renderer.test.ts create mode 100644 src/lib/messaging/compiler/engines/policy-template-renderer.ts create mode 100644 src/lib/onboard/messaging-policy-templates.ts create mode 100644 test/channels-add-generated-policy.test.ts diff --git a/agents/openclaw/manifest.yaml b/agents/openclaw/manifest.yaml index 4660213dcdf..ba98337f786 100644 --- a/agents/openclaw/manifest.yaml +++ b/agents/openclaw/manifest.yaml @@ -80,6 +80,7 @@ messaging_platforms: - slack - wechat - whatsapp + - mattermost # ── Inference ─────────────────────────────────────────────────── inference: diff --git a/ci/test-file-size-budget.json b/ci/test-file-size-budget.json index 9071c1bae1c..31dc66b6123 100644 --- a/ci/test-file-size-budget.json +++ b/ci/test-file-size-budget.json @@ -5,7 +5,7 @@ "nemoclaw/src/commands/migration-state.test.ts": 1566, "src/lib/inference/nim.test.ts": 2068, "src/lib/onboard/preflight.test.ts": 1905, - "test/channels-add-preset.test.ts": 1871, + "test/channels-add-preset.test.ts": 1838, "test/generate-openclaw-config.test.ts": 1984, "test/install-preflight.test.ts": 4207, "test/nemoclaw-start.test.ts": 5160, diff --git a/nemoclaw-blueprint/policies/templates/mattermost.yaml b/nemoclaw-blueprint/policies/templates/mattermost.yaml new file mode 100644 index 00000000000..1550d3e3dc1 --- /dev/null +++ b/nemoclaw-blueprint/policies/templates/mattermost.yaml @@ -0,0 +1,37 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +preset: + name: mattermost + description: "Mattermost self-hosted API and WebSocket access" + template: + sourceType: http-url + +network_policies: + mattermost: + name: mattermost + endpoints: + # Mattermost serves REST and WebSocket traffic from the same self-hosted + # host:port. Keep them on one inspected endpoint so policy matching does + # not collapse duplicate endpoint keys while credential rewrite still + # resolves the bot-token placeholder before egress. + - host: "{{url.host}}" + port: "{{url.port}}" + protocol: rest + enforcement: enforce + request_body_credential_rewrite: true + websocket_credential_rewrite: true + allowed_ips: + - 10.0.0.0/8 + - 172.16.0.0/12 + - 192.168.0.0/16 + rules: + - allow: { method: GET, path: "{{url.basePath}}/api/v4/websocket" } + - allow: { method: WEBSOCKET_TEXT, path: "{{url.basePath}}/api/v4/websocket" } + - allow: { method: GET, path: "{{url.basePath}}/api/v4/**" } + - allow: { method: POST, path: "{{url.basePath}}/api/v4/**" } + - allow: { method: PUT, path: "{{url.basePath}}/api/v4/**" } + - allow: { method: PATCH, path: "{{url.basePath}}/api/v4/**" } + - allow: { method: DELETE, path: "{{url.basePath}}/api/v4/**" } + binaries: + - path: "{{agent.binaries}}" diff --git a/src/lib/actions/sandbox/policy-channel.ts b/src/lib/actions/sandbox/policy-channel.ts index 09aa5bc42b8..e70c307779c 100644 --- a/src/lib/actions/sandbox/policy-channel.ts +++ b/src/lib/actions/sandbox/policy-channel.ts @@ -33,6 +33,7 @@ const onboardProviders = require("../../onboard/providers"); import { filterSetupPolicyPresetsForAgent } from "../../onboard/agent-policy-presets"; import { getStoredMessagingChannelConfig } from "../../onboard/messaging-config"; +import { applyGeneratedMessagingPolicyTemplates } from "../../onboard/messaging-policy-templates"; import * as policies from "../../policy"; const onboardSession = @@ -908,19 +909,21 @@ export async function addSandboxChannel( process.exit(1); } - const presetContent = policies.loadPreset(canonical); - const presetPolicyKeys = - presetContent === null ? [] : policies.parsePresetPolicyKeys(presetContent); - if (presetContent === null || presetPolicyKeys.length === 0) { - if (presetContent !== null && presetPolicyKeys.length === 0) { + for (const presetName of manifestPolicyPresetNames(manifest)) { + const presetContent = policies.loadPreset(presetName); + const presetPolicyKeys = + presetContent === null ? [] : policies.parsePresetPolicyKeys(presetContent); + if (presetContent === null || presetPolicyKeys.length === 0) { + if (presetContent !== null && presetPolicyKeys.length === 0) { + console.error( + ` Preset YAML for channel '${canonical}' has no parseable entries under 'network_policies:'.`, + ); + } console.error( - ` Preset YAML for channel '${canonical}' has no parseable entries under 'network_policies:'.`, + ` Restore the preset YAML and re-run: ${CLI_NAME} ${sandboxName} channels add ${canonical}`, ); + process.exit(1); } - console.error( - ` Restore the preset YAML and re-run: ${CLI_NAME} ${sandboxName} channels add ${canonical}`, - ); - process.exit(1); } if (dryRun) { @@ -944,7 +947,7 @@ export async function addSandboxChannel( // host-side credential to acquire; register the bridge now and let the // operator complete pairing after rebuild. if (manifest.auth.mode === "in-sandbox-qr") { - if (!applyChannelPresetIfAvailable(sandboxName, canonical)) { + if (!applyChannelPolicyIfAvailable(sandboxName, canonical, plan)) { process.exit(1); } await applyChannelAddToGatewayAndRegistry(sandboxName, canonical, {}); @@ -993,7 +996,7 @@ export async function addSandboxChannel( await applyChannelAddToGatewayAndRegistry(sandboxName, canonical, acquired); console.log(` ${G}✓${R} Registered ${canonical} bridge with the OpenShell gateway.`); - if (!applyChannelPresetIfAvailable(sandboxName, canonical)) { + if (!applyChannelPolicyIfAvailable(sandboxName, canonical, plan)) { await rollbackChannelAdd(sandboxName, channelDef, canonical, { wasAlreadyEnabled, priorCreds, @@ -1073,6 +1076,12 @@ async function rollbackChannelAdd( return result; } +function manifestPolicyPresetNames(manifest: ChannelManifest): string[] { + return (manifest.policyPresets ?? []).map((preset) => + typeof preset === "string" ? preset : preset.name, + ); +} + export function applyChannelPresetIfAvailable(sandboxName: string, channelName: string): boolean { try { const applied = policies.applyPreset(sandboxName, channelName); @@ -1098,6 +1107,28 @@ export function applyChannelPresetIfAvailable(sandboxName: string, channelName: } } +export function applyChannelPolicyIfAvailable( + sandboxName: string, + channelName: string, + plan: SandboxMessagingPlan, +): boolean { + try { + const appliedGenerated = applyGeneratedMessagingPolicyTemplates(sandboxName, plan, { + channelId: channelName, + }); + if (appliedGenerated.length > 0) { + refreshSandboxPolicyContextFile(sandboxName); + return true; + } + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + console.error(` ${YW}⚠${R} Failed to apply generated '${channelName}' policy: ${msg}`); + return false; + } + + return applyChannelPresetIfAvailable(sandboxName, channelName); +} + function getSandboxChannelStatePaths(agent: AgentDefinition, channelName: string): string[] { const configDir = agent.configPaths.dir; const stateDirs = new Set(agent.stateDirs); @@ -1206,11 +1237,6 @@ function syncSessionPolicyPresetsWithRegistry( // not abort the remove flow — the bridge teardown has already succeeded; // the operator can run `policy-remove ` manually if cleanup falters. export function removeChannelPresetIfPresent(sandboxName: string, channelName: string): void { - const builtinPresets = new Set(policies.listPresets().map((p) => p.name)); - if (!builtinPresets.has(channelName)) { - syncSessionPolicyPresetsWithRegistry(sandboxName, channelName, "remove"); - return; - } if (!policies.getAppliedPresets(sandboxName).includes(channelName)) { syncSessionPolicyPresetsWithRegistry(sandboxName, channelName, "remove"); return; diff --git a/src/lib/agent/defs.test.ts b/src/lib/agent/defs.test.ts index 6fcb2557fd1..03143342f1f 100644 --- a/src/lib/agent/defs.test.ts +++ b/src/lib/agent/defs.test.ts @@ -53,6 +53,7 @@ describe("agent definitions", () => { "slack", "wechat", "whatsapp", + "mattermost", ]); expect(openclaw.inferenceProviderOptions).toEqual([]); // #5027: openclaw.json must be declared as a durable state file so diff --git a/src/lib/messaging-channel-config.test.ts b/src/lib/messaging-channel-config.test.ts index 2d1cb5a05d0..40b4ddfca97 100644 --- a/src/lib/messaging-channel-config.test.ts +++ b/src/lib/messaging-channel-config.test.ts @@ -22,10 +22,14 @@ describe("messaging channel config", () => { "SLACK_ALLOWED_USERS", "SLACK_ALLOWED_CHANNELS", "WHATSAPP_ALLOWED_IDS", + "MATTERMOST_ALLOWED_USERS", + "MATTERMOST_ALLOWED_CHANNELS", + "MATTERMOST_REQUIRE_MENTION", "TELEGRAM_GROUP_POLICY", "WECHAT_ACCOUNT_ID", "WECHAT_BASE_URL", "WECHAT_USER_ID", + "MATTERMOST_URL", ]); }); @@ -40,6 +44,9 @@ describe("messaging channel config", () => { DISCORD_REQUIRE_MENTION: "0", SLACK_ALLOWED_USERS: " U01ABC2DEF3, U04GHI5JKL6 ", SLACK_ALLOWED_CHANNELS: " C012AB3CD, C987ZY6XW ", + MATTERMOST_URL: " https://mattermost.com ", + MATTERMOST_ALLOWED_CHANNELS: " town-square, ops ", + MATTERMOST_REQUIRE_MENTION: "1", NVIDIA_INFERENCE_API_KEY: "not-channel-config", }), ).toEqual({ @@ -49,6 +56,9 @@ describe("messaging channel config", () => { DISCORD_REQUIRE_MENTION: "0", SLACK_ALLOWED_USERS: "U01ABC2DEF3, U04GHI5JKL6", SLACK_ALLOWED_CHANNELS: "C012AB3CD, C987ZY6XW", + MATTERMOST_URL: "https://mattermost.com", + MATTERMOST_ALLOWED_CHANNELS: "town-square, ops", + MATTERMOST_REQUIRE_MENTION: "1", }); }); diff --git a/src/lib/messaging/applier/host-state-applier.ts b/src/lib/messaging/applier/host-state-applier.ts index b930f368217..2c08c93a250 100644 --- a/src/lib/messaging/applier/host-state-applier.ts +++ b/src/lib/messaging/applier/host-state-applier.ts @@ -95,6 +95,10 @@ function mergeSandboxMessagingPlans( existing.networkPolicy.entries, incoming.networkPolicy.entries, ); + const networkTemplates = mergeByChannelId( + existing.networkPolicy.templates ?? [], + incoming.networkPolicy.templates ?? [], + ); return clonePlan({ ...incoming, @@ -104,6 +108,7 @@ function mergeSandboxMessagingPlans( networkPolicy: { presets: uniqueStrings(networkEntries.map((entry) => entry.presetName)), entries: networkEntries, + ...(networkTemplates.length > 0 ? { templates: networkTemplates } : {}), }, agentRender: mergeByChannelId(existing.agentRender, incoming.agentRender), buildSteps: mergeByChannelId(existing.buildSteps, incoming.buildSteps), diff --git a/src/lib/messaging/applier/policy.ts b/src/lib/messaging/applier/policy.ts index 103b6be1d27..a98c4923e3f 100644 --- a/src/lib/messaging/applier/policy.ts +++ b/src/lib/messaging/applier/policy.ts @@ -10,8 +10,13 @@ export function applyPolicyAtOpenShell( options: MessagingPolicyApplyOptions, ): MessagingPolicyApplyResult { const activeEntries = filterEnabledPlanEntries(plan, plan.networkPolicy.entries); + const activeTemplates = filterEnabledPlanEntries(plan, plan.networkPolicy.templates ?? []); const activePresets = uniqueStrings(activeEntries.map((entry) => entry.presetName)); - const activePolicyKeys = uniqueStrings(activeEntries.flatMap((entry) => entry.policyKeys)); + const activeTemplatePresets = uniqueStrings(activeTemplates.map((entry) => entry.presetName)); + const activePolicyKeys = uniqueStrings([ + ...activeEntries.flatMap((entry) => entry.policyKeys), + ...activeTemplates.flatMap((entry) => entry.policyKeys), + ]); if ( activePresets.length > 0 && !options.applyPresets(plan.sandboxName, activePresets, { @@ -23,9 +28,28 @@ export function applyPolicyAtOpenShell( throw new Error(`Failed to apply messaging policy preset(s): ${activePresets.join(", ")}`); } + if (activeTemplates.length > 0 && !options.applyPresetContent) { + throw new Error( + `Cannot apply generated messaging policy template(s): ${activeTemplatePresets.join(", ")}`, + ); + } + + for (const template of activeTemplates) { + if ( + !options.applyPresetContent?.(plan.sandboxName, template.presetName, template.content, { + agent: plan.agent, + entries: activeEntries, + policyKeys: activePolicyKeys, + }) + ) { + throw new Error(`Failed to apply generated messaging policy: ${template.presetName}`); + } + } + return { appliedPresets: activePresets, appliedPolicyKeys: activePolicyKeys, + ...(activeTemplatePresets.length > 0 ? { appliedTemplatePresets: activeTemplatePresets } : {}), }; } diff --git a/src/lib/messaging/applier/setup-applier.test.ts b/src/lib/messaging/applier/setup-applier.test.ts index 248e80688ca..8f0d5eef4aa 100644 --- a/src/lib/messaging/applier/setup-applier.test.ts +++ b/src/lib/messaging/applier/setup-applier.test.ts @@ -28,6 +28,7 @@ const TEST_CREDENTIALS: Readonly> = { WECHAT_BOT_TOKEN: "test-wechat-token", SLACK_BOT_TOKEN: "xoxb-test-slack-token", SLACK_APP_TOKEN: "xapp-test-slack-token", + MATTERMOST_BOT_TOKEN: "test-mattermost-token", }; async function withEnv( @@ -36,6 +37,7 @@ async function withEnv( ): Promise { const scopedValues = { NEMOCLAW_SKIP_TELEGRAM_REACHABILITY: "1", + NEMOCLAW_SKIP_MATTERMOST_AUTH_VALIDATION: "1", ...values, }; const previous = Object.fromEntries( @@ -804,6 +806,48 @@ describe("MessagingSetupApplier", () => { }); }); + it("applies generated policy template content directly from the serializable plan", async () => { + const plan = await buildOnboardPlan( + { + MATTERMOST_BOT_TOKEN: "test-mattermost-token", + MATTERMOST_URL: "https://chat.example.com/team", + }, + ["mattermost"], + ); + const presetCalls: string[][] = []; + const contentCalls: string[][] = []; + + const result = MessagingSetupApplier.applyPolicyAtOpenShell(plan, { + applyPresets: (sandboxName, presetNames) => { + presetCalls.push([sandboxName, ...presetNames]); + return true; + }, + applyPresetContent: (sandboxName, presetName, content, context) => { + contentCalls.push([sandboxName, presetName, content]); + expect(context.policyKeys).toEqual(["mattermost"]); + return true; + }, + }); + + expect(presetCalls).toEqual([]); + expect(contentCalls).toHaveLength(1); + expect(contentCalls[0][0]).toBe("demo"); + expect(contentCalls[0][1]).toBe("mattermost"); + expect(contentCalls[0][2]).toContain("chat.example.com"); + expect(contentCalls[0][2]).toContain("protocol: rest"); + expect(contentCalls[0][2]).toContain("request_body_credential_rewrite: true"); + expect(contentCalls[0][2]).toContain("websocket_credential_rewrite: true"); + expect(contentCalls[0][2]).toContain("path: /team/api/v4/**"); + expect(contentCalls[0][2]).toContain("method: WEBSOCKET_TEXT"); + expect(contentCalls[0][2]).not.toContain("access: full"); + expect(contentCalls[0][2]).not.toContain("tls: skip"); + expect(result).toEqual({ + appliedPresets: [], + appliedPolicyKeys: ["mattermost"], + appliedTemplatePresets: ["mattermost"], + }); + }); + it("passes concrete policy keys for agent-aware preset application", async () => { const plan = await buildOnboardPlan( { diff --git a/src/lib/messaging/applier/types.ts b/src/lib/messaging/applier/types.ts index 70e6a77be43..d96634c626b 100644 --- a/src/lib/messaging/applier/types.ts +++ b/src/lib/messaging/applier/types.ts @@ -103,11 +103,18 @@ export interface MessagingPolicyApplyOptions { presetNames: string[], context: MessagingPolicyApplyContext, ) => boolean; + readonly applyPresetContent?: ( + sandboxName: string, + presetName: string, + presetContent: string, + context: MessagingPolicyApplyContext, + ) => boolean; } export interface MessagingPolicyApplyResult { readonly appliedPresets: readonly string[]; readonly appliedPolicyKeys: readonly string[]; + readonly appliedTemplatePresets?: readonly string[]; } export type MessagingSerializablePlan = SandboxMessagingPlan; diff --git a/src/lib/messaging/channels/built-ins.ts b/src/lib/messaging/channels/built-ins.ts index 441e224122b..359d6707afb 100644 --- a/src/lib/messaging/channels/built-ins.ts +++ b/src/lib/messaging/channels/built-ins.ts @@ -4,12 +4,14 @@ import type { ChannelManifestRegistry } from "../manifest"; import { createChannelManifestRegistry } from "../manifest"; import { discordManifest } from "./discord/manifest"; +import { mattermostManifest } from "./mattermost/manifest"; import { slackManifest } from "./slack/manifest"; import { telegramManifest } from "./telegram/manifest"; import { wechatManifest } from "./wechat/manifest"; import { whatsappManifest } from "./whatsapp/manifest"; export { discordManifest } from "./discord/manifest"; +export { mattermostManifest } from "./mattermost/manifest"; export { slackManifest } from "./slack/manifest"; export { telegramManifest } from "./telegram/manifest"; export { wechatManifest } from "./wechat/manifest"; @@ -21,6 +23,7 @@ export const BUILT_IN_CHANNEL_MANIFESTS = [ wechatManifest, slackManifest, whatsappManifest, + mattermostManifest, ] as const; export function createBuiltInChannelManifestRegistry(): ChannelManifestRegistry { diff --git a/src/lib/messaging/channels/manifests.test.ts b/src/lib/messaging/channels/manifests.test.ts index 9654133aabd..db0d10af4be 100644 --- a/src/lib/messaging/channels/manifests.test.ts +++ b/src/lib/messaging/channels/manifests.test.ts @@ -20,11 +20,13 @@ import { BUILT_IN_CHANNEL_MANIFESTS, createBuiltInChannelManifestRegistry, discordManifest, + mattermostManifest, slackManifest, telegramManifest, wechatManifest, whatsappManifest, } from "./index"; +import { MATTERMOST_REACHABILITY_HOOK_HANDLER_ID } from "./mattermost/hooks"; import { SLACK_SOCKET_MODE_GATEWAY_CONFLICT_HOOK_HANDLER_ID, SLACK_SOCKET_MODE_GATEWAY_STATUS_HOOK_HANDLER_ID, @@ -78,6 +80,10 @@ function policyPresetNames(manifest: ChannelManifest): string[] { ); } +function policyTemplateNames(manifest: ChannelManifest): string[] { + return (manifest.policyTemplates ?? []).map((template) => template.name); +} + function expectTokenPasteEnrollHook(manifest: ChannelManifest, outputIds: readonly string[]): void { expect(manifest.hooks).toContainEqual({ id: `${manifest.id}-token-paste`, @@ -202,6 +208,7 @@ describe("built-in channel manifests", () => { "wechat", "slack", "whatsapp", + "mattermost", ]); expect(registry.listAvailable({ agent: "hermes" }).map((manifest) => manifest.id)).toEqual([ "telegram", @@ -238,6 +245,8 @@ describe("built-in channel manifests", () => { "src/lib/messaging/channels/slack/hooks/socket-mode-gateway-status.ts", "src/lib/messaging/channels/slack/hooks/validate-credentials.ts", "src/lib/messaging/channels/whatsapp/manifest.ts", + "src/lib/messaging/channels/mattermost/manifest.ts", + "src/lib/messaging/channels/mattermost/hooks/reachability.ts", "src/lib/messaging/hooks/common/config-prompt.ts", "src/lib/messaging/hooks/common/token-paste.ts", ]; @@ -298,6 +307,10 @@ describe("built-in channel manifests", () => { label: KNOWN_CHANNELS.wechat.label, help: KNOWN_CHANNELS.wechat.help, }); + expect(findInput(mattermostManifest, "botToken").prompt).toEqual({ + label: KNOWN_CHANNELS.mattermost.label, + help: KNOWN_CHANNELS.mattermost.help, + }); }); it("declares Telegram env keys, policy, and OpenClaw/Hermes render intent", () => { @@ -649,4 +662,120 @@ describe("built-in channel manifests", () => { expect(JSON.stringify(whatsappManifest.runtime?.openclaw)).toContain("whatsapp-qr-compact"); expectOpenClawRuntimeVisibility(whatsappManifest, ["whatsapp"], ["whatsapp"]); }); + + it("declares Mattermost token, server URL, allowlist, and render intent", () => { + const botToken = findInput(mattermostManifest, "botToken"); + const baseUrl = findInput(mattermostManifest, "baseUrl"); + const allowedUsers = findInput(mattermostManifest, "allowedUsers"); + const allowedChannels = findInput(mattermostManifest, "allowedChannels"); + const requireMention = findInput(mattermostManifest, "requireMention"); + + expect(getChannelTokenKeys(KNOWN_CHANNELS.mattermost)).toEqual(["MATTERMOST_BOT_TOKEN"]); + expect(botToken.envKey).toBe("MATTERMOST_BOT_TOKEN"); + expect(baseUrl).toMatchObject({ + kind: "config", + envKey: "MATTERMOST_URL", + statePath: "mattermostConfig.baseUrl", + }); + expect(new RegExp(baseUrl.formatPattern ?? "").test("https://chat.example.com")).toBe(true); + expect(new RegExp(baseUrl.formatPattern ?? "").test("http://chat.example.com")).toBe(true); + expect(new RegExp(baseUrl.formatPattern ?? "").test("http://192.0.2.10:8065")).toBe(true); + expect(new RegExp(baseUrl.formatPattern ?? "").test("ftp://chat.example.com")).toBe(false); + expect(allowedUsers).toMatchObject({ + kind: "config", + envKey: "MATTERMOST_ALLOWED_USERS", + statePath: "allowedIds.mattermost", + }); + expect(allowedChannels).toMatchObject({ + kind: "config", + envKey: "MATTERMOST_ALLOWED_CHANNELS", + statePath: "mattermostConfig.allowedChannels", + }); + expect(requireMention).toMatchObject({ + kind: "config", + envKey: "MATTERMOST_REQUIRE_MENTION", + defaultValue: "1", + validValues: ["0", "1"], + }); + expect(KNOWN_CHANNELS.mattermost.allowIdsMode).toBe("dm"); + expect(KNOWN_CHANNELS.mattermost.channelIdEnvKey).toBe("MATTERMOST_ALLOWED_CHANNELS"); + expect(KNOWN_CHANNELS.mattermost.requireMentionEnvKey).toBe("MATTERMOST_REQUIRE_MENTION"); + expect(mattermostManifest.credentials).toEqual([ + { + id: "mattermostBotToken", + sourceInput: "botToken", + providerName: "{sandboxName}-mattermost-bridge", + providerEnvKey: "MATTERMOST_BOT_TOKEN", + placeholder: "openshell:resolve:env:MATTERMOST_BOT_TOKEN", + }, + ]); + expect(policyPresetNames(mattermostManifest)).toEqual([]); + expect(policyTemplateNames(mattermostManifest)).toEqual(["mattermost"]); + expect(mattermostManifest.policyTemplates).toEqual([ + { + name: "mattermost", + templateFile: "mattermost.yaml", + sourceInput: "baseUrl", + sourceType: "http-url", + binariesByAgent: { + openclaw: ["/usr/local/bin/node", "/usr/bin/node"], + }, + }, + ]); + expect(renderJson(mattermostManifest)).toContain('"path":"channels.mattermost"'); + expect(renderJson(mattermostManifest)).toContain("mattermostConfig.baseUrl"); + expect(renderJson(mattermostManifest)).toContain("allowedIds.mattermost"); + expect(renderJson(mattermostManifest)).toContain("mattermostConfig.openclawGroups"); + expect(findRender(mattermostManifest, "mattermost-openclaw-channel")).toMatchObject({ + fragment: { + value: { + network: { + dangerouslyAllowPrivateNetwork: true, + }, + }, + }, + }); + expect(renderJson(mattermostManifest)).not.toContain('"path":"mattermost"'); + expect(renderJson(mattermostManifest)).not.toContain('"path":"platforms.mattermost"'); + expect("agentPackages" in mattermostManifest).toBe(false); + expectTokenPasteEnrollHook(mattermostManifest, ["botToken"]); + expectConfigPromptEnrollHook(mattermostManifest, [ + "baseUrl", + "allowedUsers", + "allowedChannels", + "requireMention", + ]); + expect(mattermostManifest.hooks).toContainEqual({ + id: "mattermost-reachability", + phase: "reachability-check", + handler: MATTERMOST_REACHABILITY_HOOK_HANDLER_ID, + inputs: ["botToken", "baseUrl"], + onFailure: "skip-channel", + }); + expectOpenClawRuntimeVisibility(mattermostManifest, ["mattermost"], ["mattermost"]); + expect(mattermostManifest.state).toEqual({ + persist: { + mattermostConfig: ["baseUrl", "allowedChannels", "requireMention"], + allowedIds: ["allowedUsers"], + }, + rebuildHydration: [ + { + statePath: "mattermostConfig.baseUrl", + env: "MATTERMOST_URL", + }, + { + statePath: "allowedIds.mattermost", + env: "MATTERMOST_ALLOWED_USERS", + }, + { + statePath: "mattermostConfig.allowedChannels", + env: "MATTERMOST_ALLOWED_CHANNELS", + }, + { + statePath: "mattermostConfig.requireMention", + env: "MATTERMOST_REQUIRE_MENTION", + }, + ], + }); + }); }); diff --git a/src/lib/messaging/channels/mattermost/hooks/index.ts b/src/lib/messaging/channels/mattermost/hooks/index.ts new file mode 100644 index 00000000000..a51672dce77 --- /dev/null +++ b/src/lib/messaging/channels/mattermost/hooks/index.ts @@ -0,0 +1,4 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export * from "./reachability"; diff --git a/src/lib/messaging/channels/mattermost/hooks/reachability.test.ts b/src/lib/messaging/channels/mattermost/hooks/reachability.test.ts new file mode 100644 index 00000000000..6b2c86f108c --- /dev/null +++ b/src/lib/messaging/channels/mattermost/hooks/reachability.test.ts @@ -0,0 +1,164 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; + +import { MessagingHookRegistry, runMessagingHook } from "../../../hooks"; +import type { ChannelHookSpec } from "../../../manifest"; +import { + createMattermostReachabilityHook, + MATTERMOST_AUTH_VALIDATION_SKIP_ENV, + MATTERMOST_REACHABILITY_HOOK_HANDLER_ID, +} from "./reachability"; + +const MATTERMOST_REACHABILITY_HOOK = { + id: "mattermost-reachability", + phase: "reachability-check", + handler: MATTERMOST_REACHABILITY_HOOK_HANDLER_ID, + inputs: ["botToken", "baseUrl"], + onFailure: "skip-channel", +} as const satisfies ChannelHookSpec; + +describe("Mattermost reachability hook implementation", () => { + it("calls Mattermost /users/me with a bearer token without exposing secrets in outputs", async () => { + const calls: Array<{ url: string; authorization: string | undefined }> = []; + const registry = new MessagingHookRegistry([ + { + id: MATTERMOST_REACHABILITY_HOOK_HANDLER_ID, + handler: createMattermostReachabilityHook({ + fetch: async (url, options) => { + calls.push({ url, authorization: options?.headers?.Authorization }); + return { + ok: true, + status: 200, + async json() { + return { id: "bot-user-id" }; + }, + async text() { + return ""; + }, + }; + }, + }), + }, + ]); + + await expect( + runMessagingHook(MATTERMOST_REACHABILITY_HOOK, registry, { + channelId: "mattermost", + inputs: { + botToken: "mattermost-token", + baseUrl: "https://chat.example.com/api/v4/", + }, + }), + ).resolves.toEqual({ + hookId: "mattermost-reachability", + handlerId: MATTERMOST_REACHABILITY_HOOK_HANDLER_ID, + phase: "reachability-check", + outputs: {}, + }); + expect(calls).toEqual([ + { + url: "https://chat.example.com/api/v4/users/me", + authorization: "Bearer mattermost-token", + }, + ]); + }); + + it("fails so the compiler can skip the channel when Mattermost rejects the token", async () => { + const logs: string[] = []; + const registry = new MessagingHookRegistry([ + { + id: MATTERMOST_REACHABILITY_HOOK_HANDLER_ID, + handler: createMattermostReachabilityHook({ + log: (message) => logs.push(message), + fetch: async () => ({ + ok: false, + status: 401, + statusText: "Unauthorized", + async json() { + return {}; + }, + async text() { + return "unauthorized"; + }, + }), + }), + }, + ]); + + await expect( + runMessagingHook(MATTERMOST_REACHABILITY_HOOK, registry, { + channelId: "mattermost", + inputs: { + botToken: "bad-token", + baseUrl: "https://mattermost.com", + }, + }), + ).rejects.toThrow("Mattermost token was rejected."); + expect(logs).toEqual([ + " ⚠ Mattermost token was rejected — verify the token and bot account status.", + " Mattermost integration will be disabled for this enrollment run because the token was rejected by Mattermost.", + ]); + }); + + it("fails so the compiler can skip the channel when the API is unreachable", async () => { + const logs: string[] = []; + const registry = new MessagingHookRegistry([ + { + id: MATTERMOST_REACHABILITY_HOOK_HANDLER_ID, + handler: createMattermostReachabilityHook({ + log: (message) => logs.push(message), + fetch: async () => { + throw new Error("network unavailable"); + }, + }), + }, + ]); + + await expect( + runMessagingHook(MATTERMOST_REACHABILITY_HOOK, registry, { + channelId: "mattermost", + inputs: { + botToken: "mattermost-token", + baseUrl: "https://mattermost.com", + }, + }), + ).rejects.toThrow("Mattermost API was unreachable."); + expect(logs).toEqual([ + " Mattermost integration will be disabled for this enrollment run because Mattermost API was unreachable: network unavailable.", + ]); + }); + + it("honors the explicit skip env without calling Mattermost", async () => { + const urls: string[] = []; + const registry = new MessagingHookRegistry([ + { + id: MATTERMOST_REACHABILITY_HOOK_HANDLER_ID, + handler: createMattermostReachabilityHook({ + env: { + [MATTERMOST_AUTH_VALIDATION_SKIP_ENV]: "1", + }, + fetch: async (url) => { + urls.push(url); + throw new Error("fetch should not run"); + }, + }), + }, + ]); + + await expect( + runMessagingHook(MATTERMOST_REACHABILITY_HOOK, registry, { + channelId: "mattermost", + inputs: { + botToken: "mattermost-token", + baseUrl: "https://mattermost.com", + }, + }), + ).resolves.toMatchObject({ + hookId: "mattermost-reachability", + outputs: {}, + }); + expect(urls).toEqual([]); + }); +}); diff --git a/src/lib/messaging/channels/mattermost/hooks/reachability.ts b/src/lib/messaging/channels/mattermost/hooks/reachability.ts new file mode 100644 index 00000000000..2557167aacb --- /dev/null +++ b/src/lib/messaging/channels/mattermost/hooks/reachability.ts @@ -0,0 +1,197 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { MessagingHookHandler, MessagingHookRegistration } from "../../../hooks/types"; + +export const MATTERMOST_REACHABILITY_HOOK_HANDLER_ID = "mattermost.reachability"; +export const MATTERMOST_AUTH_VALIDATION_SKIP_ENV = "NEMOCLAW_SKIP_MATTERMOST_AUTH_VALIDATION"; + +const DEFAULT_MATTERMOST_REACHABILITY_TIMEOUT_MS = 10_000; + +interface MattermostFetchResponse { + readonly ok: boolean; + readonly status: number; + readonly statusText?: string; + json(): Promise; + text(): Promise; +} + +interface MattermostFetchOptions { + readonly headers?: Record; + readonly signal?: AbortSignal; +} + +type MattermostFetch = ( + url: string, + options?: MattermostFetchOptions, +) => Promise; + +export interface MattermostReachabilityHookOptions { + readonly env?: NodeJS.ProcessEnv | Record; + readonly fetch?: MattermostFetch; + readonly timeoutMs?: number; + readonly log?: (message: string) => void; +} + +export function createMattermostReachabilityHook( + options: MattermostReachabilityHookOptions = {}, +): MessagingHookHandler { + return async (context) => { + const env = options.env ?? process.env; + if (isTruthyEnvFlag(env[MATTERMOST_AUTH_VALIDATION_SKIP_ENV])) { + return {}; + } + + const token = normalizeInput(context.inputs?.botToken); + const baseUrl = normalizeMattermostBaseUrl(normalizeInput(context.inputs?.baseUrl)); + if (!token) { + throw new Error("Mattermost reachability check requires botToken."); + } + if (!baseUrl) { + throw new Error("Mattermost reachability check requires baseUrl."); + } + + const log = options.log ?? console.log; + const response = await fetchMattermostMe({ baseUrl, token }, options).catch((error) => { + const message = formatFetchError(error); + logMattermostDisabled(`Mattermost API was unreachable: ${message}`, log); + throw new Error("Mattermost API was unreachable."); + }); + + if (!response.ok) { + if (isRejectedTokenResponse(response)) { + log(" ⚠ Mattermost token was rejected — verify the token and bot account status."); + logMattermostDisabled("the token was rejected by Mattermost", log); + throw new Error("Mattermost token was rejected."); + } + + const detail = await readResponseText(response); + logMattermostDisabled( + `Mattermost API returned HTTP ${response.status}${ + response.statusText ? ` ${response.statusText}` : "" + }${detail ? `: ${detail}` : ""}`, + log, + ); + throw new Error("Mattermost API did not accept the configured URL and token."); + } + + const payload = await readResponseJson(response); + if (!isObject(payload) || typeof payload.id !== "string" || payload.id.trim() === "") { + logMattermostDisabled("Mattermost API returned an unexpected /users/me response", log); + throw new Error("Mattermost API returned an unexpected /users/me response."); + } + + return {}; + }; +} + +export function createMattermostHookRegistrations( + options: MattermostReachabilityHookOptions = {}, +): readonly MessagingHookRegistration[] { + return [ + { + id: MATTERMOST_REACHABILITY_HOOK_HANDLER_ID, + handler: createMattermostReachabilityHook(options), + }, + ] as const; +} + +async function fetchMattermostMe( + params: { readonly baseUrl: string; readonly token: string }, + options: MattermostReachabilityHookOptions, +): Promise { + const fetchImpl = options.fetch ?? defaultFetch; + const timeoutMs = normalizeTimeoutMs(options.timeoutMs); + return fetchWithTimeout(fetchImpl, `${params.baseUrl}/api/v4/users/me`, params.token, timeoutMs); +} + +async function defaultFetch( + url: string, + options?: MattermostFetchOptions, +): Promise { + if (typeof fetch !== "function") { + throw new Error("Mattermost reachability check requires global fetch."); + } + return fetch(url, options as RequestInit) as Promise; +} + +function normalizeTimeoutMs(timeoutMs: number | undefined): number { + return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 + ? timeoutMs + : DEFAULT_MATTERMOST_REACHABILITY_TIMEOUT_MS; +} + +async function fetchWithTimeout( + fetchImpl: MattermostFetch, + url: string, + token: string, + timeoutMs: number, +): Promise { + const controller = typeof AbortController === "function" ? new AbortController() : null; + let timeout: ReturnType | undefined; + const timeoutPromise = new Promise((_, reject) => { + timeout = setTimeout(() => { + controller?.abort(); + reject(new Error("Mattermost reachability check timed out.")); + }, timeoutMs); + timeout.unref?.(); + }); + + try { + return await Promise.race([ + fetchImpl(url, { + headers: { + Authorization: `Bearer ${token}`, + }, + ...(controller ? { signal: controller.signal } : {}), + }), + timeoutPromise, + ]); + } finally { + if (timeout) clearTimeout(timeout); + } +} + +function normalizeMattermostBaseUrl(value: string): string { + return value.replace(/\/+$/g, "").replace(/\/api\/v4$/i, ""); +} + +function normalizeInput(value: unknown): string { + return typeof value === "string" ? value.replace(/\r/g, "").trim() : ""; +} + +function isTruthyEnvFlag(value: string | undefined): boolean { + return value === "1" || value === "true" || value === "yes" || value === "on"; +} + +function isRejectedTokenResponse(response: MattermostFetchResponse): boolean { + return response.status === 401 || response.status === 403; +} + +async function readResponseJson(response: MattermostFetchResponse): Promise { + try { + return await response.json(); + } catch (_error) { + return {}; + } +} + +async function readResponseText(response: MattermostFetchResponse): Promise { + try { + return (await response.text()).replace(/\s+/g, " ").trim().slice(0, 240); + } catch (_error) { + return ""; + } +} + +function formatFetchError(error: unknown): string { + return error instanceof Error && error.message ? error.message : String(error); +} + +function logMattermostDisabled(reason: string, log: (message: string) => void): void { + log(` Mattermost integration will be disabled for this enrollment run because ${reason}.`); +} + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/src/lib/messaging/channels/mattermost/manifest.ts b/src/lib/messaging/channels/mattermost/manifest.ts new file mode 100644 index 00000000000..84c2662edb6 --- /dev/null +++ b/src/lib/messaging/channels/mattermost/manifest.ts @@ -0,0 +1,215 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { ChannelManifest } from "../../manifest"; + +export const mattermostManifest = { + schemaVersion: 1, + id: "mattermost", + displayName: "Mattermost", + description: "Mattermost bot messaging", + supportedAgents: ["openclaw"], + auth: { + mode: "token-paste", + }, + inputs: [ + { + id: "botToken", + kind: "secret", + required: true, + envKey: "MATTERMOST_BOT_TOKEN", + prompt: { + label: "Mattermost Bot Token", + help: "Mattermost > Integrations > Bot Accounts > Add Bot Account, then copy the bot token.", + }, + }, + { + id: "baseUrl", + kind: "config", + required: true, + envKey: "MATTERMOST_URL", + statePath: "mattermostConfig.baseUrl", + formatPattern: "^https?://[^\\s/]+(?:/.*)?$", + formatHint: + "Use an HTTP or HTTPS Mattermost base URL in the form https://host.example.com or http://host:port.", + prompt: { + label: "Mattermost Base URL", + help: "Enter the Mattermost server URL in the form https://host.example.com or http://host:port. Do not include /api/v4.", + placeholder: "https://chat.example.com", + }, + }, + { + id: "allowedUsers", + kind: "config", + required: false, + envKey: "MATTERMOST_ALLOWED_USERS", + statePath: "allowedIds.mattermost", + prompt: { + label: "Mattermost User IDs (comma-separated allowlist)", + help: "Optional but recommended: copy Mattermost User IDs from each allowed user's profile. User IDs are long alphanumeric IDs, not @usernames.", + emptyValueMessage: + "DM access will require agent-side pairing or upstream authorization defaults", + }, + }, + { + id: "allowedChannels", + kind: "config", + required: false, + envKey: "MATTERMOST_ALLOWED_CHANNELS", + statePath: "mattermostConfig.allowedChannels", + prompt: { + label: "Mattermost Channel IDs (comma-separated allowlist)", + help: "Optional: restrict channel messages to specific Mattermost channel IDs. DMs are not affected.", + emptyValueMessage: "channel @mentions stay unrestricted by channel ID", + }, + }, + { + id: "requireMention", + kind: "config", + required: false, + envKey: "MATTERMOST_REQUIRE_MENTION", + statePath: "mattermostConfig.requireMention", + validValues: ["0", "1"], + defaultValue: "1", + prompt: { + label: "Mattermost mention mode", + help: "Controls channel behavior only - reply only when @mentioned vs. to all channel messages. Direct messages still require authorization.", + }, + }, + ], + credentials: [ + { + id: "mattermostBotToken", + sourceInput: "botToken", + providerName: "{sandboxName}-mattermost-bridge", + providerEnvKey: "MATTERMOST_BOT_TOKEN", + placeholder: "openshell:resolve:env:MATTERMOST_BOT_TOKEN", + }, + ], + policyTemplates: [ + { + name: "mattermost", + templateFile: "mattermost.yaml", + sourceInput: "baseUrl", + sourceType: "http-url", + binariesByAgent: { + openclaw: ["/usr/local/bin/node", "/usr/bin/node"], + }, + }, + ], + render: [ + { + id: "mattermost-openclaw-channel", + kind: "json-fragment", + agent: "openclaw", + target: "openclaw.json", + fragment: { + path: "channels.mattermost", + value: { + enabled: true, + botToken: "{{credential.mattermostBotToken.placeholder}}", + baseUrl: "{{mattermostConfig.baseUrl}}", + dmPolicy: "{{allowedIds.mattermost.dmPolicy}}", + allowFrom: "{{allowedIds.mattermost.values}}", + groupPolicy: "{{mattermostConfig.openclawGroupPolicy}}", + groupAllowFrom: "{{allowedIds.mattermost.values}}", + chatmode: "{{mattermostConfig.openclawChatmode}}", + groups: "{{mattermostConfig.openclawGroups}}", + network: { + dangerouslyAllowPrivateNetwork: true, + }, + }, + }, + }, + { + id: "mattermost-openclaw-plugin", + kind: "json-fragment", + agent: "openclaw", + target: "openclaw.json", + fragment: { + path: "plugins.entries.mattermost", + value: { + enabled: true, + }, + }, + }, + ], + runtime: { + openclaw: { + channelName: "mattermost", + visibility: { + configKeys: ["mattermost"], + logPatterns: ["mattermost"], + }, + }, + }, + state: { + persist: { + mattermostConfig: ["baseUrl", "allowedChannels", "requireMention"], + allowedIds: ["allowedUsers"], + }, + rebuildHydration: [ + { + statePath: "mattermostConfig.baseUrl", + env: "MATTERMOST_URL", + }, + { + statePath: "allowedIds.mattermost", + env: "MATTERMOST_ALLOWED_USERS", + }, + { + statePath: "mattermostConfig.allowedChannels", + env: "MATTERMOST_ALLOWED_CHANNELS", + }, + { + statePath: "mattermostConfig.requireMention", + env: "MATTERMOST_REQUIRE_MENTION", + }, + ], + }, + hooks: [ + { + id: "mattermost-token-paste", + phase: "enroll", + handler: "common.tokenPaste", + outputs: [ + { + id: "botToken", + kind: "secret", + required: true, + }, + ], + onFailure: "skip-channel", + }, + { + id: "mattermost-config-prompt", + phase: "enroll", + handler: "common.configPrompt", + outputs: [ + { + id: "baseUrl", + kind: "config", + }, + { + id: "allowedUsers", + kind: "config", + }, + { + id: "allowedChannels", + kind: "config", + }, + { + id: "requireMention", + kind: "config", + }, + ], + }, + { + id: "mattermost-reachability", + phase: "reachability-check", + handler: "mattermost.reachability", + inputs: ["botToken", "baseUrl"], + onFailure: "skip-channel", + }, + ], +} as const satisfies ChannelManifest; diff --git a/src/lib/messaging/channels/mattermost/template-resolver.test.ts b/src/lib/messaging/channels/mattermost/template-resolver.test.ts new file mode 100644 index 00000000000..17b07e7c846 --- /dev/null +++ b/src/lib/messaging/channels/mattermost/template-resolver.test.ts @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; + +import type { SandboxMessagingInputReference } from "../../manifest"; +import { resolveMattermostTemplateReference } from "./template-resolver"; + +function input(inputId: string, statePath: string, value: string): SandboxMessagingInputReference { + return { + channelId: "mattermost", + inputId, + kind: "config", + required: false, + statePath, + value, + }; +} + +describe("Mattermost template resolver", () => { + it("normalizes Mattermost base URLs for OpenClaw config", () => { + const inputs = [ + input("baseUrl", "mattermostConfig.baseUrl", "https://chat.example.com/api/v4/"), + ]; + + expect(resolveMattermostTemplateReference("mattermostConfig.baseUrl", { inputs })?.value).toBe( + "https://chat.example.com", + ); + }); + + it("maps mention, channel, and user allowlists into OpenClaw group policy", () => { + const inputs: SandboxMessagingInputReference[] = [ + input("requireMention", "mattermostConfig.requireMention", "1"), + input("allowedChannels", "mattermostConfig.allowedChannels", "town-square,ops"), + input("allowedUsers", "allowedIds.mattermost", "user-a,user-b"), + ]; + + expect( + resolveMattermostTemplateReference("mattermostConfig.openclawChatmode", { inputs })?.value, + ).toBe("oncall"); + expect( + resolveMattermostTemplateReference("mattermostConfig.openclawGroupPolicy", { inputs })?.value, + ).toBe("allowlist"); + expect( + resolveMattermostTemplateReference("mattermostConfig.openclawGroups", { inputs })?.value, + ).toEqual({ + "town-square": { requireMention: true }, + ops: { requireMention: true }, + }); + }); + + it("opens OpenClaw channels when mention mode is disabled without a channel allowlist", () => { + const inputs = [input("requireMention", "mattermostConfig.requireMention", "0")]; + + expect( + resolveMattermostTemplateReference("mattermostConfig.openclawChatmode", { inputs })?.value, + ).toBe("onmessage"); + expect( + resolveMattermostTemplateReference("mattermostConfig.openclawGroupPolicy", { inputs })?.value, + ).toBe("open"); + expect( + resolveMattermostTemplateReference("mattermostConfig.openclawGroups", { inputs })?.value, + ).toEqual({ "*": { requireMention: false } }); + }); + + it("resolves shared list values without inventing empty arrays", () => { + const inputs: SandboxMessagingInputReference[] = [ + input("requireMention", "mattermostConfig.requireMention", "0"), + input("allowedChannels", "mattermostConfig.allowedChannels", "town-square, ops"), + ]; + + expect( + resolveMattermostTemplateReference("mattermostConfig.requireMention", { inputs })?.value, + ).toBe(false); + expect( + resolveMattermostTemplateReference("mattermostConfig.allowedChannels.values", { inputs }) + ?.value, + ).toEqual(["town-square", "ops"]); + expect( + resolveMattermostTemplateReference("mattermostConfig.allowedChannels.csv", { inputs })?.value, + ).toBe("town-square,ops"); + }); +}); diff --git a/src/lib/messaging/channels/mattermost/template-resolver.ts b/src/lib/messaging/channels/mattermost/template-resolver.ts new file mode 100644 index 00000000000..e0a95f87d83 --- /dev/null +++ b/src/lib/messaging/channels/mattermost/template-resolver.ts @@ -0,0 +1,103 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { RenderTemplateContext } from "../../compiler/engines/template"; +import { + allowedIds, + type BuiltInRenderTemplateResolver, + nonEmptyArray, + nonEmptyCsv, + nonEmptyObject, + nonEmptyString, + parseBoolean, + parseList, + resolvedRenderTemplateReference, + stateValue, +} from "../template-resolver-utils"; + +type MattermostGroupConfig = { + readonly requireMention?: boolean; +}; + +export const resolveMattermostTemplateReference: BuiltInRenderTemplateResolver = ( + reference, + context, +) => { + switch (reference) { + case "mattermostConfig.baseUrl": + return resolvedRenderTemplateReference(mattermostBaseUrl(context)); + case "mattermostConfig.requireMention": + return resolvedRenderTemplateReference(mattermostRequireMention(context)); + case "mattermostConfig.openclawChatmode": + return resolvedRenderTemplateReference(mattermostOpenClawChatmode(context)); + case "mattermostConfig.openclawGroupPolicy": + return resolvedRenderTemplateReference(mattermostOpenClawGroupPolicy(context)); + case "mattermostConfig.openclawGroups": + return resolvedRenderTemplateReference(nonEmptyObject(mattermostOpenClawGroups(context))); + case "mattermostConfig.allowedChannels.csv": + return resolvedRenderTemplateReference(nonEmptyCsv(mattermostAllowedChannels(context))); + case "mattermostConfig.allowedChannels.values": + return resolvedRenderTemplateReference(nonEmptyArray(mattermostAllowedChannels(context))); + default: + break; + } + + const allowedIdsReference = reference.match(/^allowedIds[.]mattermost[.](values|csv|dmPolicy)$/); + if (!allowedIdsReference?.[1]) return undefined; + const ids = allowedIds(context, "mattermost"); + switch (allowedIdsReference[1]) { + case "values": + return resolvedRenderTemplateReference(nonEmptyArray(ids)); + case "csv": + return resolvedRenderTemplateReference(nonEmptyCsv(ids)); + case "dmPolicy": + return resolvedRenderTemplateReference(ids.length > 0 ? "allowlist" : undefined); + default: + return undefined; + } +}; + +function mattermostBaseUrl(context: RenderTemplateContext): string | undefined { + const raw = nonEmptyString(stateValue(context, "mattermostConfig.baseUrl")); + if (!raw) return undefined; + return raw.replace(/\/+$/g, "").replace(/\/api\/v4$/i, ""); +} + +function mattermostRequireMention(context: RenderTemplateContext): boolean { + return parseBoolean(stateValue(context, "mattermostConfig.requireMention")) ?? true; +} + +function mattermostOpenClawChatmode(context: RenderTemplateContext): "oncall" | "onmessage" { + return mattermostRequireMention(context) ? "oncall" : "onmessage"; +} + +function mattermostOpenClawGroupPolicy( + context: RenderTemplateContext, +): "open" | "allowlist" | undefined { + if (!mattermostRequireMention(context) && mattermostAllowedChannels(context).length === 0) { + return "open"; + } + return mattermostAllowedChannels(context).length > 0 || + allowedIds(context, "mattermost").length > 0 + ? "allowlist" + : undefined; +} + +function mattermostOpenClawGroups( + context: RenderTemplateContext, +): Record { + const channels = mattermostAllowedChannels(context); + const users = allowedIds(context, "mattermost"); + const requireMention = mattermostRequireMention(context); + const entry: MattermostGroupConfig = { + requireMention, + }; + if (channels.length > 0) { + return Object.fromEntries(channels.map((channelId) => [channelId, entry])); + } + return users.length > 0 || !requireMention ? { "*": entry } : {}; +} + +function mattermostAllowedChannels(context: RenderTemplateContext): string[] { + return parseList(stateValue(context, "mattermostConfig.allowedChannels")); +} diff --git a/src/lib/messaging/channels/metadata.test.ts b/src/lib/messaging/channels/metadata.test.ts index 1e498d9110a..ada2119c478 100644 --- a/src/lib/messaging/channels/metadata.test.ts +++ b/src/lib/messaging/channels/metadata.test.ts @@ -30,6 +30,7 @@ describe("built-in messaging channel metadata", () => { "wechat", "slack", "whatsapp", + "mattermost", ]); expect(listAvailableMessagingChannelIds({ agent: "hermes" })).toEqual([ "telegram", @@ -47,6 +48,7 @@ describe("built-in messaging channel metadata", () => { wechat: ["WECHAT_BOT_TOKEN"], slack: ["SLACK_BOT_TOKEN", "SLACK_APP_TOKEN"], whatsapp: [], + mattermost: ["MATTERMOST_BOT_TOKEN"], }); expect(getMessagingChannelForCredentialEnvKey("SLACK_APP_TOKEN")).toBe("slack"); expect(getMessagingChannelForCredentialEnvKey("WHATSAPP_ALLOWED_IDS")).toBeNull(); @@ -55,6 +57,7 @@ describe("built-in messaging channel metadata", () => { discord: ["-discord-bridge"], wechat: ["-wechat-bridge"], slack: ["-slack-bridge", "-slack-app"], + mattermost: ["-mattermost-bridge"], }); expect(listMessagingProviderNamesForChannel("demo", "slack")).toEqual([ "demo-slack-bridge", @@ -78,6 +81,10 @@ describe("built-in messaging channel metadata", () => { "SLACK_ALLOWED_USERS", "SLACK_ALLOWED_CHANNELS", "WHATSAPP_ALLOWED_IDS", + "MATTERMOST_URL", + "MATTERMOST_ALLOWED_USERS", + "MATTERMOST_ALLOWED_CHANNELS", + "MATTERMOST_REQUIRE_MENTION", ]); expect(getMessagingConfigEnvAliases()).toEqual({ DISCORD_SERVER_ID: ["DISCORD_SERVER_IDS"], @@ -93,6 +100,7 @@ describe("built-in messaging channel metadata", () => { slack: ["slack"], whatsapp: ["whatsapp"], }); + expect(getMessagingPolicyKeyAliases().mattermost).toBeUndefined(); expect(getMessagingPolicyKeysByChannel({ agent: "hermes" })).toMatchObject({ telegram: ["telegram"], discord: ["discord"], @@ -100,16 +108,19 @@ describe("built-in messaging channel metadata", () => { slack: ["slack"], whatsapp: ["whatsapp"], }); + expect(getMessagingPolicyKeysByChannel({ agent: "hermes" }).mattermost).toBeUndefined(); expect(listRequiredCreateTimeMessagingPolicyPresetNames()).toEqual(["slack"]); expect(getMessagingPolicyPresetValidationWarnings().discord).toContain( "https://discord.com/api/v10/gateway or validate the configured", ); + expect(getMessagingPolicyPresetValidationWarnings().mattermost).toBeUndefined(); expect(listOpenClawManagedChannelNames()).toEqual([ "telegram", "discord", "openclaw-weixin", "slack", "whatsapp", + "mattermost", ]); expect( Object.fromEntries( @@ -121,6 +132,7 @@ describe("built-in messaging channel metadata", () => { wechat: ["openclaw-weixin"], slack: ["slack"], whatsapp: ["whatsapp"], + mattermost: ["mattermost"], }); expect( Object.fromEntries( diff --git a/src/lib/messaging/channels/metadata.ts b/src/lib/messaging/channels/metadata.ts index 62cdb3d28d9..5142c681d03 100644 --- a/src/lib/messaging/channels/metadata.ts +++ b/src/lib/messaging/channels/metadata.ts @@ -316,7 +316,7 @@ export function listMessagingPackageInstallSpecs( } function selectManifests(options: MessagingManifestMetadataOptions): ChannelManifest[] { - const manifests = options.manifests ?? BUILT_IN_CHANNEL_MANIFESTS; + const manifests: readonly ChannelManifest[] = options.manifests ?? BUILT_IN_CHANNEL_MANIFESTS; const agent = options.agent; const selected = agent ? manifests.filter((manifest) => manifest.supportedAgents.includes(agent)) diff --git a/src/lib/messaging/channels/template-resolver.ts b/src/lib/messaging/channels/template-resolver.ts index 6e93187fe05..7785f0a5aaa 100644 --- a/src/lib/messaging/channels/template-resolver.ts +++ b/src/lib/messaging/channels/template-resolver.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { resolveDiscordTemplateReference } from "./discord/template-resolver"; +import { resolveMattermostTemplateReference } from "./mattermost/template-resolver"; import { resolveSlackTemplateReference } from "./slack/template-resolver"; import { resolveTelegramTemplateReference } from "./telegram/template-resolver"; import type { BuiltInRenderTemplateResolver } from "./template-resolver-utils"; @@ -14,6 +15,7 @@ const BUILT_IN_TEMPLATE_REFERENCE_RESOLVERS: readonly BuiltInRenderTemplateResol resolveWechatTemplateReference, resolveSlackTemplateReference, resolveWhatsappTemplateReference, + resolveMattermostTemplateReference, ]; export function createBuiltInRenderTemplateResolver(): BuiltInRenderTemplateResolver { diff --git a/src/lib/messaging/compiler/engines/policy-resolver.ts b/src/lib/messaging/compiler/engines/policy-resolver.ts index 63f3bf48d13..6a616a2a4bd 100644 --- a/src/lib/messaging/compiler/engines/policy-resolver.ts +++ b/src/lib/messaging/compiler/engines/policy-resolver.ts @@ -5,19 +5,34 @@ import type { ChannelManifest, ChannelPolicyPresetReference, ChannelPolicyPresetSpec, + SandboxMessagingInputReference, SandboxMessagingNetworkPolicyEntryPlan, SandboxMessagingNetworkPolicyPlan, } from "../../manifest"; import type { ManifestCompilerContext } from "../types"; +import { renderPolicyTemplate } from "./policy-template-renderer"; export function planNetworkPolicy( manifests: readonly ChannelManifest[], context: ManifestCompilerContext, + inputRegistry: ReadonlyMap = new Map(), ): SandboxMessagingNetworkPolicyPlan { const entries = manifests.flatMap((manifest) => planManifestPolicyEntries(manifest, context)); + const templates = manifests.flatMap((manifest) => + (manifest.policyTemplates ?? []).flatMap((template) => { + const rendered = renderPolicyTemplate( + manifest.id, + template, + context.agent, + inputRegistry.get(manifest.id) ?? [], + ); + return rendered ? [rendered] : []; + }), + ); return { presets: unique(entries.map((entry) => entry.presetName)), entries, + ...(templates.length > 0 ? { templates } : {}), }; } diff --git a/src/lib/messaging/compiler/engines/policy-template-renderer.test.ts b/src/lib/messaging/compiler/engines/policy-template-renderer.test.ts new file mode 100644 index 00000000000..06399b16cbe --- /dev/null +++ b/src/lib/messaging/compiler/engines/policy-template-renderer.test.ts @@ -0,0 +1,101 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; +import YAML from "yaml"; + +import type { SandboxMessagingInputReference } from "../../manifest"; +import { renderPolicyTemplate, renderTemplateUrlContext } from "./policy-template-renderer"; + +function input(value: string): SandboxMessagingInputReference { + return { + channelId: "mattermost", + inputId: "baseUrl", + kind: "config", + required: true, + sourceEnv: "MATTERMOST_URL", + statePath: "mattermostConfig.baseUrl", + value, + }; +} + +describe("policy template renderer", () => { + const PRIVATE_NETWORK_RANGES = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"]; + + it("normalizes HTTP and HTTPS URL sources for self-hosted policy templates", () => { + expect(renderTemplateUrlContext("https://chat.example.com/api/v4/", "https-url")).toEqual({ + host: "chat.example.com", + port: 443, + basePath: "", + }); + expect(renderTemplateUrlContext("http://chat.example.com/team/api/v4", "http-url")).toEqual({ + host: "chat.example.com", + port: 80, + basePath: "/team", + }); + expect(renderTemplateUrlContext("http://192.0.2.10:8065/api/v4", "http-url")).toEqual({ + host: "192.0.2.10", + port: 8065, + basePath: "", + }); + }); + + it("rejects unsafe or unsupported URL sources", () => { + expect(() => renderTemplateUrlContext("http://chat.example.com", "https-url")).toThrow(/https/); + expect(() => renderTemplateUrlContext("ftp://chat.example.com", "http-url")).toThrow( + /http:\/\/ or https:\/\//, + ); + expect(() => + renderTemplateUrlContext("https://user:pass@chat.example.com", "http-url"), + ).toThrow(/credentials/); + expect(() => renderTemplateUrlContext("https://*.example.com", "http-url")).toThrow( + /exact DNS name/, + ); + expect(() => renderTemplateUrlContext("https://chat.example.com?x=1", "http-url")).toThrow( + /query strings/, + ); + }); + + it("renders Mattermost template content for OpenClaw", () => { + const rendered = renderPolicyTemplate( + "mattermost", + { + name: "mattermost", + templateFile: "mattermost.yaml", + sourceInput: "baseUrl", + sourceType: "http-url", + }, + "openclaw", + [input("http://chat.example.com:8065/team/api/v4")], + ); + + expect(rendered?.presetName).toBe("mattermost"); + expect(rendered?.policyKeys).toEqual(["mattermost"]); + const parsed = YAML.parse(rendered?.content ?? ""); + const policy = parsed.network_policies.mattermost; + expect(policy.endpoints).toEqual([ + expect.objectContaining({ + host: "chat.example.com", + port: 8065, + protocol: "rest", + enforcement: "enforce", + request_body_credential_rewrite: true, + websocket_credential_rewrite: true, + allowed_ips: PRIVATE_NETWORK_RANGES, + rules: [ + { allow: { method: "GET", path: "/team/api/v4/websocket" } }, + { allow: { method: "WEBSOCKET_TEXT", path: "/team/api/v4/websocket" } }, + { allow: { method: "GET", path: "/team/api/v4/**" } }, + { allow: { method: "POST", path: "/team/api/v4/**" } }, + { allow: { method: "PUT", path: "/team/api/v4/**" } }, + { allow: { method: "PATCH", path: "/team/api/v4/**" } }, + { allow: { method: "DELETE", path: "/team/api/v4/**" } }, + ], + }), + ]); + expect(policy.endpoints[0]).not.toHaveProperty("access"); + expect(policy.endpoints[0]).not.toHaveProperty("tls"); + expect(policy.binaries).toEqual([{ path: "/usr/local/bin/node" }, { path: "/usr/bin/node" }]); + expect(parsed.preset.template).toBeUndefined(); + }); +}); diff --git a/src/lib/messaging/compiler/engines/policy-template-renderer.ts b/src/lib/messaging/compiler/engines/policy-template-renderer.ts new file mode 100644 index 00000000000..0cba5dc131b --- /dev/null +++ b/src/lib/messaging/compiler/engines/policy-template-renderer.ts @@ -0,0 +1,231 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; + +import YAML from "yaml"; + +import type { + ChannelPolicyTemplateSpec, + MessagingAgentId, + SandboxMessagingInputReference, + SandboxMessagingNetworkPolicyTemplatePlan, +} from "../../manifest"; + +const POLICY_TEMPLATES_DIR = path.resolve( + __dirname, + "..", + "..", + "..", + "..", + "..", + "nemoclaw-blueprint", + "policies", + "templates", +); +const TEMPLATE_TOKEN_PATTERN = /\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}/g; +const LINE_ONLY_AGENT_BINARIES_PATTERN = + /^([ \t]*)-\s*path:\s*["']\{\{\s*agent\.binaries\s*\}\}["'][ \t]*$/gm; + +const DEFAULT_MESSAGING_BINARIES_BY_AGENT: Readonly> = { + openclaw: ["/usr/local/bin/node", "/usr/bin/node"], + hermes: ["/usr/local/bin/hermes", "/usr/bin/python3*", "/opt/hermes/.venv/bin/python"], +}; + +interface TemplateUrlContext { + readonly host: string; + readonly port: number; + readonly basePath: string; +} + +export function renderPolicyTemplate( + channelId: string, + spec: ChannelPolicyTemplateSpec, + agent: MessagingAgentId, + inputs: readonly SandboxMessagingInputReference[], +): SandboxMessagingNetworkPolicyTemplatePlan | null { + const sourceValue = inputStringValue(inputs, spec.sourceInput); + if (!sourceValue) return null; + + const url = renderTemplateUrlContext(sourceValue, spec.sourceType); + const binaries = spec.binariesByAgent?.[agent] ?? DEFAULT_MESSAGING_BINARIES_BY_AGENT[agent]; + const template = readPolicyTemplate(spec.templateFile); + const rendered = renderPolicyTemplateContent(template, { url, binaries }); + const parsed = parseRenderedPolicyTemplate(spec.name, rendered); + + return { + channelId, + presetName: spec.name, + templateFile: spec.templateFile, + sourceInput: spec.sourceInput, + policyKeys: Object.keys(parsed.network_policies), + content: YAML.stringify(parsed), + }; +} + +export function renderTemplateUrlContext( + value: string, + sourceType: ChannelPolicyTemplateSpec["sourceType"], +): TemplateUrlContext { + if (sourceType !== "https-url" && sourceType !== "http-url") { + throw new Error(`Unsupported policy template source type: ${sourceType}`); + } + + let url: URL; + try { + url = new URL(value); + } catch { + const scheme = sourceType === "http-url" ? "HTTP or HTTPS" : "HTTPS"; + throw new Error(`Policy template URL must be an absolute ${scheme} URL.`); + } + + if (sourceType === "https-url" && url.protocol !== "https:") { + throw new Error("Policy template URL must use https://."); + } + if (sourceType === "http-url" && url.protocol !== "http:" && url.protocol !== "https:") { + throw new Error("Policy template URL must use http:// or https://."); + } + if (url.username || url.password) { + throw new Error("Policy template URL must not include credentials."); + } + if (url.search || url.hash) { + throw new Error("Policy template URL must not include query strings or fragments."); + } + + const host = url.hostname.toLowerCase(); + if (!/^[a-z0-9.-]+$/.test(host) || host.includes("..") || host.includes("*")) { + throw new Error("Policy template URL host must be an exact DNS name or IPv4 address."); + } + + return { + host, + port: portForUrl(url), + basePath: normalizeUrlBasePath(url.pathname), + }; +} + +function portForUrl(url: URL): number { + const explicitPort = url.port ? Number(url.port) : undefined; + const port = explicitPort ?? (url.protocol === "https:" ? 443 : 80); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error("Policy template URL port must be between 1 and 65535."); + } + return port; +} + +function inputStringValue( + inputs: readonly SandboxMessagingInputReference[], + sourceInput: string, +): string | null { + const input = inputs.find( + (entry) => entry.inputId === sourceInput || entry.statePath === sourceInput, + ); + const value = input?.value; + if (typeof value !== "string") return null; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} + +function normalizeUrlBasePath(pathname: string): string { + let basePath = pathname.trim().replace(/\/+$/g, ""); + if (basePath === "/" || basePath === "") return ""; + if (basePath.endsWith("/api/v4")) basePath = basePath.slice(0, -"/api/v4".length); + if (basePath === "/" || basePath === "") return ""; + if (!basePath.startsWith("/")) basePath = `/${basePath}`; + return basePath; +} + +function readPolicyTemplate(templateFile: string): string { + if (!templateFile || templateFile.includes("\0")) { + throw new Error("Policy template file must be a relative YAML file path."); + } + const resolved = path.resolve(POLICY_TEMPLATES_DIR, templateFile); + if (!resolved.startsWith(POLICY_TEMPLATES_DIR + path.sep) || !/\.ya?ml$/i.test(resolved)) { + throw new Error(`Invalid policy template path: ${templateFile}`); + } + return fs.readFileSync(resolved, "utf-8"); +} + +function renderPolicyTemplateContent( + template: string, + context: { readonly url: TemplateUrlContext; readonly binaries: readonly string[] }, +): string { + const withBinaries = template.replace( + LINE_ONLY_AGENT_BINARIES_PATTERN, + (_match, indent: string) => renderAgentBinaries(indent, context.binaries), + ); + const rendered = withBinaries.replace(TEMPLATE_TOKEN_PATTERN, (_match, token: string) => { + switch (token) { + case "url.host": + return context.url.host; + case "url.port": + return String(context.url.port); + case "url.basePath": + return context.url.basePath; + default: + throw new Error(`Unknown policy template token: ${token}`); + } + }); + if (TEMPLATE_TOKEN_PATTERN.test(rendered)) { + throw new Error("Policy template contains unresolved tokens."); + } + return rendered; +} + +function renderAgentBinaries(indent: string, binaries: readonly string[]): string { + if (binaries.length === 0) return `${indent}[]`; + return binaries.map((binary) => `${indent}- { path: ${validateYamlScalar(binary)} }`).join("\n"); +} + +function validateYamlScalar(value: string): string { + if (!value || /[\r\n\0]/.test(value)) { + throw new Error("Policy template binary paths must be non-empty single-line values."); + } + return value; +} + +function parseRenderedPolicyTemplate( + expectedPresetName: string, + rendered: string, +): { preset: { name: string; description?: string }; network_policies: Record } { + const parsed = YAML.parse(rendered) as unknown; + if (!isObject(parsed)) { + throw new Error("Rendered policy template must be a YAML mapping."); + } + + const preset = parsed.preset; + if (!isObject(preset) || preset.name !== expectedPresetName) { + throw new Error(`Rendered policy template must declare preset.name: ${expectedPresetName}`); + } + delete preset.template; + + const networkPolicies = parsed.network_policies; + if (!isObject(networkPolicies) || Object.keys(networkPolicies).length === 0) { + throw new Error("Rendered policy template must declare network_policies."); + } + normalizeNetworkPolicyPorts(networkPolicies); + + return parsed as { + preset: { name: string; description?: string }; + network_policies: Record; + }; +} + +function normalizeNetworkPolicyPorts(networkPolicies: Record): void { + for (const policy of Object.values(networkPolicies)) { + if (!isObject(policy) || !Array.isArray(policy.endpoints)) continue; + for (const endpoint of policy.endpoints) { + if (!isObject(endpoint) || typeof endpoint.port !== "string") continue; + if (!/^[0-9]+$/.test(endpoint.port)) continue; + const port = Number(endpoint.port); + if (Number.isInteger(port) && port >= 1 && port <= 65535) { + endpoint.port = port; + } + } + } +} + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/src/lib/messaging/compiler/manifest-compiler.test.ts b/src/lib/messaging/compiler/manifest-compiler.test.ts index 08b20dd93cb..ebf4e113c15 100644 --- a/src/lib/messaging/compiler/manifest-compiler.test.ts +++ b/src/lib/messaging/compiler/manifest-compiler.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it } from "vitest"; +import YAML from "yaml"; import { createBuiltInChannelManifestRegistry, @@ -15,13 +16,15 @@ import { } from "../manifest"; import { ManifestCompiler } from "./manifest-compiler"; -const ALL_CHANNELS = ["telegram", "discord", "wechat", "slack", "whatsapp"] as const; +const ALL_CHANNELS = ["telegram", "discord", "wechat", "slack", "whatsapp", "mattermost"] as const; +const HERMES_CHANNELS = ["telegram", "discord", "wechat", "slack", "whatsapp"] as const; const TEST_CREDENTIALS: Readonly> = { TELEGRAM_BOT_TOKEN: "123456:test-telegram-token", DISCORD_BOT_TOKEN: "test-discord-token", WECHAT_BOT_TOKEN: "test-wechat-token", SLACK_BOT_TOKEN: "xoxb-test-slack-token", SLACK_APP_TOKEN: "xapp-test-slack-token", + MATTERMOST_BOT_TOKEN: "test-mattermost-token", }; const TEST_WECHAT_LOGIN = { token: "test-wechat-token", @@ -47,6 +50,18 @@ function compiler(): ManifestCompiler { validateCredentials: () => ({ ok: true }), }, }, + mattermost: { + fetch: async () => ({ + ok: true, + status: 200, + async json() { + return { id: "mattermost-bot-user" }; + }, + async text() { + return ""; + }, + }), + }, telegram: { fetch: async () => ({ ok: true, @@ -122,20 +137,29 @@ async function withEnv( describe("ManifestCompiler", () => { it("compiles built-in manifests into a deterministic OpenClaw plan", async () => { - const plan = await compiler().compile({ - sandboxName: "demo", - agent: "openclaw", - workflow: "onboard", - isInteractive: true, - configuredChannels: ["slack", "telegram", "wechat", "discord", "whatsapp"], - credentialAvailability: { - TELEGRAM_BOT_TOKEN: true, - DISCORD_BOT_TOKEN: true, - WECHAT_BOT_TOKEN: true, - SLACK_BOT_TOKEN: true, - SLACK_APP_TOKEN: true, + const plan = await withEnv( + { + MATTERMOST_URL: "https://mattermost.com", + MATTERMOST_ALLOWED_USERS: "user-a,user-b", + MATTERMOST_ALLOWED_CHANNELS: "town-square", }, - }); + () => + compiler().compile({ + sandboxName: "demo", + agent: "openclaw", + workflow: "onboard", + isInteractive: true, + configuredChannels: ["slack", "telegram", "wechat", "discord", "whatsapp", "mattermost"], + credentialAvailability: { + TELEGRAM_BOT_TOKEN: true, + DISCORD_BOT_TOKEN: true, + WECHAT_BOT_TOKEN: true, + SLACK_BOT_TOKEN: true, + SLACK_APP_TOKEN: true, + MATTERMOST_BOT_TOKEN: true, + }, + }), + ); expect(plan.channels.map((channel) => channel.channelId)).toEqual(ALL_CHANNELS); expect(plan.channels.every((channel) => channel.active)).toBe(true); @@ -145,6 +169,7 @@ describe("ManifestCompiler", () => { "demo-wechat-bridge", "demo-slack-bridge", "demo-slack-app", + "demo-mattermost-bridge", ]); expect(plan.credentialBindings.map((binding) => binding.placeholder)).toEqual([ "openshell:resolve:env:TELEGRAM_BOT_TOKEN", @@ -152,6 +177,7 @@ describe("ManifestCompiler", () => { "openshell:resolve:env:WECHAT_BOT_TOKEN", "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN", + "openshell:resolve:env:MATTERMOST_BOT_TOKEN", ]); expect(plan.networkPolicy.entries).toEqual([ { @@ -185,6 +211,38 @@ describe("ManifestCompiler", () => { source: "manifest", }, ]); + expect(plan.networkPolicy.templates).toHaveLength(1); + expect(plan.networkPolicy.templates?.[0]).toMatchObject({ + channelId: "mattermost", + presetName: "mattermost", + templateFile: "mattermost.yaml", + sourceInput: "baseUrl", + policyKeys: ["mattermost"], + }); + expect( + YAML.parse(plan.networkPolicy.templates?.[0]?.content ?? "").network_policies.mattermost + .endpoints[0], + ).toMatchObject({ + host: "mattermost.com", + port: 443, + protocol: "rest", + enforcement: "enforce", + request_body_credential_rewrite: true, + websocket_credential_rewrite: true, + allowed_ips: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"], + }); + expect( + YAML.parse(plan.networkPolicy.templates?.[0]?.content ?? "").network_policies.mattermost + .endpoints[0].rules, + ).toEqual([ + { allow: { method: "GET", path: "/api/v4/websocket" } }, + { allow: { method: "WEBSOCKET_TEXT", path: "/api/v4/websocket" } }, + { allow: { method: "GET", path: "/api/v4/**" } }, + { allow: { method: "POST", path: "/api/v4/**" } }, + { allow: { method: "PUT", path: "/api/v4/**" } }, + { allow: { method: "PATCH", path: "/api/v4/**" } }, + { allow: { method: "DELETE", path: "/api/v4/**" } }, + ]); expect(plan.agentRender.map((render) => `${render.channelId}:${render.renderId}`)).toEqual([ "telegram:telegram-openclaw-channel", "telegram:telegram-openclaw-groups", @@ -196,10 +254,45 @@ describe("ManifestCompiler", () => { "slack:slack-openclaw-plugin", "whatsapp:whatsapp-openclaw-channel", "whatsapp:whatsapp-openclaw-plugin", + "mattermost:mattermost-openclaw-channel", + "mattermost:mattermost-openclaw-plugin", ]); expect(plan.agentRender.every((render) => render.handler === "common.staticOutputs")).toBe( true, ); + const mattermostRender = plan.agentRender.find( + (render) => + render.channelId === "mattermost" && render.renderId === "mattermost-openclaw-channel", + ); + if (mattermostRender?.kind !== "json-fragment") { + throw new Error("missing Mattermost OpenClaw json-fragment render"); + } + expect(mattermostRender).toMatchObject({ + kind: "json-fragment", + path: "channels.mattermost", + value: { + network: { + dangerouslyAllowPrivateNetwork: true, + }, + allowFrom: ["user-a", "user-b"], + groupAllowFrom: ["user-a", "user-b"], + groups: { + "town-square": { + requireMention: true, + }, + }, + }, + }); + expect(mattermostRender?.value).toMatchObject({ + allowFrom: ["user-a", "user-b"], + groupAllowFrom: ["user-a", "user-b"], + }); + expect(mattermostRender?.value).toHaveProperty("groups"); + expect((mattermostRender?.value as { groups?: unknown } | undefined)?.groups).toEqual({ + "town-square": { + requireMention: true, + }, + }); expect(JSON.stringify(plan.agentRender)).toContain("openshell:resolve:env:TELEGRAM_BOT_TOKEN"); expect(plan.buildSteps.map(({ value: _value, ...step }) => step)).toEqual([ { @@ -272,6 +365,7 @@ describe("ManifestCompiler", () => { }), ]), ); + expect(plan.buildSteps.some((step) => step.channelId === "mattermost")).toBe(false); expect(plan.buildSteps.every((step) => step.value !== undefined)).toBe(true); expect(plan.stateUpdates).toContainEqual({ channelId: "wechat", @@ -323,7 +417,7 @@ describe("ManifestCompiler", () => { agent: "hermes", workflow: "rebuild", isInteractive: false, - configuredChannels: ALL_CHANNELS, + configuredChannels: HERMES_CHANNELS, credentialAvailability: { TELEGRAM_BOT_TOKEN: true, DISCORD_BOT_TOKEN: true, @@ -340,6 +434,9 @@ describe("ManifestCompiler", () => { policyKeys: ["wechat_bridge"], source: "manifest", }); + expect( + plan.networkPolicy.templates?.find((entry) => entry.channelId === "mattermost"), + ).toBeUndefined(); expect(plan.agentRender.map((render) => `${render.channelId}:${render.target}`)).toEqual([ "telegram:~/.hermes/.env", "telegram:~/.hermes/config.yaml", diff --git a/src/lib/messaging/compiler/manifest-compiler.ts b/src/lib/messaging/compiler/manifest-compiler.ts index 30f7758c230..c6b8e317cfc 100644 --- a/src/lib/messaging/compiler/manifest-compiler.ts +++ b/src/lib/messaging/compiler/manifest-compiler.ts @@ -62,7 +62,7 @@ export class ManifestCompiler { const credentialBindings = manifests.flatMap((manifest) => planCredentialBindings(manifest, context, inputRegistry.get(manifest.id) ?? []), ); - const networkPolicy = planNetworkPolicy(manifests, context); + const networkPolicy = planNetworkPolicy(manifests, context, inputRegistry); const agentRender = ( await Promise.all( manifests.map((manifest) => diff --git a/src/lib/messaging/compiler/workflow-planner.ts b/src/lib/messaging/compiler/workflow-planner.ts index ce901ad1d3c..3e74aa17e6c 100644 --- a/src/lib/messaging/compiler/workflow-planner.ts +++ b/src/lib/messaging/compiler/workflow-planner.ts @@ -289,6 +289,10 @@ function mergeSandboxMessagingPlans( existing.networkPolicy.entries, incoming.networkPolicy.entries, ); + const networkTemplates = mergePlanEntriesByChannel( + existing.networkPolicy.templates ?? [], + incoming.networkPolicy.templates ?? [], + ); return clonePlan({ ...incoming, @@ -301,6 +305,7 @@ function mergeSandboxMessagingPlans( networkPolicy: { presets: uniqueSortedStrings(networkEntries.map((entry) => entry.presetName)), entries: networkEntries, + ...(networkTemplates.length > 0 ? { templates: networkTemplates } : {}), }, agentRender: mergePlanEntriesByChannel(existing.agentRender, incoming.agentRender), buildSteps: mergePlanEntriesByChannel(existing.buildSteps, incoming.buildSteps), @@ -376,6 +381,9 @@ function removePlanChannel( const networkEntries = plan.networkPolicy.entries.filter( (entry) => entry.channelId !== channelId, ); + const networkTemplates = (plan.networkPolicy.templates ?? []).filter( + (entry) => entry.channelId !== channelId, + ); const keepEntry = (entry: T) => entry.channelId !== channelId && remainingChannelIds.has(entry.channelId); @@ -390,6 +398,7 @@ function removePlanChannel( networkPolicy: { presets: uniqueSortedStrings(networkEntries.map((entry) => entry.presetName)), entries: networkEntries, + ...(networkTemplates.length > 0 ? { templates: networkTemplates } : {}), }, agentRender: plan.agentRender.filter(keepEntry), buildSteps: plan.buildSteps.filter(keepEntry), diff --git a/src/lib/messaging/diagnostics.test.ts b/src/lib/messaging/diagnostics.test.ts index 79497f108ff..b19046e5597 100644 --- a/src/lib/messaging/diagnostics.test.ts +++ b/src/lib/messaging/diagnostics.test.ts @@ -15,6 +15,7 @@ describe("messaging channel diagnostics", () => { "wechat", "slack", "whatsapp", + "mattermost", ]); expect(specs.find((spec) => spec.channelId === "telegram")).toMatchObject({ policyPresets: ["telegram"], @@ -31,5 +32,9 @@ describe("messaging channel diagnostics", () => { hint: "run `{cli} {sandbox} channels status --channel {channel}` to probe inbound delivery", }), }); + expect(specs.find((spec) => spec.channelId === "mattermost")).toMatchObject({ + policyPresets: ["mattermost"], + preferredDefault: false, + }); }); }); diff --git a/src/lib/messaging/diagnostics.ts b/src/lib/messaging/diagnostics.ts index 0b91a03e5d8..b276c944f81 100644 --- a/src/lib/messaging/diagnostics.ts +++ b/src/lib/messaging/diagnostics.ts @@ -2,7 +2,12 @@ // SPDX-License-Identifier: Apache-2.0 import { createBuiltInChannelManifestRegistry } from "./channels"; -import type { ChannelManifest, ChannelPolicyPresetReference, MessagingAgentId } from "./manifest"; +import type { + ChannelManifest, + ChannelPolicyPresetReference, + ChannelPolicyTemplateSpec, + MessagingAgentId, +} from "./manifest"; export interface MessagingChannelDiagnosticSpec { readonly channelId: string; @@ -32,7 +37,7 @@ export function collectMessagingChannelDiagnostics( const deepProbe = manifest.auth.mode === "in-sandbox-qr" ? "in-sandbox-qr" : undefined; return { channelId: manifest.id, - policyPresets: policyPresetNames(manifest.policyPresets), + policyPresets: policyNames(manifest.policyPresets, manifest.policyTemplates), preferredDefault: deepProbe !== undefined, ...(deepProbe ? { deepProbe, doctorWhenNoHealthSignals: qrDeepProbeDoctorHint() } : {}), }; @@ -47,6 +52,12 @@ function qrDeepProbeDoctorHint(): MessagingChannelDiagnosticSpec["doctorWhenNoHe }; } -function policyPresetNames(presets: readonly ChannelPolicyPresetReference[] | undefined): string[] { - return (presets ?? []).map((preset) => (typeof preset === "string" ? preset : preset.name)); +function policyNames( + presets: readonly ChannelPolicyPresetReference[] | undefined, + templates: readonly ChannelPolicyTemplateSpec[] | undefined, +): string[] { + return [ + ...(presets ?? []).map((preset) => (typeof preset === "string" ? preset : preset.name)), + ...(templates ?? []).map((template) => template.name), + ]; } diff --git a/src/lib/messaging/hooks/builtins.ts b/src/lib/messaging/hooks/builtins.ts index 0e8ad9e11b2..92c0340771a 100644 --- a/src/lib/messaging/hooks/builtins.ts +++ b/src/lib/messaging/hooks/builtins.ts @@ -2,6 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { createDiscordHookRegistrations, type DiscordHookOptions } from "../channels/discord/hooks"; +import { + createMattermostHookRegistrations, + type MattermostReachabilityHookOptions, +} from "../channels/mattermost/hooks"; import type { OpenClawBridgeHealthHookOptions } from "../channels/openclaw-bridge-health"; import { createSlackHookRegistrations, type SlackHookOptions } from "../channels/slack/hooks"; import { @@ -16,6 +20,7 @@ import type { MessagingHookRegistration } from "./types"; export interface BuiltInMessagingHookOptions { readonly common?: CommonHookOptions; readonly discord?: DiscordHookOptions; + readonly mattermost?: MattermostReachabilityHookOptions; readonly openclawBridgeHealth?: OpenClawBridgeHealthHookOptions; readonly slack?: SlackHookOptions; readonly telegram?: TelegramHookOptions; @@ -33,6 +38,7 @@ export function createBuiltInMessagingHookRegistrations( ...createSlackHookRegistrations( withOpenClawBridgeHealthOptions(options.slack, options.openclawBridgeHealth), ), + ...createMattermostHookRegistrations(options.mattermost), ...createTelegramHookRegistrations( withOpenClawBridgeHealthOptions(options.telegram, options.openclawBridgeHealth), ), diff --git a/src/lib/messaging/hooks/hook-runner.test.ts b/src/lib/messaging/hooks/hook-runner.test.ts index 835599aeccc..7ae39e5b4d7 100644 --- a/src/lib/messaging/hooks/hook-runner.test.ts +++ b/src/lib/messaging/hooks/hook-runner.test.ts @@ -42,6 +42,7 @@ describe("MessagingHookRegistry", () => { "slack.socketModeGatewayStatus", "slack.openclawBridgeHealth", "slack.validateCredentials", + "mattermost.reachability", "telegram.allowlistAliases", "telegram.openclawBridgeHealth", "telegram.gatewayConflictStatus", diff --git a/src/lib/messaging/manifest/types.ts b/src/lib/messaging/manifest/types.ts index 9395e085a97..c946a486e07 100644 --- a/src/lib/messaging/manifest/types.ts +++ b/src/lib/messaging/manifest/types.ts @@ -41,6 +41,8 @@ export interface ChannelManifest { readonly credentials: readonly ChannelCredentialSpec[]; /** Policy presets needed when this channel is active. */ readonly policyPresets?: readonly ChannelPolicyPresetReference[]; + /** Policy templates rendered from channel config such as self-hosted URLs. */ + readonly policyTemplates?: readonly ChannelPolicyTemplateSpec[]; readonly render: readonly ChannelRenderSpec[]; readonly runtime?: ChannelRuntimeByAgentSpec; readonly agentPackages?: readonly ChannelAgentPackageSpec[]; @@ -60,6 +62,15 @@ export interface ChannelPolicyPresetSpec { readonly validationWarningLines?: readonly string[]; } +/** Parameterized policy template rendered from non-secret channel input. */ +export interface ChannelPolicyTemplateSpec { + readonly name: string; + readonly templateFile: string; + readonly sourceInput: string; + readonly sourceType: "https-url" | "http-url"; + readonly binariesByAgent?: Partial>; +} + /** How a channel obtains credential or session material. */ export type ChannelAuthMode = "none" | "token-paste" | "host-qr" | "in-sandbox-qr"; @@ -331,6 +342,7 @@ export interface SandboxMessagingCredentialBindingPlan { export interface SandboxMessagingNetworkPolicyPlan { readonly presets: readonly string[]; readonly entries: readonly SandboxMessagingNetworkPolicyEntryPlan[]; + readonly templates?: readonly SandboxMessagingNetworkPolicyTemplatePlan[]; } /** One active channel's requested policy preset and resolved policy keys. */ @@ -341,6 +353,16 @@ export interface SandboxMessagingNetworkPolicyEntryPlan { readonly source: "agent-alias" | "manifest"; } +/** One active channel's rendered custom network policy template. */ +export interface SandboxMessagingNetworkPolicyTemplatePlan { + readonly channelId: MessagingChannelId; + readonly presetName: string; + readonly templateFile: string; + readonly sourceInput: string; + readonly policyKeys: readonly string[]; + readonly content: string; +} + /** Compiled render output for supported target formats. */ export type SandboxMessagingAgentRenderPlan = | SandboxMessagingJsonRenderPlan diff --git a/src/lib/messaging/persistence.ts b/src/lib/messaging/persistence.ts index 9e5ca171284..d9a7b7650b0 100644 --- a/src/lib/messaging/persistence.ts +++ b/src/lib/messaging/persistence.ts @@ -157,7 +157,7 @@ export function hydrateDerivedSandboxMessagingPlanFields( return { ...planWithCredentials, networkPolicy: - plan.networkPolicy.entries.length > 0 + plan.networkPolicy.entries.length > 0 || (plan.networkPolicy.templates?.length ?? 0) > 0 ? plan.networkPolicy : planNetworkPolicy(manifests, compilerContext(planWithCredentials)), agentRender: diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index dd341a9b5c7..a5f979ed4f9 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -115,6 +115,8 @@ const { const { syncPresetSelection, }: typeof import("./onboard/policy-preset-sync") = require("./onboard/policy-preset-sync"); +const messagingPolicyTemplates: typeof import("./onboard/messaging-policy-templates") = + require("./onboard/messaging-policy-templates"); const { maybeForceE2eStepFailure, }: typeof import("./onboard/e2e-failure-injection") = require("./onboard/e2e-failure-injection"); @@ -4594,7 +4596,8 @@ async function setupPoliciesWithSelection( sandboxName: string, options: SetupPolicySelectionOptions = {}, ) { - return setupPoliciesWithSelectionImpl( + let reconciledLivePolicy = false; + const result = await setupPoliciesWithSelectionImpl( { policies, tiers, @@ -4612,8 +4615,18 @@ async function setupPoliciesWithSelection( env: process.env, }, sandboxName, - options, + { + ...options, + onSelection: (policyPresets) => { + reconciledLivePolicy = true; + options.onSelection?.(policyPresets); + }, + }, ); + if (reconciledLivePolicy) { + messagingPolicyTemplates.applyGeneratedMessagingPolicyTemplatesFromRegistry(sandboxName); + } + return result; } const { diff --git a/src/lib/onboard/messaging-policy-templates.ts b/src/lib/onboard/messaging-policy-templates.ts new file mode 100644 index 00000000000..330837d24f6 --- /dev/null +++ b/src/lib/onboard/messaging-policy-templates.ts @@ -0,0 +1,42 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { filterEnabledPlanEntries } from "../messaging/applier/plan-filter"; +import type { SandboxMessagingPlan } from "../messaging/manifest"; +import * as policies from "../policy"; +import * as registry from "../state/registry"; + +export function applyGeneratedMessagingPolicyTemplates( + sandboxName: string, + plan: SandboxMessagingPlan | null | undefined, + options: { + readonly channelId?: string | null; + readonly sourcePath?: string; + } = {}, +): string[] { + if (!plan || plan.sandboxName !== sandboxName) return []; + const activeTemplates = filterEnabledPlanEntries(plan, plan.networkPolicy.templates ?? []).filter( + (template) => !options.channelId || template.channelId === options.channelId, + ); + const applied: string[] = []; + for (const template of activeTemplates) { + const ok = policies.applyPresetContent(sandboxName, template.presetName, template.content, { + custom: { sourcePath: options.sourcePath ?? `messaging:${template.channelId}` }, + }); + if (!ok) { + throw new Error(`Failed to apply generated messaging policy: ${template.presetName}`); + } + applied.push(template.presetName); + } + return [...new Set(applied)]; +} + +export function applyGeneratedMessagingPolicyTemplatesFromRegistry( + sandboxName: string, + options: { + readonly channelId?: string | null; + } = {}, +): string[] { + const plan = registry.getHydratedMessagingPlanFromEntry(registry.getSandbox(sandboxName)); + return applyGeneratedMessagingPolicyTemplates(sandboxName, plan, options); +} diff --git a/src/lib/onboard/messaging-prep.test.ts b/src/lib/onboard/messaging-prep.test.ts index cbc28d332d8..0df2a9e0e97 100644 --- a/src/lib/onboard/messaging-prep.test.ts +++ b/src/lib/onboard/messaging-prep.test.ts @@ -144,6 +144,7 @@ describe("prepareCreateSandboxMessaging", () => { expect([...result.messagingTokenDefs.map(({ envKey }) => envKey)].sort()).toEqual([ "DISCORD_BOT_TOKEN", + "MATTERMOST_BOT_TOKEN", "SLACK_APP_TOKEN", "SLACK_BOT_TOKEN", "TELEGRAM_BOT_TOKEN", diff --git a/src/lib/sandbox/channels.test.ts b/src/lib/sandbox/channels.test.ts index 27b3b98b030..5dd2f70a2b3 100644 --- a/src/lib/sandbox/channels.test.ts +++ b/src/lib/sandbox/channels.test.ts @@ -16,8 +16,15 @@ import { } from "./channels"; describe("sandbox-channels KNOWN_CHANNELS", () => { - it("covers telegram, discord, wechat, slack, and whatsapp", () => { - expect(knownChannelNames()).toEqual(["telegram", "discord", "wechat", "slack", "whatsapp"]); + it("covers telegram, discord, wechat, slack, whatsapp, and mattermost", () => { + expect(knownChannelNames()).toEqual([ + "telegram", + "discord", + "wechat", + "slack", + "whatsapp", + "mattermost", + ]); }); it("exposes the primary bot-token env var for token-based channels", () => { @@ -25,6 +32,7 @@ describe("sandbox-channels KNOWN_CHANNELS", () => { expect(getChannelDef("discord")?.envKey).toBe("DISCORD_BOT_TOKEN"); expect(getChannelDef("slack")?.envKey).toBe("SLACK_BOT_TOKEN"); expect(getChannelDef("wechat")?.envKey).toBe("WECHAT_BOT_TOKEN"); + expect(getChannelDef("mattermost")?.envKey).toBe("MATTERMOST_BOT_TOKEN"); }); it("classifies channels by login method", () => { @@ -40,6 +48,7 @@ describe("sandbox-channels KNOWN_CHANNELS", () => { expect(getChannelDef("telegram")?.loginMethod).toBeUndefined(); expect(getChannelDef("discord")?.loginMethod).toBeUndefined(); expect(getChannelDef("slack")?.loginMethod).toBeUndefined(); + expect(getChannelDef("mattermost")?.loginMethod).toBeUndefined(); }); it("declares wechat as DM-only with the WECHAT_ALLOWED_IDS env key", () => { @@ -57,6 +66,17 @@ describe("sandbox-channels KNOWN_CHANNELS", () => { expect(channelUsesInSandboxQrPairing(KNOWN_CHANNELS.slack)).toBe(false); }); + it("asks for Mattermost base URL, user IDs, channel IDs, and mention mode", () => { + const mattermost = getChannelDef("mattermost"); + expect(mattermost?.envKey).toBe("MATTERMOST_BOT_TOKEN"); + expect(mattermost?.userIdEnvKey).toBe("MATTERMOST_ALLOWED_USERS"); + expect(mattermost?.userIdLabel).toBe("Mattermost User IDs (comma-separated allowlist)"); + expect(mattermost?.allowIdsMode).toBe("dm"); + expect(mattermost?.channelIdEnvKey).toBe("MATTERMOST_ALLOWED_CHANNELS"); + expect(mattermost?.channelIdLabel).toBe("Mattermost Channel IDs (comma-separated allowlist)"); + expect(mattermost?.requireMentionEnvKey).toBe("MATTERMOST_REQUIRE_MENTION"); + }); + it("declares no provider-credential metadata for WhatsApp", () => { const whatsapp = getChannelDef("whatsapp"); expect(whatsapp?.envKey).toBeUndefined(); @@ -107,10 +127,11 @@ describe("sandbox-channels KNOWN_CHANNELS", () => { expect(getChannelDef(" Telegram ")).toBe(KNOWN_CHANNELS.telegram); expect(getChannelDef("DISCORD")).toBe(KNOWN_CHANNELS.discord); expect(getChannelDef(" WhatsApp ")).toBe(KNOWN_CHANNELS.whatsapp); + expect(getChannelDef("MATTERMOST")).toBe(KNOWN_CHANNELS.mattermost); }); it("returns undefined for unknown channel names", () => { - expect(getChannelDef("mattermost")).toBeUndefined(); + expect(getChannelDef("matrix")).toBeUndefined(); expect(getChannelDef("")).toBeUndefined(); }); }); @@ -119,6 +140,7 @@ describe("sandbox-channels getChannelTokenKeys", () => { it("returns just the primary token key for single-token channels", () => { expect(getChannelTokenKeys(KNOWN_CHANNELS.telegram)).toEqual(["TELEGRAM_BOT_TOKEN"]); expect(getChannelTokenKeys(KNOWN_CHANNELS.discord)).toEqual(["DISCORD_BOT_TOKEN"]); + expect(getChannelTokenKeys(KNOWN_CHANNELS.mattermost)).toEqual(["MATTERMOST_BOT_TOKEN"]); }); it("returns primary then app token for slack", () => { @@ -146,6 +168,7 @@ describe("sandbox-channels token-shape helpers", () => { expect(channelUsesInSandboxQrPairing(KNOWN_CHANNELS.wechat)).toBe(false); expect(channelUsesInSandboxQrPairing(KNOWN_CHANNELS.telegram)).toBe(false); expect(channelUsesInSandboxQrPairing(KNOWN_CHANNELS.slack)).toBe(false); + expect(channelUsesInSandboxQrPairing(KNOWN_CHANNELS.mattermost)).toBe(false); }); it("channelHasStaticToken narrows to ChannelDef with a defined envKey", () => { @@ -163,7 +186,14 @@ describe("sandbox-channels token-shape helpers", () => { describe("sandbox-channels listChannels", () => { it("materialises an array with the name merged into each entry", () => { const list = listChannels(); - expect(list.map((c) => c.name)).toEqual(["telegram", "discord", "wechat", "slack", "whatsapp"]); + expect(list.map((c) => c.name)).toEqual([ + "telegram", + "discord", + "wechat", + "slack", + "whatsapp", + "mattermost", + ]); const telegram = list.find((c) => c.name === "telegram"); expect(telegram?.envKey).toBe("TELEGRAM_BOT_TOKEN"); expect(telegram?.allowIdsMode).toBe("dm"); diff --git a/test/channels-add-generated-policy.test.ts b/test/channels-add-generated-policy.test.ts new file mode 100644 index 00000000000..145d0a68441 --- /dev/null +++ b/test/channels-add-generated-policy.test.ts @@ -0,0 +1,196 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; +import { type SpawnSyncReturns, spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, it } from "vitest"; + +const repoRoot = path.join(import.meta.dirname, ".."); + +function runScript(scriptBody: string): SpawnSyncReturns { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-generated-policy-")); + const scriptPath = path.join(tmpDir, "script.js"); + fs.writeFileSync(scriptPath, scriptBody); + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmpDir, + NEMOCLAW_NON_INTERACTIVE: "1", + NEMOCLAW_SKIP_MATTERMOST_AUTH_VALIDATION: "1", + MATTERMOST_BOT_TOKEN: "test-mattermost-token", + MATTERMOST_URL: "https://mattermost.com", + }, + timeout: 15000, + }); + fs.rmSync(tmpDir, { recursive: true, force: true }); + return result; +} + +function parseResultPayload>( + result: SpawnSyncReturns, +): T { + const marker = result.stdout.lastIndexOf("__RESULT__"); + assert.ok(marker >= 0, `no __RESULT__ marker in stdout:\n${result.stdout}`); + const payload = JSON.parse(result.stdout.slice(marker + "__RESULT__".length).trim()) as T; + assert.ok(!payload.error, `unexpected error: ${payload.error}\n${payload.stack || ""}`); + return payload; +} + +function buildPreamble(): string { + const j = (p: string) => JSON.stringify(path.join(repoRoot, "dist", "lib", p)); + return String.raw` +const resolver = require(${j("adapters/openshell/resolve.js")}); +resolver.resolveOpenshell = () => "/fake/openshell"; + +const openshellRuntime = require(${j("adapters/openshell/runtime.js")}); +openshellRuntime.runOpenshell = () => ({ status: 0, stdout: "", stderr: "" }); + +const processRecovery = require(${j("actions/sandbox/process-recovery.js")}); +processRecovery.executeSandboxExecCommand = () => ({ status: 0, stdout: "", stderr: "" }); +processRecovery.executeSandboxCommand = () => null; + +const runner = require(${j("runner.js")}); +runner.run = () => ({ status: 0, stdout: "", stderr: "" }); +runner.runCapture = () => ""; + +const gatewayRuntime = require(${j("gateway-runtime-action.js")}); +gatewayRuntime.recoverNamedGatewayRuntime = async () => ({ recovered: true }); + +const credentials = require(${j("credentials/store.js")}); +credentials.getCredential = (key) => process.env[key] || null; +credentials.saveCredential = () => true; +credentials.deleteCredential = () => true; +credentials.prompt = async (msg) => { throw new Error("unexpected prompt: " + msg); }; + +const onboard = require(${j("onboard.js")}); +onboard.isNonInteractive = () => true; + +const onboardProviders = require(${j("onboard/providers.js")}); +onboardProviders.upsertMessagingProviders = () => {}; + +const registry = require(${j("state/registry.js")}); +registry.getSandbox = () => ({ name: "test-sb", agent: "openclaw" }); +registry.updateSandbox = () => true; + +const policies = require(${j("policy/index.js")}); +const appliedCalls = []; +const appliedContentCalls = []; +const callOrder = []; +policies.listPresets = () => ["telegram", "slack", "discord", "npm", "github"].map((name) => ({ name })); +policies.applyPreset = (sandboxName, presetName) => { + appliedCalls.push({ sandboxName, presetName }); + callOrder.push("applyPreset:" + presetName); + return true; +}; +policies.applyPresetContent = (sandboxName, presetName, content, options) => { + appliedContentCalls.push({ sandboxName, presetName, content, options }); + callOrder.push("applyPresetContent:" + presetName); + return true; +}; +policies.getAppliedPresets = () => []; + +const onboardSession = require(${j("state/onboard-session.js")}); +onboardSession.loadSession = () => ({ sandboxName: "test-sb", policyPresets: [] }); +onboardSession.updateSession = (mutator) => mutator({ sandboxName: "test-sb", policyPresets: [] }); + +const origLog = console.log; +console.log = (...args) => { + const line = args.map((a) => (typeof a === "string" ? a : JSON.stringify(a))).join(" "); + if (line.includes("Change queued")) callOrder.push("promptAndRebuild"); + origLog.call(console, ...args); +}; + +const channelModule = require(${j("actions/sandbox/policy-channel.js")}); +module.exports = { channelModule, appliedCalls, appliedContentCalls, callOrder }; +`; +} + +describe("channels add generated policy templates", () => { + it("applies the generated Mattermost policy before triggering rebuild", () => { + const script = `${buildPreamble()} +const ctx = module.exports; +(async () => { + try { + await ctx.channelModule.addSandboxChannel("test-sb", { channel: "mattermost" }); + process.stdout.write("\\n__RESULT__" + JSON.stringify({ + appliedCalls: ctx.appliedCalls, + appliedContentCalls: ctx.appliedContentCalls, + callOrder: ctx.callOrder, + }) + "\\n"); + } catch (err) { + process.stdout.write("\\n__RESULT__" + JSON.stringify({ error: err.message, stack: err.stack }) + "\\n"); + } +})(); +`; + const result = runScript(script); + assert.equal(result.status, 0, `script failed: ${result.stderr}\n${result.stdout}`); + const payload = parseResultPayload<{ + appliedCalls: unknown[]; + appliedContentCalls: Array<{ + sandboxName: string; + presetName: string; + content: string; + options: unknown; + }>; + callOrder: string[]; + }>(result); + + assert.deepEqual(payload.appliedCalls, []); + assert.equal(payload.appliedContentCalls.length, 1); + assert.equal(payload.appliedContentCalls[0].sandboxName, "test-sb"); + assert.equal(payload.appliedContentCalls[0].presetName, "mattermost"); + assert.deepEqual(payload.appliedContentCalls[0].options, { + custom: { sourcePath: "messaging:mattermost" }, + }); + assert.match(payload.appliedContentCalls[0].content, /host: mattermost\.com/); + assert.match(payload.appliedContentCalls[0].content, /port: 443/); + + const applyIdx = payload.callOrder.indexOf("applyPresetContent:mattermost"); + const rebuildIdx = payload.callOrder.indexOf("promptAndRebuild"); + assert.ok(applyIdx >= 0, `applyPresetContent was never called: ${payload.callOrder}`); + assert.ok(rebuildIdx >= 0, `promptAndRebuild was never called: ${payload.callOrder}`); + assert.ok(applyIdx < rebuildIdx, `generated policy applied too late: ${payload.callOrder}`); + }); +}); + +describe("channel preset source-of-truth", () => { + it("every known channel ships a preset YAML or generated policy template", () => { + const { knownChannelNames } = require( + path.join(repoRoot, "dist", "lib", "sandbox", "channels.js"), + ) as { knownChannelNames: () => string[] }; + const { loadPreset, parsePresetPolicyKeys } = require( + path.join(repoRoot, "dist", "lib", "policy", "index.js"), + ) as { + loadPreset: (name: string) => string | null; + parsePresetPolicyKeys: (content: string | null | undefined) => string[]; + }; + const { listBuiltInMessagingChannelManifests } = require( + path.join(repoRoot, "dist", "lib", "messaging", "channels", "index.js"), + ) as { + listBuiltInMessagingChannelManifests: () => Array<{ + id: string; + policyTemplates?: readonly unknown[]; + }>; + }; + const generatedPolicyChannels = new Set( + listBuiltInMessagingChannelManifests() + .filter((manifest) => (manifest.policyTemplates?.length ?? 0) > 0) + .map((manifest) => manifest.id), + ); + const failures: string[] = []; + for (const name of knownChannelNames()) { + if (generatedPolicyChannels.has(name)) continue; + const content = loadPreset(name); + const keys = parsePresetPolicyKeys(content); + if (content === null || keys.length === 0) { + failures.push(name); + } + } + assert.deepEqual(failures, []); + }); +}); diff --git a/test/channels-add-preset.test.ts b/test/channels-add-preset.test.ts index 15b1f7bcf78..277c04b9da4 100644 --- a/test/channels-add-preset.test.ts +++ b/test/channels-add-preset.test.ts @@ -56,10 +56,10 @@ function parseResultPayload = Record> // Build a preamble that: // - stubs every module touched by addSandboxChannel so no real openshell, // gateway, or filesystem credential write happens -// - records every policies.applyPreset call in `appliedCalls` -// - records the relative order of applyPreset vs promptAndRebuild via +// - records every policy apply call +// - records the relative order of policy application vs promptAndRebuild via // a console.log marker, so the test can assert the ordering invariant -// (apply MUST precede rebuild) +// (policy MUST precede rebuild) function buildPreamble({ presetNamesAvailable = ["telegram", "slack", "discord", "npm", "github"], applyPresetResult = true, @@ -307,7 +307,7 @@ const ctx = module.exports; isInteractive: false, configuredChannels: ["slack"], disabledChannels: [], - supportedChannelIds: ["telegram", "discord", "wechat", "slack", "whatsapp"], + supportedChannelIds: ["telegram", "discord", "wechat", "slack", "whatsapp", "mattermost"], }, ]); }); @@ -1836,36 +1836,3 @@ global.__testLog = ""; ); }); }); - -describe("channel preset source-of-truth", () => { - it("every channel registered in KNOWN_CHANNELS ships a preset YAML that parsePresetPolicyKeys() accepts", () => { - const { knownChannelNames } = require( - path.join(repoRoot, "dist", "lib", "sandbox", "channels.js"), - ) as { - knownChannelNames: () => string[]; - }; - const { loadPreset, parsePresetPolicyKeys } = require( - path.join(repoRoot, "dist", "lib", "policy", "index.js"), - ) as { - loadPreset: (name: string) => string | null; - parsePresetPolicyKeys: (content: string | null | undefined) => string[]; - }; - const failures: string[] = []; - for (const name of knownChannelNames()) { - const content = loadPreset(name); - if (content === null) { - failures.push(`${name}: preset YAML not found on disk`); - continue; - } - const keys = parsePresetPolicyKeys(content); - if (keys.length === 0) { - failures.push(`${name}: parsePresetPolicyKeys returned no entries`); - } - } - assert.deepEqual( - failures, - [], - `every channel in KNOWN_CHANNELS must ship a parseable preset YAML; failures: ${failures.join("; ")}`, - ); - }); -}); diff --git a/test/sandbox-provider-cleanup.test.ts b/test/sandbox-provider-cleanup.test.ts index f301ebd9b37..41d72eeaccd 100644 --- a/test/sandbox-provider-cleanup.test.ts +++ b/test/sandbox-provider-cleanup.test.ts @@ -38,6 +38,7 @@ describe("SANDBOX_PROVIDER_SUFFIXES", () => { "wechat-bridge", "slack-bridge", "slack-app", + "mattermost-bridge", "brave-search", ].sort(), ); From 75b08a8995a402491b4d784657d2a640648ce5f4 Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 23 Jun 2026 00:46:37 +0700 Subject: [PATCH 02/12] refactor(onboard): move generated policy apply into selection --- src/lib/onboard.ts | 17 ++--------------- src/lib/onboard/policy-selection.ts | 9 +++++++++ 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index a5f979ed4f9..dd341a9b5c7 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -115,8 +115,6 @@ const { const { syncPresetSelection, }: typeof import("./onboard/policy-preset-sync") = require("./onboard/policy-preset-sync"); -const messagingPolicyTemplates: typeof import("./onboard/messaging-policy-templates") = - require("./onboard/messaging-policy-templates"); const { maybeForceE2eStepFailure, }: typeof import("./onboard/e2e-failure-injection") = require("./onboard/e2e-failure-injection"); @@ -4596,8 +4594,7 @@ async function setupPoliciesWithSelection( sandboxName: string, options: SetupPolicySelectionOptions = {}, ) { - let reconciledLivePolicy = false; - const result = await setupPoliciesWithSelectionImpl( + return setupPoliciesWithSelectionImpl( { policies, tiers, @@ -4615,18 +4612,8 @@ async function setupPoliciesWithSelection( env: process.env, }, sandboxName, - { - ...options, - onSelection: (policyPresets) => { - reconciledLivePolicy = true; - options.onSelection?.(policyPresets); - }, - }, + options, ); - if (reconciledLivePolicy) { - messagingPolicyTemplates.applyGeneratedMessagingPolicyTemplatesFromRegistry(sandboxName); - } - return result; } const { diff --git a/src/lib/onboard/policy-selection.ts b/src/lib/onboard/policy-selection.ts index 6102f147ad3..06d2ab7fb08 100644 --- a/src/lib/onboard/policy-selection.ts +++ b/src/lib/onboard/policy-selection.ts @@ -46,6 +46,12 @@ type TiersApi = { getTier(tierName: string): unknown; }; +function applyGeneratedMessagingPolicyTemplatesFromRegistry(sandboxName: string): void { + const messagingPolicyTemplates: typeof import("./messaging-policy-templates") = + require("./messaging-policy-templates"); + messagingPolicyTemplates.applyGeneratedMessagingPolicyTemplatesFromRegistry(sandboxName); +} + export type SetupPresetSuggestionOptions = { enabledChannels?: string[] | null; webSearchConfig?: WebSearchConfig | null; @@ -373,6 +379,7 @@ async function setupPoliciesWithSelectionInner( } deps.note(` [resume] Reapplying policy presets: ${resumeSelection.join(", ")}`); deps.syncPresetSelection(sandboxName, currentAppliedPresets, resumeSelection); + applyGeneratedMessagingPolicyTemplatesFromRegistry(sandboxName); return resumeSelection; } @@ -464,6 +471,7 @@ async function setupPoliciesWithSelectionInner( } deps.note(` [non-interactive] Applying policy presets: ${chosen.join(", ")}`); deps.syncPresetSelection(sandboxName, currentAppliedPresets, chosen); + applyGeneratedMessagingPolicyTemplatesFromRegistry(sandboxName); return chosen; } @@ -499,5 +507,6 @@ async function setupPoliciesWithSelectionInner( const accessByName: Record = {}; for (const preset of resolvedPresets) accessByName[preset.name] = preset.access; deps.syncPresetSelection(sandboxName, currentAppliedPresets, interactiveChoice, accessByName); + applyGeneratedMessagingPolicyTemplatesFromRegistry(sandboxName); return interactiveChoice; } From 7a6e0b2d8d6d1794c7a88f88007bb5874066bc6a Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 23 Jun 2026 15:22:19 +0700 Subject: [PATCH 03/12] fix(messaging): address Mattermost review feedback --- src/lib/messaging/channels/manifests.test.ts | 2 +- .../mattermost/hooks/reachability.test.ts | 44 ++++++++++++ .../channels/mattermost/hooks/reachability.ts | 27 +++++++- .../messaging/channels/mattermost/manifest.ts | 1 + .../compiler/manifest-compiler.test.ts | 14 ++-- src/lib/onboard/policy-selection.ts | 5 ++ test/channels-add-generated-policy.test.ts | 16 ++--- test/policy-tiers-onboard.test.ts | 67 ++++++++++++++++++- 8 files changed, 153 insertions(+), 23 deletions(-) diff --git a/src/lib/messaging/channels/manifests.test.ts b/src/lib/messaging/channels/manifests.test.ts index db0d10af4be..d0324ea3dc2 100644 --- a/src/lib/messaging/channels/manifests.test.ts +++ b/src/lib/messaging/channels/manifests.test.ts @@ -737,7 +737,7 @@ describe("built-in channel manifests", () => { }); expect(renderJson(mattermostManifest)).not.toContain('"path":"mattermost"'); expect(renderJson(mattermostManifest)).not.toContain('"path":"platforms.mattermost"'); - expect("agentPackages" in mattermostManifest).toBe(false); + expect(mattermostManifest.agentPackages).toEqual([]); expectTokenPasteEnrollHook(mattermostManifest, ["botToken"]); expectConfigPromptEnrollHook(mattermostManifest, [ "baseUrl", diff --git a/src/lib/messaging/channels/mattermost/hooks/reachability.test.ts b/src/lib/messaging/channels/mattermost/hooks/reachability.test.ts index 6b2c86f108c..254a2519bcc 100644 --- a/src/lib/messaging/channels/mattermost/hooks/reachability.test.ts +++ b/src/lib/messaging/channels/mattermost/hooks/reachability.test.ts @@ -130,6 +130,50 @@ describe("Mattermost reachability hook implementation", () => { ]); }); + it.each([ + ["relative URL", "chat.example.com", "requires an absolute http:// or https:// baseUrl"], + ["non-http scheme", "ftp://chat.example.com", "baseUrl must use http:// or https://"], + [ + "embedded credentials", + "https://bot:token@chat.example.com", + "baseUrl must not include credentials", + ], + [ + "query string", + "https://chat.example.com?team=dev", + "baseUrl must not include query strings or fragments", + ], + [ + "fragment", + "https://chat.example.com#main", + "baseUrl must not include query strings or fragments", + ], + ])("rejects unsafe Mattermost base URLs before fetching: %s", async (_name, baseUrl, error) => { + const urls: string[] = []; + const registry = new MessagingHookRegistry([ + { + id: MATTERMOST_REACHABILITY_HOOK_HANDLER_ID, + handler: createMattermostReachabilityHook({ + fetch: async (url) => { + urls.push(url); + throw new Error("fetch should not run"); + }, + }), + }, + ]); + + await expect( + runMessagingHook(MATTERMOST_REACHABILITY_HOOK, registry, { + channelId: "mattermost", + inputs: { + botToken: "mattermost-token", + baseUrl, + }, + }), + ).rejects.toThrow(error); + expect(urls).toEqual([]); + }); + it("honors the explicit skip env without calling Mattermost", async () => { const urls: string[] = []; const registry = new MessagingHookRegistry([ diff --git a/src/lib/messaging/channels/mattermost/hooks/reachability.ts b/src/lib/messaging/channels/mattermost/hooks/reachability.ts index 2557167aacb..f2684bd61f7 100644 --- a/src/lib/messaging/channels/mattermost/hooks/reachability.ts +++ b/src/lib/messaging/channels/mattermost/hooks/reachability.ts @@ -43,13 +43,14 @@ export function createMattermostReachabilityHook( } const token = normalizeInput(context.inputs?.botToken); - const baseUrl = normalizeMattermostBaseUrl(normalizeInput(context.inputs?.baseUrl)); + const rawBaseUrl = normalizeInput(context.inputs?.baseUrl); if (!token) { throw new Error("Mattermost reachability check requires botToken."); } - if (!baseUrl) { + if (!rawBaseUrl) { throw new Error("Mattermost reachability check requires baseUrl."); } + const baseUrl = normalizeMattermostBaseUrl(rawBaseUrl); const log = options.log ?? console.log; const response = await fetchMattermostMe({ baseUrl, token }, options).catch((error) => { @@ -153,7 +154,27 @@ async function fetchWithTimeout( } function normalizeMattermostBaseUrl(value: string): string { - return value.replace(/\/+$/g, "").replace(/\/api\/v4$/i, ""); + let url: URL; + try { + url = new URL(value); + } catch { + throw new Error( + "Mattermost reachability check requires an absolute http:// or https:// baseUrl.", + ); + } + if (url.protocol !== "http:" && url.protocol !== "https:") { + throw new Error("Mattermost reachability check baseUrl must use http:// or https://."); + } + if (url.username || url.password) { + throw new Error("Mattermost reachability check baseUrl must not include credentials."); + } + if (url.search || url.hash) { + throw new Error( + "Mattermost reachability check baseUrl must not include query strings or fragments.", + ); + } + const basePath = url.pathname.replace(/\/+$/g, "").replace(/\/api\/v4$/i, ""); + return `${url.origin}${basePath}`; } function normalizeInput(value: unknown): string { diff --git a/src/lib/messaging/channels/mattermost/manifest.ts b/src/lib/messaging/channels/mattermost/manifest.ts index 84c2662edb6..5c234571bad 100644 --- a/src/lib/messaging/channels/mattermost/manifest.ts +++ b/src/lib/messaging/channels/mattermost/manifest.ts @@ -143,6 +143,7 @@ export const mattermostManifest = { }, }, }, + agentPackages: [], state: { persist: { mattermostConfig: ["baseUrl", "allowedChannels", "requireMention"], diff --git a/src/lib/messaging/compiler/manifest-compiler.test.ts b/src/lib/messaging/compiler/manifest-compiler.test.ts index ebf4e113c15..ae7bbfa7203 100644 --- a/src/lib/messaging/compiler/manifest-compiler.test.ts +++ b/src/lib/messaging/compiler/manifest-compiler.test.ts @@ -18,6 +18,10 @@ import { ManifestCompiler } from "./manifest-compiler"; const ALL_CHANNELS = ["telegram", "discord", "wechat", "slack", "whatsapp", "mattermost"] as const; const HERMES_CHANNELS = ["telegram", "discord", "wechat", "slack", "whatsapp"] as const; +type JsonRenderPlan = Extract< + SandboxMessagingPlan["agentRender"][number], + { kind: "json-fragment" } +>; const TEST_CREDENTIALS: Readonly> = { TELEGRAM_BOT_TOKEN: "123456:test-telegram-token", DISCORD_BOT_TOKEN: "test-discord-token", @@ -264,9 +268,6 @@ describe("ManifestCompiler", () => { (render) => render.channelId === "mattermost" && render.renderId === "mattermost-openclaw-channel", ); - if (mattermostRender?.kind !== "json-fragment") { - throw new Error("missing Mattermost OpenClaw json-fragment render"); - } expect(mattermostRender).toMatchObject({ kind: "json-fragment", path: "channels.mattermost", @@ -283,12 +284,13 @@ describe("ManifestCompiler", () => { }, }, }); - expect(mattermostRender?.value).toMatchObject({ + const mattermostRenderValue = (mattermostRender as JsonRenderPlan | undefined)?.value; + expect(mattermostRenderValue).toMatchObject({ allowFrom: ["user-a", "user-b"], groupAllowFrom: ["user-a", "user-b"], }); - expect(mattermostRender?.value).toHaveProperty("groups"); - expect((mattermostRender?.value as { groups?: unknown } | undefined)?.groups).toEqual({ + expect(mattermostRenderValue).toHaveProperty("groups"); + expect((mattermostRenderValue as { groups?: unknown } | undefined)?.groups).toEqual({ "town-square": { requireMention: true, }, diff --git a/src/lib/onboard/policy-selection.ts b/src/lib/onboard/policy-selection.ts index 06d2ab7fb08..37b2904226d 100644 --- a/src/lib/onboard/policy-selection.ts +++ b/src/lib/onboard/policy-selection.ts @@ -405,6 +405,11 @@ async function setupPoliciesWithSelectionInner( if (policyMode === "skip" || policyMode === "none" || policyMode === "no") { deps.note(" [non-interactive] Skipping policy presets."); + if (!deps.waitForSandboxReady(sandboxName)) { + console.error(` Sandbox '${sandboxName}' was not ready for policy application.`); + process.exit(1); + } + applyGeneratedMessagingPolicyTemplatesFromRegistry(sandboxName); return []; } diff --git a/test/channels-add-generated-policy.test.ts b/test/channels-add-generated-policy.test.ts index 145d0a68441..47a4afb1c72 100644 --- a/test/channels-add-generated-policy.test.ts +++ b/test/channels-add-generated-policy.test.ts @@ -18,7 +18,6 @@ function runScript(scriptBody: string): SpawnSyncReturns { cwd: repoRoot, encoding: "utf-8", env: { - ...process.env, HOME: tmpDir, NEMOCLAW_NON_INTERACTIVE: "1", NEMOCLAW_SKIP_MATTERMOST_AUTH_VALIDATION: "1", @@ -182,15 +181,12 @@ describe("channel preset source-of-truth", () => { .filter((manifest) => (manifest.policyTemplates?.length ?? 0) > 0) .map((manifest) => manifest.id), ); - const failures: string[] = []; - for (const name of knownChannelNames()) { - if (generatedPolicyChannels.has(name)) continue; - const content = loadPreset(name); - const keys = parsePresetPolicyKeys(content); - if (content === null || keys.length === 0) { - failures.push(name); - } - } + const failures = knownChannelNames() + .filter((name) => !generatedPolicyChannels.has(name)) + .map((name) => ({ name, content: loadPreset(name) })) + .map(({ name, content }) => ({ name, content, keys: parsePresetPolicyKeys(content) })) + .filter(({ content, keys }) => content === null || keys.length === 0) + .map(({ name }) => name); assert.deepEqual(failures, []); }); }); diff --git a/test/policy-tiers-onboard.test.ts b/test/policy-tiers-onboard.test.ts index f94b6a3f480..595b05dac73 100644 --- a/test/policy-tiers-onboard.test.ts +++ b/test/policy-tiers-onboard.test.ts @@ -5,7 +5,7 @@ // Verifies that selectPolicyTier and setupPoliciesWithSelection wire correctly. import assert from "node:assert/strict"; -import { spawnSync, type SpawnSyncReturns } from "node:child_process"; +import { type SpawnSyncReturns, spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -413,9 +413,62 @@ console.log = (...args) => lines.push(args.join(" ")); buildPreamble({ tierEnv: "open", policyMode: "skip" }) + String.raw` const policies = require(${policiesPath}); +const generatedPolicyContent = "preset:\n name: mattermost\nnetwork_policies:\n mattermost: {}\n"; +const appliedContentCalls = []; policies.applyPreset = () => {}; policies.applyPresets = () => true; +policies.applyPresetContent = (sandboxName, presetName, content, options) => { + appliedContentCalls.push({ sandboxName, presetName, content, options }); + return true; +}; policies.getAppliedPresets = () => []; +registry.getSandbox = () => ({ + name: "test-sb", + model: null, + provider: null, + messaging: { + schemaVersion: 1, + plan: { + schemaVersion: 1, + sandboxName: "test-sb", + agent: "openclaw", + workflow: "onboard", + channels: [ + { + channelId: "mattermost", + displayName: "Mattermost", + authMode: "token-paste", + active: true, + selected: true, + configured: true, + disabled: false, + inputs: [], + hooks: [], + }, + ], + disabledChannels: [], + credentialBindings: [], + networkPolicy: { + presets: [], + entries: [], + templates: [ + { + channelId: "mattermost", + presetName: "mattermost", + templateFile: "mattermost.yaml", + sourceInput: "baseUrl", + policyKeys: ["mattermost"], + content: generatedPolicyContent, + }, + ], + }, + agentRender: [], + buildSteps: [], + stateUpdates: [], + healthChecks: [], + }, + }, +}); const lines = []; const origLog = console.log; @@ -425,10 +478,10 @@ console.log = (...args) => lines.push(args.join(" ")); try { const applied = await setupPoliciesWithSelection("test-sb", {}); console.log = origLog; - origLog(JSON.stringify({ applied, updates })); + origLog(JSON.stringify({ applied, updates, appliedContentCalls })); } catch (err) { console.log = origLog; - origLog(JSON.stringify({ error: err.message, updates })); + origLog(JSON.stringify({ error: err.message, updates, appliedContentCalls })); } })(); `; @@ -447,6 +500,14 @@ console.log = (...args) => lines.push(args.join(" ")); assert.equal(tierUpdate.policyTier, "open"); // With POLICY_MODE=skip, applied presets list is empty assert.deepEqual(payload.applied, []); + assert.deepEqual(payload.appliedContentCalls, [ + { + sandboxName: "test-sb", + presetName: "mattermost", + content: "preset:\n name: mattermost\nnetwork_policies:\n mattermost: {}\n", + options: { custom: { sourcePath: "messaging:mattermost" } }, + }, + ]); }); it("omits Brave from policy preset selection when web search is unsupported", () => { From 0a8cf7444b1c05ee39a089d7c26059bf624a861d Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 23 Jun 2026 15:43:06 +0700 Subject: [PATCH 04/12] test(onboard): stub OpenShell in policy skip test --- test/policy-tiers-onboard.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/policy-tiers-onboard.test.ts b/test/policy-tiers-onboard.test.ts index 595b05dac73..2d21b4a79ea 100644 --- a/test/policy-tiers-onboard.test.ts +++ b/test/policy-tiers-onboard.test.ts @@ -410,7 +410,12 @@ console.log = (...args) => lines.push(args.join(" ")); it("selected tier is persisted to the registry via updateSandbox({ policyTier })", () => { const policiesPath = JSON.stringify(path.join(repoRoot, "dist", "lib", "policy", "index.js")); const script = - buildPreamble({ tierEnv: "open", policyMode: "skip" }) + + buildPreamble({ + tierEnv: "open", + policyMode: "skip", + stubOpenshellBin: true, + runCaptureReturn: "Running", + }) + String.raw` const policies = require(${policiesPath}); const generatedPolicyContent = "preset:\n name: mattermost\nnetwork_policies:\n mattermost: {}\n"; From 48dd3f44067a86addd81420b82f7cc5fa4fa8877 Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 23 Jun 2026 17:04:18 +0700 Subject: [PATCH 05/12] fix(messaging): align Mattermost manifest shape --- src/lib/messaging/channels/manifests.test.ts | 1 + src/lib/messaging/channels/mattermost/manifest.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/src/lib/messaging/channels/manifests.test.ts b/src/lib/messaging/channels/manifests.test.ts index d0324ea3dc2..4b1f37d8763 100644 --- a/src/lib/messaging/channels/manifests.test.ts +++ b/src/lib/messaging/channels/manifests.test.ts @@ -709,6 +709,7 @@ describe("built-in channel manifests", () => { placeholder: "openshell:resolve:env:MATTERMOST_BOT_TOKEN", }, ]); + expect(mattermostManifest.policyPresets).toEqual([]); expect(policyPresetNames(mattermostManifest)).toEqual([]); expect(policyTemplateNames(mattermostManifest)).toEqual(["mattermost"]); expect(mattermostManifest.policyTemplates).toEqual([ diff --git a/src/lib/messaging/channels/mattermost/manifest.ts b/src/lib/messaging/channels/mattermost/manifest.ts index 5c234571bad..f2849583982 100644 --- a/src/lib/messaging/channels/mattermost/manifest.ts +++ b/src/lib/messaging/channels/mattermost/manifest.ts @@ -86,6 +86,7 @@ export const mattermostManifest = { placeholder: "openshell:resolve:env:MATTERMOST_BOT_TOKEN", }, ], + policyPresets: [], policyTemplates: [ { name: "mattermost", From 1f6b5e61f5653116c590823251ce3872927ce593 Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 23 Jun 2026 22:51:54 +0700 Subject: [PATCH 06/12] fix(messaging): route mattermost fetches through trusted proxy --- .../policies/templates/mattermost.yaml | 4 - src/lib/messaging/channels/manifests.test.ts | 6 +- .../messaging/channels/mattermost/manifest.ts | 14 +- .../runtime/mattermost-trusted-env-proxy.ts | 159 ++++++++++++++++++ .../engines/policy-template-renderer.test.ts | 4 +- .../compiler/manifest-compiler.test.ts | 9 +- test/mattermost-trusted-env-proxy.test.ts | 134 +++++++++++++++ 7 files changed, 313 insertions(+), 17 deletions(-) create mode 100644 src/lib/messaging/channels/mattermost/runtime/mattermost-trusted-env-proxy.ts create mode 100644 test/mattermost-trusted-env-proxy.test.ts diff --git a/nemoclaw-blueprint/policies/templates/mattermost.yaml b/nemoclaw-blueprint/policies/templates/mattermost.yaml index 1550d3e3dc1..6da11322d77 100644 --- a/nemoclaw-blueprint/policies/templates/mattermost.yaml +++ b/nemoclaw-blueprint/policies/templates/mattermost.yaml @@ -21,10 +21,6 @@ network_policies: enforcement: enforce request_body_credential_rewrite: true websocket_credential_rewrite: true - allowed_ips: - - 10.0.0.0/8 - - 172.16.0.0/12 - - 192.168.0.0/16 rules: - allow: { method: GET, path: "{{url.basePath}}/api/v4/websocket" } - allow: { method: WEBSOCKET_TEXT, path: "{{url.basePath}}/api/v4/websocket" } diff --git a/src/lib/messaging/channels/manifests.test.ts b/src/lib/messaging/channels/manifests.test.ts index 4b1f37d8763..7566ed70aa1 100644 --- a/src/lib/messaging/channels/manifests.test.ts +++ b/src/lib/messaging/channels/manifests.test.ts @@ -730,12 +730,11 @@ describe("built-in channel manifests", () => { expect(findRender(mattermostManifest, "mattermost-openclaw-channel")).toMatchObject({ fragment: { value: { - network: { - dangerouslyAllowPrivateNetwork: true, - }, + enabled: true, }, }, }); + expect(renderJson(mattermostManifest)).not.toContain("dangerouslyAllowPrivateNetwork"); expect(renderJson(mattermostManifest)).not.toContain('"path":"mattermost"'); expect(renderJson(mattermostManifest)).not.toContain('"path":"platforms.mattermost"'); expect(mattermostManifest.agentPackages).toEqual([]); @@ -754,6 +753,7 @@ describe("built-in channel manifests", () => { onFailure: "skip-channel", }); expectOpenClawRuntimeVisibility(mattermostManifest, ["mattermost"], ["mattermost"]); + expectOpenClawNodePreload(mattermostManifest, "mattermost-trusted-env-proxy"); expect(mattermostManifest.state).toEqual({ persist: { mattermostConfig: ["baseUrl", "allowedChannels", "requireMention"], diff --git a/src/lib/messaging/channels/mattermost/manifest.ts b/src/lib/messaging/channels/mattermost/manifest.ts index f2849583982..8cc7168f1ed 100644 --- a/src/lib/messaging/channels/mattermost/manifest.ts +++ b/src/lib/messaging/channels/mattermost/manifest.ts @@ -116,9 +116,6 @@ export const mattermostManifest = { groupAllowFrom: "{{allowedIds.mattermost.values}}", chatmode: "{{mattermostConfig.openclawChatmode}}", groups: "{{mattermostConfig.openclawGroups}}", - network: { - dangerouslyAllowPrivateNetwork: true, - }, }, }, }, @@ -142,6 +139,17 @@ export const mattermostManifest = { configKeys: ["mattermost"], logPatterns: ["mattermost"], }, + nodePreloads: [ + { + module: "mattermost-trusted-env-proxy", + injectInto: ["boot", "connect"], + optional: false, + installMessage: + "[channels] Installing Mattermost trusted env-proxy guard (SSRF-preserving DNS delegation)", + installedMessage: + "[channels] Mattermost trusted env-proxy guard installed (NODE_OPTIONS updated)", + }, + ], }, }, agentPackages: [], diff --git a/src/lib/messaging/channels/mattermost/runtime/mattermost-trusted-env-proxy.ts b/src/lib/messaging/channels/mattermost/runtime/mattermost-trusted-env-proxy.ts new file mode 100644 index 00000000000..57db7250214 --- /dev/null +++ b/src/lib/messaging/channels/mattermost/runtime/mattermost-trusted-env-proxy.ts @@ -0,0 +1,159 @@ +// @ts-nocheck +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// Mattermost's upstream OpenClaw extension calls fetchWithSsrFGuard in strict +// mode. In OpenShell/NemoClaw sandboxes, strict mode can fail before proxy +// egress because local DNS resolution is intentionally unavailable for some +// operator-routed hosts. Patch only the Mattermost guarded fetch call sites to +// keep hostname SSRF checks while delegating DNS resolution to the trusted env +// proxy. + +(function () { + "use strict"; + + var PATCH_MARKER = "__nemoclawMattermostTrustedEnvProxyPatchInstalled"; + var MODE_PROPERTY = 'mode: "trusted_env_proxy",'; + var AUDIT_CONTEXTS = ["mattermost-api", "mattermost-probe"]; + + if (process[PATCH_MARKER]) return; + try { + Object.defineProperty(process, PATCH_MARKER, { value: true }); + } catch (_e) { + process[PATCH_MARKER] = true; + } + + function isOpenClawDistFile(filename) { + var normalized = String(filename || "").replace(/\\/g, "/"); + return normalized.indexOf("/openclaw/dist/") !== -1 && normalized.endsWith(".js"); + } + + function countMatches(source, pattern) { + var count = 0; + var match; + pattern.lastIndex = 0; + while ((match = pattern.exec(source)) !== null) count += 1; + return count; + } + + function patchAuditContext(source, filename, context) { + var auditPattern = new RegExp("auditContext\\s*:\\s*[\"']" + context + "[\"']", "g"); + var matches = countMatches(source, auditPattern); + if (matches === 0) return source; + if (matches > 1) { + throw new Error( + "OpenClaw Mattermost trusted env-proxy patch shape not recognized in " + + filename + + "; expected one " + + context + + " audit context", + ); + } + + auditPattern.lastIndex = 0; + var match = auditPattern.exec(source); + if (!match) return source; + + var auditIndex = match.index; + var callStart = source.lastIndexOf("fetchWithSsrFGuard({", auditIndex); + if (callStart === -1) { + throw new Error( + "OpenClaw Mattermost trusted env-proxy patch shape not recognized in " + + filename + + "; expected fetchWithSsrFGuard object before " + + context, + ); + } + + var prefix = source.slice(callStart, auditIndex); + var existingMode = prefix.match(/mode\s*:\s*["']([^"']+)["']/); + if (existingMode) { + if (existingMode[1] === "trusted_env_proxy") return source; + throw new Error( + "OpenClaw Mattermost trusted env-proxy patch found unexpected guarded-fetch mode in " + + filename + + " for " + + context, + ); + } + + if (prefix.indexOf("policy:") !== -1) { + throw new Error( + "OpenClaw Mattermost trusted env-proxy patch shape not recognized in " + + filename + + "; expected policy after auditContext for " + + context, + ); + } + + var lineStart = source.lastIndexOf("\n", auditIndex) + 1; + var indentMatch = source.slice(lineStart, auditIndex).match(/^\s*/); + var indent = indentMatch ? indentMatch[0] : ""; + return source.slice(0, auditIndex) + indent + MODE_PROPERTY + "\n" + source.slice(auditIndex); + } + + function patchMattermostGuardedFetchSource(source, filename) { + var next = source; + for (var i = 0; i < AUDIT_CONTEXTS.length; i++) { + next = patchAuditContext(next, filename, AUDIT_CONTEXTS[i]); + } + return next; + } + + function fileNameFromModuleUrl(urlValue) { + if (typeof urlValue !== "string" || !urlValue.startsWith("file:")) return ""; + try { + return require("url").fileURLToPath(urlValue); + } catch (_e) { + return ""; + } + } + + function sourceToText(source) { + if (typeof source === "string") return source; + if (typeof Buffer !== "undefined") { + if (Buffer.isBuffer(source)) return source.toString("utf8"); + if (source instanceof Uint8Array) return Buffer.from(source).toString("utf8"); + if (source instanceof ArrayBuffer) return Buffer.from(source).toString("utf8"); + } + return null; + } + + function installPatch() { + var Module = require("module"); + var fs = require("fs"); + var originalJsLoader = Module._extensions && Module._extensions[".js"]; + if (typeof originalJsLoader === "function") { + Module._extensions[".js"] = function nemoclawMattermostTrustedEnvProxyJsLoader( + mod, + filename, + ) { + if (isOpenClawDistFile(filename)) { + var source = fs.readFileSync(filename, "utf8"); + var patched = patchMattermostGuardedFetchSource(source, filename); + if (patched !== source) { + return mod._compile(patched, filename); + } + } + return originalJsLoader.apply(this, arguments); + }; + } + + if (typeof Module.registerHooks === "function") { + Module.registerHooks({ + load: function nemoclawMattermostTrustedEnvProxyLoadHook(urlValue, context, nextLoad) { + var result = nextLoad(urlValue, context); + var filename = fileNameFromModuleUrl(urlValue); + if (!isOpenClawDistFile(filename)) return result; + var sourceText = sourceToText(result && result.source); + if (sourceText === null) return result; + var patched = patchMattermostGuardedFetchSource(sourceText, filename); + if (patched === sourceText) return result; + return Object.assign({}, result, { source: patched }); + }, + }); + } + } + + installPatch(); +})(); diff --git a/src/lib/messaging/compiler/engines/policy-template-renderer.test.ts b/src/lib/messaging/compiler/engines/policy-template-renderer.test.ts index 06399b16cbe..a418a4d2047 100644 --- a/src/lib/messaging/compiler/engines/policy-template-renderer.test.ts +++ b/src/lib/messaging/compiler/engines/policy-template-renderer.test.ts @@ -20,8 +20,6 @@ function input(value: string): SandboxMessagingInputReference { } describe("policy template renderer", () => { - const PRIVATE_NETWORK_RANGES = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"]; - it("normalizes HTTP and HTTPS URL sources for self-hosted policy templates", () => { expect(renderTemplateUrlContext("https://chat.example.com/api/v4/", "https-url")).toEqual({ host: "chat.example.com", @@ -81,7 +79,6 @@ describe("policy template renderer", () => { enforcement: "enforce", request_body_credential_rewrite: true, websocket_credential_rewrite: true, - allowed_ips: PRIVATE_NETWORK_RANGES, rules: [ { allow: { method: "GET", path: "/team/api/v4/websocket" } }, { allow: { method: "WEBSOCKET_TEXT", path: "/team/api/v4/websocket" } }, @@ -93,6 +90,7 @@ describe("policy template renderer", () => { ], }), ]); + expect(policy.endpoints[0]).not.toHaveProperty("allowed_ips"); expect(policy.endpoints[0]).not.toHaveProperty("access"); expect(policy.endpoints[0]).not.toHaveProperty("tls"); expect(policy.binaries).toEqual([{ path: "/usr/local/bin/node" }, { path: "/usr/bin/node" }]); diff --git a/src/lib/messaging/compiler/manifest-compiler.test.ts b/src/lib/messaging/compiler/manifest-compiler.test.ts index ae7bbfa7203..94a1f4cd6f0 100644 --- a/src/lib/messaging/compiler/manifest-compiler.test.ts +++ b/src/lib/messaging/compiler/manifest-compiler.test.ts @@ -233,8 +233,11 @@ describe("ManifestCompiler", () => { enforcement: "enforce", request_body_credential_rewrite: true, websocket_credential_rewrite: true, - allowed_ips: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"], }); + expect( + YAML.parse(plan.networkPolicy.templates?.[0]?.content ?? "").network_policies.mattermost + .endpoints[0], + ).not.toHaveProperty("allowed_ips"); expect( YAML.parse(plan.networkPolicy.templates?.[0]?.content ?? "").network_policies.mattermost .endpoints[0].rules, @@ -272,9 +275,6 @@ describe("ManifestCompiler", () => { kind: "json-fragment", path: "channels.mattermost", value: { - network: { - dangerouslyAllowPrivateNetwork: true, - }, allowFrom: ["user-a", "user-b"], groupAllowFrom: ["user-a", "user-b"], groups: { @@ -289,6 +289,7 @@ describe("ManifestCompiler", () => { allowFrom: ["user-a", "user-b"], groupAllowFrom: ["user-a", "user-b"], }); + expect(mattermostRenderValue).not.toHaveProperty("network"); expect(mattermostRenderValue).toHaveProperty("groups"); expect((mattermostRenderValue as { groups?: unknown } | undefined)?.groups).toEqual({ "town-square": { diff --git a/test/mattermost-trusted-env-proxy.test.ts b/test/mattermost-trusted-env-proxy.test.ts new file mode 100644 index 00000000000..53f470c26b2 --- /dev/null +++ b/test/mattermost-trusted-env-proxy.test.ts @@ -0,0 +1,134 @@ +// @ts-nocheck +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +const PRELOAD_PATH = path.join( + import.meta.dirname, + "..", + "src", + "lib", + "messaging", + "channels", + "mattermost", + "runtime", + "mattermost-trusted-env-proxy.ts", +); + +function runDriver(driverBody: string) { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mattermost-proxy-")); + const driverPath = path.join(tmpDir, "driver.js"); + try { + fs.writeFileSync(driverPath, driverBody); + return spawnSync(process.execPath, [driverPath], { + encoding: "utf-8", + env: { + PATH: process.env.PATH || "/usr/bin:/bin", + PRELOAD_PATH, + TEST_ROOT: tmpDir, + }, + timeout: 5_000, + }); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +} + +describe("mattermost trusted env-proxy preload", () => { + it("patches the Mattermost API and probe guarded-fetch call sites", () => { + const result = runDriver(String.raw` + const fs = require("node:fs"); + const path = require("node:path"); + const openclawDist = path.join(process.env.TEST_ROOT, "node_modules", "openclaw", "dist"); + fs.mkdirSync(openclawDist, { recursive: true }); + const fixture = path.join(openclawDist, "mattermost-fixture.js"); + fs.writeFileSync(fixture, [ + "const calls = [];", + "function fetchWithSsrFGuard(params) { calls.push(params); return params; }", + "function ssrfPolicyFromPrivateNetworkOptIn(value) { return value; }", + "fetchWithSsrFGuard({", + " url: 'https://chat.example.com/api/v4/users/me',", + " init: {},", + " auditContext: \"mattermost-api\",", + " policy: ssrfPolicyFromPrivateNetworkOptIn(false),", + "});", + "fetchWithSsrFGuard({", + " url: 'https://chat.example.com/api/v4/users/me',", + " init: {},", + " auditContext: \"mattermost-probe\",", + " policy: ssrfPolicyFromPrivateNetworkOptIn(false),", + "});", + "module.exports = calls;", + ].join(String.fromCharCode(10))); + + require(process.env.PRELOAD_PATH); + const calls = require(fixture); + console.log(JSON.stringify(calls.map((call) => ({ + auditContext: call.auditContext, + mode: call.mode, + })))); + `); + + expect(result.status, result.stderr || result.stdout).toBe(0); + expect(result.stderr).toBe(""); + expect(JSON.parse(result.stdout.trim())).toEqual([ + { auditContext: "mattermost-api", mode: "trusted_env_proxy" }, + { auditContext: "mattermost-probe", mode: "trusted_env_proxy" }, + ]); + }); + + it("fails closed when a Mattermost guarded-fetch call shape is ambiguous", () => { + const result = runDriver(String.raw` + const fs = require("node:fs"); + const path = require("node:path"); + const openclawDist = path.join(process.env.TEST_ROOT, "node_modules", "openclaw", "dist"); + fs.mkdirSync(openclawDist, { recursive: true }); + const fixture = path.join(openclawDist, "mattermost-ambiguous.js"); + fs.writeFileSync(fixture, [ + "function fetchWithSsrFGuard(params) { return params; }", + "fetchWithSsrFGuard({ auditContext: \"mattermost-api\" });", + "fetchWithSsrFGuard({ auditContext: \"mattermost-api\" });", + ].join(String.fromCharCode(10))); + + require(process.env.PRELOAD_PATH); + require(fixture); + `); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("expected one mattermost-api audit context"); + }); + + it("leaves non-Mattermost guarded-fetch call sites untouched", () => { + const result = runDriver(String.raw` + const fs = require("node:fs"); + const path = require("node:path"); + const openclawDist = path.join(process.env.TEST_ROOT, "node_modules", "openclaw", "dist"); + fs.mkdirSync(openclawDist, { recursive: true }); + const fixture = path.join(openclawDist, "other-fixture.js"); + fs.writeFileSync(fixture, [ + "const calls = [];", + "function fetchWithSsrFGuard(params) { calls.push(params); return params; }", + "fetchWithSsrFGuard({", + " url: 'https://example.com',", + " auditContext: \"other-api\",", + "});", + "module.exports = calls;", + ].join(String.fromCharCode(10))); + + require(process.env.PRELOAD_PATH); + const calls = require(fixture); + console.log(JSON.stringify(calls[0])); + `); + + expect(result.status, result.stderr || result.stdout).toBe(0); + expect(JSON.parse(result.stdout.trim())).toEqual({ + url: "https://example.com", + auditContext: "other-api", + }); + }); +}); From e2e321599332d115e2eac6c15d597d063ba65011 Mon Sep 17 00:00:00 2001 From: San Dang Date: Tue, 23 Jun 2026 22:59:33 +0700 Subject: [PATCH 07/12] Potential fix for pull request finding 'Useless assignment to local variable' Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> --- .../mattermost/runtime/mattermost-trusted-env-proxy.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/lib/messaging/channels/mattermost/runtime/mattermost-trusted-env-proxy.ts b/src/lib/messaging/channels/mattermost/runtime/mattermost-trusted-env-proxy.ts index 57db7250214..e1862c61833 100644 --- a/src/lib/messaging/channels/mattermost/runtime/mattermost-trusted-env-proxy.ts +++ b/src/lib/messaging/channels/mattermost/runtime/mattermost-trusted-env-proxy.ts @@ -30,9 +30,8 @@ function countMatches(source, pattern) { var count = 0; - var match; pattern.lastIndex = 0; - while ((match = pattern.exec(source)) !== null) count += 1; + while (pattern.exec(source) !== null) count += 1; return count; } From 009a9069a616b4518a1799713e3bcdf406dc00d5 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 24 Jun 2026 12:21:44 +0700 Subject: [PATCH 08/12] fix(blueprint): default OpenClaw fetch guard to sandbox proxy Signed-off-by: San Dang --- Dockerfile | 158 +++------- test/fetch-guard-patch-regression.test.ts | 346 +++++++--------------- 2 files changed, 153 insertions(+), 351 deletions(-) diff --git a/Dockerfile b/Dockerfile index eba7e506abe..bbbe37c9d31 100644 --- a/Dockerfile +++ b/Dockerfile @@ -206,23 +206,20 @@ RUN set -eu; \ # sandbox. The generic SSRF helper and strict/direct DNS-pinned paths remain # unmodified, so metadata/link-local/private IP literals are unchanged. # -# === Patch 4: route unconfigured strict SSRF fetches through the egress proxy === -# (NVIDIA/NemoClaw#4687). fetchWithSsrFGuard builds a per-request DNS-pinned -# *direct* undici dispatcher for STRICT-mode fetches that pass no explicit -# dispatcherPolicy — e.g. the @openclaw/googlechat inbound JWT signing-cert -# fetch from www.googleapis.com/service_accounts/v1/metadata/x509/.... A direct -# dispatcher ignores the global EnvHttpProxyAgent installed by -# NODE_USE_ENV_PROXY=1, so the request never reaches the OpenShell L7 proxy and -# fails in the proxy-only sandbox netns — rejecting every inbound Google Chat -# webhook. OpenClaw already has a "managed proxy" branch that routes such -# fetches through the env proxy (createHttp1EnvHttpProxyAgent) while still -# resolving + SSRF-validating the target hostname, but it is gated on -# isManagedProxyActive() (OPENCLAW_PROXY_ACTIVE=1), which NemoClaw does not set. -# Inside an OpenShell sandbox the configured egress proxy IS the managed proxy, -# so extend that activation to OPENSHELL_SANDBOX=1 for fetches that supply no -# explicit dispatcherPolicy. Explicit-proxy and direct(mTLS) dispatcher policies -# (Google auth proxy / client-cert paths) keep their existing behavior, and -# resolvePinnedHostnameWithPolicy still blocks private/link-local targets. +# === Patch 4: default bare SSRF fetches to trusted env proxy in sandbox === +# (NVIDIA/NemoClaw#396, #4687, openclaw#5129). fetchWithSsrFGuard defaults to +# STRICT mode when callers omit `mode`. STRICT does local DNS pinning before it +# can route through any proxy path, which fails for OpenShell-only hostnames +# such as inference.local and public endpoints reachable only through the +# sandbox egress proxy. OpenClaw web_search already avoids this by wrapping +# calls with withTrustedEnvProxyGuardedFetchMode(); the repeated failure class is +# bare fetchWithSsrFGuard({...}) callsites. +# +# Patch resolveGuardedFetchMode() so missing mode defaults to +# TRUSTED_ENV_PROXY only when OPENSHELL_SANDBOX=1. Explicit modes still win. +# The deprecated `proxy: "env"` compatibility branch is removed; outside an +# OpenShell sandbox, omitted mode remains STRICT. This broad default replaces +# narrower callsite-specific rewrites such as the old cron preflight patch. # # === Removal criteria === # Patch 1: drop when OpenClaw deprecates withStrictGuardedFetchMode or @@ -233,9 +230,9 @@ RUN set -eu; \ # Patch 2b: drop when OpenClaw ships a reviewed web_fetch trusted-proxy SSRF # policy surface that can allow host.openshell.internal without allowing # broader private/special-use hostnames. -# Patch 4: drop when OpenClaw routes unconfigured strict fetches through the -# env proxy in proxy-only environments without OPENCLAW_PROXY_ACTIVE, or when -# NemoClaw sets OPENCLAW_PROXY_ACTIVE=1 in the sandbox runtime instead. +# Patch 4: drop when OpenClaw defaults bare fetchWithSsrFGuard calls to +# trusted_env_proxy in an OpenShell sandbox, or when all sandbox-sensitive +# callsites explicitly pass mode: "trusted_env_proxy". # # SYNC WITH OPENCLAW: these patches classify the compiled OpenClaw dist at # build time. They apply the legacy patch when the old target exists, skip @@ -354,105 +351,48 @@ RUN set -eu; \ patch_fail "Patch 2b cannot safely skip"; \ fi; \ fi; \ - # --- Patch 4: route unconfigured strict fetches through the sandbox egress proxy (#4687) --- \ - # Reviewed against openclaw@2026.5.27 dist fetch-guard: the STRICT-mode \ - # managed-proxy gate is `mode === GUARDED_FETCH_MODE.STRICT && \ - # isManagedProxyActive() && hasProxyEnvConfigured()`. Extend activation to \ - # OPENSHELL_SANDBOX=1 only for fetches with no explicit dispatcherPolicy so \ - # the per-request direct dispatcher reuses the env proxy (EnvHttpProxyAgent) \ - # like the managed-proxy path already does; explicit-proxy / direct dispatcher \ - # policies and out-of-sandbox behavior are unchanged. \ - mp_files="$(grep -RIlF --include='*.js' 'const canUseManagedProxy = mode === GUARDED_FETCH_MODE.STRICT && isManagedProxyActive() && hasProxyEnvConfigured();' "$OC_DIST" || true)"; \ - if [ -n "$mp_files" ]; then \ - patched_managed_proxy=0; \ - for f in $mp_files; do \ - if grep -q 'nemoclaw: route unconfigured strict fetch' "$f"; then \ + # --- Patch 4: default bare guarded fetches to trusted env-proxy in sandbox --- \ + # Reviewed against openclaw@2026.5.27 dist fetch-guard: \ + # resolveGuardedFetchMode() returns explicit params.mode, then the deprecated \ + # proxy+dangerous opt-in, then STRICT. Remove the deprecated proxy opt-in and \ + # make omitted mode resolve to trusted_env_proxy only when OPENSHELL_SANDBOX=1. \ + mode_files="$(grep -RIlE --include='*.js' 'function resolveGuardedFetchMode\(params\)' "$OC_DIST" || true)"; \ + if [ -n "$mode_files" ]; then \ + patched_mode_default=0; \ + for f in $mode_files; do \ + if grep -q 'nemoclaw: default bare guarded fetches to trusted env proxy' "$f"; then \ echo "INFO: Patch 4 already present in $f"; \ else \ - sed -i -E 's#const canUseManagedProxy = mode === GUARDED_FETCH_MODE\.STRICT \&\& isManagedProxyActive\(\) \&\& hasProxyEnvConfigured\(\);#const canUseManagedProxy = mode === GUARDED_FETCH_MODE.STRICT \&\& (isManagedProxyActive() || (process.env.OPENSHELL_SANDBOX === "1" \&\& !params.dispatcherPolicy)) \&\& hasProxyEnvConfigured(); /* nemoclaw: route unconfigured strict fetch through sandbox egress proxy, see Dockerfile */#' "$f"; \ - grep -Fq 'process.env.OPENSHELL_SANDBOX === "1" && !params.dispatcherPolicy' "$f" \ - || patch_fail "Patch 4 verification failed for $f"; \ - patched_managed_proxy=1; \ + grep -Fq 'params.dangerouslyAllowEnvProxyWithoutPinnedDns === true' "$f" \ + || patch_fail "Patch 4 target $f is missing reviewed deprecated env-proxy opt-in"; \ + grep -Fq 'return GUARDED_FETCH_MODE.STRICT;' "$f" \ + || patch_fail "Patch 4 target $f is missing reviewed strict default"; \ + sed -i -E '/function resolveGuardedFetchMode\(params\)/,/return GUARDED_FETCH_MODE\.STRICT;/ { /if \(params\.proxy === "env" \&\& params\.dangerouslyAllowEnvProxyWithoutPinnedDns === true\) \{/,/^[[:space:]]*\}/ d; }' "$f"; \ + sed -i -E '/function resolveGuardedFetchMode\(params\)/,/return GUARDED_FETCH_MODE\.STRICT;/ s#return GUARDED_FETCH_MODE\.STRICT;#if (process.env.OPENSHELL_SANDBOX === "1") return GUARDED_FETCH_MODE.TRUSTED_ENV_PROXY; return GUARDED_FETCH_MODE.STRICT; /* nemoclaw: default bare guarded fetches to trusted env proxy in OpenShell sandbox, see Dockerfile */#' "$f"; \ + grep -Fq 'if (process.env.OPENSHELL_SANDBOX === "1") return GUARDED_FETCH_MODE.TRUSTED_ENV_PROXY; return GUARDED_FETCH_MODE.STRICT; /* nemoclaw: default bare guarded fetches to trusted env proxy in OpenShell sandbox, see Dockerfile */' "$f" \ + || patch_fail "Patch 4 verification failed to add sandbox default in $f"; \ + if grep -Fq 'params.proxy === "env"' "$f"; then \ + patch_fail "Patch 4 verification left deprecated proxy env opt-in in $f"; \ + fi; \ + if grep -Fq 'params.dangerouslyAllowEnvProxyWithoutPinnedDns === true' "$f"; then \ + patch_fail "Patch 4 verification left deprecated dangerous env-proxy opt-in in $f"; \ + fi; \ + patched_mode_default=1; \ fi; \ done; \ - if [ "$patched_managed_proxy" = "1" ]; then \ - echo "INFO: Patch 4 applied to OpenClaw ${OC_VERSION} managed-proxy strict-fetch activation"; \ + if [ "$patched_mode_default" = "1" ]; then \ + echo "INFO: Patch 4 applied to OpenClaw ${OC_VERSION} sandbox trusted env-proxy default"; \ fi; \ else \ - managed_proxy_refs="$(grep -RIlE --include='*.js' 'canUseManagedProxy|isManagedProxyActive' "$OC_DIST" || true)"; \ - if [ -z "$managed_proxy_refs" ]; then \ - echo "INFO: OpenClaw ${OC_VERSION} has no managed-proxy strict-fetch gate; Patch 4 not needed"; \ + mode_refs="$(grep -RIlE --include='*.js' 'resolveGuardedFetchMode|dangerouslyAllowEnvProxyWithoutPinnedDns' "$OC_DIST" || true)"; \ + if [ -z "$mode_refs" ]; then \ + echo "INFO: OpenClaw ${OC_VERSION} has no guarded-fetch mode resolver; Patch 4 not needed"; \ else \ - echo "ERROR: Patch 4 target missing but managed-proxy references remain:" >&2; \ - printf '%s\n' "$managed_proxy_refs" | head -n 5 >&2; \ + echo "ERROR: Patch 4 target missing but guarded-fetch mode/proxy references remain:" >&2; \ + printf '%s\n' "$mode_refs" | head -n 5 >&2; \ patch_fail "Patch 4 cannot safely skip"; \ fi; \ fi; \ - # --- Patch 6: cron model-provider preflight opts into trusted env-proxy mode --- \ - # Reviewed against openclaw@2026.5.27 dist: the cron isolated-agent preflight \ - # (`probeLocalProviderEndpoint`) calls `fetchWithSsrFGuard` with \ - # `auditContext: "cron-model-provider-preflight"` and a narrow hostname-allowlist \ - # SsrFPolicy from `buildLocalProviderSsrFPolicy`, but does not pass a `mode`. \ - # Default STRICT mode pins DNS for the managed inference hostname \ - # (`inference.local`), which is intentionally only resolvable through the \ - # OpenShell L7 proxy — pinned `dns.lookup` therefore fails with EAI_AGAIN and \ - # the scheduler permanently skips every cron run. Inject \ - # `mode: "trusted_env_proxy"` so the call uses the env proxy dispatcher; SSRF \ - # protection is retained through the existing hostname allowlist and the \ - # proxy's own ACLs. \ - # \ - # The patch keys on the co-located shape of the reviewed preflight call: in \ - # any file that mentions the audit context literal, both the \ - # `fetchWithSsrFGuard(` helper and the `buildLocalProviderSsrFPolicy` policy \ - # builder must appear; the audit literal itself must appear exactly once; and \ - # after patching exactly one patched literal must remain. Any ambiguous \ - # multi-callsite or mixed patched/unpatched layout fails the image build \ - # rather than silently widening the rewrite. \ - # \ - # Removal condition: drop this block (and any related `OC_VERSION` floor bump) \ - # once an OpenClaw release sets `mode: "trusted_env_proxy"` directly at the \ - # preflight call site or otherwise routes the managed inference base URL \ - # through the env-proxy dispatcher by default. The reviewed shape lives at \ - # `src/cron/isolated-agent/model-preflight.runtime.ts` in the openclaw repo. \ - preflight_files="$(grep -RIlF --include='*.js' 'cron-model-provider-preflight' "$OC_DIST" || true)"; \ - if [ -n "$preflight_files" ]; then \ - patched_preflight=0; \ - for f in $preflight_files; do \ - audit_count="$(grep -Fc 'auditContext: "cron-model-provider-preflight"' "$f" || true)"; \ - [ "${audit_count:-0}" -ge 1 ] \ - || patch_fail "Patch 6 shape gate: $f mentions cron-model-provider-preflight but has no auditContext literal"; \ - [ "${audit_count:-0}" -eq 1 ] \ - || patch_fail "Patch 6 shape gate: $f has ${audit_count} auditContext literals (expected exactly 1); refusing ambiguous multi-callsite rewrite"; \ - grep -Fq 'fetchWithSsrFGuard(' "$f" \ - || patch_fail "Patch 6 shape gate: $f has cron-model-provider-preflight but no fetchWithSsrFGuard call"; \ - grep -Fq 'buildLocalProviderSsrFPolicy' "$f" \ - || patch_fail "Patch 6 shape gate: $f has cron-model-provider-preflight but no buildLocalProviderSsrFPolicy"; \ - patched_count="$(grep -Fc 'mode: "trusted_env_proxy", auditContext: "cron-model-provider-preflight"' "$f" || true)"; \ - if [ "${patched_count:-0}" -eq 1 ]; then \ - echo "INFO: Patch 6 already present in $f"; \ - elif [ "${patched_count:-0}" -eq 0 ]; then \ - sed -i -E 's|auditContext: "cron-model-provider-preflight"|mode: "trusted_env_proxy", auditContext: "cron-model-provider-preflight"|g' "$f"; \ - new_patched_count="$(grep -Fc 'mode: "trusted_env_proxy", auditContext: "cron-model-provider-preflight"' "$f" || true)"; \ - [ "${new_patched_count:-0}" -eq 1 ] \ - || patch_fail "Patch 6 verification: expected exactly one patched literal in $f, found ${new_patched_count}"; \ - patched_preflight=1; \ - else \ - patch_fail "Patch 6 shape gate: $f has ${patched_count} already-patched literals (expected 0 or 1); refusing mixed-state rewrite"; \ - fi; \ - done; \ - if [ "$patched_preflight" = "1" ]; then \ - echo "INFO: Patch 6 applied to OpenClaw ${OC_VERSION} cron preflight trusted env-proxy"; \ - fi; \ - else \ - preflight_refs="$(grep -RIlE --include='*.js' 'preflightCronModelProvider|probeLocalProviderEndpoint' "$OC_DIST" || true)"; \ - if [ -z "$preflight_refs" ]; then \ - echo "INFO: OpenClaw ${OC_VERSION} has no cron model-provider preflight; Patch 6 not needed"; \ - else \ - echo "ERROR: Patch 6 target missing but cron preflight references remain:" >&2; \ - printf '%s\n' "$preflight_refs" | head -n 5 >&2; \ - patch_fail "Patch 6 cannot safely skip"; \ - fi; \ - fi; \ # --- Patch 3: follow symlinks in plugin-install path checks (#2203) --- \ # OpenClaw's install-safe-path and install-package-dir reject symlinked \ # directories via lstat. Changing lstat → stat in these two modules lets \ diff --git a/test/fetch-guard-patch-regression.test.ts b/test/fetch-guard-patch-regression.test.ts index 9f3398b4adf..4c29821fb31 100644 --- a/test/fetch-guard-patch-regression.test.ts +++ b/test/fetch-guard-patch-regression.test.ts @@ -32,8 +32,17 @@ const REVIEWED_OPENCLAW_2026_5_27_WEB_FETCH_SHAPE = [ " return fetchWithSsrFGuard(useEnvProxy ? withTrustedEnvProxyGuardedFetchMode(resolved) : withStrictGuardedFetchMode(resolved));", "}", ].join("\n"); -const REVIEWED_OPENCLAW_2026_5_27_MANAGED_PROXY_SHAPE = - "const canUseManagedProxy = mode === GUARDED_FETCH_MODE.STRICT && isManagedProxyActive() && hasProxyEnvConfigured();"; +const REVIEWED_OPENCLAW_2026_5_27_GUARDED_MODE_SHAPE = [ + "function resolveGuardedFetchMode(params) {", + " if (params.mode) {", + " return params.mode;", + " }", + ' if (params.proxy === "env" && params.dangerouslyAllowEnvProxyWithoutPinnedDns === true) {', + " return GUARDED_FETCH_MODE.TRUSTED_ENV_PROXY;", + " }", + " return GUARDED_FETCH_MODE.STRICT;", + "}", +].join("\n"); const REVIEWED_OPENCLAW_2026_5_27_SSRF_POLICY_SHAPE = [ "function shouldSkipPrivateNetworkChecks(hostname, policy) {", " return isPrivateNetworkAllowedByPolicy(policy) || normalizeHostnameSet(policy?.allowedHostnames).has(hostname);", @@ -328,6 +337,12 @@ describe("fetch-guard patch regression guard", () => { expect(REVIEWED_OPENCLAW_2026_5_27_WEB_FETCH_SHAPE).toContain( "withTrustedEnvProxyGuardedFetchMode(resolved)", ); + expect(REVIEWED_OPENCLAW_2026_5_27_GUARDED_MODE_SHAPE).toContain( + "function resolveGuardedFetchMode(params)", + ); + expect(REVIEWED_OPENCLAW_2026_5_27_GUARDED_MODE_SHAPE).toContain( + "params.dangerouslyAllowEnvProxyWithoutPinnedDns === true", + ); expect(REVIEWED_OPENCLAW_2026_5_27_SSRF_POLICY_SHAPE).toContain( "normalizeHostnameSet(policy?.allowedHostnames).has(hostname)", ); @@ -1092,25 +1107,20 @@ if (!blocked) throw new Error('private IP literal was not blocked');`, } }); - it("activates the managed-proxy path for unconfigured strict fetches only inside the sandbox (#4687)", async () => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fetch-guard-managed-proxy-")); + it("defaults bare guarded fetches to trusted env proxy only inside the sandbox (#396, #4687)", async () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fetch-guard-mode-default-")); const dist = path.join(tmp, "dist"); fs.mkdirSync(dist, { recursive: true }); fs.writeFileSync(path.join(tmp, "package.json"), '{"type":"module"}\n'); - const modulePath = path.join(dist, "fetch-guard-managed-proxy.js"); + const modulePath = path.join(dist, "fetch-guard-mode-default.js"); fs.writeFileSync( modulePath, [ "const withStrictGuardedFetchMode = Symbol('strict');", "const withTrustedEnvProxyGuardedFetchMode = Symbol('trusted');", - "const GUARDED_FETCH_MODE = { STRICT: 'strict' };", - "function isManagedProxyActive() { return process.env.OPENCLAW_PROXY_ACTIVE === '1'; }", - "function hasProxyEnvConfigured() { return true; }", - "function computeCanUseManagedProxy(mode, params) {", - ` ${REVIEWED_OPENCLAW_2026_5_27_MANAGED_PROXY_SHAPE}`, - " return canUseManagedProxy;", - "}", - "export { withStrictGuardedFetchMode as a, withTrustedEnvProxyGuardedFetchMode as b, computeCanUseManagedProxy as g };", + "const GUARDED_FETCH_MODE = { STRICT: 'strict', TRUSTED_ENV_PROXY: 'trusted_env_proxy' };", + REVIEWED_OPENCLAW_2026_5_27_GUARDED_MODE_SHAPE, + "export { withStrictGuardedFetchMode as a, withTrustedEnvProxyGuardedFetchMode as b, resolveGuardedFetchMode as g };", "", ].join("\n"), ); @@ -1124,77 +1134,107 @@ if (!blocked) throw new Error('private IP literal was not blocked');`, expect(patch.status, `${patch.stdout}${patch.stderr}`).toBe(0); expect(patch.stdout).toContain("Patch 4 applied"); const patched = fs.readFileSync(modulePath, "utf-8"); - expect(patched).toContain("nemoclaw: route unconfigured strict fetch"); + expect(patched).toContain("nemoclaw: default bare guarded fetches"); + expect(patched).not.toContain("dangerouslyAllowEnvProxyWithoutPinnedDns === true"); + expect(patched).not.toContain('params.proxy === "env"'); + expect(patched).toContain("process.env.OPENSHELL_SANDBOX"); + expect(patched).not.toContain("OPENCLAW_PROXY_ACTIVE"); const mod = await import(`${modulePath}?${Date.now()}`); const prevSandbox = process.env.OPENSHELL_SANDBOX; - const prevManaged = process.env.OPENCLAW_PROXY_ACTIVE; try { - // In-sandbox, no explicit dispatcher policy -> reuse the env proxy. + // In-sandbox, omitted mode uses trusted env proxy and avoids local DNS pinning. process.env.OPENSHELL_SANDBOX = "1"; - delete process.env.OPENCLAW_PROXY_ACTIVE; - expect(mod.g("strict", {})).toBe(true); - // In-sandbox but an explicit dispatcher policy is supplied -> untouched. - expect(mod.g("strict", { dispatcherPolicy: { mode: "explicit-proxy" } })).toBe(false); - // Outside the sandbox -> original strict/direct behavior is preserved. + expect(mod.g({})).toBe("trusted_env_proxy"); + // Explicit mode remains caller-owned. + expect(mod.g({ mode: "strict" })).toBe("strict"); + expect(mod.g({ mode: "trusted_env_proxy" })).toBe("trusted_env_proxy"); + + // Outside the sandbox -> omitted mode remains strict. delete process.env.OPENSHELL_SANDBOX; - expect(mod.g("strict", {})).toBe(false); - // Upstream managed-proxy activation still works regardless of sandbox. - process.env.OPENCLAW_PROXY_ACTIVE = "1"; - expect(mod.g("strict", {})).toBe(true); - // Non-strict modes never take the managed-proxy branch. - process.env.OPENSHELL_SANDBOX = "1"; - delete process.env.OPENCLAW_PROXY_ACTIVE; - expect(mod.g("trusted_env_proxy", {})).toBe(false); + expect(mod.g({})).toBe("strict"); + expect(mod.g({ proxy: "env" })).toBe("strict"); } finally { if (prevSandbox === undefined) delete process.env.OPENSHELL_SANDBOX; else process.env.OPENSHELL_SANDBOX = prevSandbox; - if (prevManaged === undefined) delete process.env.OPENCLAW_PROXY_ACTIVE; - else process.env.OPENCLAW_PROXY_ACTIVE = prevManaged; } } finally { fs.rmSync(tmp, { recursive: true, force: true }); } }); - it("reports Patch 4 not needed when the managed-proxy gate is absent", () => { - const tmp = fs.mkdtempSync( - path.join(os.tmpdir(), "nemoclaw-fetch-guard-managed-proxy-absent-"), - ); + it("leaves cron preflight callsites unmodified because omitted mode is patched centrally", async () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fetch-guard-cron-central-")); const dist = path.join(tmp, "dist"); fs.mkdirSync(dist, { recursive: true }); + fs.writeFileSync(path.join(tmp, "package.json"), '{"type":"module"}\n'); + const fetchGuardPath = path.join(dist, "fetch-guard-mode-default.js"); + const preflightPath = path.join(dist, "model-preflight.runtime.js"); fs.writeFileSync( - path.join(dist, "fetch-guard-no-managed-proxy.js"), + fetchGuardPath, [ "const withStrictGuardedFetchMode = Symbol('strict');", "const withTrustedEnvProxyGuardedFetchMode = Symbol('trusted');", - "export { withStrictGuardedFetchMode as a, withTrustedEnvProxyGuardedFetchMode as b };", + "const GUARDED_FETCH_MODE = { STRICT: 'strict', TRUSTED_ENV_PROXY: 'trusted_env_proxy' };", + REVIEWED_OPENCLAW_2026_5_27_GUARDED_MODE_SHAPE, + "export { withStrictGuardedFetchMode as a, withTrustedEnvProxyGuardedFetchMode as b, resolveGuardedFetchMode as g };", + "", + ].join("\n"), + ); + fs.writeFileSync( + preflightPath, + [ + "async function probeLocalProviderEndpoint(params) {", + " return fetchWithSsrFGuard({", + " url: params.baseUrl + '/v1/models',", + " policy: { hostnameAllowlist: ['inference.local'] },", + ' auditContext: "cron-model-provider-preflight",', + " });", + "}", + "export { probeLocalProviderEndpoint };", "", ].join("\n"), ); try { - const patch = runFetchGuardPatchBlock(dist, tmp, "2026.6.1"); + const patch = runFetchGuardPatchBlock( + dist, + tmp, + CURRENT_REVIEWED_OPENCLAW_PATCH_CLASSIFIER_VERSION, + ); expect(patch.status, `${patch.stdout}${patch.stderr}`).toBe(0); - expect(patch.stdout).toContain("Patch 4 not needed"); + expect(patch.stdout).toContain("Patch 4 applied"); + expect(patch.stdout).not.toContain("Patch 6"); + + const preflight = fs.readFileSync(preflightPath, "utf-8"); + expect(preflight).toContain('auditContext: "cron-model-provider-preflight"'); + expect(preflight).not.toContain('mode: "trusted_env_proxy"'); + + const mod = await import(`${fetchGuardPath}?${Date.now()}`); + const prevSandbox = process.env.OPENSHELL_SANDBOX; + try { + process.env.OPENSHELL_SANDBOX = "1"; + expect(mod.g({})).toBe("trusted_env_proxy"); + } finally { + if (prevSandbox === undefined) delete process.env.OPENSHELL_SANDBOX; + else process.env.OPENSHELL_SANDBOX = prevSandbox; + } } finally { fs.rmSync(tmp, { recursive: true, force: true }); } }); - it("fails closed when the managed-proxy gate drifts but managed-proxy references remain", () => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fetch-guard-managed-proxy-drift-")); + it("reports Patch 4 not needed when the guarded-fetch mode resolver is absent", () => { + const tmp = fs.mkdtempSync( + path.join(os.tmpdir(), "nemoclaw-fetch-guard-mode-resolver-absent-"), + ); const dist = path.join(tmp, "dist"); fs.mkdirSync(dist, { recursive: true }); fs.writeFileSync( - path.join(dist, "fetch-guard-managed-proxy-drift.js"), + path.join(dist, "fetch-guard-no-mode-resolver.js"), [ "const withStrictGuardedFetchMode = Symbol('strict');", "const withTrustedEnvProxyGuardedFetchMode = Symbol('trusted');", - "function isManagedProxyActive() { return process.env.OPENCLAW_PROXY_ACTIVE === '1'; }", - "function proxyEnvSet() { return true; }", - // Drifted shape: renamed variables, so the exact reviewed gate is gone. - "const canUseManagedProxy = currentMode === 'strict' && isManagedProxyActive() && proxyEnvSet();", "export { withStrictGuardedFetchMode as a, withTrustedEnvProxyGuardedFetchMode as b };", "", ].join("\n"), @@ -1202,216 +1242,38 @@ if (!blocked) throw new Error('private IP literal was not blocked');`, try { const patch = runFetchGuardPatchBlock(dist, tmp, "2026.6.1"); - expect(patch.status).toBe(1); - expect(patch.stderr).toContain("Patch 4 target missing but managed-proxy references remain"); - expect(patch.stderr).toContain("Patch 4 cannot safely skip"); - expect(patch.stderr).toContain("OpenClaw 2026.6.1"); + expect(patch.status, `${patch.stdout}${patch.stderr}`).toBe(0); + expect(patch.stdout).toContain("Patch 4 not needed"); + expect(patch.stdout).toContain("has no guarded-fetch mode resolver"); } finally { fs.rmSync(tmp, { recursive: true, force: true }); } }); - function reviewedCronPreflightFixture({ - auditOccurrences = 1, - includeFetchWithSsrFGuard = true, - includeBuildLocalProviderSsrFPolicy = true, - patchedOccurrences = 0, - }: { - auditOccurrences?: number; - includeFetchWithSsrFGuard?: boolean; - includeBuildLocalProviderSsrFPolicy?: boolean; - patchedOccurrences?: number; - } = {}): string { - const lines: string[] = [ - "const PREFLIGHT_TIMEOUT_MS = 2500;", - "function buildProbeUrl(api, baseUrl) { return baseUrl + (api === 'ollama' ? '/api/tags' : '/models'); }", - ]; - const policyHelper = includeBuildLocalProviderSsrFPolicy - ? "buildLocalProviderSsrFPolicy" - : "buildDriftedSsrFPolicy"; - if (includeBuildLocalProviderSsrFPolicy) { - lines.push( - "function buildLocalProviderSsrFPolicy(baseUrl) {", - " const parsed = new URL(baseUrl);", - " return { hostnameAllowlist: [parsed.hostname], allowPrivateNetwork: true };", - "}", - ); - } else { - lines.push( - "function buildDriftedSsrFPolicy(baseUrl) {", - " const parsed = new URL(baseUrl);", - " return { hostnameAllowlist: [parsed.hostname] };", - "}", - ); - } - lines.push("async function probeLocalProviderEndpoint(params) {"); - for (let index = 0; index < patchedOccurrences; index += 1) { - lines.push( - ` const ${index === 0 ? "patched" : `patched_${index}`} = await ${ - includeFetchWithSsrFGuard ? "fetchWithSsrFGuard" : "callPatchedFetch" - }({`, - ` url: buildProbeUrl(params.api, params.baseUrl),`, - ` policy: ${policyHelper}(params.baseUrl),`, - ` timeoutMs: PREFLIGHT_TIMEOUT_MS,`, - ` mode: "trusted_env_proxy", auditContext: "cron-model-provider-preflight",`, - " });", - ); - } - for (let index = 0; index < auditOccurrences - patchedOccurrences; index += 1) { - lines.push( - ` const ${index === 0 ? "result" : `result_${index}`} = await ${ - includeFetchWithSsrFGuard ? "fetchWithSsrFGuard" : "callUnpatchedFetch" - }({`, - ` url: buildProbeUrl(params.api, params.baseUrl),`, - ` policy: ${policyHelper}(params.baseUrl),`, - ` timeoutMs: PREFLIGHT_TIMEOUT_MS,`, - ` auditContext: "cron-model-provider-preflight",`, - " });", - ); - } - lines.push( - " return null;", - "}", - "export { probeLocalProviderEndpoint, preflightCronModelProvider };", - "function preflightCronModelProvider() {}", - "", - ); - return lines.join("\n"); - } - - function writeNeighbouringFetchGuardFixtures(dist: string): void { - // Earlier patches in the same RUN block (1, 2, 2b, 4) only need the dist to - // navigate their "not needed" branches; mirror the shape proven by the - // "skips the strict export patch when strict fetch mode is absent" test so - // execution reaches Patch 6 without classifying the dist as unknown. - fs.writeFileSync( - path.join(dist, "media-runtime.js"), - "export { readRemoteMediaBuffer, saveRemoteMedia, fetchRemoteMedia };\n", - ); + it("fails closed when the mode resolver is missing but guarded-fetch proxy references remain", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fetch-guard-mode-resolver-drift-")); + const dist = path.join(tmp, "dist"); + fs.mkdirSync(dist, { recursive: true }); fs.writeFileSync( - path.join(dist, "fetch-guard-neighbour.js"), + path.join(dist, "fetch-guard-mode-resolver-drift.js"), [ + "const withStrictGuardedFetchMode = Symbol('strict');", "const withTrustedEnvProxyGuardedFetchMode = Symbol('trusted');", - "async function fetchGuardedMediaResponse() {", - " return fetchWithSsrFGuard(withTrustedEnvProxyGuardedFetchMode({}));", - "}", - "export { withTrustedEnvProxyGuardedFetchMode as a };", + // Drifted shape: legacy env-proxy fields remain, but the reviewed resolver is gone. + "const legacyProxyOptIn = params.dangerouslyAllowEnvProxyWithoutPinnedDns === true;", + "export { withStrictGuardedFetchMode as a, withTrustedEnvProxyGuardedFetchMode as b };", "", ].join("\n"), ); - } - - it("applies Patch 6 to a reviewed single-callsite cron preflight fixture", () => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-patch6-happy-")); - const dist = path.join(tmp, "dist"); - fs.mkdirSync(dist, { recursive: true }); - writeNeighbouringFetchGuardFixtures(dist); - const preflightPath = path.join(dist, "model-preflight.runtime.js"); - fs.writeFileSync(preflightPath, reviewedCronPreflightFixture()); - try { - const patch = runFetchGuardPatchBlock(dist, tmp); - expect(patch.status, `${patch.stdout}${patch.stderr}`).toBe(0); - expect(patch.stdout).toContain( - "Patch 6 applied to OpenClaw 2026.5.27 cron preflight trusted env-proxy", - ); - const patched = fs.readFileSync(preflightPath, "utf-8"); - expect( - patched.match(/mode: "trusted_env_proxy", auditContext: "cron-model-provider-preflight"/g) - ?.length, - ).toBe(1); - expect(patched).not.toMatch(/(? { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-patch6-idempotent-")); - const dist = path.join(tmp, "dist"); - fs.mkdirSync(dist, { recursive: true }); - writeNeighbouringFetchGuardFixtures(dist); - const preflightPath = path.join(dist, "model-preflight.runtime.js"); - const source = reviewedCronPreflightFixture({ auditOccurrences: 1, patchedOccurrences: 1 }); - fs.writeFileSync(preflightPath, source); - try { - const patch = runFetchGuardPatchBlock(dist, tmp); - expect(patch.status, `${patch.stdout}${patch.stderr}`).toBe(0); - expect(patch.stdout).toContain("Patch 6 already present in"); - expect(patch.stdout).not.toContain("Patch 6 applied to OpenClaw"); - expect(fs.readFileSync(preflightPath, "utf-8")).toBe(source); - } finally { - fs.rmSync(tmp, { recursive: true, force: true }); - } - }); - it("skips Patch 6 when the dist has no cron preflight references", () => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-patch6-absent-")); - const dist = path.join(tmp, "dist"); - fs.mkdirSync(dist, { recursive: true }); - writeNeighbouringFetchGuardFixtures(dist); try { - const patch = runFetchGuardPatchBlock(dist, tmp); - expect(patch.status, `${patch.stdout}${patch.stderr}`).toBe(0); - expect(patch.stdout).toContain( - "OpenClaw 2026.5.27 has no cron model-provider preflight; Patch 6 not needed", - ); - } finally { - fs.rmSync(tmp, { recursive: true, force: true }); - } - }); - - it("fails Patch 6 closed when the fetchWithSsrFGuard helper is missing", () => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-patch6-no-fetch-")); - const dist = path.join(tmp, "dist"); - fs.mkdirSync(dist, { recursive: true }); - writeNeighbouringFetchGuardFixtures(dist); - fs.writeFileSync( - path.join(dist, "model-preflight.runtime.js"), - reviewedCronPreflightFixture({ includeFetchWithSsrFGuard: false }), - ); - try { - const patch = runFetchGuardPatchBlock(dist, tmp); - expect(patch.status).toBe(1); - expect(patch.stderr).toContain("Patch 6 shape gate: "); - expect(patch.stderr).toContain("no fetchWithSsrFGuard call"); - } finally { - fs.rmSync(tmp, { recursive: true, force: true }); - } - }); - - it("fails Patch 6 closed when the SsrF policy helper is missing", () => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-patch6-no-policy-")); - const dist = path.join(tmp, "dist"); - fs.mkdirSync(dist, { recursive: true }); - writeNeighbouringFetchGuardFixtures(dist); - fs.writeFileSync( - path.join(dist, "model-preflight.runtime.js"), - reviewedCronPreflightFixture({ includeBuildLocalProviderSsrFPolicy: false }), - ); - try { - const patch = runFetchGuardPatchBlock(dist, tmp); - expect(patch.status).toBe(1); - expect(patch.stderr).toContain("Patch 6 shape gate: "); - expect(patch.stderr).toContain("no buildLocalProviderSsrFPolicy"); - } finally { - fs.rmSync(tmp, { recursive: true, force: true }); - } - }); - - it("fails Patch 6 closed when the audit context literal is ambiguous (multi-callsite)", () => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-patch6-ambiguous-")); - const dist = path.join(tmp, "dist"); - fs.mkdirSync(dist, { recursive: true }); - writeNeighbouringFetchGuardFixtures(dist); - fs.writeFileSync( - path.join(dist, "model-preflight.runtime.js"), - reviewedCronPreflightFixture({ auditOccurrences: 2 }), - ); - try { - const patch = runFetchGuardPatchBlock(dist, tmp); + const patch = runFetchGuardPatchBlock(dist, tmp, "2026.6.1"); expect(patch.status).toBe(1); - expect(patch.stderr).toContain("Patch 6 shape gate: "); - expect(patch.stderr).toContain("refusing ambiguous multi-callsite rewrite"); + expect(patch.stderr).toContain( + "Patch 4 target missing but guarded-fetch mode/proxy references remain", + ); + expect(patch.stderr).toContain("Patch 4 cannot safely skip"); + expect(patch.stderr).toContain("OpenClaw 2026.6.1"); } finally { fs.rmSync(tmp, { recursive: true, force: true }); } From cb0e070e597a7fd5e26a398f87f9690d4e4938d6 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 24 Jun 2026 12:39:13 +0700 Subject: [PATCH 09/12] fix(blueprint): scope fetch guard patch verification Signed-off-by: San Dang --- Dockerfile | 5 +++-- test/fetch-guard-patch-regression.test.ts | 12 ++++++++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/Dockerfile b/Dockerfile index bbbe37c9d31..447dd3ad8a7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -371,10 +371,11 @@ RUN set -eu; \ sed -i -E '/function resolveGuardedFetchMode\(params\)/,/return GUARDED_FETCH_MODE\.STRICT;/ s#return GUARDED_FETCH_MODE\.STRICT;#if (process.env.OPENSHELL_SANDBOX === "1") return GUARDED_FETCH_MODE.TRUSTED_ENV_PROXY; return GUARDED_FETCH_MODE.STRICT; /* nemoclaw: default bare guarded fetches to trusted env proxy in OpenShell sandbox, see Dockerfile */#' "$f"; \ grep -Fq 'if (process.env.OPENSHELL_SANDBOX === "1") return GUARDED_FETCH_MODE.TRUSTED_ENV_PROXY; return GUARDED_FETCH_MODE.STRICT; /* nemoclaw: default bare guarded fetches to trusted env proxy in OpenShell sandbox, see Dockerfile */' "$f" \ || patch_fail "Patch 4 verification failed to add sandbox default in $f"; \ - if grep -Fq 'params.proxy === "env"' "$f"; then \ + patched_resolver="$(sed -n '/function resolveGuardedFetchMode(params)/,/nemoclaw: default bare guarded fetches to trusted env proxy/p' "$f")"; \ + if printf '%s\n' "$patched_resolver" | grep -Fq 'params.proxy === "env"'; then \ patch_fail "Patch 4 verification left deprecated proxy env opt-in in $f"; \ fi; \ - if grep -Fq 'params.dangerouslyAllowEnvProxyWithoutPinnedDns === true' "$f"; then \ + if printf '%s\n' "$patched_resolver" | grep -Fq 'params.dangerouslyAllowEnvProxyWithoutPinnedDns === true'; then \ patch_fail "Patch 4 verification left deprecated dangerous env-proxy opt-in in $f"; \ fi; \ patched_mode_default=1; \ diff --git a/test/fetch-guard-patch-regression.test.ts b/test/fetch-guard-patch-regression.test.ts index 4c29821fb31..f7039a77322 100644 --- a/test/fetch-guard-patch-regression.test.ts +++ b/test/fetch-guard-patch-regression.test.ts @@ -1120,6 +1120,9 @@ if (!blocked) throw new Error('private IP literal was not blocked');`, "const withTrustedEnvProxyGuardedFetchMode = Symbol('trusted');", "const GUARDED_FETCH_MODE = { STRICT: 'strict', TRUSTED_ENV_PROXY: 'trusted_env_proxy' };", REVIEWED_OPENCLAW_2026_5_27_GUARDED_MODE_SHAPE, + "function preserveUnrelatedLegacyProxyLiteral(params) {", + ' return params.proxy === "env";', + "}", "export { withStrictGuardedFetchMode as a, withTrustedEnvProxyGuardedFetchMode as b, resolveGuardedFetchMode as g };", "", ].join("\n"), @@ -1135,8 +1138,13 @@ if (!blocked) throw new Error('private IP literal was not blocked');`, expect(patch.stdout).toContain("Patch 4 applied"); const patched = fs.readFileSync(modulePath, "utf-8"); expect(patched).toContain("nemoclaw: default bare guarded fetches"); - expect(patched).not.toContain("dangerouslyAllowEnvProxyWithoutPinnedDns === true"); - expect(patched).not.toContain('params.proxy === "env"'); + const resolverBlock = + patched.match( + /function resolveGuardedFetchMode\(params\) \{[\s\S]*?\/\* nemoclaw: default bare guarded fetches[^\n]*/, + )?.[0] ?? ""; + expect(resolverBlock).not.toContain("dangerouslyAllowEnvProxyWithoutPinnedDns === true"); + expect(resolverBlock).not.toContain('params.proxy === "env"'); + expect(patched).toContain('params.proxy === "env";'); expect(patched).toContain("process.env.OPENSHELL_SANDBOX"); expect(patched).not.toContain("OPENCLAW_PROXY_ACTIVE"); From ed8ab384e1fa96789ccfd667b0155705ad54823a Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 24 Jun 2026 12:45:35 +0700 Subject: [PATCH 10/12] fix(blueprint): remove compiled one-line proxy opt-in Signed-off-by: San Dang --- Dockerfile | 2 +- test/fetch-guard-patch-regression.test.ts | 8 ++------ 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/Dockerfile b/Dockerfile index 447dd3ad8a7..8cd069d3ed5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -367,7 +367,7 @@ RUN set -eu; \ || patch_fail "Patch 4 target $f is missing reviewed deprecated env-proxy opt-in"; \ grep -Fq 'return GUARDED_FETCH_MODE.STRICT;' "$f" \ || patch_fail "Patch 4 target $f is missing reviewed strict default"; \ - sed -i -E '/function resolveGuardedFetchMode\(params\)/,/return GUARDED_FETCH_MODE\.STRICT;/ { /if \(params\.proxy === "env" \&\& params\.dangerouslyAllowEnvProxyWithoutPinnedDns === true\) \{/,/^[[:space:]]*\}/ d; }' "$f"; \ + sed -i -E '/function resolveGuardedFetchMode\(params\)/,/return GUARDED_FETCH_MODE\.STRICT;/ { /if \(params\.proxy === "env" \&\& params\.dangerouslyAllowEnvProxyWithoutPinnedDns === true\) return GUARDED_FETCH_MODE\.TRUSTED_ENV_PROXY;/ d; /if \(params\.proxy === "env" \&\& params\.dangerouslyAllowEnvProxyWithoutPinnedDns === true\) \{/,/^[[:space:]]*\}/ d; }' "$f"; \ sed -i -E '/function resolveGuardedFetchMode\(params\)/,/return GUARDED_FETCH_MODE\.STRICT;/ s#return GUARDED_FETCH_MODE\.STRICT;#if (process.env.OPENSHELL_SANDBOX === "1") return GUARDED_FETCH_MODE.TRUSTED_ENV_PROXY; return GUARDED_FETCH_MODE.STRICT; /* nemoclaw: default bare guarded fetches to trusted env proxy in OpenShell sandbox, see Dockerfile */#' "$f"; \ grep -Fq 'if (process.env.OPENSHELL_SANDBOX === "1") return GUARDED_FETCH_MODE.TRUSTED_ENV_PROXY; return GUARDED_FETCH_MODE.STRICT; /* nemoclaw: default bare guarded fetches to trusted env proxy in OpenShell sandbox, see Dockerfile */' "$f" \ || patch_fail "Patch 4 verification failed to add sandbox default in $f"; \ diff --git a/test/fetch-guard-patch-regression.test.ts b/test/fetch-guard-patch-regression.test.ts index f7039a77322..911c269bd16 100644 --- a/test/fetch-guard-patch-regression.test.ts +++ b/test/fetch-guard-patch-regression.test.ts @@ -34,12 +34,8 @@ const REVIEWED_OPENCLAW_2026_5_27_WEB_FETCH_SHAPE = [ ].join("\n"); const REVIEWED_OPENCLAW_2026_5_27_GUARDED_MODE_SHAPE = [ "function resolveGuardedFetchMode(params) {", - " if (params.mode) {", - " return params.mode;", - " }", - ' if (params.proxy === "env" && params.dangerouslyAllowEnvProxyWithoutPinnedDns === true) {', - " return GUARDED_FETCH_MODE.TRUSTED_ENV_PROXY;", - " }", + " if (params.mode) return params.mode;", + ' if (params.proxy === "env" && params.dangerouslyAllowEnvProxyWithoutPinnedDns === true) return GUARDED_FETCH_MODE.TRUSTED_ENV_PROXY;', " return GUARDED_FETCH_MODE.STRICT;", "}", ].join("\n"); From e7385b57be5910ed48746e77bf6c5f07edca87e1 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 24 Jun 2026 12:55:34 +0700 Subject: [PATCH 11/12] test(blueprint): cover fetch guard proxy contract Signed-off-by: San Dang --- test/fetch-guard-patch-regression.test.ts | 94 +++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/test/fetch-guard-patch-regression.test.ts b/test/fetch-guard-patch-regression.test.ts index 911c269bd16..d551b1f0107 100644 --- a/test/fetch-guard-patch-regression.test.ts +++ b/test/fetch-guard-patch-regression.test.ts @@ -1167,6 +1167,100 @@ if (!blocked) throw new Error('private IP literal was not blocked');`, } }); + it("bare omitted-mode fetches skip pinned DNS in sandbox while preserving SSRF denies", async () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fetch-guard-mode-contract-")); + const dist = path.join(tmp, "dist"); + fs.mkdirSync(dist, { recursive: true }); + fs.writeFileSync(path.join(tmp, "package.json"), '{"type":"module"}\n'); + const modulePath = path.join(dist, "fetch-guard-mode-contract.js"); + fs.writeFileSync( + modulePath, + [ + "const pinnedDnsCalls = [];", + "const policyChecks = [];", + "const withStrictGuardedFetchMode = (params) => ({ ...params, mode: GUARDED_FETCH_MODE.STRICT });", + "const withTrustedEnvProxyGuardedFetchMode = (params) => ({ ...params, mode: GUARDED_FETCH_MODE.TRUSTED_ENV_PROXY });", + "const GUARDED_FETCH_MODE = { STRICT: 'strict', TRUSTED_ENV_PROXY: 'trusted_env_proxy' };", + REVIEWED_OPENCLAW_2026_5_27_GUARDED_MODE_SHAPE, + "function normalizeHostname(value) { return String(value || '').toLowerCase().replace(/\\.+$/, ''); }", + "function assertHostnameAllowedWithPolicy(hostname, policy) {", + " const normalized = normalizeHostname(hostname);", + " policyChecks.push({ normalized, policy });", + " const allowedHostnames = new Set((policy?.allowedHostnames ?? []).map(normalizeHostname));", + " if (allowedHostnames.has(normalized)) return normalized;", + " if (normalized === '169.254.169.254' || normalized === '10.0.0.1' || normalized.endsWith('.internal')) throw new Error('blocked ' + normalized);", + " return normalized;", + "}", + "async function resolvePinnedHostnameWithPolicy(hostname, params = {}) {", + " pinnedDnsCalls.push({ hostname: normalizeHostname(hostname), policy: params.policy });", + " return { hostname: assertHostnameAllowedWithPolicy(hostname, params.policy), addresses: ['203.0.113.10'] };", + "}", + "function shouldUseEnvHttpProxyForUrl() { return true; }", + "function createHttp1EnvHttpProxyAgent() { return { kind: 'env-proxy' }; }", + "function createPinnedDispatcher(pinned) { return { kind: 'pinned', pinned }; }", + "async function fetchWithSsrFGuard(params) {", + " const parsedUrl = new URL(params.url);", + " const mode = resolveGuardedFetchMode(params);", + " const canUseTrustedEnvProxy = mode === GUARDED_FETCH_MODE.TRUSTED_ENV_PROXY && shouldUseEnvHttpProxyForUrl(parsedUrl.toString());", + " if (canUseTrustedEnvProxy) {", + " assertHostnameAllowedWithPolicy(parsedUrl.hostname, params.policy);", + " return { mode, dispatcher: createHttp1EnvHttpProxyAgent().kind, hostname: parsedUrl.hostname };", + " }", + " return { mode, dispatcher: createPinnedDispatcher(await resolvePinnedHostnameWithPolicy(parsedUrl.hostname, { policy: params.policy })).kind, hostname: parsedUrl.hostname };", + "}", + "export { withStrictGuardedFetchMode as a, withTrustedEnvProxyGuardedFetchMode as b, fetchWithSsrFGuard as f, resolveGuardedFetchMode as g, pinnedDnsCalls as p, policyChecks as c };", + "", + ].join("\n"), + ); + + try { + const patch = runFetchGuardPatchBlock( + dist, + tmp, + CURRENT_REVIEWED_OPENCLAW_PATCH_CLASSIFIER_VERSION, + ); + expect(patch.status, `${patch.stdout}${patch.stderr}`).toBe(0); + const mod = await import(`${modulePath}?${Date.now()}`); + const prevSandbox = process.env.OPENSHELL_SANDBOX; + try { + process.env.OPENSHELL_SANDBOX = "1"; + await expect( + mod.f({ + url: "https://www.googleapis.com/service_accounts/v1/metadata/x509/chat%40system.gserviceaccount.com", + }), + ).resolves.toMatchObject({ + mode: "trusted_env_proxy", + dispatcher: "env-proxy", + hostname: "www.googleapis.com", + }); + expect(mod.p).toEqual([]); + expect(mod.c).toContainEqual({ normalized: "www.googleapis.com", policy: undefined }); + + await expect(mod.f({ url: "http://169.254.169.254/latest/meta-data" })).rejects.toThrow( + /blocked 169\.254\.169\.254/, + ); + await expect(mod.f({ url: "http://10.0.0.1/" })).rejects.toThrow(/blocked 10\.0\.0\.1/); + await expect(mod.f({ url: "http://foo.internal/" })).rejects.toThrow( + /blocked foo\.internal/, + ); + expect(mod.p).toEqual([]); + + delete process.env.OPENSHELL_SANDBOX; + await expect(mod.f({ url: "https://www.googleapis.com/" })).resolves.toMatchObject({ + mode: "strict", + dispatcher: "pinned", + hostname: "www.googleapis.com", + }); + expect(mod.p).toContainEqual({ hostname: "www.googleapis.com", policy: undefined }); + } finally { + if (prevSandbox === undefined) delete process.env.OPENSHELL_SANDBOX; + else process.env.OPENSHELL_SANDBOX = prevSandbox; + } + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + it("leaves cron preflight callsites unmodified because omitted mode is patched centrally", async () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fetch-guard-cron-central-")); const dist = path.join(tmp, "dist"); From 2da5ab8a1ccd1226615370b01aa58d069107781a Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 24 Jun 2026 14:38:25 +0700 Subject: [PATCH 12/12] fix(messaging): rely on shared fetch guard proxy for Mattermost --- src/lib/messaging/channels/manifests.test.ts | 1 - .../messaging/channels/mattermost/manifest.ts | 11 -- .../runtime/mattermost-trusted-env-proxy.ts | 158 ------------------ test/mattermost-trusted-env-proxy.test.ts | 134 --------------- 4 files changed, 304 deletions(-) delete mode 100644 src/lib/messaging/channels/mattermost/runtime/mattermost-trusted-env-proxy.ts delete mode 100644 test/mattermost-trusted-env-proxy.test.ts diff --git a/src/lib/messaging/channels/manifests.test.ts b/src/lib/messaging/channels/manifests.test.ts index 7566ed70aa1..ce8f0819669 100644 --- a/src/lib/messaging/channels/manifests.test.ts +++ b/src/lib/messaging/channels/manifests.test.ts @@ -753,7 +753,6 @@ describe("built-in channel manifests", () => { onFailure: "skip-channel", }); expectOpenClawRuntimeVisibility(mattermostManifest, ["mattermost"], ["mattermost"]); - expectOpenClawNodePreload(mattermostManifest, "mattermost-trusted-env-proxy"); expect(mattermostManifest.state).toEqual({ persist: { mattermostConfig: ["baseUrl", "allowedChannels", "requireMention"], diff --git a/src/lib/messaging/channels/mattermost/manifest.ts b/src/lib/messaging/channels/mattermost/manifest.ts index 8cc7168f1ed..2c51a2eb27b 100644 --- a/src/lib/messaging/channels/mattermost/manifest.ts +++ b/src/lib/messaging/channels/mattermost/manifest.ts @@ -139,17 +139,6 @@ export const mattermostManifest = { configKeys: ["mattermost"], logPatterns: ["mattermost"], }, - nodePreloads: [ - { - module: "mattermost-trusted-env-proxy", - injectInto: ["boot", "connect"], - optional: false, - installMessage: - "[channels] Installing Mattermost trusted env-proxy guard (SSRF-preserving DNS delegation)", - installedMessage: - "[channels] Mattermost trusted env-proxy guard installed (NODE_OPTIONS updated)", - }, - ], }, }, agentPackages: [], diff --git a/src/lib/messaging/channels/mattermost/runtime/mattermost-trusted-env-proxy.ts b/src/lib/messaging/channels/mattermost/runtime/mattermost-trusted-env-proxy.ts deleted file mode 100644 index e1862c61833..00000000000 --- a/src/lib/messaging/channels/mattermost/runtime/mattermost-trusted-env-proxy.ts +++ /dev/null @@ -1,158 +0,0 @@ -// @ts-nocheck -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 -// -// Mattermost's upstream OpenClaw extension calls fetchWithSsrFGuard in strict -// mode. In OpenShell/NemoClaw sandboxes, strict mode can fail before proxy -// egress because local DNS resolution is intentionally unavailable for some -// operator-routed hosts. Patch only the Mattermost guarded fetch call sites to -// keep hostname SSRF checks while delegating DNS resolution to the trusted env -// proxy. - -(function () { - "use strict"; - - var PATCH_MARKER = "__nemoclawMattermostTrustedEnvProxyPatchInstalled"; - var MODE_PROPERTY = 'mode: "trusted_env_proxy",'; - var AUDIT_CONTEXTS = ["mattermost-api", "mattermost-probe"]; - - if (process[PATCH_MARKER]) return; - try { - Object.defineProperty(process, PATCH_MARKER, { value: true }); - } catch (_e) { - process[PATCH_MARKER] = true; - } - - function isOpenClawDistFile(filename) { - var normalized = String(filename || "").replace(/\\/g, "/"); - return normalized.indexOf("/openclaw/dist/") !== -1 && normalized.endsWith(".js"); - } - - function countMatches(source, pattern) { - var count = 0; - pattern.lastIndex = 0; - while (pattern.exec(source) !== null) count += 1; - return count; - } - - function patchAuditContext(source, filename, context) { - var auditPattern = new RegExp("auditContext\\s*:\\s*[\"']" + context + "[\"']", "g"); - var matches = countMatches(source, auditPattern); - if (matches === 0) return source; - if (matches > 1) { - throw new Error( - "OpenClaw Mattermost trusted env-proxy patch shape not recognized in " + - filename + - "; expected one " + - context + - " audit context", - ); - } - - auditPattern.lastIndex = 0; - var match = auditPattern.exec(source); - if (!match) return source; - - var auditIndex = match.index; - var callStart = source.lastIndexOf("fetchWithSsrFGuard({", auditIndex); - if (callStart === -1) { - throw new Error( - "OpenClaw Mattermost trusted env-proxy patch shape not recognized in " + - filename + - "; expected fetchWithSsrFGuard object before " + - context, - ); - } - - var prefix = source.slice(callStart, auditIndex); - var existingMode = prefix.match(/mode\s*:\s*["']([^"']+)["']/); - if (existingMode) { - if (existingMode[1] === "trusted_env_proxy") return source; - throw new Error( - "OpenClaw Mattermost trusted env-proxy patch found unexpected guarded-fetch mode in " + - filename + - " for " + - context, - ); - } - - if (prefix.indexOf("policy:") !== -1) { - throw new Error( - "OpenClaw Mattermost trusted env-proxy patch shape not recognized in " + - filename + - "; expected policy after auditContext for " + - context, - ); - } - - var lineStart = source.lastIndexOf("\n", auditIndex) + 1; - var indentMatch = source.slice(lineStart, auditIndex).match(/^\s*/); - var indent = indentMatch ? indentMatch[0] : ""; - return source.slice(0, auditIndex) + indent + MODE_PROPERTY + "\n" + source.slice(auditIndex); - } - - function patchMattermostGuardedFetchSource(source, filename) { - var next = source; - for (var i = 0; i < AUDIT_CONTEXTS.length; i++) { - next = patchAuditContext(next, filename, AUDIT_CONTEXTS[i]); - } - return next; - } - - function fileNameFromModuleUrl(urlValue) { - if (typeof urlValue !== "string" || !urlValue.startsWith("file:")) return ""; - try { - return require("url").fileURLToPath(urlValue); - } catch (_e) { - return ""; - } - } - - function sourceToText(source) { - if (typeof source === "string") return source; - if (typeof Buffer !== "undefined") { - if (Buffer.isBuffer(source)) return source.toString("utf8"); - if (source instanceof Uint8Array) return Buffer.from(source).toString("utf8"); - if (source instanceof ArrayBuffer) return Buffer.from(source).toString("utf8"); - } - return null; - } - - function installPatch() { - var Module = require("module"); - var fs = require("fs"); - var originalJsLoader = Module._extensions && Module._extensions[".js"]; - if (typeof originalJsLoader === "function") { - Module._extensions[".js"] = function nemoclawMattermostTrustedEnvProxyJsLoader( - mod, - filename, - ) { - if (isOpenClawDistFile(filename)) { - var source = fs.readFileSync(filename, "utf8"); - var patched = patchMattermostGuardedFetchSource(source, filename); - if (patched !== source) { - return mod._compile(patched, filename); - } - } - return originalJsLoader.apply(this, arguments); - }; - } - - if (typeof Module.registerHooks === "function") { - Module.registerHooks({ - load: function nemoclawMattermostTrustedEnvProxyLoadHook(urlValue, context, nextLoad) { - var result = nextLoad(urlValue, context); - var filename = fileNameFromModuleUrl(urlValue); - if (!isOpenClawDistFile(filename)) return result; - var sourceText = sourceToText(result && result.source); - if (sourceText === null) return result; - var patched = patchMattermostGuardedFetchSource(sourceText, filename); - if (patched === sourceText) return result; - return Object.assign({}, result, { source: patched }); - }, - }); - } - } - - installPatch(); -})(); diff --git a/test/mattermost-trusted-env-proxy.test.ts b/test/mattermost-trusted-env-proxy.test.ts deleted file mode 100644 index 53f470c26b2..00000000000 --- a/test/mattermost-trusted-env-proxy.test.ts +++ /dev/null @@ -1,134 +0,0 @@ -// @ts-nocheck -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { spawnSync } from "node:child_process"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { describe, expect, it } from "vitest"; - -const PRELOAD_PATH = path.join( - import.meta.dirname, - "..", - "src", - "lib", - "messaging", - "channels", - "mattermost", - "runtime", - "mattermost-trusted-env-proxy.ts", -); - -function runDriver(driverBody: string) { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mattermost-proxy-")); - const driverPath = path.join(tmpDir, "driver.js"); - try { - fs.writeFileSync(driverPath, driverBody); - return spawnSync(process.execPath, [driverPath], { - encoding: "utf-8", - env: { - PATH: process.env.PATH || "/usr/bin:/bin", - PRELOAD_PATH, - TEST_ROOT: tmpDir, - }, - timeout: 5_000, - }); - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } -} - -describe("mattermost trusted env-proxy preload", () => { - it("patches the Mattermost API and probe guarded-fetch call sites", () => { - const result = runDriver(String.raw` - const fs = require("node:fs"); - const path = require("node:path"); - const openclawDist = path.join(process.env.TEST_ROOT, "node_modules", "openclaw", "dist"); - fs.mkdirSync(openclawDist, { recursive: true }); - const fixture = path.join(openclawDist, "mattermost-fixture.js"); - fs.writeFileSync(fixture, [ - "const calls = [];", - "function fetchWithSsrFGuard(params) { calls.push(params); return params; }", - "function ssrfPolicyFromPrivateNetworkOptIn(value) { return value; }", - "fetchWithSsrFGuard({", - " url: 'https://chat.example.com/api/v4/users/me',", - " init: {},", - " auditContext: \"mattermost-api\",", - " policy: ssrfPolicyFromPrivateNetworkOptIn(false),", - "});", - "fetchWithSsrFGuard({", - " url: 'https://chat.example.com/api/v4/users/me',", - " init: {},", - " auditContext: \"mattermost-probe\",", - " policy: ssrfPolicyFromPrivateNetworkOptIn(false),", - "});", - "module.exports = calls;", - ].join(String.fromCharCode(10))); - - require(process.env.PRELOAD_PATH); - const calls = require(fixture); - console.log(JSON.stringify(calls.map((call) => ({ - auditContext: call.auditContext, - mode: call.mode, - })))); - `); - - expect(result.status, result.stderr || result.stdout).toBe(0); - expect(result.stderr).toBe(""); - expect(JSON.parse(result.stdout.trim())).toEqual([ - { auditContext: "mattermost-api", mode: "trusted_env_proxy" }, - { auditContext: "mattermost-probe", mode: "trusted_env_proxy" }, - ]); - }); - - it("fails closed when a Mattermost guarded-fetch call shape is ambiguous", () => { - const result = runDriver(String.raw` - const fs = require("node:fs"); - const path = require("node:path"); - const openclawDist = path.join(process.env.TEST_ROOT, "node_modules", "openclaw", "dist"); - fs.mkdirSync(openclawDist, { recursive: true }); - const fixture = path.join(openclawDist, "mattermost-ambiguous.js"); - fs.writeFileSync(fixture, [ - "function fetchWithSsrFGuard(params) { return params; }", - "fetchWithSsrFGuard({ auditContext: \"mattermost-api\" });", - "fetchWithSsrFGuard({ auditContext: \"mattermost-api\" });", - ].join(String.fromCharCode(10))); - - require(process.env.PRELOAD_PATH); - require(fixture); - `); - - expect(result.status).not.toBe(0); - expect(result.stderr).toContain("expected one mattermost-api audit context"); - }); - - it("leaves non-Mattermost guarded-fetch call sites untouched", () => { - const result = runDriver(String.raw` - const fs = require("node:fs"); - const path = require("node:path"); - const openclawDist = path.join(process.env.TEST_ROOT, "node_modules", "openclaw", "dist"); - fs.mkdirSync(openclawDist, { recursive: true }); - const fixture = path.join(openclawDist, "other-fixture.js"); - fs.writeFileSync(fixture, [ - "const calls = [];", - "function fetchWithSsrFGuard(params) { calls.push(params); return params; }", - "fetchWithSsrFGuard({", - " url: 'https://example.com',", - " auditContext: \"other-api\",", - "});", - "module.exports = calls;", - ].join(String.fromCharCode(10))); - - require(process.env.PRELOAD_PATH); - const calls = require(fixture); - console.log(JSON.stringify(calls[0])); - `); - - expect(result.status, result.stderr || result.stdout).toBe(0); - expect(JSON.parse(result.stdout.trim())).toEqual({ - url: "https://example.com", - auditContext: "other-api", - }); - }); -});