From 0cd06526297f9dfbc23ba1f1dc044b4ddad7ec80 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Wed, 28 Oct 2026 05:08:21 +0000 Subject: [PATCH 1/4] fix(policy): bind web-search preset endpoints to their provider Signed-off-by: Tinson Lai --- .../quickstart-langchain-deepagents-code.mdx | 2 + docs/reference/troubleshooting.mdx | 4 + docs/security/credential-storage.mdx | 4 + .../onboard/sandbox-create/orchestration.ts | 4 + .../rebuild-policy-handoff.test.ts | 61 ++++++ .../sandbox-create/rebuild-policy-handoff.ts | 46 ++++- src/lib/policy/index.ts | 46 ++++- src/lib/policy/preset-parsing.test.ts | 184 ++++++++++++++++++ src/lib/policy/preset-parsing.ts | 96 +++++++++ 9 files changed, 439 insertions(+), 8 deletions(-) create mode 100644 src/lib/policy/preset-parsing.test.ts diff --git a/docs/get-started/quickstart-langchain-deepagents-code.mdx b/docs/get-started/quickstart-langchain-deepagents-code.mdx index 24137f080ee..f468f626f07 100644 --- a/docs/get-started/quickstart-langchain-deepagents-code.mdx +++ b/docs/get-started/quickstart-langchain-deepagents-code.mdx @@ -237,6 +237,8 @@ nemo-deepagents rebuild The shared `tavily` preset only opens `POST /search` and `POST /extract` egress to `api.tavily.com:443`. Attaching the credential provider alone does not authorize the managed Python interpreter; the explicit policy preset is the interpreter-level opt-in. Export `TAVILY_API_KEY` only for registration, then remove it from the host shell; the gateway injects the stored value at egress, and the sandbox never sees the raw value. NemoClaw does not bake `TAVILY_API_KEY` into the managed config or image, and the managed wrapper rejects direct service-key injection into `dcode`. Because OpenShell attributes the harness's calls to the sandbox `python3` interpreter, this egress is process-wide for sandbox Python rather than a `dcode`-only boundary. +The `tavily` preset binds its endpoint to the `tavily-search` provider that you registered with `nemo-deepagents credentials add`, so OpenShell can replace the `openshell:resolve:env:TAVILY_API_KEY` placeholder at egress. The rebuild also adds the binding when you applied the preset first. If you rebuilt the sandbox before you registered the credential, rebuild it again after registration. + Remove the target sandbox's managed-Python opt-in when it is no longer needed. ```bash diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 061ad6bdc6d..92d7bfe5df7 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -1857,6 +1857,10 @@ If Tavily is still blocked after rebuild, inspect recent policy denials: nemo-deepagents logs --tail 50 ``` +A `credential_unavailable` denial means the `tavily` preset endpoint has no credential binding. +NemoClaw adds the binding only for a `tavily-search` provider that you registered with `nemo-deepagents credentials add`. +Confirm that `nemo-deepagents credentials list` shows `tavily-search`. If the last rebuild ran before you registered it, rebuild the sandbox again. + The `tavily` preset is a managed-Python opt-in. It is process-wide for sandbox Python and is not a `dcode`-only boundary. ### Deep Agents read-only path checks fail diff --git a/docs/security/credential-storage.mdx b/docs/security/credential-storage.mdx index 70441c1f131..2f6e1d08cb8 100644 --- a/docs/security/credential-storage.mdx +++ b/docs/security/credential-storage.mdx @@ -94,6 +94,7 @@ During onboarding, NemoClaw registers the selected key in an OpenShell provider The `credentials add` command registers the key under the provider name that you pass. The documented Deep Agents flow uses the gateway-wide name `tavily-search` without a sandbox prefix; pass that name to `credentials list` and `credentials reset`. +NemoClaw binds the `tavily` preset only to the provider name `tavily-search` or `-tavily-search`. A credential registered under any other name causes `credential_unavailable` denials. Agent configuration uses `openshell:resolve:env:` references instead of raw keys. @@ -120,6 +121,9 @@ The `tavily` policy preset enables request-body credential rewriting so OpenShel For Deep Agents, the managed launch paths reject direct `TAVILY_API_KEY` injection into `dcode`. Register the key with OpenShell through `$$nemoclaw credentials add tavily-search --type tavily --agent dcode --credential TAVILY_API_KEY`, then apply the `tavily` policy preset and rebuild the sandbox so the provider attaches. The `tavily` preset is the sandbox-level network opt-in, while the `tavily-search` provider is gateway-wide and can attach to future sandboxes that you build or rebuild. +Applying the `tavily` preset binds its endpoint to the `tavily-search` provider when `credentials add` has registered it, so OpenShell can replace the placeholder at egress. +The rebuild that attaches the provider also adds the binding when you applied the preset first. +If no `tavily-search` provider is registered, the preset opens egress without a binding and OpenShell denies the request with `credential_unavailable`. Use a dedicated low-scope search key and keep the matching `brave` or `tavily` policy preset applied only while the sandbox needs web search. diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 971064f002a..4198f3efbfb 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -390,6 +390,7 @@ export function selectRebuildCreatePolicy( authorizedCredentialBindingProviders: readonly string[], policySource?: string, inferenceProvider: string | null = null, + webSearchCredentialProviders: readonly string[] = [], ): import("../initial-policy").InitialSandboxPolicy { const requiredNetworkPolicySources = requiredNetworkPolicyPresetNames.map((presetName) => { const source = loadMessagingChannelPolicyPreset(presetName, { @@ -425,6 +426,8 @@ export function selectRebuildCreatePolicy( ], requiredNetworkPolicySources, authorizedCredentialBindingProviders, + webSearchAgentName: messagingAgent, + webSearchCredentialProviders, }); } @@ -3019,6 +3022,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche rebuildPolicyProviderAuthority, rebuildPolicySource?.document, resolvedCreateIntent.inferenceProvider, + resolvedCreateIntent.extraProviders, ) : materializedInitialSandboxPolicy; const createRequestPlan = selectRebuildCreateRequestPlan({ diff --git a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts index 011f7ff8d91..004c147f470 100644 --- a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts +++ b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts @@ -475,6 +475,67 @@ network_policies: expect(handoff.cleanup?.()).toBe(true); }); + it("binds an applied web-search policy to the attached provider", () => { + const livePath = tempPolicy( + "live-web-search.yaml", + `version: 1 +network_policies: + tavily: + name: tavily + endpoints: + - host: api.tavily.com + port: 443 + protocol: rest + enforcement: enforce +`, + ); + const replacementPath = tempPolicy("replacement-web-search.yaml", "version: 1\n"); + + const handoff = materializeRebuildPolicyHandoff({ + sandboxName: "alpha", + livePolicyPath: livePath, + replacementPolicy: { policyPath: replacementPath, appliedPresets: [] }, + webSearchAgentName: "langchain-deepagents-code", + webSearchCredentialProviders: ["tavily-search"], + }); + + expect(handoff.credentialBindingProviders).toEqual(["tavily-search"]); + const endpoint = readPrivatePolicy(handoff.policyPath).policy as { + network_policies: { tavily: { endpoints: Array> } }; + }; + expect(endpoint.network_policies.tavily.endpoints[0]!.credential_binding).toEqual({ + provider: "tavily-search", + }); + expect(handoff.cleanup?.()).toBe(true); + }); + + it("leaves an applied web-search policy unbound without an attached provider", () => { + const source = `version: 1 +network_policies: + tavily: + name: tavily + endpoints: + - host: api.tavily.com + port: 443 + protocol: rest + enforcement: enforce +`; + const livePath = tempPolicy("live-unbound.yaml", source); + const replacementPath = tempPolicy("replacement-unbound.yaml", source); + + const handoff = materializeRebuildPolicyHandoff({ + sandboxName: "alpha", + livePolicyPath: livePath, + livePolicySource: source, + replacementPolicy: { policyPath: replacementPath, appliedPresets: [] }, + webSearchAgentName: "langchain-deepagents-code", + webSearchCredentialProviders: [], + }); + + expect(handoff.credentialBindingProviders).toEqual([]); + expect(fs.readFileSync(handoff.policyPath, "utf8")).toBe(source); + }); + it("rejects live credential bindings outside the verified replacement plan", () => { const livePath = tempPolicy( "live-provider.yaml", diff --git a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts index faac085c290..032e44d3fac 100644 --- a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts +++ b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts @@ -11,6 +11,7 @@ import { } from "../../adapters/openshell/policy-boundary"; import { isReviewedMessagingChannelPolicyUpgrade } from "../../messaging/channels/policy"; import { reconcileTeamsOutlookLoginCredentialBinding } from "../../policy/microsoft-login-credential-binding"; +import { bindWebSearchPresetProviders } from "../../policy/preset-parsing"; import { parseAndValidateSandboxPolicy } from "../../policy/sandbox-policy-validation"; import { getCredentialBindingProviders, type InitialSandboxPolicy } from "../initial-policy"; import { cleanupTempDir, createExactTempFileCleanup, secureTempFile } from "../temp-files"; @@ -312,6 +313,35 @@ export function mergeReplacementPolicyAccess( : { changed: false, source: normalizedLivePolicySource }; } +function bindRebuildWebSearchProviders( + source: string, + input: { + readonly sandboxName?: string; + readonly webSearchAgentName?: string | null; + readonly webSearchCredentialProviders?: readonly string[]; + }, +): string { + const providers = input.webSearchCredentialProviders ?? []; + if (!input.sandboxName || providers.length === 0) return source; + return bindWebSearchPresetProviders({ + content: source, + sandboxName: input.sandboxName, + agentName: input.webSearchAgentName, + availableProviders: new Set(providers), + }); +} + +/** Providers this handoff may bind: the verified replacement plan and the attached web-search providers. */ +function handoffAuthorizedProviders(input: { + readonly authorizedCredentialBindingProviders?: readonly string[]; + readonly webSearchCredentialProviders?: readonly string[]; +}): string[] { + return [ + ...(input.authorizedCredentialBindingProviders ?? []), + ...(input.webSearchCredentialProviders ?? []), + ]; +} + /** Materialize the single ephemeral policy input consumed by an explicit rebuild. */ export function materializeRebuildPolicyHandoff(input: { readonly sandboxName?: string; @@ -322,6 +352,8 @@ export function materializeRebuildPolicyHandoff(input: { readonly removedNetworkPolicyKeys?: readonly string[]; readonly requiredNetworkPolicySources?: readonly string[]; readonly authorizedCredentialBindingProviders?: readonly string[]; + readonly webSearchAgentName?: string | null; + readonly webSearchCredentialProviders?: readonly string[]; }): InitialSandboxPolicy { const liveSource = input.livePolicySource ?? fs.readFileSync(input.livePolicyPath, "utf8"); const replacementSource = @@ -335,7 +367,9 @@ export function materializeRebuildPolicyHandoff(input: { input.requiredNetworkPolicySources, input.sandboxName, ); - if (!merged.changed && input.livePolicySource === undefined) { + const boundSource = bindRebuildWebSearchProviders(merged.source, input); + const changed = merged.changed || boundSource !== merged.source; + if (!changed && input.livePolicySource === undefined) { return { ...input.replacementPolicy, policyPath: input.livePolicyPath, @@ -343,7 +377,7 @@ export function materializeRebuildPolicyHandoff(input: { credentialBindingProviders: authorizedCredentialBindingProviders( liveSource, input.replacementPolicy, - input.authorizedCredentialBindingProviders ?? [], + handoffAuthorizedProviders(input), ), sourceBytes: Buffer.from(liveSource), }; @@ -351,7 +385,7 @@ export function materializeRebuildPolicyHandoff(input: { const policyPath = secureTempFile(REBUILD_POLICY_HANDOFF_PREFIX, ".yaml"); try { - fs.writeFileSync(policyPath, merged.source, { + fs.writeFileSync(policyPath, boundSource, { encoding: "utf8", flag: "wx", mode: 0o600, @@ -367,11 +401,11 @@ export function materializeRebuildPolicyHandoff(input: { policyPath, appliedPresets: [], credentialBindingProviders: authorizedCredentialBindingProviders( - merged.source, + boundSource, input.replacementPolicy, - input.authorizedCredentialBindingProviders ?? [], + handoffAuthorizedProviders(input), ), - sourceBytes: Buffer.from(merged.source), + sourceBytes: Buffer.from(boundSource), cleanup, cleanupExact: cleanup, }; diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index cd8cb1d7974..e64fa95b40b 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -79,6 +79,9 @@ import { type PolicyObject, type PolicyValue, parseNetworkPolicies, + applyWebSearchCredentialBinding, + isWebSearchPolicyPreset, + resolveWebSearchCredentialProvider, } from "./preset-parsing"; import { escapeTerminalText, logPresetScope, renderPresetScope } from "./preset-scope-render"; import { parseAndValidateSandboxPolicy } from "./sandbox-policy-validation"; @@ -412,6 +415,39 @@ function loadAgentPresetContent( } } +/** + * Providers the sandbox create plan attaches. A credential binding that names + * any other provider fails the create-time provider check, so web-search + * presets bind only a provider recorded here. + */ +function recordedWebSearchProviders(): Set { + try { + return new Set(registry.listExtraProviders()); + } catch { + // Preset loading must not fail on an unreadable extra-provider registry. + return new Set(); + } +} + +function bindWebSearchPreset( + content: string, + presetName: string, + sandboxName: string, + agentName: string | null, +): string { + if (!isWebSearchPolicyPreset(presetName)) return content; + return applyWebSearchCredentialBinding( + content, + presetName, + resolveWebSearchCredentialProvider({ + presetName, + sandboxName, + agentName, + availableProviders: recordedWebSearchProviders(), + }), + ); +} + /** * Resolve a preset across messaging, central or agent, and live custom sources. * Source misses stay silent so callers report only after the composite lookup fails. @@ -465,11 +501,17 @@ async function loadPresetForSandbox( const resolvedPresetContent = loadAgentPresetContent(sandboxName, presetName, builtinPresetContent, options.sandbox) || builtinPresetContent; + const boundPresetContent = bindWebSearchPreset( + resolvedPresetContent, + presetName, + sandboxName, + sandboxAgent, + ); return presetName === "outlook" && sandboxAgent !== "hermes" && configuredMessagingChannels.includes("teams") - ? reconcileTeamsOutlookLoginCredentialBinding(resolvedPresetContent, sandboxName, true) - : resolvedPresetContent; + ? reconcileTeamsOutlookLoginCredentialBinding(boundPresetContent, sandboxName, true) + : boundPresetContent; } /** diff --git a/src/lib/policy/preset-parsing.test.ts b/src/lib/policy/preset-parsing.test.ts new file mode 100644 index 00000000000..9d10451f4a9 --- /dev/null +++ b/src/lib/policy/preset-parsing.test.ts @@ -0,0 +1,184 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import YAML from "yaml"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + getSandbox: vi.fn(), + listExtraProviders: vi.fn(), +})); + +vi.mock("../state/registry", async (importOriginal) => ({ + ...(await importOriginal()), + getSandbox: mocks.getSandbox, + listExtraProviders: mocks.listExtraProviders, +})); + +import { loadPresetForSandbox } from "./index"; +import { + applyWebSearchCredentialBinding, + bindWebSearchPresetProviders, + isWebSearchPolicyPreset, + resolveWebSearchCredentialProvider, + webSearchCredentialProviderCandidates, +} from "./preset-parsing"; + +const sandboxName = "alpha"; +const tavilyPreset = `preset:\n name: tavily\n description: Tavily Search API access\nnetwork_policies:\n tavily:\n name: tavily\n endpoints:\n - host: api.tavily.com\n port: 443\n protocol: rest\n enforcement: enforce\n request_body_credential_rewrite: true\n rules:\n - allow: { method: POST, path: "/search" }\n`; + +function tavilyEndpoints(content: string): Array> { + return YAML.parse(content).network_policies.tavily.endpoints; +} + +describe("web-search credential provider resolution", () => { + it("recognizes the web-search presets", () => { + expect(isWebSearchPolicyPreset("tavily")).toBe(true); + expect(isWebSearchPolicyPreset("brave")).toBe(true); + expect(isWebSearchPolicyPreset("weather")).toBe(false); + }); + + it("prefers the gateway-wide provider for Deep Agents", () => { + expect( + webSearchCredentialProviderCandidates("tavily", sandboxName, "langchain-deepagents-code"), + ).toEqual(["tavily-search", `${sandboxName}-tavily-search`]); + }); + + it("prefers the sandbox-scoped provider for OpenClaw and Hermes", () => { + expect(webSearchCredentialProviderCandidates("tavily", sandboxName, "openclaw")).toEqual([ + `${sandboxName}-tavily-search`, + "tavily-search", + ]); + expect(webSearchCredentialProviderCandidates("brave", sandboxName, "hermes")).toEqual([ + `${sandboxName}-brave-search`, + "brave-search", + ]); + }); + + it("resolves only a provider that is recorded", () => { + expect( + resolveWebSearchCredentialProvider({ + presetName: "tavily", + sandboxName, + agentName: "langchain-deepagents-code", + availableProviders: new Set(["tavily-search"]), + }), + ).toBe("tavily-search"); + expect( + resolveWebSearchCredentialProvider({ + presetName: "tavily", + sandboxName, + agentName: "openclaw", + availableProviders: new Set(["tavily-search"]), + }), + ).toBe("tavily-search"); + expect( + resolveWebSearchCredentialProvider({ + presetName: "tavily", + sandboxName, + agentName: "openclaw", + availableProviders: new Set(), + }), + ).toBeNull(); + }); +}); + +describe("web-search credential binding", () => { + it("binds every unbound endpoint of the preset policy", () => { + const bound = applyWebSearchCredentialBinding(tavilyPreset, "tavily", "tavily-search"); + expect(tavilyEndpoints(bound)).toEqual([ + expect.objectContaining({ credential_binding: { provider: "tavily-search" } }), + ]); + }); + + it("leaves the preset unchanged when no provider is resolved", () => { + expect(applyWebSearchCredentialBinding(tavilyPreset, "tavily", null)).toBe(tavilyPreset); + }); + + it("preserves an existing credential binding", () => { + const existing = tavilyPreset.replace( + " request_body_credential_rewrite: true\n", + " request_body_credential_rewrite: true\n credential_binding:\n provider: operator-provider\n", + ); + expect(applyWebSearchCredentialBinding(existing, "tavily", "tavily-search")).toBe(existing); + }); + + it("binds each web-search policy present in a sandbox policy document", () => { + const document = `version: 1\nnetwork_policies:\n tavily:\n endpoints:\n - host: api.tavily.com\n port: 443\n brave:\n endpoints:\n - host: api.search.brave.com\n port: 443\n weather:\n endpoints:\n - host: wttr.in\n port: 443\n`; + const bound = bindWebSearchPresetProviders({ + content: document, + sandboxName, + agentName: "langchain-deepagents-code", + availableProviders: new Set(["tavily-search"]), + }); + const parsed = YAML.parse(bound).network_policies; + expect(parsed.tavily.endpoints[0].credential_binding).toEqual({ provider: "tavily-search" }); + expect(parsed.brave.endpoints[0].credential_binding).toBeUndefined(); + expect(parsed.weather.endpoints[0].credential_binding).toBeUndefined(); + }); +}); + +describe("loadPresetForSandbox web-search binding", () => { + beforeEach(() => { + mocks.getSandbox.mockReset(); + mocks.listExtraProviders.mockReset(); + }); + + it("binds the gateway-wide provider for a Deep Agents sandbox", async () => { + mocks.getSandbox.mockReturnValue({ + name: sandboxName, + agent: "langchain-deepagents-code", + gatewayName: "nemoclaw", + }); + mocks.listExtraProviders.mockReturnValue(["tavily-search"]); + + const content = await loadPresetForSandbox(sandboxName, "tavily"); + + expect(content).not.toBeNull(); + expect(tavilyEndpoints(content!)).toEqual([ + expect.objectContaining({ credential_binding: { provider: "tavily-search" } }), + ]); + }); + + it("binds the sandbox-scoped provider for an OpenClaw sandbox", async () => { + mocks.getSandbox.mockReturnValue({ + name: sandboxName, + agent: "openclaw", + gatewayName: "nemoclaw", + }); + mocks.listExtraProviders.mockReturnValue([`${sandboxName}-tavily-search`]); + + const content = await loadPresetForSandbox(sandboxName, "tavily"); + + expect(tavilyEndpoints(content!)).toEqual([ + expect.objectContaining({ credential_binding: { provider: `${sandboxName}-tavily-search` } }), + ]); + }); + + it("omits the binding when no web-search provider is recorded", async () => { + mocks.getSandbox.mockReturnValue({ + name: sandboxName, + agent: "langchain-deepagents-code", + gatewayName: "nemoclaw", + }); + mocks.listExtraProviders.mockReturnValue([]); + + const content = await loadPresetForSandbox(sandboxName, "tavily"); + + expect(tavilyEndpoints(content!)).toEqual([ + expect.not.objectContaining({ credential_binding: expect.anything() }), + ]); + }); + + it("leaves a non-web-search preset unbound", async () => { + mocks.getSandbox.mockReturnValue({ name: sandboxName, agent: "openclaw" }); + mocks.listExtraProviders.mockReturnValue(["tavily-search"]); + + const content = await loadPresetForSandbox(sandboxName, "weather"); + + expect(content).not.toBeNull(); + const endpoints = YAML.parse(content!).network_policies.weather.endpoints; + expect(endpoints.length).toBeGreaterThan(0); + expect(endpoints.some((endpoint: object) => "credential_binding" in endpoint)).toBe(false); + }); +}); diff --git a/src/lib/policy/preset-parsing.ts b/src/lib/policy/preset-parsing.ts index e4d53b1b8e8..ab7c8b1f154 100644 --- a/src/lib/policy/preset-parsing.ts +++ b/src/lib/policy/preset-parsing.ts @@ -6,6 +6,7 @@ import YAML from "yaml"; import { isObjectRecord, type JsonObject, type JsonValue } from "../core/json-types"; import { DEFAULT_VLLM_PORT, VLLM_PORT } from "../core/vllm-port"; +import { isDcodeAgent } from "../onboard/observability-policy-presets"; export type PolicyValue = JsonValue; export type PolicyObject = JsonObject; @@ -143,3 +144,98 @@ export function materializeLocalInferencePresetPorts(content: string): string { vllmEndpoints[0].port = VLLM_PORT; return YAML.stringify(document); } + +const WEB_SEARCH_PRESET_PROVIDER_SUFFIXES: Readonly> = { + brave: "brave-search", + tavily: "tavily-search", +}; + +export function isWebSearchPolicyPreset(presetName: string): boolean { + return Object.hasOwn(WEB_SEARCH_PRESET_PROVIDER_SUFFIXES, presetName); +} + +/** + * OpenClaw and Hermes register a sandbox-scoped web-search provider during + * onboarding. Deep Agents registers the gateway-wide name because its opt-in + * runs after the sandbox exists. + */ +export function webSearchCredentialProviderCandidates( + presetName: string, + sandboxName: string, + agentName: string | null | undefined, +): readonly string[] { + const suffix = WEB_SEARCH_PRESET_PROVIDER_SUFFIXES[presetName]; + if (!suffix || !sandboxName) return []; + const scoped = `${sandboxName}-${suffix}`; + return isDcodeAgent(agentName) ? [suffix, scoped] : [scoped, suffix]; +} + +export function resolveWebSearchCredentialProvider(input: { + readonly presetName: string; + readonly sandboxName: string; + readonly agentName?: string | null; + readonly availableProviders: ReadonlySet; +}): string | null { + for (const candidate of webSearchCredentialProviderCandidates( + input.presetName, + input.sandboxName, + input.agentName, + )) { + if (input.availableProviders.has(candidate)) return candidate; + } + return null; +} + +/** + * Bind a web-search preset endpoint to the provider that holds its credential. + * OpenShell resolves a static credential only at an endpoint that names its + * provider, so an unbound endpoint denies the request after the network and L7 + * stages allow it. + */ +export function applyWebSearchCredentialBinding( + content: string, + presetName: string, + providerName: string | null, +): string { + if (!providerName) return content; + let parsed: PolicyValue; + try { + parsed = YAML.parse(content); + } catch { + return content; + } + if (!isPolicyDocument(parsed) || !isPolicyObject(parsed.network_policies)) return content; + const policy = parsed.network_policies[presetName]; + if (!isPolicyObject(policy) || !Array.isArray(policy.endpoints)) return content; + let changed = false; + for (const endpoint of policy.endpoints) { + if (!isPolicyObject(endpoint) || Object.hasOwn(endpoint, "credential_binding")) continue; + endpoint.credential_binding = { provider: providerName }; + changed = true; + } + return changed ? YAML.stringify(parsed) : content; +} + +/** + * Bind every web-search policy already present in a sandbox policy document. + * Only providers the sandbox create plan attaches qualify: a binding that names + * any other provider fails the create-time provider check. + */ +export function bindWebSearchPresetProviders(input: { + readonly content: string; + readonly sandboxName: string; + readonly agentName?: string | null; + readonly availableProviders: ReadonlySet; +}): string { + let content = input.content; + for (const presetName of Object.keys(WEB_SEARCH_PRESET_PROVIDER_SUFFIXES)) { + const providerName = resolveWebSearchCredentialProvider({ + presetName, + sandboxName: input.sandboxName, + agentName: input.agentName, + availableProviders: input.availableProviders, + }); + content = applyWebSearchCredentialBinding(content, presetName, providerName); + } + return content; +} From a47d34388a064518bffde0e668c50dd015e6ef4e Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Wed, 28 Oct 2026 16:02:31 +0000 Subject: [PATCH 2/4] fix(policy): bind Tavily credentials only to the preset endpoint A policy binding that names an endpoint-bearing profile is rejected, and a binding granted from the policy key alone delivers the credential to a substituted endpoint. Signed-off-by: Tinson Lai --- .../quickstart-langchain-deepagents-code.mdx | 4 +- docs/reference/troubleshooting.mdx | 16 +- docs/security/credential-storage.mdx | 8 +- .../tavily-policy-binding-v1.yaml | 24 +++ src/commands/credentials.test.ts | 8 +- .../live-export-search-source-test-fixture.ts | 122 +++++++++++ .../config/live-export-source-tavily.test.ts | 141 ++++++++++++ .../config/live-export-source.test.ts | 200 +----------------- src/lib/adapters/openshell/providers.test.ts | 90 ++++---- src/lib/adapters/openshell/providers.ts | 2 + src/lib/adapters/openshell/sdk-read-schema.ts | 19 ++ .../config/export-source-test-fixture.ts | 2 +- .../config/verify-export-web-search.test.ts | 4 +- .../inference/web-search/provider-profile.ts | 20 +- src/lib/onboard/checkpoint-replay.test.ts | 4 +- .../hermes-portable-build-context-files.ts | 4 + src/lib/onboard/gateway-binding.ts | 25 +++ src/lib/onboard/initial-policy.ts | 3 + src/lib/onboard/messaging-prep.test.ts | 2 +- .../sandbox-create-plan-materialization.ts | 27 ++- .../rebuild-policy-handoff.test.ts | 36 ++++ .../sandbox-create/rebuild-policy-handoff.ts | 27 ++- src/lib/policy/index.ts | 109 +++++++++- src/lib/policy/preset-parsing.test.ts | 70 +++++- src/lib/policy/preset-parsing.ts | 126 ++++++++++- test/fixtures/openshell-provider-profile.ts | 18 ++ 26 files changed, 817 insertions(+), 294 deletions(-) create mode 100644 nemoclaw-blueprint/provider-profiles/tavily-policy-binding-v1.yaml create mode 100644 src/lib/adapters/config/live-export-search-source-test-fixture.ts create mode 100644 src/lib/adapters/config/live-export-source-tavily.test.ts diff --git a/docs/get-started/quickstart-langchain-deepagents-code.mdx b/docs/get-started/quickstart-langchain-deepagents-code.mdx index f468f626f07..9e11edf06dc 100644 --- a/docs/get-started/quickstart-langchain-deepagents-code.mdx +++ b/docs/get-started/quickstart-langchain-deepagents-code.mdx @@ -237,7 +237,7 @@ nemo-deepagents rebuild The shared `tavily` preset only opens `POST /search` and `POST /extract` egress to `api.tavily.com:443`. Attaching the credential provider alone does not authorize the managed Python interpreter; the explicit policy preset is the interpreter-level opt-in. Export `TAVILY_API_KEY` only for registration, then remove it from the host shell; the gateway injects the stored value at egress, and the sandbox never sees the raw value. NemoClaw does not bake `TAVILY_API_KEY` into the managed config or image, and the managed wrapper rejects direct service-key injection into `dcode`. Because OpenShell attributes the harness's calls to the sandbox `python3` interpreter, this egress is process-wide for sandbox Python rather than a `dcode`-only boundary. -The `tavily` preset binds its endpoint to the `tavily-search` provider that you registered with `nemo-deepagents credentials add`, so OpenShell can replace the `openshell:resolve:env:TAVILY_API_KEY` placeholder at egress. The rebuild also adds the binding when you applied the preset first. If you rebuilt the sandbox before you registered the credential, rebuild it again after registration. +The `tavily` preset binds its endpoint to the attached `tavily-search` provider, so OpenShell can replace the `openshell:resolve:env:TAVILY_API_KEY` placeholder at egress. If the provider is already attached, `policy add` adds the binding. Otherwise, the next rebuild adds it. If `tavily-search` uses the earlier `tavily` profile, reset it, register it again with `--agent dcode`, and rebuild the sandbox. Remove the target sandbox's managed-Python opt-in when it is no longer needed. @@ -245,7 +245,7 @@ Remove the target sandbox's managed-Python opt-in when it is no longer needed. nemo-deepagents policy remove tavily --yes ``` -This does not unregister the gateway-wide `tavily-search` provider; its credential and Node/curl routes remain available to sandboxes that attach it. When no sandbox needs the provider, remove it globally with `nemo-deepagents credentials reset tavily-search --yes`. The command detaches current sandbox attachments, removes the gateway provider, and reports every detached sandbox that you must rebuild after registering a replacement. +This does not unregister the gateway-wide `tavily-search` provider. A provider that uses the `tavily-policy-binding-v1` profile opens no egress, so the sandbox cannot reach Tavily after you remove the preset. A provider that uses the earlier `tavily` profile still opens egress to `api.tavily.com` until you reset it. When no sandbox needs the provider, remove it globally with `nemo-deepagents credentials reset tavily-search --yes`. The command detaches current sandbox attachments, removes the gateway provider, and reports every detached sandbox that you must rebuild after registering a replacement. diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 92d7bfe5df7..ef2463d61cb 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -822,6 +822,8 @@ $$nemoclaw config get --key tools.web.search --format yaml The provider should be `brave` or `tavily` and `enabled` should be `true`. If the provider is wrong, rerun onboarding with `NEMOCLAW_WEB_SEARCH_PROVIDER=brave` or `tavily` and the matching `BRAVE_API_KEY` or `TAVILY_API_KEY`. +If a rebuild reports that `TAVILY_API_KEY` is not available for a sandbox that was onboarded with the earlier `tavily` profile, export `TAVILY_API_KEY` and rerun the rebuild so NemoClaw registers `-tavily-search` with the current profile. + @@ -1857,9 +1859,17 @@ If Tavily is still blocked after rebuild, inspect recent policy denials: nemo-deepagents logs --tail 50 ``` -A `credential_unavailable` denial means the `tavily` preset endpoint has no credential binding. -NemoClaw adds the binding only for a `tavily-search` provider that you registered with `nemo-deepagents credentials add`. -Confirm that `nemo-deepagents credentials list` shows `tavily-search`. If the last rebuild ran before you registered it, rebuild the sandbox again. +A `credential_unavailable` denial means the `tavily` endpoint has no usable credential binding. +NemoClaw adds the binding only for an attached `tavily-search` provider that uses the `tavily-policy-binding-v1` profile. Register it with `--agent dcode`, not `--agent hermes`. +Confirm that `nemo-deepagents credentials list` shows `tavily-search`. If `tavily-search` uses the earlier `tavily` profile, replace it and rebuild the sandbox: + +```bash +nemo-deepagents credentials reset tavily-search --yes +export TAVILY_API_KEY=tvly-... +nemo-deepagents credentials add tavily-search --type tavily --agent dcode --credential TAVILY_API_KEY +unset TAVILY_API_KEY +nemo-deepagents rebuild +``` The `tavily` preset is a managed-Python opt-in. It is process-wide for sandbox Python and is not a `dcode`-only boundary. diff --git a/docs/security/credential-storage.mdx b/docs/security/credential-storage.mdx index 2f6e1d08cb8..8b6dec04367 100644 --- a/docs/security/credential-storage.mdx +++ b/docs/security/credential-storage.mdx @@ -94,10 +94,10 @@ During onboarding, NemoClaw registers the selected key in an OpenShell provider The `credentials add` command registers the key under the provider name that you pass. The documented Deep Agents flow uses the gateway-wide name `tavily-search` without a sandbox prefix; pass that name to `credentials list` and `credentials reset`. -NemoClaw binds the `tavily` preset only to the provider name `tavily-search` or `-tavily-search`. A credential registered under any other name causes `credential_unavailable` denials. Agent configuration uses `openshell:resolve:env:` references instead of raw keys. +NemoClaw binds the `tavily` preset only to an attached provider named `tavily-search` or `-tavily-search`. OpenShell denies requests that use a Tavily credential under any other name with `credential_unavailable`. OpenShell supplies `TAVILY_API_KEY` through the Hermes process environment as a revision-scoped reference such as `openshell:resolve:env:v_TAVILY_API_KEY`. @@ -120,10 +120,10 @@ The `tavily` policy preset enables request-body credential rewriting so OpenShel For Deep Agents, the managed launch paths reject direct `TAVILY_API_KEY` injection into `dcode`. Register the key with OpenShell through `$$nemoclaw credentials add tavily-search --type tavily --agent dcode --credential TAVILY_API_KEY`, then apply the `tavily` policy preset and rebuild the sandbox so the provider attaches. +If `tavily-search` uses the earlier `tavily` profile, run `$$nemoclaw credentials reset tavily-search --yes`, register it again with `--agent dcode`, and rebuild the sandbox. The `tavily` preset is the sandbox-level network opt-in, while the `tavily-search` provider is gateway-wide and can attach to future sandboxes that you build or rebuild. -Applying the `tavily` preset binds its endpoint to the `tavily-search` provider when `credentials add` has registered it, so OpenShell can replace the placeholder at egress. -The rebuild that attaches the provider also adds the binding when you applied the preset first. -If no `tavily-search` provider is registered, the preset opens egress without a binding and OpenShell denies the request with `credential_unavailable`. +When `tavily-search` is attached to the sandbox, `policy add` and `rebuild` bind the `tavily` preset endpoint to that provider, so OpenShell replaces the placeholder at egress. +If `tavily-search` is not attached, the preset opens egress without a binding and OpenShell denies the request with `credential_unavailable`. Use a dedicated low-scope search key and keep the matching `brave` or `tavily` policy preset applied only while the sandbox needs web search. diff --git a/nemoclaw-blueprint/provider-profiles/tavily-policy-binding-v1.yaml b/nemoclaw-blueprint/provider-profiles/tavily-policy-binding-v1.yaml new file mode 100644 index 00000000000..ff22e0a3158 --- /dev/null +++ b/nemoclaw-blueprint/provider-profiles/tavily-policy-binding-v1.yaml @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Endpointless carrier for a Tavily credential bound by the tavily policy preset. +# OpenShell withholds a static credential stored under a profile that declares +# no endpoints until the sandbox policy names that profile's provider in an +# endpoint credential_binding. A profile that already declares endpoints cannot +# supply that binding. The network contract stays with the preset. +id: tavily-policy-binding-v1 +display_name: Tavily credential for policy binding +description: Endpointless profile for a Tavily credential bound by the tavily policy preset +category: agent +credentials: + - name: api_key + description: Tavily Search API key + env_vars: + - TAVILY_API_KEY + required: true + auth_style: bearer + header_name: authorization + query_param: '' +endpoints: [] +binaries: [] +inference_capable: false diff --git a/src/commands/credentials.test.ts b/src/commands/credentials.test.ts index de036c02158..c34dc0e3010 100644 --- a/src/commands/credentials.test.ts +++ b/src/commands/credentials.test.ts @@ -79,8 +79,8 @@ describe("credentials oclif adapter source coverage", () => { ["TaViLy", "nemohermes", "tavily-hermes-v1"], ["tavily-hermes-v1", "hermes", "tavily-hermes-v1"], ["tavily-hermes-v1", undefined, "tavily-hermes-v1"], - ["tavily", "dcode", "tavily"], - ["tavily", "openclaw", "tavily"], + ["tavily", "dcode", "tavily-policy-binding-v1"], + ["tavily", "openclaw", "tavily-policy-binding-v1"], ] as const)( "registers %s for %s using the intended runtime profile", async (type, agent, profile) => { @@ -150,7 +150,7 @@ describe("credentials oclif adapter source coverage", () => { const exportedProfile = JSON.stringify( parseYaml( fs.readFileSync( - path.join(rootDir, "nemoclaw-blueprint/provider-profiles/tavily.yaml"), + path.join(rootDir, "nemoclaw-blueprint/provider-profiles/tavily-policy-binding-v1.yaml"), "utf8", ), ), @@ -176,7 +176,7 @@ describe("credentials oclif adapter source coverage", () => { "--name", "shared-search", "--type", - "tavily", + "tavily-policy-binding-v1", "--credential", "TAVILY_API_KEY", ], diff --git a/src/lib/adapters/config/live-export-search-source-test-fixture.ts b/src/lib/adapters/config/live-export-search-source-test-fixture.ts new file mode 100644 index 00000000000..3355e30c9eb --- /dev/null +++ b/src/lib/adapters/config/live-export-search-source-test-fixture.ts @@ -0,0 +1,122 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { mockSupportedLiveSource, raw } from "../../../../test/support/config-export-harness"; +import { + endpointlessTavilyProfile, + managedBraveProfile, + managedTavilyProfile, +} from "../../../../test/fixtures/openshell-provider-profile"; +import { buildManagedStartupProfile } from "../../onboard/managed-startup/profile-builder"; +import type { SandboxEntry } from "../../state/registry/types"; +import { + braveProvider, + entry, + imageRef, + inventory, + provider, + startupInput, +} from "./live-export-source-test-fixture"; + +export function tavilyProfile(agent: "openclaw" | "hermes") { + return agent === "hermes" ? managedTavilyProfile(agent) : endpointlessTavilyProfile(); +} + +function hermesDashboard() { + return { + agent: "hermes" as const, + mode: "disabled" as const, + url: "http://127.0.0.1:18789", + browserUrl: "http://127.0.0.1:18789", + publicPort: null, + internalPort: null, + tuiEnabled: false as const, + }; +} + +function searchStartup(searchProvider: "brave" | "tavily", agent: "openclaw" | "hermes") { + return buildManagedStartupProfile({ + ...startupInput, + agent, + ...(agent === "hermes" + ? { + inference: { ...startupInput.inference, primaryModelRef: null, compatibility: null }, + dashboard: hermesDashboard(), + } + : {}), + webSearch: { fetchEnabled: true, provider: searchProvider }, + }); +} + +function searchRegistry( + searchProvider: "brave" | "tavily", + agent: "openclaw" | "hermes", + runtimeImage: string, + built: ReturnType, +) { + return { + ...entry, + agent, + imageTag: runtimeImage, + ...(agent === "hermes" ? { hermesApiPort: 8642 } : {}), + webSearchEnabled: true, + webSearchProvider: searchProvider, + workload: { + ...(entry.workload as Extract< + NonNullable, + { kind: "managed-image" } + >), + reference: runtimeImage, + encodedProfile: built.encodedProfile, + startupProfileSha256: built.startupProfileSha256, + }, + }; +} + +function searchProviderRow(searchProvider: "brave" | "tavily", agent: "openclaw" | "hermes") { + const base = braveProvider(); + const profile = searchProvider === "brave" ? managedBraveProfile() : tavilyProfile(agent); + const providerName = `alpha-${searchProvider}-search`; + return { + providerName, + profile, + search: { + ...base, + provider: { + ...base.provider, + metadata: { ...base.provider.metadata, name: providerName }, + type: profile.id, + credentials: Object.defineProperty( + {}, + searchProvider === "brave" ? "BRAVE_API_KEY" : "TAVILY_API_KEY", + { + enumerable: true, + get: base.readCredential, + }, + ), + }, + }, + }; +} + +export function mockSearchLiveSource( + searchProvider: "brave" | "tavily", + agent: "openclaw" | "hermes" = "openclaw", +) { + const runtimeImage = + agent === "hermes" ? imageRef.replace("openclaw-sandbox", "hermes-sandbox") : imageRef; + const built = searchStartup(searchProvider, agent); + mockSupportedLiveSource(3, 3, searchRegistry(searchProvider, agent, runtimeImage, built)); + const { providerName, profile, search } = searchProviderRow(searchProvider, agent); + raw.getProviderProfile.mockResolvedValue({ profile }); + raw.getProvider.mockImplementation(async ({ name }: { name: string }) => + name === providerName ? { provider: search.provider } : provider(), + ); + raw.getSandbox.mockResolvedValue({ + sandbox: { + ...inventory().sandbox, + spec: { template: { image: runtimeImage }, providers: [providerName] }, + }, + }); + return search; +} diff --git a/src/lib/adapters/config/live-export-source-tavily.test.ts b/src/lib/adapters/config/live-export-source-tavily.test.ts new file mode 100644 index 00000000000..4b35918bb89 --- /dev/null +++ b/src/lib/adapters/config/live-export-source-tavily.test.ts @@ -0,0 +1,141 @@ +// 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 { exportLiveSource, raw } from "../../../../test/support/config-export-harness"; +import { mockSearchLiveSource, tavilyProfile } from "./live-export-search-source-test-fixture"; +import { asExportedConfig } from "../../../../test/support/config-export-document"; +import { + imageRef, + inventory, + provider, + readFailureCanary, +} from "./live-export-source-test-fixture"; + +describe("live Tavily export", () => { + it.each(["openclaw", "hermes"] as const)( + "exports %s Tavily from verified SDK reads without reading credential values (#12138)", + async (agent) => { + const search = mockSearchLiveSource("tavily", agent); + const { result, writeStdout, publish } = await exportLiveSource(); + expect(result).toEqual({ ok: true, completion: { kind: "stdout" } }); + const yaml = writeStdout.mock.calls[0]![0]; + const document = asExportedConfig(YAML.parse(yaml)); + const sandbox = document.spec.sandboxes[0]!; + expect(sandbox.harness.kind).toBe(agent); + expect(sandbox.integrations).toEqual({ + "tavily-search": { + kind: "webSearch", + provider: "tavily", + credential: { env: "TAVILY_API_KEY" }, + }, + }); + expect(sandbox.agent.integrationRefs).toEqual(["tavily-search"]); + expect(raw.getProvider.mock.calls.map(([request]) => request.name)).toEqual([ + "nvidia-prod", + "alpha-tavily-search", + "nvidia-prod", + "alpha-tavily-search", + ]); + expect(raw.getProviderProfile).toHaveBeenCalledWith( + { + id: agent === "hermes" ? "tavily-hermes-v1" : "tavily-policy-binding-v1", + workspace: "default", + }, + { signal: expect.any(AbortSignal) }, + ); + expect(search.readCredential).not.toHaveBeenCalled(); + expect(yaml).not.toContain(readFailureCanary); + expect(publish).not.toHaveBeenCalled(); + }, + ); + + describe.each(["openclaw", "hermes"] as const)("%s Tavily export refusal", (agent) => { + it.each([ + [ + "provider evidence is missing", + () => + raw.getProvider.mockImplementation(async ({ name }: { name: string }) => + name === "alpha-tavily-search" + ? Promise.reject(Object.assign(new Error(readFailureCanary), { code: 5 })) + : provider(), + ), + ], + [ + "the sandbox attaches a different provider", + () => + raw.getSandbox.mockResolvedValue({ + sandbox: { + ...inventory().sandbox, + spec: { + template: { + image: + agent === "hermes" + ? imageRef.replace("openclaw-sandbox", "hermes-sandbox") + : imageRef, + }, + providers: ["other-tavily-search"], + }, + }, + }), + ], + [ + "the profile executable differs", + () => + raw.getProviderProfile.mockResolvedValue({ + profile: { ...tavilyProfile(agent), binaries: [{ path: "/usr/bin/python" }] }, + }), + ], + [ + "the profile adds a read-write access preset", + () => { + const profile = tavilyProfile(agent); + raw.getProviderProfile.mockResolvedValue({ + profile: + agent === "hermes" + ? { ...profile, endpoints: [{ ...profile.endpoints[0], access: "read-write" }] } + : { ...profile, endpoints: [{ host: "foreign.example" }] }, + }); + }, + ], + [ + "the profile allows uninspected credentials", + () => { + const profile = tavilyProfile(agent); + raw.getProviderProfile.mockResolvedValue({ + profile: + agent === "hermes" + ? { + ...profile, + endpoints: [{ ...profile.endpoints[0], allowUninspectedCredentials: true }], + } + : { ...profile, binaries: [{ path: "/usr/bin/python" }] }, + }); + }, + ], + [ + "the profile never stabilizes", + () => { + let version = 4n; + raw.getProviderProfile.mockImplementation(async () => ({ + profile: { + ...tavilyProfile(agent), + resourceVersion: version++, + }, + })); + }, + ], + ] as const)("does not publish when %s (#12138)", async (_label, arrange) => { + const search = mockSearchLiveSource("tavily", agent); + arrange(); + const exported = await exportLiveSource(); + expect(exported.result).toMatchObject({ ok: false, failure: { kind: "observation" } }); + expect(exported.writeStdout).not.toHaveBeenCalled(); + expect(exported.publish).not.toHaveBeenCalled(); + expect(search.readCredential).not.toHaveBeenCalled(); + expect(JSON.stringify(exported.result)).not.toContain(readFailureCanary); + }); + }); +}); diff --git a/src/lib/adapters/config/live-export-source.test.ts b/src/lib/adapters/config/live-export-source.test.ts index e9d10fcc8d8..72fd9f49fa0 100644 --- a/src/lib/adapters/config/live-export-source.test.ts +++ b/src/lib/adapters/config/live-export-source.test.ts @@ -24,10 +24,7 @@ import { getSandboxEntryInference } from "../../state/registry-entry-view"; import { createHash } from "node:crypto"; import { assert, describe, expect, it, vi } from "vitest"; import YAML from "yaml"; -import { - managedBraveProfile, - managedTavilyProfile, -} from "../../../../test/fixtures/openshell-provider-profile"; +import { managedBraveProfile } from "../../../../test/fixtures/openshell-provider-profile"; import { runConfigExport } from "../../actions/config/export"; import { parseNemoClawConfigDocumentName, @@ -39,7 +36,7 @@ import { resolveGatewayStateDirForPort } from "../../onboard/gateway/state-dir"; import { buildManagedStartupProfile } from "../../onboard/managed-startup/profile-builder"; import { encodeManagedStartupProfile } from "../../onboard/managed-startup/profile"; import { load as loadRegistry } from "../../state/registry/persistence"; -import type { SandboxEntry } from "../../state/registry/types"; + import { observeStableExportSource } from "../../actions/config/observe-export-source"; import { captureSanitizedResolvedOpenshell } from "../openshell/sanitized-capture"; import { createLiveExportSnapshotReader } from "./live-export-source"; @@ -59,82 +56,9 @@ import { nativeNvidiaProfile, telemetryEntry, dashboardSource, - braveProvider, } from "./live-export-source-test-fixture"; -function mockSearchLiveSource( - searchProvider: "brave" | "tavily", - agent: "openclaw" | "hermes" = "openclaw", -) { - const runtimeImage = - agent === "hermes" ? imageRef.replace("openclaw-sandbox", "hermes-sandbox") : imageRef; - const built = buildManagedStartupProfile({ - ...startupInput, - agent, - ...(agent === "hermes" - ? ({ - inference: { ...startupInput.inference, primaryModelRef: null, compatibility: null }, - dashboard: { - agent: "hermes", - mode: "disabled", - url: "http://127.0.0.1:18789", - browserUrl: "http://127.0.0.1:18789", - publicPort: null, - internalPort: null, - tuiEnabled: false, - }, - } as const) - : {}), - webSearch: { fetchEnabled: true, provider: searchProvider }, - }); - mockSupportedLiveSource(3, 3, { - ...entry, - agent, - imageTag: runtimeImage, - ...(agent === "hermes" ? { hermesApiPort: 8642 } : {}), - webSearchEnabled: true, - webSearchProvider: searchProvider, - workload: { - ...(entry.workload as Extract< - NonNullable, - { kind: "managed-image" } - >), - reference: runtimeImage, - encodedProfile: built.encodedProfile, - startupProfileSha256: built.startupProfileSha256, - }, - }); - const base = braveProvider(); - const profile = searchProvider === "brave" ? managedBraveProfile() : managedTavilyProfile(agent); - const providerName = `alpha-${searchProvider}-search`; - const search = { - ...base, - provider: { - ...base.provider, - metadata: { ...base.provider.metadata, name: providerName }, - type: profile.id, - credentials: Object.defineProperty( - {}, - searchProvider === "brave" ? "BRAVE_API_KEY" : "TAVILY_API_KEY", - { - enumerable: true, - get: base.readCredential, - }, - ), - }, - }; - raw.getProviderProfile.mockResolvedValue({ profile }); - raw.getProvider.mockImplementation(async ({ name }: { name: string }) => - name === providerName ? { provider: search.provider } : provider(), - ); - raw.getSandbox.mockResolvedValue({ - sandbox: { - ...inventory().sandbox, - spec: { template: { image: runtimeImage }, providers: [providerName] }, - }, - }); - return search; -} +import { mockSearchLiveSource } from "./live-export-search-source-test-fixture"; function mockBraveLiveSource() { return mockSearchLiveSource("brave"); @@ -289,124 +213,6 @@ function mockNativeHostedSource(definition: HostedProviderDefinition) { } describe("live export snapshot reader", () => { - it.each(["openclaw", "hermes"] as const)( - "exports %s Tavily from verified SDK reads without reading credential values (#12138)", - async (agent) => { - const search = mockSearchLiveSource("tavily", agent); - const { result, writeStdout, publish } = await exportLiveSource(); - expect(result).toEqual({ ok: true, completion: { kind: "stdout" } }); - const yaml = writeStdout.mock.calls[0]![0]; - const document = asExportedConfig(YAML.parse(yaml)); - const sandbox = document.spec.sandboxes[0]!; - expect(sandbox.harness.kind).toBe(agent); - expect(sandbox.integrations).toEqual({ - "tavily-search": { - kind: "webSearch", - provider: "tavily", - credential: { env: "TAVILY_API_KEY" }, - }, - }); - expect(sandbox.agent.integrationRefs).toEqual(["tavily-search"]); - expect(raw.getProvider.mock.calls.map(([request]) => request.name)).toEqual([ - "nvidia-prod", - "alpha-tavily-search", - "nvidia-prod", - "alpha-tavily-search", - ]); - expect(raw.getProviderProfile).toHaveBeenCalledWith( - { id: agent === "hermes" ? "tavily-hermes-v1" : "tavily", workspace: "default" }, - { signal: expect.any(AbortSignal) }, - ); - expect(search.readCredential).not.toHaveBeenCalled(); - expect(yaml).not.toContain(readFailureCanary); - expect(publish).not.toHaveBeenCalled(); - }, - ); - - describe.each(["openclaw", "hermes"] as const)("%s Tavily export refusal", (agent) => { - it.each([ - [ - "provider evidence is missing", - () => - raw.getProvider.mockImplementation(async ({ name }: { name: string }) => - name === "alpha-tavily-search" - ? Promise.reject(Object.assign(new Error(readFailureCanary), { code: 5 })) - : provider(), - ), - ], - [ - "the sandbox attaches a different provider", - () => - raw.getSandbox.mockResolvedValue({ - sandbox: { - ...inventory().sandbox, - spec: { - template: { - image: - agent === "hermes" - ? imageRef.replace("openclaw-sandbox", "hermes-sandbox") - : imageRef, - }, - providers: ["other-tavily-search"], - }, - }, - }), - ], - [ - "the profile executable differs", - () => - raw.getProviderProfile.mockResolvedValue({ - profile: { ...managedTavilyProfile(agent), binaries: [{ path: "/usr/bin/python" }] }, - }), - ], - [ - "the profile adds a read-write access preset", - () => { - const profile = managedTavilyProfile(agent); - raw.getProviderProfile.mockResolvedValue({ - profile: { - ...profile, - endpoints: [{ ...profile.endpoints[0], access: "read-write" }], - }, - }); - }, - ], - [ - "the profile allows uninspected credentials", - () => { - const profile = managedTavilyProfile(agent); - raw.getProviderProfile.mockResolvedValue({ - profile: { - ...profile, - endpoints: [{ ...profile.endpoints[0], allowUninspectedCredentials: true }], - }, - }); - }, - ], - [ - "the profile never stabilizes", - () => { - let version = 4n; - raw.getProviderProfile.mockImplementation(async () => ({ - profile: { - ...managedTavilyProfile(agent), - resourceVersion: version++, - }, - })); - }, - ], - ] as const)("does not publish when %s (#12138)", async (_label, arrange) => { - const search = mockSearchLiveSource("tavily", agent); - arrange(); - const exported = await exportLiveSource(); - expect(exported.result).toMatchObject({ ok: false, failure: { kind: "observation" } }); - expect(exported.writeStdout).not.toHaveBeenCalled(); - expect(exported.publish).not.toHaveBeenCalled(); - expect(search.readCredential).not.toHaveBeenCalled(); - expect(JSON.stringify(exported.result)).not.toContain(readFailureCanary); - }); - }); - it("exports Brave through SDK metadata without reading its credential value (#10904)", async () => { const search = mockBraveLiveSource(); const { result, writeStdout, publish } = await exportLiveSource(); diff --git a/src/lib/adapters/openshell/providers.test.ts b/src/lib/adapters/openshell/providers.test.ts index 43f3ce48679..6585db1ec88 100644 --- a/src/lib/adapters/openshell/providers.test.ts +++ b/src/lib/adapters/openshell/providers.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; import { + endpointlessTavilyProfile, managedBraveProfile, managedTavilyProfile, } from "../../../../test/fixtures/openshell-provider-profile"; @@ -101,8 +102,10 @@ describe("OpenShell provider evidence", () => { "qualifies %s Tavily with allowUninspectedCredentials=%s without credential reads (#12138)", async (agent, allowUninspectedCredentials) => { const { raw, connect } = fixture(); - const profile = managedTavilyProfile(agent); - const profileContract = agent === "hermes" ? "tavily-hermes-v1" : "tavily"; + const profile = + agent === "hermes" ? managedTavilyProfile(agent) : endpointlessTavilyProfile(); + const profileContract = + agent === "hermes" ? ("tavily-hermes-v1" as const) : ("tavily-policy-binding-v1" as const); const readCredential = vi.fn(() => { throw new Error(canary); }); @@ -154,8 +157,9 @@ describe("OpenShell provider evidence", () => { ); describe.each(["openclaw", "hermes"] as const)("%s Tavily profile contract", (agent) => { - const profileContract = agent === "hermes" ? "tavily-hermes-v1" : "tavily"; - const profile = managedTavilyProfile(agent); + const profile = agent === "hermes" ? managedTavilyProfile(agent) : endpointlessTavilyProfile(); + const profileContract = + agent === "hermes" ? ("tavily-hermes-v1" as const) : ("tavily-policy-binding-v1" as const); const credential = profile.credentials[0]!; const endpoint = profile.endpoints[0]!; it.each([ @@ -176,43 +180,47 @@ describe("OpenShell provider evidence", () => { { credentials: [{ ...credential, headerName: "x-unexpected" }] }, ], ["credential refresh", { credentials: [{ ...credential, refresh: {} }] }], - ["a foreign endpoint", { endpoints: [{ ...endpoint, host: "foreign.example" }] }], - ["a read-write access preset", { endpoints: [{ ...endpoint, access: "read-write" }] }], - [ - "uninspected credentials", - { endpoints: [{ ...endpoint, allowUninspectedCredentials: true }] }, - ], - [ - "disabled body rewriting", - { endpoints: [{ ...endpoint, requestBodyCredentialRewrite: false }] }, - ], - ["missing request rules", { endpoints: [{ ...endpoint, rules: [] }] }], - [ - "a wildcard request path", - { - endpoints: [ - { ...endpoint, rules: [{ allow: { ...endpoint.rules[0]!.allow, path: "/*" } }] }, - ], - }, - ], - [ - "unknown request rule fields", - { - endpoints: [ - { - ...endpoint, - rules: [ - { allow: { ...endpoint.rules[0]!.allow, $unknown: [{}] } }, - endpoint.rules[1], - ], - }, - ], - }, - ], - [ - "a different credential binding", - { endpoints: [{ ...endpoint, credentialBinding: { provider: "other" } }] }, - ], + ...(agent === "hermes" + ? ([ + ["a foreign endpoint", { endpoints: [{ ...endpoint, host: "foreign.example" }] }], + ["a read-write access preset", { endpoints: [{ ...endpoint, access: "read-write" }] }], + [ + "uninspected credentials", + { endpoints: [{ ...endpoint, allowUninspectedCredentials: true }] }, + ], + [ + "disabled body rewriting", + { endpoints: [{ ...endpoint, requestBodyCredentialRewrite: false }] }, + ], + ["missing request rules", { endpoints: [{ ...endpoint, rules: [] }] }], + [ + "a wildcard request path", + { + endpoints: [ + { ...endpoint, rules: [{ allow: { ...endpoint.rules[0]!.allow, path: "/*" } }] }, + ], + }, + ], + [ + "unknown request rule fields", + { + endpoints: [ + { + ...endpoint, + rules: [ + { allow: { ...endpoint.rules[0]!.allow, $unknown: [{}] } }, + endpoint.rules[1], + ], + }, + ], + }, + ], + [ + "a different credential binding", + { endpoints: [{ ...endpoint, credentialBinding: { provider: "other" } }] }, + ], + ] as const) + : []), ["a different executable", { binaries: [{ path: "/usr/bin/python" }] }], ] as const)("rejects %s (#12138)", async (_label, change) => { const { raw, connect } = fixture(); diff --git a/src/lib/adapters/openshell/providers.ts b/src/lib/adapters/openshell/providers.ts index d1481a8a4dc..484edb8333f 100644 --- a/src/lib/adapters/openshell/providers.ts +++ b/src/lib/adapters/openshell/providers.ts @@ -20,6 +20,7 @@ import { ManagedBraveProfileResponseSchema, ManagedTavilyProfileResponseSchema, ManagedHermesTavilyProfileResponseSchema, + EndpointlessTavilyProfileResponseSchema, ManagedOpenAiProfileResponseSchema, BuiltinNvidiaProfileResponseSchema, ProviderResponseSchema, @@ -46,6 +47,7 @@ const managedProfileSchemas = { openai: ManagedOpenAiProfileResponseSchema, tavily: ManagedTavilyProfileResponseSchema, "tavily-hermes-v1": ManagedHermesTavilyProfileResponseSchema, + "tavily-policy-binding-v1": EndpointlessTavilyProfileResponseSchema, }; type ManagedProfileContract = keyof typeof managedProfileSchemas; type ProfileContract = diff --git a/src/lib/adapters/openshell/sdk-read-schema.ts b/src/lib/adapters/openshell/sdk-read-schema.ts index bbefb3ced36..6f8b0c6c625 100644 --- a/src/lib/adapters/openshell/sdk-read-schema.ts +++ b/src/lib/adapters/openshell/sdk-read-schema.ts @@ -187,6 +187,25 @@ export const ManagedHermesTavilyProfileResponseSchema = tavilyProfile("tavily-he "/usr/local/bin/curl", "/usr/bin/curl", ]); +// Endpointless carrier. The tavily policy preset owns the network contract and +// names this profile's provider in credential_binding. +export const EndpointlessTavilyProfileResponseSchema = Type.Object({ + profile: Type.Object({ + ...ManagedProfileIdentity, + id: Type.Literal("tavily-policy-binding-v1"), + inferenceCapable: Type.Literal(false), + endpoints: Type.Tuple([]), + credentials: Type.Tuple([ + Type.Object({ + ...ManagedSearchCredentialFields, + envVars: Type.Tuple([Type.Literal("TAVILY_API_KEY")]), + authStyle: Type.Literal("bearer"), + headerName: Type.Literal("authorization"), + }), + ]), + binaries: Type.Tuple([]), + }), +}); export const ManagedOpenAiProfileResponseSchema = Type.Object({ profile: Type.Object({ ...ManagedProfileIdentity, diff --git a/src/lib/domain/config/export-source-test-fixture.ts b/src/lib/domain/config/export-source-test-fixture.ts index 0a225045d99..069592526c8 100644 --- a/src/lib/domain/config/export-source-test-fixture.ts +++ b/src/lib/domain/config/export-source-test-fixture.ts @@ -330,7 +330,7 @@ export function hermesSnapshot( export function tavilySnapshot(agent: "openclaw" | "hermes" = "openclaw"): ObservedExportSnapshot { const value = agent === "hermes" ? hermesSnapshot() : snapshot(); const input = agent === "hermes" ? hermesProfileInput() : profileInput(); - const profileId = agent === "hermes" ? "tavily-hermes-v1" : "tavily"; + const profileId = agent === "hermes" ? "tavily-hermes-v1" : "tavily-policy-binding-v1"; return { ...value, registry: { diff --git a/src/lib/domain/config/verify-export-web-search.test.ts b/src/lib/domain/config/verify-export-web-search.test.ts index e2195932673..bd67d207eb1 100644 --- a/src/lib/domain/config/verify-export-web-search.test.ts +++ b/src/lib/domain/config/verify-export-web-search.test.ts @@ -25,7 +25,7 @@ function verifiedSource(result: ReturnType) { describe("Tavily export source verification", () => { it.each([ ["openclaw", "brave", "brave", "BRAVE_API_KEY"], - ["openclaw", "tavily", "tavily", "TAVILY_API_KEY"], + ["openclaw", "tavily", "tavily-policy-binding-v1", "TAVILY_API_KEY"], ["hermes", "tavily", "tavily-hermes-v1", "TAVILY_API_KEY"], ] as const)( "preserves the onboard %s %s profile binding during export (#12138)", @@ -55,7 +55,7 @@ describe("Tavily export source verification", () => { expect(exportWebSearchBinding(value.registry)).toEqual({ provider: "tavily", name: "alpha-tavily-search", - profileId: agent === "hermes" ? "tavily-hermes-v1" : "tavily", + profileId: agent === "hermes" ? "tavily-hermes-v1" : "tavily-policy-binding-v1", credentialEnv: "TAVILY_API_KEY", }); const source = verifiedSource(verify(value)); diff --git a/src/lib/inference/web-search/provider-profile.ts b/src/lib/inference/web-search/provider-profile.ts index 013be640226..b7ffee11079 100644 --- a/src/lib/inference/web-search/provider-profile.ts +++ b/src/lib/inference/web-search/provider-profile.ts @@ -7,10 +7,16 @@ export const TAVILY_PROVIDER_PROFILE_ID = "tavily"; // profile so upgrades never accept the earlier Deep Agents-only Tavily binary // allowlist as compatible with Hermes. export const HERMES_TAVILY_PROVIDER_PROFILE_ID = "tavily-hermes-v1"; +// Endpointless carrier for a Tavily credential that the tavily policy preset +// binds. The pinned OpenShell release rejects a credential_binding that names a +// provider whose profile declares endpoints, and it withholds the credential of +// an endpointless profile until the policy names that provider. +export const TAVILY_POLICY_BINDING_PROVIDER_PROFILE_ID = "tavily-policy-binding-v1"; export const WEB_SEARCH_PROVIDER_PROFILE_IDS = [ BRAVE_PROVIDER_PROFILE_ID, TAVILY_PROVIDER_PROFILE_ID, HERMES_TAVILY_PROVIDER_PROFILE_ID, + TAVILY_POLICY_BINDING_PROVIDER_PROFILE_ID, ] as const; export type WebSearchProviderProfileId = (typeof WEB_SEARCH_PROVIDER_PROFILE_IDS)[number]; export const TAVILY_PROVIDER_PROFILE_AGENTS = [ @@ -22,8 +28,16 @@ export const TAVILY_PROVIDER_PROFILE_AGENTS = [ export function webSearchProviderProfileId( provider: Provider, agentName?: string | null, -): Provider | typeof HERMES_TAVILY_PROVIDER_PROFILE_ID { - return provider === TAVILY_PROVIDER_PROFILE_ID && agentName?.trim().toLowerCase() === "hermes" +): + | Provider + | typeof HERMES_TAVILY_PROVIDER_PROFILE_ID + | typeof TAVILY_POLICY_BINDING_PROVIDER_PROFILE_ID { + if (provider !== TAVILY_PROVIDER_PROFILE_ID) return provider; + // Hermes keeps its versioned profile. That profile declares the Tavily + // endpoint, so its attachment delivers the credential without a policy + // binding. Every other agent stores the credential in the endpointless + // carrier, and the tavily preset binding is what delivers it. + return agentName?.trim().toLowerCase() === "hermes" ? HERMES_TAVILY_PROVIDER_PROFILE_ID - : provider; + : TAVILY_POLICY_BINDING_PROVIDER_PROFILE_ID; } diff --git a/src/lib/onboard/checkpoint-replay.test.ts b/src/lib/onboard/checkpoint-replay.test.ts index 5f2e4b3f316..846fd1111b9 100644 --- a/src/lib/onboard/checkpoint-replay.test.ts +++ b/src/lib/onboard/checkpoint-replay.test.ts @@ -279,7 +279,9 @@ describe("observeProviderEffectFingerprint", () => { describe("requiredWebSearchProviderType", () => { it("uses the Hermes Tavily profile only for Hermes Tavily selection", () => { expect(requiredWebSearchProviderType("tavily", { name: "hermes" })).toBe("tavily-hermes-v1"); - expect(requiredWebSearchProviderType("tavily", { name: "openclaw" })).toBe("tavily"); + expect(requiredWebSearchProviderType("tavily", { name: "openclaw" })).toBe( + "tavily-policy-binding-v1", + ); expect(requiredWebSearchProviderType("brave", { name: "hermes" })).toBe("brave"); }); }); diff --git a/src/lib/onboard/experimental/hermes-portable-build-context-files.ts b/src/lib/onboard/experimental/hermes-portable-build-context-files.ts index 1338ddcbb55..2afff79f731 100644 --- a/src/lib/onboard/experimental/hermes-portable-build-context-files.ts +++ b/src/lib/onboard/experimental/hermes-portable-build-context-files.ts @@ -122,6 +122,10 @@ export const HERMES_PORTABLE_BUILD_CONTEXT_FILES = [ { path: "nemoclaw-blueprint/provider-profiles/nemoclaw-mcp-v1.yaml", mode: "100644" }, { path: "nemoclaw-blueprint/provider-profiles/okta-runtime-v1.yaml", mode: "100644" }, { path: "nemoclaw-blueprint/provider-profiles/tavily-hermes-v1.yaml", mode: "100644" }, + { + path: "nemoclaw-blueprint/provider-profiles/tavily-policy-binding-v1.yaml", + mode: "100644", + }, { path: "nemoclaw-blueprint/provider-profiles/tavily.yaml", mode: "100644" }, { path: "nemoclaw-blueprint/router/llm-router", mode: "160000" }, { path: "nemoclaw-blueprint/router/pool-config.yaml", mode: "100644" }, diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index cad6b5c9035..f8624801191 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -61,6 +61,31 @@ export { UnsafeGatewayStateDirectoryError, } from "./gateway/state-dir"; +/** + * Providers the gateway reports as attached to one sandbox. A failed or + * unreadable observation returns null, so the caller adds no credential + * binding rather than submitting one the gateway would reject. + */ +export async function readSandboxProviderAttachments( + sandboxName: string, + sandbox: SandboxGatewayBinding | null, +): Promise { + if (!sandbox) return null; + try { + const { createSandboxes } = + require("../adapters/openshell/sandboxes") as typeof import("../adapters/openshell/sandboxes"); + const row = await createSandboxes().get({ + target: { kind: "named", gatewayName: resolveSandboxGatewayName(sandbox) }, + workspace: "default", + name: sandboxName, + signal: AbortSignal.timeout(5_000), + }); + return row ? row.providers : null; + } catch { + return null; + } +} + /** Resolve one attempt-wide onboarding target without overriding an authoritative rebuild. */ export function resolveCoreOnboardGatewayBinding(options: { authoritativeGateway?: { name: string; port: number } | null; diff --git a/src/lib/onboard/initial-policy.ts b/src/lib/onboard/initial-policy.ts index 8e9e554fb7d..5f4c3bc98f7 100644 --- a/src/lib/onboard/initial-policy.ts +++ b/src/lib/onboard/initial-policy.ts @@ -342,6 +342,8 @@ type InitialPolicyOptions = { sandboxName?: string; policyTier?: string | null; messagingConfig?: MessagingChannelConfig | null; + /** Providers the create plan attaches. A web-search preset binds only a provider named here. */ + plannedProviders?: readonly string[]; }; type PolicyMaterializer = (content: string, prefix: string) => InitialSandboxPolicy; @@ -598,6 +600,7 @@ function resolveInitialSandboxCreatePolicy( sandboxName: options.sandboxName, credentialBoundMessagingChannels: activeMessagingChannels, messagingConfig: options.messagingConfig, + plannedProviders: options.plannedProviders, }); if (mergedPolicy.missingPresets.length > 0) { throw new Error( diff --git a/src/lib/onboard/messaging-prep.test.ts b/src/lib/onboard/messaging-prep.test.ts index cd6e6901aee..10cf2a96ba6 100644 --- a/src/lib/onboard/messaging-prep.test.ts +++ b/src/lib/onboard/messaging-prep.test.ts @@ -382,7 +382,7 @@ describe("prepareCreateSandboxMessaging", () => { name: "demo-tavily-search", envKey: TAVILY_API_KEY_ENV, token: "tvly-store", - providerType: "tavily", + providerType: "tavily-policy-binding-v1", }); }); diff --git a/src/lib/onboard/sandbox-create-plan-materialization.ts b/src/lib/onboard/sandbox-create-plan-materialization.ts index c456437989c..28eb1b14081 100644 --- a/src/lib/onboard/sandbox-create-plan-materialization.ts +++ b/src/lib/onboard/sandbox-create-plan-materialization.ts @@ -225,6 +225,7 @@ export function prepareSandboxCreatePolicy( intent: SandboxCreateIntent, prepareInitialSandboxCreatePolicy: PrepareInitialSandboxCreatePolicy = getInitialSandboxCreatePolicy, messagingConfig?: MaterializeSandboxCreatePlanInput["messagingConfig"], + plannedMessagingProviders: readonly string[] = [], ): { readonly initialSandboxPolicy: InitialSandboxPolicy; readonly compatibilityPolicyPath: string | null; @@ -248,6 +249,11 @@ export function prepareSandboxCreatePolicy( sandboxName: intent.sandboxName, policyTier: intent.policy.options.policyTier, messagingConfig, + plannedProviders: [ + ...(intent.inferenceProvider ? [intent.inferenceProvider] : []), + ...intent.extraProviders, + ...plannedMessagingProviders, + ], }, intent.gpuRoutePlan, prepareInitialSandboxCreatePolicy, @@ -389,16 +395,26 @@ export async function materializeSandboxCreatePlan({ discloseInitialSandboxPolicy, prepareInitialSandboxCreatePolicy = getInitialSandboxCreatePolicy, }: MaterializeSandboxCreatePlanInput): Promise { - const enabledMessagingTokenDefs = validateSandboxCreateIntentBindings(intent, messagingTokenDefs); const driverConfig = buildSandboxDriverConfig( intent, managedStateMounts, managedStateMountDriverId, ); + const enabledMessagingTokenDefs = validateSandboxCreateIntentBindings(intent, messagingTokenDefs); + const plannedMessagingProviders = filterMessagingProvidersForSandboxCreate( + [ + ...enabledMessagingTokenDefs.filter(hasConfiguredMessagingCredential).map(({ name }) => name), + ...intent.reusableMessagingProviders, + ], + intent.messagingProviderRequests, + intent.policy.activeMessagingChannels, + intent.disabledChannelNames, + ); const { initialSandboxPolicy, compatibilityPolicyPath } = prepareSandboxCreatePolicy( intent, prepareInitialSandboxCreatePolicy, messagingConfig, + plannedMessagingProviders, ); const createProviders: string[] = []; @@ -411,15 +427,6 @@ export async function materializeSandboxCreatePlan({ : null; return hermesToolGatewayProvider; }; - const plannedMessagingProviders = filterMessagingProvidersForSandboxCreate( - [ - ...enabledMessagingTokenDefs.filter(hasConfiguredMessagingCredential).map(({ name }) => name), - ...intent.reusableMessagingProviders, - ], - intent.messagingProviderRequests, - intent.policy.activeMessagingChannels, - intent.disabledChannelNames, - ); if (deferSandboxEffectsUntilIdentityVerification) { assertDeferredProviderPlanSupported(intent, plannedMessagingProviders, initialSandboxPolicy); } diff --git a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts index 004c147f470..05e2d4f3d20 100644 --- a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts +++ b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts @@ -487,6 +487,10 @@ network_policies: port: 443 protocol: rest enforcement: enforce + request_body_credential_rewrite: true + rules: + - allow: { method: POST, path: "/search" } + - allow: { method: POST, path: "/extract" } `, ); const replacementPath = tempPolicy("replacement-web-search.yaml", "version: 1\n"); @@ -509,6 +513,38 @@ network_policies: expect(handoff.cleanup?.()).toBe(true); }); + it("leaves a substituted web-search endpoint unbound", () => { + const livePath = tempPolicy( + "live-substituted.yaml", + `version: 1 +network_policies: + tavily: + endpoints: + - host: operator.example + port: 443 + protocol: rest + rules: + - allow: { method: POST, path: "/search" } + - allow: { method: POST, path: "/extract" } +`, + ); + const replacementPath = tempPolicy("replacement-substituted.yaml", "version: 1\n"); + + const handoff = materializeRebuildPolicyHandoff({ + sandboxName: "alpha", + livePolicyPath: livePath, + replacementPolicy: { policyPath: replacementPath, appliedPresets: [] }, + webSearchAgentName: "langchain-deepagents-code", + webSearchCredentialProviders: ["tavily-search"], + }); + + const endpoint = readPrivatePolicy(handoff.policyPath).policy as { + network_policies: { tavily: { endpoints: Array> } }; + }; + expect(handoff.policyPath).toBe(livePath); + expect(endpoint.network_policies.tavily.endpoints[0]!.credential_binding).toBeUndefined(); + }); + it("leaves an applied web-search policy unbound without an attached provider", () => { const source = `version: 1 network_policies: diff --git a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts index 032e44d3fac..b5454e3bebf 100644 --- a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts +++ b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; +import path from "node:path"; import { isDeepStrictEqual } from "node:util"; import YAML from "yaml"; @@ -11,13 +12,36 @@ import { } from "../../adapters/openshell/policy-boundary"; import { isReviewedMessagingChannelPolicyUpgrade } from "../../messaging/channels/policy"; import { reconcileTeamsOutlookLoginCredentialBinding } from "../../policy/microsoft-login-credential-binding"; -import { bindWebSearchPresetProviders } from "../../policy/preset-parsing"; +import { + bindWebSearchPresetProviders, + parseWebSearchEndpointContract, +} from "../../policy/preset-parsing"; import { parseAndValidateSandboxPolicy } from "../../policy/sandbox-policy-validation"; import { getCredentialBindingProviders, type InitialSandboxPolicy } from "../initial-policy"; import { cleanupTempDir, createExactTempFileCleanup, secureTempFile } from "../temp-files"; const REBUILD_POLICY_HANDOFF_PREFIX = "nemoclaw-rebuild-policy-handoff"; +function webSearchRebuildContracts(): Record< + string, + ReturnType +> { + const contracts: Record> = {}; + const presetsDir = path.join( + path.resolve(__dirname, "..", "..", "..", ".."), + "nemoclaw-blueprint", + "policies", + "presets", + ); + for (const presetName of ["brave", "tavily"]) { + const file = path.join(presetsDir, `${presetName}.yaml`); + contracts[presetName] = fs.existsSync(file) + ? parseWebSearchEndpointContract(fs.readFileSync(file, "utf8"), presetName) + : null; + } + return contracts; +} + type PolicyMapping = Record; export function parseRebuildPolicyProviderNames(policyDocument: string): string[] { @@ -328,6 +352,7 @@ function bindRebuildWebSearchProviders( sandboxName: input.sandboxName, agentName: input.webSearchAgentName, availableProviders: new Set(providers), + contracts: webSearchRebuildContracts(), }); } diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index e64fa95b40b..d4a7ab1c3f4 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -40,7 +40,10 @@ import { listMessagingPolicyPresetMetadata, loadMessagingChannelPolicyPreset, } from "../messaging/channels"; -import { resolveSandboxGatewayName } from "../onboard/gateway-binding"; +import { + readSandboxProviderAttachments, + resolveSandboxGatewayName, +} from "../onboard/gateway-binding"; import { assertNoOpenShellGatewayEndpointOverride } from "../openshell-gateway-endpoint-guard"; import { OPENSHELL_SANDBOX_HOST_BRIDGE } from "../private-networks"; import { ROOT } from "../runner"; @@ -81,6 +84,7 @@ import { parseNetworkPolicies, applyWebSearchCredentialBinding, isWebSearchPolicyPreset, + parseWebSearchEndpointContract, resolveWebSearchCredentialProvider, } from "./preset-parsing"; import { escapeTerminalText, logPresetScope, renderPresetScope } from "./preset-scope-render"; @@ -131,6 +135,11 @@ type MergePresetNamesOptions = { sandboxName?: string; credentialBoundMessagingChannels?: readonly string[]; messagingConfig?: MessagingPolicyConfig | null; + /** + * Providers the sandbox create plan attaches. A web-search preset binds only a + * provider named here, because the plan has not attached it yet. + */ + plannedProviders?: readonly string[]; }; type SandboxPresetLoadOptions = { @@ -138,6 +147,9 @@ type SandboxPresetLoadOptions = { messagingConfig?: MessagingPolicyConfig | null; sandbox?: registry.SandboxEntry | null; gatewayName?: string; + /** Providers attached to the sandbox. Null means the observation failed and no binding is added. */ + attachedProviders?: readonly string[] | null; + recordedProviders?: readonly string[]; }; type SetupPolicyPresetSupportOptions = { @@ -420,12 +432,48 @@ function loadAgentPresetContent( * any other provider fails the create-time provider check, so web-search * presets bind only a provider recorded here. */ -function recordedWebSearchProviders(): Set { +function recordedWebSearchProviders(sandboxName: string): Set { + const providers = new Set(); try { - return new Set(registry.listExtraProviders()); + for (const provider of registry.listExtraProviders()) providers.add(provider); } catch { // Preset loading must not fail on an unreadable extra-provider registry. - return new Set(); + } + // Onboarding registers a sandbox-scoped web-search provider without recording + // it as an extra provider. The attachment observation decides whether it binds. + providers.add(`${sandboxName}-brave-search`); + providers.add(`${sandboxName}-tavily-search`); + return providers; +} + +let webSearchContracts: Record> | null = + null; + +function webSearchPresetContracts(): Record< + string, + ReturnType +> { + if (webSearchContracts) return webSearchContracts; + webSearchContracts = {}; + for (const presetName of ["brave", "tavily"]) { + const content = loadCentralPreset(presetName, { reportMissing: false }); + webSearchContracts[presetName] = content + ? parseWebSearchEndpointContract(content, presetName) + : null; + } + return webSearchContracts; +} + +/** + * Providers the gateway reports as attached to one sandbox. A failed or + * unreadable observation returns null, so the caller adds no credential + * binding rather than submitting one the gateway would reject. + */ +async function observedSandboxAttachments(sandboxName: string): Promise { + try { + return await readSandboxProviderAttachments(sandboxName, registry.getSandbox(sandboxName)); + } catch { + return null; } } @@ -434,8 +482,19 @@ function bindWebSearchPreset( presetName: string, sandboxName: string, agentName: string | null, + attachedProviders: readonly string[] | null, + recordedProviders: readonly string[] | undefined, ): string { - if (!isWebSearchPolicyPreset(presetName)) return content; + // Hermes Tavily and every Brave provider use an endpoint-bearing profile. + // The pinned OpenShell release rejects a policy binding that names that + // provider, and the profile attachment delivers the credential itself. + if ( + presetName === "brave" || + (presetName === "tavily" && agentName?.trim().toLowerCase() === "hermes") + ) { + return content; + } + if (!isWebSearchPolicyPreset(presetName) || attachedProviders === null) return content; return applyWebSearchCredentialBinding( content, presetName, @@ -443,8 +502,10 @@ function bindWebSearchPreset( presetName, sandboxName, agentName, - availableProviders: recordedWebSearchProviders(), + availableProviders: new Set(recordedProviders ?? recordedWebSearchProviders(sandboxName)), + attachedProviders: new Set(attachedProviders), }), + webSearchPresetContracts()[presetName] ?? null, ); } @@ -460,9 +521,9 @@ async function loadPresetForSandbox( let sandboxAgent: string | null = null; let configuredMessagingChannels: string[] = []; let messagingConfig = options.messagingConfig; + let sandbox: registry.SandboxEntry | null = null; try { - const sandbox = - options.sandbox === undefined ? registry.getSandbox(sandboxName) : options.sandbox; + sandbox = options.sandbox === undefined ? registry.getSandbox(sandboxName) : options.sandbox; sandboxAgent = sandbox?.agent ?? null; configuredMessagingChannels = getCredentialBoundMessagingChannelsFromEntry(sandbox); if (messagingConfig === undefined) { @@ -501,11 +562,19 @@ async function loadPresetForSandbox( const resolvedPresetContent = loadAgentPresetContent(sandboxName, presetName, builtinPresetContent, options.sandbox) || builtinPresetContent; + const attachedProviders = + options.attachedProviders !== undefined + ? options.attachedProviders + : isWebSearchPolicyPreset(presetName) + ? await readSandboxProviderAttachments(sandboxName, sandbox) + : null; const boundPresetContent = bindWebSearchPreset( resolvedPresetContent, presetName, sandboxName, sandboxAgent, + attachedProviders, + options.recordedProviders, ); return presetName === "outlook" && sandboxAgent !== "hermes" && @@ -1746,13 +1815,25 @@ function mergePresetNamesIntoPolicy( const appliedPresets: string[] = []; const missingPresets: string[] = []; + const planned = options.plannedProviders; for (const presetName of [...new Set(presetNames)]) { - const presetContent = loadPresetForAgent(presetName, { + const loaded = loadPresetForAgent(presetName, { agent: options.agent, sandboxName: options.sandboxName, credentialBoundMessagingChannels: options.credentialBoundMessagingChannels, messagingConfig: options.messagingConfig, }); + const presetContent = + loaded && isWebSearchPolicyPreset(presetName) + ? bindWebSearchPreset( + loaded, + presetName, + options.sandboxName ?? "", + options.agent ?? null, + planned ?? null, + planned, + ) + : loaded; const presetEntries = extractPresetEntries(presetContent); if (!presetEntries) { const materializesWithSandboxName = @@ -2589,6 +2670,9 @@ async function applyPreset( const presetContent = await loadPresetForSandbox(sandboxName, presetName, { includeMessagingCredentialBindings: options.includeMessagingCredentialBindings === true, messagingConfig: options.messagingConfig as MessagingPolicyConfig | null | undefined, + ...(isWebSearchPolicyPreset(presetName) + ? { attachedProviders: await observedSandboxAttachments(sandboxName) } + : {}), }); if (!presetContent) { console.error(` Cannot load preset: ${presetName}`); @@ -2620,8 +2704,13 @@ async function applyPresets(sandboxName: string, presetNames: string[]): Promise name: string; }> = []; + const attachedProviders = uniquePresetNames.some(isWebSearchPolicyPreset) + ? await observedSandboxAttachments(sandboxName) + : null; for (const presetName of uniquePresetNames) { - const presetContent = await loadPresetForSandbox(sandboxName, presetName); + const presetContent = await loadPresetForSandbox(sandboxName, presetName, { + ...(isWebSearchPolicyPreset(presetName) ? { attachedProviders } : {}), + }); if (!presetContent) { console.error(` Cannot load preset: ${presetName}`); return false; diff --git a/src/lib/policy/preset-parsing.test.ts b/src/lib/policy/preset-parsing.test.ts index 9d10451f4a9..f5983a54484 100644 --- a/src/lib/policy/preset-parsing.test.ts +++ b/src/lib/policy/preset-parsing.test.ts @@ -20,6 +20,7 @@ import { applyWebSearchCredentialBinding, bindWebSearchPresetProviders, isWebSearchPolicyPreset, + parseWebSearchEndpointContract, resolveWebSearchCredentialProvider, webSearchCredentialProviderCandidates, } from "./preset-parsing"; @@ -31,6 +32,8 @@ function tavilyEndpoints(content: string): Array> { return YAML.parse(content).network_policies.tavily.endpoints; } +const tavilyContract = parseWebSearchEndpointContract(tavilyPreset, "tavily"); + describe("web-search credential provider resolution", () => { it("recognizes the web-search presets", () => { expect(isWebSearchPolicyPreset("tavily")).toBe(true); @@ -84,15 +87,38 @@ describe("web-search credential provider resolution", () => { }); describe("web-search credential binding", () => { - it("binds every unbound endpoint of the preset policy", () => { - const bound = applyWebSearchCredentialBinding(tavilyPreset, "tavily", "tavily-search"); + it("does not bind an endpoint that differs from the preset contract", () => { + const substituted = tavilyPreset.replace("host: api.tavily.com", "host: operator.example"); + const bound = applyWebSearchCredentialBinding( + substituted, + "tavily", + "tavily-search", + tavilyContract, + ); + expect( + YAML.parse(bound).network_policies.tavily.endpoints[0].credential_binding, + ).toBeUndefined(); + expect(applyWebSearchCredentialBinding(tavilyPreset, "tavily", "tavily-search", null)).toBe( + tavilyPreset, + ); + }); + + it("binds every unbound contract endpoint of the preset policy", () => { + const bound = applyWebSearchCredentialBinding( + tavilyPreset, + "tavily", + "tavily-search", + tavilyContract, + ); expect(tavilyEndpoints(bound)).toEqual([ expect.objectContaining({ credential_binding: { provider: "tavily-search" } }), ]); }); it("leaves the preset unchanged when no provider is resolved", () => { - expect(applyWebSearchCredentialBinding(tavilyPreset, "tavily", null)).toBe(tavilyPreset); + expect(applyWebSearchCredentialBinding(tavilyPreset, "tavily", null, tavilyContract)).toBe( + tavilyPreset, + ); }); it("preserves an existing credential binding", () => { @@ -100,16 +126,19 @@ describe("web-search credential binding", () => { " request_body_credential_rewrite: true\n", " request_body_credential_rewrite: true\n credential_binding:\n provider: operator-provider\n", ); - expect(applyWebSearchCredentialBinding(existing, "tavily", "tavily-search")).toBe(existing); + expect( + applyWebSearchCredentialBinding(existing, "tavily", "tavily-search", tavilyContract), + ).toBe(existing); }); it("binds each web-search policy present in a sandbox policy document", () => { - const document = `version: 1\nnetwork_policies:\n tavily:\n endpoints:\n - host: api.tavily.com\n port: 443\n brave:\n endpoints:\n - host: api.search.brave.com\n port: 443\n weather:\n endpoints:\n - host: wttr.in\n port: 443\n`; + const document = `version: 1\nnetwork_policies:\n tavily:\n endpoints:\n - host: api.tavily.com\n port: 443\n protocol: rest\n enforcement: enforce\n request_body_credential_rewrite: true\n rules:\n - allow: { method: POST, path: "/search" }\n brave:\n endpoints:\n - host: api.search.brave.com\n port: 443\n weather:\n endpoints:\n - host: wttr.in\n port: 443\n`; const bound = bindWebSearchPresetProviders({ content: document, sandboxName, agentName: "langchain-deepagents-code", availableProviders: new Set(["tavily-search"]), + contracts: { tavily: tavilyContract }, }); const parsed = YAML.parse(bound).network_policies; expect(parsed.tavily.endpoints[0].credential_binding).toEqual({ provider: "tavily-search" }); @@ -132,7 +161,9 @@ describe("loadPresetForSandbox web-search binding", () => { }); mocks.listExtraProviders.mockReturnValue(["tavily-search"]); - const content = await loadPresetForSandbox(sandboxName, "tavily"); + const content = await loadPresetForSandbox(sandboxName, "tavily", { + attachedProviders: ["tavily-search"], + }); expect(content).not.toBeNull(); expect(tavilyEndpoints(content!)).toEqual([ @@ -148,13 +179,30 @@ describe("loadPresetForSandbox web-search binding", () => { }); mocks.listExtraProviders.mockReturnValue([`${sandboxName}-tavily-search`]); - const content = await loadPresetForSandbox(sandboxName, "tavily"); + const content = await loadPresetForSandbox(sandboxName, "tavily", { + attachedProviders: [`${sandboxName}-tavily-search`], + }); expect(tavilyEndpoints(content!)).toEqual([ expect.objectContaining({ credential_binding: { provider: `${sandboxName}-tavily-search` } }), ]); }); + it("omits the binding when the recorded provider is not attached", async () => { + mocks.getSandbox.mockReturnValue({ + name: sandboxName, + agent: "langchain-deepagents-code", + gatewayName: "nemoclaw", + }); + mocks.listExtraProviders.mockReturnValue(["tavily-search"]); + + const content = await loadPresetForSandbox(sandboxName, "tavily", { attachedProviders: [] }); + + expect(tavilyEndpoints(content!)).toEqual([ + expect.not.objectContaining({ credential_binding: expect.anything() }), + ]); + }); + it("omits the binding when no web-search provider is recorded", async () => { mocks.getSandbox.mockReturnValue({ name: sandboxName, @@ -163,7 +211,9 @@ describe("loadPresetForSandbox web-search binding", () => { }); mocks.listExtraProviders.mockReturnValue([]); - const content = await loadPresetForSandbox(sandboxName, "tavily"); + const content = await loadPresetForSandbox(sandboxName, "tavily", { + attachedProviders: ["tavily-search"], + }); expect(tavilyEndpoints(content!)).toEqual([ expect.not.objectContaining({ credential_binding: expect.anything() }), @@ -174,7 +224,9 @@ describe("loadPresetForSandbox web-search binding", () => { mocks.getSandbox.mockReturnValue({ name: sandboxName, agent: "openclaw" }); mocks.listExtraProviders.mockReturnValue(["tavily-search"]); - const content = await loadPresetForSandbox(sandboxName, "weather"); + const content = await loadPresetForSandbox(sandboxName, "weather", { + attachedProviders: ["tavily-search"], + }); expect(content).not.toBeNull(); const endpoints = YAML.parse(content!).network_policies.weather.endpoints; diff --git a/src/lib/policy/preset-parsing.ts b/src/lib/policy/preset-parsing.ts index ab7c8b1f154..959a777f2e0 100644 --- a/src/lib/policy/preset-parsing.ts +++ b/src/lib/policy/preset-parsing.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { isDeepStrictEqual } from "node:util"; import { isIP } from "node:net"; import YAML from "yaml"; @@ -175,29 +176,121 @@ export function resolveWebSearchCredentialProvider(input: { readonly sandboxName: string; readonly agentName?: string | null; readonly availableProviders: ReadonlySet; + /** + * Providers attached to the target sandbox. Omitted for the rebuild handoff, + * which binds before physical attachment. When present, a candidate the + * sandbox does not attach does not qualify: the gateway rejects a + * credential_binding that names an unattached provider. + */ + readonly attachedProviders?: ReadonlySet; }): string | null { for (const candidate of webSearchCredentialProviderCandidates( input.presetName, input.sandboxName, input.agentName, )) { - if (input.availableProviders.has(candidate)) return candidate; + if (!input.availableProviders.has(candidate)) continue; + if (input.attachedProviders && !input.attachedProviders.has(candidate)) continue; + return candidate; } return null; } +/** + * Network contract an endpoint must match before it can receive a web-search + * credential binding. A binding hands the stored credential to every request + * the endpoint allows, so the binding is granted only to the destination the + * checked-in preset declares. + */ +export type WebSearchEndpointContract = Readonly<{ + host: string; + port: number; + protocol: string; + enforcement: string; + rules: readonly Readonly>[]; + requestBodyCredentialRewrite: boolean; +}>; + +const WEB_SEARCH_CONTRACT_KEYS = ["host", "port", "protocol", "enforcement", "rules"] as const; + +function contractString(value: JsonValue): string | null { + return typeof value === "string" ? value : null; +} + +function contractNumber(value: JsonValue): number | null { + return typeof value === "number" ? value : null; +} + +function contractRules(value: JsonValue): WebSearchEndpointContract["rules"] | null { + if (!Array.isArray(value) || value.length === 0 || !value.every(isPolicyObject)) return null; + return value; +} + +/** + * Derive the endpoint contract from the checked-in preset content. The preset + * is the only authority for the destination that may receive the credential, so + * a preset that does not declare exactly one complete endpoint has no contract + * and receives no binding. + */ +export function parseWebSearchEndpointContract( + presetContent: string, + presetName: string, +): WebSearchEndpointContract | null { + let parsed: PolicyValue; + try { + parsed = YAML.parse(presetContent); + } catch { + return null; + } + if (!isPolicyDocument(parsed) || !isPolicyObject(parsed.network_policies)) return null; + const policy = parsed.network_policies[presetName]; + if (!isPolicyObject(policy) || !Array.isArray(policy.endpoints)) return null; + if (policy.endpoints.length !== 1 || !isPolicyObject(policy.endpoints[0])) return null; + const endpoint = policy.endpoints[0]; + if (Object.hasOwn(endpoint, "credential_binding")) return null; + const host = contractString(endpoint.host); + const port = contractNumber(endpoint.port); + const protocol = contractString(endpoint.protocol); + const enforcement = contractString(endpoint.enforcement); + const rules = contractRules(endpoint.rules); + if (!host || port === null || !protocol || !enforcement || !rules) return null; + return { + host, + port, + protocol, + enforcement, + rules, + requestBodyCredentialRewrite: endpoint.request_body_credential_rewrite === true, + }; +} + +function matchesWebSearchEndpointContract( + endpoint: PolicyObject, + contract: WebSearchEndpointContract, +): boolean { + return ( + WEB_SEARCH_CONTRACT_KEYS.every((key) => + isDeepStrictEqual(endpoint[key], contract[key as keyof WebSearchEndpointContract]), + ) && + (endpoint.request_body_credential_rewrite === true) === contract.requestBodyCredentialRewrite + ); +} + /** * Bind a web-search preset endpoint to the provider that holds its credential. * OpenShell resolves a static credential only at an endpoint that names its * provider, so an unbound endpoint denies the request after the network and L7 - * stages allow it. + * stages allow it. The binding is added only to an endpoint that matches the + * checked-in preset contract; a substituted or added endpoint keeps none of + * the credential. */ export function applyWebSearchCredentialBinding( content: string, presetName: string, providerName: string | null, + contract: WebSearchEndpointContract | null, ): string { - if (!providerName) return content; + if (!providerName || !contract) return content; let parsed: PolicyValue; try { parsed = YAML.parse(content); @@ -209,7 +302,15 @@ export function applyWebSearchCredentialBinding( if (!isPolicyObject(policy) || !Array.isArray(policy.endpoints)) return content; let changed = false; for (const endpoint of policy.endpoints) { - if (!isPolicyObject(endpoint) || Object.hasOwn(endpoint, "credential_binding")) continue; + // An existing binding is never replaced, and an endpoint that differs from + // the checked-in contract receives none of the stored credential. + if ( + !isPolicyObject(endpoint) || + Object.hasOwn(endpoint, "credential_binding") || + !matchesWebSearchEndpointContract(endpoint, contract) + ) { + continue; + } endpoint.credential_binding = { provider: providerName }; changed = true; } @@ -226,16 +327,31 @@ export function bindWebSearchPresetProviders(input: { readonly sandboxName: string; readonly agentName?: string | null; readonly availableProviders: ReadonlySet; + readonly contracts?: Readonly>; }): string { let content = input.content; for (const presetName of Object.keys(WEB_SEARCH_PRESET_PROVIDER_SUFFIXES)) { + // Hermes Tavily and every Brave provider use an endpoint-bearing profile. + // A policy binding that names that provider is rejected, and the profile + // attachment delivers the credential itself. + if ( + presetName === "brave" || + (presetName === "tavily" && input.agentName?.trim().toLowerCase() === "hermes") + ) { + continue; + } const providerName = resolveWebSearchCredentialProvider({ presetName, sandboxName: input.sandboxName, agentName: input.agentName, availableProviders: input.availableProviders, }); - content = applyWebSearchCredentialBinding(content, presetName, providerName); + content = applyWebSearchCredentialBinding( + content, + presetName, + providerName, + input.contracts?.[presetName] ?? null, + ); } return content; } diff --git a/test/fixtures/openshell-provider-profile.ts b/test/fixtures/openshell-provider-profile.ts index bdb4b7ccb0e..3134e09b733 100644 --- a/test/fixtures/openshell-provider-profile.ts +++ b/test/fixtures/openshell-provider-profile.ts @@ -52,6 +52,24 @@ export function managedBraveProfile() { }; } +export function endpointlessTavilyProfile() { + const base = managedBraveProfile(); + return { + ...base, + id: "tavily-policy-binding-v1", + credentials: [ + { + ...base.credentials[0], + envVars: ["TAVILY_API_KEY"], + authStyle: "bearer", + headerName: "authorization", + }, + ], + endpoints: [], + binaries: [], + }; +} + export function managedTavilyProfile(agent: "openclaw" | "hermes" = "openclaw") { const base = managedBraveProfile(); return { From bddee37628016a5e25bb0cb4d3153e038f405bff Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Thu, 29 Oct 2026 04:14:23 +0000 Subject: [PATCH 3/4] fix(policy): verify endpointless Tavily profile before preset binding Signed-off-by: Tinson Lai --- .../quickstart-langchain-deepagents-code.mdx | 2 +- docs/reference/commands.mdx | 5 +- docs/reference/troubleshooting.mdx | 8 +- docs/security/credential-storage.mdx | 10 +- .../tavily-policy-binding-v1.yaml | 0 src/commands/credentials.test.ts | 10 +- src/lib/actions/credentials-add.ts | 11 +-- .../credentials-provider-adapter.test.ts | 2 +- .../adapters/openshell/provider-profile.ts | 6 +- src/lib/adapters/openshell/providers.test.ts | 7 +- src/lib/adapters/openshell/sandboxes.ts | 18 +++- .../applier/web-search-provider-profile.ts | 11 ++- .../hermes-portable-build-context-files.ts | 4 - src/lib/onboard/gateway-binding.ts | 26 +++++ .../sandbox-provider-effect-replay.test.ts | 10 +- .../onboard/sandbox-create/orchestration.ts | 13 +++ .../sandbox-create/provider-publication.ts | 43 +++++++++ .../rebuild-policy-handoff.test.ts | 11 +++ .../sandbox-create/rebuild-policy-handoff.ts | 52 +++++----- src/lib/policy/index.ts | 94 +++++++++++++++---- src/lib/policy/preset-parsing.test.ts | 29 +++++- src/lib/policy/preset-parsing.ts | 48 ++++++++-- .../cli/credentials-cli-command.test.ts | 54 ++++++----- 23 files changed, 365 insertions(+), 109 deletions(-) rename {nemoclaw-blueprint => managed-inference}/provider-profiles/tavily-policy-binding-v1.yaml (100%) diff --git a/docs/get-started/quickstart-langchain-deepagents-code.mdx b/docs/get-started/quickstart-langchain-deepagents-code.mdx index 9e11edf06dc..9cba07a0c92 100644 --- a/docs/get-started/quickstart-langchain-deepagents-code.mdx +++ b/docs/get-started/quickstart-langchain-deepagents-code.mdx @@ -237,7 +237,7 @@ nemo-deepagents rebuild The shared `tavily` preset only opens `POST /search` and `POST /extract` egress to `api.tavily.com:443`. Attaching the credential provider alone does not authorize the managed Python interpreter; the explicit policy preset is the interpreter-level opt-in. Export `TAVILY_API_KEY` only for registration, then remove it from the host shell; the gateway injects the stored value at egress, and the sandbox never sees the raw value. NemoClaw does not bake `TAVILY_API_KEY` into the managed config or image, and the managed wrapper rejects direct service-key injection into `dcode`. Because OpenShell attributes the harness's calls to the sandbox `python3` interpreter, this egress is process-wide for sandbox Python rather than a `dcode`-only boundary. -The `tavily` preset binds its endpoint to the attached `tavily-search` provider, so OpenShell can replace the `openshell:resolve:env:TAVILY_API_KEY` placeholder at egress. If the provider is already attached, `policy add` adds the binding. Otherwise, the next rebuild adds it. If `tavily-search` uses the earlier `tavily` profile, reset it, register it again with `--agent dcode`, and rebuild the sandbox. +The `tavily` preset binds its endpoint to the attached `tavily-search` provider when that provider uses the `tavily-policy-binding-v1` profile. OpenShell then replaces the `openshell:resolve:env:TAVILY_API_KEY` placeholder at egress. If the provider is already attached, `policy add` adds the binding. Otherwise, the next rebuild adds it. Resetting the gateway-wide `tavily-search` provider detaches every sandbox that uses it, so you must rebuild each detached sandbox after you register the replacement. If `tavily-search` uses the earlier `tavily` profile, reset it, register it again with `--agent dcode`, and rebuild each detached sandbox. Remove the target sandbox's managed-Python opt-in when it is no longer needed. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index b3a3a02f119..8323ca61682 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3999,8 +3999,9 @@ Registered providers are gateway-wide and attach to every sandbox you build or r Tavily requires a provider profile that permits the intended agent runtime. Use `--type tavily --agent hermes` to select the versioned `tavily-hermes-v1` profile for Hermes Python. The explicit `--type tavily-hermes-v1` form remains supported without `--agent`. -OpenClaw and Deep Agents use the existing `tavily` profile with `--agent openclaw` or `--agent dcode`. -Without `--agent`, `--type tavily` retains that profile and prints a warning that it does not authorise Hermes Python. +OpenClaw and Deep Agents use the endpointless `tavily-policy-binding-v1` profile with `--agent openclaw` or `--agent dcode`. +Without `--agent`, `--type tavily` also selects `tavily-policy-binding-v1` and prints a warning that it does not authorise Hermes Python. +A provider that you registered with the earlier `tavily` profile keeps that profile until you reset it and register it again. `--agent` accepts `hermes`, `openclaw`, `langchain-deepagents-code`, and their aliases only for Tavily profiles. An explicit Hermes profile combined with a non-Hermes agent is rejected before gateway operations. diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index ef2463d61cb..f14b11452cd 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -823,6 +823,7 @@ $$nemoclaw config get --key tools.web.search --format yaml The provider should be `brave` or `tavily` and `enabled` should be `true`. If the provider is wrong, rerun onboarding with `NEMOCLAW_WEB_SEARCH_PROVIDER=brave` or `tavily` and the matching `BRAVE_API_KEY` or `TAVILY_API_KEY`. If a rebuild reports that `TAVILY_API_KEY` is not available for a sandbox that was onboarded with the earlier `tavily` profile, export `TAVILY_API_KEY` and rerun the rebuild so NemoClaw registers `-tavily-search` with the current profile. +If `logs` shows a `credential_unavailable` denial for `api.tavily.com`, confirm that `-tavily-search` is attached and uses the `tavily-policy-binding-v1` profile, then rerun `$$nemoclaw rebuild`. @@ -1860,8 +1861,11 @@ nemo-deepagents logs --tail 50 ``` A `credential_unavailable` denial means the `tavily` endpoint has no usable credential binding. -NemoClaw adds the binding only for an attached `tavily-search` provider that uses the `tavily-policy-binding-v1` profile. Register it with `--agent dcode`, not `--agent hermes`. -Confirm that `nemo-deepagents credentials list` shows `tavily-search`. If `tavily-search` uses the earlier `tavily` profile, replace it and rebuild the sandbox: +NemoClaw adds the binding only when `tavily-search` is attached to the sandbox, uses the `tavily-policy-binding-v1` profile, and the `tavily` endpoint matches the checked-in preset. +Register the provider with `--agent dcode`, not `--agent hermes`. +Confirm that `nemo-deepagents credentials list` shows `tavily-search` and check its profile with `openshell provider get tavily-search`. +Resetting the gateway-wide `tavily-search` provider detaches every sandbox that uses it, so you must rebuild each detached sandbox after you register the replacement. +If `tavily-search` uses the earlier `tavily` profile, replace it and rebuild each detached sandbox: ```bash nemo-deepagents credentials reset tavily-search --yes diff --git a/docs/security/credential-storage.mdx b/docs/security/credential-storage.mdx index 8b6dec04367..ca0b02b6d14 100644 --- a/docs/security/credential-storage.mdx +++ b/docs/security/credential-storage.mdx @@ -97,7 +97,10 @@ The documented Deep Agents flow uses the gateway-wide name `tavily-search` witho Agent configuration uses `openshell:resolve:env:` references instead of raw keys. -NemoClaw binds the `tavily` preset only to an attached provider named `tavily-search` or `-tavily-search`. OpenShell denies requests that use a Tavily credential under any other name with `credential_unavailable`. +NemoClaw binds the `tavily` preset only to an attached provider named `tavily-search` or `-tavily-search` that uses the `tavily-policy-binding-v1` profile. +An endpointless Tavily provider without a matching binding cannot supply the credential for the placeholder, and OpenShell denies the request with `credential_unavailable`. +A provider that uses the earlier `tavily` profile declares the Tavily endpoint, so it can open egress to `api.tavily.com` without the `tavily` preset. +Reset that provider and register it again to use `tavily-policy-binding-v1`. OpenShell supplies `TAVILY_API_KEY` through the Hermes process environment as a revision-scoped reference such as `openshell:resolve:env:v_TAVILY_API_KEY`. @@ -120,9 +123,10 @@ The `tavily` policy preset enables request-body credential rewriting so OpenShel For Deep Agents, the managed launch paths reject direct `TAVILY_API_KEY` injection into `dcode`. Register the key with OpenShell through `$$nemoclaw credentials add tavily-search --type tavily --agent dcode --credential TAVILY_API_KEY`, then apply the `tavily` policy preset and rebuild the sandbox so the provider attaches. -If `tavily-search` uses the earlier `tavily` profile, run `$$nemoclaw credentials reset tavily-search --yes`, register it again with `--agent dcode`, and rebuild the sandbox. +Resetting the gateway-wide `tavily-search` provider detaches every sandbox that uses it, so you must rebuild each detached sandbox after you register the replacement. +If `tavily-search` uses the earlier `tavily` profile, run `$$nemoclaw credentials reset tavily-search --yes`, register it again with `--agent dcode`, and rebuild each detached sandbox. The `tavily` preset is the sandbox-level network opt-in, while the `tavily-search` provider is gateway-wide and can attach to future sandboxes that you build or rebuild. -When `tavily-search` is attached to the sandbox, `policy add` and `rebuild` bind the `tavily` preset endpoint to that provider, so OpenShell replaces the placeholder at egress. +When `tavily-search` is attached to the sandbox and uses the `tavily-policy-binding-v1` profile, `policy add` and `rebuild` bind the `tavily` preset endpoint to that provider, so OpenShell replaces the placeholder at egress. If `tavily-search` is not attached, the preset opens egress without a binding and OpenShell denies the request with `credential_unavailable`. diff --git a/nemoclaw-blueprint/provider-profiles/tavily-policy-binding-v1.yaml b/managed-inference/provider-profiles/tavily-policy-binding-v1.yaml similarity index 100% rename from nemoclaw-blueprint/provider-profiles/tavily-policy-binding-v1.yaml rename to managed-inference/provider-profiles/tavily-policy-binding-v1.yaml diff --git a/src/commands/credentials.test.ts b/src/commands/credentials.test.ts index c34dc0e3010..6a4a07fa615 100644 --- a/src/commands/credentials.test.ts +++ b/src/commands/credentials.test.ts @@ -88,7 +88,13 @@ describe("credentials oclif adapter source coverage", () => { const exportedProfile = JSON.stringify( parseYaml( fs.readFileSync( - path.join(rootDir, "nemoclaw-blueprint/provider-profiles", `${profile}.yaml`), + path.join( + rootDir, + profile === "tavily-policy-binding-v1" + ? "managed-inference/provider-profiles" + : "nemoclaw-blueprint/provider-profiles", + `${profile}.yaml`, + ), "utf8", ), ), @@ -150,7 +156,7 @@ describe("credentials oclif adapter source coverage", () => { const exportedProfile = JSON.stringify( parseYaml( fs.readFileSync( - path.join(rootDir, "nemoclaw-blueprint/provider-profiles/tavily-policy-binding-v1.yaml"), + path.join(rootDir, "managed-inference/provider-profiles/tavily-policy-binding-v1.yaml"), "utf8", ), ), diff --git a/src/lib/actions/credentials-add.ts b/src/lib/actions/credentials-add.ts index 351cfb867cd..af7b346277c 100644 --- a/src/lib/actions/credentials-add.ts +++ b/src/lib/actions/credentials-add.ts @@ -33,6 +33,7 @@ import { } from "../inference/native-nvidia"; import { HERMES_TAVILY_PROVIDER_PROFILE_ID, + TAVILY_POLICY_BINDING_PROVIDER_PROFILE_ID, TAVILY_PROVIDER_PROFILE_AGENTS, TAVILY_PROVIDER_PROFILE_ID, webSearchProviderProfileId, @@ -157,12 +158,10 @@ function bundledProviderProfile(type: string): { profileType: string; profilePat if (profileType === NVIDIA_HOSTED_NATIVE_PROFILE_ID) { return { profileType, profilePath: nativeNvidiaProviderProfilePath() }; } - const profilePath = path.join( - ROOT, - "nemoclaw-blueprint", - "provider-profiles", - `${profileType}.yaml`, - ); + const profilePath = + profileType === TAVILY_POLICY_BINDING_PROVIDER_PROFILE_ID + ? path.join(ROOT, "managed-inference", "provider-profiles", `${profileType}.yaml`) + : path.join(ROOT, "nemoclaw-blueprint", "provider-profiles", `${profileType}.yaml`); return fs.existsSync(profilePath) ? { profileType, profilePath } : null; } diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index 94c6310d37c..e4d36537c2b 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -731,7 +731,7 @@ describe("credential actions use typed OpenShell provider results", () => { expect(result.exitCode).toBe(1); expect(result.failureLines).toContain( - " OpenShell provider profile 'tavily' does not match NemoClaw's checked-in credential boundary.", + " OpenShell provider profile 'tavily-policy-binding-v1' does not match NemoClaw's checked-in credential boundary.", ); expect(adapter.createProvider).not.toHaveBeenCalled(); }); diff --git a/src/lib/adapters/openshell/provider-profile.ts b/src/lib/adapters/openshell/provider-profile.ts index a0f3855b7ad..d1211cbc5c8 100644 --- a/src/lib/adapters/openshell/provider-profile.ts +++ b/src/lib/adapters/openshell/provider-profile.ts @@ -130,5 +130,9 @@ export function isMissingProviderProfile(output: string, profileId: string): boo } export function endpointlessProviderProfilePath(root: string, profileId: string): string { - return path.join(root, "nemoclaw-blueprint", "provider-profiles", `${profileId}.yaml`); + const directory = + profileId === "tavily-policy-binding-v1" + ? path.join(root, "managed-inference", "provider-profiles") + : path.join(root, "nemoclaw-blueprint", "provider-profiles"); + return path.join(directory, `${profileId}.yaml`); } diff --git a/src/lib/adapters/openshell/providers.test.ts b/src/lib/adapters/openshell/providers.test.ts index 6585db1ec88..dda1aabc4f7 100644 --- a/src/lib/adapters/openshell/providers.test.ts +++ b/src/lib/adapters/openshell/providers.test.ts @@ -162,7 +162,7 @@ describe("OpenShell provider evidence", () => { agent === "hermes" ? ("tavily-hermes-v1" as const) : ("tavily-policy-binding-v1" as const); const credential = profile.credentials[0]!; const endpoint = profile.endpoints[0]!; - it.each([ + const cases: readonly (readonly [string, Record])[] = [ ["another agent's profile", { id: agent === "hermes" ? "tavily" : "tavily-hermes-v1" }], ["an unknown profile source", { source: "foreign" }], ["a different scope", { scope: "platform" }], @@ -220,9 +220,10 @@ describe("OpenShell provider evidence", () => { { endpoints: [{ ...endpoint, credentialBinding: { provider: "other" } }] }, ], ] as const) - : []), + : ([["an endpoint", { endpoints: [{ host: "api.tavily.com" }] }]] as const)), ["a different executable", { binaries: [{ path: "/usr/bin/python" }] }], - ] as const)("rejects %s (#12138)", async (_label, change) => { + ]; + it.each(cases)("rejects %s (#12138)", async (_label, change) => { const { raw, connect } = fixture(); raw.getProvider.mockResolvedValue({ provider: { ...provider().provider, type: profileContract, profileWorkspace: "default" }, diff --git a/src/lib/adapters/openshell/sandboxes.ts b/src/lib/adapters/openshell/sandboxes.ts index a5f0ad24a4d..57b5fc0667d 100644 --- a/src/lib/adapters/openshell/sandboxes.ts +++ b/src/lib/adapters/openshell/sandboxes.ts @@ -13,7 +13,7 @@ import { type ReadRequest, } from "./sdk-read"; -import { SandboxResponseSchema } from "./sdk-read-schema"; +import { ProviderResponseSchema, SandboxResponseSchema } from "./sdk-read-schema"; export type Sandbox = Readonly<{ id: string; @@ -52,5 +52,21 @@ export function createSandboxes(connect: ConnectOpenShellReader = connectOpenShe providers: [...spec.providers].sort(), }); }), + getProviderType: (request: ReadRequest & Readonly<{ name: string }>): Promise => + readOpenShell(request, async () => { + const name = text(request.name); + const client = await connect(request.target); + request.signal.throwIfAborted(); + try { + const response = await client.raw.getProvider( + { name, workspace: request.workspace }, + { signal: request.signal }, + ); + return readValue(ProviderResponseSchema, response).provider.type; + } catch (error) { + if (isNotFound(error)) return null; + throw error; + } + }), }; } diff --git a/src/lib/messaging/applier/web-search-provider-profile.ts b/src/lib/messaging/applier/web-search-provider-profile.ts index fdef930819b..e8f74b58a5e 100644 --- a/src/lib/messaging/applier/web-search-provider-profile.ts +++ b/src/lib/messaging/applier/web-search-provider-profile.ts @@ -2,11 +2,18 @@ // SPDX-License-Identifier: Apache-2.0 import path from "node:path"; -import type { WebSearchProviderProfileId } from "../../inference/web-search/provider-profile"; +import { + TAVILY_POLICY_BINDING_PROVIDER_PROFILE_ID, + type WebSearchProviderProfileId, +} from "../../inference/web-search/provider-profile"; export function webSearchProviderProfilePath( root: string, provider: WebSearchProviderProfileId, ): string { - return path.join(root, "nemoclaw-blueprint", "provider-profiles", `${provider}.yaml`); + const directory = + provider === TAVILY_POLICY_BINDING_PROVIDER_PROFILE_ID + ? path.join(root, "managed-inference", "provider-profiles") + : path.join(root, "nemoclaw-blueprint", "provider-profiles"); + return path.join(directory, `${provider}.yaml`); } diff --git a/src/lib/onboard/experimental/hermes-portable-build-context-files.ts b/src/lib/onboard/experimental/hermes-portable-build-context-files.ts index 2afff79f731..1338ddcbb55 100644 --- a/src/lib/onboard/experimental/hermes-portable-build-context-files.ts +++ b/src/lib/onboard/experimental/hermes-portable-build-context-files.ts @@ -122,10 +122,6 @@ export const HERMES_PORTABLE_BUILD_CONTEXT_FILES = [ { path: "nemoclaw-blueprint/provider-profiles/nemoclaw-mcp-v1.yaml", mode: "100644" }, { path: "nemoclaw-blueprint/provider-profiles/okta-runtime-v1.yaml", mode: "100644" }, { path: "nemoclaw-blueprint/provider-profiles/tavily-hermes-v1.yaml", mode: "100644" }, - { - path: "nemoclaw-blueprint/provider-profiles/tavily-policy-binding-v1.yaml", - mode: "100644", - }, { path: "nemoclaw-blueprint/provider-profiles/tavily.yaml", mode: "100644" }, { path: "nemoclaw-blueprint/router/llm-router", mode: "160000" }, { path: "nemoclaw-blueprint/router/pool-config.yaml", mode: "100644" }, diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index f8624801191..9534fe0eef6 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -86,6 +86,32 @@ export async function readSandboxProviderAttachments( } } +/** + * Profile type the gateway reports for one provider, or null when the provider + * cannot be inspected. Used at the live policy-binding boundary so an + * endpoint-bearing Tavily profile is never added to credential_binding. + */ +export async function readSandboxProviderProfileType( + providerName: string, + sandbox: SandboxGatewayBinding | null, + gatewayName?: string, +): Promise { + const resolvedGatewayName = gatewayName ?? (sandbox ? resolveSandboxGatewayName(sandbox) : null); + if (!resolvedGatewayName) return null; + try { + const { createSandboxes } = + require("../adapters/openshell/sandboxes") as typeof import("../adapters/openshell/sandboxes"); + return await createSandboxes().getProviderType({ + target: { kind: "named", gatewayName: resolvedGatewayName }, + workspace: "default", + name: providerName, + signal: AbortSignal.timeout(5_000), + }); + } catch { + return null; + } +} + /** Resolve one attempt-wide onboarding target without overriding an authoritative rebuild. */ export function resolveCoreOnboardGatewayBinding(options: { authoritativeGateway?: { name: string; port: number } | null; diff --git a/src/lib/onboard/machine/handlers/sandbox-provider-effect-replay.test.ts b/src/lib/onboard/machine/handlers/sandbox-provider-effect-replay.test.ts index e19a3fcee95..fbec45ce0b2 100644 --- a/src/lib/onboard/machine/handlers/sandbox-provider-effect-replay.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-provider-effect-replay.test.ts @@ -235,7 +235,7 @@ describe("handleSandboxState provider effect replay", () => { }; const tavilyBinding = { name: "my-assistant-tavily-search", - type: "tavily", + type: "tavily-policy-binding-v1", credentialEnv: "TAVILY_API_KEY", }; const session = createSession({ @@ -386,7 +386,7 @@ describe("handleSandboxState provider effect replay", () => { }; const currentBinding = { name: "my-assistant-tavily-search", - type: "tavily", + type: "tavily-policy-binding-v1", credentialEnv: "TAVILY_API_KEY", }; const session = createSession({ @@ -460,7 +460,7 @@ describe("handleSandboxState provider effect replay", () => { }; const currentBinding = { name: "my-assistant-tavily-search", - type: "tavily", + type: "tavily-policy-binding-v1", credentialEnv: "TAVILY_API_KEY", }; const messagingBinding = { @@ -636,7 +636,7 @@ describe("handleSandboxState provider effect replay", () => { }; const currentBinding = { name: "my-assistant-tavily-search", - type: "tavily", + type: "tavily-policy-binding-v1", credentialEnv: "TAVILY_API_KEY", }; const session = createSession({ @@ -706,7 +706,7 @@ describe("handleSandboxState provider effect replay", () => { }; const currentBinding = { name: "my-assistant-tavily-search", - type: "tavily", + type: "tavily-policy-binding-v1", credentialEnv: "TAVILY_API_KEY", }; const session = createSession({ diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 4198f3efbfb..736dea86e79 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -89,6 +89,7 @@ import { import { publishAttachedProvidersBeforeDockerSandboxCreation, resolveProviderAdapter, + resolveRebuildWebSearchProviderTypes, usesNativeNvidiaProvider, usesNativeHostedProvider, validateAttachedNativeProfileBeforeSandboxCreation, @@ -391,6 +392,7 @@ export function selectRebuildCreatePolicy( policySource?: string, inferenceProvider: string | null = null, webSearchCredentialProviders: readonly string[] = [], + webSearchProviderTypes?: Readonly>, ): import("../initial-policy").InitialSandboxPolicy { const requiredNetworkPolicySources = requiredNetworkPolicyPresetNames.map((presetName) => { const source = loadMessagingChannelPolicyPreset(presetName, { @@ -428,6 +430,7 @@ export function selectRebuildCreatePolicy( authorizedCredentialBindingProviders, webSearchAgentName: messagingAgent, webSearchCredentialProviders, + webSearchProviderTypes, }); } @@ -3003,6 +3006,15 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche ? { policyProviders: rebuildPolicySource.providers } : { policyDocument: rebuildPolicyDocument }), }); + const rebuildWebSearchProviderTypes = await resolveRebuildWebSearchProviderTypes({ + rebuildPolicySourcePath: createIntent?.rebuildPolicySourcePath, + sandboxName, + agentName: effectiveMessagingAgent, + extraProviders: resolvedCreateIntent.extraProviders, + messagingProviderRequests: resolvedCreateIntent.messagingProviderRequests, + gatewayName: GATEWAY_NAME, + runOpenshell, + }); const initialSandboxPolicy = createIntent?.rebuildPolicySourcePath ? selectRebuildCreatePolicy( createIntent.rebuildPolicySourcePath, @@ -3023,6 +3035,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche rebuildPolicySource?.document, resolvedCreateIntent.inferenceProvider, resolvedCreateIntent.extraProviders, + rebuildWebSearchProviderTypes, ) : materializedInitialSandboxPolicy; const createRequestPlan = selectRebuildCreateRequestPlan({ diff --git a/src/lib/onboard/sandbox-create/provider-publication.ts b/src/lib/onboard/sandbox-create/provider-publication.ts index 1aa166c9296..2f95635cddd 100644 --- a/src/lib/onboard/sandbox-create/provider-publication.ts +++ b/src/lib/onboard/sandbox-create/provider-publication.ts @@ -33,6 +33,8 @@ import { NVIDIA_HOSTED_NATIVE_PROVIDER, requireNativeNvidiaProviderProfileBoundary, } from "../../inference/native-nvidia"; +import { TAVILY_POLICY_BINDING_PROVIDER_PROFILE_ID } from "../../inference/web-search/provider-profile"; +import { webSearchCredentialProviderCandidates } from "../../policy/preset-parsing"; import { messagingCredentialProviderProfilePath, MESSAGING_CREDENTIAL_PROVIDER_TYPE, @@ -301,6 +303,47 @@ export function usesNativeHostedProvider(inferenceProvider: string | null): bool return isNativeHostedProviderName(inferenceProvider); } +/** + * Inspect the gateway profile types of rebuild web-search candidates so a + * legacy endpoint-bearing tavily-search provider is never bound into policy. + */ +export async function resolveRebuildWebSearchProviderTypes(input: { + readonly rebuildPolicySourcePath?: string | null; + readonly sandboxName: string; + readonly agentName: string | null | undefined; + readonly extraProviders: readonly string[]; + readonly messagingProviderRequests: SandboxCreateIntent["messagingProviderRequests"]; + readonly gatewayName: string; + readonly runOpenshell: SandboxCreateOrchestrationRuntime["runOpenshell"]; +}): Promise> | undefined> { + if (!input.rebuildPolicySourcePath) return undefined; + const candidates = webSearchCredentialProviderCandidates( + "tavily", + input.sandboxName, + input.agentName, + ); + const extraSet = new Set(input.extraProviders); + const requestTypes = new Map( + input.messagingProviderRequests.map((request) => [request.name, request.providerType ?? null]), + ); + const providerTypes: Record = {}; + let adapter: OpenShellProviderAdapter | null = null; + const target = namedOpenShellGateway(input.gatewayName); + for (const candidate of candidates) { + if (requestTypes.get(candidate) === TAVILY_POLICY_BINDING_PROVIDER_PROFILE_ID) { + providerTypes[candidate] = TAVILY_POLICY_BINDING_PROVIDER_PROFILE_ID; + continue; + } + if (!extraSet.has(candidate)) continue; + adapter ??= createCliOpenShellProviderAdapter({ + run: (args, options) => input.runOpenshell(args, options), + }); + const observed = await adapter.getProvider({ target, providerName: candidate }); + providerTypes[candidate] = observed.ok ? observed.value.type : null; + } + return providerTypes; +} + export async function verifyNativeHostedAttachmentAfterCreate(input: { readonly sandboxName: string; readonly gatewayName: string; diff --git a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts index 05e2d4f3d20..9af22db3b52 100644 --- a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts +++ b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts @@ -511,6 +511,17 @@ network_policies: provider: "tavily-search", }); expect(handoff.cleanup?.()).toBe(true); + + const legacyHandoff = materializeRebuildPolicyHandoff({ + sandboxName: "alpha", + livePolicyPath: livePath, + replacementPolicy: { policyPath: replacementPath, appliedPresets: [] }, + webSearchAgentName: "langchain-deepagents-code", + webSearchCredentialProviders: ["tavily-search"], + webSearchProviderTypes: { "tavily-search": "tavily" }, + }); + expect(legacyHandoff.policyPath).toBe(livePath); + expect(legacyHandoff.credentialBindingProviders).toEqual([]); }); it("leaves a substituted web-search endpoint unbound", () => { diff --git a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts index b5454e3bebf..63869a6a54f 100644 --- a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts +++ b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts @@ -10,11 +10,12 @@ import { parseOpenShellPolicy, stripProviderComposedPolicies, } from "../../adapters/openshell/policy-boundary"; +import { TAVILY_POLICY_BINDING_PROVIDER_PROFILE_ID } from "../../inference/web-search/provider-profile"; import { isReviewedMessagingChannelPolicyUpgrade } from "../../messaging/channels/policy"; import { reconcileTeamsOutlookLoginCredentialBinding } from "../../policy/microsoft-login-credential-binding"; import { bindWebSearchPresetProviders, - parseWebSearchEndpointContract, + getWebSearchPresetContracts, } from "../../policy/preset-parsing"; import { parseAndValidateSandboxPolicy } from "../../policy/sandbox-policy-validation"; import { getCredentialBindingProviders, type InitialSandboxPolicy } from "../initial-policy"; @@ -22,24 +23,17 @@ import { cleanupTempDir, createExactTempFileCleanup, secureTempFile } from "../t const REBUILD_POLICY_HANDOFF_PREFIX = "nemoclaw-rebuild-policy-handoff"; -function webSearchRebuildContracts(): Record< - string, - ReturnType -> { - const contracts: Record> = {}; - const presetsDir = path.join( - path.resolve(__dirname, "..", "..", "..", ".."), - "nemoclaw-blueprint", - "policies", - "presets", - ); - for (const presetName of ["brave", "tavily"]) { - const file = path.join(presetsDir, `${presetName}.yaml`); - contracts[presetName] = fs.existsSync(file) - ? parseWebSearchEndpointContract(fs.readFileSync(file, "utf8"), presetName) - : null; - } - return contracts; +function webSearchRebuildContracts() { + return getWebSearchPresetContracts((presetName) => { + const file = path.join( + path.resolve(__dirname, "..", "..", "..", ".."), + "nemoclaw-blueprint", + "policies", + "presets", + `${presetName}.yaml`, + ); + return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null; + }); } type PolicyMapping = Record; @@ -337,21 +331,35 @@ export function mergeReplacementPolicyAccess( : { changed: false, source: normalizedLivePolicySource }; } +function compatibleRebuildWebSearchProviders(input: { + readonly webSearchCredentialProviders?: readonly string[]; + readonly webSearchProviderTypes?: Readonly>; +}): string[] { + const providers = input.webSearchCredentialProviders ?? []; + if (!input.webSearchProviderTypes) return [...providers]; + return providers.filter( + (provider) => + input.webSearchProviderTypes![provider] === TAVILY_POLICY_BINDING_PROVIDER_PROFILE_ID, + ); +} + function bindRebuildWebSearchProviders( source: string, input: { readonly sandboxName?: string; readonly webSearchAgentName?: string | null; readonly webSearchCredentialProviders?: readonly string[]; + readonly webSearchProviderTypes?: Readonly>; }, ): string { - const providers = input.webSearchCredentialProviders ?? []; + const providers = compatibleRebuildWebSearchProviders(input); if (!input.sandboxName || providers.length === 0) return source; return bindWebSearchPresetProviders({ content: source, sandboxName: input.sandboxName, agentName: input.webSearchAgentName, availableProviders: new Set(providers), + providerTypes: input.webSearchProviderTypes, contracts: webSearchRebuildContracts(), }); } @@ -360,10 +368,11 @@ function bindRebuildWebSearchProviders( function handoffAuthorizedProviders(input: { readonly authorizedCredentialBindingProviders?: readonly string[]; readonly webSearchCredentialProviders?: readonly string[]; + readonly webSearchProviderTypes?: Readonly>; }): string[] { return [ ...(input.authorizedCredentialBindingProviders ?? []), - ...(input.webSearchCredentialProviders ?? []), + ...compatibleRebuildWebSearchProviders(input), ]; } @@ -379,6 +388,7 @@ export function materializeRebuildPolicyHandoff(input: { readonly authorizedCredentialBindingProviders?: readonly string[]; readonly webSearchAgentName?: string | null; readonly webSearchCredentialProviders?: readonly string[]; + readonly webSearchProviderTypes?: Readonly>; }): InitialSandboxPolicy { const liveSource = input.livePolicySource ?? fs.readFileSync(input.livePolicyPath, "utf8"); const replacementSource = diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index d4a7ab1c3f4..f45ac8e6ba9 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -42,6 +42,7 @@ import { } from "../messaging/channels"; import { readSandboxProviderAttachments, + readSandboxProviderProfileType, resolveSandboxGatewayName, } from "../onboard/gateway-binding"; import { assertNoOpenShellGatewayEndpointOverride } from "../openshell-gateway-endpoint-guard"; @@ -83,8 +84,8 @@ import { type PolicyValue, parseNetworkPolicies, applyWebSearchCredentialBinding, + getWebSearchPresetContracts, isWebSearchPolicyPreset, - parseWebSearchEndpointContract, resolveWebSearchCredentialProvider, } from "./preset-parsing"; import { escapeTerminalText, logPresetScope, renderPresetScope } from "./preset-scope-render"; @@ -149,6 +150,8 @@ type SandboxPresetLoadOptions = { gatewayName?: string; /** Providers attached to the sandbox. Null means the observation failed and no binding is added. */ attachedProviders?: readonly string[] | null; + /** Profile types keyed by attached provider name. */ + attachedProviderProfiles?: Readonly>; recordedProviders?: readonly string[]; }; @@ -446,22 +449,12 @@ function recordedWebSearchProviders(sandboxName: string): Set { return providers; } -let webSearchContracts: Record> | null = - null; - -function webSearchPresetContracts(): Record< - string, - ReturnType +function webSearchPresetContracts(): Readonly< + Record[string]> > { - if (webSearchContracts) return webSearchContracts; - webSearchContracts = {}; - for (const presetName of ["brave", "tavily"]) { - const content = loadCentralPreset(presetName, { reportMissing: false }); - webSearchContracts[presetName] = content - ? parseWebSearchEndpointContract(content, presetName) - : null; - } - return webSearchContracts; + return getWebSearchPresetContracts((presetName) => + loadCentralPreset(presetName, { reportMissing: false }), + ); } /** @@ -484,6 +477,7 @@ function bindWebSearchPreset( agentName: string | null, attachedProviders: readonly string[] | null, recordedProviders: readonly string[] | undefined, + attachedProviderProfiles?: Readonly>, ): string { // Hermes Tavily and every Brave provider use an endpoint-bearing profile. // The pinned OpenShell release rejects a policy binding that names that @@ -504,6 +498,7 @@ function bindWebSearchPreset( agentName, availableProviders: new Set(recordedProviders ?? recordedWebSearchProviders(sandboxName)), attachedProviders: new Set(attachedProviders), + providerTypes: attachedProviderProfiles, }), webSearchPresetContracts()[presetName] ?? null, ); @@ -568,6 +563,28 @@ async function loadPresetForSandbox( : isWebSearchPolicyPreset(presetName) ? await readSandboxProviderAttachments(sandboxName, sandbox) : null; + let attachedProviderProfiles = options.attachedProviderProfiles; + if ( + presetName === "tavily" && + attachedProviders !== null && + attachedProviderProfiles === undefined && + options.attachedProviders === undefined + ) { + const candidate = resolveWebSearchCredentialProvider({ + presetName, + sandboxName, + agentName: sandboxAgent, + availableProviders: new Set( + options.recordedProviders ?? recordedWebSearchProviders(sandboxName), + ), + attachedProviders: new Set(attachedProviders), + }); + if (candidate) { + attachedProviderProfiles = { + [candidate]: await readSandboxProviderProfileType(candidate, sandbox, options.gatewayName), + }; + } + } const boundPresetContent = bindWebSearchPreset( resolvedPresetContent, presetName, @@ -575,6 +592,7 @@ async function loadPresetForSandbox( sandboxAgent, attachedProviders, options.recordedProviders, + attachedProviderProfiles, ); return presetName === "outlook" && sandboxAgent !== "hermes" && @@ -2667,12 +2685,29 @@ async function applyPreset( presetName: string, options: Record = {}, ): Promise { + const attachedProviders = isWebSearchPolicyPreset(presetName) + ? await observedSandboxAttachments(sandboxName) + : null; + let attachedProviderProfiles: Readonly> | undefined; + if (presetName === "tavily" && attachedProviders !== null) { + const sandbox = registry.getSandbox(sandboxName); + const candidate = resolveWebSearchCredentialProvider({ + presetName, + sandboxName, + agentName: sandbox?.agent ?? null, + availableProviders: recordedWebSearchProviders(sandboxName), + attachedProviders: new Set(attachedProviders), + }); + if (candidate) { + attachedProviderProfiles = { + [candidate]: await readSandboxProviderProfileType(candidate, sandbox), + }; + } + } const presetContent = await loadPresetForSandbox(sandboxName, presetName, { includeMessagingCredentialBindings: options.includeMessagingCredentialBindings === true, messagingConfig: options.messagingConfig as MessagingPolicyConfig | null | undefined, - ...(isWebSearchPolicyPreset(presetName) - ? { attachedProviders: await observedSandboxAttachments(sandboxName) } - : {}), + ...(isWebSearchPolicyPreset(presetName) ? { attachedProviders, attachedProviderProfiles } : {}), }); if (!presetContent) { console.error(` Cannot load preset: ${presetName}`); @@ -2707,9 +2742,27 @@ async function applyPresets(sandboxName: string, presetNames: string[]): Promise const attachedProviders = uniquePresetNames.some(isWebSearchPolicyPreset) ? await observedSandboxAttachments(sandboxName) : null; + let attachedProviderProfiles: Readonly> | undefined; + if (uniquePresetNames.includes("tavily") && attachedProviders !== null) { + const sandbox = registry.getSandbox(sandboxName); + const candidate = resolveWebSearchCredentialProvider({ + presetName: "tavily", + sandboxName, + agentName: sandbox?.agent ?? null, + availableProviders: recordedWebSearchProviders(sandboxName), + attachedProviders: new Set(attachedProviders), + }); + if (candidate) { + attachedProviderProfiles = { + [candidate]: await readSandboxProviderProfileType(candidate, sandbox), + }; + } + } for (const presetName of uniquePresetNames) { const presetContent = await loadPresetForSandbox(sandboxName, presetName, { - ...(isWebSearchPolicyPreset(presetName) ? { attachedProviders } : {}), + ...(isWebSearchPolicyPreset(presetName) + ? { attachedProviders, attachedProviderProfiles } + : {}), }); if (!presetContent) { console.error(` Cannot load preset: ${presetName}`); @@ -3280,4 +3333,5 @@ export { selectForRemoval, selectFromList, setupPolicyPresetSupported, + webSearchPresetContracts, }; diff --git a/src/lib/policy/preset-parsing.test.ts b/src/lib/policy/preset-parsing.test.ts index f5983a54484..1efffc653ee 100644 --- a/src/lib/policy/preset-parsing.test.ts +++ b/src/lib/policy/preset-parsing.test.ts @@ -35,7 +35,7 @@ function tavilyEndpoints(content: string): Array> { const tavilyContract = parseWebSearchEndpointContract(tavilyPreset, "tavily"); describe("web-search credential provider resolution", () => { - it("recognizes the web-search presets", () => { + it("classifies brave and tavily as web-search presets and rejects other presets", () => { expect(isWebSearchPolicyPreset("tavily")).toBe(true); expect(isWebSearchPolicyPreset("brave")).toBe(true); expect(isWebSearchPolicyPreset("weather")).toBe(false); @@ -98,6 +98,15 @@ describe("web-search credential binding", () => { expect( YAML.parse(bound).network_policies.tavily.endpoints[0].credential_binding, ).toBeUndefined(); + const withAddedField = tavilyPreset.replace( + " request_body_credential_rewrite: true\n", + " request_body_credential_rewrite: true\n path: /custom\n", + ); + expect( + YAML.parse( + applyWebSearchCredentialBinding(withAddedField, "tavily", "tavily-search", tavilyContract), + ).network_policies.tavily.endpoints[0].credential_binding, + ).toBeUndefined(); expect(applyWebSearchCredentialBinding(tavilyPreset, "tavily", "tavily-search", null)).toBe( tavilyPreset, ); @@ -203,6 +212,24 @@ describe("loadPresetForSandbox web-search binding", () => { ]); }); + it("omits the binding when the attached provider uses an endpoint-bearing profile", async () => { + mocks.getSandbox.mockReturnValue({ + name: sandboxName, + agent: "langchain-deepagents-code", + gatewayName: "nemoclaw", + }); + mocks.listExtraProviders.mockReturnValue(["tavily-search"]); + + const content = await loadPresetForSandbox(sandboxName, "tavily", { + attachedProviders: ["tavily-search"], + attachedProviderProfiles: { "tavily-search": "tavily" }, + }); + + expect(tavilyEndpoints(content!)).toEqual([ + expect.not.objectContaining({ credential_binding: expect.anything() }), + ]); + }); + it("omits the binding when no web-search provider is recorded", async () => { mocks.getSandbox.mockReturnValue({ name: sandboxName, diff --git a/src/lib/policy/preset-parsing.ts b/src/lib/policy/preset-parsing.ts index 959a777f2e0..45db7c7fae6 100644 --- a/src/lib/policy/preset-parsing.ts +++ b/src/lib/policy/preset-parsing.ts @@ -7,6 +7,7 @@ import YAML from "yaml"; import { isObjectRecord, type JsonObject, type JsonValue } from "../core/json-types"; import { DEFAULT_VLLM_PORT, VLLM_PORT } from "../core/vllm-port"; +import { TAVILY_POLICY_BINDING_PROVIDER_PROFILE_ID } from "../inference/web-search/provider-profile"; import { isDcodeAgent } from "../onboard/observability-policy-presets"; export type PolicyValue = JsonValue; @@ -183,6 +184,12 @@ export function resolveWebSearchCredentialProvider(input: { * credential_binding that names an unattached provider. */ readonly attachedProviders?: ReadonlySet; + /** + * Observed profile types keyed by provider name. When supplied for Tavily, + * only a provider that uses tavily-policy-binding-v1 qualifies; OpenShell + * rejects a credential_binding that names an endpoint-bearing profile. + */ + readonly providerTypes?: Readonly>; }): string | null { for (const candidate of webSearchCredentialProviderCandidates( input.presetName, @@ -191,6 +198,13 @@ export function resolveWebSearchCredentialProvider(input: { )) { if (!input.availableProviders.has(candidate)) continue; if (input.attachedProviders && !input.attachedProviders.has(candidate)) continue; + if ( + input.presetName === "tavily" && + input.providerTypes && + input.providerTypes[candidate] !== TAVILY_POLICY_BINDING_PROVIDER_PROFILE_ID + ) { + continue; + } return candidate; } return null; @@ -203,6 +217,7 @@ export function resolveWebSearchCredentialProvider(input: { * checked-in preset declares. */ export type WebSearchEndpointContract = Readonly<{ + endpoint: Readonly>; host: string; port: number; protocol: string; @@ -211,8 +226,6 @@ export type WebSearchEndpointContract = Readonly<{ requestBodyCredentialRewrite: boolean; }>; -const WEB_SEARCH_CONTRACT_KEYS = ["host", "port", "protocol", "enforcement", "rules"] as const; - function contractString(value: JsonValue): string | null { return typeof value === "string" ? value : null; } @@ -255,6 +268,7 @@ export function parseWebSearchEndpointContract( const rules = contractRules(endpoint.rules); if (!host || port === null || !protocol || !enforcement || !rules) return null; return { + endpoint, host, port, protocol, @@ -268,12 +282,9 @@ function matchesWebSearchEndpointContract( endpoint: PolicyObject, contract: WebSearchEndpointContract, ): boolean { - return ( - WEB_SEARCH_CONTRACT_KEYS.every((key) => - isDeepStrictEqual(endpoint[key], contract[key as keyof WebSearchEndpointContract]), - ) && - (endpoint.request_body_credential_rewrite === true) === contract.requestBodyCredentialRewrite - ); + const candidate = { ...endpoint }; + delete candidate.credential_binding; + return isDeepStrictEqual(candidate, contract.endpoint); } /** @@ -327,6 +338,7 @@ export function bindWebSearchPresetProviders(input: { readonly sandboxName: string; readonly agentName?: string | null; readonly availableProviders: ReadonlySet; + readonly providerTypes?: Readonly>; readonly contracts?: Readonly>; }): string { let content = input.content; @@ -345,6 +357,7 @@ export function bindWebSearchPresetProviders(input: { sandboxName: input.sandboxName, agentName: input.agentName, availableProviders: input.availableProviders, + providerTypes: input.providerTypes, }); content = applyWebSearchCredentialBinding( content, @@ -355,3 +368,22 @@ export function bindWebSearchPresetProviders(input: { } return content; } + +let cachedWebSearchContracts: Record | null = null; + +/** + * Parse and cache the checked-in web-search preset endpoint contracts once so + * live policy loading and rebuild handoff share the same contract source. + */ +export function getWebSearchPresetContracts( + loadPresetContent?: (presetName: string) => string | null, +): Readonly> { + if (cachedWebSearchContracts) return cachedWebSearchContracts; + const contracts: Record = {}; + for (const presetName of Object.keys(WEB_SEARCH_PRESET_PROVIDER_SUFFIXES)) { + const content = loadPresetContent ? loadPresetContent(presetName) : null; + contracts[presetName] = content ? parseWebSearchEndpointContract(content, presetName) : null; + } + if (loadPresetContent) cachedWebSearchContracts = contracts; + return contracts; +} diff --git a/test/package-contract/cli/credentials-cli-command.test.ts b/test/package-contract/cli/credentials-cli-command.test.ts index dd02db3ade5..f969cd846a3 100644 --- a/test/package-contract/cli/credentials-cli-command.test.ts +++ b/test/package-contract/cli/credentials-cli-command.test.ts @@ -60,7 +60,7 @@ type RuntimeBridge = { type OpenshellCall = { args: string[]; opts?: RuntimeBridgeRunOptions }; const TAVILY_PROFILE_EXPORT = JSON.stringify({ - id: "tavily", + id: "tavily-policy-binding-v1", credentials: [ { name: "api_key", @@ -71,26 +71,8 @@ const TAVILY_PROFILE_EXPORT = JSON.stringify({ query_param: "", }, ], - endpoints: [ - { - host: "api.tavily.com", - port: 443, - protocol: "rest", - enforcement: "enforce", - request_body_credential_rewrite: true, - rules: [ - { allow: { method: "POST", path: "/search" } }, - { allow: { method: "POST", path: "/extract" } }, - ], - }, - ], - binaries: [ - "/opt/venv/bin/python3*", - "/usr/local/bin/node", - "/usr/bin/node", - "/usr/local/bin/curl", - "/usr/bin/curl", - ], + endpoints: [], + binaries: [], inference_capable: false, }); @@ -445,7 +427,16 @@ describe("credentials oclif commands", () => { expect(calls).toEqual([ { - args: ["provider", "profile", "-g", "nemoclaw", "export", "tavily", "--output", "json"], + args: [ + "provider", + "profile", + "-g", + "nemoclaw", + "export", + "tavily-policy-binding-v1", + "--output", + "json", + ], opts: { env: expect.any(Object), ignoreError: true, @@ -464,7 +455,7 @@ describe("credentials oclif commands", () => { "--name", "tavily-search", "--type", - "tavily", + "tavily-policy-binding-v1", "--credential", "TAVILY_API_KEY", ], @@ -479,7 +470,16 @@ describe("credentials oclif commands", () => { }, }, { - args: ["provider", "profile", "-g", "nemoclaw", "export", "tavily", "--output", "json"], + args: [ + "provider", + "profile", + "-g", + "nemoclaw", + "export", + "tavily-policy-binding-v1", + "--output", + "json", + ], opts: { env: expect.any(Object), ignoreError: true, @@ -654,11 +654,13 @@ describe("credentials oclif commands", () => { "-g", "nemoclaw", "export", - "tavily", + "tavily-policy-binding-v1", "--output", "json", ]); - expect(output.stderr).toContain("Could not import bundled provider profile 'tavily'"); + expect(output.stderr).toContain( + "Could not import bundled provider profile 'tavily-policy-binding-v1'", + ); expect(output.stderr).not.toContain(leakedTavilyValue); } finally { delete process.env.TAVILY_API_KEY; From 7c3606e8e2981e39cb9c8c74a41761d321c8a8d4 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Thu, 29 Oct 2026 08:16:39 +0000 Subject: [PATCH 4/4] fix(policy): unify web-search preset binding and verify rebuild rewrite Signed-off-by: Tinson Lai --- docs/reference/troubleshooting.mdx | 4 +- .../onboard/sandbox-create/orchestration.ts | 5 +- .../rebuild-policy-handoff.test.ts | 45 ++++++ src/lib/policy/index.ts | 144 +++++++----------- src/lib/policy/policy-live-state.test.ts | 54 +++++++ src/lib/policy/preset-parsing.test.ts | 57 +++++++ src/lib/policy/preset-parsing.ts | 3 + .../09-deepagents-code-tavily-opt-in.sh | 116 ++++++++++++-- ...platform-parity-cloud-experimental.test.ts | 47 +++++- 9 files changed, 365 insertions(+), 110 deletions(-) diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index f14b11452cd..1c879892eab 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -823,7 +823,9 @@ $$nemoclaw config get --key tools.web.search --format yaml The provider should be `brave` or `tavily` and `enabled` should be `true`. If the provider is wrong, rerun onboarding with `NEMOCLAW_WEB_SEARCH_PROVIDER=brave` or `tavily` and the matching `BRAVE_API_KEY` or `TAVILY_API_KEY`. If a rebuild reports that `TAVILY_API_KEY` is not available for a sandbox that was onboarded with the earlier `tavily` profile, export `TAVILY_API_KEY` and rerun the rebuild so NemoClaw registers `-tavily-search` with the current profile. -If `logs` shows a `credential_unavailable` denial for `api.tavily.com`, confirm that `-tavily-search` is attached and uses the `tavily-policy-binding-v1` profile, then rerun `$$nemoclaw rebuild`. +If `logs` shows a `credential_unavailable` denial for `api.tavily.com`, confirm that `-tavily-search` is attached and uses the `tavily-policy-binding-v1` profile, and compare the configured `tavily` endpoint with the checked-in preset. +A differing endpoint remains unbound even when the provider and profile are valid, and a rebuild preserves that edited policy. +If the endpoint differs, review your custom policy changes, reapply the `tavily` preset when appropriate, and then rerun `$$nemoclaw rebuild`. diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 736dea86e79..7f1cd204405 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -3034,7 +3034,10 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche rebuildPolicyProviderAuthority, rebuildPolicySource?.document, resolvedCreateIntent.inferenceProvider, - resolvedCreateIntent.extraProviders, + [ + ...resolvedCreateIntent.extraProviders, + ...resolvedCreateIntent.messagingProviderRequests.map((request) => request.name), + ], rebuildWebSearchProviderTypes, ) : materializedInitialSandboxPolicy; diff --git a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts index 9af22db3b52..788a96a0c9e 100644 --- a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts +++ b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.test.ts @@ -17,6 +17,8 @@ import { mergeReplacementPolicyAccess, readValidatedRebuildPolicySource, } from "./rebuild-policy-handoff"; +import { selectRebuildCreatePolicy } from "./orchestration"; +import { resolveRebuildWebSearchProviderTypes } from "./provider-publication"; const roots: string[] = []; @@ -522,6 +524,49 @@ network_policies: }); expect(legacyHandoff.policyPath).toBe(livePath); expect(legacyHandoff.credentialBindingProviders).toEqual([]); + + const messagingProviderRequests = [ + { + name: "alpha-tavily-search", + envKey: "TAVILY_API_KEY", + channel: null, + credentialConfigured: true, + providerType: "tavily-policy-binding-v1", + }, + ] as const; + return resolveRebuildWebSearchProviderTypes({ + rebuildPolicySourcePath: livePath, + sandboxName: "alpha", + agentName: "openclaw", + extraProviders: [], + messagingProviderRequests, + gatewayName: "nemoclaw", + runOpenshell: vi.fn(), + }).then((providerTypes) => { + const openClawHandoff = selectRebuildCreatePolicy( + livePath, + { policyPath: replacementPath, appliedPresets: [] }, + [], + [], + [], + "openclaw", + null, + "alpha", + [], + undefined, + null, + [...messagingProviderRequests.map((request) => request.name)], + providerTypes, + ); + expect(openClawHandoff.credentialBindingProviders).toEqual(["alpha-tavily-search"]); + const openClawEndpoint = readPrivatePolicy(openClawHandoff.policyPath).policy as { + network_policies: { tavily: { endpoints: Array> } }; + }; + expect(openClawEndpoint.network_policies.tavily.endpoints[0]!.credential_binding).toEqual({ + provider: "alpha-tavily-search", + }); + expect(openClawHandoff.cleanup?.()).toBe(true); + }); }); it("leaves a substituted web-search endpoint unbound", () => { diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index f45ac8e6ba9..2ad88df4c5b 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -83,10 +83,10 @@ import { type PolicyObject, type PolicyValue, parseNetworkPolicies, - applyWebSearchCredentialBinding, + bindWebSearchPresetProviders, getWebSearchPresetContracts, isWebSearchPolicyPreset, - resolveWebSearchCredentialProvider, + webSearchCredentialProviderCandidates, } from "./preset-parsing"; import { escapeTerminalText, logPresetScope, renderPresetScope } from "./preset-scope-render"; import { parseAndValidateSandboxPolicy } from "./sandbox-policy-validation"; @@ -470,38 +470,25 @@ async function observedSandboxAttachments(sandboxName: string): Promise>, -): string { - // Hermes Tavily and every Brave provider use an endpoint-bearing profile. - // The pinned OpenShell release rejects a policy binding that names that - // provider, and the profile attachment delivers the credential itself. - if ( - presetName === "brave" || - (presetName === "tavily" && agentName?.trim().toLowerCase() === "hermes") - ) { - return content; - } - if (!isWebSearchPolicyPreset(presetName) || attachedProviders === null) return content; - return applyWebSearchCredentialBinding( - content, - presetName, - resolveWebSearchCredentialProvider({ - presetName, - sandboxName, - agentName, - availableProviders: new Set(recordedProviders ?? recordedWebSearchProviders(sandboxName)), - attachedProviders: new Set(attachedProviders), - providerTypes: attachedProviderProfiles, - }), - webSearchPresetContracts()[presetName] ?? null, - ); + sandbox: registry.SandboxEntry | null, + attachedProviders: readonly string[], + recordedProviders?: readonly string[], + gatewayName?: string, +): Promise>> { + const available = new Set(recordedProviders ?? recordedWebSearchProviders(sandboxName)); + const attached = new Set(attachedProviders); + const profiles: Record = {}; + for (const candidate of webSearchCredentialProviderCandidates( + "tavily", + sandboxName, + sandbox?.agent ?? null, + )) { + if (!available.has(candidate) || !attached.has(candidate)) continue; + profiles[candidate] = await readSandboxProviderProfileType(candidate, sandbox, gatewayName); + } + return profiles; } /** @@ -570,30 +557,27 @@ async function loadPresetForSandbox( attachedProviderProfiles === undefined && options.attachedProviders === undefined ) { - const candidate = resolveWebSearchCredentialProvider({ - presetName, + attachedProviderProfiles = await observeAttachedTavilyProviderProfiles( sandboxName, - agentName: sandboxAgent, - availableProviders: new Set( - options.recordedProviders ?? recordedWebSearchProviders(sandboxName), - ), - attachedProviders: new Set(attachedProviders), - }); - if (candidate) { - attachedProviderProfiles = { - [candidate]: await readSandboxProviderProfileType(candidate, sandbox, options.gatewayName), - }; - } + sandbox, + attachedProviders, + options.recordedProviders, + options.gatewayName, + ); } - const boundPresetContent = bindWebSearchPreset( - resolvedPresetContent, - presetName, - sandboxName, - sandboxAgent, - attachedProviders, - options.recordedProviders, - attachedProviderProfiles, - ); + const boundPresetContent = isWebSearchPolicyPreset(presetName) + ? bindWebSearchPresetProviders({ + content: resolvedPresetContent, + sandboxName, + agentName: sandboxAgent, + availableProviders: new Set( + options.recordedProviders ?? recordedWebSearchProviders(sandboxName), + ), + attachedProviders: attachedProviders === null ? null : new Set(attachedProviders), + providerTypes: attachedProviderProfiles, + contracts: webSearchPresetContracts(), + }) + : resolvedPresetContent; return presetName === "outlook" && sandboxAgent !== "hermes" && configuredMessagingChannels.includes("teams") @@ -1843,14 +1827,16 @@ function mergePresetNamesIntoPolicy( }); const presetContent = loaded && isWebSearchPolicyPreset(presetName) - ? bindWebSearchPreset( - loaded, - presetName, - options.sandboxName ?? "", - options.agent ?? null, - planned ?? null, - planned, - ) + ? bindWebSearchPresetProviders({ + content: loaded, + sandboxName: options.sandboxName ?? "", + agentName: options.agent ?? null, + availableProviders: new Set( + planned ?? recordedWebSearchProviders(options.sandboxName ?? ""), + ), + attachedProviders: planned ? new Set(planned) : null, + contracts: webSearchPresetContracts(), + }) : loaded; const presetEntries = extractPresetEntries(presetContent); if (!presetEntries) { @@ -2690,19 +2676,11 @@ async function applyPreset( : null; let attachedProviderProfiles: Readonly> | undefined; if (presetName === "tavily" && attachedProviders !== null) { - const sandbox = registry.getSandbox(sandboxName); - const candidate = resolveWebSearchCredentialProvider({ - presetName, + attachedProviderProfiles = await observeAttachedTavilyProviderProfiles( sandboxName, - agentName: sandbox?.agent ?? null, - availableProviders: recordedWebSearchProviders(sandboxName), - attachedProviders: new Set(attachedProviders), - }); - if (candidate) { - attachedProviderProfiles = { - [candidate]: await readSandboxProviderProfileType(candidate, sandbox), - }; - } + registry.getSandbox(sandboxName), + attachedProviders, + ); } const presetContent = await loadPresetForSandbox(sandboxName, presetName, { includeMessagingCredentialBindings: options.includeMessagingCredentialBindings === true, @@ -2744,19 +2722,11 @@ async function applyPresets(sandboxName: string, presetNames: string[]): Promise : null; let attachedProviderProfiles: Readonly> | undefined; if (uniquePresetNames.includes("tavily") && attachedProviders !== null) { - const sandbox = registry.getSandbox(sandboxName); - const candidate = resolveWebSearchCredentialProvider({ - presetName: "tavily", + attachedProviderProfiles = await observeAttachedTavilyProviderProfiles( sandboxName, - agentName: sandbox?.agent ?? null, - availableProviders: recordedWebSearchProviders(sandboxName), - attachedProviders: new Set(attachedProviders), - }); - if (candidate) { - attachedProviderProfiles = { - [candidate]: await readSandboxProviderProfileType(candidate, sandbox), - }; - } + registry.getSandbox(sandboxName), + attachedProviders, + ); } for (const presetName of uniquePresetNames) { const presetContent = await loadPresetForSandbox(sandboxName, presetName, { diff --git a/src/lib/policy/policy-live-state.test.ts b/src/lib/policy/policy-live-state.test.ts index a073ea2a984..1cad3f4d5de 100644 --- a/src/lib/policy/policy-live-state.test.ts +++ b/src/lib/policy/policy-live-state.test.ts @@ -14,8 +14,11 @@ import { digestBaselineEntry } from "./baseline-exclusion"; const mocks = vi.hoisted(() => ({ getSandbox: vi.fn(), inspectSandboxPolicy: vi.fn(), + listExtraProviders: vi.fn(), readSandboxPolicy: vi.fn(), readSandboxPolicyRevision: vi.fn(), + readSandboxProviderAttachments: vi.fn(), + readSandboxProviderProfileType: vi.fn(), resolveOpenshell: vi.fn(), setSandboxPolicy: vi.fn<(request: SetOpenShellSandboxPolicyRequest) => OpenShellSandboxPolicySetSubmission>(), @@ -36,12 +39,19 @@ vi.mock("../adapters/openshell/resolve", async (importOriginal) => ({ ...(await importOriginal()), resolveOpenshell: mocks.resolveOpenshell, })); +vi.mock("../onboard/gateway-binding", async (importOriginal) => ({ + ...(await importOriginal()), + readSandboxProviderAttachments: mocks.readSandboxProviderAttachments, + readSandboxProviderProfileType: mocks.readSandboxProviderProfileType, +})); vi.mock("../state/registry", async (importOriginal) => ({ ...(await importOriginal()), getSandbox: mocks.getSandbox, + listExtraProviders: mocks.listExtraProviders, })); import { + applyPreset, applyPresetContent, applyPresets, arePresetsCoveredByPersonalPolicy, @@ -78,6 +88,9 @@ describe("live OpenShell policy mutations", () => { network_policies: { host_approval: hostEntry }, }); mocks.getSandbox.mockReturnValue({ name: sandboxName, gatewayName: "nemoclaw" }); + mocks.listExtraProviders.mockReturnValue([]); + mocks.readSandboxProviderAttachments.mockResolvedValue(null); + mocks.readSandboxProviderProfileType.mockResolvedValue(null); mocks.inspectSandboxPolicy.mockImplementation(() => policyInspection({ policySource: "sandbox", @@ -730,6 +743,47 @@ describe("live OpenShell policy mutations", () => { expect.stringContaining("Cannot load preset: no-such-preset"), ); }); + + it.each(["single", "batch"] as const)( + "submits Tavily credential_binding through %s policy application only for the endpointless profile", + async (mode) => { + mocks.getSandbox.mockReturnValue({ + name: sandboxName, + agent: "langchain-deepagents-code", + gatewayName: "nemoclaw", + }); + mocks.listExtraProviders.mockReturnValue(["tavily-search"]); + mocks.readSandboxProviderAttachments.mockResolvedValue(["tavily-search"]); + mocks.readSandboxProviderProfileType.mockResolvedValue("tavily-policy-binding-v1"); + + await expect( + mode === "single" + ? applyPreset(sandboxName, "tavily", { nonFatal: true }) + : applyPresets(sandboxName, ["tavily"]), + ).resolves.toBe(true); + expect(mocks.setSandboxPolicy).toHaveBeenCalledOnce(); + expect( + YAML.parse(livePolicy).network_policies.tavily.endpoints[0].credential_binding, + ).toEqual({ provider: "tavily-search" }); + + livePolicy = YAML.stringify({ + version: 1, + network_policies: { host_approval: hostEntry }, + }); + mocks.setSandboxPolicy.mockClear(); + mocks.readSandboxProviderProfileType.mockResolvedValue("tavily"); + + await expect( + mode === "single" + ? applyPreset(sandboxName, "tavily", { nonFatal: true }) + : applyPresets(sandboxName, ["tavily"]), + ).resolves.toBe(true); + expect(mocks.setSandboxPolicy).toHaveBeenCalledOnce(); + expect( + YAML.parse(livePolicy).network_policies.tavily.endpoints[0].credential_binding, + ).toBeUndefined(); + }, + ); }); describe("getSandboxAgentName (#13618)", () => { diff --git a/src/lib/policy/preset-parsing.test.ts b/src/lib/policy/preset-parsing.test.ts index 1efffc653ee..db7dba26716 100644 --- a/src/lib/policy/preset-parsing.test.ts +++ b/src/lib/policy/preset-parsing.test.ts @@ -7,6 +7,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ getSandbox: vi.fn(), listExtraProviders: vi.fn(), + readSandboxProviderAttachments: vi.fn(), + readSandboxProviderProfileType: vi.fn(), })); vi.mock("../state/registry", async (importOriginal) => ({ @@ -14,6 +16,11 @@ vi.mock("../state/registry", async (importOriginal) => ({ getSandbox: mocks.getSandbox, listExtraProviders: mocks.listExtraProviders, })); +vi.mock("../onboard/gateway-binding", async (importOriginal) => ({ + ...(await importOriginal()), + readSandboxProviderAttachments: mocks.readSandboxProviderAttachments, + readSandboxProviderProfileType: mocks.readSandboxProviderProfileType, +})); import { loadPresetForSandbox } from "./index"; import { @@ -153,6 +160,28 @@ describe("web-search credential binding", () => { expect(parsed.tavily.endpoints[0].credential_binding).toEqual({ provider: "tavily-search" }); expect(parsed.brave.endpoints[0].credential_binding).toBeUndefined(); expect(parsed.weather.endpoints[0].credential_binding).toBeUndefined(); + + const unattached = bindWebSearchPresetProviders({ + content: document, + sandboxName, + agentName: "langchain-deepagents-code", + availableProviders: new Set(["tavily-search"]), + attachedProviders: new Set(), + contracts: { tavily: tavilyContract }, + }); + expect( + YAML.parse(unattached).network_policies.tavily.endpoints[0].credential_binding, + ).toBeUndefined(); + expect( + bindWebSearchPresetProviders({ + content: document, + sandboxName, + agentName: "langchain-deepagents-code", + availableProviders: new Set(["tavily-search"]), + attachedProviders: null, + contracts: { tavily: tavilyContract }, + }), + ).toBe(document); }); }); @@ -160,6 +189,8 @@ describe("loadPresetForSandbox web-search binding", () => { beforeEach(() => { mocks.getSandbox.mockReset(); mocks.listExtraProviders.mockReset(); + mocks.readSandboxProviderAttachments.mockReset(); + mocks.readSandboxProviderProfileType.mockReset(); }); it("binds the gateway-wide provider for a Deep Agents sandbox", async () => { @@ -230,6 +261,32 @@ describe("loadPresetForSandbox web-search binding", () => { ]); }); + it("inspects both Tavily candidates and selects the compatible fallback when the preferred candidate is legacy", async () => { + mocks.getSandbox.mockReturnValue({ + name: sandboxName, + agent: "langchain-deepagents-code", + gatewayName: "nemoclaw", + }); + mocks.listExtraProviders.mockReturnValue(["tavily-search"]); + mocks.readSandboxProviderAttachments.mockResolvedValue([ + "tavily-search", + `${sandboxName}-tavily-search`, + ]); + mocks.readSandboxProviderProfileType.mockImplementation(async (provider: string) => + provider === "tavily-search" ? "tavily" : "tavily-policy-binding-v1", + ); + + const content = await loadPresetForSandbox(sandboxName, "tavily"); + + expect(mocks.readSandboxProviderProfileType.mock.calls.map(([provider]) => provider)).toEqual([ + "tavily-search", + `${sandboxName}-tavily-search`, + ]); + expect(tavilyEndpoints(content!)).toEqual([ + expect.objectContaining({ credential_binding: { provider: `${sandboxName}-tavily-search` } }), + ]); + }); + it("omits the binding when no web-search provider is recorded", async () => { mocks.getSandbox.mockReturnValue({ name: sandboxName, diff --git a/src/lib/policy/preset-parsing.ts b/src/lib/policy/preset-parsing.ts index 45db7c7fae6..e2943bf82b8 100644 --- a/src/lib/policy/preset-parsing.ts +++ b/src/lib/policy/preset-parsing.ts @@ -338,9 +338,11 @@ export function bindWebSearchPresetProviders(input: { readonly sandboxName: string; readonly agentName?: string | null; readonly availableProviders: ReadonlySet; + readonly attachedProviders?: ReadonlySet | null; readonly providerTypes?: Readonly>; readonly contracts?: Readonly>; }): string { + if (input.attachedProviders === null) return input.content; let content = input.content; for (const presetName of Object.keys(WEB_SEARCH_PRESET_PROVIDER_SUFFIXES)) { // Hermes Tavily and every Brave provider use an endpoint-bearing profile. @@ -357,6 +359,7 @@ export function bindWebSearchPresetProviders(input: { sandboxName: input.sandboxName, agentName: input.agentName, availableProviders: input.availableProviders, + attachedProviders: input.attachedProviders, providerTypes: input.providerTypes, }); content = applyWebSearchCredentialBinding( diff --git a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh index 5fbe65d72fe..efaa667f1ea 100755 --- a/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh +++ b/test/e2e/e2e-cloud-experimental/checks/09-deepagents-code-tavily-opt-in.sh @@ -12,6 +12,10 @@ REPO="${REPO:-$(pwd)}" CLI="${NEMOCLAW_E2E_CLI:-${REPO}/bin/nemoclaw.js}" PROJECT_VENV="/sandbox/.nemoclaw-e2e-project-venv" PROJECT_PYTHON="${PROJECT_VENV}/bin/python3" +TAVILY_PROVIDER_NAME="tavily-search" +TAVILY_PROBE_CREDENTIAL="tvly-e2e-probe-$$" +TAVILY_CREDENTIAL_REGISTERED=0 +TAVILY_POLICY_APPLIED=0 ok() { printf '%s\n' "${PREFIX}: OK ($*)"; } info() { printf '%s\n' "${PREFIX}: $*"; } @@ -92,7 +96,10 @@ url = sys.argv[1] request = urllib.request.Request( url, data=json.dumps({'query': 'nemoclaw reachability probe', 'max_results': 1}).encode('utf-8'), - headers={'Content-Type': 'application/json'}, + headers={ + 'Authorization': 'Bearer openshell:resolve:env:TAVILY_API_KEY', + 'Content-Type': 'application/json', + }, method='POST', ) try: @@ -105,7 +112,9 @@ except urllib.error.HTTPError as exc: except Exception: body = '' details = f'{exc} {body}'.strip() - if is_policy_denial(details): + if 'credential_unavailable' in details.lower(): + print(f'CREDENTIAL_UNAVAILABLE:HTTPError:{details}') + elif is_policy_denial(details): print(f'BLOCKED:HTTPError:{details}') else: print(f'REACHED:{exc.code}') @@ -152,20 +161,60 @@ verify_observability_state() { pass "host registry and persistent marker preserve enabled observability $phase" } +rebuild_named_sandbox() { + local attempt output status prior_timeout_output retry_delay_seconds + prior_timeout_output="" + retry_delay_seconds="${NEMOCLAW_E2E_DCODE_REBUILD_RETRY_DELAY_SECONDS:-3}" + for attempt in 1 2; do + if output="$(nemoclaw_cli "$SANDBOX_NAME" rebuild --yes 2>&1)"; then + printf '%s\n' "$output" + return 0 + else + status=$? + fi + if [ "$attempt" -eq 1 ] \ + && printf '%s\n' "$output" | grep -Fq "existing sandbox inference probe exited with status 28" \ + && printf '%s\n' "$output" | grep -Fq "Sandbox is untouched"; then + prior_timeout_output="$output" + info "Retrying named sandbox rebuild once after a fail-closed inference timeout" >&2 + sleep "$retry_delay_seconds" + continue + fi + if [ -n "$prior_timeout_output" ]; then + printf '%s\n%s\n' "$prior_timeout_output" "$output" + else + printf '%s\n' "$output" + fi + return "$status" + done +} + restore_tavily_denial() { - local cleanup_status=0 remove_output post_remove_probe_output - if ! remove_output="$(nemoclaw_cli "$SANDBOX_NAME" policy-remove tavily --yes 2>&1)"; then - fail_test "policy-remove tavily failed after the opt-in proof: $remove_output" - cleanup_status=1 - else - sleep "${NEMOCLAW_E2E_POLICY_SETTLE_SECONDS:-5}" - post_remove_probe_output="$(python_probe "https://api.tavily.com/search" || true)" - if [[ "$post_remove_probe_output" == *"BLOCKED:"* && - "$post_remove_probe_output" != *"REACHED:"* ]]; then - pass "managed Deep Agents Code python returns to the default Tavily denial" + local cleanup_status=0 remove_output reset_output post_remove_probe_output + if [ "$TAVILY_POLICY_APPLIED" -eq 1 ]; then + if ! remove_output="$(nemoclaw_cli "$SANDBOX_NAME" policy-remove tavily --yes 2>&1)"; then + fail_test "policy-remove tavily failed after the opt-in proof: $remove_output" + cleanup_status=1 else - fail_test "policy-remove did not restore the default Tavily denial: $post_remove_probe_output" + TAVILY_POLICY_APPLIED=0 + sleep "${NEMOCLAW_E2E_POLICY_SETTLE_SECONDS:-5}" + post_remove_probe_output="$(python_probe "https://api.tavily.com/search" || true)" + if [[ "$post_remove_probe_output" == *"BLOCKED:"* && + "$post_remove_probe_output" != *"REACHED:"* ]]; then + pass "managed Deep Agents Code python returns to the default Tavily denial" + else + fail_test "policy-remove did not restore the default Tavily denial: $post_remove_probe_output" + cleanup_status=1 + fi + fi + fi + + if [ "$TAVILY_CREDENTIAL_REGISTERED" -eq 1 ]; then + if ! reset_output="$(nemoclaw_cli credentials reset "$TAVILY_PROVIDER_NAME" --yes 2>&1)"; then + fail_test "credentials reset $TAVILY_PROVIDER_NAME failed after the opt-in proof: $reset_output" cleanup_status=1 + else + TAVILY_CREDENTIAL_REGISTERED=0 fi fi @@ -196,6 +245,8 @@ if [ "${NEMOCLAW_E2E_TAVILY_SELF_TEST:-}" = "restore-denial" ]; then OBSERVABILITY_MARKER_FIXTURE="$(mktemp)" printf '%s\n' "1" >"$OBSERVABILITY_MARKER_FIXTURE" trap 'rm -f "$OBSERVABILITY_MARKER_FIXTURE"' EXIT + TAVILY_POLICY_APPLIED=1 + TAVILY_CREDENTIAL_REGISTERED=1 observability_marker_value() { cat "$OBSERVABILITY_MARKER_FIXTURE" } @@ -203,6 +254,10 @@ if [ "${NEMOCLAW_E2E_TAVILY_SELF_TEST:-}" = "restore-denial" ]; then printf '%s' "${NEMOCLAW_E2E_OBSERVABILITY_REGISTRY_FIXTURE:-enabled}" } nemoclaw_cli() { + if [[ "$*" == "credentials reset $TAVILY_PROVIDER_NAME --yes" ]]; then + [[ "${NEMOCLAW_E2E_TAVILY_RESET_FIXTURE:-ok}" == "ok" ]] + return $? + fi [[ "$*" == "$SANDBOX_NAME policy-remove tavily --yes" ]] || return 1 case "${NEMOCLAW_E2E_TAVILY_REMOVE_FIXTURE:-ok}" in ok) ;; @@ -245,18 +300,49 @@ else fail_test "tavily dry-run did not show api.tavily.com: $DRY_RUN_OUTPUT" fi +trap restore_tavily_denial EXIT + +CREDENTIAL_ADD_OUTPUT="$( + TAVILY_API_KEY="$TAVILY_PROBE_CREDENTIAL" \ + nemoclaw_cli credentials add "$TAVILY_PROVIDER_NAME" --type tavily --agent dcode --credential TAVILY_API_KEY 2>&1 +)" || { + fail_test "credentials add $TAVILY_PROVIDER_NAME failed: $CREDENTIAL_ADD_OUTPUT" + printf '%s\n' "${PREFIX}: $PASSED passed, $FAILED failed" + exit 1 +} +TAVILY_CREDENTIAL_REGISTERED=1 +pass "tavily-search credential registers for Deep Agents Code" + APPLY_OUTPUT="$(nemoclaw_cli "$SANDBOX_NAME" policy-add tavily --yes 2>&1)" || { fail_test "policy-add tavily failed: $APPLY_OUTPUT" printf '%s\n' "${PREFIX}: $PASSED passed, $FAILED failed" exit 1 } -trap restore_tavily_denial EXIT +TAVILY_POLICY_APPLIED=1 pass "tavily policy preset applies" +REBUILD_OUTPUT="$(rebuild_named_sandbox 2>&1)" || { + fail_test "rebuild after Tavily credential registration failed: $REBUILD_OUTPUT" + printf '%s\n' "${PREFIX}: $PASSED passed, $FAILED failed" + exit 1 +} +pass "Deep Agents Code sandbox rebuilds with tavily-search attached" + sleep "${NEMOCLAW_E2E_POLICY_SETTLE_SECONDS:-5}" +SANDBOX_ENV_OUTPUT="$(sandbox_exec 'env' || true)" +if printf '%s\n' "$SANDBOX_ENV_OUTPUT" | grep -Fq "$TAVILY_PROBE_CREDENTIAL"; then + fail_test "sandbox environment exposed the raw Tavily credential" +else + pass "sandbox environment does not expose the raw Tavily credential" +fi + PROBE_OUTPUT="$(python_probe "https://api.tavily.com/search")" -if echo "$PROBE_OUTPUT" | grep -q "REACHED:"; then +if printf '%s\n' "$PROBE_OUTPUT" | grep -Fq "$TAVILY_PROBE_CREDENTIAL"; then + fail_test "Tavily probe output exposed the raw Tavily credential" +elif echo "$PROBE_OUTPUT" | grep -q "CREDENTIAL_UNAVAILABLE:"; then + fail_test "managed Deep Agents Code python hit credential_unavailable after rebuild: $PROBE_OUTPUT" +elif echo "$PROBE_OUTPUT" | grep -q "REACHED:"; then pass "managed Deep Agents Code python can reach Tavily after policy-add" elif echo "$PROBE_OUTPUT" | grep -q "BLOCKED:"; then fail_test "managed Deep Agents Code python is still policy-blocked after policy-add: $PROBE_OUTPUT" diff --git a/test/e2e/support/platform-parity-cloud-experimental.test.ts b/test/e2e/support/platform-parity-cloud-experimental.test.ts index 034b6c02d84..6fe0bee1c7f 100644 --- a/test/e2e/support/platform-parity-cloud-experimental.test.ts +++ b/test/e2e/support/platform-parity-cloud-experimental.test.ts @@ -439,27 +439,62 @@ describe("P0-E cloud-experimental parity guardrails", () => { }); it.each([ - [tavilyBlocked, "ok", observabilityEnabled, 0, denialRestored, observabilityPreserved], - ["REACHED:403", "ok", observabilityEnabled, 1, denialNotRestored, observabilityPreserved], - [tavilyBlocked, "fail", observabilityEnabled, 1, policyRemoveFailed, observabilityPreserved], + [tavilyBlocked, "ok", "ok", observabilityEnabled, 0, denialRestored, observabilityPreserved], + ["REACHED:403", "ok", "ok", observabilityEnabled, 1, denialNotRestored, observabilityPreserved], + [ + tavilyBlocked, + "fail", + "ok", + observabilityEnabled, + 1, + policyRemoveFailed, + observabilityPreserved, + ], + [ + tavilyBlocked, + "ok", + "fail", + observabilityEnabled, + 1, + /credentials reset tavily-search failed/, + observabilityPreserved, + ], [ tavilyBlocked, "clear-marker", + "ok", observabilityEnabled, 1, denialRestored, observabilityDriftedAfter, ], - [tavilyBlocked, "ok", "disabled", 1, observabilityDriftedBefore, /registry=disabled, marker=1/], + [ + tavilyBlocked, + "ok", + "ok", + "disabled", + 1, + observabilityDriftedBefore, + /registry=disabled, marker=1/, + ], ])( - "restores the default Tavily denial without observability drift (%s/%s/%s)", - (fixture, removeFixture, registryFixture, status, expected, observabilityExpected) => { + "restores the default Tavily denial without observability drift (%s/%s/%s/%s)", + ( + fixture, + removeFixture, + resetFixture, + registryFixture, + status, + expected, + observabilityExpected, + ) => { const result = spawnSync("bash", [dcodeTavilyCheck], { encoding: "utf8", env: { NEMOCLAW_E2E_OBSERVABILITY_REGISTRY_FIXTURE: registryFixture, NEMOCLAW_E2E_TAVILY_PROBE_FIXTURE: fixture, NEMOCLAW_E2E_TAVILY_REMOVE_FIXTURE: removeFixture, + NEMOCLAW_E2E_TAVILY_RESET_FIXTURE: resetFixture, NEMOCLAW_E2E_TAVILY_SELF_TEST: "restore-denial", PATH: DEFAULT_TEST_PATH, SANDBOX_NAME: "deepagents-sandbox",