diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.yml index 8421b2ee5e..ac53e4051c 100644 --- a/.github/workflows/python-tests.yml +++ b/.github/workflows/python-tests.yml @@ -215,6 +215,18 @@ jobs: run: | python -m pip install --disable-pip-version-check -e ".[test]" node apps/presentation/dashboard/smoke/team-task-revalidation-smoke.mjs + - name: Qualify packaged remote task inspection and recovery + if: matrix.shard == 2 + working-directory: apps/presentation/dashboard + run: npm run smoke:remote-authority-inspection + - name: Preserve synthetic remote task inspection views + if: always() && matrix.shard == 2 + uses: actions/upload-artifact@v7 + with: + name: remote-authority-inspection-${{ github.sha }} + path: output/playwright/remote-authority-inspection/ + if-no-files-found: ignore + retention-days: 7 - name: Preserve synthetic original-task recovery views if: always() && matrix.shard == 2 uses: actions/upload-artifact@v7 diff --git a/apps/presentation/dashboard/package.json b/apps/presentation/dashboard/package.json index 9809927263..5a34259f32 100644 --- a/apps/presentation/dashboard/package.json +++ b/apps/presentation/dashboard/package.json @@ -75,6 +75,7 @@ "smoke:delivery-review": "tsc --ignoreConfig --target ES2022 --module NodeNext --moduleResolution NodeNext --skipLibCheck --strict --rootDir src --outDir node_modules/.cache/delivery-review src/data/delivery-review.ts src/data/goal-work-map.ts src/data/goal-acceptance-observation.ts src/features/personal-workspace/delivery-review-copy.ts && node smoke/delivery-review-smoke.mjs", "smoke:team-artifact-comparison": "tsc --noEmit && vite build --ssr smoke/team-artifact-comparison-smoke.mjs --outDir node_modules/.cache/team-comparison --emptyOutDir && node node_modules/.cache/team-comparison/team-artifact-comparison-smoke.js", "smoke:settings-target": "vite build --ssr smoke/settings-target-smoke.mjs --outDir node_modules/.cache/settings-target --emptyOutDir && node node_modules/.cache/settings-target/settings-target-smoke.js", + "smoke:remote-authority-inspection": "LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/remote-authority-inspection-browser-smoke.mjs", "smoke:team-report": "node --no-warnings --experimental-strip-types --test src/features/personal-workspace/markdown-blocks.test.mjs && vite build --ssr smoke/team-report-smoke.mjs --outDir node_modules/.cache/team-report --emptyOutDir && node node_modules/.cache/team-report/team-report-smoke.js", "build:chat:vite": "tsc --noEmit && vite build --config vite.chat.config.ts", "smoke:chat-upgrade": "LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node ../../../examples/chat-bundle-upgrade-browser-smoke.mjs", diff --git a/apps/presentation/dashboard/smoke/remote-authority-inspection-browser-smoke.mjs b/apps/presentation/dashboard/smoke/remote-authority-inspection-browser-smoke.mjs new file mode 100644 index 0000000000..1dc84d52e6 --- /dev/null +++ b/apps/presentation/dashboard/smoke/remote-authority-inspection-browser-smoke.mjs @@ -0,0 +1,127 @@ +// Packaged App -> real Chat route -> typed inspection -> synthetic HTTPS peer. +import assert from "node:assert/strict"; +import {spawn} from "node:child_process"; +import {createInterface} from "node:readline"; +import {once} from "node:events"; +import {mkdtemp, mkdir, rm} from "node:fs/promises"; +import {tmpdir} from "node:os"; +import {resolve} from "node:path"; +import {fileURLToPath} from "node:url"; +import {testPythonCommand} from "../../../../scripts/test-python.mjs"; +import {launchBrowser, loadPlaywright} from "../../../../examples/dashboard-browser-smoke-support.mjs"; +import {openWorkspacePage} from "../../../../examples/personal-workspace-browser/scenario-context.mjs"; + +const root = fileURLToPath(new URL("../../../../", import.meta.url)); +const temporary = await mkdtemp(resolve(tmpdir(), "loopx-remote-inspection-")); +const output = resolve(root, "output/playwright/remote-authority-inspection"); +const baseline = process.env.LOOPX_REMOTE_INSPECT_BASELINE_ASSETS; +const arguments_ = ["fixture", "--root", temporary, ...(baseline ? ["--assets", baseline] : [])]; +const python = testPythonCommand(` +import runpy +sys.argv = ${JSON.stringify(arguments_)} +runpy.run_module("tests.control_plane.remote_authority_browser_fixture", run_name="__main__") +`); +const server = spawn(python.command, python.args, {cwd: root, + env: {...process.env, LOOPX_USAGE_PING: "0"}, stdio: ["pipe", "pipe", "pipe"]}); +const replies = [], waiting = []; +let diagnostics = "", browser, session, release; +const lines = createInterface({input: server.stdout}); +lines.on("line", line => { + const reply = JSON.parse(line); + if (waiting.length) waiting.shift().resolve(reply); else replies.push(reply); +}); +server.stderr.on("data", chunk => {diagnostics = (diagnostics + chunk).slice(-4000);}); +server.on("exit", code => {for (const waiter of waiting.splice(0)) waiter.reject(new Error(`Fixture exited ${code}: ${diagnostics}`));}); +function reply() { + return replies.length ? Promise.resolve(replies.shift()) : new Promise((resolveReply, reject) => { + const timer = setTimeout(() => reject(new Error(`Fixture response timed out: ${diagnostics}`)), 20000); + waiting.push({resolve: value => {clearTimeout(timer); resolveReply(value);}, reject: error => {clearTimeout(timer); reject(error);}}); + }); +} +async function control(value = {}) {server.stdin.write(JSON.stringify(value) + "\n"); return await reply();} +try { + const {origin} = await reply(); + await mkdir(output, {recursive: true}); + browser = await launchBrowser(loadPlaywright().chromium); + let hold = false, fail = false, requestHeld; + session = await openWorkspacePage(browser, origin + "/chat/?statusUrl=/status.json", { + apiOptions: {fixturePort: Number(new URL(origin).port)}, + viewport: {width: 1440, height: 1000}, gotoWaitUntil: "domcontentloaded", + beforeGoto: async (_api, page) => { + await page.addInitScript(() => localStorage.setItem("loopx-pw-locale", "en")); + await page.route("**/api/chat/goal-configuration/remote-authority/inspect", async route => { + if (hold) await new Promise(resolveRequest => {release = resolveRequest; requestHeld();}); + if (fail) await route.abort(); else await route.continue(); + }); + }, + }); + const {page} = session; + page.setDefaultTimeout(15000); + await page.goto(origin + "/chat/?statusUrl=/status.json&settings_scope=goal&settings_goal=product-release&settings_tab=capabilities", + {waitUntil: "domcontentloaded"}); + await page.locator(".personal-capability-settings").waitFor(); + assert.equal((await control()).requests, 0, "discovery never contacts the remote service"); + if (baseline) { + assert.equal(await page.getByRole("region", {name: "Remote task connection"}).count(), 0); + await page.screenshot({path: resolve(output, "before-desktop.png")}); + await page.setViewportSize({width: 390, height: 844}); + await page.screenshot({path: resolve(output, "before-narrow.png")}); + } else { + const panel = page.getByRole("region", {name: "Remote task connection"}); + await panel.getByRole("button", {name: "Check connection", exact: true}).click(); + await panel.getByText("Read verified", {exact: true}).waitFor(); + await page.screenshot({path: resolve(output, "success-desktop.png")}); + assert.equal((await control({mode: "denied"})).requests, 1); + await panel.getByRole("button", {name: "Check again", exact: true}).click(); + await panel.getByText("Read unverified", {exact: true}).waitFor(); + await page.screenshot({path: resolve(output, "denied-desktop.png")}); + assert.equal((await control({mode: "found"})).requests, 2); + await panel.getByRole("button", {name: "Check again", exact: true}).click(); + await panel.getByText("Read verified", {exact: true}).waitFor(); + assert.equal((await control()).requests, 3); + + hold = true; + const held = new Promise(resolveHeld => {requestHeld = resolveHeld;}); + const delayedResponse = page.waitForResponse(response => response.url().endsWith("/remote-authority/inspect")); + await panel.getByRole("button", {name: "Check again", exact: true}).click(); + await held; + await panel.getByRole("button", {name: "Checking…", exact: true}).waitFor(); + assert.equal(await panel.getByRole("button").isDisabled(), true); + const target = page.locator(".personal-settings-goal-choice select"); + const other = await target.locator("option").evaluateAll(options => options.find(option => option.value && option.value !== "product-release").value); + await target.selectOption(other); + hold = false; + release(); + await (await delayedResponse).finished(); + assert.equal(await panel.getByText("Read verified", {exact: true}).count(), 0, "stale results cannot cross Goals"); + await target.selectOption("product-release"); + fail = true; + await panel.getByRole("button", {name: "Check connection", exact: true}).click(); + await panel.getByRole("alert").waitFor(); + fail = false; + await control({mode: "denied"}); + await panel.getByRole("button", {name: "Check again", exact: true}).click(); + await panel.getByText("Read unverified", {exact: true}).waitFor(); + await page.setViewportSize({width: 390, height: 844}); + await page.screenshot({path: resolve(output, "denied-narrow.png")}); + assert.ok(await panel.evaluate(element => element.getBoundingClientRect().right <= innerWidth + 1), "narrow view has no horizontal overflow"); + const editor = page.locator(".personal-capability-detail"); + await editor.getByRole("heading", {name: "Periodic reports", exact: true}).scrollIntoViewIfNeeded(); + assert.ok(await editor.evaluate(element => element.clientHeight >= 200), "inspection preserves a usable settings editor on narrow screens"); + await editor.getByRole("combobox").first().click(); + await page.keyboard.press("Escape"); + await page.screenshot({path: resolve(output, "settings-narrow.png")}); + assert.equal((await control()).unchanged, true, "inspection never mutates local authority"); + assert.equal(session.errors.filter(error => !error.includes("net::ERR_FAILED")).length, 0, session.errors.join("\n")); + } + console.log(baseline ? "Captured baseline packaged Goal settings" : "Packaged inspection, denial/recovery, scope fencing, network failure and state parity passed"); +} finally { + release?.(); + await session?.close(); + await browser?.close(); + const stopped = server.exitCode === null ? once(server, "exit") : Promise.resolve(); + server.stdin.end(); + server.kill("SIGTERM"); + await stopped; + await rm(temporary, {recursive: true, force: true}); +} diff --git a/apps/presentation/dashboard/src/data/remote-authority.ts b/apps/presentation/dashboard/src/data/remote-authority.ts new file mode 100644 index 0000000000..43d4a35cf3 --- /dev/null +++ b/apps/presentation/dashboard/src/data/remote-authority.ts @@ -0,0 +1,22 @@ +import {z} from "zod"; +import {requestJson} from "./chat"; + +// Validate the existing owner's safe projection, never interpret a wire reply +// or accept execution authority in the browser. +const inspectionSchema = z.object({ + schema_version: z.literal("loopx_remote_authority_inspection_v1"), + ok: z.boolean(), status: z.enum(["verified", "unavailable"]), + stage: z.string(), reason_code: z.string(), message: z.string(), recommended_action: z.string(), + execution_admitted: z.literal(false), http_status: z.number().int().optional(), +}).strict().refine(value => value.ok === (value.status === "verified")); +export type RemoteAuthorityInspection = z.infer; + +export async function inspectGoalRemoteAuthority(goalId: string): Promise { + const response = z.object({goal_id: z.string(), inspection: inspectionSchema}).strict().parse( + await requestJson("/api/chat/goal-configuration/remote-authority/inspect", { + method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({goal_id: goalId}), + }), + ); + if (response.goal_id !== goalId) throw new Error("Inspection returned a different Goal"); + return response.inspection; +} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace.css b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace.css index f87520f1fb..0cd4d0c1bf 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace.css +++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace.css @@ -659,7 +659,21 @@ button.personal-execution-chip:focus-visible { outline: 2px solid #0070f3; outli .personal-settings-tabs button > span { display: grid; gap: 2px; min-width: 0; } .personal-settings-tabs strong { font-size: var(--text-body); line-height: var(--leading-body); } .personal-settings-body { min-width: 0; min-height: 0; overflow: auto; overscroll-behavior: contain; scrollbar-gutter: stable; padding: 0 clamp(24px, 5vw, 72px) 30px; } -.personal-settings-body:has(> .personal-capability-settings) { display: grid; grid-template-rows: auto minmax(0, 1fr); overflow: hidden; } +.personal-settings-body:has(> .personal-capability-settings), .personal-settings-body:has(> .personal-goal-capability-content) { display: grid; grid-template-rows: auto minmax(0, 1fr); overflow: hidden; } +.personal-goal-capability-content { display: grid; grid-template-rows: auto minmax(420px, 1fr); min-width: 0; min-height: 0; overflow: auto; overscroll-behavior: contain; } +.personal-remote-authority { padding: 16px 20px; border-bottom: 1px solid var(--pw-line); } +.personal-remote-authority-heading { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; } +.personal-remote-authority h3 { margin: 0; font-size: var(--text-body); line-height: var(--leading-body); } +.personal-remote-authority p { margin: 5px 0; color: var(--pw-muted); font-size: var(--text-body); line-height: var(--leading-body); } +.personal-remote-authority button { display: inline-flex; align-items: center; gap: 7px; min-height: 40px; padding: 8px 12px; border: 1px solid var(--pw-line-strong); border-radius: 7px; background: var(--pw-card); color: var(--pw-text); font: inherit; cursor: pointer; } +.personal-remote-authority button:disabled { opacity: .6; cursor: wait; } +.personal-remote-authority-result { margin-top: 14px; } +.personal-remote-authority-result strong { display: flex; align-items: center; gap: 8px; font-size: var(--text-body); } +.personal-remote-authority-result[data-verified="true"] strong { color: var(--pw-green); } +.personal-remote-authority-result[data-verified="false"] strong { color: var(--pw-caution); } +.personal-remote-authority details { margin-top: 8px; color: var(--pw-muted); font-size: var(--text-caption); overflow-wrap: anywhere; } +.personal-remote-authority details summary { cursor: pointer; } +.personal-remote-authority .personal-machine-error { margin: 12px 0 0; } .personal-settings-body > .personal-settings-header { min-width: 0; } .personal-settings-page *, .personal-settings-page *::before, .personal-settings-page *::after { box-sizing: border-box; } .personal-appearance-settings { max-width: 680px; } diff --git a/apps/presentation/dashboard/src/features/personal-workspace/remote-authority-inspection.tsx b/apps/presentation/dashboard/src/features/personal-workspace/remote-authority-inspection.tsx new file mode 100644 index 0000000000..9b65fea442 --- /dev/null +++ b/apps/presentation/dashboard/src/features/personal-workspace/remote-authority-inspection.tsx @@ -0,0 +1,88 @@ +import {useLayoutEffect, useRef, useState} from "react"; +import {CheckCircle2, LoaderCircle, RefreshCw, AlertTriangle} from "lucide-react"; +import {inspectGoalRemoteAuthority, type RemoteAuthorityInspection} from "../../data/remote-authority"; +import {useWorkspaceI18n} from "./i18n"; + +// Presentation copy only; the existing owner decides the diagnostic and authority. +const chineseDiagnostics: Record = { + goal_unregistered: "当前 Goal 未注册,请重新选择已有 Goal。", + actor_unregistered: "远程配置中的成员未在此 Goal 注册,请检查成员配置。", + disabled: "此 Goal 尚未启用远程连接,本地任务不受影响。", + binding_incomplete: "此 Goal 的远程连接配置不完整,请补齐已有配置后重试。", + binding_invalid: "此 Goal 的远程连接配置无效,请检查配置格式。", + actor_mismatch: "当前成员与远程配置不一致,请检查成员配置。", + endpoint_invalid: "远程服务地址无效,请使用不含凭据或路径的 HTTPS 地址。", + credential_required: "缺少服务凭据,请在运行 LoopX 的环境中配置后重试。", + credential_invalid: "服务凭据格式无效,请检查运行 LoopX 的环境配置。", + ca_invalid: "无法读取证书文件,请检查证书文件路径和权限。", + dns: "无法解析远程服务地址,请检查地址和网络连接。", + connection_refused: "远程服务拒绝连接,请检查服务是否运行及端口是否正确。", + tls: "安全连接未通过验证,请检查服务证书、域名和证书有效期。", + connection: "连接中断,请检查网络和服务状态后重试。", + timeout: "检查超时,请检查网络和服务响应后重试。", + http: "远程服务返回 HTTP 错误,请检查服务和代理配置。", + response_invalid: "服务响应无法验证,请检查客户端与服务端的兼容性。", + response_too_large: "服务响应超出读取限制,请检查服务地址是否正确。", + unauthenticated: "服务拒绝了当前凭据,请检查凭据是否有效。", + scope_denied: "当前凭据无权读取此 Goal 的任务,请联系服务管理员核对权限。", + rejected: "服务拒绝读取,请联系服务管理员核对配置和访问策略。", + todo_missing: "未找到配置中的检查任务,请核对任务和访问范围。", + read_unverified: "任务读取未通过验证,请检查服务和连接配置。", + read_verified: "已验证配置中的任务读取。此检查不会启动任务。", + registry_unreadable: "无法读取本地 Goal 注册信息,请检查文件格式和访问权限。", + node_unavailable: "本地运行环境不可用,请运行 LoopX 安装诊断并修复。", + probe_unavailable: "本地检查程序未返回有效结果,请运行 LoopX 安装诊断后重试。", +}; + +export function GoalRemoteAuthorityInspection({goalId}: Readonly<{goalId: string}>) { + const {locale} = useWorkspaceI18n(); + const zh = locale === "zh-CN"; + const [result, setResult] = useState(null); + const [failed, setFailed] = useState(false); + const [busy, setBusy] = useState(false); + const generation = useRef(0); + useLayoutEffect(() => { + generation.current++; + setResult(null); setFailed(false); setBusy(false); + return () => {generation.current++;}; + }, [goalId]); + + async function inspect() { + const current = ++generation.current; + setBusy(true); setFailed(false); setResult(null); + try { + const value = await inspectGoalRemoteAuthority(goalId); + if (current === generation.current) setResult(value); + } catch { + if (current === generation.current) setFailed(true); + } finally { + if (current === generation.current) setBusy(false); + } + } + + const title = zh ? "远程任务连接" : "Remote task connection"; + const translated = result && zh ? chineseDiagnostics[result.reason_code.replace(/^remote_authority_/, "")] : null; + return
+
+

