diff --git a/docs/changelog/2026-11-18.mdx b/docs/changelog/2026-11-18.mdx index 9f592fed4d6..72afb7d94e3 100644 --- a/docs/changelog/2026-11-18.mdx +++ b/docs/changelog/2026-11-18.mdx @@ -23,6 +23,10 @@ NemoClaw v0.0.145 improves onboarding recovery, Deep Agents state restoration, a - Onboarding refusals for unowned providers preserve the complete shell-quoted removal command. Whitespace-only tool-disclosure environment values use the unset behavior. Related changes: [PR #14157](https://github.com/NVIDIA/NemoClaw/pull/14157) and [PR #14509](https://github.com/NVIDIA/NemoClaw/pull/14509). +- Sandboxes whose Microsoft Teams channel was added before OpenClaw 2026.10.5 load again after an upgrade. + The registry converts that older Teams webhook setting when it reads the saved workload receipt, so `nemoclaw list`, `status`, and the pre-upgrade backup no longer fail on it. + Malformed, noncanonical, unexpected-shape, or digest-mismatched profiles are still rejected. + Related change: [PR #14545](https://github.com/NVIDIA/NemoClaw/pull/14545). ### Hermes Routing and Startup diff --git a/src/lib/messaging/channels/teams/contract.ts b/src/lib/messaging/channels/teams/contract.ts index 90381435c9e..d5848be67b9 100644 --- a/src/lib/messaging/channels/teams/contract.ts +++ b/src/lib/messaging/channels/teams/contract.ts @@ -55,6 +55,34 @@ export function authorizeTeamsOpenClawWebhookField( return [{ path: ["value", "webhook"], value: webhook }]; } +/** + * Convert the stock Teams render written before OpenClaw 2026.10.5, which kept + * the listener port inside `webhook`, to the current shape. Returns null unless + * the entry is exactly that old render: the current render contract must accept + * the converted entry, so identity and field checks stay in one place. + */ +export function upgradeLegacyTeamsOpenClawWebhookRender( + entry: unknown, +): Record | null { + if (!isPlainDataObject(entry)) return null; + const value = ownDataPropertyValue(entry, "value"); + if (!isPlainDataObject(value) || Object.hasOwn(value, "legacyWebhook")) return null; + const webhook = ownDataPropertyValue(value, "webhook"); + if ( + !isPlainDataObject(webhook) || + !hasExactlyOwnDataProperties(webhook, ["path", "port"]) || + ownDataPropertyValue(webhook, "path") !== TEAMS_OPENCLAW_WEBHOOK_RENDER_CONTRACT.webhookPath + ) { + return null; + } + const port = ownDataPropertyValue(webhook, "port"); + const upgraded = { + ...entry, + value: { ...value, webhook: { path: webhook.path }, legacyWebhook: { port } }, + }; + return authorizeTeamsOpenClawWebhookField(upgraded).length === 1 ? upgraded : null; +} + function isPlainDataObject(value: unknown): value is Record { if (value === null || typeof value !== "object" || Array.isArray(value)) return false; const prototype = Object.getPrototypeOf(value); diff --git a/src/lib/onboard/managed-startup-stored-teams-profile.test.ts b/src/lib/onboard/managed-startup-stored-teams-profile.test.ts new file mode 100644 index 00000000000..d5b5e9fee5b --- /dev/null +++ b/src/lib/onboard/managed-startup-stored-teams-profile.test.ts @@ -0,0 +1,257 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { Buffer } from "node:buffer"; +import { createHash } from "node:crypto"; + +import { describe, expect, it } from "vitest"; + +import { managedStartupE2eProfile } from "../../../scripts/checks/generate-managed-startup-profile-fixture.mts"; +import type { SandboxWorkloadReceipt } from "../state/registry/types"; +import { cloneSandboxWorkloadReceipt } from "../state/registry/workload"; +import { + MANAGED_IMAGE_CAPABILITY_CONTRACT_VERSION, + MANAGED_IMAGE_REPOSITORIES, + MANAGED_IMAGE_STARTUP_PROFILE_CONTRACT_VERSION, +} from "./managed-image/contract"; +import { + decodeManagedStartupProfile, + encodeManagedStartupProfile, + MANAGED_STARTUP_PROFILE_MAX_ENCODED_BYTES, + type ManagedStartupProfile, + readStoredManagedStartupProfileMetadata, +} from "./managed-startup/profile"; +import { readStoredWorkloadProfile } from "./managed-startup/stored-profile"; +import { readManagedWorkloadAuthority } from "./workload/authority"; + +const TEAMS_RENDER_IDENTITY = { + channelId: "teams", + renderId: "teams-openclaw-channel", + hookId: "teams-openclaw-channel", + handler: "common.staticOutputs", + kind: "json-fragment", + agent: "openclaw", + target: "openclaw.json", + path: "channels.msteams", +} as const; + +// Keys are sorted because stored profiles are canonical JSON. +const CURRENT_VALUE = { + appId: "teams-app", + enabled: true, + legacyWebhook: { port: 3978 }, + webhook: { path: "/api/messages" }, +}; +// OpenClaw before 2026.10.5 rendered the listener port inside webhook. +const PRE_10_5_VALUE = { + appId: "teams-app", + enabled: true, + webhook: { path: "/api/messages", port: 3978 }, +}; + +function currentProfile(): ManagedStartupProfile { + return { + ...managedStartupE2eProfile("openclaw"), + messaging: { + plan: { + schemaVersion: 1, + agent: "openclaw", + agentRender: [{ ...TEAMS_RENDER_IDENTITY, value: CURRENT_VALUE }], + }, + }, + }; +} + +/** Re-encode the valid current profile with a different Teams render, keeping its key order. */ +function encodeWithRender(value: unknown, identity: Record = {}): string { + const profile = JSON.parse( + Buffer.from(encodeManagedStartupProfile(currentProfile()), "base64url").toString("utf8"), + ) as { messaging: { plan: { agentRender: object[] } } }; + Object.assign(profile.messaging.plan.agentRender[0] as object, identity, { value }); + return Buffer.from(JSON.stringify(profile), "utf8").toString("base64url"); +} + +type ManagedReceipt = Extract; + +function receiptFor(encodedProfile: string): ManagedReceipt { + return { + schemaVersion: 1, + kind: "managed-image", + reference: `${MANAGED_IMAGE_REPOSITORIES.openclaw}@sha256:${"a".repeat(64)}`, + platform: "linux/amd64", + release: "v0.0.130", + sourceRevision: "d".repeat(40), + sourceCohort: "ghrun-100-1", + capabilityContractVersion: MANAGED_IMAGE_CAPABILITY_CONTRACT_VERSION, + startupProfileContractVersion: MANAGED_IMAGE_STARTUP_PROFILE_CONTRACT_VERSION, + encodedProfile, + startupProfileSha256: sha256(encodedProfile), + credentialProxyReplayRequired: false, + shared: true, + }; +} + +function sha256(text: string): string { + return createHash("sha256").update(text, "utf8").digest("hex"); +} + +describe("stored Teams managed startup profiles (#14540)", () => { + it("converts a profile written before the webhook port moved to the current form", () => { + const encoded = encodeWithRender(PRE_10_5_VALUE); + const current = encodeManagedStartupProfile(currentProfile()); + expect(readStoredWorkloadProfile(encoded)).toMatchObject({ + encodedProfile: current, + agent: "openclaw", + }); + // The validators that managed startup runs stay strict. + expect(() => decodeManagedStartupProfile(encoded)).toThrow(/credential-shaped field name/); + expect(() => readStoredManagedStartupProfileMetadata(encoded)).toThrow( + /credential-shaped field name/, + ); + }); + + it("loads the old receipt as a current-form receipt with a matching digest", () => { + const encoded = encodeWithRender(PRE_10_5_VALUE); + const current = encodeManagedStartupProfile(currentProfile()); + const loaded = cloneSandboxWorkloadReceipt(receiptFor(encoded)); + expect(loaded).toMatchObject({ + kind: "managed-image", + encodedProfile: current, + startupProfileSha256: sha256(current), + }); + // Saving and loading again keeps the converted form. + expect(cloneSandboxWorkloadReceipt(loaded)).toEqual(loaded); + }); + + it("rejects the old receipt when its stored digest does not match the stored profile", () => { + const encoded = encodeWithRender(PRE_10_5_VALUE); + const convertedDigest = sha256(encodeManagedStartupProfile(currentProfile())); + const withDigest = (startupProfileSha256: string) => ({ + ...receiptFor(encoded), + startupProfileSha256, + }); + expect(cloneSandboxWorkloadReceipt(withDigest(convertedDigest))).toBeUndefined(); + expect(cloneSandboxWorkloadReceipt(withDigest(sha256("another profile")))).toBeUndefined(); + }); + + it("lets managed workload authority read the old receipt for rebuild, clone and snapshot", () => { + const encoded = encodeWithRender(PRE_10_5_VALUE); + const current = encodeManagedStartupProfile(currentProfile()); + const receipt = receiptFor(encoded); + const authority = readManagedWorkloadAuthority({ + agent: "openclaw", + fromDockerfile: null, + imageTag: receipt.reference, + workload: receipt, + }); + expect(authority?.receipt).toMatchObject({ + encodedProfile: current, + startupProfileSha256: sha256(current), + }); + expect(authority?.profile).toEqual(decodeManagedStartupProfile(current)); + expect(() => decodeManagedStartupProfile(encoded)).toThrow(/credential-shaped field name/); + }); + + it("still reads the current render unchanged", () => { + const encoded = encodeManagedStartupProfile(currentProfile()); + expect(decodeManagedStartupProfile(encoded).agent).toBe("openclaw"); + expect(readStoredWorkloadProfile(encoded)).toEqual({ + encodedProfile: encoded, + ...readStoredManagedStartupProfileMetadata(encoded), + }); + }); + + it.each([ + ["an extra webhook field", { webhook: { path: "/api/messages", port: 3978, secret: "x" } }, {}], + ["a different webhook path", { webhook: { path: "/hook", port: 3978 } }, {}], + ["an out-of-range port", { webhook: { path: "/api/messages", port: 70_000 } }, {}], + ["a string port", { webhook: { path: "/api/messages", port: "3978" } }, {}], + [ + "both webhook shapes at once", + { webhook: { path: "/api/messages", port: 3978 }, legacyWebhook: { port: 3978 } }, + {}, + ], + ["another channel's render", {}, { channelId: "slack" }], + ["another render id", {}, { renderId: "teams-other" }], + ] as const)("rejects a stored profile with %s", (_label, overrides, identity) => { + const encoded = encodeWithRender({ ...PRE_10_5_VALUE, ...overrides }, identity); + expect(() => readStoredWorkloadProfile(encoded)).toThrow(/credential-shaped field name/); + expect(cloneSandboxWorkloadReceipt(receiptFor(encoded))).toBeUndefined(); + }); + + describe("noncanonical encodings of the old profile", () => { + const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + + /** The old profile's canonical JSON text, with an app id long enough to leave spare base64 bits. */ + function legacyTextWith(appIdSuffix: string): string { + return Buffer.from( + encodeWithRender({ ...PRE_10_5_VALUE, appId: `teams-app${appIdSuffix}` }), + "base64url", + ).toString("utf8"); + } + + function legacyText(): string { + const plain = legacyTextWith(""); + // One extra character moves a multiple-of-three byte length off the boundary. + return legacyTextWith("x".repeat(Number(Buffer.byteLength(plain, "utf8") % 3 === 0))); + } + + const encode = (bytes: Buffer): string => bytes.toString("base64url"); + + function variants(): Array<[string, string]> { + const text = legacyText(); + const canonical = encode(Buffer.from(text, "utf8")); + const parsed = JSON.parse(text) as Record; + const last = canonical[canonical.length - 1]; + const spareBitsAlias = canonical.slice(0, -1) + ALPHABET[ALPHABET.indexOf(last) ^ 1]; + return [ + ["padding", canonical + "=".repeat((4 - (canonical.length % 4)) % 4 || 1)], + ["the standard alphabet", canonical.slice(0, 8) + "+/" + canonical.slice(10)], + [ + "a remainder of one character", + canonical + "A".repeat((((1 - canonical.length) % 4) + 4) % 4 || 4), + ], + ["spare trailing bits", spareBitsAlias], + ["whitespace in the JSON", encode(Buffer.from(JSON.stringify(parsed, null, 1), "utf8"))], + [ + "unsorted keys", + encode(Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(parsed).reverse())))), + ], + [ + "a duplicate key", + encode(Buffer.from(text.replace('"agent":', '"agent":"hermes","agent":'), "utf8")), + ], + [ + "invalid UTF-8 inside a string", + encode( + Buffer.concat([ + Buffer.from(text.slice(0, text.indexOf("teams-app")), "utf8"), + Buffer.from([0xff]), + Buffer.from(text.slice(text.indexOf("teams-app")), "utf8"), + ]), + ), + ], + ]; + } + + it("builds a canonical legacy profile that converts, so each variant below is the only change", () => { + const text = legacyText(); + expect(Buffer.byteLength(text, "utf8") % 3).not.toBe(0); + expect(readStoredWorkloadProfile(encode(Buffer.from(text, "utf8"))).agent).toBe("openclaw"); + }); + + it.each(variants())( + "rejects %s in the profile reader and in the receipt loader", + (_label, encoded) => { + expect(() => readStoredWorkloadProfile(encoded)).toThrow(); + expect(cloneSandboxWorkloadReceipt(receiptFor(encoded))).toBeUndefined(); + }, + ); + + it("rejects an encoded profile past the size limit", () => { + const encoded = "A".repeat(MANAGED_STARTUP_PROFILE_MAX_ENCODED_BYTES + 4); + expect(() => readStoredWorkloadProfile(encoded)).toThrow(); + expect(cloneSandboxWorkloadReceipt(receiptFor(encoded))).toBeUndefined(); + }); + }); +}); diff --git a/src/lib/onboard/managed-startup/profile.ts b/src/lib/onboard/managed-startup/profile.ts index 43fe46c43a6..acf34ab29a3 100644 --- a/src/lib/onboard/managed-startup/profile.ts +++ b/src/lib/onboard/managed-startup/profile.ts @@ -2387,7 +2387,8 @@ function migrateDecodedManagedStartupProfile(value: unknown): ManagedStartupProf }; } -function canonicalizeJson(value: unknown): unknown { +/** Sorted-key JSON normal form shared by the profile transport and legacy receipt readers. */ +export function canonicalizeJson(value: unknown): unknown { if (Array.isArray(value)) return mapArrayByIndex(value, (item) => canonicalizeJson(item)); if (!isPlainObject(value)) return value; const result: Record = {}; diff --git a/src/lib/onboard/managed-startup/stored-profile.ts b/src/lib/onboard/managed-startup/stored-profile.ts new file mode 100644 index 00000000000..c12eab9b705 --- /dev/null +++ b/src/lib/onboard/managed-startup/stored-profile.ts @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { Buffer } from "node:buffer"; + +import { upgradeLegacyTeamsOpenClawWebhookRender } from "../../messaging/channels/teams/contract"; +import { canonicalizeJson, readStoredManagedStartupProfileMetadata } from "./profile"; + +export interface StoredManagedStartupProfile { + /** The profile as stored, or its current-form equivalent when the stored form was old. */ + readonly encodedProfile: string; + readonly agent: ReturnType["agent"]; + readonly corporateCaBundleSha256: string | null; +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function encodeCanonical(value: unknown): string { + return Buffer.from(JSON.stringify(canonicalizeJson(value)), "utf8").toString("base64url"); +} + +/** + * Re-encode a stored profile with its pre-2026.10.5 Teams render converted, or return null. + * + * The stored input must already be in canonical form: re-encoding the parsed + * value with the profile reader's own canonicalization has to reproduce it + * exactly, which rules out padding, the standard alphabet, spare bits, + * whitespace, unsorted or duplicate keys and invalid UTF-8. Only the one known + * render difference is converted, and the profile reader then validates the + * result in full, size limits included. + */ +function upgradeStoredTeamsRender(encoded: string): string | null { + let parsed: unknown; + try { + parsed = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")); + } catch { + return null; + } + if (encodeCanonical(parsed) !== encoded) return null; + if (!isRecord(parsed) || !isRecord(parsed.messaging) || !isRecord(parsed.messaging.plan)) { + return null; + } + const agentRender = parsed.messaging.plan.agentRender; + if (!Array.isArray(agentRender)) return null; + let upgraded = false; + parsed.messaging.plan.agentRender = agentRender.map((entry: unknown) => { + const converted = upgradeLegacyTeamsOpenClawWebhookRender(entry); + if (converted === null) return entry; + upgraded = true; + return converted; + }); + return upgraded ? encodeCanonical(parsed) : null; +} + +/** + * Read a stored workload receipt's startup profile, including a Teams profile + * recorded before OpenClaw 2026.10.5. + * + * That profile is converted to the current form before it is validated, and + * the converted encoding is returned so the receipt can carry it. The profile + * validator that managed startup runs stays strict and still rejects the old + * shape. Every other failure keeps its original error. + */ +export function readStoredWorkloadProfile(encoded: string): StoredManagedStartupProfile { + try { + return { encodedProfile: encoded, ...readStoredManagedStartupProfileMetadata(encoded) }; + } catch (error) { + const upgraded = upgradeStoredTeamsRender(encoded); + if (upgraded === null) throw error; + try { + return { encodedProfile: upgraded, ...readStoredManagedStartupProfileMetadata(upgraded) }; + } catch { + throw error; + } + } +} diff --git a/src/lib/state/registry/workload.ts b/src/lib/state/registry/workload.ts index 0ac601eb79e..98197be664e 100644 --- a/src/lib/state/registry/workload.ts +++ b/src/lib/state/registry/workload.ts @@ -6,10 +6,10 @@ import { createHash } from "node:crypto"; import { MANAGED_IMAGE_REPOSITORIES } from "../../onboard/managed-image/contract"; import { - readStoredManagedStartupProfileMetadata, MANAGED_STARTUP_PROFILE_MAX_BYTES, MANAGED_STARTUP_PROFILE_MAX_ENCODED_BYTES, } from "../../onboard/managed-startup/profile"; +import { readStoredWorkloadProfile } from "../../onboard/managed-startup/stored-profile"; import { parseNativeArtifactWorkloadReceiptV1 } from "../../onboard/workload/native-artifact"; import type { SandboxWorkloadReceipt } from "./types"; @@ -141,9 +141,9 @@ export function cloneSandboxWorkloadReceipt( ) { return undefined; } - let profile: ReturnType; + let profile: ReturnType; try { - profile = readStoredManagedStartupProfileMetadata(value.encodedProfile); + profile = readStoredWorkloadProfile(value.encodedProfile); } catch { return undefined; } @@ -173,8 +173,11 @@ export function cloneSandboxWorkloadReceipt( sourceCohort: value.sourceCohort, capabilityContractVersion: value.capabilityContractVersion, startupProfileContractVersion: value.startupProfileContractVersion, - encodedProfile: value.encodedProfile, - startupProfileSha256: value.startupProfileSha256, + encodedProfile: profile.encodedProfile, + startupProfileSha256: + profile.encodedProfile === value.encodedProfile + ? value.startupProfileSha256 + : createHash("sha256").update(profile.encodedProfile, "utf8").digest("hex"), credentialProxyReplayRequired: value.credentialProxyReplayRequired, ...(value.corporateCaB64 === undefined ? {} : { corporateCaB64: value.corporateCaB64 }), shared: true, diff --git a/test/state/registry.test.ts b/test/state/registry.test.ts index 99b1a653d71..9262f83ddea 100644 --- a/test/state/registry.test.ts +++ b/test/state/registry.test.ts @@ -1,12 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { createHash } from "node:crypto"; import fs from "node:fs"; import { createRequire } from "node:module"; import os from "node:os"; import path from "node:path"; import { beforeEach, describe, expect, it } from "vitest"; +import { managedStartupE2eProfile } from "../../scripts/checks/generate-managed-startup-profile-fixture.mts"; +import { encodeManagedStartupProfile } from "../../src/lib/onboard/managed-startup/profile"; import { makeMessagingPlan } from "../helpers/messaging-plan-fixtures"; // Use a temp dir so tests don't touch real ~/.nemoclaw. @@ -907,6 +910,79 @@ describe("registry", () => { expect(() => registry.getSandbox("alpha")).toThrow(/invalid workload receipt/); }); + it("loads a Teams receipt from before OpenClaw 2026.10.5 and saves it in the current form (#14540)", () => { + const teamsValue = { appId: "teams-app", enabled: true }; + const current = encodeManagedStartupProfile({ + ...managedStartupE2eProfile("openclaw"), + messaging: { + plan: { + schemaVersion: 1, + agent: "openclaw", + agentRender: [ + { + channelId: "teams", + renderId: "teams-openclaw-channel", + hookId: "teams-openclaw-channel", + handler: "common.staticOutputs", + kind: "json-fragment", + agent: "openclaw", + target: "openclaw.json", + path: "channels.msteams", + value: { + ...teamsValue, + legacyWebhook: { port: 3978 }, + webhook: { path: "/api/messages" }, + }, + }, + ], + }, + }, + }); + const old = JSON.parse(Buffer.from(current, "base64url").toString("utf8")); + old.messaging.plan.agentRender[0].value = { + ...teamsValue, + webhook: { path: "/api/messages", port: 3978 }, + }; + const encoded = Buffer.from(JSON.stringify(old), "utf8").toString("base64url"); + const sha256 = (text: string) => createHash("sha256").update(text, "utf8").digest("hex"); + fs.mkdirSync(path.dirname(regFile), { recursive: true }); + fs.writeFileSync( + regFile, + JSON.stringify({ + defaultSandbox: "alpha", + sandboxes: { + alpha: { + name: "alpha", + workload: { + schemaVersion: 1, + kind: "managed-image", + reference: `ghcr.io/nvidia/nemoclaw/openclaw-sandbox@sha256:${"1".repeat(64)}`, + release: "v0.0.130", + sourceRevision: "2".repeat(40), + sourceCohort: "ghrun-1-1", + capabilityContractVersion: 1, + startupProfileContractVersion: 1, + encodedProfile: encoded, + startupProfileSha256: sha256(encoded), + credentialProxyReplayRequired: false, + shared: true, + }, + }, + }, + }), + ); + + expect(registry.getSandbox("alpha").workload).toMatchObject({ + encodedProfile: current, + startupProfileSha256: sha256(current), + }); + registry.updateSandbox("alpha", { model: "new-model" }); + expect(JSON.parse(fs.readFileSync(regFile, "utf-8")).sandboxes.alpha.workload).toMatchObject({ + encodedProfile: current, + startupProfileSha256: sha256(current), + }); + }); + it("does not serialize an invalid workload receipt", () => { expect(() => registry.save({