diff --git a/.agents/skills/nemoclaw-contributor-create-pr/SKILL.md b/.agents/skills/nemoclaw-contributor-create-pr/SKILL.md index 0d87d272a2f..b8cc15a0a21 100644 --- a/.agents/skills/nemoclaw-contributor-create-pr/SKILL.md +++ b/.agents/skills/nemoclaw-contributor-create-pr/SKILL.md @@ -8,7 +8,7 @@ description: Create or update a NemoClaw pull request with its authoring-session # Create or Update a Pull Request -Session reporting follows v1 PR #13918 at `7238cbdff9`, retaining its notices and report contract. Main retains its publication and validation requirements. +Session reporting retains the format from v1 PR #13918. Main also accepts reports posted by repository maintainers, including when they take over an existing PR. Before publication, follow [Validation](references/validation.md) and [Publication](references/publication.md). For an open PR, first follow the [PR follow-up contract](../_shared/pr-follow-up.md); route valid code repairs to `nemoclaw-contributor-implement-issue`. These references own trusted-base validation, source-repository selection, guarded writes, verified commits, DCO, draft handling, and review follow-up. Follow [Writing and review](../_shared/documentation-writing-review.md) for PR text. @@ -22,11 +22,11 @@ When changing live E2E evidence, require the implementation handoff to apply [De /tmp/pr-session-report report-comment.md ``` -3. Publish through the [publication procedure](references/publication.md), preserving main’s description sections, DCO, and draft requirements. Read all pages of PR comments before posting, including after an uncertain retry; reuse an existing opening report by the PR author instead of duplicating it. If absent, post once as the PR author with `gh pr comment NUMBER --body-file report-comment.md`. -4. Read back the description and comments. Verify the description has no report, exactly one opening report by the PR author exists, and its contents match the intended report. Keep the exact summary `Authoring session — opening`. Validate the retrieved files with `/tmp/pr-session-report --pr description.md author-comment-1.md author-comment-2.md`; pass every PR-author comment, including later reports and unrelated comments. Comments by others are ignored; a maintainer's comment cannot substitute for an automated PR author's report. +3. Publish through the [publication procedure](references/publication.md), preserving main’s description sections, DCO, and draft requirements. Read all pages of PR comments before posting, including after an uncertain retry. Reuse an existing opening report from the PR author or a repository maintainer. If absent, either may post it with `gh pr comment NUMBER --body-file report-comment.md`. When a maintainer takes over an existing or automated PR, do not require the original author to post the report or add a separate takeover record. +4. Read back the description and comments. Verify the description has no report, exactly one eligible opening report exists, and its contents match the intended report. CI accepts the PR author and accounts with repository `maintain` or `admin` permission, verified through GitHub's collaborator-permission API. Keep the exact summary `Authoring session — opening`. Validate the retrieved files with `/tmp/pr-session-report --pr description.md report-comment-1.md report-comment-2.md`; pass comments from eligible accounts, including later reports and unrelated comments. Ignore reports from other accounts. 5. Follow checks and automated reviews on the latest commit. If the metadata job fetched comments before the opening report was posted, wait for that run to finish, then use `gh run rerun --job JOB_ID` for its failed `commit-lint` job. Select the job from this PR's latest-revision run; a rerun retains the original revision but fetches current comments. Reruns require repository write permission, so external contributors may need a maintainer. Confirm the rerun passes. -CI fetches the description and all comment pages on PR opening, updates, reopening, and description/title edits. It checks the presence and format of the PR author's opening report, not the truth or completeness of its evidence. Fetch failures fail the check. Comment posting, editing, or deletion alone does not trigger a refresh; rerun the metadata job after such changes. +CI fetches the description and all comment pages on PR opening, updates, reopening, and description/title edits. It checks the report's presence, format, and posting account's eligibility, not the truth or completeness of its evidence. Comment or permission fetch failures fail the check. Comment posting, editing, or deletion alone does not trigger a refresh; rerun the metadata job after such changes. The check uses the candidate checkout's validator and workflow. It does not protect against a PR changing its own validation; trusted-base enforcement is outside this check's scope. @@ -34,7 +34,7 @@ Preserve historical reports and their cutoffs. Optional later commit or merge re ## Session Report -Report the session that wrote the change, up to a cutoff you state; if this session only publishes the PR, mark every row unavailable. +Report the session that wrote the change, up to a cutoff you state. When publishing or taking over a PR without the original authoring-session evidence, mark the fields unavailable; the report does not need to come from the person who wrote the change. Give each row one status: - `recorded`: the session record covers the whole session. diff --git a/.github/workflows/commit-lint.yaml b/.github/workflows/commit-lint.yaml index 8a73b41e77e..74b79e62956 100644 --- a/.github/workflows/commit-lint.yaml +++ b/.github/workflows/commit-lint.yaml @@ -62,11 +62,16 @@ jobs: mkdir -p "$input" gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq '.body // ""' > "$input/description.md" gh api --paginate --slurp "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments?per_page=100" > "$input/comments.json" - jq -r --argjson author "$PR_AUTHOR_ID" '.[][] | select(.user.id == $author) | .body | @base64' "$input/comments.json" > "$input/author-comments.b64" + printf '%s\n' "$PR_AUTHOR_ID" > "$input/reporters.jsonl" + jq -r --argjson author "$PR_AUTHOR_ID" '.[][] | select(.user.id != $author and ((.body // "") | contains("Authoring session — opening"))) | .user.login' "$input/comments.json" | sort -u > "$input/reporters.txt" + while IFS= read -r login; do + gh api "repos/$GITHUB_REPOSITORY/collaborators/$login/permission" --jq 'select(.role_name == "maintain" or .role_name == "admin") | .user.id' >> "$input/reporters.jsonl" + done < "$input/reporters.txt" + jq -r --slurpfile reporters "$input/reporters.jsonl" '.[][] | select(.user.id as $id | $reporters | index($id)) | .body | @base64' "$input/comments.json" > "$input/report-comments.b64" comments=() while IFS= read -r encoded; do path="$input/comment-${#comments[@]}.md" printf '%s' "$encoded" | base64 --decode > "$path" comments+=("$path") - done < "$input/author-comments.b64" + done < "$input/report-comments.b64" "$RUNNER_TEMP/report-check" --pr "$input/description.md" "${comments[@]}" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 86f08355e70..b12b9c11f87 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -189,7 +189,7 @@ owns the automated publication and review-follow-up workflow. The root Every PR includes a collapsed opening [authoring-session report](.agents/skills/nemoclaw-contributor-create-pr/SKILL.md#session-report) comment, including existing and automated PRs. Post the report when opening a PR, or on the next update to an existing PR. -The metadata job checks the PR author's posted comment and the shared template. Use unavailable fields when historical evidence is missing; preserve existing evidence and cutoffs. After posting, rerun a failed metadata job for the current PR revision. Comment events alone do not refresh this check. +The PR author or a repository maintainer may post the report, including when taking over an existing or automated PR. CI verifies maintainer eligibility through repository `maintain` or `admin` permission. Use unavailable fields when historical evidence is missing; preserve existing evidence and cutoffs. After posting, rerun a failed metadata job for the current PR revision. Comment events alone do not refresh this check. After each revision, follow CI and review to completion. Address valid findings with a change, or explain why they do not apply. Keep the PR description and validation evidence current. diff --git a/src/lib/onboard/__test-helpers__/compatible-endpoint-smoke-helpers.ts b/src/lib/onboard/__test-helpers__/compatible-endpoint-smoke-helpers.ts index 583cfabcd12..e4ca30f8d86 100644 --- a/src/lib/onboard/__test-helpers__/compatible-endpoint-smoke-helpers.ts +++ b/src/lib/onboard/__test-helpers__/compatible-endpoint-smoke-helpers.ts @@ -169,6 +169,13 @@ export function runProviderNeutralScript(options: { denialBytes?: readonly number[]; denialOversized?: boolean; directError?: "connection-refused" | "dns" | "timeout"; + directAddresses?: readonly string[]; + directOutcomes?: Readonly< + Record< + string, + "connection-refused" | "network-unreachable" | "host-unreachable" | "timeout" | "http-200" + > + >; managedProxyResponses?: unknown[]; inferenceUrl?: string; expectedAuthorization?: string; @@ -191,7 +198,7 @@ export function runProviderNeutralScript(options: { const prelude = ` import atexit import errno -import io +import http.client import json import socket import time @@ -204,9 +211,15 @@ managed_proxy_responses = json.loads(${JSON.stringify( )}) managed_proxy_enabled = ${options.managedProxyResponses === undefined ? "False" : "True"} denial_bytes = ${denialBody} +direct_addresses = json.loads(${JSON.stringify( + JSON.stringify(options.directAddresses ?? ["192.168.65.254"]), + )}) +direct_outcomes = json.loads(${JSON.stringify(JSON.stringify(options.directOutcomes ?? {}))}) inference_request_tokens = [] direct_request_count = [] direct_request_urls = [] +direct_request_addresses = [] +direct_request_hosts = [] managed_proxy_request_count = [] managed_proxy_request_urls = [] sleep_delays = [] @@ -216,6 +229,8 @@ def emit_request_evidence(): print("INFERENCE_REQUEST_TOKENS=" + ",".join(str(value) for value in inference_request_tokens)) print("DIRECT_REQUEST_COUNT=" + str(len(direct_request_count))) print("DIRECT_REQUEST_URLS=" + ",".join(direct_request_urls)) + print("DIRECT_REQUEST_ADDRESSES=" + ",".join(direct_request_addresses)) + print("DIRECT_REQUEST_HOSTS=" + ",".join(direct_request_hosts)) print("MANAGED_PROXY_REQUEST_COUNT=" + str(len(managed_proxy_request_count))) print("MANAGED_PROXY_REQUEST_URLS=" + ",".join(managed_proxy_request_urls)) print("SLEEP_DELAYS=" + ",".join(str(value) for value in sleep_delays)) @@ -236,6 +251,12 @@ class FakeResponse: return b"x" * (size if size >= 0 else 1048577) return self.payload if size < 0 else self.payload[:size] +class FakeDirectResponse: + def __init__(self, status): + self.status = status + def read(self, size=-1): + return denial_bytes if size < 0 else denial_bytes[:size] + class FakeOpener: def open(self, request, timeout): if request.full_url == ${JSON.stringify(options.inferenceUrl ?? "https://inference.local/v1/chat/completions")}: @@ -246,22 +267,65 @@ class FakeOpener: inference_request_tokens.append( request_data.get("max_tokens", request_data.get("max_completion_tokens")) ) + if responses[0] == "__timeout__": + raise TimeoutError("timed out after %s seconds" % timeout) + if responses[0] == "__wrapped_timeout__": + raise urllib.error.URLError(TimeoutError("timed out after %s seconds" % timeout)) return FakeResponse(200, responses.pop(0)) - direct_request_count.append(1) - direct_request_urls.append(request.full_url) - if direct_error == "connection-refused": - raise urllib.error.URLError(ConnectionRefusedError(errno.ECONNREFUSED, "refused")) - if direct_error == "dns": - raise urllib.error.URLError(socket.gaierror(socket.EAI_NONAME, "not known")) - if direct_error == "timeout": - raise urllib.error.URLError(TimeoutError("timed out")) - raise urllib.error.HTTPError( - request.full_url, - 403, - "Forbidden", - {}, - io.BytesIO(denial_bytes), + raise RuntimeError("unexpected direct request through inference opener") + +def fake_getaddrinfo(host, port, type=0): + if direct_error == "dns": + raise socket.gaierror(socket.EAI_NONAME, "not known") + return [ + ( + socket.AF_INET6 if ":" in address else socket.AF_INET, + socket.SOCK_STREAM, + socket.IPPROTO_TCP, + "", + (address, port, 0, 0) if ":" in address else (address, port), ) + for address in direct_addresses + ] + +class FakeSocket: + def __init__(self, family, type): + self.address = None + def __enter__(self): + return self + def __exit__(self, exc_type, exc, traceback): + return False + def settimeout(self, timeout): + pass + def connect(self, sockaddr): + self.address = sockaddr[0] + direct_request_count.append(1) + direct_request_urls.append(direct_url) + direct_request_addresses.append(self.address) + outcome = direct_outcomes.get(self.address, direct_error) + if outcome == "connection-refused": + raise ConnectionRefusedError(errno.ECONNREFUSED, "refused") + if outcome == "network-unreachable": + raise OSError(errno.ENETUNREACH, "network unreachable") + if outcome == "host-unreachable": + raise OSError(errno.EHOSTUNREACH, "host unreachable") + if outcome == "timeout": + raise TimeoutError("timed out") + +class FakeHTTPConnection: + def __init__(self, host, port, timeout): + self.sock = None + def request(self, method, path, body, headers): + direct_request_hosts.append(headers.get("Host")) + def getresponse(self): + outcome = direct_outcomes.get(self.sock.address, direct_error) + return FakeDirectResponse(200 if outcome == "http-200" else 403) + def close(self): + pass + +socket.getaddrinfo = fake_getaddrinfo +socket.socket = FakeSocket +http.client.HTTPConnection = FakeHTTPConnection class ManagedProxyOpener: def open(self, request, timeout): @@ -276,11 +340,7 @@ class ManagedProxyOpener: return FakeResponse(200, managed_proxy_responses.pop(0)) def build_test_opener(*handlers): - proxy_disabled = any( - isinstance(handler, urllib.request.ProxyHandler) and handler.proxies == {} - for handler in handlers - ) - if managed_proxy_enabled and not proxy_disabled: + if managed_proxy_enabled: return ManagedProxyOpener() return FakeOpener() diff --git a/src/lib/onboard/compatible-endpoint-smoke.test.ts b/src/lib/onboard/compatible-endpoint-smoke.test.ts index 01f941e2114..23044712fbe 100644 --- a/src/lib/onboard/compatible-endpoint-smoke.test.ts +++ b/src/lib/onboard/compatible-endpoint-smoke.test.ts @@ -1,13 +1,14 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { describe, expect, it, vi } from "vitest"; import type { OpenShellSandboxBufferedCommandRequest } from "../adapters/openshell/sandbox-command"; import { + providerNeutralResponses, + runProviderNeutralScript, runSmokeScript, writeFakeCurl, writeFakeSleep, @@ -118,177 +119,6 @@ const allAgentProofAuthorities = [ }, ] as const satisfies readonly { agentName: string; authority: ProviderNeutralAuthority }[]; -function providerNeutralResponses( - model: string, - includeToolCall = true, - toolArguments: unknown = "{}", -): unknown[] { - return [ - { model, choices: [{ message: { content: "PONG" } }] }, - { - model, - choices: [ - { - message: { - tool_calls: includeToolCall - ? [ - { - function: { - name: "nemoclaw_route_probe", - arguments: toolArguments, - }, - }, - ] - : [], - }, - }, - ], - }, - ]; -} - -function runProviderNeutralScript(options: { - authority: ProviderNeutralAuthority; - model?: string; - script?: string; - responses?: unknown[]; - denial?: unknown; - denialBytes?: readonly number[]; - denialOversized?: boolean; - directError?: "connection-refused" | "dns" | "timeout"; - managedProxyResponses?: unknown[]; -}) { - const model = options.model ?? "qwen3.5-9b"; - const directAuthority = `host.openshell.internal:${String(options.authority.directHostPort)}`; - const responses = options.responses ?? providerNeutralResponses(model); - const denial = - options.denial ?? - ({ - error: "policy_denied", - detail: `POST ${directAuthority}/v1/chat/completions not permitted by policy`, - } satisfies Record); - const denialBytes = - options.denialBytes ?? Array.from(Buffer.from(JSON.stringify(denial), "utf8")); - const denialBody = options.denialOversized - ? 'b"x" * 1048577' - : `bytes(${JSON.stringify(denialBytes)})`; - const prelude = ` -import atexit -import errno -import io -import json -import socket -import time -import urllib.error -import urllib.request - -responses = json.loads(${JSON.stringify(JSON.stringify(responses))}) -managed_proxy_responses = json.loads(${JSON.stringify( - JSON.stringify(options.managedProxyResponses ?? []), - )}) -managed_proxy_enabled = ${options.managedProxyResponses === undefined ? "False" : "True"} -denial_bytes = ${denialBody} -inference_request_tokens = [] -direct_request_count = [] -direct_request_urls = [] -managed_proxy_request_count = [] -managed_proxy_request_urls = [] -sleep_delays = [] -direct_error = ${options.directError === undefined ? "None" : JSON.stringify(options.directError)} - -def emit_request_evidence(): - print("INFERENCE_REQUEST_TOKENS=" + ",".join(str(value) for value in inference_request_tokens)) - print("DIRECT_REQUEST_COUNT=" + str(len(direct_request_count))) - print("DIRECT_REQUEST_URLS=" + ",".join(direct_request_urls)) - print("MANAGED_PROXY_REQUEST_COUNT=" + str(len(managed_proxy_request_count))) - print("MANAGED_PROXY_REQUEST_URLS=" + ",".join(managed_proxy_request_urls)) - print("SLEEP_DELAYS=" + ",".join(str(value) for value in sleep_delays)) - -atexit.register(emit_request_evidence) - -class FakeResponse: - def __init__(self, status, payload): - self.status = status - self.payload_source = payload - self.payload = json.dumps(payload).encode("utf-8") - def __enter__(self): - return self - def __exit__(self, exc_type, exc, traceback): - return False - def read(self, size=-1): - if isinstance(self.payload_source, dict) and self.payload_source.get("__oversized__") is True: - return b"x" * (size if size >= 0 else 1048577) - return self.payload if size < 0 else self.payload[:size] - -class FakeOpener: - def open(self, request, timeout): - if request.full_url.startswith("https://inference.local/"): - if not responses: - raise RuntimeError("test response queue exhausted") - request_data = json.loads(request.data.decode("utf-8")) - inference_request_tokens.append( - request_data.get("max_tokens", request_data.get("max_completion_tokens")) - ) - if responses[0] == "__timeout__": - raise TimeoutError("timed out after %s seconds" % timeout) - if responses[0] == "__wrapped_timeout__": - raise urllib.error.URLError(TimeoutError("timed out after %s seconds" % timeout)) - return FakeResponse(200, responses.pop(0)) - direct_request_count.append(1) - direct_request_urls.append(request.full_url) - if direct_error == "connection-refused": - raise urllib.error.URLError(ConnectionRefusedError(errno.ECONNREFUSED, "refused")) - if direct_error == "dns": - raise urllib.error.URLError(socket.gaierror(socket.EAI_NONAME, "not known")) - if direct_error == "timeout": - raise urllib.error.URLError(TimeoutError("timed out")) - raise urllib.error.HTTPError( - request.full_url, - 403, - "Forbidden", - {}, - io.BytesIO(denial_bytes), - ) - -class ManagedProxyOpener: - def open(self, request, timeout): - managed_proxy_request_count.append(1) - managed_proxy_request_urls.append(request.full_url) - if not managed_proxy_responses: - raise urllib.error.URLError(ConnectionRefusedError(errno.ECONNREFUSED, "refused")) - request_data = json.loads(request.data.decode("utf-8")) - inference_request_tokens.append( - request_data.get("max_tokens", request_data.get("max_completion_tokens")) - ) - return FakeResponse(200, managed_proxy_responses.pop(0)) - -def build_test_opener(*handlers): - proxy_disabled = any( - isinstance(handler, urllib.request.ProxyHandler) and handler.proxies == {} - for handler in handlers - ) - if managed_proxy_enabled and not proxy_disabled: - return ManagedProxyOpener() - return FakeOpener() - -urllib.request.build_opener = build_test_opener -time.sleep = lambda seconds: sleep_delays.append(seconds) -`; - const script = - options.script ?? buildProviderNeutralInferenceSandboxSmokeScript(model, options.authority); - return spawnSync("python3", ["-c", `${prelude}\n${script}`], { - encoding: "utf8", - env: - options.managedProxyResponses === undefined - ? process.env - : { - ...process.env, - HTTPS_PROXY: "http://openshell-runtime-proxy.invalid:8080", - NO_PROXY: "", - }, - }); -} - describe("compatible endpoint sandbox smoke helpers", () => { const providerMetadata = (name: string): string => [ @@ -723,12 +553,10 @@ describe("compatible endpoint sandbox smoke helpers", () => { `host.openshell.internal:${String(port)}/v1/chat/completions`, ); expect(sandboxCommand[7]).toContain('direct_method = "POST"'); - expect(sandboxCommand[7]).toContain("method=direct_method"); expect(sandboxCommand[7]).toContain('response_data.get("model") != model'); expect(sandboxCommand[7]).toContain('"tool_choice"'); expect(sandboxCommand[7]).toContain('direct_denial_error = "policy_denied"'); expect(sandboxCommand[7]).toContain('denial.get("error") != direct_denial_error'); - expect(sandboxCommand[7]).toContain("ProxyHandler({})"); expect(sandboxCommand[7]).not.toContain("curl"); }, ); @@ -794,16 +622,13 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(script).toContain('denial.get("error") != direct_denial_error'); expect(script).toContain("host.openshell.internal:8001/v1/chat/completions"); expect(script).toContain('direct_method = "POST"'); - expect(script).toContain("method=direct_method"); expect(script).toContain("max_tokens_field: 1"); expect(script).toContain('response_data.get("model") != model'); expect(script).toContain('"tool_choice"'); expect(script).toContain("direct_denial_contract_version = 1"); expect(script).toContain('direct_denial_error = "policy_denied"'); - expect(script).toContain("error.read(max_response_bytes + 1)"); expect(script).toContain('denial_bytes.decode("utf-8", errors="strict")'); expect(script).toContain("direct_deny_timeout_seconds = 10"); - expect(script).toContain("ProxyHandler({})"); expect(script).not.toContain("curl"); }); @@ -816,6 +641,9 @@ describe("compatible endpoint sandbox smoke helpers", () => { expect(result.stdout).toContain("INFERENCE_SMOKE_OK PONG"); expect(result.stdout).toContain("INFERENCE_REQUEST_TOKENS=512,512"); expect(result.stdout).toContain("DIRECT_REQUEST_COUNT=1"); + expect(result.stdout).toContain( + `DIRECT_REQUEST_HOSTS=host.openshell.internal:${String(authority.directHostPort)}`, + ); }, ); @@ -1004,7 +832,7 @@ describe("compatible endpoint sandbox smoke helpers", () => { ); it.each(allAgentProofAuthorities)( - "accepts exact connection refusal as a direct-host deny proof for $agentName (#9211)", + "accepts refused direct access after authorized inference for $agentName (#9211)", ({ authority }) => { const result = runProviderNeutralScript({ authority, directError: "connection-refused" }); @@ -1013,6 +841,81 @@ describe("compatible endpoint sandbox smoke helpers", () => { }, ); + it.each(["network-unreachable", "host-unreachable"] as const)( + "checks IPv4 after a %s IPv6 host bridge (#13518)", + (ipv6Outcome) => { + const result = runProviderNeutralScript({ + authority: allAgentProofAuthorities[0].authority, + directAddresses: ["fdc4:f303:9324::254", "192.168.65.254"], + directOutcomes: { + "fdc4:f303:9324::254": ipv6Outcome, + "192.168.65.254": "connection-refused", + }, + }); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain("INFERENCE_SMOKE_OK PONG"); + expect(result.stdout).toContain( + "DIRECT_REQUEST_ADDRESSES=fdc4:f303:9324::254,192.168.65.254", + ); + }, + ); + + it("rejects a reachable IPv4 route after an unreachable IPv6 host bridge (#13518)", () => { + const result = runProviderNeutralScript({ + authority: allAgentProofAuthorities[0].authority, + directAddresses: ["fdc4:f303:9324::254", "192.168.65.254"], + directOutcomes: { + "fdc4:f303:9324::254": "network-unreachable", + "192.168.65.254": "http-200", + }, + }); + + expect(result.status).toBe(1); + expect(result.stderr).toContain( + "direct host inference response was not an OpenShell policy denial", + ); + expect(result.stderr).toContain("fdc4:f303:9324::254 (network-unreachable)"); + expect(result.stderr).toContain("192.168.65.254 (unexpected-response)"); + expect(result.stdout).toContain("DIRECT_REQUEST_ADDRESSES=fdc4:f303:9324::254,192.168.65.254"); + }); + + it("checks every resolved address after a valid policy denial (#13518)", () => { + const result = runProviderNeutralScript({ + authority: allAgentProofAuthorities[0].authority, + directAddresses: ["fdc4:f303:9324::254", "192.168.65.254"], + directOutcomes: { "192.168.65.254": "http-200" }, + }); + + expect(result.status).toBe(1); + expect(result.stderr).toContain( + "direct host inference response was not an OpenShell policy denial", + ); + expect(result.stderr).toContain("fdc4:f303:9324::254 (policy-denied)"); + expect(result.stderr).toContain("192.168.65.254 (unexpected-response)"); + expect(result.stdout).toContain("DIRECT_REQUEST_ADDRESSES=fdc4:f303:9324::254,192.168.65.254"); + }); + + it("keeps direct failure diagnostics bounded and names the failing address", () => { + const directAddresses = Array.from({ length: 10 }, (_, index) => `192.0.2.${index + 1}`); + const directOutcomes: Record = Object.fromEntries( + directAddresses.map((address) => [address, "network-unreachable"]), + ); + directOutcomes["192.0.2.10"] = "http-200"; + const result = runProviderNeutralScript({ + authority: allAgentProofAuthorities[0].authority, + directAddresses, + directOutcomes, + }); + + expect(result.status).toBe(1); + expect(result.stderr).toContain("192.0.2.1 (network-unreachable)"); + expect(result.stderr).toContain("192.0.2.10 (unexpected-response)"); + expect(result.stderr).toContain("2 earlier outcomes omitted"); + expect(result.stderr).not.toContain("192.0.2.8 ("); + expect(result.stderr.length).toBeLessThan(600); + }); + it.each(["dns", "timeout"] as const)( "does not accept a %s transport error as a direct-host deny proof (#9211)", (directError) => { diff --git a/src/lib/onboard/compatible-endpoint-smoke.ts b/src/lib/onboard/compatible-endpoint-smoke.ts index 40f75570476..92a4e28b826 100644 --- a/src/lib/onboard/compatible-endpoint-smoke.ts +++ b/src/lib/onboard/compatible-endpoint-smoke.ts @@ -658,7 +658,7 @@ export function buildCompatibleEndpointSandboxSmokeCommand(model: string): strin /** * Runs a Python standard-library request inside the sandbox, proving a real - * chat response through the selected endpoint and explicit denial outside its policy. + * chat response through the selected endpoint and unavailable direct host access. */ export function buildProviderNeutralInferenceSandboxSmokeScript( model: string, @@ -712,6 +712,7 @@ auth_headers = {"Authorization": "Bearer " + credential}` : "auth_headers = {}"; return ` import errno +import http.client import json import os import re @@ -719,6 +720,7 @@ import socket import sys import time import urllib.error +import urllib.parse import urllib.request ${authSetup} @@ -729,7 +731,6 @@ max_tokens_field = ${maxTokensField} tool_calling_required = ${toolCallingRequired} max_response_bytes = 1048576 inference_opener = urllib.request.build_opener() -direct_opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) def post_inference(payload, label): request = urllib.request.Request( @@ -872,58 +873,113 @@ direct_denial_http_status = ${String(OPEN_SHELL_DIRECT_POLICY_DENIAL_CONTRACT.ht direct_denial_error = ${directDenialError} direct_denial_detail = ${directDenialDetail} direct_deny_timeout_seconds = ${String(PROVIDER_NEUTRAL_SMOKE_DIRECT_DENY_TIMEOUT_SECONDS)} -direct_request = urllib.request.Request( - direct_url, - data=json.dumps({ - "model": model, - "messages": [{"role": "user", "content": "Prove direct inference is denied."}], - max_tokens_field: 1, - }).encode("utf-8"), - headers={"Content-Type": "application/json"}, - method=direct_method, -) +direct_target = urllib.parse.urlsplit(direct_url) try: - with direct_opener.open(direct_request, timeout=direct_deny_timeout_seconds) as direct_response: - print( - "direct host inference route unexpectedly returned HTTP %s" % direct_response.status, - file=sys.stderr, + direct_addresses = list(dict.fromkeys( + (family, sockaddr) + for family, _, _, _, sockaddr in socket.getaddrinfo( + direct_target.hostname, direct_target.port, type=socket.SOCK_STREAM ) - sys.exit(1) -except urllib.error.HTTPError as error: - denial_bytes = error.read(max_response_bytes + 1) + if family in (socket.AF_INET, socket.AF_INET6) + )) +except OSError: + print("direct host inference deny could not be proven; address resolution failed", file=sys.stderr) + sys.exit(1) +if not direct_addresses: + print("direct host inference deny could not be proven; no usable address", file=sys.stderr) + sys.exit(1) +direct_probe_outcomes = [] +direct_probe_omitted_outcomes = 0 + +def record_direct_outcome(sockaddr, outcome): + global direct_probe_omitted_outcomes + entry = "%s (%s)" % (sockaddr[0], outcome) + # Keep the first seven outcomes and the latest result within the error budget. + if len(direct_probe_outcomes) < 8: + direct_probe_outcomes.append(entry) + else: + direct_probe_outcomes[-1] = entry + direct_probe_omitted_outcomes += 1 + +def fail_direct(message): + summary = ", ".join(direct_probe_outcomes) + if direct_probe_omitted_outcomes: + summary += ", %s earlier outcomes omitted" % direct_probe_omitted_outcomes + print("%s; direct outcomes: %s" % (message, summary), file=sys.stderr) + sys.exit(1) + +direct_body = json.dumps({ + "model": model, + "messages": [{"role": "user", "content": "Prove direct inference is denied."}], + max_tokens_field: 1, +}).encode("utf-8") +direct_deadline = time.monotonic() + direct_deny_timeout_seconds +for family, sockaddr in direct_addresses: + remaining = direct_deadline - time.monotonic() + if remaining <= 0: + record_direct_outcome(sockaddr, "deadline-exceeded") + fail_direct("direct host inference deny could not be proven") + with socket.socket(family, socket.SOCK_STREAM) as direct_socket: + direct_socket.settimeout(remaining) + try: + direct_socket.connect(sockaddr) + except OSError as error: + transport_outcome = { + errno.ECONNREFUSED: "connection-refused", + errno.ENETUNREACH: "network-unreachable", + errno.EHOSTUNREACH: "host-unreachable", + }.get(error.errno) + if transport_outcome: + record_direct_outcome(sockaddr, transport_outcome) + continue + record_direct_outcome(sockaddr, "connection-error") + fail_direct("direct host inference deny could not be proven") + direct_connection = http.client.HTTPConnection( + direct_target.hostname, direct_target.port, timeout=remaining + ) + direct_connection.sock = direct_socket + try: + direct_connection.request( + direct_method, + direct_target.path, + body=direct_body, + headers={"Content-Type": "application/json", "Host": direct_target.netloc}, + ) + direct_response = direct_connection.getresponse() + denial_bytes = direct_response.read(max_response_bytes + 1) + except (OSError, http.client.HTTPException): + record_direct_outcome(sockaddr, "request-error") + fail_direct("direct host inference deny could not be proven") + finally: + direct_connection.close() if len(denial_bytes) > max_response_bytes: - print("direct host inference policy-denial response exceeded byte limit", file=sys.stderr) - sys.exit(1) + record_direct_outcome(sockaddr, "response-too-large") + fail_direct("direct host inference policy-denial response exceeded byte limit") try: denial_text = denial_bytes.decode("utf-8", errors="strict") except UnicodeDecodeError: - print("direct host inference policy-denial response was not valid UTF-8", file=sys.stderr) - sys.exit(1) + record_direct_outcome(sockaddr, "invalid-utf8") + fail_direct("direct host inference policy-denial response was not valid UTF-8") try: denial = json.loads(denial_text) except json.JSONDecodeError: - print("direct host inference policy-denial response was not valid JSON", file=sys.stderr) - sys.exit(1) + record_direct_outcome(sockaddr, "invalid-json") + fail_direct("direct host inference policy-denial response was not valid JSON") detail = denial.get("detail") if isinstance(denial, dict) else None if ( - error.code != direct_denial_http_status + direct_response.status != direct_denial_http_status or not isinstance(denial, dict) or denial.get("error") != direct_denial_error ): - print("direct host inference response was not an OpenShell policy denial", file=sys.stderr) - sys.exit(1) + record_direct_outcome(sockaddr, "unexpected-response") + fail_direct("direct host inference response was not an OpenShell policy denial") if detail != direct_denial_detail: - print( + record_direct_outcome(sockaddr, "policy-format-drift") + fail_direct( "direct host inference OpenShell policy-denial contract v%s format drifted" - % direct_denial_contract_version, - file=sys.stderr, + % direct_denial_contract_version ) - sys.exit(1) -except urllib.error.URLError as error: - reason = error.reason - if not isinstance(reason, ConnectionRefusedError) or reason.errno != errno.ECONNREFUSED: - print("direct host inference deny could not be proven", file=sys.stderr) - sys.exit(1) + record_direct_outcome(sockaddr, "policy-denied") print("INFERENCE_SMOKE_OK " + content.strip()[:200]) `.trim(); diff --git a/tools/ci/pr-session-report-workflow.rs b/tools/ci/pr-session-report-workflow.rs index 256589293ee..64bf4628e27 100644 --- a/tools/ci/pr-session-report-workflow.rs +++ b/tools/ci/pr-session-report-workflow.rs @@ -29,12 +29,29 @@ gh() {{ 'api repos/example/repo/pulls/1 --jq .body // ""') printf 'Description\n' ;; 'api --paginate --slurp repos/example/repo/issues/1/comments?per_page=100') jq -n --rawfile report .github/SESSION_REPORT_TEMPLATE.md --arg scenario "$scenario" ' - [[range(100) | {{user: {{id: 8}}, body: $report}}], [{{user: {{id: 7}}, body: $report}}]] + [[range(100) | {{user: {{id: 8, login: "outsider"}}, body: $report}}], [{{user: {{id: 7, login: "author"}}, body: $report}}]] | if $scenario == "missing" then [] elif $scenario == "outsider" then .[:1] elif $scenario == "duplicate" then .[1] += .[1] elif $scenario == "malformed" then .[1][0].body |= gsub("Models"; "Skills") + elif $scenario == "maintainer" or $scenario == "permission_failure" or $scenario == "duplicate_maintainer" or $scenario == "malformed_maintainer" then .[1][0].user = {{id: 9, login: "maintainer"}} + elif $scenario == "admin" then .[1][0].user = {{id: 10, login: "admin"}} + elif $scenario == "writer" then .[1][0].user = {{id: 11, login: "writer"}} + elif $scenario == "triage" then .[1][0].user = {{id: 12, login: "triage"}} + else . end + | if $scenario == "duplicate_maintainer" then .[1] += .[1] + elif $scenario == "malformed_maintainer" then .[1][0].body |= gsub("Models"; "Skills") else . end' ;; + api\ repos/example/repo/collaborators/*/permission*) + if [ "$scenario" = permission_failure ]; then return 42; fi + case "$2" in + */maintainer/permission) identity='{{role_name: "maintain", user: {{id: 9}}}}' ;; + */admin/permission) identity='{{role_name: "admin", user: {{id: 10}}}}' ;; + */writer/permission) identity='{{role_name: "write", user: {{id: 11}}}}' ;; + */triage/permission) identity='{{role_name: "triage", user: {{id: 12}}}}' ;; + *) identity='{{role_name: "read", user: {{id: 8}}}}' ;; + esac + jq -n "$identity" | jq -r "${{@: -1}}" ;; *) return 43 ;; esac }} @@ -42,12 +59,12 @@ check() {{ {adapter} }} # A fresh invocation after publication must recover from the initial missing report. -for scenario in missing valid outsider duplicate malformed api_failure valid; do +for scenario in missing valid outsider maintainer admin writer triage duplicate duplicate_maintainer malformed malformed_maintainer api_failure permission_failure maintainer; do set +e (set -e; check) > "$RUNNER_TEMP/output" 2>&1 actual=$? set -e - case "$scenario" in valid) expected=0 ;; api_failure) expected=42 ;; *) expected=1 ;; esac + case "$scenario" in valid|maintainer|admin) expected=0 ;; api_failure|permission_failure) expected=42 ;; *) expected=1 ;; esac if [ "$actual" -ne "$expected" ]; then cat "$RUNNER_TEMP/output" >&2 printf '%s: expected %s, got %s\n' "$scenario" "$expected" "$actual" >&2 diff --git a/tools/ci/pr-session-report.rs b/tools/ci/pr-session-report.rs index 98b2e289454..7d09e88590d 100644 --- a/tools/ci/pr-session-report.rs +++ b/tools/ci/pr-session-report.rs @@ -94,14 +94,16 @@ fn check(args: &[String]) -> Result<(), &'static str> { } let comments = args[2..] .iter() - .map(|path| fs::read_to_string(path).map_err(|_| "cannot read PR-author comment file")) + .map(|path| fs::read_to_string(path).map_err(|_| "cannot read report comment file")) .collect::, _>>()?; let mut openings = comments.iter().filter(|body| body.contains(OPENING)); let opening = openings .next() - .ok_or("PR author must post an opening report comment")?; + .ok_or("PR author or repository maintainer must post an opening report comment")?; if openings.next().is_some() { - return Err("PR author must have exactly one opening report comment"); + return Err( + "PR must have exactly one opening report from its author or a repository maintainer", + ); } return validate(opening); }