{title}

{zh ? "读取此 Goal 的已配置任务,不会启动工作。" : "Read this Goal’s configured task without starting work."}

+ +
+
+ {failed ?

{zh ? "未能完成检查,请重试。" : "The check could not finish. Please try again."}

: null} + {result ?
+ {result.ok ? : } + {result.ok ? (zh ? "读取已验证" : "Read verified") : (zh ? "读取未验证" : "Read unverified")} +

{translated || result.message}

+ {!result.ok && !translated ?

{result.recommended_action}

: null} +
{zh ? "诊断详情" : "Diagnostic details"} + {result.reason_code} + {result.http_status !== undefined ?

HTTP {result.http_status}

: null} +

{zh ? "检查结果不会授予任务执行权限。" : "This result does not admit task execution."}

+
+
: null} +
+
; +} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/workspace-settings-page.tsx b/apps/presentation/dashboard/src/features/personal-workspace/workspace-settings-page.tsx index 04ca0f06e5..8b5a5c2b3b 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/workspace-settings-page.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/workspace-settings-page.tsx @@ -10,6 +10,7 @@ import type { WorkspaceLocale } from "./i18n"; import { useWorkspaceI18n } from "./i18n"; import { LarkSettingsPage } from "./lark-settings-page"; import { GoalCapabilitySettings } from "./goal-capability-settings"; +import { GoalRemoteAuthorityInspection } from "./remote-authority-inspection"; import { GoalAmendmentSettings } from "./goal-amendment-settings"; import { GoalDirectionSettings } from "./goal-direction-settings"; import { GoalOwnershipSettings } from "./goal-ownership-settings"; @@ -264,7 +265,8 @@ export function WorkspaceSettingsPage({ /> : null} {tab === "conversation" ? : null} {tab === "capabilities" && scope === "machine" ? : null} - {tab === "capabilities" && editableGoal ? ( + {tab === "capabilities" && editableGoal ?
+ row.goalId === editableGoal.goalId)} onChanged={onChanged} /> - ) : null} +
: null} {tab === "ownership" && editableGoal ?
{canonicalSettingsReady ? : null} { diff --git a/docs/reference/README.md b/docs/reference/README.md index a15ef0a037..53767d06ea 100644 --- a/docs/reference/README.md +++ b/docs/reference/README.md @@ -15,6 +15,8 @@ Current groups: Apache-2.0 outbound HTTPS task-command wire contract and TLS client in `loopx` (server-side PostgreSQL authority and multi-tenant coordination live in `loopx-project/loopx-cloud`). +- [Remote authority inspection](remote-authority-inspection.md): installed read-only + CLI checks, safe diagnostics, and execution-admission boundaries. - [Usage ping](usage-ping.md): default-on basic usage statistics, disclosure/opt-out and exact payload, opt-out switches, and the published active-installation counts. diff --git a/docs/reference/remote-authority-inspection.md b/docs/reference/remote-authority-inspection.md new file mode 100644 index 0000000000..0b087c9371 --- /dev/null +++ b/docs/reference/remote-authority-inspection.md @@ -0,0 +1,60 @@ +# Remote authority inspection + +`loopx` and standalone `loopx-core` include a read-only inspection command: + +```bash +loopx remote-authority inspect --goal-id --agent-id --format json +``` + +In the App, open **Settings → One Goal → Capability Center**, select the Goal, +and use **Remote task connection → Check connection**. Opening settings makes +no remote request. The button checks that Goal's existing bound actor and shows +the verified/unverified result, a safe next step and diagnostic details. After +correcting configuration or access, use **Check again**. Switching Goals clears +the result; a late response cannot appear under the newly selected Goal. + +The App and CLI use the same inspection owner. The App's local POST route accepts +only the Goal identifier, enforces the Chat server's origin checks, and reads +the existing binding and credential on the server. The browser cannot supply +an endpoint, credential, actor override or execution operation. Binding setup +remains a separate operation; the button does not enable or modify a binding. + +It uses the selected registered Goal's existing `remote_authority` binding: +`enabled: true`, `endpoint`, `tenant_id`, `store_identity`, `actor_id`, and +`probe_todo_id`, plus optional `ca_file`. The selected agent must be registered +for that Goal and match `actor_id`. The command does not create or change this +binding. Other Goals and environment-only endpoint settings cannot enable it. + +Supply the service credential through `LOOPX_AUTHORITY_CREDENTIAL` or, if unset +or empty, `LOOPX_REMOTE_AUTHORITY_CREDENTIAL`. Credentials are passed to the +private client process over stdin, not command arguments. `endpoint` must be a +credential-free HTTPS origin. An optional CA file must be an absolute path to a +readable regular file of 1–65536 bytes. Certificate verification stays enabled. + +The command reads only the configured probe Todo through the existing task wire +contract. It makes one request, with a three-second network deadline and a +64 KiB response limit, without retries, redirects or writes. Local validation +failures make no request. The outer client process has a five-second deadline. + +JSON output uses `loopx_remote_authority_inspection_v1` and contains `ok`, +`status`, `stage`, `reason_code`, a fixed `message`, `recommended_action`, and +`execution_admitted: false`. HTTP failures additionally include `http_status`. +Output never includes binding values, credentials, remote Todo content, raw +server messages or exception details. Omit `--format json` for readable output. + +| Result | Meaning and next step | +| --- | --- | +| `remote_authority_read_verified` | The configured read was verified; exit code 0. Execution still requires the existing admission and lease workflow. | +| Configuration/runtime failure | Check Goal registration, selected agent, binding, credential, CA file or local Node.js installation as directed. | +| DNS/connection/TLS/timeout failure | Check hostname, network, server and certificate configuration. TLS verification is never bypassed. | +| `remote_authority_http` | Check the returned HTTP status and service/proxy configuration. An HTTP 401/403 alone does not establish the protocol's authentication or scope result. | +| `remote_authority_unauthenticated` / `remote_authority_scope_denied` | A correlated protocol response rejected authentication or scope; check with the service operator. | +| Protocol/read failure | Check client/service compatibility or the configured probe Todo. Unknown service reasons are reduced to a fixed safe diagnostic. | + +Every unverified result exits 1. A missing Todo does not verify readiness. A +verified read does not claim a task, renew a lease, spend quota or enable remote +execution. The existing scheduler gateway and its `verified`/`unavailable` +private probe remain compatible; this command adds operator diagnostics only. + +This client command does not install a remote service or qualify a production +deployment. Server-side authority remains in `loopx-project/loopx-cloud`. diff --git a/loopx/chat/goal_configuration_api.py b/loopx/chat/goal_configuration_api.py index c420f4922b..689c910acb 100644 --- a/loopx/chat/goal_configuration_api.py +++ b/loopx/chat/goal_configuration_api.py @@ -40,6 +40,7 @@ CHAT_GOAL_CONFIGURATION_PATH = "/api/chat/goal-configuration" CHAT_GOAL_CONFIGURATION_PREVIEW_PATH = f"{CHAT_GOAL_CONFIGURATION_PATH}/preview" CHAT_GOAL_CONFIGURATION_APPLY_PATH = f"{CHAT_GOAL_CONFIGURATION_PATH}/apply" +CHAT_GOAL_REMOTE_AUTHORITY_INSPECTION_PATH = f"{CHAT_GOAL_CONFIGURATION_PATH}/remote-authority/inspect" class GoalConfigurationRequestMixin: @@ -69,6 +70,23 @@ def _goal_configuration_reader(self) -> GoalConfigurationReader: def _goal_configuration_writer(self) -> GoalConfigurationWriter: return configure_goal_with_global_sync + def _goal_remote_authority_inspect(self) -> None: + """Explicit, origin-guarded read through the same owner as the CLI.""" + from ..control_plane.coordination.remote_authority_gateway import inspect_remote_authority + + try: + body = self._read_json() + goal_id = body.get("goal_id") + if (set(body) != {"goal_id"} or not isinstance(goal_id, str) + or not goal_id.strip() or len(goal_id) > 200): + raise ValueError("invalid inspection target") + except (TypeError, ValueError): + self._send_error("Select one registered Goal to inspect.", status=400, + error_code="invalid_remote_authority_inspection_request") + return + result = inspect_remote_authority(self.server.registry_path, goal_id) + self._send_json({"goal_id": goal_id, "inspection": result}) + @staticmethod def _goal_configuration_readback_matches( capability_id: str, diff --git a/loopx/cli.py b/loopx/cli.py index dcd69760ee..4db2de2d50 100644 --- a/loopx/cli.py +++ b/loopx/cli.py @@ -19,6 +19,7 @@ from .cli_commands.agent_capabilities import register_agent_capabilities from .cli_commands.agent_directory import register_agent_directory from .cli_commands.agent_context import register_agent_context +from .cli_commands.remote_authority import register_remote_authority_command, handle_remote_authority_command from .capabilities.multi_subagent.cli import ( register_native_child_commands, handle_native_child_command, ) @@ -326,6 +327,7 @@ def build_parser() -> LoopXArgumentParser: register_coordination_shadow_command(sub, add_subcommand_format) register_automation_cadence_command(sub, add_subcommand_format) register_authority_archive_command(sub, add_subcommand_format) + register_remote_authority_command(sub, add_subcommand_format) register_task_lease_command(sub, add_subcommand_format) register_authority_shadow_command(sub, add_subcommand_format) register_todo_continuation(sub, add_subcommand_format) @@ -406,6 +408,12 @@ def _main(argv: list[str] | None = None) -> int: if worker_bridge_result is not None: return worker_bridge_result + remote_authority_result = handle_remote_authority_command( + args, registry_path=registry_path, print_payload=print_payload, output_format=output_format, + ) + if remote_authority_result is not None: + return remote_authority_result + support_control_result = handle_support_control_command( args, registry_path=registry_path, diff --git a/loopx/cli_commands/remote_authority.py b/loopx/cli_commands/remote_authority.py new file mode 100644 index 0000000000..7349c1de50 --- /dev/null +++ b/loopx/cli_commands/remote_authority.py @@ -0,0 +1,38 @@ +"""Explicit operator entry point for read-only remote authority inspection.""" + +from __future__ import annotations + +import argparse +from collections.abc import Callable +from pathlib import Path + + +def register_remote_authority_command( + subparsers: argparse._SubParsersAction[argparse.ArgumentParser], + add_subcommand_format: Callable[[argparse.ArgumentParser], None], +) -> None: + parser = subparsers.add_parser("remote-authority", help="Inspect a Goal's configured remote authority without admitting work.") + add_subcommand_format(parser) + actions = parser.add_subparsers(dest="remote_authority_action", required=True) + inspect = actions.add_parser("inspect", help="Read the bound probe Todo once and report safe diagnostics.") + inspect.add_argument("--goal-id", required=True) + inspect.add_argument("--agent-id", required=True) + inspect.add_argument("--format", dest="inspection_format", choices=("markdown", "json")) + + +def handle_remote_authority_command( + args: argparse.Namespace, *, registry_path: Path, + output_format: Callable[..., str], + print_payload: Callable[[dict[str, object], str, Callable[[dict[str, object]], str]], None], +) -> int | None: + if args.command != "remote-authority": + return None + from ..control_plane.coordination.remote_authority_gateway import inspect_remote_authority + + result = inspect_remote_authority(registry_path, args.goal_id, args.agent_id) + print_payload(result, output_format(args, "inspection_format"), lambda payload: "\n".join(( + f"Remote authority: {payload['status']} ({payload['reason_code']})", + str(payload["message"]), str(payload["recommended_action"]), + "Execution admitted: no.", + ))) + return 0 if result["ok"] else 1 diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py index 89df88b673..0dfc416361 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -64,7 +64,7 @@ "todo", "quota", "task-lease", "change-window", "delegation", "turn", "doctor", "commands", "version", "bootstrap", "connect", "configure-goal", "start-goal", "bootstrap-command-pack", "register-agent", "bind-agent-thread", - "authority-archive", "coordination-shadow", "extension", "slash-commands", + "authority-archive", "remote-authority", "coordination-shadow", "extension", "slash-commands", "manager-inbox", "agent-context", "agent-directory", "agent-capabilities", "handoff", "handoff-mode", @@ -518,6 +518,10 @@ def _build_selected_parser(command: str) -> LoopXArgumentParser: from .cli_commands.agent_capabilities import register_agent_capabilities register_agent_capabilities(subparsers, add_subcommand_format) + elif command == "remote-authority": + from .cli_commands.remote_authority import register_remote_authority_command + + register_remote_authority_command(subparsers, add_subcommand_format) elif command == "authority-archive": from .cli_commands.authority_archive import register_authority_archive_command @@ -728,6 +732,12 @@ def _dispatch_common_command( args, registry_path=registry_path, runtime_root_arg=args.runtime_root, output_format=output_format, print_payload=print_payload, ) + if args.command == "remote-authority": + from .cli_commands.remote_authority import handle_remote_authority_command + + return handle_remote_authority_command( + args, registry_path=registry_path, output_format=output_format, print_payload=print_payload, + ) if args.command == "authority-archive": from .cli_commands.authority_archive import handle_authority_archive_command diff --git a/loopx/control_plane/coordination/remote_authority_gateway.py b/loopx/control_plane/coordination/remote_authority_gateway.py index de4fb29862..ea94b9d9b3 100644 --- a/loopx/control_plane/coordination/remote_authority_gateway.py +++ b/loopx/control_plane/coordination/remote_authority_gateway.py @@ -77,3 +77,70 @@ def check_remote_authority_gateway_status( except (EffectRuntimeStartupError, OSError, subprocess.SubprocessError): pass return {**projection, "status": "unavailable", "reason_code": "remote_authority_read_unverified"} + + +def _inspection_io_failure(reason: str, message: str, action: str) -> dict[str, object]: + return { + "schema_version": "loopx_remote_authority_inspection_v1", "ok": False, + "status": "unavailable", "stage": "runtime", "reason_code": reason, + "message": message, "recommended_action": action, "execution_admitted": False, + } + + +def inspect_remote_authority(registry_path: Path, goal_id: str, agent_id: str | None = None) -> dict[str, object]: + from ...agent_registry import load_goal_from_registry, registered_agent_ids_for_goal + from ..effect_runtime import EffectRuntimeStartupError, _node_executable + from ..runtime.node_probe import node_typescript_flags + + try: + goal = load_goal_from_registry(registry_path, goal_id) + except (OSError, ValueError): + return _inspection_io_failure( + "remote_authority_registry_unreadable", "The selected registry could not be read.", + "Check the registry's format and local access permissions.", + ) + cfg = goal.get("remote_authority") if goal is not None else None + # Copy only the existing binding, never remote content or unrelated Goal state. + if isinstance(cfg, dict): + cfg = {key: cfg[key] for key in ( + "enabled", "endpoint", "tenant_id", "store_identity", "actor_id", "probe_todo_id", "ca_file", + ) if key in cfg} + # The App inspects the existing bound actor; it cannot supply a credential, + # endpoint or alternative binding. CLI callers keep their explicit actor. + if agent_id is None and isinstance(cfg, dict): + bound_actor = cfg.get("actor_id") + agent_id = bound_actor if isinstance(bound_actor, str) else None + request = { + "goal_registered": goal is not None, + "actor_registered": agent_id in registered_agent_ids_for_goal(goal), + "goal_id": goal_id, "agent_id": agent_id, "config": cfg, + "credential": os.environ.get("LOOPX_AUTHORITY_CREDENTIAL") or os.environ.get("LOOPX_REMOTE_AUTHORITY_CREDENTIAL"), + } + try: + # Bindings and credentials travel through stdin, never argv or diagnostics. + bridge = Path(__file__).with_name("remote_authority_probe.ts") + completed = subprocess.run( + [_node_executable(), "--no-warnings", "--experimental-strip-types", + *node_typescript_flags(), str(bridge), "--inspect"], + input=json.dumps(request), + env={key: os.environ[key] for key in ("PATH", "SystemRoot", "WINDIR", "TMPDIR", "TEMP") + if key in os.environ}, + text=True, encoding="utf-8", capture_output=True, check=True, timeout=5, + ) + payload = json.loads(completed.stdout) + if (isinstance(payload, dict) + and payload.get("schema_version") == "loopx_remote_authority_inspection_v1" + and payload.get("execution_admitted") is False + and isinstance(payload.get("ok"), bool)): + return payload + except EffectRuntimeStartupError: + return _inspection_io_failure( + "remote_authority_node_unavailable", "The required Node.js runtime is unavailable.", + "Run loopx doctor and repair the Node.js installation.", + ) + except (OSError, ValueError, subprocess.SubprocessError): + pass + return _inspection_io_failure( + "remote_authority_probe_unavailable", "The local inspection process did not return a valid result.", + "Run loopx doctor and check the installed runtime files.", + ) diff --git a/loopx/control_plane/coordination/remote_authority_http.ts b/loopx/control_plane/coordination/remote_authority_http.ts index bb3d6839f8..0ec895ca18 100644 --- a/loopx/control_plane/coordination/remote_authority_http.ts +++ b/loopx/control_plane/coordination/remote_authority_http.ts @@ -11,41 +11,88 @@ export interface RemoteAuthorityCallOptions { timeoutMs?: number; } +export type RemoteAuthorityTransportFailure = "dns" | "connection_refused" | "tls" | "connection" + | "timeout" | "http" | "response_invalid" | "response_too_large"; +export interface RemoteAuthorityCallObservation { + response: JsonObject; + transport: {kind: RemoteAuthorityTransportFailure; httpStatus?: number} | null; +} + +export function remoteAuthorityOrigin(endpoint: string): URL { + const base = new URL(endpoint); + if (base.protocol !== "https:" || base.username || base.password || base.search || base.hash || base.pathname !== "/") throw new TypeError("A credential-free HTTPS origin is required"); + return base; +} + +export function validateRemoteAuthorityCredential(credential: string): void { + if (!/^[\x21-\x7e]{32,512}$/u.test(credential)) throw new TypeError("Invalid service credential"); +} + +function connectionFailure(error: NodeJS.ErrnoException): RemoteAuthorityTransportFailure { + const code = error.code ?? ""; + if (code === "ENOTFOUND" || code === "EAI_AGAIN") return "dns"; + if (code === "ECONNREFUSED") return "connection_refused"; + if (/^(ERR_TLS_|ERR_SSL_|ERR_OSSL_|CERT_|DEPTH_ZERO_SELF_SIGNED_CERT|SELF_SIGNED_CERT_IN_CHAIN|UNABLE_TO_)/u.test(code)) return "tls"; + return "connection"; +} + /** No automatic retry, redirects, or certificate-verification bypass. Recovery * reuses the complete original command; missing receipt is not a new operation. */ export async function callRemoteAuthority(endpoint: string, credential: string, raw: RemoteAuthorityRequest, options: RemoteAuthorityCallOptions = {}): Promise { + return (await observeRemoteAuthorityCall(endpoint, credential, raw, options)).response; +} + +/** Local transport evidence is separate from the wire outcome. In particular, + * transport failures never prove that a mutating command did not commit. */ +export async function observeRemoteAuthorityCall(endpoint: string, credential: string, + raw: RemoteAuthorityRequest, options: RemoteAuthorityCallOptions = {}): Promise { const request = decodeRemoteAuthorityRequest(raw), mode = options.mode ?? "execute"; - const base = new URL(endpoint); - if (base.protocol !== "https:" || base.username || base.password || base.search || base.hash || base.pathname !== "/") throw new TypeError("A credential-free HTTPS origin is required"); - if (!/^[\x21-\x7e]{32,512}$/u.test(credential)) throw new TypeError("Invalid service credential"); + const base = remoteAuthorityOrigin(endpoint); + validateRemoteAuthorityCredential(credential); const timeout = options.timeoutMs ?? 15000; if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 120000) throw new TypeError("Invalid request deadline"); const uncertain = () => remoteAuthorityResponse(request, mode, {status: mode === "recover" || request.operation === "read" || request.operation === "snapshot" ? "unavailable" : "ambiguous", reason_code: "remote_authority_transport_uncertain"}); return new Promise(resolve => { + let settled = false; + let timer: ReturnType | undefined; + const finish = (result: RemoteAuthorityCallObservation) => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve(result); + }; + const fail = (kind: RemoteAuthorityTransportFailure, httpStatus?: number) => + finish({response: uncertain(), transport: {kind, ...(httpStatus === undefined ? {} : {httpStatus})}}); const body = JSON.stringify(request); const outgoing = httpsRequest(new URL(`/v0/tasks/${mode}`, base), {method: "POST", ca: options.ca, rejectUnauthorized: true, headers: {Authorization: `Bearer ${credential}`, "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body)}}, response => { + if (response.statusCode !== 200) { + fail("http", response.statusCode); + response.destroy(); + outgoing.destroy(); + return; + } const chunks: Buffer[] = []; let bytes = 0; response.on("data", chunk => { bytes += chunk.length; - if (bytes > MAX_RESPONSE_BYTES) outgoing.destroy(); else chunks.push(Buffer.from(chunk)); + if (bytes > MAX_RESPONSE_BYTES) {fail("response_too_large"); outgoing.destroy();} + else chunks.push(Buffer.from(chunk)); }); - response.on("error", () => resolve(uncertain())); + response.on("error", () => fail("connection")); response.on("end", () => { - if (response.statusCode !== 200) {resolve(uncertain()); return;} try { - resolve(decodeRemoteAuthorityResponse(JSON.parse(Buffer.concat(chunks).toString("utf8")), request, mode)); - } catch {resolve(uncertain());} + finish({response: decodeRemoteAuthorityResponse(JSON.parse(Buffer.concat(chunks).toString("utf8")), request, mode), transport: null}); + } catch {fail("response_invalid");} }); }); // Absolute deadline also covers a peer that keeps sending partial bytes. - const timer = setTimeout(() => outgoing.destroy(), timeout); - outgoing.on("close", () => {clearTimeout(timer); resolve(uncertain());}); - outgoing.on("error", () => resolve(uncertain())); + timer = setTimeout(() => {fail("timeout"); outgoing.destroy();}, timeout); + outgoing.on("close", () => fail("connection")); + outgoing.on("error", error => fail(connectionFailure(error))); outgoing.end(body); }); } diff --git a/loopx/control_plane/coordination/remote_authority_inspection.ts b/loopx/control_plane/coordination/remote_authority_inspection.ts new file mode 100644 index 0000000000..6fecc21469 --- /dev/null +++ b/loopx/control_plane/coordination/remote_authority_inspection.ts @@ -0,0 +1,97 @@ +/** Read-only operator inspection. No remote content or execution authority escapes. */ +import {open} from "node:fs/promises"; +import {isAbsolute} from "node:path"; +import type {JsonObject} from "../effect_program.ts"; +import {canonicalAuthorityObject} from "./authority_store_codec.ts"; +import {decodeRemoteAuthorityRequest, REMOTE_AUTHORITY_REQUEST} from "./remote_authority_contract.ts"; +import {observeRemoteAuthorityCall, remoteAuthorityOrigin, validateRemoteAuthorityCredential} from "./remote_authority_http.ts"; + +const diagnostics = { + goal_unregistered: ["configuration", "The selected Goal is not registered.", "Select an existing registered Goal."], + actor_unregistered: ["configuration", "The selected agent is not registered for this Goal.", "Select an agent registered for this Goal."], + disabled: ["configuration", "Remote authority is not enabled for this Goal.", "Inspect the selected Goal's explicit remote_authority binding."], + binding_incomplete: ["configuration", "The remote authority binding is incomplete.", "Check endpoint, tenant_id, store_identity, actor_id and probe_todo_id in the selected Goal."], + binding_invalid: ["configuration", "The remote authority inspection input is invalid.", "Check the selected Goal's identifiers and binding format."], + actor_mismatch: ["configuration", "The selected agent does not match the bound remote actor.", "Select the agent named by this Goal's remote binding."], + endpoint_invalid: ["configuration", "The endpoint is not a credential-free HTTPS origin.", "Use an HTTPS origin without a path, query, fragment or embedded credentials."], + credential_required: ["configuration", "No service credential is available.", "Set LOOPX_AUTHORITY_CREDENTIAL or LOOPX_REMOTE_AUTHORITY_CREDENTIAL in the environment."], + credential_invalid: ["configuration", "The service credential has an invalid format.", "Check the configured environment credential; never put it in command arguments."], + ca_invalid: ["configuration", "The configured CA file cannot be read safely.", "Use an absolute path to a readable regular CA file of 1 to 65536 bytes."], + dns: ["transport", "The service hostname could not be resolved.", "Check the configured hostname and local DNS connectivity."], + connection_refused: ["transport", "The service refused the connection.", "Check the configured port and whether the service is listening."], + tls: ["transport", "The TLS connection could not be verified or established.", "Check the server certificate, hostname, validity and configured CA; keep verification enabled."], + connection: ["transport", "The connection ended without a verified response.", "Check network and service availability before inspecting again."], + timeout: ["transport", "The read exceeded its deadline.", "Check network and service responsiveness before inspecting again."], + http: ["transport", "The service returned a non-success HTTP status.", "Check service and proxy configuration; an HTTP status alone does not verify identity or scope."], + response_invalid: ["protocol", "The response did not match the read contract and request.", "Check client/service compatibility and request correlation."], + response_too_large: ["protocol", "The response exceeded the bounded read limit.", "Check that the endpoint serves the remote task protocol."], + unauthenticated: ["authority", "The service rejected the credential.", "Check credential validity with the service operator."], + scope_denied: ["authority", "The service denied the requested scope.", "Check the credential's tenant, Goal, actor and store permissions with the service operator."], + rejected: ["authority", "The service rejected the read.", "Check service-side policy and the selected binding with the service operator."], + todo_missing: ["read", "The configured probe Todo was not found.", "Check probe_todo_id and the selected scope; a missing Todo does not verify readiness."], + read_unverified: ["read", "The service did not verify the configured read.", "Check service availability and the selected binding."], + read_verified: ["read", "The configured Todo read was verified. Execution is not admitted.", "Use the existing execution admission and lease workflow before running work."], +} as const; + +export function remoteAuthorityInspectionResult(reason: keyof typeof diagnostics, httpStatus?: number): JsonObject { + const [stage, message, recommended_action] = diagnostics[reason]; + const ok = reason === "read_verified"; + return {schema_version: "loopx_remote_authority_inspection_v1", ok, + status: ok ? "verified" : "unavailable", stage, reason_code: `remote_authority_${reason}`, + message, recommended_action, execution_admitted: false, + ...(httpStatus === undefined ? {} : {http_status: httpStatus})}; +} + +export async function readRemoteAuthorityCa(path: unknown): Promise { + if (path === null || path === undefined) return undefined; + if (typeof path !== "string" || !isAbsolute(path)) throw new TypeError("Invalid CA path"); + const file = await open(path, "r"); + try { + const info = await file.stat(); + if (!info.isFile() || info.size === 0 || info.size > 64 * 1024) throw new TypeError("Invalid CA file"); + const bytes = Buffer.alloc(info.size); + if ((await file.read(bytes, 0, bytes.length, 0)).bytesRead !== bytes.length) throw new TypeError("Incomplete CA file"); + return bytes; + } finally {await file.close();} +} + +/** Only the private bridge supplies registration evidence. Caller configuration + * cannot select an operation, bypass TLS verification or request a retry. */ +export async function inspectRemoteAuthority(raw: unknown): Promise { + let input: JsonObject, cfg: JsonObject; + try { + input = canonicalAuthorityObject(raw, "inspection input"); + if (input.goal_registered !== true) return remoteAuthorityInspectionResult("goal_unregistered"); + cfg = canonicalAuthorityObject(input.config ?? {}, "remote authority binding"); + } catch {return remoteAuthorityInspectionResult("binding_invalid");} + if (cfg.enabled !== true) return remoteAuthorityInspectionResult("disabled"); + if (!["endpoint", "tenant_id", "store_identity", "actor_id", "probe_todo_id"].every( + key => typeof cfg[key] === "string" && cfg[key].trim())) return remoteAuthorityInspectionResult("binding_incomplete"); + if (input.actor_registered !== true) return remoteAuthorityInspectionResult("actor_unregistered"); + if (input.agent_id !== cfg.actor_id) return remoteAuthorityInspectionResult("actor_mismatch"); + const endpoint = cfg.endpoint as string; + try {remoteAuthorityOrigin(endpoint);} catch {return remoteAuthorityInspectionResult("endpoint_invalid");} + if (!input.credential) return remoteAuthorityInspectionResult("credential_required"); + if (typeof input.credential !== "string") return remoteAuthorityInspectionResult("credential_invalid"); + try {validateRemoteAuthorityCredential(input.credential);} catch {return remoteAuthorityInspectionResult("credential_invalid");} + let request; + try { + request = decodeRemoteAuthorityRequest({schema_version: REMOTE_AUTHORITY_REQUEST, operation: "read", + tenant_id: cfg.tenant_id, goal_id: input.goal_id, actor_id: cfg.actor_id, + store_identity: cfg.store_identity, todo_id: cfg.probe_todo_id}); + } catch {return remoteAuthorityInspectionResult("binding_invalid");} + let ca; + try {ca = await readRemoteAuthorityCa(cfg.ca_file);} catch {return remoteAuthorityInspectionResult("ca_invalid");} + try { + const {response, transport} = await observeRemoteAuthorityCall(endpoint, input.credential, request, {ca, timeoutMs: 3000}); + if (transport) return remoteAuthorityInspectionResult(transport.kind, transport.httpStatus); + if (response.status === "found") return remoteAuthorityInspectionResult("read_verified"); + if (response.status === "missing") return remoteAuthorityInspectionResult("todo_missing"); + if (response.status === "rejected") { + if (response.reason_code === "principal_unauthenticated") return remoteAuthorityInspectionResult("unauthenticated"); + if (response.reason_code === "remote_authority_scope_denied") return remoteAuthorityInspectionResult("scope_denied"); + return remoteAuthorityInspectionResult("rejected"); + } + return remoteAuthorityInspectionResult("read_unverified"); + } catch {return remoteAuthorityInspectionResult("read_unverified");} +} diff --git a/loopx/control_plane/coordination/remote_authority_probe.ts b/loopx/control_plane/coordination/remote_authority_probe.ts index 9f64de6046..878952c9a5 100644 --- a/loopx/control_plane/coordination/remote_authority_probe.ts +++ b/loopx/control_plane/coordination/remote_authority_probe.ts @@ -1,22 +1,10 @@ /** Private stdin bridge to the same scoped TLS client used by task commands. */ -import {open} from "node:fs/promises"; -import {isAbsolute} from "node:path"; import {canonicalAuthorityObject} from "./authority_store_codec.ts"; import {decodeRemoteAuthorityRequest, REMOTE_AUTHORITY_REQUEST} from "./remote_authority_contract.ts"; import {callRemoteAuthority} from "./remote_authority_http.ts"; +import {inspectRemoteAuthority, readRemoteAuthorityCa, remoteAuthorityInspectionResult} from "./remote_authority_inspection.ts"; -async function readCa(path: unknown): Promise { - if (path === null || path === undefined) return undefined; - if (typeof path !== "string" || !isAbsolute(path)) throw new TypeError("Invalid CA path"); - const file = await open(path, "r"); - try { - const info = await file.stat(); - if (!info.isFile() || info.size === 0 || info.size > 64 * 1024) throw new TypeError("Invalid CA file"); - const bytes = Buffer.alloc(info.size); - if ((await file.read(bytes, 0, bytes.length, 0)).bytesRead !== bytes.length) throw new TypeError("Incomplete CA file"); - return bytes; - } finally {await file.close();} -} +const inspect = process.argv[2] === "--inspect"; try { let input = ""; @@ -25,16 +13,20 @@ try { input += chunk; if (Buffer.byteLength(input) > 16 * 1024) throw new TypeError("Invalid probe input"); } - const cfg = canonicalAuthorityObject(JSON.parse(input), "remote authority probe"); - if (typeof cfg.endpoint !== "string" || typeof cfg.credential !== "string") throw new TypeError("Invalid probe binding"); - const request = decodeRemoteAuthorityRequest({ - schema_version: REMOTE_AUTHORITY_REQUEST, operation: "read", - tenant_id: cfg.tenant_id, goal_id: cfg.goal_id, actor_id: cfg.actor_id, - store_identity: cfg.store_identity, todo_id: cfg.probe_todo_id, - }); - const response = await callRemoteAuthority(cfg.endpoint, cfg.credential, request, {ca: await readCa(cfg.ca_file), timeoutMs: 3000}); + if (inspect) { + process.stdout.write(JSON.stringify(await inspectRemoteAuthority(JSON.parse(input))) + "\n"); + } else { + const cfg = canonicalAuthorityObject(JSON.parse(input), "remote authority probe"); + if (typeof cfg.endpoint !== "string" || typeof cfg.credential !== "string") throw new TypeError("Invalid probe binding"); + const request = decodeRemoteAuthorityRequest({ + schema_version: REMOTE_AUTHORITY_REQUEST, operation: "read", + tenant_id: cfg.tenant_id, goal_id: cfg.goal_id, actor_id: cfg.actor_id, + store_identity: cfg.store_identity, todo_id: cfg.probe_todo_id, + }); + const response = await callRemoteAuthority(cfg.endpoint, cfg.credential, request, {ca: await readRemoteAuthorityCa(cfg.ca_file), timeoutMs: 3000}); - process.stdout.write(response.status === "found" ? "verified\n" : "unavailable\n"); + process.stdout.write(response.status === "found" ? "verified\n" : "unavailable\n"); + } } catch { - process.stdout.write("unavailable\n"); + process.stdout.write(inspect ? JSON.stringify(remoteAuthorityInspectionResult("binding_invalid")) + "\n" : "unavailable\n"); } diff --git a/loopx/control_plane/testing/cli_output_budget.py b/loopx/control_plane/testing/cli_output_budget.py index 20c3995eda..20e3f1bcaa 100644 --- a/loopx/control_plane/testing/cli_output_budget.py +++ b/loopx/control_plane/testing/cli_output_budget.py @@ -808,6 +808,12 @@ class CliOutputCommandClassification: surface_id="todo_list", rationale="agent work-queue read path", ), + CliOutputCommandClassification( + command_id="remote-authority", + qualification="explicit_cold_path_exception", + surface_id=None, + rationale="explicit operator inspection of a configured remote read; never invoked by the recurring turn guard", + ), CliOutputCommandClassification( command_id="coordination-shadow", qualification="explicit_cold_path_exception", diff --git a/loopx/help_surface.py b/loopx/help_surface.py index 99a336d72e..b9f3a18d03 100644 --- a/loopx/help_surface.py +++ b/loopx/help_surface.py @@ -139,6 +139,10 @@ def register_command_reference(subparsers: argparse._SubParsersAction[argparse.A "purpose": "Preview an explicit local-state path migration or receipt-bound rollback; stop writers before execution.", }, {"command": "loopx todo --help", "purpose": "Show todo lifecycle commands."}, + { + "command": "loopx remote-authority inspect --goal-id --agent-id ", + "purpose": "Read a configured remote probe Todo and report safe diagnostics; never admit execution.", + }, { "command": "loopx coordination-shadow --help", "purpose": "Inspect, bootstrap, or revision-fenced rollback the default-off Stage 2C file shadow.", diff --git a/loopx/presentation/configuration_api.py b/loopx/presentation/configuration_api.py index 51a7e329d0..07c9054db0 100644 --- a/loopx/presentation/configuration_api.py +++ b/loopx/presentation/configuration_api.py @@ -67,6 +67,7 @@ def _configuration_get_routes(self) -> dict[str, Callable[[], None]]: def _configuration_post_routes(self) -> dict[str, Callable[[], None]]: return { + goal_api.CHAT_GOAL_REMOTE_AUTHORITY_INSPECTION_PATH: self._goal_remote_authority_inspect, media_api.CONTENT_MEDIA_PATH: self._content_media_request, accounts_api.CODEX_ACCOUNTS_PATH: self._codex_accounts_write, f"{accounts_api.CODEX_ACCOUNTS_PATH}/keys": self._codex_api_keys_write, diff --git a/tests/control_plane/remote_authority_browser_fixture.py b/tests/control_plane/remote_authority_browser_fixture.py new file mode 100644 index 0000000000..905c85d058 --- /dev/null +++ b/tests/control_plane/remote_authority_browser_fixture.py @@ -0,0 +1,48 @@ +"""Packaged UI fixture with the real Chat inspection route and a synthetic TLS peer.""" + +import argparse +import json +import os +from pathlib import Path +import sys + +from examples.control_plane.quota_plan_fixtures import SCOPED_AGENT_ID, write_cli_fixture +from loopx.chat_server import default_chat_assets_dir +from loopx.presentation.chat_bundle import validate_bundle +from tests.control_plane.remote_authority_inspection_fixture import ( + CREDENTIAL, bind_remote_authority, remote_authority_service, +) +from tests.test_chat_remote_authority_inspection import inspection_api + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--assets", type=Path) + args = parser.parse_args() + assets = args.assets or default_chat_assets_dir() + validate_bundle(assets, source_root=None if args.assets else Path(__file__).resolve().parents[2]) + registry, runtime, _ = write_cli_fixture(args.root, scoped_agents=True) + document = json.loads(registry.read_text()) + for goal in document["goals"]: + if goal["id"] == "full-speed": + goal["id"] = "product-release" + registry.write_text(json.dumps(document)) + os.environ["LOOPX_AUTHORITY_CREDENTIAL"] = CREDENTIAL + with remote_authority_service(args.root, SCOPED_AGENT_ID) as (config, control), inspection_api( + registry, runtime, assets=assets, + ) as origin: + bind_remote_authority(registry, "product-release", config) + before = {p: p.read_bytes() for p in args.root.rglob("*") if p.is_file()} + print(json.dumps({"origin": origin}), flush=True) + for line in sys.stdin: + command = json.loads(line) + if "mode" in command: + control["mode"] = command["mode"] + print(json.dumps({"requests": len(control["requests"]), "unchanged": before == { + p: p.read_bytes() for p in args.root.rglob("*") if p.is_file() + }}), flush=True) + + +if __name__ == "__main__": + main() diff --git a/tests/control_plane/remote_authority_inspection_fixture.py b/tests/control_plane/remote_authority_inspection_fixture.py new file mode 100644 index 0000000000..f396d0d587 --- /dev/null +++ b/tests/control_plane/remote_authority_inspection_fixture.py @@ -0,0 +1,89 @@ +"""Disposable HTTPS peer; independently encode correlated, synthetic read replies.""" + +from __future__ import annotations + +import hashlib +import http.server +import json +import shutil +import ssl +import subprocess +import threading +from contextlib import contextmanager + +import pytest + +CREDENTIAL = "synthetic-inspection-credential-" + "a" * 32 + + +@contextmanager +def remote_authority_service(tmp_path, actor_id): + if shutil.which("openssl") is None: + pytest.skip("openssl required for disposable TLS certificate") + key, cert = tmp_path / "key.pem", tmp_path / "cert.pem" + subprocess.run( + ["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "1", + "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1", + "-keyout", str(key), "-out", str(cert)], check=True, capture_output=True, + ) + requests = [] + control = {"mode": "found", "requests": requests} + + class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self, _format, *_args): + return + + def do_POST(self): # noqa: N802 + req = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + requests.append((self.path, req)) + assert req["operation"] == "read" + assert self.headers["Authorization"] == f"Bearer {CREDENTIAL}" + if control["mode"] == "http": + self.send_response(401) + self.end_headers() + self.wfile.write(CREDENTIAL.encode()) + return + digest = hashlib.sha256(json.dumps( + {"mode": "execute", "request": req}, sort_keys=True, separators=(",", ":"), + ).encode()).hexdigest() + packet = { + "schema_version": "loopx_remote_authority_scoped_read_response_v1", + "request_sha256": digest, "status": "found", + "goal_ref": {"goal_id": req["goal_id"], "goal_instance_id": "ginst_" + "a" * 32}, + "todo": {"todo_id": req["todo_id"], "status": "open"}, "lease": None, + } + if control["mode"] == "denied": + packet = { + "schema_version": "loopx_remote_authority_response_v0", "request_sha256": digest, + "status": "rejected", "reason_code": "remote_authority_scope_denied", + } + body = json.dumps(packet).encode() if control["mode"] != "invalid" else CREDENTIAL.encode() + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx.load_cert_chain(certfile=cert, keyfile=key) + server.socket = ctx.wrap_socket(server.socket, server_side=True) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + config = { + "enabled": True, "endpoint": f"https://127.0.0.1:{server.server_port}", + "tenant_id": "synthetic-inspection-tenant", "actor_id": actor_id, + "store_identity": "postgresql:" + "b" * 32, "probe_todo_id": "todo_probe", + "ca_file": str(cert), + } + try: + yield config, control + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) + + +def bind_remote_authority(registry, goal_id, config): + document = json.loads(registry.read_text()) + next(goal for goal in document["goals"] if goal["id"] == goal_id)["remote_authority"] = config + registry.write_text(json.dumps(document), encoding="utf-8") diff --git a/tests/control_plane/test_remote_authority_inspection.py b/tests/control_plane/test_remote_authority_inspection.py new file mode 100644 index 0000000000..71327e7a80 --- /dev/null +++ b/tests/control_plane/test_remote_authority_inspection.py @@ -0,0 +1,143 @@ +"""Installed CLI inspection is explicit, read-only, and safe to share.""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys + +import pytest + +from examples.control_plane.quota_plan_fixtures import SCOPED_AGENT_ID, write_cli_fixture +from tests.control_plane.remote_authority_inspection_fixture import ( + CREDENTIAL, bind_remote_authority, remote_authority_service, +) + + +def test_inspect_disabled_binding_does_not_change_registry_or_runtime(tmp_path): + registry, runtime, _ = write_cli_fixture(tmp_path, scoped_agents=True) + before = {path: path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()} + result = subprocess.run( + [sys.executable, "-m", "loopx.entrypoint", "--registry", str(registry), + "--runtime-root", str(runtime), "remote-authority", "inspect", + "--goal-id", "full-speed", "--agent-id", SCOPED_AGENT_ID, "--format", "json"], + env={**os.environ, "LOOPX_USAGE_PING": "0", "LOOPX_CONTEXT_DELIVERY": "off"}, + capture_output=True, text=True, timeout=15, + ) + assert result.returncode == 1, (result.stdout, result.stderr) + packet = json.loads(result.stdout) + assert packet["reason_code"] == "remote_authority_disabled" + assert packet["execution_admitted"] is False + assert before == {path: path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()} + + +def _inspect(registry, runtime, *extra, goal="full-speed", actor=SCOPED_AGENT_ID): + return subprocess.run( + [sys.executable, "-m", "loopx.entrypoint", "--registry", str(registry), + "--runtime-root", str(runtime), "remote-authority", "inspect", + "--goal-id", goal, "--agent-id", actor, *extra], + env={**os.environ, "LOOPX_USAGE_PING": "0", "LOOPX_CONTEXT_DELIVERY": "off"}, + capture_output=True, text=True, timeout=15, + ) + + +def test_inspect_real_https_preserves_local_state_and_hides_private_fields(tmp_path, monkeypatch): + registry, runtime, _ = write_cli_fixture(tmp_path, scoped_agents=True) + monkeypatch.setenv("LOOPX_AUTHORITY_CREDENTIAL", CREDENTIAL) + with remote_authority_service(tmp_path, SCOPED_AGENT_ID) as (cfg, control): + bind_remote_authority(registry, "full-speed", cfg) + before = {path: path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()} + for mode, reason in (("found", "read_verified"), ("denied", "scope_denied"), + ("http", "http"), ("invalid", "response_invalid")): + control["mode"] = mode + previous = len(control["requests"]) + result = _inspect(registry, runtime, "--format", "json") + assert result.returncode == (0 if mode == "found" else 1), result.stderr + packet = json.loads(result.stdout) + assert packet["reason_code"] == f"remote_authority_{reason}" + assert packet["execution_admitted"] is False + assert len(control["requests"]) == previous + 1 + for private in (CREDENTIAL, *[cfg[key] for key in ( + "endpoint", "tenant_id", "store_identity", "probe_todo_id", "ca_file", + )]): + assert private not in result.stdout + result.stderr + assert before == {path: path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()} + control["mode"] = "found" + monkeypatch.delenv("LOOPX_AUTHORITY_CREDENTIAL") + monkeypatch.setenv("LOOPX_REMOTE_AUTHORITY_CREDENTIAL", CREDENTIAL) + markdown = _inspect(registry, runtime) + assert markdown.returncode == 0, markdown.stderr + assert "Execution admitted: no." in markdown.stdout + assert CREDENTIAL not in markdown.stdout + markdown.stderr + + +@pytest.mark.parametrize(("mutation", "reason"), [ + ("unknown-goal", "goal_unregistered"), ("unknown-actor", "actor_unregistered"), + ("other-goal", "disabled"), ("disabled", "disabled"), ("missing-binding", "binding_incomplete"), + ("actor-mismatch", "actor_mismatch"), ("no-credential", "credential_required"), + ("short-credential", "credential_invalid"), ("endpoint", "endpoint_invalid"), + ("ca", "ca_invalid"), ("registry", "registry_unreadable"), +]) +def test_inspect_configuration_errors_never_contact_remote(tmp_path, monkeypatch, mutation, reason): + registry, runtime, _ = write_cli_fixture(tmp_path, scoped_agents=True) + monkeypatch.setenv("LOOPX_AUTHORITY_CREDENTIAL", CREDENTIAL) + monkeypatch.delenv("LOOPX_REMOTE_AUTHORITY_CREDENTIAL", raising=False) + with remote_authority_service(tmp_path, SCOPED_AGENT_ID) as (cfg, control): + if mutation == "disabled": + cfg["enabled"] = False + if mutation == "missing-binding": + del cfg["tenant_id"] + if mutation == "actor-mismatch": + cfg["actor_id"] = "other-registered-actor" + if mutation == "no-credential": + monkeypatch.delenv("LOOPX_AUTHORITY_CREDENTIAL") + if mutation == "short-credential": + monkeypatch.setenv("LOOPX_AUTHORITY_CREDENTIAL", "short-secret") + if mutation == "endpoint": + cfg["endpoint"] += "/private-path?secret=value" + if mutation == "ca": + cfg["ca_file"] = "private-relative-path.pem" + bind_remote_authority(registry, "half-speed" if mutation == "other-goal" else "full-speed", cfg) + if mutation == "registry": + registry.write_text("invalid-registry-private-content", encoding="utf-8") + result = _inspect( + registry, runtime, "--format", "json", + goal="absent-goal" if mutation == "unknown-goal" else "full-speed", + actor="unregistered-actor" if mutation == "unknown-actor" else SCOPED_AGENT_ID, + ) + assert result.returncode == 1, result.stderr + assert json.loads(result.stdout)["reason_code"] == f"remote_authority_{reason}" + assert control["requests"] == [] + for private in (CREDENTIAL, "short-secret", "private-path", "private-content", str(registry)): + assert private not in result.stdout + result.stderr + + +def test_inspect_runtime_error_does_not_emit_exception_details(tmp_path, monkeypatch): + from loopx.control_plane.coordination.remote_authority_gateway import inspect_remote_authority + from loopx.control_plane.effect_runtime import EffectRuntimeStartupError + + registry, _, _ = write_cli_fixture(tmp_path, scoped_agents=True) + + def missing_node(): + raise EffectRuntimeStartupError("private-host-detail", diagnostic_code="node_unavailable") + + monkeypatch.setattr("loopx.control_plane.effect_runtime._node_executable", missing_node) + packet = inspect_remote_authority(registry, "full-speed", SCOPED_AGENT_ID) + assert packet["reason_code"] == "remote_authority_node_unavailable" + assert packet["execution_admitted"] is False + assert "private-host-detail" not in json.dumps(packet) + + +def test_inspect_full_parser_and_format_positions_are_discoverable(): + from loopx.cli import build_parser + from loopx.cli_runtime import output_format + from loopx.help_surface import COMMAND_GROUPS + + for prefix, middle, suffix in ((["--format", "json"], [], []), + ([], ["--format", "json"], []), ([], [], ["--format", "json"])): + args = build_parser().parse_args([ + *prefix, "remote-authority", *middle, "inspect", "--goal-id", "goal", "--agent-id", "actor", *suffix, + ]) + assert output_format(args, "inspection_format") == "json" + assert "remote-authority inspect" in json.dumps(COMMAND_GROUPS) diff --git a/tests/control_plane_ts/remote_authority_client.test.ts b/tests/control_plane_ts/remote_authority_client.test.ts index 62d5b5bd4a..7d124b9b01 100644 --- a/tests/control_plane_ts/remote_authority_client.test.ts +++ b/tests/control_plane_ts/remote_authority_client.test.ts @@ -22,7 +22,8 @@ import { type RemoteAuthorityMode, type RemoteAuthorityRequest, } from "../../loopx/control_plane/coordination/remote_authority_contract.ts"; -import {callRemoteAuthority} from "../../loopx/control_plane/coordination/remote_authority_http.ts"; +import {callRemoteAuthority, observeRemoteAuthorityCall} from "../../loopx/control_plane/coordination/remote_authority_http.ts"; +import {inspectRemoteAuthority} from "../../loopx/control_plane/coordination/remote_authority_inspection.ts"; const storeIdentity = `postgresql:${"c".repeat(32)}`; const credential = `fixture-${"a".repeat(48)}`; @@ -311,3 +312,104 @@ test("callRemoteAuthority, CLI client and probe verify TLS and classify transpor assert.equal(probeResult.code, 0); assert.equal(probeResult.stdout, "verified\n"); }); + +test("inspection distinguishes safe read diagnostics and never requests a mutation or retry", async t => { + const tls = await tlsFixture(t); + let behavior = "found", requests = 0; + const server = createServer({key: tls.key, cert: tls.cert}, async (req, res) => { + requests++; + assert.equal(req.url, "/v0/tasks/execute"); + assert.equal(req.headers.authorization, `Bearer ${credential}`); + const chunks: Buffer[] = []; + for await (const chunk of req) chunks.push(Buffer.from(chunk)); + const request = decodeRemoteAuthorityRequest(JSON.parse(Buffer.concat(chunks).toString("utf8"))); + assert.equal(request.operation, "read"); + assert.equal(request.todo_id, "todo_one"); + if (behavior.startsWith("http-")) {res.writeHead(Number(behavior.slice(5))).end(credential); return;} + if (behavior === "invalid") {res.end(`not-json-${credential}`); return;} + if (behavior === "oversized") {res.end("x".repeat(65537)); return;} + if (behavior === "timeout") return; + if (behavior === "truncated") {res.writeHead(200, {"content-length": "1000"}); res.write("{"); setImmediate(() => res.destroy()); return;} + let result: JsonObject = {status: "found", provider_revision: `${storeIdentity}:1`, + todo: {todo_id: request.todo_id ?? "", status: "open"}, lease: null}; + if (behavior === "missing") result = {status: "missing", provider_revision: `${storeIdentity}:1`}; + if (behavior === "principal_unauthenticated" || behavior === "remote_authority_scope_denied" || behavior === "unknown-rejection") { + result = {status: "rejected", reason_code: behavior === "unknown-rejection" ? credential : behavior}; + } + if (behavior === "unavailable") result = {status: "unavailable", reason_code: "private-service-detail"}; + let packet = remoteAuthorityResponse(request, "execute", result); + if (behavior === "scoped") packet = remoteAuthorityResponse(request, "execute", { + status: "found", todo: {todo_id: request.todo_id ?? "", status: "open"}, lease: null, + goal_ref: {goal_id: request.goal_id, goal_instance_id: "ginst_" + "a".repeat(32)}, + }, REMOTE_AUTHORITY_SCOPED_READ_RESPONSE); + if (behavior === "wrong-correlation") packet.request_sha256 = "0".repeat(64); + res.end(JSON.stringify(packet)); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + t.after(() => {server.closeAllConnections(); server.close();}); + const endpoint = `https://127.0.0.1:${(server.address() as AddressInfo).port}`; + const config = {enabled: true, endpoint, tenant_id: "tenant-one", actor_id: "actor-a", + store_identity: storeIdentity, probe_todo_id: "todo_one", ca_file: tls.certPath, + operation: "claim", request_id: "must-be-ignored", rejectUnauthorized: false}; + const input = {goal_registered: true, actor_registered: true, goal_id: "goal-one", + agent_id: "actor-a", credential, config}; + const cases = [ + ["found", "read_verified"], ["scoped", "read_verified"], ["missing", "todo_missing"], + ["principal_unauthenticated", "unauthenticated"], ["remote_authority_scope_denied", "scope_denied"], + ["unknown-rejection", "rejected"], ["unavailable", "read_unverified"], + ["invalid", "response_invalid"], ["wrong-correlation", "response_invalid"], + ["oversized", "response_too_large"], ["truncated", "connection"], ["timeout", "timeout"], + ["http-401", "http"], ["http-403", "http"], ["http-503", "http"], + ]; + for (const [mode, reason] of cases) { + behavior = mode!; + const before = requests; + const result = await inspectRemoteAuthority(input); + assert.equal(result.reason_code, `remote_authority_${reason}`, mode); + assert.equal(result.ok, reason === "read_verified", mode); + assert.equal(result.execution_admitted, false); + assert.equal(requests, before + 1, "exactly one read, no automatic retry"); + if (mode!.startsWith("http-")) assert.equal(result.http_status, Number(mode!.slice(5))); + for (const secret of [credential, endpoint, storeIdentity, tls.certPath, "tenant-one", "actor-a", "todo_one", "private-service-detail"]) { + assert.equal(JSON.stringify(result).includes(secret), false, secret); + } + } + const before = requests; + assert.equal((await inspectRemoteAuthority({...input, config: {...config, ca_file: null}})).reason_code, "remote_authority_tls"); + assert.equal(requests, before, "untrusted certificate never reaches HTTP handler"); + + for (const [patch, reason] of [ + [{goal_registered: false}, "goal_unregistered"], [{actor_registered: false}, "actor_unregistered"], + [{config: {...config, enabled: false}}, "disabled"], [{config: {...config, tenant_id: ""}}, "binding_incomplete"], + [{agent_id: "other"}, "actor_mismatch"], [{credential: null}, "credential_required"], + [{credential: "short"}, "credential_invalid"], [{config: {...config, endpoint: "http://localhost"}}, "endpoint_invalid"], + [{config: {...config, store_identity: "invalid"}}, "binding_invalid"], + [{config: {...config, ca_file: "relative.pem"}}, "ca_invalid"], + ] as const) { + assert.equal((await inspectRemoteAuthority({...input, ...patch})).reason_code, `remote_authority_${reason}`); + assert.equal(requests, before, "invalid local configuration must not contact the service"); + } +}); + +test("transport observations cannot turn uncertain writes or recovery into permission to execute", async t => { + const tls = await tlsFixture(t); + let requests = 0; + const server = createServer({key: tls.key, cert: tls.cert}, (_req, res) => { + requests++; res.writeHead(401).end("untrusted-details"); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + t.after(() => {server.closeAllConnections(); server.close();}); + const endpoint = `https://127.0.0.1:${(server.address() as AddressInfo).port}`; + for (const mode of ["execute", "recover"] as const) { + const observed = await observeRemoteAuthorityCall(endpoint, credential, claimRequest(), {ca: tls.cert, mode}); + assert.equal(observed.response.status, mode === "execute" ? "ambiguous" : "unavailable"); + assert.equal(observed.response.reason_code, "remote_authority_transport_uncertain"); + assert.deepEqual(observed.transport, {kind: "http", httpStatus: 401}); + assert.deepEqual(await callRemoteAuthority(endpoint, credential, claimRequest(), {ca: tls.cert, mode}), observed.response); + } + assert.equal(requests, 4); + await new Promise(resolve => server.close(() => resolve())); + const refused = await observeRemoteAuthorityCall(endpoint, credential, claimRequest(), {ca: tls.cert}); + assert.equal(refused.transport?.kind, "connection_refused"); + assert.equal(refused.response.status, "ambiguous"); +}); diff --git a/tests/test_chat_remote_authority_inspection.py b/tests/test_chat_remote_authority_inspection.py new file mode 100644 index 0000000000..6fb65f2958 --- /dev/null +++ b/tests/test_chat_remote_authority_inspection.py @@ -0,0 +1,80 @@ +"""The App's explicit read uses the same typed inspection owner as the CLI.""" + +import json +import threading +from contextlib import contextmanager +from urllib.error import HTTPError +from urllib.request import Request, urlopen + +import pytest + +from examples.control_plane.quota_plan_fixtures import SCOPED_AGENT_ID, write_cli_fixture +from loopx.chat_server import ChatHTTPServer, ChatRequestHandler +from tests.control_plane.remote_authority_inspection_fixture import ( + CREDENTIAL, bind_remote_authority, remote_authority_service, +) + +PATH = "/api/chat/goal-configuration/remote-authority/inspect" + + +@contextmanager +def inspection_api(registry, runtime, *, assets=None): + server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler) + server.registry_path, server.runtime_root, server.verbose = registry, runtime, False + if assets is not None: + server.assets_dir = assets + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_port}" + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) + + +def inspect(origin, body, *, browser_origin=None): + request = Request(origin + PATH, data=json.dumps(body).encode(), method="POST", + headers={"Content-Type": "application/json", "Origin": browser_origin or origin}) + try: + response = urlopen(request, timeout=10) + except HTTPError as error: + response = error + with response: + return response.status, json.load(response) + + +def test_app_inspects_bound_actor_without_mutation_and_recovers(tmp_path, monkeypatch): + registry, runtime, _ = write_cli_fixture(tmp_path, scoped_agents=True) + monkeypatch.setenv("LOOPX_AUTHORITY_CREDENTIAL", CREDENTIAL) + with remote_authority_service(tmp_path, SCOPED_AGENT_ID) as (cfg, control), inspection_api(registry, runtime) as origin: + bind_remote_authority(registry, "full-speed", cfg) + before = {p: p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()} + for mode, reason in (("found", "read_verified"), ("denied", "scope_denied"), ("found", "read_verified")): + control["mode"] = mode + status, result = inspect(origin, {"goal_id": "full-speed"}) + assert status == 200 + assert result["goal_id"] == "full-speed" + assert result["inspection"]["reason_code"] == f"remote_authority_{reason}" + assert result["inspection"]["execution_admitted"] is False + assert CREDENTIAL not in json.dumps(result) and cfg["endpoint"] not in json.dumps(result) + assert before == {p: p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()} + assert len(control["requests"]) == 3 + assert all(req[1]["actor_id"] == SCOPED_AGENT_ID for req in control["requests"]) + _, disabled = inspect(origin, {"goal_id": "half-speed"}) + assert disabled["inspection"]["reason_code"] == "remote_authority_disabled" + assert len(control["requests"]) == 3 + + +@pytest.mark.parametrize("extra", [{"endpoint": "https://example.invalid"}, {"credential": "secret"}, + {"agent_id": "other"}, {"registry_path": "private-path"}]) +def test_app_rejects_binding_overrides_and_foreign_origins(tmp_path, monkeypatch, extra): + registry, runtime, _ = write_cli_fixture(tmp_path, scoped_agents=True) + monkeypatch.setenv("LOOPX_AUTHORITY_CREDENTIAL", CREDENTIAL) + with remote_authority_service(tmp_path, SCOPED_AGENT_ID) as (cfg, control), inspection_api(registry, runtime) as origin: + bind_remote_authority(registry, "full-speed", cfg) + status, _ = inspect(origin, {"goal_id": "full-speed", **extra}) + assert status == 400 + status, _ = inspect(origin, {"goal_id": "full-speed"}, browser_origin="https://example.invalid") + assert status == 403 + assert control["requests"] == [] diff --git a/tests/test_core_distribution.py b/tests/test_core_distribution.py index c2c4144012..6fb4ece261 100644 --- a/tests/test_core_distribution.py +++ b/tests/test_core_distribution.py @@ -224,6 +224,35 @@ def _environment(python, overrides=None): return env +def test_installed_core_inspects_remote_authority_without_checkout(core_python, tmp_path): + from tests.control_plane.remote_authority_inspection_fixture import CREDENTIAL, remote_authority_service + + registry = tmp_path / "projects.json" + runtime = tmp_path / "runtime" + with remote_authority_service(tmp_path, "fixture-actor") as (config, control): + # A synthetic registered binding is all inspection needs; no local task + # creation, cloud package, examples tree or editable source installation. + registry.write_text(json.dumps({"goals": [{"id": "fixture-goal", + "registered_agents": ["fixture-actor"], "remote_authority": config}]}), encoding="utf-8") + before = registry.read_bytes() + arguments = ["--registry", str(registry), "--runtime-root", str(runtime), + "remote-authority", "inspect", "--goal-id", "fixture-goal", + "--agent-id", "fixture-actor", "--format", "json"] + for mode, reason in (("found", "read_verified"), ("denied", "scope_denied"), + ("http", "http"), ("invalid", "response_invalid")): + control["mode"] = mode + result = _run(core_python, arguments, tmp_path, + environment={"LOOPX_AUTHORITY_CREDENTIAL": CREDENTIAL}, expected=0 if mode == "found" else 1) + packet = json.loads(result.stdout) + assert packet["reason_code"] == f"remote_authority_{reason}" + assert packet["execution_admitted"] is False + assert CREDENTIAL not in result.stdout + result.stderr + assert config["endpoint"] not in result.stdout + result.stderr + assert registry.read_bytes() == before + assert not runtime.exists() + assert len(control["requests"]) == 4 + + def _run(python, arguments, cwd, *, environment=None, expected=0): result = subprocess.run(_command(python, arguments), cwd=cwd, env=_environment(python, environment),