Skip to content
Back to search

claude-notifications-go

MarketplaceWorks with Claude CodeGitHub

Agent Notifications marketplace; the legacy Claude ID is retained for compatibility

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/777genius/agent-notifications with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/777genius/agent-notifications'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/777genius--agent-notifications/badge.svg)](/listings/777genius--agent-notifications)

HTML

<a href="/listings/777genius--agent-notifications"><img src="/api/listings/777genius--agent-notifications/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

**[Guided installer](https://agent-notifications.com/#install)** or run:

(set -o pipefail; curl -fsSL https://agent-notifications.com/install.sh | bash)

Choose **Claude**, **Codex CLI**, **OpenCode**, **Gemini CLI**, **Qoder**, **Cursor CLI**, **Pi**, or a combination. Install the selected agent CLIs first and make them available on `PATH`. Pi requires its official standalone distribution; on Windows, use the real `pi.exe`, not an npm `pi.cmd` shim. The installer also requires curl, Bash, and a working `python3` or `node` on `PATH`; see [agent/platform prerequisites](docs/INSTALLATION.md#prerequisites). Run the same command to update.

All seven agents use the common installer with one product selection and channel confirmation, with UAP managing each integration. Fresh OpenCode/Gemini/Qoder/Cursor/Pi installs default to desktop on and webhooks off; updates without channel flags preserve each agent's saved choice, including disabled channels. Cursor CLI sends informational Stop alerts on qualified Linux amd64, macOS arm64 and Windows amd64 hosts; see [its profile requirements and limits](docs/cursor-notifications.md).

Qoder includes `StopFailure` error/rate-limit alerts and five bundled MP3s. Native audible qualification remains tracked in [#562](https://github.com/777genius/agent-notifications/issues/562).

**Windows:** use **Git Bash**, not WSL, for a native Windows installation.

After setup:

- **Claude:** restart Claude. - **Codex:** restart Codex, then review and trust the installed hooks in `/hooks`. - **OpenCode:** restart OpenCode; on macOS, [grant notification permission](docs/opencode-notifications.md#macos-notification-permission). - **Gemini CLI:** restart Gemini to reload its hooks. - **Qoder:** install the Qoder CLI first, then reload Qoder to activate its native plugin. - **Cursor CLI:** restart Cursor CLI to load its informational Stop observer. - **Pi:** restart Pi or run `/reload`. Desktop sounds and click-to-focus use the originating local terminal; [setup, modes and settings](docs/pi-notifications.md).

The installer selects a release from the [platform channels](docs/PLATFORM_RELEASE_CHANNELS.md) for your OS and architecture. See that page for current versions and the [release notes](https://github.com/777genius/agent-notifications/releases) for validation details and known limitations.

Run the command once to migrate a normal Claude marketplace installation to its platform channel. Claude's plugin updater then follows that channel; rerun setup to update a standalone Codex bundle. Explicitly pinned/custom marketplace sources are retained.

<details> <summary>Non-interactive installation and optional notification tools</summary>

For Codex only:

(set -o pipefail; curl -fsSL https://agent-notifications.com/install.sh | bash -s -- --product codex)

Use `--product claude` or `--product both` for Claude or Claude + Codex. For Claude, Codex and OpenCode on any supported platform:

(set -o pipefail; curl -fsSL https://agent-notifications.com/install.sh | bash -s -- --products claude,codex,opencode --desktop)

Add `,gemini`, `,qoder`, `,cursor` or `,pi` to `--products`, or select one agent with `--product`. Each integration keeps its own desktop/webhook consent. Fresh installs default to desktop notifications with webhooks off; updates preserve saved channel choices when no channel flags are supplied. Explicit flags replace the channel pair: `--desktop` enables desktop only, `--webhook` enables webhooks only, and both enable both. Use `--desktop=false --webhook=false` to disable these channels while retaining the integration. Webhook destinations need separate configuration. These flags do not change Claude/Codex channels.

For Pi, use `--product pi --desktop` or add `,pi` to a combined `--products` selection. Pi has its own desktop/webhook consent and uses the same common installer. [Pi setup and event meanings](docs/pi-notifications.md).

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 37 lines
  1. {
  2. "name": "claude-notifications-go",
  3. "description": "Agent Notifications marketplace; the legacy Claude ID is retained for compatibility",
  4. "owner": {
  5. "name": "777genius",
  6. "email": "iliyazelenkog@gmail.com"
  7. },
  8. "metadata": {
  9. "description": "Agent Notifications marketplace for coding agents (Go implementation)",
  10. "version": "1.51.4"
  11. },
  12. "plugins": [{
  13. "name": "claude-notifications-go",
  14. "displayName": "Agent Notifications",
  15. "source": "./",
  16. "description": "Agent Notifications for Claude and Codex CLI (Go implementation)",
  17. "version": "1.51.4",
  18. "author": {
  19. "name": "777genius",
  20. "email": "iliyazelenkog@gmail.com"
  21. },
  22. "repository": "https://github.com/777genius/agent-notifications",
  23. "metadata": {
  24. "renamePolicy": "Legacy Claude install identity. Do not rename; see docs/CLAUDE_PLUGIN_IDENTITY.md."
  25. },
  26. "license": "GPL-3.0",
  27. "keywords": [
  28. "notifications",
  29. "alerts",
  30. "productivity",
  31. "go",
  32. "hooks"
  33. ],
  34. "category": "productivity",
  35. "tags": ["notifications", "hooks", "alerts", "go"]
  36. }]
  37. }
README.md · README · 177 lines · 3 findings marked
  1. <p align="center">
  2. <a href="https://agent-notifications.com/"><img src="brand/agent-notifications-logo-transparent.png" width="148" alt="Agent Notifications logo" /></a>
  3. </p>
  4. <h1 align="center"><a href="https://agent-notifications.com/">Agent Notifications</a></h1>
  5. <p align="center">
  6. Built using <a href="https://github.com/777genius/universal-agent-plugins">Universal Agent Plugins</a>
  7. </p>
  8. <p align="center">
  9. <a href="#install-or-update"><img src="landing/public/agents/claude.png" width="64" height="64" alt="Claude" title="Claude" /></a>
  10. &nbsp;&nbsp;
  11. <a href="docs/CODEX.md"><img src="brand/codex-logo.svg" width="64" height="64" alt="Codex CLI" title="Codex CLI" /></a>
  12. &nbsp;&nbsp;
  13. <a href="docs/opencode-notifications.md"><img src="brand/opencode-logo.svg" width="64" height="64" alt="OpenCode" title="OpenCode" /></a>
  14. &nbsp;&nbsp;
  15. <a href="docs/gemini-notifications.md"><img src="landing/public/agents/gemini.svg" width="64" height="64" alt="Gemini CLI" title="Gemini CLI" /></a>
  16. &nbsp;&nbsp;
  17. <a href="docs/cursor-notifications.md"><img src="landing/public/agents/cursor.svg" width="64" height="64" alt="Cursor CLI" title="Cursor CLI" /></a>
  18. &nbsp;&nbsp;
  19. <a href="docs/QODER.md"><img src="landing/public/agents/qoder.svg" width="64" height="64" alt="Qoder" title="Qoder" /></a>
  20. &nbsp;&nbsp;
  21. <a href="docs/pi-notifications.md"><img src="landing/public/agents/pi.svg" width="64" height="64" alt="Pi" title="Pi" /></a>
  22. </p>
  23. [![Ubuntu CI](https://github.com/777genius/agent-notifications/actions/workflows/ci-ubuntu.yml/badge.svg?branch=main&event=push)](https://github.com/777genius/agent-notifications/actions/workflows/ci-ubuntu.yml?query=branch%3Amain+event%3Apush)
  24. [![macOS CI](https://github.com/777genius/agent-notifications/actions/workflows/ci-macos.yml/badge.svg?branch=main&event=push)](https://github.com/777genius/agent-notifications/actions/workflows/ci-macos.yml?query=branch%3Amain+event%3Apush)
  25. [![Windows CI](https://github.com/777genius/agent-notifications/actions/workflows/ci-windows.yml/badge.svg?branch=main&event=push)](https://github.com/777genius/agent-notifications/actions/workflows/ci-windows.yml?query=branch%3Amain+event%3Apush)
  26. <a href="https://trendshift.io/repositories/24861?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-24861" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/repositories/24861" alt="777genius%2Fagent-notifications | Trendshift" width="125" height="27"/></a>
  27. [![Go Reference](https://pkg.go.dev/badge/github.com/777genius/agent-notifications.svg)](https://pkg.go.dev/github.com/777genius/agent-notifications)
  28. [![codecov](https://codecov.io/gh/777genius/agent-notifications/graph/badge.svg?branch=main)](https://codecov.io/gh/777genius/agent-notifications)
  29. Desktop notifications for **Claude, Codex CLI, OpenCode, Gemini CLI, Cursor CLI, Qoder and Pi** on **macOS, Linux and Windows**. Supported architectures and events vary by agent; see the support table and linked guides. Claude, Codex and Pi provide OS-dependent terminal focus where qualified. **Qoder CLI, Gemini CLI and Cursor CLI have a separate guarded, explicit opt-in for the originating terminal window on verified local Linux/X11**; unsupported or unverified origins remain informational-only. This is window focus, not exact desktop-chat navigation, and installed authenticated CLI-to-click E2E remains unqualified. OpenCode, Gemini and Cursor offer an optional OS-default sound cue; Qoder includes five built-in MP3 assets with separate native audio qualification.
  30. <p align="center">
  31. <img width="100%" alt="macOS, Windows, Linux (left to right)" src="docs/images/notification-platform-labels.svg" />
  32. <a href="docs/images/notifications-macos.png"><img width="31%" align="top" alt="macOS notification preview" src="docs/images/notifications-macos.png" /></a>
  33. <a href="docs/images/notifications-windows.png"><img width="31%" align="top" alt="Windows notification preview" src="docs/images/notifications-windows.png" /></a>
  34. <a href="docs/images/notifications-linux.png"><img width="31%" align="top" alt="Linux notification preview" src="docs/images/notifications-linux.png" /></a>
  35. </p>
  36. ## Install Or Update
  37. **[Guided installer](https://agent-notifications.com/#install)** or run:
  38. ```bash
  39. (set -o pipefail; curl -fsSL https://agent-notifications.com/install.sh | bash)
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 47 on GitHub
  40. ```
  41. Choose **Claude**, **Codex CLI**, **OpenCode**, **Gemini CLI**, **Qoder**, **Cursor CLI**, **Pi**, or a combination. Install the selected agent CLIs first and make them available on `PATH`. Pi requires its official standalone distribution; on Windows, use the real `pi.exe`, not an npm `pi.cmd` shim. The installer also requires curl, Bash, and a working `python3` or `node` on `PATH`; see [agent/platform prerequisites](docs/INSTALLATION.md#prerequisites). Run the same command to update.
  42. All seven agents use the common installer with one product selection and channel confirmation, with UAP managing each integration. Fresh OpenCode/Gemini/Qoder/Cursor/Pi installs default to desktop on and webhooks off; updates without channel flags preserve each agent's saved choice, including disabled channels. Cursor CLI sends informational Stop alerts on qualified Linux amd64, macOS arm64 and Windows amd64 hosts; see [its profile requirements and limits](docs/cursor-notifications.md).
  43. Qoder includes `StopFailure` error/rate-limit alerts and five bundled MP3s. Native audible qualification remains tracked in [#562](https://github.com/777genius/agent-notifications/issues/562).
  44. **Windows:** use **Git Bash**, not WSL, for a native Windows installation.
  45. After setup:
  46. - **Claude:** restart Claude.
  47. - **Codex:** restart Codex, then review and trust the installed hooks in `/hooks`.
  48. - **OpenCode:** restart OpenCode; on macOS, [grant notification permission](docs/opencode-notifications.md#macos-notification-permission).
  49. - **Gemini CLI:** restart Gemini to reload its hooks.
  50. - **Qoder:** install the Qoder CLI first, then reload Qoder to activate its native plugin.
  51. - **Cursor CLI:** restart Cursor CLI to load its informational Stop observer.
  52. - **Pi:** restart Pi or run `/reload`. Desktop sounds and click-to-focus use the originating local terminal; [setup, modes and settings](docs/pi-notifications.md).
  53. The installer selects a release from the [platform channels](docs/PLATFORM_RELEASE_CHANNELS.md) for your OS and architecture. See that page for current versions and the [release notes](https://github.com/777genius/agent-notifications/releases) for validation details and known limitations.
  54. Run the command once to migrate a normal Claude marketplace installation to its platform channel. Claude's plugin updater then follows that channel; rerun setup to update a standalone Codex bundle. Explicitly pinned/custom marketplace sources are retained.
  55. <details>
  56. <summary>Non-interactive installation and optional notification tools</summary>
  57. For Codex only:
  58. ```bash
  59. (set -o pipefail; curl -fsSL https://agent-notifications.com/install.sh | bash -s -- --product codex)
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 78 on GitHub
  60. ```
  61. Use `--product claude` or `--product both` for Claude or Claude + Codex. For Claude, Codex and OpenCode on any supported platform:
  62. ```bash
  63. (set -o pipefail; curl -fsSL https://agent-notifications.com/install.sh | bash -s -- --products claude,codex,opencode --desktop)
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 84 on GitHub
  64. ```
  65. Add `,gemini`, `,qoder`, `,cursor` or `,pi` to `--products`, or select one agent with `--product`. Each integration keeps its own desktop/webhook consent. Fresh installs default to desktop notifications with webhooks off; updates preserve saved channel choices when no channel flags are supplied. Explicit flags replace the channel pair: `--desktop` enables desktop only, `--webhook` enables webhooks only, and both enable both. Use `--desktop=false --webhook=false` to disable these channels while retaining the integration. Webhook destinations need separate configuration. These flags do not change Claude/Codex channels.
  66. For Pi, use `--product pi --desktop` or add `,pi` to a combined `--products` selection. Pi has its own desktop/webhook consent and uses the same common installer. [Pi setup and event meanings](docs/pi-notifications.md).
  67. Claude/Codex setup also installs the `agent-notifications` MCP server and `agent-notifications` skill so an agent can notify you during a task. Open a new session after setup. When an existing managed MCP installation or binding is detected, automatic setup keeps absent clients off; use `--agent-notify` to add them explicitly. Use `--skip-agent-notify` to skip their setup and any selected Cursor integration for that run; it neither removes existing registrations nor records a permanent opt-out. Qoder, OpenCode, Gemini and Pi are unaffected. [Setup and recovery details](docs/INSTALLATION.md).
  68. </details>
  69. [Manual installation](docs/INSTALLATION.md#manual-install) · [Manual Codex registration](docs/CODEX.md#manual-codex-registration) · [Uninstall](docs/INSTALLATION.md#uninstalling) · [Troubleshooting](docs/troubleshooting.md)
  70. ## Features
  71. - **Task and attention alerts:** completions, questions, tool approvals and more, depending on the agent. See the table below.
  72. - **Click-to-focus:** Claude/Codex/Pi use their existing OS-dependent terminal/editor routes. Qoder/Gemini/Cursor use **guarded Linux/X11 window focus only after explicit per-agent consent** and verified local origin; per-CLI authenticated click qualification is still outstanding. Other hosts retain informational alerts. [Requirements and configuration](docs/CLICK_TO_FOCUS.md#guarded-local-cli-routing-qoder-gemini-cli-cursor-cli)
  73. - **Sounds:** Claude/Codex/Pi support their configured audio where qualified; Qoder bundles five MP3s (native audible qualification pending). OpenCode/Gemini/Cursor can request the OS-default cue with `notifications.desktop.systemSound=true` and the master sound switch. **Sound consent never grants window focus.** [Sound settings](docs/CONFIGURATION.md#sound-options)
  74. - **Useful context:** Claude/Codex desktop alerts show project, git branch and native session names, with generated labels as fallback. OpenCode desktop alerts show native session names when available. Question alerts show the current question when supplied by the host. OpenCode webhooks retain generic text. [Session context](docs/CONFIGURATION.md#session-context) · [OpenCode context](docs/opencode-notifications.md)
  75. - **Less noise (Claude/Codex):** optional focus-aware desktop delivery, delays, filters and subagent alerts. Plugin-level Do Not Disturb detection is Linux-only. [Configuration](docs/CONFIGURATION.md#focus-aware--delayed-notifications) · [Do Not Disturb](docs/DO_NOT_DISTURB.md)
  76. - **Webhooks:** Slack, Discord, Telegram, Lark/Feishu and custom endpoints. [Integration guides](docs/webhooks/README.md)
  77. - **Cross-platform:** macOS (Intel/Apple Silicon), Linux (x64/ARM64) and Windows 10+ (x64). Agent and delivery limits are listed below. [Platform details](docs/PLATFORMS.md)
  78. ## Supported Agents
  79. | Agent | Alerts | Sounds | Click-to-focus | Details |
  80. | --- | --- | --- | --- | --- |
  81. | **Claude Code** | Completions, reviews, questions, plans, session limits and API errors | Yes | Terminal/editor, OS-dependent | [Notification types](docs/NOTIFICATION_TYPES.md) |
  82. | **Codex CLI** | Turn completion and tool permissions; experimental question hooks and final-message question/error detection | Yes | Terminal/editor where supported; separately configured Codex desktop chat route | [Setup and limits](docs/CODEX.md) |
  83. | **OpenCode** | Root-session completion, questions, permissions and errors | Opt-in OS-default cue | No | [Setup and limits](docs/opencode-notifications.md) |
  84. | **Gemini CLI** | Turn completion and tool permissions | Opt-in OS-default cue | Guarded Linux/X11 window, explicit opt-in; CLI-to-click E2E pending | [Cross-platform setup and limits](docs/gemini-notifications.md) |
  85. | **Cursor CLI** | Agent loop stopping; fixed informational text | Opt-in OS-default cue | Guarded Linux/X11 window, explicit opt-in; CLI-to-click E2E pending | [Qualified hosts and setup](docs/cursor-notifications.md) |
  86. | **Qoder** | Completion, question, permission, plan and subagent hooks; StopFailure errors/rate limits since v1.50.0 | Configured; five MP3s bundled, native audible proof pending | Guarded Linux/X11 window, explicit opt-in; no exact-chat focus; CLI-to-click E2E pending | [Native hooks and setup](docs/QODER.md) |
  87. | **Pi** | Final completed activity, blocking extension UI questions and final API errors | Yes, local TUI | Originating local terminal; native qualification varies by OS | [Common installation, modes, sound and terminal focus](docs/pi-notifications.md) |
  88. **[Detailed support matrix](docs/AGENT_SUPPORT_MATRIX.md)** — event coverage, sounds, terminal vs exact-chat navigation, currently unshipped Copilot work, evidence limits and effort estimates.
  89. For Qoder/Gemini/Cursor, guarded focus requires an active managed installation, a **schema-2 selected config** with `agents.<id>.notifications.desktop.clickToFocus: true` and `terminalClickConsentVersion: 1`, and a verified **local X11 window**. It never follows a guessed title or an old window; a revoked consent or unverified host leaves a normal banner without a focus action. [Enable guarded focus](docs/CLICK_TO_FOCUS.md#guarded-local-cli-routing-qoder-gemini-cli-cursor-cli).
  90. Pi's process/lifecycle acceptance uses 27 cases per OS on Linux, macOS and
  91. Windows in isolated TEST profiles. Those checks do not establish full native
  92. macOS/Windows desktop acceptance; remaining coverage is tracked in
  93. [#561](https://github.com/777genius/agent-notifications/issues/561).
  94. OpenCode, Gemini and Cursor's optional OS-default cue (`systemSound`) is independent of navigation. OpenCode has no click-to-focus route; Gemini/Cursor require separate explicit Linux/X11 terminal-click consent.
  95. OpenCode V1 and V2 use one installed plugin. The installer does not restrict agent CLI versions. See [OpenCode setup, release reports and delivery limits](docs/opencode-notifications.md) for qualification of specific versions and platforms.
  96. Gemini CLI versions are not restricted by the installer. See [the Gemini guide](docs/gemini-notifications.md) for platform evidence and limits. A completed Gemini turn does not necessarily mean task success or a final answer. Gemini alerts and OpenCode webhooks use generic text; OpenCode desktop alerts may include native session titles and current question text. Gemini's built-in notifications can cause duplicate desktop alerts; choose one desktop source or use Agent Notifications for webhooks only.
  97. For OpenCode on stock Windows V1, the original event age is not always independently verifiable. A delayed completion may notify once and recur after the 24-hour claim lifetime; filters, provenance, deduplication and limits still apply. One-shot `opencode run` delivery at host shutdown is best effort; use a persistent host for sustained delivery.
  98. ## Settings
  99. In Claude, run `/claude-notifications-go:settings` for the settings wizard. You can request sound previews during the wizard.
  100. For Claude/Codex, use the installed launcher to find or safely inspect settings. The commands below assume `agent-notifications` is on your `PATH`; otherwise, use its full path.
  101. ```bash
  102. agent-notifications config path
  103. agent-notifications config inspect --json
  104. ```
  105. Claude/Codex share settings, with optional per-agent overrides after an explicit upgrade to configuration schema 2. The `claude-notifications` alias and Claude's existing slash-command names remain supported.
  106. Managed OpenCode uses a separate settings target:
  107. ```bash
  108. agent-notifications config path --target opencode --json
  109. agent-notifications config inspect --target opencode --json
  110. ```
  111. Use the executable and control root reported by its installer. See [OpenCode settings](docs/opencode-notifications.md#edit-installed-opencode-settings) and [Gemini settings](docs/gemini-notifications.md#settings-duplicates-and-lifecycle) for agent-specific configuration and channel consent.
  112. Pi uses shared configuration with optional schema 2 `agents.pi` overrides. Its desktop route is local-TUI-only; explicitly enabled webhooks also work in JSON, print, RPC and remote sessions. [Pi configuration](docs/pi-notifications.md#sound-and-channel-settings).
  113. [Configuration reference](docs/CONFIGURATION.md) · [Per-agent overrides](docs/AGENT_CONFIGURATION.md) · [Sound previews](docs/interactive-sound-preview.md)
  114. ## Documentation
  115. - [Installation, updates and removal](docs/INSTALLATION.md)
  116. - [Notification types](docs/NOTIFICATION_TYPES.md) and [click-to-focus](docs/CLICK_TO_FOCUS.md)
  117. - [Webhooks](docs/webhooks/README.md)
  118. - [Troubleshooting](docs/troubleshooting.md) and [plugin compatibility](docs/PLUGIN_COMPATIBILITY.md)
  119. - [Architecture](docs/ARCHITECTURE.md) and [local development](docs/LOCAL_DEVELOPMENT.md)
  120. - [Changelog](CHANGELOG.md)
  121. Built with [Universal Agent Plugins](https://github.com/777genius/universal-agent-plugins). [Build plugins for multiple AI agents](https://github.com/777genius/universal-agent-plugins#build-plugins).
  122. ## Contributing
  123. See [CONTRIBUTING.md](CONTRIBUTING.md) for development and testing. Pull requests are subject to the [Contributor License Agreement](.github/CLA.md); contributors keep copyright.
  124. GPL-3.0-or-later. See [LICENSE](LICENSE) and [third-party notices](internal/thirdpartynotices/THIRD_PARTY_NOTICES.txt).
.github/fixtures/cursor-installed-e/proof-source/exact-old-executor/native_case.py · Bundled script · 3,517 lines · 1 finding marked
  1. """Goal17 SAME R340 installed USER carrier, under construction; NOT_RUN here.
  2. Source-bound outer observer/session, two planned phases and public readback bridge.
  3. Native/OS/E NOT_RUN. Root build qualification and exact independent review apply.
  4. """
  5. import argparse, ast, base64, ctypes, datetime, gzip, hashlib, http.server, io, json, os, pathlib, re, copy, unicodedata
  6. import platform, resource, shlex, signal, socket, stat, struct, subprocess, sys, threading, time, types, zipfile, tarfile, fcntl, select, termios
  7. HERE = pathlib.Path(__file__).resolve().parent
  8. SOURCE_SHA = '9f014e72af510783d58d00ad3d2db455a2f8117b'
  9. WIRE_SHA = 'c0033c7b5a01b252815e0c9bf0ea47062150a03bc857b71d4a2e9317127b6ea2'
  10. INDEX_SHA = '45d9b1df85d0165cb2e690f96fa5fbe4b59e8a71ddd22176a301ba7e5b18a0b9'
  11. LAUNCHER_SHA = '2ccc9a8e167797641448b5e5c936f006ba137a2555f117f38c5eb76a5238a233'
  12. CURSOR_ARCHIVE_SHA = '6e4cd936a4866b8a77c50ff51a564460d715772fabc477a01aa0f0455d9559f0'
  13. CONSENT = 'TEST-only-public-sdk-stop-and-workspace-trust'
  14. LIMIT = 1048576
  15. TEST_RUNTIME_FILE_LIMIT = 25264137
  16. REFUSALS = ['/aiserver.v1.DashboardService/ListMarketplaces',
  17. '/aiserver.v1.DashboardService/GetCliDownloadUrl',
  18. '/aiserver.v1.DashboardService/GetGlobalCommands', '/aiserver.v1.AnalyticsService/SubmitLogs']
  19. w = None
  20. CASE_CLOCK = None
  21. SESSION_ENV = {}
  22. READBACK_INPUTS = None
  23. AUTHORITY_BASELINE = {}
  24. READBACK_SOURCE_SHA256 = '77030250348f8af0ee99878627b59c39cc7d658974c11adca67f7d98a4d4c8fc'
  25. READBACK_SOURCE_BYTES = base64.b64decode('Ly8gUmVhZC1vbmx5IGJyaWRnZSB0byB0aGUgU0FNRSBwaW5uZWQgcHVibGljIEFQSXMuIFJvb3QgYnVpbGRzIHRoaXMgcGFja2V0IGZpbGUKLy8gaW4gdGhlIGV4YWN0IHNvdXJjZSBtb2R1bGU7IG5vIHByb2R1Y3QgY29tbWFuZCwgaG9vaywgY2FsbGJhY2sgb3IgQUNLIGlzIGFkZGVkLgovLyBUaGlzIHdvcmtlciBkb2VzIG5vdCBidWlsZCBvciBleGVjdXRlIGl0LiBBbGwgbXV0YXRpb25zIHN0YXkgd2l0aCB0aGUgd2l6YXJkLgpwYWNrYWdlIG1haW4KaW1wb3J0ICgKImJ5dGVzIgoiY29udGV4dCIKImNyeXB0by9zaGEyNTYiCiJlbmNvZGluZy9qc29uIgoiZXJyb3JzIgoiZm10IgoiaW8iCiJvcyIKInBhdGgvZmlsZXBhdGgiCiJydW50aW1lL2RlYnVnIgoidGltZSIKImdpdGh1Yi5jb20vNzc3Z2VuaXVzL2FnZW50LW5vdGlmaWNhdGlvbnMvaW50ZXJuYWwvYWdlbnRub3RpZnkvcG9ydGFibGUiCiJnaXRodWIuY29tLzc3N2dlbml1cy9hZ2VudC1ub3RpZmljYXRpb25zL2ludGVybmFsL2NvcGlsb3R2c2NvZGVpbnN0YWxsIgoiZ2l0aHViLmNvbS83NzdnZW5pdXMvYWdlbnQtbm90aWZpY2F0aW9ucy9pbnRlcm5hbC9jdXJzb3JpbnN0YWxsIgoiZ2l0aHViLmNvbS83NzdnZW5pdXMvYWdlbnQtbm90aWZpY2F0aW9ucy9pbnRlcm5hbC9pbnN0YWxscnVudGltZSIKImdpdGh1Yi5jb20vNzc3Z2VuaXVzL3BsdWdpbi1raXQtYWkvaW5zdGFsbC9pbnRlZ3JhdGlvbmN0bC9hZGFwdGVycy9wYXRocG9saWN5IgoiZ2l0aHViLmNvbS83NzdnZW5pdXMvcGx1Z2luLWtpdC1haS9pbnN0YWxsL2ludGVncmF0aW9uY3RsL2FnZW50cGx1Z2lucy9hZGFwdGVycy9uYXRpdmVjb25maWciCiJnaXRodWIuY29tLzc3N2dlbml1cy9wbHVnaW4ta2l0LWFpL2luc3RhbGwvaW50ZWdyYXRpb25jdGwvYWdlbnRwbHVnaW5zL2FkYXB0ZXJzL3Byb2ZpbGVhdXRob3JpdHkiCiJnaXRodWIuY29tLzc3N2dlbml1cy9wbHVnaW4ta2l0LWFpL2luc3RhbGwvaW50ZWdyYXRpb25jdGwvYWdlbnRwbHVnaW5zL2FkYXB0ZXJzL3N0YXRldjIiCiJnaXRodWIuY29tLzc3N2dlbml1cy9wbHVnaW4ta2l0LWFpL2luc3RhbGwvaW50ZWdyYXRpb25jdGwvYWdlbnRwbHVnaW5zL2NsaWVudHMiCiJnaXRodWIuY29tLzc3N2dlbml1cy9wbHVnaW4ta2l0LWFpL2luc3RhbGwvaW50ZWdyYXRpb25jdGwvYWdlbnRwbHVnaW5zL2N1cnNvcmhvb2tzIgoiZ2l0aHViLmNvbS83NzdnZW5pdXMvcGx1Z2luLWtpdC1haS9pbnN0YWxsL2ludGVncmF0aW9uY3RsL2FnZW50cGx1Z2lucy9kb21haW4iCnVhcCAiZ2l0aHViLmNvbS83NzdnZW5pdXMvcGx1Z2luLWtpdC1haS9pbnN0YWxsL2ludGVncmF0aW9uY3RsL2FnZW50cGx1Z2lucy9pbnN0YWxsZXIiCikKLy8gUmVxdWlyZWQgbGRmbGFnOyBoYXNoZWQgZXhhY3QgYnJpZGdlIHNvdXJjZSBpcyBpbmRlcGVuZGVudGx5IGJvdW5kIGJ5IGNhcnJpZXIuCnZhciBwYWNrZXRTb3VyY2VTSEEyNTYgc3RyaW5nCmNvbnN0IHByb2R1Y3RSZXZpc2lvbiA9ICI5ZjAxNGU3MmFmNTEwNzgzZDU4ZDAwYWQzZDJkYjQ1NWEyZjgxMTdiIgp0eXBlIHJlcXVlc3Qgc3RydWN0IHsKCU1vZGUgc3RyaW5nIGBqc29uOiJtb2RlImAKCVNlbGVjdG9yIHN0cmluZyBganNvbjoic2VsZWN0b3IiYAoJQmluZGluZyBwb3J0YWJsZS5CaW5kaW5nIGBqc29uOiJiaW5kaW5nImAKCU9yaWdpbmFsQXV0aG9yaXR5ICpkb21haW4uUHJvZmlsZUF1dGhvcml0eSBganNvbjoib3JpZ2luYWxBdXRob3JpdHkiYAoJT3JpZ2luYWxOYW1lc3BhY2Ugc3RyaW5nIGBqc29uOiJvcmlnaW5hbE5hbWVzcGFjZSJgCglGaXhlZCAqY3Vyc29yaW5zdGFsbC5BdXRob3JpdHkgYGpzb246ImZpeGVkImAKCVRlbXBSb290IHN0cmluZyBganNvbjoidGVtcFJvb3QiYAoJVGltZW91dE1pbGxpcyBpbnQgYGpzb246InRpbWVvdXRNaWxsaXMiYAoJU291cmNlU0hBMjU2IHN0cmluZyBganNvbjoic291cmNlU0hBMjU2ImAKfQpmdW5jIHJlcXVpcmUob2sgYm9vbCwgbWVzc2FnZSBzdHJpbmcpIGVycm9yIHsKCWlmICFvayB7CgkJcmV0dXJuIGVycm9ycy5OZXcobWVzc2FnZSkKCX07CglyZXR1cm4gbmlsCn0KZnVuYyByZWFkYmFjayhyIHJlcXVlc3QpIChtYXBbc3RyaW5nXWFueSxlcnJvcikgewoJaWYgZXJyIDo9IHJlcXVpcmUoci5Tb3VyY2VTSEEyNTYgIT0gIiIgJiYgci5Tb3VyY2VTSEEyNTYgPT0gcGFja2V0U291cmNlU0hBMjU2ICYmIHIuVGltZW91dE1pbGxpcyA+IDAgJiYgci5UaW1lb3V0TWlsbGlzIDw9IDUwMDAsICJwYWNrZXQvZGVhZGxpbmUgYmluZGluZyIpOwoJZXJyICE9IG5pbCB7CgkJcmV0dXJuIG5pbCxlcnIKCX0KCWluZm8sb2s6PWRlYnVnLlJlYWRCdWlsZEluZm8oKTsKCWlmICFvayB7CgkJcmV0dXJuIG5pbCxlcnJvcnMuTmV3KCJidWlsZCBwcm92ZW5hbmNlIG1pc3NpbmciKQoJfQoJcmV2aXNpb24sbW9kaWZpZWQ6PSIiLCIiCglmb3IgXyxzOj1yYW5nZSBpbmZvLlNldHRpbmdzIHsKCQlpZiBzLktleT09InZjcy5yZXZpc2lvbiIgewoJCQlyZXZpc2lvbj1zLlZhbHVlCgkJfTsKCQlpZiBzLktleT09InZjcy5tb2RpZmllZCIgewoJCQltb2RpZmllZD1zLlZhbHVlCgkJfX0KCWlmIGVycjo9cmVxdWlyZShyZXZpc2lvbj09cHJvZHVjdFJldmlzaW9uICYmIG1vZGlmaWVkPT0iZmFsc2UiLCAiZXhhY3QgcHVibGljIGJ1aWxkIHJldmlzaW9uIik7CgllcnIhPW5pbCB7CgkJcmV0dXJuIG5pbCxlcnIKCX0KCWN0eCxjYW5jZWw6PWNvbnRleHQuV2l0aFRpbWVvdXQoY29udGV4dC5CYWNrZ3JvdW5kKCksdGltZS5EdXJhdGlvbihyLlRpbWVvdXRNaWxsaXMpKnRpbWUuTWlsbGlzZWNvbmQpOwoJZGVmZXIgY2FuY2VsKCkKCWI6PXIuQmluZGluZwoJaWYgci5Nb2RlIT0iYWJzZW50IiB7CgkJbGl2ZSxlcnI6PXBvcnRhYmxlLlJlYWRDdXJzb3JCaW5kaW5nKHIuU2VsZWN0b3IpOwoJCWlmIGVyciE9bmlsIHsKCQkJcmV0dXJuIG5pbCxlcnIKCQl9CgkJaWYgYi5WZXJzaW9uIT0wICYmIGxpdmUhPWIgewoJCQlyZXR1cm4gbmlsLGVycm9ycy5OZXcoIm9yaWdpbmFsIHBvcnRhYmxlIGJpbmRpbmcgY2hhbmdlZCIpCgkJfTsKCQliPWxpdmUKCX0KCWlmIGVycjo9cmVxdWlyZShiLkludGVncmF0aW9uPT1wb3J0YWJsZS5DdXJzb3IgJiYgZmlsZXBhdGguSXNBYnMoci5UZW1wUm9vdCkgJiYgZmlsZXBhdGguQ2xlYW4oci5UZW1wUm9vdCk9PXIuVGVtcFJvb3QsImV4cGxpY2l0IEN1cnNvciBsYXlvdXQiKTsKCWVyciE9bmlsIHsKCQlyZXR1cm4gbmlsLGVycgoJfQoJc25hcCxlcnI6PWluc3RhbGxydW50aW1lLlJlYWRJbnN0YWxsZWRTbmFwc2hvdChiLkNvbnRyb2xSb290KTsKCWlmIGVyciE9bmlsIHsKCQlyZXR1cm4gbmlsLGVycgoJfQoJaWYgZXJyPXJlcXVpcmUoIXNuYXAuUmVjb3ZlcnkgJiYgc25hcC5MZWRnZXIuUGVuZGluZ011dGF0aW9uPT1uaWwsInBlbmRpbmcgY29yZSBtdXRhdGlvbi9yZWNvdmVyeSIpOwoJZXJyIT1uaWwgewoJCXJldHVybiBuaWwsZXJyCgl9Cglyb290Oj1maWxlcGF0aC5Kb2luKGZpbGVwYXRoLkRpcihiLkNvbnRyb2xSb290KSwidWFwIikKCWNmZzo9dWFwLkNvbmZpZ3tTdGF0ZVJvb3Q6ZmlsZXBhdGguSm9pbihyb290LCJzdGF0ZSIpLFN0YXRlRmlsZTpmaWxlcGF0aC5Kb2luKHJvb3QsInN0YXRlIiwic3RhdGUtdjIuanNvbiIpLExvY2tGaWxlOmZpbGVwYXRoLkpvaW4ocm9vdCwic3RhdGUiLCJtdXRhdGlvbi5sb2NrIiksT3BlcmF0aW9uc0RpcjpmaWxlcGF0aC5Kb2luKHJvb3QsInN0YXRlIiwib3BlcmF0aW9ucyIpLFBsdWdpbkRhdGFCYXNlOmZpbGVwYXRoLkpvaW4ocm9vdCwicGx1Z2luLWRhdGEiKSxNYW5hZ2VkUm9vdDpmaWxlcGF0aC5Kb2luKHJvb3QsIm1hbmFnZWQiKSxUZW1wUm9vdDpyLlRlbXBSb290LE9wZW5Db2RlUHJvYmVFbnZpcm9ubWVudDpbXXN0cmluZ3siUEFUSD0ifX0KCXN0YXRlLGVycjo9KHN0YXRldjIuU3RvcmV7UGF0aDpjZmcuU3RhdGVGaWxlfSkuTG9hZCgpOwoJaWYgZXJyIT1uaWwgewoJCXJldHVybiBuaWwsZXJyCgl9CglpZiBlcnI9cmVxdWlyZShzdGF0ZS5TY2hlbWFWZXJzaW9uPT1kb21haW4uU3RhdGVTY2hlbWFWZXJzaW9uLCJub25jdXJyZW50IHN0YXRlIHNjaGVtYSIpOwoJZXJyIT1uaWwgewoJCXJldHVybiBuaWwsZXJyCgl9Cgl2YXIgc2VsZWN0ZWQgKmRvbWFpbi5DbGllbnRCaW5kaW5nCglmb3IgXyxpOj1yYW5nZSBzdGF0ZS5JbnN0YWxsYXRpb25zIHsKCQlpZiBpLk5lZWRzUmViaW5kIHsKCQkJcmV0dXJuIG5pbCxlcnJvcnMuTmV3KCJwZW5kaW5nIHJlYmluZCIpCgkJfQoJCWZvciBfLGM6PXJhbmdlIGkuQ2xpZW50cyB7CgkJCWlmIGMuUGVuZGluZ05hdGl2ZUludGVudCE9bmlsIHx8IGMuTmF0aXZlQWN0aXZhdGlvbkF0dGVtcHQhPSIiIHx8IGMuTG9jYWxFbnRyeU9ic2VydmF0aW9uIT1uaWwgewoJCQkJcmV0dXJuIG5pbCxlcnJvcnMuTmV3KCJwZW5kaW5nL3Vua25vd24gbmF0aXZlIHN0YXRlIikKCQkJfQoJCQlpZiBpLkluc3RhbGxhdGlvbklEPT1iLkluc3RhbGxhdGlvbklEICYmIGMuQ2xpZW50QmluZGluZ0lEPT1iLkJpbmRpbmdJRCB7CgkJCQlpZiBzZWxlY3RlZCE9bmlsIHsKCQkJCQlyZXR1cm4gbmlsLGVycm9ycy5OZXcoImR1cGxpY2F0ZSBzZWxlY3RlZCBiaW5kaW5nIikKCQkJCX07CgkJCQl2Oj1jOwoJCQkJc2VsZWN0ZWQ9JnZ9CgkJfQoJfQoJZml4ZWQ6PXIuRml4ZWQKCWlmIHIuTW9kZSE9ImFic2VudCIgewoJCWlmIHNlbGVjdGVkPT1uaWwgfHwgc2VsZWN0ZWQuUHJvZmlsZUF1dGhvcml0eT09bmlsIHsKCQkJcmV0dXJuIG5pbCxlcnJvcnMuTmV3KCJzZWxlY3RlZCBvcmlnaW5hbCB0b2tlbiBtaXNzaW5nIikKCQl9CgkJYzo9KnNlbGVjdGVkCgkJaWYgZXJyPXJlcXVpcmUoYy5Qcm9maWxlTmFtZXNwYWNlPT1jZmcuU3RhdGVSb290ICYmIGMuUHJvZmlsZUF1dGhvcml0eS5GYWN0cygpLkNhbm9uaWNhbFJvb3Q9PWIuU2NvcGVSb290LCJmdWxsIHByb2ZpbGUgbmFtZXNwYWNlL3Jvb3QiKTsKCQllcnIhPW5pbCB7CgkJCXJldHVybiBuaWwsZXJyCgkJfQoJCWlmIHIuT3JpZ2luYWxBdXRob3JpdHkhPW5pbCAmJiAoIXIuT3JpZ2luYWxBdXRob3JpdHkuRXF1YWwoKmMuUHJvZmlsZUF1dGhvcml0eSkgfHwgci5PcmlnaW5hbE5hbWVzcGFjZSE9Yy5Qcm9maWxlTmFtZXNwYWNlKSB7CgkJCXJldHVybiBuaWwsZXJyb3JzLk5ldygib3JpZ2luYWwgZnVsbCB0b2tlbi9uYW1lc3BhY2UgY2hhbmdlZCIpCgkJfQoJCWYsb2s6PWMuU2VsZWN0ZWREZWxpdmVyeS5DdXJzb3JGYWN0cygpOwoJCWlmICFvayB7CgkJCXJldHVybiBuaWwsZXJyb3JzLk5ldygic2VsZWN0ZWQgQ3Vyc29yIHBhY2tldCBtaXNzaW5nIikKCQl9CgkJZXhlY3V0YWJsZSxlOj1wb3J0YWJsZS5SZXNvbHZlUHJpbWFyeUV4ZWN1dGFibGUoc25hcC5MZWRnZXIsYi5QcmltYXJ5KTsKCQlpZiBlIT1uaWwgewoJCQlyZXR1cm4gbmlsLGUKCQl9CgkJYWN0dWFsOj1jdXJzb3JpbnN0YWxsLkF1dGhvcml0eXtQcm9maWxlUm9vdDpmLlByb2ZpbGVSb290LEN1cnNvclZlcnNpb246Zi5DdXJzb3JWZXJzaW9uLFF1YWxpZmljYXRpb25JRDpmLlF1YWxpZmljYXRpb25JRCxFeGVjdXRhYmxlOmV4ZWN1dGFibGUsRXhlY3V0YWJsZURpZ2VzdDoic2hhMjU2OiIrc25hcC5MZWRnZXIuRmlsZXNbZXhlY3V0YWJsZV0uU0hBMjU2LFNlbGVjdG9yOmYuU2VsZWN0b3IsT2JqZWN0SUQ6Zi5PYmplY3RJRH0KCQlpZiBmaXhlZCE9bmlsICYmICpmaXhlZCE9YWN0dWFsIHsKCQkJcmV0dXJuIG5pbCxlcnJvcnMuTmV3KCJvcmlnaW5hbCBmaXhlZCBzZWxlY3Rpb24gY2hhbmdlZCIpCgkJfTsKCQlmaXhlZD0mYWN0dWFsCgkJaWYgZXJyPWIuQ2hlY2tTbmFwc2hvdChzbmFwKTsKCQllcnIhPW5pbCB7CgkJCXJldHVybiBuaWwsZXJyCgkJfQoJfSBlbHNlIHsKCQlpZiBzZWxlY3RlZCE9bmlsIHx8IHIuT3JpZ2luYWxBdXRob3JpdHk9PW5pbCB8fCByLk9yaWdpbmFsTmFtZXNwYWNlIT1jZmcuU3RhdGVSb290IHx8IGZpeGVkPT1uaWwgewoJCQlyZXR1cm4gbmlsLGVycm9ycy5OZXcoInNlbGVjdGVkIGJpbmRpbmcgcmVtYWlucy9hYnNlbnQgb3JpZ2luYWwgYXV0aG9yaXR5IikKCQl9CgkJaWYgZXJyPXByb2ZpbGVhdXRob3JpdHkuUmV2YWxpZGF0ZShjdHgsKnIuT3JpZ2luYWxBdXRob3JpdHkpOwoJCWVyciE9bmlsIHsKCQkJcmV0dXJuIG5pbCxlcnIKCQl9CgkJa2V5LF8sXyxlOj1iLlJlZ2lzdHJhdGlvbigpOwoJCWlmIGUhPW5pbCB7CgkJCXJldHVybiBuaWwsZQoJCX0KCQlpZiBfLG9rOj1zbmFwLkxlZGdlci5Db25zdW1lcnNba2V5XTsKCQlvayB7CgkJCXJldHVybiBuaWwsZXJyb3JzLk5ldygic2VsZWN0ZWQgY29uc3VtZXIgcmVtYWlucyIpCgkJfQoJCWlmIF8sZT1vcy5Mc3RhdChyLlNlbGVjdG9yKTsKCQkhZXJyb3JzLklzKGUsb3MuRXJyTm90RXhpc3QpIHsKCQkJcmV0dXJuIG5pbCxlcnJvcnMuTmV3KCJzZWxlY3RlZCBsb2NhdG9yIHJlbWFpbnMvdW5rbm93biIpCgkJfQoJfQoJYWRhcHRlcixlcnI6PWN1cnNvcmluc3RhbGwuTmV3KG5hdGl2ZWNvbmZpZy5OZXcoKSxwYXRocG9saWN5LlBvbGljeXt9LGZpeGVkKTsKCWlmIGVyciE9bmlsIHsKCQlyZXR1cm4gbmlsLGVycgoJfQoJcmVnaXN0cnksZXJyOj1jbGllbnRzLk5ld1JlZ2lzdHJ5KGFkYXB0ZXIpOwoJaWYgZXJyIT1uaWwgewoJCXJldHVybiBuaWwsZXJyCgl9OwoJY2ZnLlJlZ2lzdHJ5PXJlZ2lzdHJ5CgllbmdpbmUsZXJyOj11YXAuTmV3KGNmZyk7CglpZiBlcnIhPW5pbCB7CgkJcmV0dXJuIG5pbCxlcnIKCX0KCWluc3BlY3Rpb24sZXJyOj1lbmdpbmUuSW5zcGVjdChjdHgpOwoJaWYgZXJyIT1uaWwgewoJCXJldHVybiBuaWwsZXJyCgl9CglyZWNvdmVyeTo9aW5zcGVjdGlvbi5SZWNvdmVyeQoJaWYgcmVjb3ZlcnkuUmVxdWlyZWQgfHwgcmVjb3ZlcnkuUmVhc29uIT0iIiB8fCBsZW4ocmVjb3ZlcnkuSm91cm5hbHMpK2xlbihyZWNvdmVyeS5SZWNlaXB0cykrbGVuKHJlY292ZXJ5Lk5hdGl2ZUludGVudHMpIT0wIHsKCQlyZXR1cm4gbmlsLGVycm9ycy5OZXcoInBlbmRpbmcgcHVibGljIHJlY292ZXJ5IikKCX0KCW91dDo9bWFwW3N0cmluZ11hbnl7InN0YXRlIjpzdGF0ZSwiaW5zcGVjdGlvbiI6aW5zcGVjdGlvbiwiZml4ZWQiOmZpeGVkLCJiaW5kaW5nIjpiLCJtb2RlIjpyLk1vZGUsImJyaWRnZVNvdXJjZVNIQTI1NiI6cGFja2V0U291cmNlU0hBMjU2fQoJaWYgci5Nb2RlIT0iYWJzZW50IiB7CgkJaWYgZXJyPWVuZ2luZS5WZXJpZnlQcm9maWxlQXV0aG9yaXR5KGN0eCxiLkluc3RhbGxhdGlvbklELGIuQmluZGluZ0lEKTsKCQllcnIhPW5pbCB7CgkJCXJldHVybiBuaWwsZXJyCgkJfQoJCWlmIGVycj1wcm9maWxlYXV0aG9yaXR5LlJldmFsaWRhdGUoY3R4LCpzZWxlY3RlZC5Qcm9maWxlQXV0aG9yaXR5KTsKCQllcnIhPW5pbCB7CgkJCXJldHVybiBuaWwsZXJyCgkJfQoJCWlmIHIuT3JpZ2luYWxBdXRob3JpdHkhPW5pbCB7CgkJCWlmIGVycj1wcm9maWxlYXV0aG9yaXR5LlJldmFsaWRhdGUoY3R4LCpyLk9yaWdpbmFsQXV0aG9yaXR5KTsKCQkJZXJyIT1uaWwgewoJCQkJcmV0dXJuIG5pbCxlcnIKCQkJfX0KCQlnYXRlLGU6PWNvcGlsb3R2c2NvZGVpbnN0YWxsLk5ld0N1cnNvckdhdGUoYixjZmcsKmZpeGVkKTsKCQlpZiBlIT1uaWwgewoJCQlyZXR1cm4gbmlsLGUKCQl9CgkJY29uc3VtZXIsZTo9Z2F0ZS5Db25zdW1lckJpbmRpbmcoY3R4KTsKCQlpZiBlIT1uaWwgewoJCQlyZXR1cm4gbmlsLGUKCQl9CgkJZWZmZWN0aXZlLGU6PWdhdGUuRWZmZWN0aXZlQ29uZmlnKGN0eCk7CgkJaWYgZSE9bmlsIHsKCQkJcmV0dXJuIG5pbCxlCgkJfQoJCW91dFsic2VsZWN0ZWQiXT1zZWxlY3RlZDsKCQlvdXRbIm9yaWdpbmFsQXV0aG9yaXR5Il09c2VsZWN0ZWQuUHJvZmlsZUF1dGhvcml0eTsKCQlvdXRbIm9yaWdpbmFsTmFtZXNwYWNlIl09c2VsZWN0ZWQuUHJvZmlsZU5hbWVzcGFjZQoJCW91dFsiY29uc3VtZXJCaW5kaW5nIl09Y29uc3VtZXI7CgkJb3V0WyJjaGFubmVscyJdPWdhdGUuQ2hhbm5lbHMoY3R4LGNvbnN1bWVyKTsKCQlvdXRbImVmZmVjdGl2ZUNvbmZpZyJdPWVmZmVjdGl2ZQoJCWlmIGNvbnN1bWVyLkdlbmVyYXRpb24hPXNuYXAuTGVkZ2VyLkdlbmVyYXRpb24gewoJCQlyZXR1cm4gbmlsLGVycm9ycy5OZXcoImFjdHVhbCBjb21taXR0ZWQgZ2VuZXJhdGlvbiBjaGFuZ2VkIikKCQl9CgkJaWYgci5Nb2RlPT0icmVtb3ZlLXBsYW4iIHsKCQkJdmFyIHJlY2VpcHQgKmN1cnNvcmhvb2tzLlJlY2VpcHQKCQkJZm9yIF8sb2JqZWN0Oj1yYW5nZSBzZWxlY3RlZC5OYXRpdmVPYmplY3RzIHsKCQkJCWlmIG9iamVjdC5LaW5kPT0iY3Vyc29yX3VzZXJfc3RvcCIgewoJCQkJCWlmIHJlY2VpcHQhPW5pbCB7CgkJCQkJCXJldHVybiBuaWwsZXJyb3JzLk5ldygiZHVwbGljYXRlIHN0b3Agb3duZXJzaGlwIikKCQkJCQl9OwoJCQkJCXY6PW9iamVjdC5DdXJzb3JSZWNlaXB0OwoJCQkJCXJlY2VpcHQ9JmN1cnNvcmhvb2tzLlJlY2VpcHR7VmVyc2lvbjp2LlZlcnNpb24sRXZlbnQ6di5FdmVudCxTaGVsbDpjdXJzb3Job29rcy5TaGVsbENvbnRyYWN0KHYuU2hlbGwpLFNwZWM6Y3Vyc29yaG9va3MuSG9va1NwZWN7RXhlY3V0YWJsZTp2LkV4ZWN1dGFibGUsU2VsZWN0b3I6di5TZWxlY3Rvcn0sRW50cnlEaWdlc3Q6di5FbnRyeURpZ2VzdCxSZW1haW5kZXJEaWdlc3Q6di5SZW1haW5kZXJEaWdlc3R9fX0KCQkJaWYgcmVjZWlwdD09bmlsIHsKCQkJCXJldHVybiBuaWwsZXJyb3JzLk5ldygiYWNrbm93bGVkZ2VkIHN0b3Agb3duZXJzaGlwIG1pc3NpbmciKQoJCQl9CgkJCWZpbGUsZTo9bmF0aXZlY29uZmlnLk5ldygpLlJlYWRFeGFjdEZpbGUoZmlsZXBhdGguSm9pbihiLlNjb3BlUm9vdCwiaG9va3MuanNvbiIpKTsKCQkJaWYgZSE9bmlsIHsKCQkJCXJldHVybiBuaWwsZQoJCQl9CgkJCS8vIEV4cG9ydGVkIHB1cmUgUGxhbihSZW1vdmUpIGlzIHRoaXMgc291cmNlJ3MgUGxhblJlbW92ZTsgbmV2ZXIgQXBwbHkvQUNLLgoJCQlwbGFuLGU6PWN1cnNvcmhvb2tzLlBsYW4oY3Vyc29yaG9va3MuUmVxdWVzdHtEb2N1bWVudDpmaWxlLkJvZHksT3BlcmF0aW9uOmN1cnNvcmhvb2tzLlJlbW92ZSxQcmV2aW91czpyZWNlaXB0LFNoZWxsOnJlY2VpcHQuU2hlbGx9KTsKCQkJaWYgZSE9bmlsIHsKCQkJCXJldHVybiBuaWwsZQoJCQl9CgkJCWlmIHBsYW4uQ29uZmxpY3QgfHwgcGxhbi5SZWNlaXB0IT1uaWwgewoJCQkJcmV0dXJuIG5pbCxlcnJvcnMuTmV3KCJ1bnByb3ZlZCBwdXJlIHJlbW92YWwiKQoJCQl9CgkJCW91dFsiZXhwZWN0ZWRIb29rQnl0ZXMiXT1wbGFuLkRlc2lyZWQ7CgkJCW91dFsiZXhwZWN0ZWRIb29rU0hBMjU2Il09Zm10LlNwcmludGYoIiV4IixzaGEyNTYuU3VtMjU2KHBsYW4uRGVzaXJlZCkpCgkJfQoJfQoJaWYgZXJyPWN0eC5FcnIoKTsKCWVyciE9bmlsIHsKCQlyZXR1cm4gbmlsLGVycgoJfTsKCXJldHVybiBvdXQsbmlsCn0KZnVuYyBtYWluKCkgewoJcmF3LGVycjo9aW8uUmVhZEFsbChpby5MaW1pdFJlYWRlcihvcy5TdGRpbiwoMjw8MjApKzEpKTsKCWlmIGVyciE9bmlsIHx8IGxlbihyYXcpPjI8PDIwIHsKCQlmbXQuRnByaW50bG4ob3MuU3RkZXJyLCJib3VuZGVkIHJlcXVlc3QgcmVxdWlyZWQiKTsKCQlvcy5FeGl0KDIpCgl9CglkZWNvZGVyOj1qc29uLk5ld0RlY29kZXIoYnl0ZXMuTmV3UmVhZGVyKHJhdykpOwoJZGVjb2Rlci5EaXNhbGxvd1Vua25vd25GaWVsZHMoKTsKCXZhciByIHJlcXVlc3QKCWlmIGVycj1kZWNvZGVyLkRlY29kZSgmcik7CgllcnI9PW5pbCB7dmFyIGV4dHJhIGFueTsKCQlpZiBlOj1kZWNvZGVyLkRlY29kZSgmZXh0cmEpOwoJCSFlcnJvcnMuSXMoZSxpby5FT0YpIHsKCQkJZXJyPWVycm9ycy5OZXcoInRyYWlsaW5nIHJlcXVlc3QiKQoJCX19CglpZiBlcnI9PW5pbCAmJiByLk1vZGUhPSJsaXZlIiAmJiByLk1vZGUhPSJyZW1vdmUtcGxhbiIgJiYgci5Nb2RlIT0iYWJzZW50IiB7CgkJZXJyPWVycm9ycy5OZXcoInVua25vd24gcmVhZGJhY2sgbW9kZSIpCgl9Cgl2YXIgcmVzdWx0IG1hcFtzdHJpbmddYW55OwoJaWYgZXJyPT1uaWwgewoJCXJlc3VsdCxlcnI9cmVhZGJhY2socikKCX0KCWlmIGVyciE9bmlsIHsKCQlmbXQuRnByaW50bG4ob3MuU3RkZXJyLGVycik7CgkJb3MuRXhpdCgyKQoJfQoJZW5jb2RlZCxlcnI6PWpzb24uTWFyc2hhbChyZXN1bHQpOwoJaWYgZXJyIT1uaWwgfHwgbGVuKGVuY29kZWQpPjE2PDwyMCB7CgkJZm10LkZwcmludGxuKG9zLlN0ZGVyciwiYm91bmRlZCByZWFkYmFjayByZXF1aXJlZCIpOwoJCW9zLkV4aXQoMikKCX0KCWZtdC5QcmludGxuKHN0cmluZyhlbmNvZGVkKSkKfQo=')
    • Dismissed after review: Contains a long base64-looking blob — not necessarily malicious, but worth inspecting what it decodes to
    • Line 25 on GitHub
  26. WIRE_BYTES = b'"""Source-pinned wire recipe only. Does not import vendor code or launch anything.\nCoordinator may import these local helpers into a finite loopback HTTP fixture.\nThis module has no main block, network access, credentials, or native execution.\n"""\nimport struct\n\ndef varint(value):\n assert value >= 0\n result = bytearray()\n while value > 127:\n result.append((value & 127) | 128)\n value >>= 7\n result.append(value)\n return bytes(result)\n\ndef uint(field, value):\n return varint(field << 3) + varint(value)\n\ndef blob(field, value):\n if isinstance(value, str):\n value = value.encode(\'utf-8\')\n return varint((field << 3) | 2) + varint(len(value)) + value\n\ndef frame(payload, flags=0):\n return bytes([flags]) + struct.pack(\'>I\', len(payload)) + payload\n\ndef read_varint(data, at):\n value = 0\n for shift in range(0, 70, 7):\n if at >= len(data):\n raise ValueError(\'truncated varint\')\n byte = data[at]\n at += 1\n value |= (byte & 127) << shift\n if byte < 128:\n return value, at\n raise ValueError(\'oversized varint\')\n\ndef fields(data):\n """Bounded wire scanner; repeated fields remain repeated. No vendor schema eval."""\n if len(data) > 1024 * 1024:\n raise ValueError(\'body budget\')\n at = 0\n result = []\n while at < len(data):\n tag, at = read_varint(data, at)\n number, wire = tag >> 3, tag & 7\n if number == 0:\n raise ValueError(\'zero tag\')\n if wire == 0:\n value, at = read_varint(data, at)\n elif wire == 2:\n size, at = read_varint(data, at)\n value = data[at:at + size]\n at += size\n elif wire in (1, 5):\n size = 8 if wire == 1 else 4\n value = data[at:at + size]\n at += size\n else:\n raise ValueError(\'unsupported wire type\')\n if at > len(data):\n raise ValueError(\'truncated field\')\n result.append((number, wire, value))\n return result\n\ndef first(data, number, default=None):\n return next((value for n, wire, value in fields(data) if n == number), default)\n\ndef model_details(model_id=\'TEST-native-stop\'):\n return b\'\'.join(blob(n, model_id) for n in (1, 3, 4, 5))\n\ndef unary_responses():\n """Only the native HTTP/1.1 Connect/protobuf callsites traced in this audit.\n GetUsableModels/DefaultModel here are AiService paths, despite AgentService\n descriptors also exposing identically named methods.\n """\n return {\n \'/aiserver.v1.ServerConfigService/GetServerConfig\': uint(7, 1),\n \'/aiserver.v1.AiService/GetUsableModels\': blob(1, model_details()),\n \'/aiserver.v1.AiService/GetDefaultModelForCli\': blob(1, model_details()),\n \'/aiserver.v1.AiService/AvailableModels\': b\'\',\n \'/aiserver.v1.DashboardService/GetMe\': blob(1, \'TEST-loopback-identity\') + uint(2, 1),\n \'/aiserver.v1.DashboardService/GetUserPrivacyMode\': b\'\',\n \'/aiserver.v1.DashboardService/GetTeamAdminSettingsOrEmptyIfNotInTeam\': b\'\',\n \'/aiserver.v1.DashboardService/GetEffectiveUserPlugins\': b\'\',\n \'/aiserver.v1.DashboardService/GetManagedSkills\': b\'\',\n }\n\ndef decode_append(body):\n """Input is unframed unary BidiAppendRequest protobuf (decompress first)."""\n request_id = first(first(body, 2), 1).decode()\n sequence = first(body, 3, 0)\n data = first(body, 4) or bytes.fromhex(first(body, 1, b\'\').decode(\'ascii\'))\n return request_id, sequence, data\n\ndef stop_frame(conversation_id, generation_id, model_id=\'TEST-native-stop\'):\n query = (blob(1, \'completed\') + uint(2, 0) + blob(3, conversation_id)\n + (blob(4, generation_id) if generation_id else b\'\')\n + blob(5, model_id) + blob(6, model_id))\n # AgentServerMessage.execServerMessage(2) -> ExecServerMessage:\n # id(1), execId(15), executeHookArgs(27) -> request(1) -> stop(11).\n args = blob(1, blob(11, query))\n message = uint(1, 1) + blob(15, \'TEST-stop-1\') + blob(27, args)\n return frame(blob(2, message))\n\ndef text_frame(text=\'TEST deterministic turn complete\'):\n # AgentServerMessage.interactionUpdate(1) -> textDelta(1) -> text(1).\n return frame(blob(1, blob(1, blob(1, text))))\n\ndef terminal_frames():\n # interactionUpdate(1) -> turnEnded(14), followed by Connect EndStream JSON.\n return frame(blob(1, blob(14, b\'\'))) + frame(b\'{}\', 2)\n\ndef classify_client_message(data):\n run = first(data, 1)\n if run is not None:\n return {\'kind\': \'run\', \'conversation\': first(run, 5, b\'\').decode(),\n \'generation\': first(run, 25, b\'\').decode(),\n \'model\': first(first(run, 3, b\'\'), 1, b\'\').decode()}\n exec_result = first(data, 2)\n if exec_result is not None:\n hook = first(exec_result, 27)\n if hook is None:\n return {\'kind\': \'unexpected-exec-result\'}\n stop_response = first(first(hook, 1, b\'\'), 11)\n return {\'kind\': \'stop-result\', \'id\': first(exec_result, 1, 0),\n \'execId\': first(exec_result, 15, b\'\').decode(),\n \'hasStop\': stop_response is not None,\n \'followup\': first(stop_response or b\'\', 1, b\'\').decode()}\n control = first(data, 5)\n if control is not None:\n if first(control, 2) is not None:\n return {\'kind\': \'exec-throw\'}\n close = first(control, 1)\n return {\'kind\': \'exec-close\', \'id\': first(close, 1, 0)} if close is not None else {\'kind\': \'exec-control\'}\n if first(data, 7) is not None:\n return {\'kind\': \'heartbeat\'}\n return {\'kind\': \'unexpected-client-message\'}\n'
  27. ARTIFACT_PINS = [{'file': 'index.js', 'sha256': '45d9b1df85d0165cb2e690f96fa5fbe4b59e8a71ddd22176a301ba7e5b18a0b9', 'byteLength': 7549229}, {'file': '1538.index.js', 'sha256': '62f61c0b6ccba0f43e79eaf947e33aa33640969050f6459aeec17360aefa1b60', 'byteLength': 5940}, {'file': '4114.index.js', 'sha256': '43386ebdc3a4af020c5398fd020083d8103ef7fbf286970d2d71d3ef9dade9df', 'byteLength': 5699}, {'file': '9725.index.js', 'sha256': '2d2c791377dfe432b3ff1f3173e5218efad7deee76e35a1fc632a577f7fe4440', 'byteLength': 6062}, {'file': 'diff-patch-worker.js', 'sha256': '8de87d1ba7886c6135522679c5d29756afcefb0fe91bdec2023cd42c911a4d0d', 'byteLength': 6646}, {'file': '7450.index.js', 'sha256': '703707729125fa35af87c15c640285d9b90b4a4cd099cfecff0e28c79c8f5f56', 'byteLength': 1341}, {'file': '478.index.js', 'sha256': '663ed1eb66a692521cc7c8bd89ed352ada8ce32da3c8138ca2813958afb9bd00', 'byteLength': 14521}, {'file': '8914.index.js', 'sha256': '0e48ce732c3866c95e3956c52cad892a74a8e7aca9d65090edc6227aad604902', 'byteLength': 671}, {'file': '3541.index.js', 'sha256': '57b1e8de43deb2e3cb8da14522189a21964ff83f915582b20c4073eb03969dc4', 'byteLength': 4469}, {'file': 'unified-diff-worker.js', 'sha256': '0191e7623aab46a080eb5752018aeb209723645558a33203e31d98d419694188', 'byteLength': 6786}, {'file': 'pdf-worker.js', 'sha256': '34cc2e8b9c321799f7d55997c42c8ccc6abc9ea902fd7c7845da5accb136a948', 'byteLength': 480099}, {'file': '5092.index.js', 'sha256': 'cdb601e4e52224c8e36885130c33241a903b87b1f0e1b897b47f1ff79ae66d4e', 'byteLength': 16085}, {'file': '6136.index.js', 'sha256': 'e1000a10d7d6b2b0ad897abcadd43177267d1c18baa907861dd19eb9708eddca', 'byteLength': 97261}, {'file': '8391.index.js', 'sha256': 'bb1f809662186fa081a1e365ce57202797bf44db1f31c071af9edbe56c9ef49a', 'byteLength': 3435}, {'file': '3575.index.js', 'sha256': '3470b1d226b47d6148f4586cabe05aebd77feeafb14d5c854c90483066406da5', 'byteLength': 13815}, {'file': '4760.index.js', 'sha256': 'a08b490045a975d5e86dd849e8b7c3c7c8c2773e27a2e9e4580b68dc425e0485', 'byteLength': 2099}, {'file': '8096.index.js.LICENSE.txt', 'sha256': '806fb10cfb2aed86c6b7b5a179ea01c9c3d736183a3de70ef1e355259bf4b52e', 'byteLength': 2659}, {'file': '3244.index.js', 'sha256': '4566b4210aef42ee023901a74a0318b5e61eb755ffbe6cf52497b67f73e17665', 'byteLength': 899}, {'file': 'cursor-askpass.js', 'sha256': 'ffb6b47c511bdbe2cab68e52ef6e3d37b5bf0ac1e632c78725e30ddb2dbde590', 'byteLength': 5653}, {'file': '8891.index.js', 'sha256': 'b9d93a11a3e4bdad0ddab4e7e5a88d2aba678a0ef42f2bbb5c4a37ff1fa871bc', 'byteLength': 3241578}, {'file': '8644.index.js', 'sha256': 'ec890f0f3073142cba2a6b14541e17f5966b68733a198b6a40be7f60f437fa02', 'byteLength': 7271}, {'file': '3284.index.js', 'sha256': '373a713f8b9f6dad4c2542885905bbb58a7b7c858250628f3088b29649448eaf', 'byteLength': 573}, {'file': '2576.index.js', 'sha256': 'e73fc1ae6529a431ccd5278b39e4cb6bb86fbe0eed6a76684950a2b3611e3717', 'byteLength': 2224}, {'file': '5336.index.js', 'sha256': '7d9543dd6ee0e75c69a18950022cd93031343c29bb8d36f678b5d8b6606a7ce0', 'byteLength': 25190}, {'file': '7923.index.js', 'sha256': 'b5333ad5328c6aa394fd6631822b5caf63a67019c1b9521e861a522ddefbbc4a', 'byteLength': 15734}, {'file': '5818.index.js', 'sha256': 'c94b3f56ed6a8555169088cb186cc2ee0917d7f4412b1921a177817f0df1258e', 'byteLength': 9840}, {'file': '190.index.js', 'sha256': '73c1e9693be17a8b6087d62a11a2159d962371d13c69869f1816a95a1cae547d', 'byteLength': 115505}, {'file': '6918.index.js', 'sha256': 'ba224f3f4d27ca1b5243a75d667b4698543993b379c9551bf9e012317845cad5', 'byteLength': 3587}, {'file': '8096.index.js', 'sha256': '99b2da77d52174213307274bf428c95ca3f7c1216c27630e49c928cfef1b2442', 'byteLength': 2723244}, {'file': '3550.index.js', 'sha256': 'e7636cd64f760f486773640de92cdd11350597e323f1981ce4ac8f401fc00111', 'byteLength': 4849}, {'file': '1429.index.js', 'sha256': '8543b0e5c57f0e33350a64707b341d949432409136ff45b0c97cdf66f6edad29', 'byteLength': 43650}, {'file': '5531.index.js', 'sha256': '3b97993589db91c120031cbb838fb8b32f4b53f611dbb9e954e01b212e2888f3', 'byteLength': 899}, {'file': '2290.index.js', 'sha256': '9f23f7dcfb33f41666f03a4235acfa63a9dbade1889946eca92c31aea3f6096a', 'byteLength': 35299}, {'file': '159.index.js', 'sha256': '66469a19bbe5023910ea7024ecbb54d3985a4a536657b4f4ca2b160b641ef1ac', 'byteLength': 341387}, {'file': '2911.index.js', 'sha256': '863ea507c6237d077c41a5feb5561acca0b95a6d13e3d80e0644ebe9d0ff773c', 'byteLength': 6282}, {'file': '4343.index.js', 'sha256': 'b02e2b0971ed8ea980a1d311fa4b2d314c365daee468944c85328cc126e1298a', 'byteLength': 665}, {'file': '1326.index.js', 'sha256': '24c9f33e87969bf629e8f9ffef267373d120bf55ef8d91375d29cd693399eae7', 'byteLength': 36858}, {'file': '5993.index.js', 'sha256': '25502e95a9b84c20dbf1e4d12daefad5cd162ae9f0fec6c59be8533524dc538f', 'byteLength': 1706}, {'file': '1623.index.js', 'sha256': '6e393636a7898efe8b9a52463682d7cddf211e668334aed58f6864b37eaef60d', 'byteLength': 116131}, {'file': '2721.index.js', 'sha256': '16ba2d3946cb1df6bfad6dbc4d7c974ca697627081ff1834da73a1b4f04c8a15', 'byteLength': 89633}, {'file': '7000.index.js', 'sha256': '749a10b62a2094860d219683b5c5bb36e12c1fb036fcd31e08789f0085b2f5bd', 'byteLength': 981259}, {'file': '6643.index.js', 'sha256': 'c7b9d6d3c3713dc213e81e26b8c5649d28cfbc368ededcc3ec29684e513b9b6e', 'byteLength': 1499}, {'file': '4155.index.js', 'sha256': '1180c477779e5c338b4264b0d671c8c458d4e444188d1e3bd74b5b482f6b5c75', 'byteLength': 9134}, {'file': '9322.index.js', 'sha256': 'ef4157396957372c84013c508e89bed33c20b020185b63ab307cd3929fca9766', 'byteLength': 8866}, {'file': '6536.index.js', 'sha256': 'd777b3cfcc2aa3f42eb0b22cb91480c31482a1c669c6942dc475c89491db9fd3', 'byteLength': 35558}, {'file': 'package.json', 'sha256': '625a6b5d64e45fd989706ab6fd21a95f454d4e70cab7c0c1c151d37582d8bee2', 'byteLength': 64}, {'file': '2761.index.js', 'sha256': 'd3bb797ae5229578f33adbe6413e151ba4ee50c022c054eb6f68a93f47f683d8', 'byteLength': 5825}, {'file': 'pdf-worker.js.LICENSE.txt', 'sha256': 'b5e8c493d516d9b156045ec3b83cc3e26785363af56db22bd52382942b394242', 'byteLength': 795}, {'file': '2422.index.js', 'sha256': 'cc119c5eccfbcf35112697c442c7bfba6670065f8c664a05d5040cce8dfc3528', 'byteLength': 1966}, {'file': '4945.index.js', 'sha256': 'e6b1a2a2d0a7974dd9ad5920483cecbcc1c3c76a9dc1978d11a081cab62e2df6', 'byteLength': 5987}, {'file': '3144.index.js', 'sha256': 'a66c828d56fdb0aee05e2d3023a8a66fe0e058a48b201f03b31d056b8e0cc591', 'byteLength': 793}, {'file': '9106.index.js', 'sha256': '4ce5d0eedcb45448c7a99350864f50122e739aaa9d9ecd12e25babd75dcda55a', 'byteLength': 387131}, {'file': '6174.index.js', 'sha256': '6bddd90df806756c130b3ebf4e74b0062cf0c030e6caa6e6537bf844e86d9496', 'byteLength': 15810}, {'file': '3857.index.js', 'sha256': '2bc55395422ae75b29d2ed5e21881cd12a060c16b5c3e913ea528eb28e117283', 'byteLength': 6881}, {'file': 'mac-webp-runtime.cjs', 'sha256': '4a6041caf835ff53c58caf36e679f65fe6c04722661f315de036ceddd107a770', 'byteLength': 309}, {'file': '3464.index.js', 'sha256': '030e649c6f5550ce08bfd657a9f07802ceecae568603e558e7fdac723cf86188', 'byteLength': 2438}, {'file': '8192.index.js', 'sha256': '06cb735afe2dd4a44d4be16d7e27bf724efbab6158aacb50c6880c4ed4cc50f2', 'byteLength': 70472}, {'file': '4632.index.js', 'sha256': '4600e9ea74d09c839889bc225530f55b9d104c8f4b2608081cd505b266f7c9e8', 'byteLength': 21998}, {'file': '9063.index.js', 'sha256': 'c425976b1aaf6963966103a3d6a7f24fdb9a38a3028daeac0e88f1509356bd95', 'byteLength': 9811}, {'file': '2734.index.js', 'sha256': 'a7c877a8dbaac4d1db3171939f9f7d6f397e9efcdbc2662d35fe0ffc054a56ec', 'byteLength': 26555}, {'file': '272.index.js', 'sha256': 'f996e8b2ec65ca48aaaa5adf9b1cd167c04c32b9a278342ceadafc8bf3a23180', 'byteLength': 6881}, {'file': 'a22718674812ee697cf3.js', 'sha256': 'ba885e166fb261506969fab7703b665d96998e6f995c8c4e8172c696f58574d6', 'byteLength': 2821}, {'file': '7351.index.js', 'sha256': '86745bbc5f2c74890e3cd5358ab4b02b0995db7558c9717abebe66a0beace206', 'byteLength': 1972}, {'file': 'diff-worker.js', 'sha256': 'f8145d47eb97535413a4ae9426c2562801ec0cffa3a4734d3bf444f7a74ca994', 'byteLength': 5945}, {'file': 'index.js.LICENSE.txt', 'sha256': 'ef63fcca608d4374bbfc9d807e32d54d272976a9ea53651471b1ed4f711bcf2b', 'byteLength': 1719}, {'file': '6436.index.js', 'sha256': '592623afe824b6db6b315e0d6a62b0279b75d8d3a4e4b297c3b28a81f08f2f54', 'byteLength': 11976}, {'file': '5740.index.js', 'sha256': 'e902aaa02a8596697eb069f2089767e61a07c168bea26db1143ea160ff7c77f2', 'byteLength': 5657}, {'file': '8991.index.js', 'sha256': 'd9645dfed24e004fe9f0d4e81df707832f2e9f0d3e4c74d7fabfc5f58cc25f3c', 'byteLength': 5435}, {'file': '2601.index.js', 'sha256': 'cf21effd409e730cc29155e5e81b76fef1ce836bfa00a1b1ef498e9065898000', 'byteLength': 14540}, {'file': '9147.index.js', 'sha256': '5fbf0cb6086f7556bf969d015bd6d3c5c209d63edf3256811145bad65716d858', 'byteLength': 340}, {'file': '5380.index.js', 'sha256': '25af69ecff6f7b1e8c12b7138122dbf040eb01144bd1b58a699c1ad75b0ce16e', 'byteLength': 58595}, {'file': '5434.index.js', 'sha256': '94b9bd7a100ac91499c1aaf7af4ec705ab1171ccec5144ace7bd824cb4ba902e', 'byteLength': 1085}, {'file': '7945.index.js', 'sha256': '399ffc412f6d14332bf44b51aa28cff40db56c25974d50fa58adefd468bb3a3b', 'byteLength': 364902}, {'file': '5720.index.js', 'sha256': '48b1bf10573d26f1cef098e5b19e2bd71177e336c1a70fc4edb9aa68991c8e0c', 'byteLength': 2419}, {'file': '5469.index.js', 'sha256': 'bccf3d9433cce7eb2a314835ffd68260158c86d1b5a85ccda7b28661f8c13039', 'byteLength': 336}, {'file': '3190.index.js', 'sha256': 'c6b0007358a0d92c1df1aa7e20c2863f94ba4732ca88334a686799b4fa4ca37e', 'byteLength': 1795}, {'file': '7373.index.js', 'sha256': '95f1e630a2fe054882701d86d447d9da645e9cdfbe25fe45123843f78f7db273', 'byteLength': 12363}, {'file': '6134.index.js', 'sha256': '356de23c9365c444bffe8e3f65982e49f6f3b181ffbfb38938e4aa3d77d1b261', 'byteLength': 7910}, {'file': '1499.index.js', 'sha256': 'c3905ad7c580b8fcc3e559ca316e3e125b7adc7a832c9dff5c7a9f10c41b5728', 'byteLength': 9146}, {'file': '2240.index.js', 'sha256': 'a6a95525446982366afb71c09241a6e7e8f31c0d409458e9928b4cf469d4830c', 'byteLength': 221412}, {'file': '6870.index.js', 'sha256': '8cd41ad250670e7162ce25daeb4b52a04356bd4a609ebf23eda719968e3ce18c', 'byteLength': 234}, {'file': '4161.index.js', 'sha256': '02a3a1a75d7951917815c42bc6e0b08d7f3af47fc0e9c1789fcb9b1c127e2810', 'byteLength': 5594}, {'file': '9494.index.js', 'sha256': '93ae84b5f457e1447331367d90ebc36f89e4d1754fba040e729b2e5ad73e1260', 'byteLength': 47082}, {'file': '7627.index.js', 'sha256': 'aa61aa5788a135dcf95dded5a94ce03f29586d53438e25877340d38260290f35', 'byteLength': 4893}, {'file': '903.index.js', 'sha256': '98537c9b472fb235ee58268a7612b9d86885851074af1274962ec012089d6c8a', 'byteLength': 9590}, {'file': 'node_modules/node-gyp-build/index.js', 'sha256': 'a7ed0d5ae218a19bdbdf15a590d0893790ddf536313b66a787554693cfaae078', 'byteLength': 390}, {'file': 'node_modules/node-gyp-build/build-test.js', 'sha256': '34c19ff8b6675d6d27c63a7df44d77a442805eeea8756d1c89e0264f4a3028f6', 'byteLength': 398}, {'file': 'node_modules/node-gyp-build/optional.js', 'sha256': 'e0b3a3a04166e6ecf1020cb31c0c4a54432c16d6d88714bd4de2214cf67dec81', 'byteLength': 143}, {'file': 'node_modules/node-gyp-build/package.json', 'sha256': '9e8def3fbf123e28aa1ca4b6aa557fba4e66eecf6e86d170b61ec1c7ed51305d', 'byteLength': 1004}, {'file': 'node_modules/node-gyp-build/bin.js', 'sha256': 'dc022adc093b9b79e1a0ef4b6bc3e6a52e3d627102113dad4afacbbe81f13a26', 'byteLength': 2094}, {'file': 'node_modules/node-gyp-build/node-gyp-build.js', 'sha256': '134f0585f7c665db89f332a379158c6f113274422e42aaf54e0aa9d5ac37f577', 'byteLength': 6078}, {'file': 'node_modules/file-uri-to-path/index.js', 'sha256': 'e62293e871bdd5a7449ff3c7956c9536ec1d2ea7369461de77322b5256bb93e7', 'byteLength': 1723}, {'file': 'node_modules/file-uri-to-path/package.json', 'sha256': '71eb1e24bb9694f89c613fa0aa307f977dd43f41d11794c7b48fabf6c55f66b0', 'byteLength': 717}, {'file': 'node_modules/better-sqlite3/package.json', 'sha256': '4665126292eff5dffe6c0ffabf98c4de18e479aa0b53edd775028eb567b3ecc1', 'byteLength': 1436}, {'file': 'node_modules/tree-sitter-bash/grammar.js', 'sha256': 'e1e7ed6840a2a692a1bd5f352ff85b38d065cdca200f95b1288230fb621ff2d7', 'byteLength': 30081}, {'file': 'node_modules/tree-sitter-bash/package.json', 'sha256': 'ee9d6515031266905123792f891fc9c3db75f55c5d9c1e027a315a60a09557c4', 'byteLength': 1616}, {'file': 'node_modules/piscina/package.json', 'sha256': '2a51b866d734d494f814027cbf422db40f8a2f14e8ac1e1b8f5b471f9bb83d52', 'byteLength': 2842}, {'file': 'node_modules/tree-sitter/index.js', 'sha256': 'ba5e8461e5068f2b58ea860aea331ed0c6d8a25f21142d75a6145a1544fc9ffe', 'byteLength': 25716}, {'file': 'node_modules/tree-sitter/package.json', 'sha256': '8cca5044dd3381dbf958dea36ef6d9f81f379886d32ef845919cf07679c6e42c', 'byteLength': 1757}, {'file': 'node_modules/bindings/bindings.js', 'sha256': '8e32a0d37f20bd6f7d5bdbf99d041aa27be47cbbe5172ac13ebf7380a10b3bf6', 'byteLength': 5986}, {'file': 'node_modules/bindings/package.json', 'sha256': 'a87721fe406e1f1798fef44d697b46ea1efe346fda118010334713346ee4207c', 'byteLength': 660}, {'file': 'node_modules/file-uri-to-path/test/tests.json', 'sha256': 'b48c50c1328ab8522fc0bf91923ea42fb59e63e847b967dac88123cb5e5b185d', 'byteLength': 810}, {'file': 'node_modules/file-uri-to-path/test/test.js', 'sha256': '223c25dba6fefbb7cb491b026a32f070b1425475d3cd2d04627be5d71a07fd38', 'byteLength': 666}, {'file': 'node_modules/better-sqlite3/deps/copy.js', 'sha256': '05a2bd41dbd96e33e2fc6cf4bcbc722b4bc8c529813b882f92113d7dbbbece67', 'byteLength': 897}, {'file': 'node_modules/better-sqlite3/lib/index.js', 'sha256': '82db11c4ee43a41d859988c5db42c3771dff565371f94bacbd1e4d8d6ceb47cd', 'byteLength': 110}, {'file': 'node_modules/better-sqlite3/lib/sqlite-error.js', 'sha256': '2582d61c27680dead168543f392eb102be621dfbef282a4ca4c7c21aa5e7c75d', 'byteLength': 717}, {'file': 'node_modules/better-sqlite3/lib/database.js', 'sha256': '02ea23bdd23d7ac5de0675a2f32fc686e76d5c6a32bd3e3891f360e72e07f61f', 'byteLength': 4149}, {'file': 'node_modules/better-sqlite3/lib/util.js', 'sha256': '92b2e39e2151b43a2252e10b6d6de876ecaf0008336a4fa1dfe1317b20f1916f', 'byteLength': 331}, {'file': 'node_modules/better-sqlite3/lib/methods/serialize.js', 'sha256': '7a10ee5c2735384b7f0c361811bc6d017db29f62b203fd3c68a35f667e2c2605', 'byteLength': 625}, {'file': 'node_modules/better-sqlite3/lib/methods/function.js', 'sha256': 'f431d49303b8bbdc044b1f1b455bdad21fc9b74b007de0acb22f08f25b4febd3', 'byteLength': 1396}, {'file': 'node_modules/better-sqlite3/lib/methods/backup.js', 'sha256': 'ea29d34992bb02e006d0fdeda9675ac5d2bb227aaf57468decd997e9fc9c7dbf', 'byteLength': 2380}, {'file': 'node_modules/better-sqlite3/lib/methods/table.js', 'sha256': '97c42d9ded1aa96c7d916b5b92f96b4e59581d50eaf629cd2c7afb78ff26a9ea', 'byteLength': 7144}, {'file': 'node_modules/better-sqlite3/lib/methods/wrappers.js', 'sha256': 'a150a6271d23f4e5f8953b129f370ff096c7cdc4b812afbf080a6cf4ab741bcf', 'byteLength': 1145}, {'file': 'node_modules/better-sqlite3/lib/methods/aggregate.js', 'sha256': 'e9f74eb919ec93fe089c95ddf25a98f1f631c80418fa34fb2346ca1bc29f1b82', 'byteLength': 1932}, {'file': 'node_modules/better-sqlite3/lib/methods/pragma.js', 'sha256': '8b1c54475bd4340b15e25c50d53d06308be65f8f919ecbe4aa9d285ca859ad5a', 'byteLength': 536}, {'file': 'node_modules/better-sqlite3/lib/methods/transaction.js', 'sha256': 'bc8624a3ef689d8f78e5669020ad121e17acbc93b1d5ee5afe26860b1084c66c', 'byteLength': 2792}, {'file': 'node_modules/better-sqlite3/lib/methods/inspect.js', 'sha256': '4975a78daee850adee62ba98719d0f223819a0ec135a07c0e302994bd8dbff61', 'byteLength': 174}, {'file': 'node_modules/tree-sitter-bash/src/node-types.json', 'sha256': '39763582e682b132eb5349af6e1d7be78aed98decf808ffa6bcf92cfed4ac5dc', 'byteLength': 49267}, {'file': 'node_modules/tree-sitter-bash/src/grammar.json', 'sha256': '899dc858b05efefb478dcefc5491b5653e2df5d2aca16292d6def5c0746ac820', 'byteLength': 179302}, {'file': 'node_modules/tree-sitter-bash/bindings/node/index.js', 'sha256': '609bdf22b8fd183025b3c24e8587f6211d50358e8f2e4c526b9217349ed9dbc0', 'byteLength': 201}, {'file': 'node_modules/piscina/benchmark/simple-benchmark-fixed-queue.js', 'sha256': '66ab8b3ee623b26d77460a3aa954890605e3407944654891bf1919d22582ce1a', 'byteLength': 801}, {'file': 'node_modules/piscina/benchmark/simple-benchmark.js', 'sha256': '10ec3fdba4616419d0d6ca8984c3d16db2d65543f19fe539eff08655e3fcc50c', 'byteLength': 743}, {'file': 'node_modules/piscina/benchmark/queue-comparison.js', 'sha256': '0f2a3d44e1f3c64b2cd7223c484b49bafb98a5c8dfd1fe34c6d327ebebc14910', 'byteLength': 758}, {'file': 'node_modules/piscina/benchmark/piscina-queue-comparison.js', 'sha256': '621d25cf2645f11be9df950199e43ab7b46a0f78cc8730f54a6484be8c6298d8', 'byteLength': 1093}, {'file': 'node_modules/piscina/dist/index.js', 'sha256': 'c47bd61dbafa0d5cada595709f0d688666402e8d53968659394fb76579c88b1f', 'byteLength': 33387}, {'file': 'node_modules/piscina/dist/worker.js', 'sha256': '081e85839bad17b8d895bae9e39ebb890933148185a9a547eb11cf4f3b410ceb', 'byteLength': 8248}, {'file': 'node_modules/piscina/dist/abort.js', 'sha256': '96bda77290b59f3f05f054fc67f8dd3c911c5b41615c767653f9c5be1100f181', 'byteLength': 690}, {'file': 'node_modules/piscina/dist/types.js', 'sha256': 'd6a24e27e1b415e8b9a6861d070c599c2fc71a86513c3a1b7d22c96798c9e14f', 'byteLength': 220}, {'file': 'node_modules/piscina/dist/errors.js', 'sha256': '8a1ba396c508b3981573e61d9d7c46c311a50f1a94891e3951b4a8a1e58d488d', 'byteLength': 551}, {'file': 'node_modules/piscina/dist/common.js', 'sha256': '7408b87975c0b2daf9f82f13b201f4e53b6f4a571ab1b4e997cbfe4204690695', 'byteLength': 3159}, {'file': 'node_modules/piscina/dist/main.js', 'sha256': '66553ddfb435a0093214eacb1c44971dc862e896f222ce9251cc6a9a15212bb6', 'byteLength': 272}, {'file': 'node_modules/piscina/dist/symbols.js', 'sha256': 'd0e30b1d318751183ffab01979895bc0fc45f1db6c6db36f83d58f2329f0011a', 'byteLength': 686}, {'file': 'node_modules/piscina/benchmark/fixtures/add.js', 'sha256': '48c3b9da5c294a707f11cfd562fe1092c68d50d52c124ac0f5305d81f874d726', 'byteLength': 52}, {'file': 'node_modules/piscina/dist/task_queue/index.js', 'sha256': 'e0bab14fc4f6e3e84adc1ed9d9190de1cda03af0894c21e7d8697382dd8741df', 'byteLength': 3723}, {'file': 'node_modules/piscina/dist/task_queue/common.js', 'sha256': 'efa0b2439294e1510ac01e9e254e9fbd509834ed9c4fdc73559c6b62f69a8264', 'byteLength': 113}, {'file': 'node_modules/piscina/dist/task_queue/array_queue.js', 'sha256': '29fe6991e3eab05119782880776adac3813e693b6c82ed8cbeab68296dca3921', 'byteLength': 862}, {'file': 'node_modules/piscina/dist/task_queue/fixed_queue.js', 'sha256': '626b1062fcfccd7568a349cd3ca2c0cb224dde65ddd98099d5b618d594c9eb10', 'byteLength': 6594}, {'file': 'node_modules/piscina/dist/worker_pool/index.js', 'sha256': 'b784db251a8f114d3ca0410468d25d05b1889050fbd266425bafc8d59664a867', 'byteLength': 6654}, {'file': 'node_modules/piscina/test/fixtures/send-buffer-then-get-length.js', 'sha256': 'b6646486752c157f6822ad178dea9bbf16c98611404afcaa773afc6ab61410f5', 'byteLength': 313}, {'file': 'node_modules/piscina/test/fixtures/vm.js', 'sha256': 'e1682e3cb237dbc16d19f28c0950d8978858d5b5d8b385997a8c5e963ac2e974', 'byteLength': 164}, {'file': 'node_modules/piscina/test/fixtures/resource-limits.js', 'sha256': '7dfd8f172c3328b7626399e2041a3d2c67a95bd5046a7a781628fa8a8342d7cf', 'byteLength': 109}, {'file': 'node_modules/piscina/test/fixtures/eval.js', 'sha256': 'ad103ef0038cda945182d95f2e8a610b44a1e46ef07771ced2e61b498567331a', 'byteLength': 93}, {'file': 'node_modules/piscina/test/fixtures/send-transferrable-then-get-length.js', 'sha256': 'fa8a63779d65ee6d41f329a948f9e75acb663c1956e0c0e84f1c11caf4985628', 'byteLength': 642}, {'file': 'node_modules/piscina/test/fixtures/eval-async.js', 'sha256': '01ff257a8f50fd0ae46531a7240dead492be9dae82c5cc0dd8537120c8a91cc8', 'byteLength': 267}, {'file': 'node_modules/piscina/test/fixtures/sleep.js', 'sha256': '53133a2a5ef9bd1ece0d0a3ea276cdf598d7cfcb6c295bcec2152819787fedf0', 'byteLength': 277}, {'file': 'node_modules/piscina/test/fixtures/multiple.js', 'sha256': '60c74291d42de9f7310de63c25a21d667ccf6b1dfe46adb87af80b70f4e7fabb', 'byteLength': 116}, {'file': 'node_modules/piscina/test/fixtures/notify-then-sleep-or.js', 'sha256': '1e3baabedf56a7af1cd2d1411334d9fe361bae91b0a87e64ffeb7704415e04bd', 'byteLength': 347}, {'file': 'node_modules/tree-sitter/jest-tests/parse_input.js', 'sha256': 'c822a080455cc0991ed04918a58a57b8ff736c62382155f3d868f27db489e800', 'byteLength': 243}, {'file': 'node_modules/tree-sitter/jest-tests/test3.test.js', 'sha256': 'dd89cb5d72894e26dd0535e326fbfc83582a5161a4b6970b8fa6bc17d117b3f3', 'byteLength': 624}, {'file': 'node_modules/tree-sitter/jest-tests/constants.js', 'sha256': 'da2f35a1728f8c6e376b87a66c9a1fc9f5c466f3103c38c01f43075f6081f138', 'byteLength': 657}, {'file': 'node_modules/tree-sitter/jest-tests/test.test.js', 'sha256': '9fb07c9ff5d3cc31298fd561f4f2f8828e713e0b75cb2208cbe204726c940716', 'byteLength': 5985}, {'file': 'node_modules/tree-sitter/jest-tests/runit.js', 'sha256': '61eabd4d64149552ff42b4f2dfe1827fef16aa104e33e5d18678e2af8852d494', 'byteLength': 298}, {'file': 'node_modules/tree-sitter/jest-tests/test2.test.js', 'sha256': 'ce68dd4056372dafa9617b7472098a3a50a9bbd61bc4792f35642263cc42f528', 'byteLength': 614}, {'file': 'node_modules/tree-sitter/test/lookahead_iterable_test.js', 'sha256': '7091be46ce22a6e76f322742e9b92d792e6916117ee1969fd39f80666db58083', 'byteLength': 1434}, {'file': 'node_modules/tree-sitter/test/parser_test.js', 'sha256': '6e9529e6d2213caf55bf8b8f4ad5293e376aad4759b836b96bcb4a20ad0def9c', 'byteLength': 24623}, {'file': 'node_modules/tree-sitter/test/node_test.js', 'sha256': '7dbf4cf445d47731fb5c7e283e74695ceb1221d5af0db465b7dabd52baf811d4', 'byteLength': 36780}, {'file': 'node_modules/tree-sitter/test/query_test.js', 'sha256': '407aed8a46d381128803ae22ce4e61441373f9a4bc0b4c9c9d61dc0fbb72f851', 'byteLength': 36549}, {'file': 'node_modules/tree-sitter/test/tree_test.js', 'sha256': 'ba487df54014f31dbf5e027bca465d4f891b7bc09943d55dbf686926ea79f838', 'byteLength': 19983}, {'file': 'node_modules/tree-sitter/vendor/tree-sitter/lib/src/wasm/stdlib-symbols.txt', 'sha256': '1162b06514d583b0e94fe9b59ddcc36257f587047cacf7944e87b01722109294', 'byteLength': 253}, {'file': 'node_modules/@jsquash/webp/index.js', 'sha256': '281f1d048db337aaa2412503423b2ca99eeb8ec104b471618ee3845930a27688', 'byteLength': 98}, {'file': 'node_modules/@jsquash/webp/package.json', 'sha256': 'bfd9f9b7ec0d51421623e92185b3b994d6430068de323dacaa1a29b8a1c9c83c', 'byteLength': 978}, {'file': 'node_modules/@jsquash/webp/decode.js', 'sha256': 'b15d9abe76ad4b07214739fe81a99a47f25d01a1e0b0a329a3bec706509cd9e2', 'byteLength': 1432}, {'file': 'node_modules/@jsquash/webp/encode.js', 'sha256': 'edcd883d10e955655946b8fe733bb139faa8b7036092827b1849a4b34d727d6b', 'byteLength': 1946}, {'file': 'node_modules/@jsquash/webp/utils.js', 'sha256': 'e71535eeee820d68b68ece7c8af761c39f3ddec93d3d957d2f83b19191339e0d', 'byteLength': 1272}, {'file': 'node_modules/@jsquash/webp/meta.js', 'sha256': '3d70163a00e6264fc5a8fa7c8f3b1fa21a50a00d910f4d2de3ef1bbd2fdc98ab', 'byteLength': 749}, {'file': 'node_modules/@jsquash/webp/codec/pre.js', 'sha256': 'b4d7da800804a2390eefa7805bb5f4e20cf349681334eb9a1715d2c58a1822b2', 'byteLength': 847}, {'file': 'node_modules/@jsquash/webp/codec/dec/webp_dec.js', 'sha256': 'c57971611f4d9ec04e4636ce7bb4a35c031b24cbdb013518f0a017d9f6014370', 'byteLength': 34823}, {'file': 'node_modules/@jsquash/webp/codec/enc/webp_enc.js', 'sha256': '5fd62301662e37785aec38e38807926f72933d4c8b919018a43faf1b1ca760f6', 'byteLength': 38665}, {'file': 'node_modules/@jsquash/webp/codec/enc/webp_enc_simd.js', 'sha256': '3038e60ebba6252baba08c691e31d1efe5036a185435daa7b4afaef3cc9273f9', 'byteLength': 38646}]
  28. def strict_json(data):
  29. def pairs(values):
  30. result = dict(values); assert len(result) == len(values), 'duplicate JSON key'; return result
  31. return json.loads(data, object_pairs_hook=pairs, parse_constant=lambda _: (_ for _ in ()).throw(ValueError('nonfinite JSON')))
  32. def append(data):
  33. fields = w.fields(data); numbers = [n for n,t,v in fields]
  34. assert len(numbers) == len(set(numbers)) and set(numbers) <= {1,2,3,4}, 'unknown/duplicate append field'
  35. assert 2 in numbers and (1 in numbers) != (4 in numbers), 'ambiguous/missing append payload'
  36. assert all(t == (0 if n == 3 else 2) for n,t,v in fields), 'append wire type'
  37. request = w.first(data,2); assert w.fields(request) == [(1,2,w.first(request,1))], 'append request identity'
  38. rid,seq,msg = w.decode_append(data); assert rid and 0 <= seq <= 127
  39. return rid,seq,msg
  40. def classify(msg):
  41. fields = w.fields(msg); assert len(fields) == 1 and fields[0][1] == 2, 'unknown client envelope'
  42. if fields[0][0] == 5 and [n for n,t,v in w.fields(fields[0][2])] == [3]:
  43. return {'kind': 'heartbeat'} # approved ExecClientControl heartbeat
  44. q = w.classify_client_message(msg)
  45. assert q['kind'] in ['run','stop-result','exec-close','heartbeat'], 'unknown native protocol'
  46. if q['kind'] == 'run':
  47. run = w.first(msg,1)
  48. q['requestedModel'] = w.first(w.first(run,9,b''),1,b'').decode()
  49. q['selectedModel'] = w.first(w.first(run,15,b''),1,b'').decode()
  50. assert q['requestedModel'] == q['selectedModel'] == 'TEST-native-stop'
  51. assert q['conversation'] and q['generation']
  52. if q['kind'] == 'stop-result':
  53. result = w.first(msg,2)
  54. assert len(w.fields(result)) == len({n for n,t,v in w.fields(result)})
  55. assert set(n for n,t,v in w.fields(result)) <= {1,15,27,39}, 'unknown Stop result'
  56. assert all(t == (2 if n in [15,27] else 0) for n,t,v in w.fields(result)), 'Stop result wire type'
  57. assert 0 <= w.first(result,39,0) <= 5000, 'local hook execution time'
  58. hook = w.first(result,27); assert w.fields(hook) == [(1,2,w.first(hook,1))]
  59. response = w.first(hook,1); assert w.fields(response) == [(11,2,b'')], 'nonneutral Stop response'
  60. assert q['id'] == 1 and q['execId'] == '' and q['hasStop'] and not q['followup']
  61. if q['kind'] == 'exec-close':
  62. assert msg == w.blob(5,w.blob(1,w.uint(1,1))), 'unexpected close'
  63. return q
  64. def body(h):
  65. # r5 Connect unary framing.
  66. if h.headers.get('Transfer-Encoding', '').lower() == 'chunked':
  67. data = bytearray()
  68. while True:
  69. size = int(h.rfile.readline(128).split(b';')[0], 16)
  70. if not size:
  71. assert h.rfile.readline(128) == b'\r\n'
  72. break
  73. assert 0 <= size <= LIMIT-len(data)
  74. data.extend(h.rfile.read(size)); assert h.rfile.read(2) == b'\r\n'
  75. data = bytes(data)
  76. else:
  77. size = int(h.headers.get('Content-Length', '0'))
  78. assert 0 <= size <= LIMIT
  79. data = h.rfile.read(size); assert len(data) == size
  80. if h.headers.get('Content-Encoding') == 'gzip':
  81. with gzip.GzipFile(fileobj=io.BytesIO(data)) as f: data = f.read(LIMIT+1)
  82. assert len(data) <= LIMIT
  83. return data
  84. def own_processes():
  85. result = []
  86. for p in pathlib.Path('/proc').glob('[0-9]*/stat'):
  87. try:
  88. fields = p.read_text().rsplit(')', 1)[1].split()
  89. result.append((int(p.parent.name), int(fields[1]), int(fields[2]), int(fields[21])*os.sysconf('SC_PAGE_SIZE'), int(fields[3]), int(fields[19])))
  90. except (FileNotFoundError, ProcessLookupError): pass
  91. return result
  92. def owned_survivors(procs, leader, controller, namespace):
  93. # stat; no names/env.
  94. assert os.getpid() == controller and os.readlink('/proc/self/ns/pid') == namespace
  95. assert any(p[0] == controller for p in procs), 'controller absent from snapshot'
  96. assert leader[0] == leader[2] == leader[4] and leader[0] != os.getpgrp(), 'unique owned group'
  97. children = [p for p in procs if p[0] != controller]
  98. ids = {p[0] for p in children} | {controller, leader[0]}
  99. for p in children:
  100. assert p[2] == p[4] == leader[0] and p[5] >= leader[5], 'unexpected outgroup/identity'
  101. assert p[1] in ids, 'unexpected descendant parent'
  102. if p[0] == leader[0]: assert p[5] == leader[5], 'native leader identity changed'
  103. try: assert os.readlink('/proc/'+str(p[0])+'/ns/pid') == namespace, 'PID namespace changed'
  104. except FileNotFoundError: pass # exited during fresh observation; join still required
  105. assert len(children) <= 65 and sum(p[3] for p in children) <= 4*1024**3, 'native process/RSS budget'
  106. assert len(procs) <= 72 and sum(p[3] for p in procs) <= 5*1024**3, 'owned namespace process/RSS budget'
  107. return children
  108. def request_owned_cleanup(procs, leader, controller, namespace, deadline, sig=signal.SIGTERM):
  109. children = owned_survivors(procs, leader, controller, namespace)
  110. assert time.monotonic() < deadline, 'cleanup deadline'
  111. for p in children:
  112. try:
  113. assert os.getpgid(p[0]) == os.getsid(p[0]) == leader[0], 'fresh group identity'
  114. except ProcessLookupError: continue
  115. assert time.monotonic() < deadline, 'cleanup deadline'
  116. if not children: return False
  117. try: os.killpg(leader[0], sig); return True
  118. except ProcessLookupError: return False
  119. def join_owned(native, leader, controller, namespace, deadline, snapshot=own_processes, budget=lambda: None):
  120. while time.monotonic() < deadline:
  121. native.poll()
  122. try:
  123. while os.waitpid(-1, os.WNOHANG)[0]: pass
  124. except ChildProcessError: pass
  125. children = owned_survivors(snapshot(), leader, controller, namespace); budget()
  126. if not children: return time.monotonic() < deadline
  127. time.sleep(min(.1, max(0, deadline-time.monotonic())))
  128. return False
  129. def cmdline_facts(raw):
  130. args = raw[:8192].decode('utf8','surrogateescape').split('\0')
  131. if args[-1] == '': args.pop()
  132. return {'argv':args, 'cmdlineBytes':len(raw), 'argvOverflow':len(raw)>8192,
  133. 'argvMalformed':bool(raw) and not raw.endswith(b'\0')}
  134. def process_snapshot(procs, namespace):
  135. # Bound facts; no env/auth.
  136. rows = []
  137. for p in procs[:73]:
  138. row = {'stat':p}; proc = pathlib.Path('/proc',str(p[0])); stage = 'cmdline'
  139. try:
  140. with (proc/'cmdline').open('rb') as f: raw = f.read(8193)
  141. row.update(cmdline_facts(raw))
  142. links = {}
  143. for field,link in (('exe','exe'),('cwd','cwd'),('namespace','ns/pid'),('netNamespace','ns/net')):
  144. stage = field
  145. links[field] = os.readlink(proc/link)
  146. row.update(links)
  147. stage = 'status'
  148. with (proc/'status').open() as f: status = f.read(8193)
  149. row['uid'] = next(l for l in status.splitlines() if l.startswith('Uid:')).split()[1:]
  150. stage = 'stat'
  151. with (proc/'stat').open() as f: fields = f.read(8193).rsplit(')',1)[1].split()
  152. row['freshIdentity'] = [int(fields[i]) for i in [1,2,3,19]]
  153. except (OSError,ValueError,StopIteration) as e:
  154. row.update(readFailure=type(e).__name__,refusalStage=stage)
  155. try:
  156. with (proc/'stat').open() as f: raw = f.read(8193)
  157. fields = raw.rsplit(')',1)[1].split()
  158. row['failureStat'] = {'pid':raw.split('(',1)[0].strip()[:32],
  159. 'birth':fields[19][:32],'state':fields[0][:1]}
  160. except (OSError,ValueError,IndexError) as diagnostic_error:
  161. row['failureStatReadFailure'] = type(diagnostic_error).__name__
  162. if len(json.dumps(row).encode()) > 12000:
  163. row = {'stat':p,'readFailure':'ProcessMetadataBudget', **{k:str(row.get(k,''))[:64] for k in ['exe','cwd','namespace','uid']},
  164. 'argv':[a[:64] for a in row.get('argv',[])[:8]]}
  165. rows.append(row)
  166. return {'namespace':namespace,'totalProcesses':len(procs),'totalRSS':sum(p[3] for p in procs),
  167. 'bornUpperTicks':int(time.clock_gettime(time.CLOCK_BOOTTIME)*os.sysconf('SC_CLK_TCK')),
  168. 'netNamespace':os.readlink('/proc/self/ns/net'),'rows':rows}
  169. def capture_active(evidence, procs, namespace, phase, previous, checks, birth_floor):
  170. snapshot = process_snapshot(procs,namespace)
  171. snapshot.update(phase=phase,previous={str(k):v for k,v in previous.items()},checks=checks,
  172. birthFloorTicks=birth_floor,ownershipContract='native-descendants')
  173. raw = json.dumps(snapshot,indent=2); assert len(raw.encode()) <= LIMIT, 'actual snapshot bytes budget'
  174. name = 'active-process-snapshot.json' if phase == 'active' else 'cleanup-actual-process-snapshot.json'
  175. (evidence/name).write_text(raw+'\n'); return snapshot
  176. class ProcessObservationRace(AssertionError): pass
  177. def active_resource_bounds(snapshot):
  178. rows = snapshot['rows']; children = [r for r in rows if r['stat'][0] != 1]
  179. # Bound totals/incomplete; no retry.
  180. assert all(len(r['stat']) == 6 and r['stat'][3] >= 0 for r in rows), 'invalid process RSS'
  181. assert snapshot['totalProcesses'] <= 72 and snapshot['totalRSS'] <= 5*1024**3, 'namespace process/RSS budget'
  182. assert len(children) <= 65 and sum(r['stat'][3] for r in children) <= 4*1024**3, 'descendant process/RSS budget'
  183. assert len(rows) == snapshot['totalProcesses'] and snapshot['totalRSS'] == sum(r['stat'][3] for r in rows), 'incomplete process totals'
  184. def complete_process_facts(snapshot, namespace):
  185. race = None
  186. for row in snapshot['rows']:
  187. p = row['stat']
  188. if 'uid' in row: assert row['uid'] == ['1000']*4, 'foreign UID'
  189. if 'namespace' in row: assert row['namespace'] == namespace, 'foreign PID namespace'
  190. if 'netNamespace' in row: assert row['netNamespace'] == snapshot['netNamespace'], 'foreign network namespace'
  191. assert not row.get('argvOverflow',False) and not row.get('argvMalformed',False), 'overflow/malformed actual cmdline'
  192. if row.get('readFailure') in ['FileNotFoundError','ProcessLookupError']:
  193. race = ProcessObservationRace('process exited during metadata snapshot'); continue
  194. assert 'readFailure' not in row and not row['argvOverflow'], 'incomplete actual process facts'
  195. assert row['uid'] == ['1000']*4 and row['namespace'] == namespace
  196. assert 0 <= row['cmdlineBytes'] <= 8192, 'actual cmdline byte budget'
  197. if row['freshIdentity'] != [p[1],p[2],p[4],p[5]]:
  198. assert row['freshIdentity'][3] == p[5], 'PID reused during metadata snapshot'
  199. race = ProcessObservationRace('process changed during metadata snapshot')
  200. if row['cmdlineBytes'] == 0:
  201. assert row['argv'] == [], 'inconsistent empty actual cmdline'
  202. race = ProcessObservationRace('empty cmdline during metadata snapshot')
  203. if race: raise race
  204. def active_descendants(snapshot, leader, namespace, root, previous, birth_floor, deadline, cwd_allowances=None):
  205. active_resource_bounds(snapshot)
  206. assert time.monotonic() < deadline, 'native runtime budget'
  207. rows = snapshot['rows']; bypid = {r['stat'][0]:r for r in rows}
  208. assert snapshot['namespace'] == namespace and len(bypid) == len(rows), 'foreign namespace/duplicate PID'
  209. assert 1 in bypid and leader[0] == leader[2] == leader[4] > 1, 'unique native leader'
  210. assert birth_floor <= leader[5] <= snapshot['bornUpperTicks'], 'fresh native leader birth'
  211. identities = dict(previous)
  212. for row in rows:
  213. p = row['stat']; old = previous.get(p[0])
  214. assert len(p) == 6 and p[0] > 0 and p[3] >= 0 and p[5] > 0, 'invalid process stat'
  215. assert not old or old['start'] == p[5], 'PID start identity changed'
  216. if 'uid' in row: assert row['uid'] == ['1000']*4, 'foreign UID'
  217. if 'namespace' in row: assert row['namespace'] == namespace, 'foreign PID namespace'
  218. if p[0] != 1:
  219. assert leader[5] <= p[5] <= snapshot['bornUpperTicks'], 'monotonic process birth bound'
  220. if 'cwd' in row: assert row['cwd'] == (cwd_allowances or {}).get((p[0],p[5]),str(root/'workspace')), 'foreign process cwd'
  221. identities[p[0]] = {'start':p[5]}
  222. assert bypid[1]['stat'][1] == 0, 'private namespace controller'
  223. assert leader[0] in bypid, 'native leader missing'
  224. observed = bypid[leader[0]]['stat']
  225. assert observed[1] == 1 and observed[2] == observed[4] == leader[0] and observed[5] == leader[5], 'native leader identity'
  226. for pid in bypid.keys()-{1}:
  227. cursor = pid; visited = set()
  228. while cursor != leader[0]:
  229. assert cursor in bypid and cursor not in visited, 'disconnected/cyclic active ancestry'
  230. visited.add(cursor); p = bypid[cursor]['stat']; parent = p[1]
  231. if parent == 1:
  232. assert previous.get(cursor) == {'start':p[5]}, 'unobserved controller adoption'
  233. break
  234. assert parent in bypid and bypid[parent]['stat'][5] <= p[5], 'foreign/reused active parent'
  235. cursor = parent
  236. complete_process_facts(snapshot,namespace)
  237. return identities # retain validated PID/start pairs across exits and shell/Node execs
  238. def active_namespace(snapshot, network, root):
  239. assert snapshot['netNamespace'] == network, 'controller network namespace changed'
  240. assert all(r['netNamespace'] == network for r in snapshot['rows']), 'foreign network namespace'
  241. assert next(r for r in snapshot['rows'] if r['stat'][0] == 1)['cwd'] == str(root/'workspace'), 'controller TEST cwd'
  242. def record_refusal(evidence, snapshot, error):
  243. raw = (json.dumps({'failure':type(error).__name__+':'+str(error),'snapshot':snapshot})+'\n').encode()
  244. target = evidence/'active-process-refusals.jsonl'
  245. assert len(raw)+(target.stat().st_size if target.exists() else 0) <= 16*LIMIT, 'refusal diagnostics budget'
  246. with target.open('ab') as f: f.write(raw)
  247. def observe_owned_active(evidence, leader, namespace, network, root, previous, checks, birth_floor, deadline, parent, installed=None):
  248. observed_previous = dict(previous)
  249. for attempt in range(32):
  250. snapshot = capture_active(evidence,own_processes(),namespace,'active',observed_previous,checks,birth_floor)
  251. try:
  252. active_resource_bounds(snapshot)
  253. assert time.monotonic() < deadline, 'native runtime budget'
  254. for row in snapshot['rows']:
  255. p = row['stat']; old = observed_previous.get(p[0])
  256. assert not old or old['start'] == p[5], 'PID start identity changed during fresh observations'
  257. if not old: observed_previous[p[0]] = {'start':p[5], 'validated':False}
  258. if parent.poll() is not None: return snapshot, observed_previous # unchanged strict postparent checks
  259. identities = active_descendants(snapshot,leader,namespace,root,observed_previous,birth_floor,deadline, native_cwd_allowances(snapshot,root,installed) if installed else None)
  260. active_namespace(snapshot,network,root)
  261. (evidence/'last-validated-active-process-snapshot.json').write_text(json.dumps(snapshot,indent=2)+'\n')
  262. return snapshot, identities
  263. except Exception as e:
  264. record_refusal(evidence,snapshot,e)
  265. if not isinstance(e,ProcessObservationRace) or attempt == 31: raise
  266. assert time.monotonic() < deadline, 'native runtime budget'
  267. time.sleep(min(.01,max(0,deadline-time.monotonic())))
  268. def observe_cleanup_facts(evidence, namespace, network, root, previous, checks, birth_floor, deadline):
  269. for attempt in range(4):
  270. snapshot = capture_active(evidence,own_processes(),namespace,'after-natural-before-strict-cleanup',previous,checks,birth_floor)
  271. try:
  272. active_resource_bounds(snapshot)
  273. assert time.monotonic() < deadline, 'cleanup deadline'
  274. complete_process_facts(snapshot,namespace); active_namespace(snapshot,network,root)
  275. return snapshot
  276. except Exception as e:
  277. record_refusal(evidence,snapshot,e)
  278. if not isinstance(e,ProcessObservationRace) or attempt == 3: raise
  279. assert time.monotonic() < deadline, 'cleanup deadline'
  280. time.sleep(min(.01,max(0,deadline-time.monotonic())))
  281. def validate_stop(root,run):
  282. evidence = root/'evidence'; record = strict_json((evidence/'native-stop.json').read_text())
  283. assert set(record) == {'event','ctxActive','cwd','home','pid','ppid'}, 'unknown SDK callback output'
  284. event = {'hook_event_name':'stop','status':'completed','conversation_id':run['conversation'],
  285. 'generation_id':run['generation'],'model':'TEST-native-stop','model_id':'TEST-native-stop',
  286. 'workspace_roots':[str(root/'workspace')],'cursor_version':'2026.09.28-64d2043',
  287. 'loop_count':0,'transcript_path':None,'user_email':''}
  288. assert json.dumps(record['event'],sort_keys=True) == json.dumps(event,sort_keys=True) and record['ctxActive'] is True
  289. assert record['home'] == str(root/'home') and record['cwd'] == str(root/'workspace')
  290. facts = strict_json((evidence/'native-fd-facts.json').read_text())
  291. assert record['pid'] == facts['observerPid'] and record['ppid'] == facts['probePid']
  292. for fd in ['0','1','2']:
  293. assert facts[fd]['socket'] and not facts[fd]['pipe'] and facts[fd]['domain'] == 1 and facts[fd]['socketType'] == 1
  294. def validate_output(evidence,run):
  295. output = strict_json((evidence/'native.stdout').read_text())
  296. assert set(output) == {'type','subtype','is_error','result','session_id','request_id','duration_ms','duration_api_ms'}, 'unknown native output'
  297. assert all(type(output[k]) is int and 0 <= output[k] <= 90000 for k in ['duration_ms','duration_api_ms'])
  298. assert output['type'] == 'result' and output['subtype'] == 'success' and output['is_error'] is False
  299. assert output['result'] == 'TEST deterministic turn complete'
  300. assert output['session_id'] == run['conversation'] and output['request_id'] == run['requestId']
  301. assert (evidence/'native.stderr').read_bytes() == b'', 'native stderr'
  302. def worker_roles(children,artifact,root,namespace):
  303. roles = []
  304. for p in children:
  305. try:
  306. proc = pathlib.Path('/proc',str(p[0]))
  307. with (proc/'cmdline').open('rb') as f: raw = f.read(4097)
  308. assert len(raw) <= 4096, 'owned argv budget'
  309. assert raw == b'\0'.join([str(artifact/'node').encode(),str(artifact/'index.js').encode(),b'worker-server',b''])
  310. assert os.readlink(proc/'exe') == str(artifact/'node') and os.readlink(proc/'cwd') == str(root/'workspace')
  311. assert os.readlink(proc/'ns/pid') == namespace
  312. assert next(l for l in (proc/'status').read_text().splitlines() if l.startswith('Uid:')).split()[1:] == ['1000']*4
  313. fresh = next(q for q in own_processes() if q[0] == p[0]); assert fresh[2] == p[2] and fresh[4:] == p[4:], 'fresh worker identity'
  314. roles.append({'pid':p[0],'workerServerArgvMatches':True,'executableIsPinnedNode':True,
  315. 'cwdMatches':True,'uid':1000,'startTicks':p[5],'pgid':p[2],'sid':p[4]})
  316. except (FileNotFoundError,ProcessLookupError,StopIteration):
  317. roles.append({'pid':p[0],'exitedBeforeRoleSnapshot':True})
  318. return roles
  319. class IncompleteInstalledContract(RuntimeError): pass
  320. class CaseClock:
  321. """One outer/work deadline and eight seconds of cumulative joining work."""
  322. def __init__(self, outer_deadline):
  323. self.outer = outer_deadline
  324. self.work = None
  325. self.cleanup_used = 0.0
  326. def native_started(self):
  327. if self.work is None:
  328. self.work = min(time.monotonic()+90, self.outer-8)
  329. self.wait(90)
  330. def wait(self, local_cap, cleanup=False):
  331. end = self.outer if cleanup else min(self.outer-8, self.work or self.outer-8)
  332. remaining = end-time.monotonic()
  333. if cleanup:
  334. remaining = min(remaining, 8-self.cleanup_used)
  335. assert remaining > 0, 'original absolute/cumulative deadline exhausted'
  336. return min(local_cap, remaining)
  337. def cleanup_deadline(self):
  338. return time.monotonic()+self.wait(8, cleanup=True)
  339. def charge_cleanup(self, began):
  340. self.cleanup_used += time.monotonic()-began
  341. assert self.cleanup_used <= 8 and time.monotonic() < self.outer, 'cumulative cleanup allowance'
  342. def startup_identity(pid, expected=None):
  343. """Provisional own-child tuple; never full executable qualification."""
  344. def sample():
  345. raw = (pathlib.Path('/proc')/str(pid)/'stat').read_text()
  346. tail = raw[raw.rindex(')')+2:].split()
  347. return {'pid':int(raw[:raw.index('(')].strip()),'birth':int(tail[19]),
  348. 'ppid':int(tail[1]),'pgid':int(tail[2]),'sid':int(tail[3]),'startup':True}
  349. facts = sample()
  350. assert facts == sample(), 'startup tuple race'
  351. assert facts['pid'] == pid and facts['ppid'] == os.getpid() and facts['pgid'] == facts['sid'] == pid, 'own startup child tuple'
  352. if expected is not None:
  353. assert facts == expected, 'startup tuple changed'
  354. return facts
  355. def proc_identity(pid, expected=None, startup=False, leader_parent=None):
  356. """Ancestor-visible identities; no inferred birth or PID-only ownership."""
  357. p = pathlib.Path('/proc')/str(pid)
  358. raw = (p/'stat').read_text()
  359. tail = raw[raw.rindex(')')+2:].split()
  360. status = {}
  361. for line in (p/'status').read_text().splitlines():
  362. key, sep, value = line.partition(':')
  363. if sep: status[key] = value.strip()
  364. cmdline = (p/'cmdline').read_bytes()
  365. if startup:
  366. assert expected is not None and expected.get('startup') is True, 'startup sample requires retained tuple'
  367. assert int(tail[19]) == expected['birth'] and int(tail[1]) == expected['ppid'] and int(tail[2]) == expected['pgid'] and int(tail[3]) == expected['sid'], 'startup sampled tuple changed'
  368. startup_identity(pid,expected)
  369. if cmdline == b'':
  370. assert tail[0] not in ('Z','X','x'), 'startup process terminal'
  371. return None
  372. immutable = ('pid','birth','ppid','tgid','uids','gids','groups','nspid','tracer','ns','uidMap','gidMap')
  373. if leader_parent is not None and cmdline == b'':
  374. fresh = trace_task_identity(pid)
  375. assert expected is not None and all(fresh[key] == expected[key] for key in immutable), 'leader observation authority drift'
  376. assert tail[0] not in ('Z','X','x') and fresh['ppid'] == leader_parent and fresh['pgid'] == fresh['sid'] == pid, 'leader observation parent/session/terminal'
  377. assert (int(raw[:raw.index('(')].strip()),int(tail[19]),int(tail[1]),int(tail[2]),int(tail[3])) == tuple(fresh[key] for key in ('pid','birth','ppid','pgid','sid')), 'leader observation stat bookend'
  378. assert int(status['Tgid']) == fresh['tgid'] and int(status['TracerPid']) == fresh['tracer'] and all(list(map(int,status[field].split())) == fresh[key] for field,key in (('Uid','uids'),('Gid','gids'),('Groups','groups'),('NSpid','nspid'))), 'leader observation status bookend'
  379. raise ProcessObservationRace('empty selected leader cmdline observation')
  380. if not (0 < len(cmdline) <= 8192 and cmdline.endswith(b'\0')):
  381. try:
  382. print('argv-budget-refusal', {'pid':int(pid), 'cmdlineBytes':len(cmdline),
  383. 'endsNUL':cmdline.endswith(b'\0'), 'state':tail[0][:1], 'birth':tail[19][:32],
  384. 'expectedBirth':str(expected.get('birth',''))[:32] if expected is not None else None},
  385. file=sys.stderr,flush=True)
  386. except Exception:
  387. pass
  388. assert 0 < len(cmdline) <= 8192 and cmdline.endswith(b'\0'), 'actual argv budget'
  389. facts = {'pid':int(pid), 'birth':int(tail[19]), 'ppid':int(tail[1]),
  390. 'pgid':int(tail[2]), 'sid':int(tail[3]), 'tgid':int(status['Tgid']),
  391. 'uids':list(map(int,status['Uid'].split())), 'gids':list(map(int,status['Gid'].split())),
  392. 'groups':list(map(int,status['Groups'].split())), 'nspid':list(map(int,status['NSpid'].split())),
  393. 'tracer':int(status['TracerPid']), 'argv':[v.decode('utf-8','strict') for v in cmdline[:-1].split(b'\0')],
  394. 'exe':os.readlink(p/'exe'), 'cwd':os.readlink(p/'cwd'),
  395. 'ns':{k:os.readlink(p/'ns'/k) for k in ('pid','net','user')},
  396. 'uidMap':(p/'uid_map').read_text(), 'gidMap':(p/'gid_map').read_text()}
  397. assert (p/'stat').read_text().split(') ')[-1].split()[19] == str(facts['birth']), 'birth race'
  398. if expected is not None:
  399. assert facts['pid'] == expected['pid'] and facts['birth'] == expected['birth'], 'PID reuse'
  400. if leader_parent is not None:
  401. assert expected is not None and all(facts[key] == expected[key] for key in immutable), 'leader complete authority drift'
  402. return facts
  403. def trace_task_identity(pid):
  404. """Fresh generic lineage metadata, never selected executable qualification."""
  405. p = pathlib.Path('/proc')/str(pid)
  406. def sample():
  407. raw = (p/'stat').read_text()
  408. tail = raw[raw.rindex(')')+2:].split()
  409. return (int(raw[:raw.index('(')].strip()),int(tail[19]),int(tail[1]),int(tail[2]),int(tail[3])),tail[0]
  410. before,state = sample()
  411. assert before[0] == pid and state not in ('Z','X','x'), 'live trace task required'
  412. status = {}
  413. for line in (p/'status').read_text().splitlines():
  414. key,sep,value = line.partition(':')
  415. if sep: status[key] = value.strip()
  416. facts = {'pid':before[0], 'birth':before[1], 'ppid':before[2],
  417. 'pgid':before[3], 'sid':before[4], 'tgid':int(status['Tgid']),
  418. 'uids':list(map(int,status['Uid'].split())), 'gids':list(map(int,status['Gid'].split())),
  419. 'groups':list(map(int,status['Groups'].split())), 'nspid':list(map(int,status['NSpid'].split())),
  420. 'tracer':int(status['TracerPid']), 'ns':{k:os.readlink(p/'ns'/k) for k in ('pid','net','user')},
  421. 'uidMap':(p/'uid_map').read_text(), 'gidMap':(p/'gid_map').read_text()}
  422. after,state = sample()
  423. assert after == before and state not in ('Z','X','x'), 'trace task metadata race'
  424. return facts
  425. def decoded_hex_string(token):
  426. assert re.fullmatch(r'"(?:\\x[0-9a-fA-F]{2})*"', token), 'abbreviated/unknown strace string'
  427. return bytes.fromhex(token[1:-1].replace('\\x',''))
  428. def captured_stop_bytes(raw):
  429. assert type(raw) is bytes and 0 < len(raw) <= LIMIT, 'native payload budget'
  430. text = raw.decode('utf-8', 'strict')
  431. def pairs(items):
  432. result = {}
  433. for key, value in items:
  434. assert key not in result, 'duplicate native JSON key'
  435. result[key] = value
  436. return result
  437. def constant(value): raise AssertionError('nonfinite JSON number')
  438. value, end = json.JSONDecoder(object_pairs_hook=pairs,parse_constant=constant).raw_decode(text)
  439. assert re.fullmatch(r'[ \t\r\n]*',text[end:]), 'trailing non-JSON native payload bytes'
  440. assert type(value) is dict and value.get('hook_event_name') == 'stop', 'actual Cursor Stop required'
  441. for key in ('conversation_id','generation_id'):
  442. s = value.get(key)
  443. assert type(s) is str and 0 < len(s.encode('utf-8')) <= 256, 'native ID bounds'
  444. assert not any(unicodedata.category(c) == 'Cc' for c in s), 'native ID control character'
  445. assert value.get('status') in ('completed','aborted','error'), 'unknown stopping status'
  446. count = value.get('loop_count')
  447. assert count is None or type(count) is int and 0 <= count <= 2147483647, 'native loop count'
  448. return {'conversation':value['conversation_id'], 'generation':value['generation_id'],
  449. 'status':value['status'], 'loopCountKnown':count is not None, 'loopCount':count or 0}
  450. def stdin_endpoint_facts(link, mode, inode, unix):
  451. """Passive /proc endpoint qualification; Node pipes may be Unix sockets."""
  452. match = re.fullmatch(r'(pipe|socket):\[(\d+)\]',link)
  453. assert match and int(match[2]) == inode, 'stdin endpoint inode/link mismatch'
  454. if match[1] == 'pipe':
  455. assert stat.S_ISFIFO(mode), 'stdin pipe mode mismatch'
  456. return {'kind':'pipe','link':link,'inode':inode,'mode':mode}
  457. assert stat.S_ISSOCK(mode) and len(unix) <= LIMIT, 'stdin socket mode/table bound'
  458. rows = []
  459. for line in unix.decode('ascii','strict').splitlines()[1:]:
  460. fields = line.split(maxsplit=7)
  461. assert len(fields) >= 7, 'unknown Unix socket table row'
  462. if fields[6] == str(inode): rows.append(fields)
  463. assert len(rows) == 1 and rows[0][4] == '0001' and rows[0][5] == '03', 'stdin is not a proven connected AF_UNIX SOCK_STREAM'
  464. return {'kind':'socket','link':link,'inode':inode,'mode':mode,
  465. 'family':'AF_UNIX','type':'SOCK_STREAM','state':'connected'}
  466. def live_stdin_endpoint(tid):
  467. proc = pathlib.Path('/proc')/str(tid)
  468. fd = proc/'fd/0'
  469. link = os.readlink(fd); first = fd.stat()
  470. unix = b''
  471. if link.startswith('socket:'):
  472. with (proc/'net/unix').open('rb') as table: unix = table.read(LIMIT+1)
  473. result = stdin_endpoint_facts(link,first.st_mode,first.st_ino,unix)
  474. last = fd.stat()
  475. assert os.readlink(fd) == link and (first.st_mode,first.st_dev,first.st_ino) == (last.st_mode,last.st_dev,last.st_ino), 'stdin endpoint replacement during qualification'
  476. result['device'] = first.st_dev
  477. return result
  478. class StdinAliasTrace:
  479. """Consume ordinary -xx syscall text. Only selected helper evidence survives.
  480. A task key is (outer TID, actual birth). Shared clone tables have reference
  481. identity; copied tables do not. Exec unshares and removes CLOEXEC descriptors.
  482. No descriptor number is a lineage fact until a selected live exec and dup(0).
  483. """
  484. MAX_STREAM = 512*LIMIT
  485. MAX_LINE = 5*LIMIT # strace's \xHH output expands each byte to four ASCII bytes.
  486. MAX_EVENTS = 1000000
  487. def __init__(self, identity, helper_argv, helper_hash, controller, tracer, root):
  488. self.identity = identity
  489. self.helper_argv = helper_argv
  490. self.helper_hash = helper_hash
  491. self.controller = controller
  492. self.tracer = tracer
  493. self.root = pathlib.Path(root)
  494. self.tasks = {}
  495. self.pending = {}
  496. self.pending_reads = {}
  497. self.selected = []
  498. self.total = self.events = 0
  499. self.fragment = b''
  500. self.error = None
  501. self.checkpoints = set()
  502. self.clone_edges = {}
  503. self.remap_history = {}
  504. self.lock = threading.RLock()
  505. self.changed = threading.Condition(self.lock)
  506. def held_clone(self, parent_tid, child_tid, parent_birth, child_birth, raw_flags):
  507. """Admit only the actual paired kernel stops, before either resumes."""
  508. parent = self.register(parent_tid)
  509. assert parent['key'] == (parent_tid,parent_birth), 'held parent birth'
  510. prefix = self.pending.get(parent_tid,'')
  511. assert prefix.startswith(('clone(','clone3(','fork(','vfork(')), 'held clone entry absent'
  512. flags = set(re.findall(r'\bCLONE_[A-Z0-9_]+\b',prefix))
  513. assert ('CLONE_FILES' in flags) == bool(raw_flags & 0x400), 'held CLONE_FILES mismatch'
  514. assert ('CLONE_THREAD' in flags) == bool(raw_flags & 0x10000), 'held CLONE_THREAD mismatch'
  515. fresh = trace_task_identity(child_tid)
  516. assert fresh['birth'] == child_birth, 'held child birth'
  517. outer = self.namespace_child(fresh['nspid'][-1],parent,flags,child_tid)
  518. child = self.tasks[outer]
  519. assert child.get('parent') is None and not child.get('capture'), 'held child already admitted'
  520. for field in ('uids','gids','groups','tracer','ns','uidMap','gidMap'):
  521. assert fresh[field] == parent['facts'][field], 'held child authority/inheritance'
  522. fd_proof = self.clone_fds(parent_tid,child_tid,flags)
  523. child['parent'] = parent['key']
  524. child['fds'] = parent['fds'] if 'CLONE_FILES' in flags else copy.deepcopy(parent['fds'])
  525. capture = parent.get('capture')
  526. if capture: assert {'CLONE_FILES','CLONE_THREAD'} <= flags, 'unexpected selected helper fork/FD unshare'
  527. if 'CLONE_THREAD' in flags: child['capture'] = capture
  528. assert parent['key'] not in self.clone_edges, 'unreconciled clone edge'
  529. self.clone_edges[parent['key']] = {'key':child['key'],'local':fresh['nspid'][-1],
  530. 'flags':flags,'prefix':prefix,'fds':fd_proof}
  531. assert trace_task_identity(parent_tid) == parent['facts'], 'held parent drift'
  532. assert trace_task_identity(child_tid) == fresh, 'held child drift'
  533. for recorded in child.pop('earlyChildCalls',[]): self.line(str(child_tid)+' '+recorded)
  534. def clone_fds(self, parent_tid, child_tid, flags):
  535. assert platform.machine() == 'x86_64', 'qualified Linux clone/table ABI'
  536. libc = ctypes.CDLL(None,use_errno=True)
  537. same_table = libc.syscall(312,parent_tid,child_tid,2,0,0) # Linux/amd64 kcmp(KCMP_FILES).
  538. assert same_table >= 0 and (same_table == 0) == ('CLONE_FILES' in flags), 'actual clone FD table sharing'
  539. def fd_numbers(tid):
  540. values = {int(p.name) for p in (pathlib.Path('/proc')/str(tid)/'fd').iterdir()}
  541. assert len(values) <= 4096, 'held inheritance FD cap'
  542. return values
  543. inherited_fds = fd_numbers(parent_tid)
  544. assert fd_numbers(child_tid) == inherited_fds and set(self.tasks[parent_tid]['fds']) <= inherited_fds, 'held complete FD inheritance'
  545. proof = {}
  546. for fd in inherited_fds:
  547. def endpoint(tid):
  548. entry = pathlib.Path('/proc')/str(tid)/'fd'/str(fd)
  549. before = entry.stat(); link = os.readlink(entry); after = entry.stat()
  550. assert (before.st_dev,before.st_ino,before.st_mode) == (after.st_dev,after.st_ino,after.st_mode), 'inherited fd replacement'
  551. info = (pathlib.Path('/proc')/str(tid)/'fdinfo'/str(fd)).read_text()
  552. flags_at_stop = re.search(r'^flags:\s+([0-7]+)$',info,re.M)
  553. assert flags_at_stop, 'inherited fd flags'
  554. return (link,before.st_dev,before.st_ino,before.st_mode,int(flags_at_stop[1],8))
  555. before = endpoint(parent_tid)
  556. assert endpoint(child_tid) == before == endpoint(parent_tid), 'actual held FD inheritance'
  557. proof[fd] = before
  558. assert fd_numbers(parent_tid) == fd_numbers(child_tid) == inherited_fds, 'inherited FD set drift'
  559. return proof
  560. def task_for_key(self, key):
  561. task = self.tasks.get(key[0])
  562. if task is None or task['key'] != key: task = self.remap_history.get(key)
  563. assert task is not None and task['key'] == key, 'unknown historical task birth'
  564. return task
  565. def exec_remap(self, tid, old_tid):
  566. old = self.tasks[old_tid]; leader = self.tasks[tid]
  567. assert old_tid != tid and old['facts']['tgid'] == tid, 'actual exec TID remap group'
  568. assert not old.get('capture') and not leader.get('capture') and not leader.get('nativeLeader'), 'selected helper/leader unexpected thread exec'
  569. prefix = self.pending.pop(old_tid,'')
  570. assert prefix.startswith(('execve(','execveat(')), 'remap without admitted exec entry'
  571. facts = trace_task_identity(tid)
  572. for field in ('uids','gids','groups','tracer','ns','uidMap','gidMap'):
  573. assert facts[field] == old['facts'][field], 'fresh exec-remap authority'
  574. assert facts['tgid'] == tid and facts['nspid'] == leader['facts']['nspid'] and facts['ppid'] == leader['facts']['ppid'], 'fresh exec-remap local/parent mapping'
  575. for task in (old,leader): self.remap_history[task['key']] = dict(task)
  576. remapped = dict(old,key=(tid,facts['birth']),facts=facts,parent=leader['parent'])
  577. remapped.pop('exited',None)
  578. remapped['execRemap'] = {'old':old['key'],'superseded':leader['key'],'fresh':remapped['key']}
  579. old['exited'] = True
  580. leader['exited'] = True
  581. leader['supersededPending'] = self.pending.pop(tid,None)
  582. assert tid not in self.pending_reads, 'exec remap cannot cancel selected read custody'
  583. self.tasks[tid] = remapped
  584. self.pending[tid] = prefix
  585. assert trace_task_identity(tid) == facts, 'exec-remap bookend'
  586. def bus_fd(self, tid, fd, connected=False):
  587. proc = pathlib.Path('/proc')/str(tid)
  588. entry = proc/'fd'/str(fd)
  589. link = os.readlink(entry); before = entry.stat()
  590. match = re.fullmatch(r'socket:\[(\d+)\]',link)
  591. assert match and stat.S_ISSOCK(before.st_mode) and int(match[1]) == before.st_ino, 'actual bus socket fd'
  592. with (proc/'net/unix').open('rb') as table: raw = table.read(LIMIT+1)
  593. assert len(raw) <= LIMIT, 'bus socket table cap'
  594. rows = [row.split() for row in raw.decode('ascii').splitlines()[1:]]
  595. rows = [row for row in rows if len(row) >= 7 and row[6] == str(before.st_ino)]
  596. assert len(rows) == 1 and rows[0][4] == '0001', 'fresh AF_UNIX stream socket'
  597. if connected: assert rows[0][5] == '03', 'tracked bus socket is not freshly connected'
  598. after = entry.stat()
  599. assert os.readlink(entry) == link and (before.st_dev,before.st_ino,before.st_mode) == (after.st_dev,after.st_ino,after.st_mode), 'bus fd replacement'
  600. return (before.st_dev,before.st_ino)
  601. def held_entry(self, task, name, arguments, session):
  602. """Closed connect intent and destruction; existing FD ledger is authority."""
  603. capture = task.get('capture')
  604. if not capture:
  605. assert not any(value.get('bus') for value in task['fds'].values()), 'unselected table cannot own watched socket authority'
  606. return None
  607. self.register(task['key'][0])
  608. prefix = self.pending.get(task['key'][0],'')
  609. assert prefix.startswith(name+'('), 'held entry lacks its actual decoded prefix'
  610. unsupported = ('unshare','setns','pidfd_getfd','io_uring_setup','io_uring_enter','io_uring_register',
  611. 'setuid','setgid','setreuid','setregid','setresuid','setresgid','setgroups','capset')
  612. assert name not in unsupported and name not in ('execve','execveat'), 'selected descriptor/identity bypass'
  613. connections = capture.setdefault('busConnections',[])
  614. if name == 'connect' and 'sa_family=AF_UNIX' in prefix:
  615. match = re.search(r'sun_path=("(?:\\x[0-9a-fA-F]{2})*")',prefix)
  616. assert match, 'complete real AF_UNIX connect address'
  617. address = decoded_hex_string(match[1])
  618. assert address == str(session.directory/'bus').encode(), 'selected AF_UNIX connect outside owned bus address'
  619. session.assert_continuous()
  620. assert not connections, 'multiple/ambiguous selected bus connections'
  621. fd = arguments[0]
  622. slot = task['fds'].get(fd)
  623. assert slot is not None and not slot.get('lineage'), 'connect fd has no admitted socket lineage'
  624. conn = {'owner':capture['identity'],'intent':task['key'],'fd':fd,
  625. 'socket':self.bus_fd(task['key'][0],fd),'tables':[task['fds']],
  626. 'connected':False,'outcome':None,'acked':False,'name':None}
  627. slot['bus'] = conn
  628. connections.append(conn) # Watching exists BEFORE connect can execute.
  629. return None
  630. if not connections: return None
  631. assert len(connections) == 1, 'one selected socket incarnation'
  632. conn = connections[0]; table = task['fds']
  633. assert any(table is known for known in conn['tables']), 'unknown bus FD table incarnation'
  634. aliases = [fd for fd,value in table.items() if value.get('bus') is conn]
  635. for fd in aliases: assert self.bus_fd(task['key'][0],fd,conn['connected']) == conn['socket'], 'tracked bus fd reused'
  636. entries = list((pathlib.Path('/proc')/str(task['key'][0])/'fd').iterdir())
  637. assert len(entries) <= 4096, 'fresh bus alias FD cap'
  638. live_aliases = set()
  639. for entry in entries:
  640. if os.readlink(entry) == 'socket:['+str(conn['socket'][1])+']':
  641. assert self.bus_fd(task['key'][0],int(entry.name),conn['connected']) == conn['socket'], 'fresh watched alias identity'
  642. live_aliases.add(int(entry.name))
  643. assert live_aliases == set(aliases), 'unconsumed/unknown watched socket alias'
  644. for other in self.tasks.values():
  645. if other.get('exited'): continue
  646. if other['fds'] is table and other['key'] != task['key']:
  647. pending = self.pending.get(other['key'][0],'')
  648. assert not pending.startswith(('dup(','dup2(','dup3(','fcntl(','close(','close_range(',
  649. 'socket(','socketpair(','open(','openat(','openat2(','pipe(','pipe2(','accept(','accept4(')), 'lagging alias/table record'
  650. fd = arguments[0]
  651. destroys = (name in ('close','shutdown') and fd in aliases or
  652. name in ('dup2','dup3') and arguments[1] in aliases and fd != arguments[1] or
  653. name == 'close_range' and any((fd & 0xffffffff) <= alias <= (arguments[1] & 0xffffffff) for alias in aliases) or
  654. name == 'exit_group' or name == 'exit' and task['facts']['tgid'] == task['key'][0])
  655. if name == 'exit' and not destroys:
  656. owner = self.register(conn['owner']['pid'])
  657. assert owner['fds'] is table and not owner.get('exited') and owner['key'][1] == conn['owner']['birth'], 'thread exit lacks surviving owner/table'
  658. assert self.identity(owner['key'][0]) == conn['owner'], 'surviving peer identity drift'
  659. return conn if destroys and not conn['acked'] else None
  660. def namespace_child(self, local, parent, flags, outer_hint=None):
  661. assert 'CLONE_PARENT' not in flags, 'unsupported clone parent relation'
  662. before = self.register(parent['key'][0])['facts']
  663. scope = pathlib.Path('/proc')/str(before['tgid'])/'task'
  664. tids = {int(p.name) for p in scope.iterdir()} if 'CLONE_THREAD' in flags else {int(p.name) for p in pathlib.Path('/proc').iterdir() if p.name.isdecimal()}
  665. assert len(tids) <= self.MAX_EVENTS, 'clone discovery task budget'
  666. if outer_hint is not None:
  667. assert outer_hint in tids, 'translated child outside original task scope'
  668. tids = {outer_hint}
  669. matches = []
  670. discovery_counts = dict.fromkeys(('statusGone','depthMismatch','localMismatch','parentMismatch','pidnsMismatch','matched'),0)
  671. for tid in sorted(tids):
  672. ids = [] # Failure context must not carry the preceding candidate's IDs.
  673. proc = pathlib.Path('/proc')/str(tid)
  674. try:
  675. rows = (proc/'status').read_text().splitlines()
  676. except FileNotFoundError:
  677. discovery_counts['statusGone'] += 1
  678. if 'CLONE_THREAD' in flags: raise
  679. continue # An unqualified enumeration entry disappeared.
  680. status = dict(row.split(':',1) for row in rows if ':' in row)
  681. ids = list(map(int,status['NSpid'].split()))
  682. if len(ids) == len(before['nspid']) and ids[-1] == local and ('CLONE_THREAD' in flags or int(status['PPid']) == before['tgid']):
  683. if os.readlink(proc/'ns/pid') != before['ns']['pid']:
  684. discovery_counts['pidnsMismatch'] += 1
  685. continue
  686. child = self.register(tid)
  687. assert child['facts']['nspid'] == ids, 'clone namespace mapping race'
  688. matches.append(child)
  689. discovery_counts['matched'] += 1
  690. else:
  691. reason = 'depthMismatch' if len(ids) != len(before['nspid']) else 'localMismatch' if ids[-1] != local else 'parentMismatch'
  692. discovery_counts[reason] += 1
  693. assert len(matches) == 1, 'one exact namespace child mapping required'
  694. self.register(parent['key'][0])
  695. facts = matches[0]['facts']
  696. if 'CLONE_THREAD' in flags:
  697. assert facts['tgid'] == before['tgid'], 'clone thread parent group'
  698. else:
  699. assert facts['tgid'] == facts['pid'] and facts['ppid'] == before['tgid'], 'clone process parent group'
  700. if outer_hint is not None:
  701. assert facts['pid'] == outer_hint, 'translated child mapping mismatch'
  702. return facts['pid']
  703. def register(self, tid, parent=None, shared=False):
  704. facts = trace_task_identity(tid)
  705. assert facts['ns'] == self.controller['ns'], 'trace namespace drift'
  706. assert facts['uids'] == facts['gids'] == [1000]*4 and facts['groups'] == [], 'trace credential drift'
  707. assert facts['tracer'] == self.tracer['pid'], 'untraced task'
  708. key = (tid, facts['birth'])
  709. if tid in self.tasks:
  710. assert self.tasks[tid]['key'] == key, 'trace PID reuse'
  711. old = self.tasks[tid]['facts']
  712. assert all(facts[field] == old[field] for field in ('tgid','uids','gids','groups','nspid','tracer','ns','uidMap','gidMap')), 'fresh task authority drift'
  713. return self.tasks[tid]
  714. table = parent['fds'] if parent is not None and shared else copy.deepcopy(parent['fds']) if parent else {}
  715. task = {'key':key,'facts':facts,'fds':table,'parent':parent['key'] if parent else None,
  716. 'capture':parent.get('capture') if parent and shared else None}
  717. self.tasks[tid] = task
  718. return task
  719. def feed(self, chunk):
  720. with self.lock:
  721. assert self.error is None, self.error
  722. self.total += len(chunk)
  723. assert self.total <= self.MAX_STREAM, 'total raw trace/hex-expansion budget'
  724. self.fragment += chunk
  725. while b'\n' in self.fragment:
  726. line, self.fragment = self.fragment.split(b'\n',1)
  727. assert len(line) <= self.MAX_LINE, 'trace line budget'
  728. self.line(line.decode('ascii','strict'))
  729. self.changed.notify_all()
  730. assert len(self.fragment) <= self.MAX_LINE, 'partial trace line budget'
  731. def line(self, line):
  732. marker = re.fullmatch(r'# R1353 ([1-9][0-9]{0,6})',line)
  733. if marker:
  734. sequence = int(marker[1])
  735. assert sequence <= self.MAX_EVENTS and sequence not in self.checkpoints, 'checkpoint sequence'
  736. self.checkpoints.add(sequence)
  737. return
  738. self.events += 1
  739. assert self.events <= self.MAX_EVENTS, 'trace record budget'
  740. m = re.fullmatch(r'(?:\[pid\s+)?(\d+)(?:\])?\s+(.+)',line)
  741. assert m, 'unqualified trace record'
  742. tid, call = int(m[1]), m[2]
  743. remap = re.fullmatch(r'\+\+\+ superseded by execve in pid ([1-9][0-9]*) \+\+\+',call)
  744. if remap:
  745. self.exec_remap(tid,int(remap[1]))
  746. return
  747. task = self.tasks.get(tid) or self.register(tid)
  748. if task.get('parent') is None and task['facts']['tgid'] != self.controller['pid'] and not task.get('nativeLeader'):
  749. clones = [prefix for prefix in self.pending.values() if prefix.startswith(('clone(','clone3(','fork(','vfork('))]
  750. if clones:
  751. queued = task.setdefault('earlyChildCalls',[])
  752. assert len(queued) < 256 and sum(len(value) for value in queued)+len(call) <= LIMIT, 'early child trace bound'
  753. queued.append(call)
  754. return
  755. if call.startswith('--- SIG'):
  756. assert tid in self.tasks and not self.tasks[tid].get('exited') and (task.get('parent') or task.get('nativeLeader') or task['facts']['tgid'] == self.controller['pid']), 'signal from unknown/terminal task'
  757. assert 'SIGKILL' not in call, 'forced native termination'
  758. return
  759. if call.startswith('+++ killed by '):
  760. assert call == '+++ killed by SIGTERM +++' and tid in self.tasks, 'unknown/forced terminal signal'
  761. task = self.tasks[tid]
  762. assert not task.get('exited') and not task.get('capture') and not task.get('nativeLeader'), 'helper/leader/control termination cannot pass'
  763. ancestor = task
  764. while ancestor.get('parent'):
  765. key = ancestor['parent']; ancestor = self.task_for_key(key)
  766. assert ancestor['key'] == key, 'terminal ancestry birth mismatch'
  767. if ancestor.get('nativeLeader'): break
  768. assert ancestor.get('nativeLeader'), 'non-native terminal signal'
  769. group = self.tasks.get(task['facts']['tgid'])
  770. assert group is not None, 'unknown terminal process birth'
  771. task['terminalCancellation'] = {'record':call,'pendingSyscall':self.pending.pop(tid,None),
  772. 'pendingRead':self.pending_reads.pop(tid,None),'leader':ancestor['key'],'worker':group['key']}
  773. # Immutable cancel; owned cleanup.
  774. pending_read = task['terminalCancellation']['pendingRead']
  775. if pending_read is not None: task['terminalCancellation']['pendingRead'] = {'fd':pending_read[0],'lineageAtEntry':pending_read[1]}
  776. task['exited'] = True
  777. return
  778. if call.startswith('+++ exited with '):
  779. assert tid in self.tasks and tid not in self.pending and (task.get('parent') or task.get('nativeLeader') or task['facts']['tgid'] == self.controller['pid']), 'unobserved/unfinished exit'
  780. task = self.tasks[tid]
  781. capture = task.get('capture')
  782. if capture and task['facts']['tgid'] == tid:
  783. assert call == '+++ exited with 0 +++', 'helper natural exit required'
  784. assert capture['eof'] and capture['bytes'] and capture['dupSeen'], 'incomplete consumed stdin'
  785. capture['exited'] = True
  786. task['exited'] = True
  787. return
  788. task = self.tasks.get(tid) or self.register(tid)
  789. assert not task.get('exited'), 'trace after terminal identity'
  790. if '<unfinished ...>' in call:
  791. assert tid not in self.pending and call.endswith(' <unfinished ...>'), 'ambiguous unfinished syscall'
  792. prefix = call[:-len(' <unfinished ...>')]
  793. if prefix.startswith('read('):
  794. fd = int(prefix.split('(',1)[1].split(',',1)[0])
  795. self.pending_reads[tid] = (fd,dict(task['fds'][fd]) if fd in task['fds'] else None,task['fds'])
  796. if task.get('capture') and task['fds'].get(fd,{}).get('lineage'):
  797. capture = task['capture']
  798. assert capture['reading'] is None, 'concurrent stdin reads have ambiguous ordering'
  799. capture['reading'] = tid
  800. self.pending[tid] = prefix
  801. return
  802. resumed = re.fullmatch(r'<\.\.\. (\w+) resumed>(.*)',call)
  803. if resumed:
  804. assert tid in self.pending, 'resumed without unfinished'
  805. prefix = self.pending.pop(tid)
  806. assert prefix.startswith(resumed[1]+'('), 'resumed syscall mismatch'
  807. call = prefix+resumed[2]
  808. if tid in self.pending_reads:
  809. fd,old,table = self.pending_reads.pop(tid)
  810. assert task['fds'] is table and task['fds'].get(fd) == old, 'unfinished read FD lineage changed'
  811. else:
  812. assert tid not in self.pending, 'missing resumed record'
  813. m = re.fullmatch(r'(\w+)\((.*)\)\s+=\s+(.+)',call)
  814. assert m, 'unknown syscall text'
  815. name, args, result = m.groups()
  816. ret = re.match(r'(-?(?:0x[0-9a-f]+|\d+))(?:\s|$)',result)
  817. restart = re.fullmatch(r'\? ERESTART(?:SYS|NOINTR|NOHAND|_RESTARTBLOCK).*',result)
  818. assert ret or result == '?' and name in ('exit','exit_group') or restart and name == 'read', 'unknown syscall result'
  819. number = int(ret[1],0) if ret else None
  820. capture = task.get('capture')
  821. if name in ('execve','execveat') and number == 0:
  822. strings = re.findall(r'"(?:\\x[0-9a-fA-F]{2})*"',args)
  823. assert strings, 'missing exec argv'
  824. # Env abbreviated; HOME /proc proof.
  825. left, sep, rest = args.partition('[')
  826. argtext, close, tail = rest.partition(']')
  827. assert sep and close and '...' not in argtext, 'incomplete exec argv'
  828. argv = [decoded_hex_string(s).decode('utf-8','strict') for s in re.findall(r'"(?:\\x[0-9a-fA-F]{2})*"',argtext)]
  829. assert len(b'\0'.join(a.encode() for a in argv))+1 <= 8192, 'exec argv budget'
  830. task['fds'] = {fd:dict(v) for fd,v in task['fds'].items() if not v.get('cloexec')}
  831. if argv == self.helper_argv:
  832. ancestor = task
  833. assert ancestor.get('parent') is not None, 'unobserved helper ancestry'
  834. while ancestor.get('parent'):
  835. parent_key = ancestor['parent']
  836. ancestor = self.task_for_key(parent_key)
  837. assert ancestor['key'] == parent_key, 'ancestor birth mismatch'
  838. if ancestor.get('nativeLeader'): break
  839. if not ancestor.get('nativeLeader'):
  840. assert ancestor['facts']['tgid'] == self.controller['pid'], 'unknown nonnative helper ancestry'
  841. task['excludedControllerHelper'] = True
  842. return # Exact observed replay/control descendant; never selected native evidence.
  843. facts = self.identity(tid)
  844. assert facts['birth'] == task['key'][1] and facts['argv'] == argv, 'exec live identity/argv mismatch'
  845. assert facts['exe'] == argv[0] and facts['cwd'] == str(self.root/'home/.cursor'), 'source-qualified USER helper executable/cwd'
  846. assert facts['ns'] == self.controller['ns'] and facts['uids'] == facts['gids'] == [1000]*4
  847. assert facts['groups'] == [] and facts['tracer'] == self.tracer['pid']
  848. assert digest(argv[0]) == self.helper_hash, 'actual helper executable hash'
  849. env = (pathlib.Path('/proc')/str(tid)/'environ').read_bytes()
  850. assert len(env) <= 65536 and b'HOME='+str(self.root/'home').encode()+b'\0' in env, 'actual helper HOME'
  851. endpoint = live_stdin_endpoint(tid)
  852. capture = {'identity':facts,'endpoint':endpoint,'bytes':bytearray(),'eof':False,
  853. 'dupSeen':False,'exited':False,'reading':None,
  854. 'events':[{'tidBirth':task['key'],'syscall':call}],'leader':ancestor['key']}
  855. assert len(self.selected) < 2, 'one genuine helper per planned phase'
  856. self.selected.append(capture)
  857. task['capture'] = capture
  858. task['fds'][0] = {'lineage':True,'cloexec':False}
  859. elif capture:
  860. raise AssertionError('selected helper unexpected exec')
  861. elif name in ('clone','clone3','fork','vfork') and number is not None and number > 0:
  862. translated = re.fullmatch(r"([1-9][0-9]{0,9})(?: /\* ([1-9][0-9]{0,9}) in strace's PID NS \*/)?",result)
  863. assert translated and int(translated[1]) == number and number <= 2147483647 and (translated[2] is None or int(translated[2]) <= 2147483647), 'unknown fork PID namespace return'
  864. outer_hint = int(translated[2]) if translated[2] is not None else None
  865. edge = self.clone_edges.pop(task['key'],None)
  866. assert edge is not None and edge['local'] == number, 'return without held clone admission'
  867. assert edge['flags'] == set(re.findall(r'\bCLONE_[A-Z0-9_]+\b',args)), 'clone flags changed at return'
  868. number = edge['key'][0]
  869. assert outer_hint in (None,number), 'held return outer namespace mismatch'
  870. child = self.tasks[number]
  871. assert child['key'] == edge['key'] and child['parent'] == task['key'], 'held return lineage mismatch'
  872. # vfork child exec/exit may precede return: only reconcile the edge
  873. # admitted while both tasks were freshly live, never dead admission.
  874. queued = child.pop('earlyChildCalls',[])
  875. for recorded in queued: self.line(str(number)+' '+recorded)
  876. elif name == 'connect':
  877. conn = task['fds'].get(int(args.split(',',1)[0]),{}).get('bus')
  878. if conn is not None:
  879. assert conn['intent'] == task['key'] and conn['outcome'] is None, 'connect outcome incarnation'
  880. conn['outcome'] = call
  881. conn['connected'] = number == 0
  882. elif name in ('dup','dup2','dup3') and number is not None and number >= 0:
  883. old = int(args.split(',',1)[0])
  884. if name != 'dup': assert number == int(args.split(',')[1]), 'dup target mismatch'
  885. if name == 'dup2' and old == number: return # POSIX no-op preserves FD_CLOEXEC.
  886. task['fds'][number] = dict(task['fds'].get(old,{'lineage':False}))
  887. task['fds'][number]['cloexec'] = 'O_CLOEXEC' in args
  888. if capture and old == 0 and task['fds'][number].get('lineage') and number != 0:
  889. capture['dupSeen'] = True
  890. elif name == 'fcntl' and number is not None and number >= 0:
  891. parts = args.split(','); fd = int(parts[0]); op = parts[1].strip()
  892. if op in ('F_DUPFD','F_DUPFD_CLOEXEC'):
  893. task['fds'][number] = dict(task['fds'].get(fd,{'lineage':False}))
  894. task['fds'][number]['cloexec'] = op.endswith('CLOEXEC')
  895. if capture and fd == 0 and number != 0 and task['fds'][number].get('lineage'): capture['dupSeen'] = True
  896. elif op == 'F_SETFD':
  897. if fd in task['fds']: task['fds'][fd]['cloexec'] = 'FD_CLOEXEC' in args
  898. else:
  899. assert op in ('F_GETFD','F_GETFL','F_SETFL','F_SETLK','F_SETLKW','F_GETLK','F_OFD_SETLK'), 'unaccounted fcntl'
  900. elif name == 'close' and number == 0:
  901. task['fds'].pop(int(args),None)
  902. elif name == 'close_range' and number == 0:
  903. parts = args.split(','); first = int(parts[0]); last = 4294967295 if '~0U' in parts[1] else int(parts[1])
  904. if 'CLOSE_RANGE_UNSHARE' in args:
  905. task['fds'] = {fd:dict(value) for fd,value in task['fds'].items()}
  906. for conn in (capture or {}).get('busConnections',[]):
  907. assert len(conn['tables']) < 4096, 'bus table lineage cap'
  908. conn['tables'].append(task['fds'])
  909. for fd in list(task['fds']):
  910. if first <= fd <= last:
  911. if 'CLOSE_RANGE_CLOEXEC' in args: task['fds'][fd]['cloexec'] = True
  912. else: task['fds'].pop(fd)
  913. elif name in ('open','openat','openat2','socket','accept','accept4','eventfd','eventfd2','epoll_create','epoll_create1','memfd_create') and number is not None and number >= 0:
  914. task['fds'][number] = {'lineage':False,'cloexec':'CLOEXEC' in args}
  915. elif name in ('pipe','pipe2','socketpair') and number == 0:
  916. fds = re.findall(r'\[(\d+),\s*(\d+)\]',args)
  917. assert len(fds) == 1, 'unknown descriptor pair'
  918. for fd in map(int,fds[0]): task['fds'][fd] = {'lineage':False,'cloexec':'CLOEXEC' in args}
  919. elif name == 'read':
  920. assert not any(any(value.startswith('read(') for value in other.get('earlyChildCalls',[])) for other in self.tasks.values()), 'ambiguous consumed order across unresolved child clone'
  921. fd = int(args.split(',',1)[0])
  922. if capture and task['fds'].get(fd,{}).get('lineage'):
  923. assert capture['dupSeen'] and fd != 0 and not capture['eof'], 'read outside consumed alias/completion'
  924. assert capture['reading'] in (None,tid), 'ambiguous read order'
  925. capture['reading'] = None
  926. if restart: pass
  927. elif number == -1:
  928. assert any(result.startswith('-1 '+e) for e in ('EINTR','EAGAIN')), 'failed stdin read'
  929. else:
  930. m = re.fullmatch(r'\d+,\s*("(?:\\x[0-9a-fA-F]{2})*"),\s*(\d+)',args)
  931. assert m and number is not None and 0 <= number <= int(m[2]), 'partial/unknown stdin read'
  932. raw = decoded_hex_string(m[1])
  933. assert len(raw) == number, 'decoded return count mismatch/truncation'
  934. capture['bytes'].extend(raw)
  935. assert len(capture['bytes']) <= LIMIT, 'consumed stdin payload budget'
  936. capture['eof'] = number == 0
  937. assert len(capture['events']) < 4096, 'selected read/lineage event budget'
  938. capture['events'].append({'tidBirth':task['key'],'syscall':call})
  939. elif capture and name in ('readv','pread64','preadv','preadv2','recvfrom','recvmsg','recvmmsg'):
  940. fd = int(args.split(',',1)[0])
  941. assert not task['fds'].get(fd,{}).get('lineage'), 'unknown read on proven stdin lineage: '+name
  942. if name in ('recvmsg','recvmmsg') and number is not None and number >= 0:
  943. assert 'SCM_RIGHTS' not in args and ('msg_controllen=0' in args or 'msg_control=NULL' in args or 'msg_control=[]' in args), 'unknown received descriptor lineage'
  944. elif capture and name in ('splice','tee','vmsplice','io_uring_setup','io_uring_enter','io_uring_register','pidfd_getfd','unshare','setns','setuid','setgid','setreuid','setregid','setresuid','setresgid','setgroups','capset'):
  945. raise AssertionError('unaccounted selected read/FD/identity operation: '+name)
  946. if capture and name in ('dup','dup2','dup3','fcntl','close','close_range','clone','clone3','fork','vfork','exit','exit_group'):
  947. assert len(capture['events']) < 4096, 'selected lineage event budget'
  948. capture['events'].append({'tidBirth':task['key'],'syscall':call})
  949. def finish(self):
  950. with self.lock:
  951. assert not self.fragment and not self.pending and not self.pending_reads and self.error is None and not self.clone_edges and not self.checkpoints and not any(task.get('earlyChildCalls') for task in self.tasks.values()), 'partial trace stream/unknown child ancestry'
  952. assert all(c['exited'] and c['eof'] and c['reading'] is None for c in self.selected), 'unfinished helper stream'
  953. return self.selected
  954. def task_key(task):
  955. return (task['facts']['pid'],task['facts']['birth'])
  956. TRACE_SYSCALLS = (
  957. 'read,readv,pread64,preadv,preadv2,recvfrom,recvmsg,recvmmsg,splice,tee,vmsplice,'
  958. 'dup,dup2,dup3,fcntl,close,close_range,open,openat,openat2,pipe,pipe2,socket,socketpair,'
  959. 'accept,accept4,eventfd,eventfd2,epoll_create,epoll_create1,memfd_create,pidfd_getfd,connect,shutdown,'
  960. 'execve,execveat,clone,clone3,fork,vfork,exit,exit_group,wait4,waitid,'
  961. 'setns,unshare,setuid,setgid,setreuid,setregid,setresuid,setresgid,setgroups,capset,'
  962. 'io_uring_setup,io_uring_enter,io_uring_register')
  963. def control_send(peer, value, clock):
  964. raw = json.dumps(value,separators=(',',':')).encode()
  965. assert len(raw) <= 2*LIMIT, 'control record bound including base64 expansion'
  966. peer.settimeout(clock.wait(5))
  967. peer.sendall(struct.pack('>I',len(raw))+raw)
  968. def control_receive(peer, clock):
  969. def exact(n):
  970. parts = bytearray()
  971. while len(parts) < n:
  972. peer.settimeout(clock.wait(5))
  973. part = peer.recv(n-len(parts))
  974. assert part, 'owned control peer EOF'
  975. parts.extend(part)
  976. return bytes(parts)
  977. size = struct.unpack('>I',exact(4))[0]
  978. assert 0 < size <= 2*LIMIT, 'control record size including base64 expansion'
  979. return strict_json(exact(size))
  980. class ControllerObservation:
  981. def __init__(self, peer, clock):
  982. self.peer, self.clock = peer, clock
  983. self.sequence = 0
  984. self.nonce = os.urandom(32).hex()
  985. self.exchange_lock = threading.Lock()
  986. def exchange(self, action, **facts):
  987. if not self.exchange_lock.acquire(timeout=self.clock.wait(1)): raise AssertionError('control exchange lock deadline')
  988. try: return self._exchange_locked(action,**facts)
  989. finally: self.exchange_lock.release()
  990. def _exchange_locked(self, action, **facts):
  991. self.sequence += 1
  992. control_send(self.peer,{'action':action,'sequence':self.sequence,'nonce':self.nonce,'cleanupUsed':self.clock.cleanup_used,**facts},self.clock)
  993. reply = control_receive(self.peer,self.clock)
  994. assert reply.get('sequence') == self.sequence and reply.get('nonce') == self.nonce, 'control synchronization identity'
  995. assert reply.get('ok') is True, reply.get('error','unknown outer observation')
  996. return reply
  997. def source_failure_frames(error, trusted_code):
  998. frames, tb, visited = [], error.__traceback__, 0
  999. while tb is not None and visited < 64:
  1000. code = tb.tb_frame.f_code
  1001. if code.co_filename == trusted_code.co_filename:
  1002. frames = (frames+[(code.co_name[:64],tb.tb_lineno)])[-8:]
  1003. tb = tb.tb_next; visited += 1
  1004. return frames
  1005. class PassiveStrace:
  1006. def __init__(self, controller, installed, root, clock, tools, session):
  1007. self.session = session
  1008. self.incarnation = os.urandom(32).hex()
  1009. self.observer_sequence = 0
  1010. self.acked_keys = set()
  1011. self.pending_acks = {}
  1012. self.custody_keys = set()
  1013. self.held_workers = []
  1014. self.stopping = False
  1015. self.observer_peer, inherited = socket.socketpair(socket.AF_UNIX,socket.SOCK_SEQPACKET)
  1016. self.clock = clock
  1017. self.controller = controller
  1018. self.root = pathlib.Path(root)
  1019. self.error = None
  1020. self.first_error = None
  1021. self.options = None
  1022. self.seize_stops = set()
  1023. self.debug_bytes = 0
  1024. self.debug_fragment = b''
  1025. self.started_tids = set()
  1026. self.closing_tids = set()
  1027. readfd, writefd = os.pipe()
  1028. primary, selector, binding, generation = installed
  1029. argv = [tools['strace']['path'],'-d','-f','-xx','--decode-pids=pidns','-s',str(LIMIT+1),
  1030. '-e','trace='+TRACE_SYSCALLS,'-o','/proc/self/fd/'+str(writefd),'-p',str(controller['pid'])]
  1031. self.child = subprocess.Popen(argv,stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,
  1032. stderr=subprocess.PIPE,pass_fds=(writefd,inherited.fileno()),env={'PATH':'/usr/bin:/bin','LANG':'C',
  1033. 'TMPDIR':str(self.root/'tmp'),'TEST_R1353_FD':str(inherited.fileno()),
  1034. 'TEST_R1353_INCARNATION':self.incarnation},start_new_session=True,bufsize=0)
  1035. inherited.close()
  1036. os.close(writefd)
  1037. self.tracer = startup_identity(self.child.pid)
  1038. self.tracer = proc_identity(self.child.pid)
  1039. assert self.tracer['argv'] == argv and self.tracer['exe'] == tools['strace']['path']
  1040. assert self.tracer['uids'] == self.tracer['gids'] == [0]*4
  1041. assert self.tracer['ns']['pid'] != controller['ns']['pid'] and self.tracer['ns']['user'] == controller['ns']['user']
  1042. assert self.tracer['uidMap'] == controller['uidMap'] and self.tracer['gidMap'] == controller['gidMap']
  1043. assert self.tracer['ns']['pid'] == os.readlink('/proc/self/ns/pid') == os.readlink('/proc/1/ns/pid'), 'tracer/parser proc PID namespace mismatch'
  1044. self.parser = StdinAliasTrace(proc_identity,[str(primary),'cursor-event','stop','--binding',str(selector)],
  1045. digest(primary),controller,self.tracer,root)
  1046. self.trace_pipe = os.fdopen(readfd,'rb',buffering=0)
  1047. self.threads = []
  1048. def pump(stream, consume):
  1049. try:
  1050. while True:
  1051. part = stream.read(8192)
  1052. if not part: break
  1053. with self.parser.changed:
  1054. try: consume(part)
  1055. except Exception as error:
  1056. self.refuse_held(error)
  1057. raise
  1058. except Exception as error:
  1059. self.refuse_held(error)
  1060. tb = error.__traceback__
  1061. try:
  1062. print('trace-pump-failure',type(error).__name__[:64],'firstStored',error is self.first_error,source_failure_frames(error,pump.__code__),file=sys.stderr,flush=True)
  1063. call_name = None
  1064. while tb is not None:
  1065. if tb.tb_frame.f_code is self.parser.line.__func__.__code__:
  1066. name = tb.tb_frame.f_locals.get('name')
  1067. if name in ('clone','clone3','fork','vfork'): call_name = name
  1068. if tb.tb_frame.f_code is self.parser.namespace_child.__func__.__code__:
  1069. context = tb.tb_frame.f_locals
  1070. parent = context['parent']; before = context.get('before',parent['facts'])
  1071. reported_flags = tuple(flag for flag in ('CLONE_THREAD','CLONE_FILES','CLONE_VM','CLONE_VFORK',
  1072. 'CLONE_PARENT','CLONE_PARENT_SETTID','CLONE_CHILD_SETTID','CLONE_CHILD_CLEARTID',
  1073. 'CLONE_NEWPID','CLONE_NEWUSER','CLONE_NEWNS','CLONE_NEWNET') if flag in context['flags'])
  1074. hint_snapshot = None
  1075. hint = context.get('outer_hint')
  1076. if error is self.first_error and type(error) is AssertionError and str(error) == 'translated child outside original task scope' and type(hint) is int and hint > 0 and hint not in context.get('tids',()):
  1077. try:
  1078. snapshot = []
  1079. for field in ('stat','status'):
  1080. with (pathlib.Path('/proc')/str(hint)/field).open('rb') as hint_stream: raw = hint_stream.read(8193)
  1081. if len(raw) > 8192: raise ValueError('diagnostic byte budget')
  1082. snapshot.append(raw.decode('ascii','strict'))
  1083. raw, status_raw = snapshot; tail = raw[raw.rindex(')')+2:].split()
  1084. number = lambda value: int(value) if re.fullmatch(r'[0-9]{1,20}',value) and int(value) <= 18446744073709551615 else (_ for _ in ()).throw(ValueError('diagnostic integer'))
  1085. pid, birth = number(raw[:raw.index('(')].strip()), number(tail[19])
  1086. if pid != hint or tail[0] not in ('R','S','D','Z','T','t','X','x','K','W','P','I'): raise ValueError('diagnostic stat')
  1087. status = {}
  1088. for line in status_raw.splitlines():
  1089. key, sep, value = line.partition(':')
  1090. if sep and key in ('Tgid','NSpid','Uid','TracerPid'):
  1091. if key in status: raise ValueError('diagnostic duplicate')
  1092. status[key] = value.split()
  1093. if set(status) != {'Tgid','NSpid','Uid','TracerPid'} or len(status['Tgid']) != 1 or len(status['TracerPid']) != 1 or len(status['Uid']) != 4 or not 1 <= len(status['NSpid']) <= 32: raise ValueError('diagnostic status')
  1094. hint_snapshot = {'pid':pid,'birth':birth,'state':tail[0],'tgid':number(status['Tgid'][0]),'nspid':[number(v) for v in status['NSpid']],'uids':[number(v) for v in status['Uid']],'tracer':number(status['TracerPid'][0])}
  1095. except Exception as diagnostic_error:
  1096. hint_snapshot = {'error':type(diagnostic_error).__name__[:64],'errno':diagnostic_error.errno if isinstance(diagnostic_error,OSError) and type(diagnostic_error.errno) is int else None}
  1097. print('namespace-registration-failure',
  1098. 'syscall',call_name,'cloneFlags',reported_flags,'otherFlagCount',len(context['flags'])-len(reported_flags),
  1099. 'refusals',context.get('discovery_counts'),
  1100. 'registrationTid',tb.tb_next.tb_frame.f_locals.get('tid') if tb.tb_next is not None else None,
  1101. 'outerHint',context.get('outer_hint') if type(context.get('outer_hint')) is int else None,
  1102. 'outerHintSnapshot',hint_snapshot,
  1103. 'candidate',(context['local'],context.get('tid'),context.get('ids',[])[:32]),
  1104. 'discovery',(len(context.get('tids',())),sorted(context.get('tids',()))[:16],len(context.get('matches',())),[task['key'] for task in context.get('matches',())[:16]]),
  1105. 'parent',(parent['key'],before['tgid'],before['nspid'][:32]),
  1106. 'CLONE_THREAD','CLONE_THREAD' in context['flags'],
  1107. 'roles',(bool(parent.get('nativeLeader')),bool(parent.get('capture'))),file=sys.stderr,flush=True)
  1108. tb = tb.tb_next
  1109. except Exception:
  1110. pass
  1111. if error is self.first_error and type(error) is AssertionError and str(error) == 'trace namespace drift':
  1112. try:
  1113. tb, visited = error.__traceback__, 0
  1114. while tb is not None and visited < 64:
  1115. if tb.tb_frame.f_code is self.parser.register.__func__.__code__:
  1116. context = tb.tb_frame.f_locals
  1117. facts, expected = context['facts'], context['self'].controller['ns']
  1118. pid, birth = context['tid'], facts['birth']
  1119. if type(pid) is not int or not 0 < pid <= 2147483647 or type(birth) is not int or not 0 <= birth <= 18446744073709551615:
  1120. raise ValueError('diagnostic identity budget')
  1121. namespaces = {}
  1122. for side, values in (('actual',facts['ns']),('expected',expected)):
  1123. namespaces[side] = {}
  1124. for kind in ('pid','net','user'):
  1125. value = values[kind]
  1126. if type(value) is not str or len(value) > 64: raise ValueError('diagnostic namespace budget')
  1127. match = re.fullmatch(kind+r':\[(0|[1-9][0-9]{0,19})\]',value)
  1128. if match is None or int(match[1]) > 18446744073709551615: raise ValueError('diagnostic namespace identity')
  1129. namespaces[side][kind] = value
  1130. print('trace-register-namespace-refusal',{'pid':pid,'birth':birth,**namespaces},file=sys.stderr,flush=True)
  1131. break
  1132. tb = tb.tb_next; visited += 1
  1133. except Exception:
  1134. pass
  1135. finally:
  1136. stream.close()
  1137. if not self.stopping and self.error is None:
  1138. self.refuse_held(AssertionError('trace/debug reader EOF before owned close'))
  1139. for stream, consume in ((self.trace_pipe,self.consume_trace),(self.child.stderr,self.consume_debug)):
  1140. t = threading.Thread(target=pump,args=(stream,consume),daemon=True)
  1141. self.threads.append(t); t.start()
  1142. dispatcher = threading.Thread(target=self.dispatch_held,daemon=True)
  1143. self.threads.append(dispatcher); dispatcher.start()
  1144. self.ready()
  1145. (self.root/'evidence/trace-readiness.json').write_text(json.dumps({
  1146. 'controller':controller,'tracer':self.tracer,'currentTids':sorted(self.started_tids),
  1147. 'seizeStopTids':sorted(self.seize_stops),'ptraceOptions':self.options,'argv':argv,
  1148. 'toolProvenance':tools['strace'],'incarnation':self.incarnation,
  1149. 'kernelACKCompletedKeys':sorted(self.acked_keys)},indent=2)+'\n')
  1150. def refuse_held(self, error):
  1151. with self.parser.changed:
  1152. if self.error is None:
  1153. self.first_error = error
  1154. self.error = self.session.error or type(error).__name__+':'+str(error)[:240]
  1155. self.parser.error = self.error
  1156. self.parser.changed.notify_all()
  1157. with self.session.records_changed:
  1158. self.session.trace_failure = self.error
  1159. self.session.records_changed.notify_all()
  1160. try: self.observer_peer.shutdown(socket.SHUT_RDWR)
  1161. except OSError: pass
  1162. def dispatch_held(self):
  1163. try:
  1164. while not self.stopping:
  1165. assert self.error is None and self.session.error is None, self.error or self.session.error
  1166. if not select.select([self.observer_peer],[],[],self.clock.wait(.25))[0]: continue
  1167. packet, ancillary, flags, _ = self.observer_peer.recvmsg(516)
  1168. if self.stopping: break
  1169. assert packet and not ancillary and not flags, 'held channel EOF/truncation/ancillary'
  1170. if packet.startswith(b'DONE '):
  1171. request = packet[5:]
  1172. with self.parser.changed:
  1173. keys = self.pending_acks.pop(request,None)
  1174. assert keys is not None, 'unrequested/duplicate kernel restart receipt'
  1175. self.acked_keys.update(keys)
  1176. self.parser.changed.notify_all()
  1177. continue
  1178. self.ack_held(packet)
  1179. except Exception as error:
  1180. if not self.stopping: self.refuse_held(error)
  1181. def ack_held(self, packet):
  1182. """Closed checkpoint dispatcher. No lock spans monitor/channel waiting."""
  1183. try:
  1184. assert type(packet) is bytes and 0 < len(packet) < 512, 'held request packet cap/EOF'
  1185. fields = packet.decode('ascii','strict').split()
  1186. assert len(fields) == 17 and fields[:3] == ['R1353',self.incarnation,str(self.tracer['pid'])], 'held tracer incarnation'
  1187. assert all(re.fullmatch(r'0|[1-9][0-9]{0,19}',fields[i]) for i in (3,5,6,7,8,10,11,12,13,14,15,16)), 'held numeric fields'
  1188. seq,phase,tid,birth,child,child_birth = int(fields[3]),fields[4],*map(int,fields[5:9])
  1189. assert seq == self.observer_sequence+1 and seq <= self.parser.MAX_EVENTS, 'held sequence'
  1190. assert phase in ('task','clone','entry','record') and re.fullmatch(r'[a-z][a-z0-9_]{0,31}',fields[9]), 'closed held phase/syscall'
  1191. assert 0 < tid <= 2147483647 and 0 < birth < 1<<64 and 0 <= child <= 2147483647 and 0 <= child_birth < 1<<64, 'held task/birth cap'
  1192. assert (child > 0 and child_birth > 0) if phase == 'clone' else (child == child_birth == 0), 'held pair fields'
  1193. arguments = list(map(int,fields[11:])); assert all(v < 1<<64 for v in arguments), 'held ABI argument cap'
  1194. assert int(fields[10]) < 1<<64, 'held clone flags cap'
  1195. self.observer_sequence = seq
  1196. with self.parser.changed:
  1197. assert self.parser.changed.wait_for(lambda:self.error or seq in self.parser.checkpoints,self.clock.wait(1)), 'complete real trace checkpoint deadline'
  1198. assert self.error is None and self.session.error is None, self.error or self.session.error
  1199. self.parser.checkpoints.remove(seq)
  1200. task = self.parser.register(tid)
  1201. assert task['key'] == (tid,birth), 'held task birth'
  1202. raw = (pathlib.Path('/proc')/str(tid)/'stat').read_text()
  1203. assert raw[raw.rindex(')')+2:].split()[0] == 't', 'actual held kernel stop'
  1204. self.custody_keys.add(task['key'])
  1205. if phase == 'clone':
  1206. fresh_child = trace_task_identity(child)
  1207. assert fresh_child['birth'] == child_birth and fresh_child['tracer'] == self.tracer['pid'], 'owned held child birth/tracer'
  1208. for field in ('uids','gids','groups','ns','uidMap','gidMap'):
  1209. assert fresh_child[field] == self.controller[field], 'owned held child authority'
  1210. assert fresh_child['tgid'] == task['facts']['tgid'] or fresh_child['ppid'] == task['facts']['tgid'], 'owned held child parent/group'
  1211. self.custody_keys.add((child,child_birth))
  1212. table = task['fds']
  1213. if phase == 'clone': self.parser.held_clone(tid,child,birth,child_birth,int(fields[10]))
  1214. conn = self.parser.held_entry(task,fields[9],arguments,self.session) if phase == 'entry' else None
  1215. capture = task.get('capture')
  1216. context = (packet,seq,phase,tid,birth,fields[9],arguments,table,capture,conn)
  1217. if conn is not None:
  1218. with self.parser.changed:
  1219. assert len(self.held_workers) < 4096, 'held credential worker cap'
  1220. worker = threading.Thread(target=self.complete_held,args=(context,),daemon=True)
  1221. self.held_workers.append(worker); worker.start()
  1222. else: self.complete_held(context)
  1223. except Exception as error:
  1224. self.refuse_held(error)
  1225. raise
  1226. def complete_held(self, context):
  1227. packet,seq,phase,tid,birth,syscall,arguments,table,capture,conn = context
  1228. try:
  1229. name = self.session.held_credentials(capture,conn) if conn is not None else None
  1230. # Revalidate the real stopped task, table and every alias AFTER the
  1231. # monitor wait. The callback's cached credential alone cannot ACK.
  1232. with self.parser.changed:
  1233. try:
  1234. assert self.error is None and self.session.error is None, self.error or self.session.error
  1235. task = self.parser.register(tid)
  1236. assert task['key'] == (tid,birth) and task['fds'] is table, 'held task/table incarnation changed'
  1237. raw = (pathlib.Path('/proc')/str(tid)/'stat').read_text()
  1238. assert raw[raw.rindex(')')+2:].split()[0] == 't', 'held stop lost before ACK'
  1239. if capture: assert proc_identity(capture['identity']['pid'],capture['identity']) == capture['identity'], 'fresh selected ACK identity'
  1240. if conn is not None:
  1241. assert self.parser.held_entry(task,syscall,arguments,self.session) is conn, 'held socket/table changed after credential wait'
  1242. assert conn['name'] == name and conn['connected'], 'held name/connection incarnation changed'
  1243. with self.session.records_lock:
  1244. if conn is not None:
  1245. assert name in self.session.active_names and self.session.credentials.get(name) == capture['identity'], 'active monitored name incarnation'
  1246. assert all(self.session.roundtrip_present(call) for call in self.session.credential_receipts[name]), 'consumed original credential roundtrips lost'
  1247. assert self.clock.wait(1) > 0 and self.error is None and self.session.error is None, 'held ACK deadline/first error'
  1248. keys = [task['key']]
  1249. if phase == 'clone':
  1250. child_tid,child_birth = map(int,packet.decode('ascii').split()[7:9])
  1251. child = self.parser.register(child_tid)
  1252. assert child['key'] == (child_tid,child_birth), 'child birth lost before ACK'
  1253. child_stat = (pathlib.Path('/proc')/str(child_tid)/'stat').read_text()
  1254. assert child_stat[child_stat.rindex(')')+2:].split()[0] == 't', 'child stop lost before ACK'
  1255. edge = self.parser.clone_edges[task['key']]
  1256. assert self.parser.clone_fds(tid,child_tid,edge['flags']) == edge['fds'], 'fresh inherited FD proof changed before ACK'
  1257. assert trace_task_identity(tid) == task['facts'] and trace_task_identity(child_tid) == child['facts'], 'fresh clone authority bookends before ACK'
  1258. keys.append(child['key'])
  1259. assert packet not in self.pending_acks, 'duplicate ACK authority'
  1260. self.pending_acks[packet] = keys
  1261. assert self.observer_peer.send(b'ACK '+packet,socket.MSG_DONTWAIT) == len(packet)+4, 'exact held ACK write'
  1262. if conn is not None:
  1263. conn['acked'] = True # Publish only after the exact ACK is accepted by the channel.
  1264. capture.setdefault('busLifetimeReceipts',[]).append({'sequence':seq,'tidBirth':task['key'],
  1265. 'fd':conn['fd'],'socket':conn['socket'],'name':name,
  1266. 'controls':self.session.credential_receipts[name]})
  1267. self.parser.changed.notify_all()
  1268. except Exception as error:
  1269. self.refuse_held(error) # Store failure before releasing validation/send locks.
  1270. raise
  1271. except Exception as error:
  1272. self.refuse_held(error)
  1273. raise
  1274. def consume_trace(self, raw):
  1275. # Require syscall readiness.
  1276. self.parser.feed(raw)
  1277. def consume_debug(self, raw):
  1278. self.debug_bytes += len(raw)
  1279. assert self.debug_bytes <= 256*LIMIT, 'bounded strace diagnostic stream'
  1280. self.debug_fragment += raw
  1281. while b'\n' in self.debug_fragment:
  1282. rawline,self.debug_fragment = self.debug_fragment.split(b'\n',1)
  1283. assert len(rawline) <= 8192, 'strace diagnostic line bound'
  1284. line = rawline.decode('ascii','strict')
  1285. if 'ptrace_setoptions = ' in line:
  1286. self.options = int(line.rsplit(' = ',1)[1],16)
  1287. assert self.options == 0x5f, 'source follow-fork option set'
  1288. stop = re.search(r'\[wait\(0x[0-9a-f]+\) = (\d+)\].*EVENT_STOP \(128\)',line)
  1289. if stop: self.seize_stops.add(int(stop[1]))
  1290. startup = re.search(r'pid (\d+) has TCB_STARTUP, initializing it',line)
  1291. if startup: self.started_tids.add(int(startup[1]))
  1292. if 'detached' in line:
  1293. detach = re.search(r'Process (\d+) detached',line)
  1294. assert detach and int(detach[1]) in self.closing_tids, 'trace detached before native join'
  1295. assert not any(s in line for s in ('PTRACE_SEIZE doesn\'t work','setting opts ','Operation not permitted',
  1296. 'Permission denied','attach: ptrace(','unknown pid','No such process')), 'strace attach/fallback uncertainty'
  1297. assert len(self.debug_fragment) <= 8192, 'partial strace diagnostic budget'
  1298. def ready(self):
  1299. end = time.monotonic()+self.clock.wait(5)
  1300. while time.monotonic() < end:
  1301. assert self.error is None and self.child.poll() is None, self.error or 'tracer exited before readiness'
  1302. current = proc_identity(self.controller['pid'],self.controller)
  1303. assert current['ns'] == self.controller['ns'] and current['uids'] == current['gids'] == [1000]*4 and current['groups'] == []
  1304. tids = {int(p.name) for p in (pathlib.Path('/proc')/str(current['pid'])/'task').iterdir()}
  1305. traced = []
  1306. for tid in tids:
  1307. facts = proc_identity(tid)
  1308. if facts['tracer'] == self.tracer['pid']: traced.append(tid)
  1309. if self.options == 0x5f and tids <= self.seize_stops and tids <= self.started_tids and set(traced) == tids:
  1310. with self.parser.changed:
  1311. assert self.parser.changed.wait_for(lambda:self.error or all(
  1312. (tid,trace_task_identity(tid)['birth']) in self.acked_keys for tid in tids),
  1313. max(.001,end-time.monotonic())), 'derived held TEST ACK readiness deadline'
  1314. assert self.error is None, self.error
  1315. with self.parser.lock:
  1316. for tid in tids: self.parser.register(tid)
  1317. return
  1318. time.sleep(min(.01,max(0,end-time.monotonic())))
  1319. raise IncompleteInstalledContract('no complete source-qualified SEIZE/TID readiness; native not launched')
  1320. def select_leader(self, local, end):
  1321. assert self.error is None and self.child.poll() is None
  1322. matches = []
  1323. for task in list(self.parser.tasks.values()):
  1324. f = task['facts']
  1325. if f['birth'] == local['birth'] and f['nspid'][-1] == local['pid'] and f['tgid'] == f['pid']:
  1326. matches.append(task)
  1327. assert len(matches) == 1, 'exact trace/native leader mapping missing'
  1328. task = matches[0]
  1329. for attempt in range(1000):
  1330. assert self.error is None and self.child.poll() is None
  1331. assert time.monotonic() < end, 'trace/native leader synchronization deadline'
  1332. try:
  1333. actual = proc_identity(task['facts']['pid'],task['facts'],leader_parent=self.controller['pid'])
  1334. break
  1335. except ProcessObservationRace:
  1336. if attempt == 999: raise
  1337. time.sleep(min(.001,max(0,end-time.monotonic())))
  1338. assert time.monotonic() < end, 'trace/native leader synchronization deadline'
  1339. assert actual['ppid'] == self.controller['pid'] and actual['ns'] == local['ns']
  1340. assert actual['pgid'] == actual['sid'] == actual['pid']
  1341. task['nativeLeader'] = True
  1342. return actual
  1343. def begin_phase(self):
  1344. assert self.error is None and self.child.poll() is None
  1345. tids = {int(p.name) for p in (pathlib.Path('/proc')/str(self.controller['pid'])/'task').iterdir()}
  1346. with self.parser.lock:
  1347. assert set(self.parser.pending) <= tids, 'previous native exit stream incomplete'
  1348. for tid, task in list(self.parser.tasks.items()):
  1349. if tid not in tids:
  1350. assert task.get('exited'), 'previous native/control trace task not terminal'
  1351. del self.parser.tasks[tid]
  1352. def phase(self, local_leader, cleanup_signal, cleanup_roles):
  1353. assert self.error is None and self.child.poll() is None, self.error
  1354. with self.parser.lock:
  1355. captures = [c for c in self.parser.selected if c['leader'][1] == local_leader['birth']]
  1356. assert len(captures) == 1 and captures[0]['exited'] and captures[0]['eof'], 'actual native helper capture absent/incomplete'
  1357. capture = captures[0]
  1358. terminal = [task for task in self.parser.tasks.values() if task.get('terminalCancellation',{}).get('leader') == capture['leader']]
  1359. approved = {(row['pid'],row['startTicks']) for row in cleanup_roles if row.get('workerServerArgvMatches') is True and row.get('executableIsPinnedNode') is True and row.get('cwdMatches') is True and row.get('uid') == 1000}
  1360. for task in terminal:
  1361. worker = self.parser.tasks[task['terminalCancellation']['worker'][0]]
  1362. assert worker['key'] == task['terminalCancellation']['worker'], 'terminal worker PID reuse'
  1363. assert cleanup_signal is True and (worker['facts']['nspid'][-1],worker['key'][1]) in approved, 'SIGTERM lacks exact original approved worker cleanup'
  1364. capture['ownedTerminalCancellations'] = [task['terminalCancellation'] for task in terminal]
  1365. assert capture['reading'] is None
  1366. raw = bytes(capture['bytes']); facts = captured_stop_bytes(raw)
  1367. return capture,raw,facts
  1368. def force_contain(self, error):
  1369. """Fatal containment precedes killing a tracer with held exit stops."""
  1370. if hasattr(self,'parser'): self.refuse_held(error)
  1371. self.stopping = True
  1372. try:
  1373. raw = (pathlib.Path('/proc')/str(self.controller['pid'])/'stat').read_text()
  1374. except FileNotFoundError: raw = None
  1375. if raw is not None:
  1376. tail = raw[raw.rindex(')')+2:].split()
  1377. assert int(tail[19]) == self.controller['birth'], 'controller containment refuses PID reuse'
  1378. if tail[0] not in ('Z','X','x'):
  1379. actual = trace_task_identity(self.controller['pid'])
  1380. for field in ('pid','birth','ppid','tgid','uids','gids','groups','nspid','ns','uidMap','gidMap'):
  1381. assert actual[field] == self.controller[field], 'owned controller containment authority'
  1382. assert actual['tracer'] in (0,self.tracer['pid']), 'foreign controller tracer at containment'
  1383. os.kill(actual['pid'],signal.SIGKILL) # PID1 death contains its entire owned namespace.
  1384. if self.child.poll() is None:
  1385. raw = (pathlib.Path('/proc')/str(self.child.pid)/'stat').read_text()
  1386. tail = raw[raw.rindex(')')+2:].split()
  1387. assert int(tail[19]) == self.tracer['birth'] and int(tail[1]) == os.getpid(), 'owned tracer containment birth/parent'
  1388. assert int(tail[2]) == int(tail[3]) == self.child.pid, 'owned tracer containment session'
  1389. if tail[0] not in ('Z','X','x'): os.kill(self.child.pid,signal.SIGKILL)
  1390. def failure_join(self, end):
  1391. """Called after the owned namespace supervisor has been killed/joined.
  1392. Containment is failure evidence. Neither channel EOF nor ESRCH is a
  1393. successful ACK or natural join; a foreign/reused birth refuses cleanup.
  1394. """
  1395. error = self.first_error or AssertionError('owned forced namespace containment')
  1396. if hasattr(self,'parser'): self.refuse_held(error)
  1397. self.stopping = True
  1398. keys = set(getattr(self,'custody_keys',()))
  1399. if hasattr(self,'parser'):
  1400. with self.parser.changed:
  1401. keys.update(t['key'] for t in self.parser.tasks.values())
  1402. self.parser.changed.notify_all()
  1403. for tid,birth in keys:
  1404. path = pathlib.Path('/proc')/str(tid)
  1405. if path.exists():
  1406. raw = (path/'stat').read_text(); tail = raw[raw.rindex(')')+2:].split()
  1407. assert int(tail[19]) == birth, 'failure join refuses reused PID'
  1408. raise AssertionError('owned namespace task survives supervisor join')
  1409. self.child.wait(timeout=max(.001,end-time.monotonic()))
  1410. self.observer_peer.close()
  1411. for worker in getattr(self,'threads',[])+getattr(self,'held_workers',[]):
  1412. worker.join(timeout=max(0,end-time.monotonic()))
  1413. assert not worker.is_alive(), 'owned failed observer worker join deadline'
  1414. (self.root/'evidence/trace-failure-join.json').write_text(json.dumps({
  1415. 'firstFailure':self.error,'forcedContainment':True,'naturalCompletion':False,
  1416. 'ownedBirthsAbsent':sorted(keys),'tracerExit':self.child.returncode,
  1417. 'allObserverWorkersJoined':True},indent=2)+'\n')
  1418. def close(self):
  1419. began = time.monotonic(); end = self.clock.cleanup_deadline()
  1420. # Native-empty P1: C TIDs.
  1421. cpid = self.controller['pid']
  1422. for p in pathlib.Path('/proc').iterdir():
  1423. if not p.name.isdecimal(): continue
  1424. try: same = os.readlink(p/'ns/pid') == self.controller['ns']['pid']
  1425. except FileNotFoundError: continue
  1426. if same: assert int(p.name) == cpid, 'native descendants survive before trace join'
  1427. proc_identity(self.child.pid,self.tracer)
  1428. with self.parser.changed:
  1429. assert not self.pending_acks and all(not t.is_alive() for t in self.held_workers), 'held ACK/credential joins incomplete'
  1430. self.stopping = True
  1431. self.closing_tids = {int(p.name) for p in (pathlib.Path('/proc')/str(cpid)/'task').iterdir()}
  1432. os.kill(self.child.pid,signal.SIGINT)
  1433. self.child.wait(timeout=min(self.clock.wait(2,cleanup=True),max(.001,end-time.monotonic())))
  1434. self.observer_peer.close()
  1435. for t in self.threads+self.held_workers: t.join(timeout=max(0,end-time.monotonic()))
  1436. assert all(not t.is_alive() for t in self.threads+self.held_workers) and self.error is None, 'trace pump/join failure'
  1437. with self.parser.lock:
  1438. assert set(self.parser.pending) <= self.closing_tids, 'unjoined native unfinished syscall'
  1439. assert set(self.parser.pending_reads) <= self.closing_tids, 'unjoined native pending read'
  1440. self.parser.pending_reads.clear()
  1441. self.parser.pending.clear() # C's blocked control read ends on this intentional detach.
  1442. self.parser.finish()
  1443. self.clock.charge_cleanup(began)
  1444. def dbus_types(signature):
  1445. assert type(signature) is str and len(signature) <= 255, 'DBus signature budget'
  1446. def parse(at, depth, dictionary=False):
  1447. assert depth <= 16 and at < len(signature), 'DBus signature truncation/depth'
  1448. ch = signature[at]
  1449. if ch in 'ybnqiuxtdhsogv': return ch, at+1
  1450. if ch == 'a':
  1451. item, end = parse(at+1,depth+1,True)
  1452. return ('a',item), end
  1453. assert ch == '(' or ch == '{' and dictionary, 'unsupported DBus signature'
  1454. closing = ')' if ch == '(' else '}'
  1455. values = []; at += 1
  1456. while at < len(signature) and signature[at] != closing:
  1457. value, at = parse(at,depth+1)
  1458. values.append(value)
  1459. assert len(values) <= 32, 'DBus struct signature budget'
  1460. assert at < len(signature) and values, 'unclosed/empty DBus struct'
  1461. if ch == '{':
  1462. assert len(values) == 2 and type(values[0]) is str and values[0] in 'ybnqiuxtdhsog', 'DBus dictionary key'
  1463. return (ch,tuple(values)), at+1
  1464. values = []; at = 0
  1465. while at < len(signature):
  1466. value, at = parse(at,0)
  1467. values.append(value)
  1468. return values
  1469. class DBusValueReader:
  1470. def __init__(self, raw, endian, at=0, end=None):
  1471. self.raw, self.endian, self.at = raw, endian, at
  1472. self.end = len(raw) if end is None else end
  1473. self.entries = 0
  1474. def align(self, n):
  1475. end = (self.at+n-1)//n*n
  1476. assert end <= self.end and not any(self.raw[self.at:end]), 'DBus alignment/padding'
  1477. self.at = end
  1478. def take(self, n):
  1479. assert 0 <= n <= self.end-self.at, 'partial DBus value'
  1480. value = self.raw[self.at:self.at+n]; self.at += n
  1481. return value
  1482. def number(self, fmt, align):
  1483. self.align(align)
  1484. return struct.unpack(self.endian+fmt,self.take(struct.calcsize(fmt)))[0]
  1485. def value(self, typ, depth=0):
  1486. self.entries += 1
  1487. assert self.entries <= 4096 and depth <= 16, 'DBus entry/depth bounds'
  1488. if type(typ) is str:
  1489. if typ in 'ybnqiuxtdh':
  1490. fmt, alignment = {'y':('B',1),'b':('I',4),'n':('h',2),'q':('H',2),
  1491. 'i':('i',4),'u':('I',4),'x':('q',8),'t':('Q',8),'d':('d',8),'h':('I',4)}[typ]
  1492. value = self.number(fmt,alignment)
  1493. if typ == 'b':
  1494. assert value in (0,1), 'invalid DBus boolean'
  1495. return bool(value)
  1496. return value
  1497. if typ in 'sog':
  1498. size = self.number('B',1) if typ == 'g' else self.number('I',4)
  1499. assert size <= 65536, 'DBus string bound'
  1500. raw = self.take(size)
  1501. assert b'\0' not in raw and self.take(1) == b'\0', 'DBus string terminator'
  1502. value = raw.decode('ascii' if typ == 'g' else 'utf-8','strict')
  1503. if typ == 'g': dbus_types(value)
  1504. if typ == 'o': assert value.startswith('/') and (value == '/' or all(re.fullmatch(r'[A-Za-z0-9_]+',p) for p in value[1:].split('/'))), 'DBus object path'
  1505. return value
  1506. assert typ == 'v', 'unsupported DBus basic type'
  1507. signature = self.value('g',depth+1); types_ = dbus_types(signature)
  1508. assert len(types_) == 1, 'DBus variant must have one type'
  1509. return {'signature':signature,'value':self.value(types_[0],depth+1)}
  1510. kind, items = typ
  1511. if kind == 'a':
  1512. size = self.number('I',4)
  1513. assert size <= LIMIT, 'DBus array bound'
  1514. alignment = dbus_alignment(items); self.align(alignment)
  1515. end = self.at+size; assert end <= self.end, 'partial DBus array'
  1516. old_end = self.end; self.end = end
  1517. values = []
  1518. while self.at < end:
  1519. values.append(self.value(items,depth+1))
  1520. assert len(values) <= 1024, 'DBus array entry bound'
  1521. self.end = old_end
  1522. if type(items) is tuple and items[0] == '{':
  1523. result = {}
  1524. for key,value in values:
  1525. assert key not in result, 'duplicate DBus dictionary key'
  1526. result[key] = value
  1527. return result
  1528. return values
  1529. assert kind in ('(','{'), 'unsupported DBus composite'
  1530. self.align(8)
  1531. return tuple(self.value(item,depth+1) for item in items)
  1532. def dbus_alignment(typ):
  1533. if type(typ) is tuple: return 4 if typ[0] == 'a' else 8
  1534. return {'y':1,'b':4,'n':2,'q':2,'i':4,'u':4,'x':8,'t':8,'d':8,'h':4,'s':4,'o':4,'g':1,'v':1}[typ]
  1535. class DBusBinaryStream:
  1536. """dbus-monitor --binary emits ordinary messages, without PCAP headers."""
  1537. def __init__(self, consume):
  1538. self.consume = consume
  1539. self.raw = b''
  1540. self.total = self.count = 0
  1541. def feed(self, chunk):
  1542. self.total += len(chunk)
  1543. assert self.total <= 16*LIMIT, 'complete DBus monitor stream bound'
  1544. self.raw += chunk
  1545. while len(self.raw) >= 16:
  1546. assert self.raw[0] in (ord('l'),ord('B')), 'DBus byte order'
  1547. endian = '<' if self.raw[0] == ord('l') else '>'
  1548. typ, flags, version = self.raw[1:4]
  1549. bodylen, serial, headers = struct.unpack(endian+'III',self.raw[4:16])
  1550. assert 1 <= typ <= 4 and flags & ~7 == 0 and version == 1 and serial > 0, 'DBus fixed header'
  1551. assert bodylen <= LIMIT and headers <= 65536, 'DBus frame budget'
  1552. start = (16+headers+7)//8*8; length = start+bodylen
  1553. if len(self.raw) < length: break
  1554. raw, self.raw = self.raw[:length],self.raw[length:]
  1555. reader = DBusValueReader(raw,endian,12,16+headers)
  1556. fields = reader.value(('a',('(',('y','v'))))
  1557. assert reader.at == 16+headers, 'DBus header boundary'
  1558. header = {}
  1559. expected = {1:'o',2:'s',3:'s',4:'s',5:'u',6:'s',7:'s',8:'g',9:'u'}
  1560. for code, variant in fields:
  1561. assert code in expected and code not in header and variant['signature'] == expected[code], 'unknown/duplicate DBus header field'
  1562. header[code] = variant['value']
  1563. assert not any(raw[16+headers:start]), 'DBus body alignment'
  1564. if typ == 1: assert {1,3} <= set(header), 'DBus method-call headers'
  1565. if typ in (2,3): assert 5 in header and header[5] > 0, 'DBus reply serial'
  1566. if typ == 3: assert 4 in header, 'DBus error header'
  1567. if typ == 4: assert {1,2,3} <= set(header), 'DBus signal headers'
  1568. signature = header.get(8,'')
  1569. body_reader = DBusValueReader(raw,endian,start)
  1570. values = [body_reader.value(t) for t in dbus_types(signature)]
  1571. assert body_reader.at == length, 'DBus trailing body bytes/signature mismatch'
  1572. self.count += 1; assert self.count <= 4096, 'DBus message count'
  1573. self.consume({'type':typ,'serial':serial,'header':header,'signature':signature,'body':values})
  1574. assert len(self.raw) <= LIMIT+65552, 'DBus partial frame bound'
  1575. def finish(self):
  1576. assert not self.raw, 'partial DBus monitor frame at join'
  1577. class NotificationsExchange:
  1578. """Pure matching logic. Identity/GUID are established by the real session."""
  1579. def __init__(self, owner):
  1580. assert re.fullmatch(r':\d+\.\d+',owner), 'actual Notifications unique owner required'
  1581. self.owner = owner
  1582. self.pending = {}
  1583. self.ready = set()
  1584. self.receipts = []
  1585. def call(self, message, helper_name):
  1586. h = message['header']
  1587. assert message['type'] == 1 and h.get(7) == helper_name, 'wrong helper sender'
  1588. method = h.get(3)
  1589. if method == 'NameHasOwner':
  1590. assert h.get(6) == 'org.freedesktop.DBus' and h.get(2) == 'org.freedesktop.DBus' and h.get(1) == '/org/freedesktop/DBus'
  1591. assert message['signature'] == 's' and message['body'] == ['org.freedesktop.Notifications']
  1592. else:
  1593. assert method in ('GetCapabilities','Notify') and h.get(6) in ('org.freedesktop.Notifications',self.owner)
  1594. assert h.get(2) == 'org.freedesktop.Notifications' and h.get(1) == '/org/freedesktop/Notifications'
  1595. if method == 'GetCapabilities': assert message['signature'] == '' and message['body'] == []
  1596. if method == 'Notify':
  1597. assert (helper_name,'NameHasOwner') in self.ready and (helper_name,'GetCapabilities') in self.ready, 'Notify before real readiness replies'
  1598. assert message['signature'] == 'susssasa{sv}i', 'Notify argument signature'
  1599. b = message['body']
  1600. assert len(b) == 8 and b[:6] == ['agent-notifications',0,'','Cursor CLI','Cursor CLI is stopping',[]], 'Notify actual source arguments'
  1601. assert b[6] == {'suppress-sound':{'signature':'b','value':True}} and type(b[7]) is int and 1 <= b[7] <= 15000
  1602. key = (helper_name,message['serial'])
  1603. assert key not in self.pending, 'duplicate DBus call serial'
  1604. self.pending[key] = {'method':method,'call':message}
  1605. def reply(self, message):
  1606. h = message['header']; key = (h.get(6),h.get(5))
  1607. assert key in self.pending, 'wrong reply serial/destination'
  1608. pending = self.pending.pop(key); method = pending['method']
  1609. assert message['type'] == 2, 'DBus ERROR/partial/missing reply is uncertainty'
  1610. sender = 'org.freedesktop.DBus' if method == 'NameHasOwner' else self.owner
  1611. assert h.get(7) == sender, 'reply from foreign/replaced Notifications owner'
  1612. if method == 'NameHasOwner': assert message['signature'] == 'b' and message['body'] == [True], 'NameHasOwner not true'
  1613. if method == 'GetCapabilities':
  1614. assert message['signature'] == 'as' and len(message['body']) == 1 and type(message['body'][0]) is list
  1615. assert all(type(s) is str for s in message['body'][0]), 'invalid GetCapabilities reply'
  1616. if method == 'Notify':
  1617. assert message['signature'] == 'u' and len(message['body']) == 1 and type(message['body'][0]) is int and 0 <= message['body'][0] <= 4294967295, 'missing actual uint32 notification ID'
  1618. self.receipts.append({'sender':key[0],'callSerial':key[1],'notificationID':message['body'][0],
  1619. 'call':pending['call'],'reply':message})
  1620. else: self.ready.add((key[0],method))
  1621. def finish(self):
  1622. assert not self.pending, 'missing notification readiness/submission reply'
  1623. class OwnedNotificationsSession:
  1624. """Standard services in P0/N1/U0; no process enters the native PID namespace."""
  1625. def __init__(self, controller, root, clock, tools, display_number):
  1626. self.controller, self.root, self.clock, self.tools = controller,pathlib.Path(root),clock,tools
  1627. self.error = None
  1628. self.processes = []
  1629. self.control_processes = []
  1630. self.pumps = []
  1631. self.messages = []
  1632. self.control_names = set()
  1633. self.credentials = {}
  1634. self.rpc_lock = threading.RLock()
  1635. self.records_lock = threading.RLock()
  1636. self.records_changed = threading.Condition(self.records_lock)
  1637. self.trace_failure = None
  1638. self.credential_receipts = {}
  1639. self.active_names = set()
  1640. self.exchange = None
  1641. self.closing = False
  1642. self.netfd = os.open('/proc/'+str(controller['pid'])+'/ns/net',os.O_RDONLY)
  1643. assert 'net:['+str(os.fstat(self.netfd).st_ino)+']' == controller['ns']['net'], 'pinned C netns handle'
  1644. self.directory = self.root/'session'
  1645. self.directory.mkdir(mode=0o700)
  1646. os.chown(self.directory,1000,1000)
  1647. self.address = 'unix:path='+str(self.directory/'bus')
  1648. assert type(display_number) is int and 90 <= display_number <= 4096
  1649. self.display = ':'+str(display_number)
  1650. self.xsocket = pathlib.Path('/tmp/.X11-unix')/('X'+str(display_number))
  1651. self.xlock = pathlib.Path('/tmp')/('.X'+str(display_number)+'-lock')
  1652. assert not self.xsocket.exists() and not self.xlock.exists(), 'accepted display already in use; no retry'
  1653. self.xauthority = self.directory/'Xauthority'
  1654. self.env = {'HOME':str(self.root/'home'),'XDG_CONFIG_HOME':str(self.root/'home/.config'),
  1655. 'XDG_CACHE_HOME':str(self.root/'cache'),'TMPDIR':str(self.root/'tmp'),
  1656. 'PATH':'/usr/bin:/bin','LANG':'C.UTF-8','DBUS_SESSION_BUS_ADDRESS':self.address,
  1657. 'DISPLAY':self.display,'XAUTHORITY':str(self.xauthority)}
  1658. cookie = os.urandom(16).hex() # TEST display cookie, never an ambient credential.
  1659. self.command('xauth',['-f',str(self.xauthority)],input=f'add {self.display} MIT-MAGIC-COOKIE-1 {cookie}\n'.encode('ascii'))
  1660. self.display_process = self.start('Xvfb',[self.display,'-screen','0','800x600x24','-nolisten','tcp','-auth',str(self.xauthority)])
  1661. self.bus = self.start('dbus-daemon',['--session','--nofork','--nopidfile','--address='+self.address,'--print-address=1'])
  1662. self.wait(lambda:(self.directory/'bus').exists(),5)
  1663. sock = (self.directory/'bus').lstat()
  1664. assert stat.S_ISSOCK(sock.st_mode) and sock.st_uid == sock.st_gid == 1000, 'owned TEST bus socket'
  1665. self.socket_identity = {'inode':sock.st_ino,'device':sock.st_dev,'mode':sock.st_mode,'uid':sock.st_uid,'gid':sock.st_gid}
  1666. self.monitor = self.start('dbus-monitor',['--address',self.address,'--binary'],binary=True)
  1667. self.stream = DBusBinaryStream(self.message)
  1668. self.monitor_pump = threading.Thread(target=self.monitor_read,daemon=True)
  1669. self.monitor_pump.start()
  1670. self.dunst = self.start('dunst',['-config','/dev/null'])
  1671. self.wait(lambda:self.xsocket.exists() and self.xlock.exists(),5)
  1672. xs = self.xsocket.lstat(); xl = self.xlock.lstat()
  1673. assert stat.S_ISSOCK(xs.st_mode) and xs.st_uid == xs.st_gid == 1000 and xl.st_uid == xl.st_gid == 1000
  1674. self.display_identity = {'socket':{'inode':xs.st_ino,'device':xs.st_dev,'mode':xs.st_mode},
  1675. 'lock':{'inode':xl.st_ino,'device':xl.st_dev,'mode':xl.st_mode}}
  1676. # Dunst owner first.
  1677. self.wait(lambda:any(m['type'] == 4 and m['header'].get(3) == 'NameOwnerChanged' and
  1678. m['body'][:1] == ['org.freedesktop.Notifications'] and len(m['body']) == 3 and m['body'][2]
  1679. for m in self.messages),5)
  1680. self.guid,self.guid_call = self.rpc('org.freedesktop.DBus.GetId',[], 's')
  1681. assert re.fullmatch(r'[0-9a-f]{32}',self.guid), 'actual owned bus GUID'
  1682. self.owner,self.owner_call = self.rpc('org.freedesktop.DBus.GetNameOwner',['string:org.freedesktop.Notifications'],'s')
  1683. self.exchange = NotificationsExchange(self.owner)
  1684. pid,_ = self.rpc('org.freedesktop.DBus.GetConnectionUnixProcessID',['string:'+self.owner],'u')
  1685. uid,_ = self.rpc('org.freedesktop.DBus.GetConnectionUnixUser',['string:'+self.owner],'u')
  1686. assert pid == self.dunst['identity']['pid'] and uid == 1000, 'real Notifications owner/daemon PID'
  1687. self.credentials[self.owner] = proc_identity(pid,self.dunst['identity'])
  1688. exists, name_call = self.rpc('org.freedesktop.DBus.NameHasOwner',['string:org.freedesktop.Notifications'],'b')
  1689. assert exists is True
  1690. capabilities, caps_call = self.rpc('org.freedesktop.Notifications.GetCapabilities',[], 'as',notifications=True)
  1691. assert type(capabilities) is list and all(type(c) is str for c in capabilities)
  1692. # Monitor roundtrips.
  1693. for call in (self.guid_call,self.owner_call,name_call,caps_call): self.observed_roundtrip(call)
  1694. self.assert_continuous()
  1695. (self.root/'evidence/session-readiness.json').write_text(json.dumps({
  1696. 'busGUID':self.guid,'notificationsOwner':self.owner,'daemon':self.dunst['identity'],
  1697. 'socket':self.socket_identity,'display':self.display,'displayIdentity':self.display_identity,
  1698. 'processes':[p['identity'] for p in self.processes],'tools':tools,
  1699. 'actualControlRoundtrips':[self.guid_call,self.owner_call,name_call,caps_call],
  1700. 'GUIVisibility':'NOT_RUN'},indent=2)+'\n')
  1701. def argv(self, name, args):
  1702. return [self.tools['nsenter']['path'],'--net=/proc/self/fd/'+str(self.netfd),
  1703. self.tools['setpriv']['path'],'--reuid=1000','--regid=1000','--clear-groups',
  1704. self.tools[name]['path'],*args]
  1705. def wait(self, predicate, cap):
  1706. end = time.monotonic()+self.clock.wait(cap)
  1707. while not predicate():
  1708. assert self.error is None, self.error
  1709. for p in self.processes: assert p['child'].poll() is None, 'owned standard session process exited'
  1710. assert time.monotonic() < end, 'session/readiness absolute deadline'
  1711. time.sleep(min(.01,max(0,end-time.monotonic())))
  1712. def live(self, child, name, args, identity, end):
  1713. while time.monotonic() < end:
  1714. assert child.poll() is None, 'standard process failed before identity'
  1715. if os.readlink(pathlib.Path('/proc')/str(child.pid)/'exe') != self.tools[name]['path']:
  1716. time.sleep(min(.001,max(0,end-time.monotonic())))
  1717. continue
  1718. facts = proc_identity(child.pid,identity,startup=True)
  1719. if facts is None:
  1720. time.sleep(min(.001,max(0,end-time.monotonic())))
  1721. continue
  1722. if facts['exe'] == self.tools[name]['path']:
  1723. if facts['argv'] != [self.tools[name]['path'],*args]:
  1724. print('standard-argv-rejected', child.pid, facts['birth'], facts['exe'], facts['uids'],
  1725. len(facts['argv']), [v[:120] for v in facts['argv'][:2]],
  1726. len(args)+1, [v[:120] for v in [self.tools[name]['path'],*args[:1]]], file=sys.stderr, flush=True)
  1727. assert facts['argv'] == [self.tools[name]['path'],*args], 'actual standard process argv'
  1728. assert facts['uids'] == facts['gids'] == [1000]*4 and facts['groups'] == []
  1729. assert facts['ns']['pid'] == os.readlink('/proc/self/ns/pid') and facts['ns']['pid'] != self.controller['ns']['pid']
  1730. assert facts['ns']['net'] == self.controller['ns']['net'] and facts['ns']['user'] == self.controller['ns']['user']
  1731. assert facts['uidMap'] == self.controller['uidMap'] and facts['gidMap'] == self.controller['gidMap']
  1732. assert facts['ppid'] == os.getpid(), 'outer service ownership'
  1733. assert digest(facts['exe']) == self.tools[name]['sha256']
  1734. return facts
  1735. time.sleep(min(.001,max(0,end-time.monotonic())))
  1736. raise IncompleteInstalledContract('standard session identity not established')
  1737. def diagnostic_pump(self, pipe, path):
  1738. def drain():
  1739. try:
  1740. with path.open('xb') as f:
  1741. size = 0
  1742. while True:
  1743. chunk = pipe.read(8192)
  1744. if not chunk: break
  1745. size += len(chunk); assert size <= LIMIT, 'session diagnostic bytes'
  1746. f.write(chunk)
  1747. except Exception as error: self.error = type(error).__name__+':'+str(error)[:240]
  1748. finally: pipe.close()
  1749. t = threading.Thread(target=drain,daemon=True); self.pumps.append(t); t.start()
  1750. def start(self, name, args, binary=False):
  1751. end = time.monotonic()+self.clock.wait(1)
  1752. child = subprocess.Popen(self.argv(name,args),stdin=subprocess.DEVNULL,stdout=subprocess.PIPE,stderr=subprocess.PIPE,
  1753. pass_fds=(self.netfd,),env=self.env,cwd=self.root/'workspace',start_new_session=True,bufsize=0)
  1754. # Pre-exec birth/ppid/sid.
  1755. record = {'name':name,'child':child,'identity':startup_identity(child.pid)}
  1756. self.processes.append(record)
  1757. self.diagnostic_pump(child.stderr,self.root/'evidence'/('session-'+name+'.stderr'))
  1758. facts = self.live(child,name,args,record['identity'],end)
  1759. assert facts['birth'] == record['identity']['birth'], 'standard process birth changed across exec'
  1760. record['identity'] = facts
  1761. if not binary: self.diagnostic_pump(child.stdout,self.root/'evidence'/('session-'+name+'.stdout'))
  1762. return record
  1763. def command(self, name, args, input=None):
  1764. held = name == 'dbus-send'
  1765. try:
  1766. if held:
  1767. assert proc_identity(self.bus['identity']['pid'],self.bus['identity']) == self.bus['identity'], 'owned bus changed before hold'
  1768. os.kill(self.bus['identity']['pid'],signal.SIGSTOP)
  1769. self.wait(lambda:(pathlib.Path('/proc')/str(self.bus['identity']['pid'])/'stat').read_text().split(') ')[-1].split()[0] == 'T',1)
  1770. end = time.monotonic()+self.clock.wait(1)
  1771. child = subprocess.Popen(self.argv(name,args),stdin=subprocess.PIPE if input is not None else subprocess.DEVNULL,stdout=subprocess.PIPE,stderr=subprocess.PIPE,
  1772. pass_fds=(self.netfd,),env=self.env,cwd=self.root/'workspace',start_new_session=True)
  1773. record = {'name':name,'child':child,'identity':startup_identity(child.pid)}
  1774. self.control_processes.append(record)
  1775. facts = self.live(child,name,args,record['identity'],end)
  1776. assert facts['birth'] == record['identity']['birth'], 'control process birth changed across exec'
  1777. record['identity'] = facts
  1778. finally:
  1779. if held:
  1780. assert proc_identity(self.bus['identity']['pid'],self.bus['identity']) == self.bus['identity'], 'owned bus changed before resume'
  1781. os.kill(self.bus['identity']['pid'],signal.SIGCONT)
  1782. output,error = child.communicate(input=input,timeout=self.clock.wait(1))
  1783. assert child.returncode == 0 and len(output) <= 65536 and len(error) <= 65536, 'standard session control failed'
  1784. assert len(self.control_processes) <= 128, 'bounded separate control connection count'
  1785. (self.root/'evidence/session-controls.json').write_text(json.dumps([
  1786. {'name':p['name'],'identity':p['identity'],'exit':p['child'].returncode,
  1787. 'provenance':self.tools[p['name']]} for p in self.control_processes],indent=2)+'\n')
  1788. return output
  1789. def rpc(self, method, args, signature, notifications=False):
  1790. with self.rpc_lock:
  1791. name = 'org.freedesktop.Notifications' if notifications else 'org.freedesktop.DBus'
  1792. path = '/org/freedesktop/Notifications' if notifications else '/org/freedesktop/DBus'
  1793. reply_timeout = max(1,int(self.clock.wait(1)*1000))
  1794. stdout = self.command('dbus-send',['--bus='+self.address,'--type=method_call','--print-reply',
  1795. '--reply-timeout='+str(reply_timeout),'--dest='+name,path,method,*args]).decode('utf-8','strict')
  1796. lines = stdout.splitlines()
  1797. assert lines and lines[0].startswith('method return '), 'control DBus ERROR/unknown response'
  1798. match = re.search(r'sender=(\S+) -> destination=(:\d+\.\d+).*reply_serial=(\d+)',lines[0])
  1799. assert match, 'control reply headers'
  1800. sender,destination,serial = match[1],match[2],int(match[3])
  1801. self.control_names.add(destination)
  1802. assert sender == (self.owner if notifications else 'org.freedesktop.DBus'), 'control owner drift'
  1803. if signature == 's':
  1804. assert len(lines) == 2 and lines[1].strip().startswith('string ')
  1805. value = json.loads(lines[1].strip()[7:])
  1806. elif signature == 'u':
  1807. assert len(lines) == 2 and re.fullmatch(r'\s*uint32 \d+',lines[1])
  1808. value = int(lines[1].split()[1])
  1809. elif signature == 'b':
  1810. assert len(lines) == 2 and lines[1].strip() in ('boolean true','boolean false')
  1811. value = lines[1].strip() == 'boolean true'
  1812. else:
  1813. assert signature == 'as' and lines[1].strip() == 'array [' and lines[-1].strip() == ']'
  1814. value = []
  1815. for line in lines[2:-1]:
  1816. assert line.strip().startswith('string ')
  1817. value.append(json.loads(line.strip()[7:]))
  1818. return value,{'sender':destination,'callSerial':serial,'replySender':sender,'method':method,
  1819. 'arguments':list(args),'signature':signature,'value':value}
  1820. def roundtrip_present(self, control):
  1821. with self.records_lock:
  1822. calls = [m for m in self.messages if m['type'] == 1 and m['header'].get(7) == control['sender'] and m['serial'] == control['callSerial']]
  1823. replies = [m for m in self.messages if m['type'] in (2,3) and m['header'].get(6) == control['sender'] and m['header'].get(5) == control['callSerial']]
  1824. if not calls or not replies: return False
  1825. assert len(calls) == len(replies) == 1 and replies[0]['type'] == 2, 'monitor control reply ambiguity'
  1826. assert calls[0]['header'].get(3) == control['method'].rsplit('.',1)[1]
  1827. assert all(arg.startswith('string:') for arg in control['arguments']), 'closed original control argument types'
  1828. assert calls[0]['signature'] == 's'*len(control['arguments']) and calls[0]['body'] == [
  1829. arg.split(':',1)[1] for arg in control['arguments']], 'original monitored credential name arguments'
  1830. assert replies[0]['header'].get(7) == control['replySender']
  1831. assert replies[0]['signature'] == control['signature'] and replies[0]['body'] == [control['value']]
  1832. return True
  1833. def observed_roundtrip(self, control):
  1834. self.wait(lambda:self.roundtrip_present(control),1)
  1835. def held_credentials(self, capture, conn):
  1836. """Independent dispatcher; the monitor never waits for its own records."""
  1837. helper = capture['identity']
  1838. key = (helper['pid'],helper['birth'])
  1839. def ready():
  1840. if self.error is not None or self.trace_failure is not None:
  1841. raise AssertionError(self.error or self.trace_failure)
  1842. names = [name for name,facts in self.credentials.items() if name in self.active_names and (facts['pid'],facts['birth']) == key]
  1843. assert len(names) <= 1, 'ambiguous helper unique names'
  1844. if not names: return False
  1845. name = names[0]
  1846. receipts = self.credential_receipts.get(name)
  1847. if receipts is None or not all(self.roundtrip_present(call) for call in receipts): return False
  1848. hellos = [m for m in self.messages if m['type'] == 1 and m['header'].get(7) == name and
  1849. m['header'].get(2) == 'org.freedesktop.DBus' and m['header'].get(3) == 'Hello']
  1850. assert len(hellos) <= 1, 'ambiguous helper Hello'
  1851. if not hellos: return False
  1852. replies = [m for m in self.messages if m['type'] in (2,3) and m['header'].get(6) == name and m['header'].get(5) == hellos[0]['serial']]
  1853. if not replies: return False
  1854. assert len(replies) == 1 and replies[0]['type'] == 2 and replies[0]['signature'] == 's' and replies[0]['body'] == [name], 'failed/ambiguous Hello'
  1855. if conn['outcome'] is None: return False
  1856. assert conn['connected'], 'connect intent/outcome is not connection proof'
  1857. assert receipts[0]['value'] == helper['pid'] and receipts[1]['value'] == 1000, 'original credential RPC values'
  1858. assert [call['method'] for call in receipts] == ['org.freedesktop.DBus.GetConnectionUnixProcessID',
  1859. 'org.freedesktop.DBus.GetConnectionUnixUser'] and all(call['arguments'] == ['string:'+name]
  1860. for call in receipts), 'original credential RPC name/method incarnation'
  1861. return name
  1862. with self.records_changed:
  1863. assert self.records_changed.wait_for(ready,self.clock.wait(1)), 'held credential/monitor deadline'
  1864. name = ready()
  1865. peer = self.credentials[name]
  1866. # No trace/rpc/records lock spans a control RPC, Condition or channel wait.
  1867. self.assert_continuous()
  1868. current = proc_identity(helper['pid'],helper)
  1869. assert current == helper == peer and current['tracer'] == capture['identity']['tracer'], 'fresh exact selected bus peer'
  1870. assert len(capture['busConnections']) == 1 and capture['busConnections'][0] is conn, 'sole socket/name incarnation'
  1871. conn['name'] = name
  1872. return name
  1873. def message(self, message):
  1874. new_credential = None
  1875. h = message['header']
  1876. ownership = message['type'] == 4 and h.get(2) == 'org.freedesktop.DBus' and h.get(3) == 'NameOwnerChanged'
  1877. with self.records_changed:
  1878. # Publish the real departure and remove its ACK authority atomically.
  1879. # The separate credential RPC below never holds the records lock.
  1880. if ownership:
  1881. assert h.get(7) == 'org.freedesktop.DBus' and h.get(1) == '/org/freedesktop/DBus', 'actual bus name authority'
  1882. assert message['signature'] == 'sss' and len(message['body']) == 3
  1883. name,old,new = message['body']
  1884. if name.startswith(':'):
  1885. assert re.fullmatch(r':\d+\.\d+',name), 'actual unique bus name'
  1886. if old == '' and new == name: self.active_names.add(name)
  1887. elif old == name and new == '': self.active_names.discard(name)
  1888. else: raise AssertionError('unique bus name replacement')
  1889. self.messages.append(message)
  1890. assert len(self.messages) <= 4096 and len(json.dumps(self.messages)) <= 16*LIMIT, 'bounded TEST monitor records'
  1891. self.records_changed.notify_all()
  1892. if ownership:
  1893. if name == 'org.freedesktop.Notifications' and self.exchange is not None:
  1894. assert self.closing or old == '' and new == self.owner, 'Notifications owner loss/replacement'
  1895. if name.startswith(':') and old == '' and new == name:
  1896. with self.rpc_lock:
  1897. if name not in self.control_names:
  1898. pid,pid_call = self.rpc('org.freedesktop.DBus.GetConnectionUnixProcessID',['string:'+name],'u')
  1899. uid,uid_call = self.rpc('org.freedesktop.DBus.GetConnectionUnixUser',['string:'+name],'u')
  1900. assert uid == 1000, 'bus peer UID'
  1901. facts = proc_identity(pid)
  1902. assert facts['uids'] == facts['gids'] == [1000]*4 and facts['groups'] == []
  1903. assert facts['ns']['net'] == self.controller['ns']['net'] and facts['ns']['user'] == self.controller['ns']['user']
  1904. if facts['ns']['pid'] != self.controller['ns']['pid']:
  1905. assert any(p['identity']['pid'] == pid and p['identity']['birth'] == facts['birth'] for p in self.processes), 'unknown outer session peer'
  1906. else:
  1907. assert facts['argv'][1:4] == ['cursor-event','stop','--binding'] and len(facts['argv']) == 5, 'unknown native bus peer'
  1908. new_credential = (name,facts,(pid_call,uid_call))
  1909. if name in self.credentials and old == name and new == '' and self.exchange is not None:
  1910. assert not any(key[0] == name for key in self.exchange.pending), 'helper disconnect before matching reply'
  1911. if self.exchange is not None:
  1912. sender = h.get(7)
  1913. credential = self.credentials.get(sender)
  1914. if message['type'] == 1 and credential and credential['ns']['pid'] == self.controller['ns']['pid']:
  1915. self.exchange.call(message,sender)
  1916. if message['type'] in (2,3) and (h.get(6),h.get(5)) in self.exchange.pending:
  1917. self.exchange.reply(message)
  1918. with self.records_changed:
  1919. if new_credential is not None:
  1920. name,facts,receipts = new_credential
  1921. assert name in self.active_names and name not in self.credentials, 'credential callback name incarnation'
  1922. self.credentials[name] = facts
  1923. self.credential_receipts[name] = receipts
  1924. self.records_changed.notify_all()
  1925. def monitor_read(self):
  1926. try:
  1927. pipe = self.monitor['child'].stdout
  1928. while True:
  1929. raw = pipe.read(8192)
  1930. if not raw: break
  1931. self.stream.feed(raw)
  1932. self.stream.finish()
  1933. assert self.closing, 'monitor continuity ended early'
  1934. except Exception as error:
  1935. with self.records_changed:
  1936. if self.error is None: self.error = type(error).__name__+':'+str(error)[:240]
  1937. self.records_changed.notify_all()
  1938. finally: self.monitor['child'].stdout.close()
  1939. def assert_continuous(self):
  1940. assert self.error is None and self.monitor_pump.is_alive(), self.error or 'monitor missing'
  1941. for p in self.processes:
  1942. assert p['child'].poll() is None, 'session process not live'
  1943. current = proc_identity(p['identity']['pid'],p['identity'])
  1944. assert current['ns'] == p['identity']['ns'] and current['uids'] == current['gids'] == [1000]*4 and current['groups'] == []
  1945. s = (self.directory/'bus').lstat()
  1946. assert {'inode':s.st_ino,'device':s.st_dev,'mode':s.st_mode,'uid':s.st_uid,'gid':s.st_gid} == self.socket_identity
  1947. def checkpoint(self, helper=None, enabled=False):
  1948. self.assert_continuous()
  1949. guid,call = self.rpc('org.freedesktop.DBus.GetId',[],'s')
  1950. assert guid == self.guid
  1951. self.observed_roundtrip(call) # binary stream passed through this boundary.
  1952. self.exchange.finish()
  1953. if helper is not None:
  1954. names = [name for name,f in self.credentials.items() if f['pid'] == helper['pid'] and f['birth'] == helper['birth']]
  1955. assert len(names) == (1 if enabled else 0), 'actual helper sender identity missing/disabled helper reached bus'
  1956. if enabled:
  1957. receipts = [r for r in self.exchange.receipts if r['sender'] == names[0]]
  1958. assert len(receipts) == 1, 'one correlated real Notify reply required'
  1959. credential = self.credentials[names[0]]
  1960. assert credential['nspid'] == helper['nspid'] and credential['ns'] == helper['ns'] and credential['argv'] == helper['argv']
  1961. assert len(self.exchange.receipts) == 1, 'duplicate/disabled Notify effect'
  1962. (self.root/'evidence/notifications-actual.json').write_text(json.dumps({
  1963. 'busGUID':self.guid,'owner':self.owner,'credentials':self.credentials,
  1964. 'receipts':self.exchange.receipts,'messages':self.messages,'GUIVisibility':'NOT_RUN'},indent=2)+'\n')
  1965. def close(self):
  1966. began = time.monotonic(); deadline = self.clock.cleanup_deadline()
  1967. self.assert_continuous(); self.exchange.finish()
  1968. assert all(p['child'].poll() == 0 for p in self.control_processes), 'separate control connection join incomplete'
  1969. self.closing = True
  1970. # Join native/RPC; close.
  1971. for p in (self.monitor,self.dunst,self.bus,self.display_process):
  1972. proc_identity(p['identity']['pid'],p['identity'])
  1973. os.kill(p['identity']['pid'],signal.SIGTERM)
  1974. p['child'].wait(timeout=max(.001,min(2,deadline-time.monotonic())))
  1975. self.monitor_pump.join(timeout=max(0,deadline-time.monotonic()))
  1976. for t in self.pumps: t.join(timeout=max(0,deadline-time.monotonic()))
  1977. assert not self.monitor_pump.is_alive() and all(not t.is_alive() for t in self.pumps) and self.error is None, 'standard session join incomplete'
  1978. self.stream.finish()
  1979. os.close(self.netfd)
  1980. self.clock.charge_cleanup(began)
  1981. class OuterObservation:
  1982. def __init__(self, child, peer, inputs, clock):
  1983. self.child, self.peer, self.inputs, self.clock = child,peer,inputs,clock
  1984. self.controller = None
  1985. self.trace = self.session = None
  1986. self.sequence = 0
  1987. self.nonce = None
  1988. self.phases = []
  1989. self.closed = False
  1990. self.active_phase = None
  1991. def controller_identity(self, local):
  1992. assert local['pid'] == local['tgid'] == 1 and local['uids'] == local['gids'] == [1000]*4 and local['groups'] == []
  1993. matches = []
  1994. for p in pathlib.Path('/proc').iterdir():
  1995. if not p.name.isdecimal(): continue
  1996. try:
  1997. if os.readlink(p/'ns/pid') != local['ns']['pid']: continue
  1998. facts = proc_identity(int(p.name))
  1999. except FileNotFoundError: continue
  2000. if facts['birth'] == local['birth'] and facts['nspid'][-1] == 1: matches.append(facts)
  2001. assert len(matches) == 1, 'one exact ancestor-visible C identity'
  2002. actual = matches[0]
  2003. assert actual['ppid'] == self.child.pid and actual['ns'] == local['ns']
  2004. assert actual['uids'] == actual['gids'] == [1000]*4 and actual['groups'] == []
  2005. assert actual['uidMap'] == local['uidMap'] and actual['gidMap'] == local['gidMap']
  2006. assert actual['ns']['user'] == os.readlink('/proc/self/ns/user')
  2007. assert actual['ns']['pid'] != os.readlink('/proc/self/ns/pid')
  2008. assert actual['ns']['net'] != os.readlink('/proc/self/ns/net')
  2009. return actual
  2010. def empty_native(self):
  2011. for p in pathlib.Path('/proc').iterdir():
  2012. if not p.name.isdecimal(): continue
  2013. try: same = os.readlink(p/'ns/pid') == self.controller['ns']['pid']
  2014. except FileNotFoundError: continue
  2015. if same: assert int(p.name) == self.controller['pid'], 'CLI/native descendants remain at phase boundary'
  2016. def request(self):
  2017. message = control_receive(self.peer,self.clock)
  2018. assert message['sequence'] == self.sequence+1, 'outer control sequence'
  2019. self.sequence += 1
  2020. if self.nonce is None: self.nonce = message['nonce']
  2021. assert message['nonce'] == self.nonce and re.fullmatch(r'[0-9a-f]{64}',self.nonce), 'case control nonce'
  2022. self.clock.cleanup_used = max(self.clock.cleanup_used,message['cleanupUsed'])
  2023. assert 0 <= self.clock.cleanup_used < 8, 'shared cumulative cleanup ledger'
  2024. reply = {'sequence':self.sequence,'nonce':self.nonce,'ok':True}
  2025. action = message['action']
  2026. if action == 'controller-thread':
  2027. expected = 'enabled-native' if not self.phases else 'disabled-restart'
  2028. if self.trace is None or self.controller is None or self.closed or self.clock.work is None or len(self.phases) >= 2 or message.get('phase') != self.active_phase or self.active_phase != expected: raise AssertionError('controller thread inactive phase')
  2029. local = message.get('thread')
  2030. if type(local) is not dict or set(local) != {'tid','birth'} or type(local['tid']) is not int or not 0 < local['tid'] <= 2147483647 or type(local['birth']) is not int or not 0 <= local['birth'] <= 18446744073709551615: raise AssertionError('controller thread tuple budget')
  2031. parser = self.trace.parser
  2032. def matching():
  2033. return [t for t in parser.tasks.values() if t.get('parent') and not t.get('exited') and not t.get('capture') and not t.get('nativeLeader') and t['key'][1] == local['birth'] and t['facts']['tgid'] == self.controller['pid'] and len(t['facts']['nspid']) == len(self.controller['nspid']) and t['facts']['nspid'][-1] == local['tid']]
  2034. with parser.changed:
  2035. if not parser.changed.wait_for(lambda:self.trace.error is not None or bool(matching()),self.clock.wait(1)): raise AssertionError('controller thread live trace deadline')
  2036. known = matching()
  2037. if self.trace.error is not None or len(known) != 1: raise AssertionError(self.trace.error or 'controller thread mapping ambiguity')
  2038. task = known[0]; parent_key = task['parent']
  2039. parent = parser.register(parent_key[0]); child = parser.register(task['key'][0])
  2040. parent_fresh = trace_task_identity(parent_key[0]); child_fresh = trace_task_identity(task['key'][0])
  2041. for fresh,retained in ((parent_fresh,parent),(child_fresh,child)):
  2042. if (fresh['pid'],fresh['birth']) != retained['key'] or fresh['ns'] != self.controller['ns'] or fresh['uids'] != fresh['gids'] or fresh['uids'] != [1000]*4 or fresh['groups'] != [] or fresh['tracer'] != self.trace.tracer['pid'] or fresh['nspid'] != retained['facts']['nspid']: raise AssertionError('controller thread fresh metadata drift')
  2043. if parent['key'] != parent_key or parent_fresh['tgid'] != self.controller['pid'] or child['key'] != task['key'] or child['parent'] != parent_key or child_fresh['tgid'] != self.controller['pid'] or len(child_fresh['nspid']) != len(self.controller['nspid']) or child_fresh['nspid'][-1] != local['tid'] or child_fresh['birth'] != local['birth']: raise AssertionError('controller thread fresh identity drift')
  2044. reply['controllerThread'] = {'tid':local['tid'],'birth':local['birth'],'phase':self.active_phase}
  2045. control_send(self.peer,reply,self.clock)
  2046. return
  2047. if action == 'prepare':
  2048. assert self.controller is None and self.trace is None and self.session is None
  2049. self.controller = self.controller_identity(message['controller'])
  2050. self.empty_native()
  2051. installed = (pathlib.Path(message['primary']),pathlib.Path(message['selector']),message['binding'],message['generation'])
  2052. # Allocate before containment.
  2053. self.session = OwnedNotificationsSession.__new__(OwnedNotificationsSession)
  2054. self.session.__init__(self.controller,self.inputs['root'],self.clock,self.inputs['tools'],self.inputs['displayNumber'])
  2055. self.empty_native() # All services are outside P1; no setup CLI remains.
  2056. self.trace = PassiveStrace.__new__(PassiveStrace)
  2057. self.trace.__init__(self.controller,installed,self.inputs['root'],self.clock,self.inputs['tools'],self.session)
  2058. reply['environment'] = {k:self.session.env[k] for k in ('DBUS_SESSION_BUS_ADDRESS','DISPLAY','XAUTHORITY')}
  2059. reply['controller'] = self.controller
  2060. reply['tracer'] = self.trace.tracer
  2061. elif action == 'begin-phase':
  2062. assert message['phase'] == ('enabled-native' if not self.phases else 'disabled-restart') and len(self.phases) < 2
  2063. self.empty_native(); self.session.assert_continuous(); self.trace.begin_phase()
  2064. self.active_phase = message['phase']
  2065. elif action == 'leader':
  2066. assert message['phase'] == ('enabled-native' if not self.phases else 'disabled-restart')
  2067. if self.clock.work is None: self.clock.work = min(message['nativeStart']+90,self.clock.outer-8)
  2068. self.clock.wait(5)
  2069. end = time.monotonic()+self.clock.wait(1)
  2070. while True:
  2071. assert self.trace.error is None, self.trace.error
  2072. with self.trace.parser.lock:
  2073. known = [t for t in self.trace.parser.tasks.values() if t['facts']['birth'] == message['localLeader']['birth'] and t['facts']['nspid'][-1] == message['localLeader']['pid']]
  2074. if len(known) == 1: break
  2075. assert time.monotonic() < end, 'trace/native leader synchronization deadline'
  2076. time.sleep(min(.001,max(0,end-time.monotonic())))
  2077. reply['leader'] = self.trace.select_leader(message['localLeader'],end)
  2078. self.session.assert_continuous()
  2079. elif action == 'phase':
  2080. phase = message['phase']
  2081. assert phase == ('enabled-native' if not self.phases else 'disabled-restart') and len(self.phases) < 2
  2082. self.empty_native()
  2083. end = time.monotonic()+self.clock.wait(1)
  2084. while True:
  2085. assert self.trace.error is None, self.trace.error
  2086. with self.trace.parser.lock:
  2087. completed = [c for c in self.trace.parser.selected if c['leader'][1] == message['localLeader']['birth'] and c['exited'] and c['eof']]
  2088. terminal = all(t.get('exited') or t['facts']['tgid'] == self.controller['pid'] for t in self.trace.parser.tasks.values())
  2089. if len(completed) == 1 and terminal: break
  2090. assert time.monotonic() < end, 'native exit/alias trace completion deadline'
  2091. time.sleep(min(.001,max(0,end-time.monotonic())))
  2092. capture,raw,facts = self.trace.phase(message['localLeader'],message['cleanupSignal'],message['cleanupRoles'])
  2093. self.session.checkpoint(capture['identity'],enabled=phase == 'enabled-native')
  2094. if self.phases:
  2095. assert facts['conversation'] != self.phases[0]['facts']['conversation'] and facts['generation'] != self.phases[0]['facts']['generation'], 'planned restart has stale native identities'
  2096. evidence = pathlib.Path(self.inputs['root'])/'evidence'/phase
  2097. sha = hashlib.sha256(raw).hexdigest()
  2098. (evidence/'native-outer-consumed-stdin.bin').write_bytes(raw)
  2099. (evidence/'native-outer-consumed-stdin.sha256').write_text(sha+'\n')
  2100. (evidence/'stdin-alias-trace.json').write_text(json.dumps({k:v for k,v in capture.items() if k not in ('bytes','busConnections')},indent=2)+'\n')
  2101. self.phases.append({'phase':phase,'facts':facts,'nativeSHA256':sha,'helperIdentity':capture['identity']})
  2102. reply.update(nativeBytes=base64.b64encode(raw).decode(),facts=facts,nativeSHA256=sha,helperIdentity=capture['identity'])
  2103. elif action == 'checkpoint':
  2104. assert self.phases
  2105. self.empty_native(); self.session.checkpoint()
  2106. elif action == 'close':
  2107. assert len(self.phases) == 2
  2108. self.empty_native(); self.session.checkpoint()
  2109. self.trace.close(); self.session.close()
  2110. self.closed = True
  2111. reply['cleanupUsed'] = self.clock.cleanup_used
  2112. else: raise AssertionError('unknown outer control action')
  2113. control_send(self.peer,reply,self.clock)
  2114. def digest(path):
  2115. with pathlib.Path(path).open('rb') as stream:
  2116. return hashlib.file_digest(stream, 'sha256').hexdigest()
  2117. def physical(path):
  2118. path = pathlib.Path(path)
  2119. assert path.is_absolute() and path.resolve(strict=True) == path, 'physical absolute input required'
  2120. return path
  2121. def execution_inputs(filename, inside=False):
  2122. data = strict_json(physical(filename).read_bytes())
  2123. assert set(data) == {'sourceSHA', 'root', 'artifact', 'stage', 'package', 'cursorArchive', 'buildInfo', 'machineID', 'sha256', 'tools', 'displayNumber', 'readbackHelper', 'readbackBuildInfo'}, 'execution input fields'
  2124. assert data['sourceSHA'] == SOURCE_SHA and data['machineID'], 'fixed final source/runner required'
  2125. root = pathlib.Path(data['root'])
  2126. assert root.is_absolute() and root.name.startswith('TEST-cursor-installed-') and (root.is_dir() if inside else not root.exists()) and not root.is_symlink(), 'fresh TEST root required'
  2127. physical(root.parent)
  2128. for key in ['artifact', 'stage', 'package', 'cursorArchive', 'buildInfo', 'readbackHelper', 'readbackBuildInfo']: physical(data[key])
  2129. primary = pathlib.Path(data['stage'])/'claude-notifications-linux-amd64'
  2130. assert digest(primary) == data['sha256']['primary'] and digest(data['package']) == data['sha256']['package']
  2131. with zipfile.ZipFile(data['package']) as archive:
  2132. names = archive.namelist()
  2133. assert len(names) == len(set(names)) and {'plugin.json', 'mcp.json', 'bin/claude-notifications'} <= set(names)
  2134. for member in archive.infolist():
  2135. path = pathlib.PurePosixPath(member.filename)
  2136. assert not path.is_absolute() and '..' not in path.parts and '\\' not in member.filename
  2137. assert not stat.S_ISLNK(member.external_attr >> 16) and member.file_size <= 80 << 20
  2138. assert sum(m.file_size for m in archive.infolist()) <= 96 << 20
  2139. assert hashlib.sha256(archive.read('bin/claude-notifications')).hexdigest() == data['sha256']['primary']
  2140. build_info = pathlib.Path(data['buildInfo']).read_bytes()
  2141. assert len(build_info) <= 65536 and hashlib.sha256(build_info).hexdigest() == data['sha256']['buildInfo']
  2142. assert ('vcs.revision='+SOURCE_SHA).encode() in build_info and b'vcs.modified=false' in build_info
  2143. assert b'github.com/777genius/plugin-kit-ai/sdk\tv1.2.1-0.20261002230153-01f7fced8098' in build_info
  2144. assert b'=>\t' not in build_info, 'local module replacement forbidden'
  2145. assert digest(data['readbackHelper']) == data['sha256']['readbackHelper'], 'source-built read-only bridge bytes'
  2146. bridge_info = pathlib.Path(data['readbackBuildInfo']).read_bytes()
  2147. assert len(bridge_info) <= 65536 and hashlib.sha256(bridge_info).hexdigest() == data['sha256']['readbackBuildInfo']
  2148. assert ('vcs.revision='+SOURCE_SHA).encode() in bridge_info and b'vcs.modified=false' in bridge_info
  2149. assert ('main.packetSourceSHA256='+READBACK_SOURCE_SHA256).encode() in bridge_info and b'=>\t' not in bridge_info
  2150. assert hashlib.sha256(READBACK_SOURCE_BYTES).hexdigest() == READBACK_SOURCE_SHA256
  2151. archive = pathlib.Path(data['cursorArchive'])
  2152. dist = pathlib.Path(data['artifact'])
  2153. assert archive.stat().st_size == 182618248 and digest(archive) == CURSOR_ARCHIVE_SHA
  2154. with tarfile.open(archive) as opened:
  2155. members = opened.getmembers()
  2156. assert len(members) == 580
  2157. assert len({m.name for m in members}) == len(members)
  2158. for member in members:
  2159. name = pathlib.PurePosixPath(member.name)
  2160. assert not name.is_absolute() and '..' not in name.parts and (member.isfile() or member.isdir())
  2161. files = [m for m in members if m.isfile()]
  2162. paths = [pathlib.PurePosixPath(m.name).parts for m in files]
  2163. strip = 1 if len({parts[0] for parts in paths}) == 1 and all(len(parts) > 1 for parts in paths) else 0
  2164. expected = set()
  2165. for member in files:
  2166. relative = pathlib.Path(*pathlib.PurePosixPath(member.name).parts[strip:])
  2167. assert str(relative) not in expected
  2168. expected.add(str(relative))
  2169. target = physical(dist/relative)
  2170. assert target.is_file()
  2171. assert target.read_bytes() == opened.extractfile(member).read()
  2172. assert target.stat().st_mode & 0o111 == member.mode & 0o111
  2173. actual = set()
  2174. for target in dist.rglob('*'):
  2175. assert not target.is_symlink() and (target.is_dir() or stat.S_ISREG(target.lstat().st_mode))
  2176. if target.is_file(): actual.add(str(target.relative_to(dist)))
  2177. assert actual == expected, 'complete fixed runtime tree required'
  2178. assert digest(pathlib.Path(data['artifact'])/'cursor-agent') == LAUNCHER_SHA
  2179. assert digest(pathlib.Path(data['artifact'])/'index.js') == INDEX_SHA
  2180. for pin in ARTIFACT_PINS:
  2181. assert digest(pathlib.Path(data['artifact'])/pin['file']) == pin['sha256']
  2182. return data
  2183. def require_native_observation_contract(inputs, clock, inside=False):
  2184. """Checks grant prerequisites only; readiness is a later actual roundtrip."""
  2185. raise IncompleteInstalledContract('R1360 TEST increment: full Linux proof/exact review/carrier qualification pending; native ineligible')
  2186. clock.wait(5)
  2187. assert inputs['sourceSHA'] == SOURCE_SHA, 'immutable current helper source'
  2188. assert hashlib.sha256(WIRE_BYTES).hexdigest() == WIRE_SHA, 'original wire protection'
  2189. assert set(inputs['tools']) == {'strace','dbus-daemon','dbus-monitor','dbus-send','dunst','Xvfb','xauth','nsenter','setpriv'}
  2190. for name, tool in inputs['tools'].items():
  2191. assert set(tool) == {'path','sha256','package','version','installedMetadataSHA256'}, 'actual standard package provenance fields'
  2192. path = physical(tool['path'])
  2193. assert path == pathlib.Path('/usr/bin')/name and path.is_file(), 'standard immutable tool path'
  2194. assert digest(path) == tool['sha256'] and stat.S_IMODE(path.stat().st_mode) & 0o111, 'actual standard binary bytes'
  2195. assert tool['package'] and tool['version'] and re.fullmatch(r'[0-9a-f]{64}',tool['installedMetadataSHA256'])
  2196. assert inputs['tools']['strace']['version'] == '6.8-0ubuntu2', 'source-qualified strace version'
  2197. assert inputs['tools']['strace']['package'] == 'strace'
  2198. if inside:
  2199. # P1 root checks/drop; setup/passive attach.
  2200. assert os.getpid() == 1 and os.geteuid() == 0
  2201. return
  2202. assert os.geteuid() == 0, 'outer capability owner required'
  2203. status = pathlib.Path('/proc/self/status').read_text()
  2204. values = dict(line.split(':',1) for line in status.splitlines() if ':' in line)
  2205. capabilities = int(values['CapEff'].strip(),16)
  2206. assert capabilities & (1<<19) and capabilities & (1<<21), 'existing SYS_PTRACE/SYS_ADMIN required'
  2207. assert values['Seccomp'].strip() == '0', 'unknown outer syscall filter permission'
  2208. assert pathlib.Path('/proc/sys/kernel/yama/ptrace_scope').read_text().strip() in ('0','1','2'), 'existing Yama attach permission'
  2209. assert pathlib.Path('/proc/self/attr/current').read_text().strip() == 'unconfined', 'unknown LSM permission'
  2210. for name, tool in inputs['tools'].items():
  2211. command = ['/usr/bin/dpkg-query','--show','--showformat=${binary:Package}\t${Version}\t${db:Status-Status}\n',tool['package']]
  2212. metadata = subprocess.check_output(command,timeout=clock.wait(5),env={'PATH':'/usr/bin:/bin','LANG':'C'})
  2213. assert metadata.decode().strip() == tool['package']+'\t'+tool['version']+'\tinstalled'
  2214. assert hashlib.sha256(metadata).hexdigest() == tool['installedMetadataSHA256'], 'actual installed package metadata'
  2215. def qualified_runner(profile, machine_id):
  2216. assert pathlib.Path('/etc/machine-id').read_text().strip() == machine_id, 'actual frozen runner identity'
  2217. assert platform.system() == 'Linux' and platform.machine() == 'x86_64'
  2218. assert pathlib.Path('/proc/sys/kernel/osrelease').read_text().strip() == '6.17.0-1022-azure'
  2219. release = pathlib.Path('/etc/os-release').read_text()
  2220. assert '\nID=ubuntu\n' in '\n'+release and 'VERSION="24.04.5 LTS' in release
  2221. mounts = pathlib.Path('/proc/self/mountinfo').read_text()
  2222. assert len(mounts.encode()) <= LIMIT
  2223. decode = lambda s: s.replace('\\040', ' ').replace('\\011', '\t').replace('\\012', '\n').replace('\\134', '\\')
  2224. for path in [profile, *profile.parents]:
  2225. matches = []
  2226. for row in mounts.splitlines():
  2227. left, sep, right = row.partition(' - ')
  2228. if not sep or len(left.split()) < 6 or len(right.split()) < 3: continue
  2229. mount = decode(left.split()[4])
  2230. if mount == '/' or str(path) == mount or str(path).startswith(mount+'/'):
  2231. matches.append((len(mount), right.split()[0]))
  2232. longest = max(n for n, fs in matches)
  2233. selected = [fs for n, fs in matches if n == longest]
  2234. assert selected == ['ext4'], 'every actual ancestor must be unambiguously ext4'
  2235. # No grants/foreign/token; capture+revalidate.
  2236. def case_env(root):
  2237. return {'HOME':str(root/'home'), 'XDG_CONFIG_HOME':str(root/'home/.config'),
  2238. 'TMPDIR':str(root/'tmp'), 'XDG_CACHE_HOME':str(root/'cache'),
  2239. 'AGENT_NOTIFICATIONS_CONFIG':str(root/'home/.config/agent-notifications/config.json'),
  2240. 'PATH':'/usr/bin:/bin', 'LANG':'C.UTF-8', **SESSION_ENV}
  2241. def cli(root, primary, argv, name, payload=None, terminal=False):
  2242. command = [str(primary), *argv]
  2243. if terminal:
  2244. master, slave = os.openpty()
  2245. def controlling_pty():
  2246. os.setsid()
  2247. fcntl.ioctl(0, termios.TIOCSCTTY, 0)
  2248. child = None
  2249. raw = bytearray()
  2250. answered = False
  2251. deadline = time.monotonic()+CASE_CLOCK.wait(30)
  2252. try:
  2253. child = subprocess.Popen(command, stdin=slave, stdout=slave, stderr=slave,
  2254. cwd=root/'workspace', env=case_env(root), preexec_fn=controlling_pty)
  2255. os.close(slave)
  2256. slave = None
  2257. while child.poll() is None:
  2258. assert time.monotonic() < deadline, 'real controlling-PTY confirmation deadline'
  2259. if not select.select([master], [], [], min(.05,CASE_CLOCK.wait(.05)))[0]: continue
  2260. try: part = os.read(master, 8192)
  2261. except OSError as error:
  2262. if error.errno == 5: break
  2263. raise
  2264. raw.extend(part)
  2265. assert len(raw) <= LIMIT, 'bounded confirmation output'
  2266. if not answered and b'Apply this plan?' in raw:
  2267. # ONE fresh Yes via PTY.
  2268. os.write(master, b'y\n')
  2269. answered = True
  2270. assert answered and child.wait(timeout=min(CASE_CLOCK.wait(30),max(.001,deadline-time.monotonic()))) == 0
  2271. result = subprocess.CompletedProcess(command, child.returncode)
  2272. (root/'evidence'/str(name+'.pty')).write_bytes(raw)
  2273. finally:
  2274. if slave is not None: os.close(slave)
  2275. os.close(master)
  2276. # PTY: no retry; contain unknown children.
  2277. if child is not None and child.poll() is None: raise IncompleteInstalledContract('PTY join incomplete')
  2278. else:
  2279. result = subprocess.run(command, input=payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  2280. cwd=root/'workspace', env=case_env(root), timeout=CASE_CLOCK.wait(30))
  2281. assert len(result.stdout) <= LIMIT and len(result.stderr) <= LIMIT
  2282. (root/'evidence'/str(name+'.stdout')).write_bytes(result.stdout)
  2283. (root/'evidence'/str(name+'.stderr')).write_bytes(result.stderr)
  2284. assert result.returncode == 0, 'public CLI failed; do not retry'
  2285. return result.stdout if not terminal else None
  2286. def wizard(root, primary, artifact, package, action, enabled, extra=(), json_output=True):
  2287. control = root/'home/.config/agent-notifications'
  2288. args = ['setup-notifications', 'wizard', '--action', action, '--agents', 'cursor',
  2289. '--hooks', 'false', '--agent-notify', str(enabled).lower(), '--control-root', str(control),
  2290. '--scope-root', str(root/'home/.cursor'), '--client-executable', str(artifact/'cursor-agent'), '--yes']
  2291. if package is not None:
  2292. ledger = strict_json((control/'ownership.json').read_bytes())
  2293. args += ['--package', str(package), '--runtime-root', ledger['RuntimeRoot'],
  2294. '--global-config', case_env(root)['AGENT_NOTIFICATIONS_CONFIG']]
  2295. args += list(extra)
  2296. if json_output: args += ['--json']
  2297. return args
  2298. def inventory_object_refusal(directory, current, facts):
  2299. """Best-effort bounded TEST-only metadata from the already-read lstat."""
  2300. try:
  2301. test_root = next(p for p in (directory, *directory.parents) if p.name.startswith('TEST-'))
  2302. relative = current.relative_to(test_root)
  2303. assert not relative.is_absolute() and '..' not in relative.parts
  2304. path = str(relative)
  2305. row = {'path':path[:512], 'pathTruncated':len(path) > 512,
  2306. 'pathSHA256':hashlib.sha256(path.encode('utf-8','surrogatepass')).hexdigest(),
  2307. 'mode':int(facts.st_mode), 'type':stat.S_IFMT(facts.st_mode),
  2308. 'device':int(facts.st_dev), 'inode':int(facts.st_ino)}
  2309. assert all(0 <= row[k] < 2**64 for k in ('mode','type','device','inode'))
  2310. message = json.dumps(row,ensure_ascii=True,separators=(',',':'))
  2311. assert len(message) <= 4096
  2312. print('inventory-object-refusal '+message,file=sys.stderr,flush=True)
  2313. except Exception:
  2314. pass
  2315. def vendor_worker_socket_path(root):
  2316. """Lexical pinned45d9 path derivation; only this isolated TEST case."""
  2317. root = pathlib.Path(root)
  2318. assert root.name == 'TEST-cursor-installed-one' and root.parent.name.startswith('TEST-cursor-installed-packet-')
  2319. assert root.parent.parent == pathlib.Path('/tmp') and '..' not in root.parts
  2320. data = root/'home/.cursor'
  2321. base = data/'projects'
  2322. if len(str(base)) > 84: base = data
  2323. if len(str(base)) > 84: return None # vendor /tmp/.cursor fallback is outside this owned TEST root
  2324. workspace = re.sub(r'^-+|-+$','',re.sub(r'-+','-',re.sub(r'[^a-zA-Z0-9]','-',str(root/'workspace'))))
  2325. joined = str(base/workspace)
  2326. if len(joined) > 92: joined = joined[:84]+'-'+hashlib.sha256(joined.encode()).hexdigest()[:7]
  2327. socket_path = pathlib.Path(joined)/'worker.sock'
  2328. return socket_path if socket_path.is_relative_to(data) else None
  2329. def bounded_tree(directory, vendor_root=None):
  2330. """Full no-follow path, member, byte and identity sets; no suffix guessing."""
  2331. directory = pathlib.Path(directory)
  2332. result = {}; total = 0
  2333. vendor_socket = vendor_worker_socket_path(vendor_root) if vendor_root is not None else None
  2334. if not os.path.lexists(directory): return result
  2335. stack = [directory]
  2336. while stack:
  2337. current = stack.pop()
  2338. facts = current.lstat()
  2339. assert len(result) < 16384, 'full object membership bound'
  2340. value = {'mode':facts.st_mode, 'uid':facts.st_uid, 'gid':facts.st_gid,
  2341. 'device':facts.st_dev,'inode':facts.st_ino,'nlink':facts.st_nlink}
  2342. if stat.S_ISLNK(facts.st_mode):
  2343. value['link'] = os.readlink(current)
  2344. assert len(value['link'].encode()) <= 4096, 'raw link bound'
  2345. elif stat.S_ISREG(facts.st_mode):
  2346. assert facts.st_size <= TEST_RUNTIME_FILE_LIMIT, 'full object file bound'
  2347. body = current.read_bytes(); assert len(body) == facts.st_size
  2348. total += len(body); assert total <= 1024**3, 'full writable-case bound'
  2349. value['sha256'] = hashlib.sha256(body).hexdigest(); value['byteLength'] = len(body)
  2350. if current.suffix == '.json':
  2351. parsed = strict_json(body)
  2352. value['jsonMembers'] = json_members(parsed)
  2353. elif stat.S_ISSOCK(facts.st_mode) and current == vendor_socket:
  2354. parent = result.get(str(current.parent.relative_to(directory)),{})
  2355. assert (facts.st_uid,facts.st_gid,facts.st_dev) == (parent.get('uid'),parent.get('gid'),parent.get('device')), 'foreign vendor socket ownership'
  2356. value['type'] = stat.S_IFSOCK
  2357. else:
  2358. if not stat.S_ISDIR(facts.st_mode):
  2359. inventory_object_refusal(directory,current,facts)
  2360. assert stat.S_ISDIR(facts.st_mode), 'unknown filesystem object'
  2361. stack.extend(sorted(current.iterdir(),reverse=True))
  2362. final = current.lstat()
  2363. assert (facts.st_mode,facts.st_uid,facts.st_gid,facts.st_dev,facts.st_ino,facts.st_nlink,facts.st_size,facts.st_mtime_ns,facts.st_ctime_ns) == (final.st_mode,final.st_uid,final.st_gid,final.st_dev,final.st_ino,final.st_nlink,final.st_size,final.st_mtime_ns,final.st_ctime_ns), 'object changed during full inventory'
  2364. result[str(current.relative_to(directory))] = value
  2365. assert len(json.dumps(result)) <= 4*LIMIT, 'bounded full tree evidence/hex expansion'
  2366. return result
  2367. def json_members(value, path=''):
  2368. result = []
  2369. def visit(node, location, depth):
  2370. assert depth <= 64 and len(result) < 65536, 'full JSON member bound'
  2371. result.append(location)
  2372. if type(node) is dict:
  2373. for key in sorted(node): visit(node[key],location+'/'+key.replace('~','~0').replace('/','~1'),depth+1)
  2374. elif type(node) is list:
  2375. for i,child in enumerate(node): visit(child,location+'/'+str(i),depth+1)
  2376. visit(value,path,0)
  2377. return result
  2378. def authoritative_readback(root, primary, selector, binding, phase, mode='live'):
  2379. """Actual public Load/Inspect/Gate/Revalidate; the first token is never recaptured."""
  2380. assert READBACK_INPUTS is not None
  2381. key = str(root)
  2382. frozen = AUTHORITY_BASELINE.get(key)
  2383. request = {'mode':mode,'selector':str(selector),'binding':binding,'tempRoot':str(root/'tmp'),
  2384. 'timeoutMillis':max(1,int(CASE_CLOCK.wait(5)*1000)), 'sourceSHA256':READBACK_SOURCE_SHA256,
  2385. 'originalAuthority':frozen['originalAuthority'] if frozen else None,
  2386. 'originalNamespace':frozen['originalNamespace'] if frozen else '',
  2387. 'fixed':frozen['fixed'] if frozen else None}
  2388. observed = strict_json(cli(root,pathlib.Path(READBACK_INPUTS['readbackHelper']),[],phase+'-public-authority',json.dumps(request).encode()))
  2389. assert observed['mode'] == mode and observed['bridgeSourceSHA256'] == READBACK_SOURCE_SHA256
  2390. assert observed['binding'] == binding
  2391. recovery = observed['inspection']['Recovery']
  2392. assert recovery['Required'] is False and not recovery['Reason']
  2393. assert not recovery['Journals'] and not recovery['Receipts'] and not recovery['NativeIntents']
  2394. state_path = root/'home/.config/uap/state/state-v2.json'
  2395. raw = strict_json(state_path.read_bytes())
  2396. assert raw['schema_version'] == 4 and raw.get('installations',[]) == (observed['state'].get('installations') or []), 'actual Load versus raw state membership'
  2397. operations = state_path.parent/'operations'
  2398. if operations.exists():
  2399. assert not list(operations.iterdir()), 'raw operation remainder is unknown'
  2400. if mode != 'absent':
  2401. selected = observed['selected']
  2402. assert selected['target_locator'] == str(root/'home/.cursor/plugins/local'/selector.parent.name), 'selected managed MCP target changed'
  2403. authority = selected['profile_authority']
  2404. assert authority == observed['originalAuthority'] and selected['profile_namespace'] == observed['originalNamespace']
  2405. assert set(authority) == {'version','canonical_root','ancestry'} and authority['version'] == 1
  2406. assert authority['canonical_root'] == binding['scopeRoot'] and authority['ancestry']
  2407. assert all(set(entry) == {'canonical_path','scheme','volume_id','object_id'} for entry in authority['ancestry'])
  2408. assert selected['materialization'] == 'materialized' and selected['activation'] == 'prepared' and selected['verification'] == 'package_validated', 'registration readback remains prepared/package-valid'
  2409. assert selected['policy'] == 'allowed' and not selected.get('pending_native_intent') and not selected.get('native_activation_attempt')
  2410. objects = selected['native_objects']
  2411. assert len(objects) == 2 and sorted(o['kind'] for o in objects) == ['cursor_user_stop','managed_package_directory']
  2412. expected_protection = {'cursor_user_stop':'owned_selector','managed_package_directory':'managed'}
  2413. assert all(not o.get('user_modified',False) and o['protection_class'] == expected_protection[o['kind']] for o in objects)
  2414. if frozen:
  2415. assert authority == frozen['originalAuthority'] and observed['originalNamespace'] == frozen['originalNamespace'], 'original raw complete ordered authority changed'
  2416. assert observed['fixed'] == frozen['fixed']
  2417. else:
  2418. AUTHORITY_BASELINE[key] = {k:copy.deepcopy(observed[k]) for k in ('originalAuthority','originalNamespace','fixed')}
  2419. (root/'evidence/original-profile-authority.json').write_text(json.dumps(AUTHORITY_BASELINE[key],indent=2)+'\n')
  2420. channels = observed['channels']
  2421. expected = phase in ('enabled','native-enabled','duplicate')
  2422. assert channels == {'Desktop':expected,'Webhook':expected}, 'actual effective channel consent readback'
  2423. assert observed['consumerBinding']['Generation'] == strict_json((root/'home/.config/agent-notifications/ownership.json').read_bytes())['Generation']
  2424. (root/'evidence'/(phase+'-authoritative-readback.json')).write_text(json.dumps(observed,indent=2)+'\n')
  2425. return observed
  2426. def installed_readback(root, primary, artifact, phase, selector=None):
  2427. control = root/'home/.config/agent-notifications'
  2428. raw = {str(p.relative_to(root)):p.read_bytes() for p in
  2429. [control/'ownership.json', control/'agent-notifications.json',
  2430. control.parent/'uap/state/state-v2.json', root/'home/.cursor/hooks.json']}
  2431. assert not (control/'transaction.json').exists(), 'recovery is not resolved'
  2432. ledger = strict_json(raw[str((control/'ownership.json').relative_to(root))])
  2433. assert ledger['Owner'] == 'existing-installer' and ledger['Generation'] > 0 and not ledger.get('PendingMutation')
  2434. assert ledger['RuntimeRoot'] == str(root/'home/.local')
  2435. assert primary == pathlib.Path(ledger['RuntimeRoot'])/'bin/claude-notifications-linux-amd64'
  2436. identity = ledger['Files'][str(primary)]
  2437. assert identity['Exists'] is True and not identity['Link'] and identity['SHA256'] == digest(primary)
  2438. assert identity['Mode'] == stat.S_IMODE(primary.stat().st_mode)
  2439. hooks = strict_json(raw['home/.cursor/hooks.json'])
  2440. assert hooks['version'] == 1
  2441. entries = []
  2442. for hook in hooks['hooks']['stop']:
  2443. argv = shlex.split(hook['command'])
  2444. if argv[:4] == [str(primary), 'cursor-event', 'stop', '--binding']:
  2445. assert len(argv) == 5 and hook['timeout'] == 5 and hook.get('failClosed') is False
  2446. entries.append(argv)
  2447. assert len(entries) == 1, 'exact USER owned helper hook required'
  2448. actual = physical(entries[0][4])
  2449. binding = strict_json(actual.read_bytes())
  2450. assert selector is None or actual == selector, 'same installed selector required'
  2451. assert binding['integration'] == 'cursor' and binding['scopeRoot'] == str(root/'home/.cursor')
  2452. assert binding['version'] == 1 and binding['owner'] == ledger['Owner'] and binding['componentID'] == ledger['ID']
  2453. assert binding['controlRoot'] == str(control) and binding['runtimeRoot'] == ledger['RuntimeRoot']
  2454. assert binding['primary'] == 'bin/claude-notifications-linux-amd64'
  2455. assert binding['globalConfig'] == case_env(root)['AGENT_NOTIFICATIONS_CONFIG']
  2456. assert physical(binding['dataRoot']) == actual.parent
  2457. # Hash committed; raw has no authority/ACK.
  2458. consumers = [(key, value) for key, value in ledger['Consumers'].items()
  2459. if key.startswith('portable:') and strict_json(value['Registration']) == binding]
  2460. assert len(consumers) == 1, 'one exact selected registered consumer required'
  2461. key, consumer = consumers[0]
  2462. registration = consumer['Registration'].encode('utf-8')
  2463. assert key == 'portable:'+hashlib.sha256(registration).hexdigest()
  2464. assert actual.name == 'agent-notify-'+key[len('portable:'):]+'.json'
  2465. assert actual.read_bytes() == registration and consumer['RuntimeRoot'] == ledger['RuntimeRoot']
  2466. assert consumer['Commands'] == [str(primary)]
  2467. # Readback authority/ACK/receipt gated.
  2468. report = strict_json(cli(root, primary, wizard(root, primary, artifact, None, 'inspect', True), phase+'-inspect'))
  2469. assert report['action'] == 'inspect' and report['outcome'] == 'completed', 'inspect exit 0 is insufficient'
  2470. assert report['installationID'] == binding['installationID']
  2471. selected = [row for row in report['targets'] if row['client'] == 'cursor' and row['unit'] == 'agent-notify']
  2472. assert len(selected) == 1 and selected[0]['outcome'] == 'installed'
  2473. assert selected[0]['reason'] == binding['bindingID'] and selected[0]['treeDigest']
  2474. assert selected[0]['profile'] == binding['scopeRoot']
  2475. assert not any(row['outcome'] in ('unknown', 'incomplete') for row in report['targets'])
  2476. assert not any(row['kind'] in ('recover', 'resume', 'activate', 'external-uninstall') for row in report.get('nextActions', []))
  2477. authoritative_readback(root,primary,actual,binding,phase)
  2478. saved = {name:base64.b64encode(data).decode() for name, data in raw.items()}
  2479. (root/'evidence'/str(phase+'-readback.json')).write_text(json.dumps(saved, indent=2)+'\n')
  2480. return actual, binding, ledger['Generation']
  2481. def install_and_confirm(root, artifact, inputs, webhook_url):
  2482. stage = pathlib.Path(inputs['stage'])
  2483. control = root/'home/.config/agent-notifications'
  2484. # Pinned native file-reader fixture, retained in the initial foreign HOME inventory.
  2485. home = root/'home'; home_facts = home.lstat()
  2486. if not stat.S_ISDIR(home_facts.st_mode) or stat.S_IMODE(home_facts.st_mode) != 0o700 or (home_facts.st_uid,home_facts.st_gid) != (1000,1000):
  2487. raise ValueError('TEST credential HOME identity')
  2488. config = home/'.config'; config.mkdir(mode=0o700)
  2489. credentials = config/'cursor'; credentials.mkdir(mode=0o700)
  2490. directory_facts = credentials.lstat()
  2491. if not stat.S_ISDIR(directory_facts.st_mode) or stat.S_IMODE(directory_facts.st_mode) != 0o700 or (directory_facts.st_uid,directory_facts.st_gid,directory_facts.st_dev) != (1000,1000,home_facts.st_dev):
  2492. raise ValueError('TEST credential directory identity')
  2493. credential_path = credentials/'auth.json'
  2494. synthetic_token = 'TEST-loopback-not-a-secret'
  2495. with os.fdopen(os.open(credential_path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600),'w') as credential_file:
  2496. file_facts = os.fstat(credential_file.fileno())
  2497. if not stat.S_ISREG(file_facts.st_mode) or stat.S_IMODE(file_facts.st_mode) != 0o600 or file_facts.st_nlink != 1 or (file_facts.st_uid,file_facts.st_gid,file_facts.st_dev) != (1000,1000,home_facts.st_dev):
  2498. raise ValueError('TEST credential file identity')
  2499. credential_file.write(json.dumps({'accessToken':synthetic_token,'refreshToken':synthetic_token},indent=2))
  2500. final_facts = credential_path.lstat()
  2501. if (final_facts.st_mode,final_facts.st_uid,final_facts.st_gid,final_facts.st_dev,final_facts.st_ino,final_facts.st_nlink) != (file_facts.st_mode,file_facts.st_uid,file_facts.st_gid,file_facts.st_dev,file_facts.st_ino,1):
  2502. raise ValueError('TEST credential file replaced')
  2503. (root/'evidence/credential-fixture.json').write_text(json.dumps({'kind':'TEST-synthetic-file-credentials',
  2504. 'relativePath':'.config/cursor/auth.json','directoryMode':0o700,'fileMode':0o600,'uid':1000,'gid':1000,
  2505. 'fields':['accessToken','refreshToken'],'beforeForeignBaseline':True},separators=(',',':'))+'\n')
  2506. target = root/'home/.local/bin'
  2507. target.mkdir(mode=0o700, parents=True)
  2508. primary = stage/'claude-notifications-linux-amd64'
  2509. cli(root, primary, ['internal-install-runtime', '--stage', str(stage), '--target', str(target),
  2510. '--entry', primary.name, '--control-root', str(control)], 'core-register')
  2511. ledger = strict_json((control/'ownership.json').read_bytes())
  2512. assert ledger['RuntimeRoot'] == str(target.parent), 'core RuntimeRoot is parent of stable bin target'
  2513. primary = target/primary.name
  2514. assert digest(primary) == inputs['sha256']['primary'], 'committed core helper bytes'
  2515. cli(root, primary, ['config', 'init', '--json'], 'config-init')
  2516. inspection = strict_json(cli(root, primary, ['config', 'inspect', '--json'], 'config-inspect'))
  2517. assert inspection['valid'] is True and inspection['revision']
  2518. edits = {'set':{'/notifications/desktop/enabled':True, '/notifications/webhook/enabled':True,
  2519. '/notifications/webhook/url':webhook_url, '/notifications/webhook/preset':'custom', '/notifications/webhook/format':'json',
  2520. '/statuses/agent_stopping/enabled':True, '/statuses/agent_stopping/desktop/enabled':True,
  2521. '/statuses/agent_stopping/webhook/enabled':True}}
  2522. cli(root, primary, ['config', 'edit', '--stdin', '--expect-revision', inspection['revision']],
  2523. 'config-edit', json.dumps(edits).encode())
  2524. with os.fdopen(os.open(control/'agent-notifications.json', os.O_WRONLY|os.O_CREAT|os.O_EXCL, 0o600), 'wb') as policy: policy.write(b'{"schemaVersion":1,"enabled":false}\n')
  2525. assert strict_json((control/'ownership.json').read_bytes()) == ledger, 'TEST policy initialization must not change core ledger'
  2526. (root/'evidence/policy-init.json').write_text(json.dumps({'path':str(control/'agent-notifications.json'), 'policy':strict_json((control/'agent-notifications.json').read_bytes()), 'mode':(control/'agent-notifications.json').stat().st_mode, 'generation':ledger['Generation']})+'\n')
  2527. foreign = foreign_preimage(root)
  2528. installed_report = strict_json(cli(root, primary, wizard(root, primary, artifact, inputs['package'], 'install', True), 'install'))
  2529. assert installed_report['action'] == 'install' and installed_report['outcome'] == 'completed', 'cancelled exit 0 is insufficient'
  2530. selector, binding, generation = installed_readback(root, primary, artifact, 'install')
  2531. assert installed_report['installationID'] == binding['installationID'] and installed_report['generation'] == generation
  2532. selected = [row for row in installed_report['targets'] if row['client'] == 'cursor' and row['unit'] == 'agent-notify']
  2533. assert len(selected) == 1 and selected[0]['outcome'] == 'completed' and selected[0]['reason'] == binding['bindingID']
  2534. intent = primary.parent/'TEST-cursor-confirmed-intent.json'
  2535. assert not intent.exists()
  2536. channel_args = ['--products', 'cursor', '--agent-notify', '--desktop', '--webhook']
  2537. cli(root, primary, ['setup-products', 'confirm', '--plain', *channel_args, '--scope-root', str(root/'home/.cursor'),
  2538. '--client-executable', str(artifact/'cursor-agent'), '--control-root', str(control),
  2539. '--intent-file', str(intent)], 'confirm', terminal=True)
  2540. cli(root, primary, ['setup-products', 'intent-args', '--intent-file', str(intent)], 'intent-args')
  2541. cli(root, primary, ['setup-products', 'preflight', '--intent-file', str(intent), *channel_args], 'preflight')
  2542. frozen = strict_json(intent.read_bytes())
  2543. assert frozen['provenance']['SourceCommit'] == SOURCE_SHA and frozen['provenance']['SHA256'] == digest(primary)
  2544. scopes = {name:base64.b64decode(value, validate=True).decode() for name, value in frozen['scopes'].items()}
  2545. assert scopes['scope-root'] == str(root/'home/.cursor') and scopes['client-executable'] == str(artifact/'cursor-agent')
  2546. args = ['setup-notifications', 'wizard', '--action', 'install', '--install-or-update', '--agents', 'cursor',
  2547. '--hooks', 'false', '--agent-notify', 'true', '--yes', '--package', inputs['package'],
  2548. '--bootstrap-intent-file', str(intent)]
  2549. for key in ['control-root', 'runtime-root', 'global-config', 'scope-root', 'client-executable']:
  2550. args += ['--'+key, scopes[key]]
  2551. # Update before consent CAS.
  2552. cli(root, primary, args, 'update-before-consent')
  2553. selector, binding, generation = installed_readback(root, primary, artifact, 'enabled', selector)
  2554. foreign['ownedOperatorObjects'] = {str(intent.relative_to(root/'home')):bounded_tree(intent)['.']}
  2555. return (primary, selector, binding, generation), foreign
  2556. def webhook_source_body(payload):
  2557. value = strict_json(payload)
  2558. expected = {'schema_version':'1.0','notification_type':'agent_stopping','status':'agent_stopping',
  2559. 'agent_source':'cursor','message':'Cursor CLI is stopping','title':'Cursor CLI',
  2560. 'session_id':'','source':'claude-notifications'}
  2561. assert type(value) is dict and set(value) == set(expected)|{'timestamp'}, 'unknown webhook source fields'
  2562. assert all(value[key] == wanted for key,wanted in expected.items()), 'wrong fixed Cursor stopping webhook copy'
  2563. assert type(value['timestamp']) is str and re.fullmatch(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:\d{2})',value['timestamp']), 'unknown source RFC3339 timestamp'
  2564. if value['timestamp'][-1] != 'Z':
  2565. assert int(value['timestamp'][-5:-3]) <= 23 and int(value['timestamp'][-2:]) <= 59, 'invalid RFC3339 numeric offset'
  2566. datetime.datetime.fromisoformat(value['timestamp'])
  2567. return value
  2568. def owned_webhook(root):
  2569. records = []
  2570. lock = threading.Lock()
  2571. class Webhook(http.server.BaseHTTPRequestHandler):
  2572. def setup(self):
  2573. super().setup()
  2574. self.connection.settimeout(CASE_CLOCK.wait(1))
  2575. def do_GET(self):
  2576. raise AssertionError('unsupported webhook method')
  2577. def log_message(self, *args): pass
  2578. def do_POST(self):
  2579. assert self.path == '/TEST-cursor-stop' and self.client_address[0] == '127.0.0.1'
  2580. assert self.headers.get('Content-Type', '').startswith('application/json')
  2581. size = int(self.headers.get('Content-Length', '-1'))
  2582. assert 0 <= size <= 65536
  2583. payload = self.rfile.read(size)
  2584. assert len(payload) == size
  2585. with lock:
  2586. assert len(records) < 2, 'no repeated channel effects allowed'
  2587. record = {'bodyHex':payload.hex(), 'json':webhook_source_body(payload), 'responseAccepted':False}
  2588. records.append(record)
  2589. (root/'evidence/webhook-actual.json').write_text(json.dumps(records, indent=2)+'\n')
  2590. self.send_response(200)
  2591. self.send_header('Content-Length', '0')
  2592. self.end_headers()
  2593. self.wfile.flush()
  2594. with lock:
  2595. record['responseAccepted'] = True
  2596. (root/'evidence/webhook-actual.json').write_text(json.dumps(records,indent=2)+'\n')
  2597. class OwnedServer(http.server.HTTPServer):
  2598. def handle_error(self, request, address):
  2599. assert len(self.case_failures) < 2, 'webhook failure budget'
  2600. self.case_failures.append(type(sys.exc_info()[1]).__name__)
  2601. (root/'evidence/webhook-failures.json').write_text(json.dumps(self.case_failures)+'\n')
  2602. server = OwnedServer(('127.0.0.1', 0), Webhook)
  2603. server.case_failures = []
  2604. thread = threading.Thread(target=server.serve_forever, daemon=True)
  2605. thread.start()
  2606. return server, thread, records, 'http://127.0.0.1:'+str(server.server_port)+'/TEST-cursor-stop'
  2607. def foreign_preimage(root):
  2608. profile = root/'home/.cursor'
  2609. control = root/'home/.config/agent-notifications'
  2610. ledger = strict_json((control/'ownership.json').read_bytes())
  2611. config = pathlib.Path(case_env(root)['AGENT_NOTIFICATIONS_CONFIG'])
  2612. state_path = control.parent/'uap/state/state-v2.json'
  2613. return {'home':bounded_tree(root/'home'),'profile':bounded_tree(profile), 'cache':bounded_tree(root/'cache'),
  2614. 'globalConfig':bounded_tree(config),'otherConsumers':ledger['Consumers'],
  2615. 'uapState':strict_json(state_path.read_bytes()) if state_path.exists() else {'schema_version':4,'installations':[]},
  2616. 'policy':strict_json((control/'agent-notifications.json').read_bytes())}
  2617. def same_preserved_object(before, after, directory_members_changed=False):
  2618. if before == after: return True
  2619. if directory_members_changed and stat.S_ISDIR(before['mode']) and stat.S_ISDIR(after['mode']):
  2620. return {k:v for k,v in before.items() if k != 'nlink'} == {k:v for k,v in after.items() if k != 'nlink'}
  2621. return False
  2622. def installation_map(state):
  2623. rows = state.get('installations') or []
  2624. assert type(rows) is list and len(rows) <= 1024, 'installation membership bound'
  2625. result = {}
  2626. for row in rows:
  2627. key = row['installation_id']
  2628. assert type(key) is str and key and key not in result, 'duplicate/unknown installation identity'
  2629. result[key] = row
  2630. return result
  2631. def removal_memberships(before, after, binding, foreign_state):
  2632. """Exact foreign membership; only source-defined selected removal changes."""
  2633. old,new,foreign = installation_map(before),installation_map(after),installation_map(foreign_state)
  2634. assert list(old) == list(new), 'ordered installation addition/deletion during removal'
  2635. selected_id = binding['installationID']
  2636. assert selected_id in old and selected_id not in foreign, 'selected installation preimage'
  2637. for key in old:
  2638. if key != selected_id: assert old[key] == new[key], 'foreign installation/client/dataReceipt changed'
  2639. for key in foreign: assert key in old and old[key] == new[key] == foreign[key], 'original foreign installation membership changed'
  2640. left,right = copy.deepcopy(old[selected_id]),copy.deepcopy(new[selected_id])
  2641. clients = left['clients']
  2642. selected = [(key,value) for key,value in clients.items() if value['client_binding_id'] == binding['bindingID']]
  2643. assert len(selected) == 1 and len(clients) == 1, 'SAME one selected client removal'
  2644. client_key,client = selected[0]
  2645. assert right['clients'] == {} and right.get('data_retained') is True, 'selected binding/retained data disposition'
  2646. assert left.get('data_receipts') and left.get('data_receipts') == right.get('data_receipts'), 'complete selected acknowledged data receipt membership'
  2647. preferences = copy.deepcopy(left.get('install_preferences',[]))
  2648. assert client.get('install_intent','') in ('','prepare'), 'unknown source install intent'
  2649. if client.get('install_intent','') != '':
  2650. preference = {'client_id':client['client_id'],'scope':client['scope'],'install_intent':client.get('install_intent','')}
  2651. matches = [i for i,row in enumerate(preferences) if row['client_id'] == preference['client_id'] and row['scope'] == preference['scope']]
  2652. assert len(matches) <= 1, 'ambiguous selected install preference'
  2653. if matches: preferences[matches[0]] = preference
  2654. else: preferences.append(preference)
  2655. assert right.get('install_preferences',[]) == preferences, 'foreign/selected preference membership'
  2656. assert type(right.get('operation_group_id')) is str and 0 < len(right['operation_group_id'].encode()) <= 256, 'actual committed removal operation group'
  2657. assert type(right['updated_at']) is str and right['updated_at'] >= left['updated_at'], 'actual removal time'
  2658. for field in ('clients','data_retained','updated_at','operation_group_id','install_preferences'):
  2659. left.pop(field,None);right.pop(field,None)
  2660. assert left == right, 'unknown selected installation mutation'
  2661. top_before = {key:value for key,value in before.items() if key != 'installations'}
  2662. top_after = {key:value for key,value in after.items() if key != 'installations'}
  2663. assert top_before == top_after, 'unknown state top-level/transaction receipt mutation'
  2664. return {'installationIDsBefore':list(old),'installationIDsAfter':list(new),'foreignInstallationsPreserved':{key:new[key] for key in new if key != selected_id},
  2665. 'selectedClientRemoved':client,'selectedDataReceiptsRetained':new[selected_id]['data_receipts'],
  2666. 'selectedCommittedAfter':new[selected_id],'stateJSONMembersBefore':json_members(before),'stateJSONMembersAfter':json_members(after)}
  2667. def classify_home_removal(root,binding,foreign,before,after,native,classified,memberships):
  2668. """Cover every HOME path, including complete control/UAP and foreign sets."""
  2669. home = root/'home'
  2670. mapped = {}
  2671. roots = {'profile':home/'.cursor','data':pathlib.Path(binding['dataRoot']),'projection':None}
  2672. for row in classified:
  2673. base = roots.get(row['area'])
  2674. if base is not None and (base == home or home in base.parents):
  2675. path = str((base/row['path']).relative_to(home))
  2676. assert path not in mapped or mapped[path] == row['disposition'], 'ambiguous full HOME classification'
  2677. mapped[path] = row['disposition']
  2678. control = pathlib.Path(binding['controlRoot'])
  2679. state = control.parent/'uap/state'
  2680. semantic = {str((control/'agent-notifications.json').relative_to(home)):'owned selected disabled channels retained; exact other policy members preserved',
  2681. str((control/'ownership.json').relative_to(home)):'owned ledger exact selected consumer removal and actual generation changes',
  2682. str((state/'state-v2.json').relative_to(home)):'owned state exact selected client removal with complete retained/foreign receipt membership'}
  2683. result = []
  2684. for path in sorted(set(before)|set(after)):
  2685. old,new = before.get(path),after.get(path)
  2686. disposition = mapped.get(path)
  2687. if disposition is None and path in semantic:
  2688. assert old and new and all(old[k] == new[k] for k in ('mode','uid','gid','device','nlink')), 'committed metadata ownership changed'
  2689. assert stat.S_ISREG(new['mode']) and 'link' not in old and 'link' not in new, 'semantic file is not regular'
  2690. disposition = semantic[path]
  2691. if disposition is None and path in foreign['home']:
  2692. assert new is not None and same_preserved_object(foreign['home'][path],new,True), 'foreign full HOME preimage changed'
  2693. disposition = 'foreign full HOME object/member set retained'
  2694. if disposition is None and path in foreign.get('ownedOperatorObjects',{}):
  2695. assert new == old == foreign['ownedOperatorObjects'][path], 'owned TEST intent altered'
  2696. disposition = 'owned retained explicit TEST consent intent'
  2697. if disposition is None and path in native:
  2698. assert old and new and same_preserved_object(native[path],old,True) and same_preserved_object(old,new,True), 'native HOME retained artifact changed/purged'
  2699. disposition = 'owned retained natural Cursor HOME artifact from native boundaries'
  2700. if disposition is None and old and new and stat.S_ISDIR(new['mode']):
  2701. assert same_preserved_object(old,new,True), 'owned structural directory metadata drift'
  2702. children = [key for key in set(before)|set(after) if key != path and key.startswith(path.rstrip('/')+'/')]
  2703. fixed = {'.config/uap','.config/uap/state','.config/uap/state/operations','.config/uap/managed','.config/uap/plugin-data'}
  2704. assert children or path in fixed, 'unknown empty retained HOME directory'
  2705. disposition = 'owned retained structural directory; all concrete child memberships classified'
  2706. if disposition is None and path == '.config/uap/state/mutation.lock':
  2707. assert old == new and new and stat.S_ISREG(new['mode']), 'mutation lock unknown identity/membership'
  2708. disposition = 'owned retained source-standard mutation lock'
  2709. assert disposition is not None, 'unclassified full HOME object addition/deletion/remainder: '+path
  2710. result.append({'area':'home','path':path,'disposition':disposition,'before':old,'after':new})
  2711. return result
  2712. def classify_removal(root,binding,selected,foreign,before,after,phases,expected_hook,state,original_state,before_ledger,after_ledger,before_policy,after_policy):
  2713. """Every concrete path has one observed owner/disposition; unknown refuses."""
  2714. target = pathlib.Path(selected['target_locator'])
  2715. profile = root/'home/.cursor'
  2716. projection_prefix = str(target.relative_to(profile)) if profile in target.parents else None
  2717. native = {'home':{},'profile':{},'cache':{}}
  2718. for phase in phases:
  2719. for area in native:
  2720. left,right = phase['nativeObjectsBefore'][area],phase['nativeObjectsAfter'][area]
  2721. for path,facts in right.items():
  2722. if left.get(path) != facts:
  2723. assert facts['uid'] == facts['gid'] == 1000, 'native retained object credential drift'
  2724. native[area][path] = facts
  2725. result = []
  2726. for area in ('profile','cache','data','projection'):
  2727. left,right = before[area],after[area]
  2728. for path in sorted(set(left)|set(right)):
  2729. old,new = left.get(path),right.get(path)
  2730. disposition = None
  2731. is_projection = area == 'projection' or area == 'profile' and projection_prefix is not None and (path == projection_prefix or path.startswith(projection_prefix+'/'))
  2732. if is_projection:
  2733. assert old is not None and new is None, 'selected owned projection remainder/addition'
  2734. disposition = 'owned projection removed including MCP/skills/binding membership'
  2735. if disposition is None and area == 'data':
  2736. selector = pathlib.Path(binding['dataRoot'])/path
  2737. if selector == pathlib.Path(AUTHORITY_BASELINE[str(root)]['fixed']['Selector']):
  2738. assert old is not None and new is None, 'selected owned selector remainder'
  2739. disposition = 'owned selected selector removed'
  2740. if disposition is None and area == 'profile' and path == 'hooks.json':
  2741. assert old is not None and new is not None and new['sha256'] == hashlib.sha256(expected_hook).hexdigest() and new['byteLength'] == len(expected_hook)
  2742. assert all(old[k] == new[k] for k in ('mode','uid','gid','device','nlink')), 'remaining hooks permissions/ownership'
  2743. disposition = 'owned stop member removed; exact public pure removal remainder retained'
  2744. if disposition is None and area == 'data':
  2745. assert old is not None and new is not None and same_preserved_object(old,new,True), 'PLUGIN_DATA/receipt/cache purge or unknown addition'
  2746. disposition = 'owned retained PLUGIN_DATA/receipt/observation cache'
  2747. if disposition is None and path in foreign.get(area,{}):
  2748. original = foreign[area][path]
  2749. assert new is not None and same_preserved_object(original,new,True), 'foreign preimage object/member/bytes changed'
  2750. disposition = 'foreign preimage retained'
  2751. if disposition is None and path in native.get(area,{}):
  2752. assert old is not None and new is not None and same_preserved_object(old,new,True), 'natural native data removed/changed'
  2753. assert same_preserved_object(native[area][path],old,True), 'native phase receipt does not match pre-remove object'
  2754. disposition = 'owned retained natural Cursor trust/cache/session object from observed native boundary'
  2755. if disposition is None and new is not None and stat.S_ISDIR(new['mode']):
  2756. # ACK/receipt identity/creds.
  2757. known = [p for p in native.get(area,{}) if p.startswith(path+'/')]
  2758. if area == 'profile' and projection_prefix and projection_prefix.startswith(path+'/'): known.append(projection_prefix)
  2759. assert known and old is not None and same_preserved_object(old,new,True), 'unknown retained directory'
  2760. disposition = 'owned retained structural parent with classified child membership'
  2761. assert disposition is not None, 'unclassified removal object: '+area+'/'+path
  2762. result.append({'area':area,'path':path,'disposition':disposition,'before':old,'after':new})
  2763. memberships = removal_memberships(original_state,state,binding,foreign['uapState'])
  2764. ledger_before = copy.deepcopy(before_ledger); ledger_after = copy.deepcopy(after_ledger)
  2765. selected_keys = [key for key,value in before_ledger['Consumers'].items() if strict_json(value['Registration']) == binding]
  2766. assert len(selected_keys) == 1, 'exact pre-remove actual selected consumer'
  2767. selected_key = selected_keys[0]
  2768. expected_consumers = {key:value for key,value in before_ledger['Consumers'].items() if key != selected_key}
  2769. assert after_ledger['Consumers'] == expected_consumers == foreign['otherConsumers'], 'full foreign consumer/binding membership'
  2770. delta = after_ledger['Generation']-before_ledger['Generation']
  2771. assert type(delta) is int and delta > 0 and after_ledger['PolicyGeneration']-before_ledger['PolicyGeneration'] == delta, 'actual removal generations'
  2772. for field in ('Generation','PolicyGeneration','Consumers'):
  2773. ledger_before.pop(field); ledger_after.pop(field)
  2774. assert ledger_before == ledger_after and not after_ledger.get('PendingMutation'), 'unknown ledger mutation/membership'
  2775. assert before_policy == after_policy, 'uninstall may not mutate foreign/disabled policy members'
  2776. foreign_policy = copy.deepcopy(foreign['policy']); retained_policy = copy.deepcopy(after_policy)
  2777. assert retained_policy.get('route',{}).get('cursorNotifications') == {'desktop':False,'webhook':False}, 'removed selected channels must remain disabled'
  2778. for document in (foreign_policy,retained_policy):
  2779. if 'route' in document:
  2780. document['route'].pop('cursorNotifications',None)
  2781. if not document['route']: document.pop('route')
  2782. assert foreign_policy == retained_policy, 'foreign policy JSON members/values changed'
  2783. home_result = classify_home_removal(root,binding,foreign,before['home'],after['home'],native['home'],result,memberships)
  2784. return {'objects':result+home_result,'stateMembership':memberships,
  2785. 'consumerMembership':{'before':before_ledger['Consumers'],'after':after_ledger['Consumers'],'selectedRemoved':selected_key},
  2786. 'ledgerSemanticChanges':{'Generation':delta,'PolicyGeneration':delta},'policyMembersPreserved':json_members(after_policy),
  2787. 'unknownRemainders':[]}
  2788. def finish_lifecycle(root, artifact, package, installed, first_phase, observation, clock, records, foreign):
  2789. primary, selector, binding, generation = installed
  2790. native_bytes = first_phase['observation']['nativeBytes']
  2791. assert type(native_bytes) is bytes and 0 < len(native_bytes) <= LIMIT, 'actual native bytes required'
  2792. assert first_phase['result']['status'] == 'PASS'
  2793. assert len(records) == 1 and records[0]['responseAccepted'] is True, 'one actual accepted webhook response'
  2794. baseline = copy.deepcopy(records)
  2795. def check_no_new_effects():
  2796. observation.exchange('checkpoint')
  2797. assert records == baseline, 'duplicate/disabled webhook delivery'
  2798. installed_readback(root, primary, artifact, 'native-enabled', selector)
  2799. cli(root, primary, ['cursor-event', 'stop', '--binding', str(selector)], 'duplicate', native_bytes)
  2800. check_no_new_effects()
  2801. installed_readback(root, primary, artifact, 'duplicate', selector)
  2802. cli(root, primary, wizard(root, primary, artifact, None, 'install', False), 'disable')
  2803. installed_readback(root, primary, artifact, 'disabled', selector)
  2804. policy = strict_json((root/'home/.config/agent-notifications/agent-notifications.json').read_bytes())
  2805. assert policy['route']['cursorNotifications'] == {'desktop':False, 'webhook':False}
  2806. cli(root, primary, ['cursor-event', 'stop', '--binding', str(selector)], 'disabled-stop', native_bytes)
  2807. check_no_new_effects()
  2808. cli(root, primary, wizard(root, primary, artifact, package, 'update', True), 'update')
  2809. installed_readback(root, primary, artifact, 'updated', selector)
  2810. policy = strict_json((root/'home/.config/agent-notifications/agent-notifications.json').read_bytes())
  2811. assert policy['route']['cursorNotifications'] == {'desktop':False, 'webhook':False}
  2812. restarted = native_run(root, artifact, installed, 'disabled-restart', clock, observation)
  2813. assert restarted['result']['status'] == 'PASS', restarted['result']['failure']
  2814. assert restarted['observation']['facts']['conversation'] != first_phase['observation']['facts']['conversation']
  2815. assert restarted['observation']['facts']['generation'] != first_phase['observation']['facts']['generation']
  2816. check_no_new_effects()
  2817. installed_readback(root, primary, artifact, 'restarted', selector)
  2818. installed_readback(root, primary, artifact, 'pre-remove', selector)
  2819. before = authoritative_readback(root,primary,selector,binding,'pre-remove','remove-plan')
  2820. selected = before['selected']
  2821. target = pathlib.Path(selected['target_locator'])
  2822. assert physical(target) == target and target != root and root in target.parents, 'selected actual projection boundary'
  2823. before_trees = {'home':bounded_tree(root/'home'),'profile':bounded_tree(root/'home/.cursor'),'cache':bounded_tree(root/'cache'),
  2824. 'data':bounded_tree(binding['dataRoot']),'projection':bounded_tree(target)}
  2825. before_ledger = strict_json((pathlib.Path(binding['controlRoot'])/'ownership.json').read_bytes())
  2826. before_policy = strict_json((pathlib.Path(binding['controlRoot'])/'agent-notifications.json').read_bytes())
  2827. removal = strict_json(cli(root, primary, wizard(root, primary, artifact, None, 'uninstall', True), 'remove'))
  2828. assert removal['action'] == 'uninstall' and removal['outcome'] == 'completed' and not removal.get('nextActions')
  2829. after_public = authoritative_readback(root,primary,selector,binding,'removed','absent')
  2830. inspect = strict_json(cli(root,primary,wizard(root,primary,artifact,None,'inspect',True),'removed-inspect'))
  2831. selected_rows = [row for row in inspect['targets'] if row['client'] == 'cursor' and row['unit'] == 'agent-notify']
  2832. assert inspect['outcome'] == 'completed' and len(selected_rows) == 1 and selected_rows[0]['outcome'] == 'absent'
  2833. assert not inspect.get('nextActions') and not any(row['outcome'] in ('unknown','incomplete','installed') for row in inspect['targets'])
  2834. after = foreign_preimage(root)
  2835. assert after['globalConfig'] == foreign['globalConfig'], 'full foreign global config bytes/mode/UIDGID/raw-link identity'
  2836. assert after['otherConsumers'] == foreign['otherConsumers'], 'other actual core ledger bindings preserved'
  2837. assert not selector.exists() and not target.exists(), 'selected consumer/selector/projection/MCP/skills removal'
  2838. assert not (root/'home/.config/agent-notifications/transaction.json').exists()
  2839. after_trees = {'home':after['home'],'profile':after['profile'],'cache':after['cache'],'data':bounded_tree(binding['dataRoot']),
  2840. 'projection':bounded_tree(target)}
  2841. after_ledger = strict_json((pathlib.Path(binding['controlRoot'])/'ownership.json').read_bytes())
  2842. after_policy = strict_json((pathlib.Path(binding['controlRoot'])/'agent-notifications.json').read_bytes())
  2843. expected_hook = base64.b64decode(before['expectedHookBytes'],validate=True)
  2844. assert hashlib.sha256(expected_hook).hexdigest() == before['expectedHookSHA256']
  2845. assert (root/'home/.cursor/hooks.json').read_bytes() == expected_hook, 'actual pure Plan(Remove) remaining bytes'
  2846. classification = classify_removal(root,binding,selected,foreign,before_trees,after_trees,
  2847. [first_phase,restarted],expected_hook,after_public['state'],before['state'],before_ledger,after_ledger,before_policy,after_policy)
  2848. classified_bytes = (json.dumps(classification,indent=2)+'\n').encode()
  2849. assert len(classified_bytes) <= 16*LIMIT, 'full removal evidence file bound'
  2850. (root/'evidence/removal-full-membership.json').write_bytes(classified_bytes)
  2851. check_no_new_effects()
  2852. return restarted
  2853. def validate_installed_effects(root, run, installed, observation, phase, leader, clock, cleanup_signal, cleanup_roles):
  2854. reply = observation.exchange('phase',phase=phase,localLeader=leader,cleanupUsed=clock.cleanup_used,cleanupSignal=cleanup_signal,cleanupRoles=cleanup_roles)
  2855. raw = base64.b64decode(reply['nativeBytes'],validate=True)
  2856. assert hashlib.sha256(raw).hexdigest() == reply['nativeSHA256'], 'actual stream bytes/hash transport'
  2857. facts = captured_stop_bytes(raw)
  2858. assert strict_json(raw).get('cursor_version') == '2026.09.28-64d2043', 'actual source-pinned native version'
  2859. assert facts == reply['facts'] and facts['conversation'] == run['conversation'] and facts['generation'] == run['generation'], 'provider correlation is not byte generation'
  2860. assert facts['status'] == 'completed' and facts['loopCountKnown'] and facts['loopCount'] == 0, 'pinned native completed Stop body'
  2861. path = root/'evidence'/phase/'native-consumed-stdin.json'
  2862. path.write_bytes(raw)
  2863. path.with_suffix('.sha256').write_text(reply['nativeSHA256']+'\n')
  2864. return {'nativeBytes':raw,'facts':facts,'identity':reply['helperIdentity']}
  2865. def native_cwd_allowances(snapshot, root, installed):
  2866. # R189/R14 UID/ns/PID+birth/adoption.
  2867. primary,selector,binding,generation = installed
  2868. target = root/'home/.cursor/plugins/local'/selector.parent.name
  2869. mcp_argv = [str(target/'bin/claude-notifications'),'portable-launch','--locator',selector.name]
  2870. primary_argv = [str(primary),'portable-primary','--locator',selector.name,'--runtime-sha256',AUTHORITY_BASELINE[str(root)]['fixed']['ExecutableDigest'].removeprefix('sha256:')]
  2871. expected = [str(primary),'cursor-event','stop','--binding',str(selector)]
  2872. document = strict_json((root/'home/.cursor/hooks.json').read_bytes())
  2873. entries = [h['command'] for h in document['hooks']['stop'] if shlex.split(h['command']) == expected]
  2874. assert len(entries) == 1 and binding['scopeRoot'] == str(root/'home/.cursor')
  2875. command = entries[0]; allowed = {}
  2876. for row in snapshot['rows']:
  2877. if row.get('cwd') == str(target) and row.get('exe') == mcp_argv[0] and row.get('argv') == mcp_argv:
  2878. p = row['stat']; allowed[(p[0],p[5])] = str(target)
  2879. continue
  2880. if row.get('cwd') != binding['scopeRoot']: continue
  2881. argv = row.get('argv',[])
  2882. fixed_helper = argv == expected
  2883. fixed_shell = (len(argv) == 7 and row.get('exe') == argv[0]
  2884. and argv[0] in ('/usr/bin/bash','/bin/bash') and argv[1:4] == ['-O','extglob','-c']
  2885. and argv[5] == '--' and argv[6] == command
  2886. and hashlib.sha256(argv[4].encode()).hexdigest() ==
  2887. 'f4c3183f20f16337ef8df116657d288385fd88ca5551c69126c63d26969dbc29')
  2888. assert fixed_helper or fixed_shell, 'unqualified native USER cwd/argv'
  2889. p = row['stat']; allowed[(p[0],p[5])] = binding['scopeRoot']
  2890. for row in snapshot['rows']:
  2891. if row.get('cwd') != binding['runtimeRoot'] or row.get('exe') != str(primary) or row.get('argv') != primary_argv: continue
  2892. p = row['stat']; parents = [r['stat'] for r in snapshot['rows'] if r['stat'][0] == p[1]]
  2893. assert len(parents) == 1 and allowed.get((p[1],parents[0][5])) == str(target), 'unqualified portable primary parent'
  2894. allowed[(p[0],p[5])] = binding['runtimeRoot']
  2895. return allowed
  2896. def native_run(root, artifact, installed, phase, clock, observation):
  2897. global w
  2898. native_observation = None
  2899. assert phase in ('enabled-native','disabled-restart')
  2900. observation.exchange('begin-phase',phase=phase)
  2901. assert hashlib.sha256(WIRE_BYTES).hexdigest() == WIRE_SHA
  2902. w = types.ModuleType("accepted_wire")
  2903. exec(compile(WIRE_BYTES, "R14/wire_plan.py", "exec"), w.__dict__)
  2904. evidence = root/'evidence'/phase; evidence.mkdir(mode=0o700)
  2905. condition = threading.Condition(); messages = {}; rows = []
  2906. state = {'seq':0,'run':None,'stopResult':False,'close':False,'sent':False,'terminal':False,
  2907. 'sse':False,'failed':None,'requests':0,'active':0}
  2908. handlers = {}; all_handlers = set(); serve_thread = None
  2909. artifact_pins = list(ARTIFACT_PINS)
  2910. artifact_pins += [{'file':'cursor-agent','sha256':LAUNCHER_SHA}]
  2911. for pin in artifact_pins: assert hashlib.sha256((artifact/pin['file']).read_bytes()).hexdigest() == pin['sha256']
  2912. node_hash = hashlib.sha256((artifact/'node').read_bytes()).hexdigest()
  2913. def auth_refusal_metadata(handler):
  2914. path = handler.path
  2915. unary_operation = None
  2916. if path == '/agent.v1.AgentService/RunSSE': category = 'run-sse'
  2917. elif path == '/aiserver.v1.BidiService/BidiAppend': category = 'bidi-append'
  2918. elif path in w.unary_responses(): category = 'known-unary'; unary_operation = path.rsplit('/',1)[1]
  2919. elif path in REFUSALS: category = 'known-refused'
  2920. elif path == '/aiserver.v1.AnalyticsService/BootstrapStatsig': category = 'analytics-bootstrap'
  2921. else: category = 'other'
  2922. authorization = handler.headers.get('Authorization')
  2923. parts = authorization[:7].split(None,1) if authorization is not None else []
  2924. scheme = parts[0].lower() if parts else ''
  2925. return {'method':'POST','pathCategory':category,'unaryOperation':unary_operation,'authPresent':authorization is not None,
  2926. 'schemeCategory':('absent' if authorization is None else scheme if scheme in ('bearer','basic') else 'other'),
  2927. 'authLength':min(len(authorization),4096) if authorization is not None else 0}
  2928. def fail(e, auth_handler=None):
  2929. with condition:
  2930. first = state['failed'] is None
  2931. state['failed'] = state['failed'] or type(e).__name__ + ':' + str(e)[:240]; condition.notify_all()
  2932. if first:
  2933. try:
  2934. print('native-callback-first-failure',type(e).__name__[:64],source_failure_frames(e,native_run.__code__),file=sys.stderr,flush=True)
  2935. except Exception:
  2936. pass
  2937. if auth_handler is not None:
  2938. try:
  2939. print('native-auth-refusal',auth_refusal_metadata(auth_handler),file=sys.stderr,flush=True)
  2940. except Exception:
  2941. pass
  2942. def capture(q):
  2943. with condition:
  2944. rows.append(q); assert len(json.dumps(rows)) <= LIMIT
  2945. (evidence/'protocol.json').write_text(json.dumps(rows,indent=2))
  2946. def consume(rid,seq,logical):
  2947. with condition:
  2948. assert seq >= state['seq'] and seq not in messages, 'duplicate/old sequence'
  2949. messages[seq] = (rid,logical); assert len(messages) <= 16, 'pending append budget'
  2950. while state['seq'] in messages:
  2951. request,q = messages.pop(state['seq']); state['seq'] += 1
  2952. if state['run'] is not None: assert request == state['run']['requestId'], 'request identity'
  2953. capture({'seq':state['seq']-1,'requestId':request,**q})
  2954. if q['kind'] == 'run':
  2955. assert state['run'] is None; state['run'] = {'requestId':request,**q}
  2956. elif q['kind'] == 'stop-result':
  2957. assert state['sent'] and not state['stopResult'] and not state['close']; state['stopResult'] = True
  2958. elif q['kind'] == 'exec-close':
  2959. assert state['stopResult'] and not state['close']; state['close'] = True
  2960. else: assert q['kind'] == 'heartbeat'
  2961. condition.notify_all()
  2962. class H(http.server.BaseHTTPRequestHandler):
  2963. protocol_version = 'HTTP/1.1'
  2964. def setup(self):
  2965. super().setup(); self.connection.settimeout(clock.wait(35))
  2966. with condition:
  2967. handlers[threading.current_thread()] = self.connection
  2968. all_handlers.add(threading.current_thread())
  2969. if len(handlers) > 72 or len(all_handlers) > 128: fail(RuntimeError('HTTP connection budget'))
  2970. def finish(self):
  2971. try: super().finish()
  2972. finally:
  2973. with condition: handlers.pop(threading.current_thread(),None); condition.notify_all()
  2974. def log_message(self,*a): pass
  2975. def send_error(self,*a,**kw):
  2976. fail(ValueError('HTTP parse/method error')); super().send_error(*a,**kw)
  2977. def answer(self,status,data,typ='application/proto'):
  2978. self.send_response(status); self.send_header('Content-Type',typ); self.send_header('Content-Length',str(len(data)))
  2979. self.end_headers(); self.wfile.write(data); self.wfile.flush()
  2980. def chunk(self,data):
  2981. assert len(data) <= LIMIT+5, 'frame budget'
  2982. self.wfile.write(hex(len(data))[2:].encode()+b'\r\n'+data+b'\r\n'); self.wfile.flush()
  2983. def await_state(self,predicate):
  2984. with condition:
  2985. assert condition.wait_for(lambda:predicate() or state['failed'],clock.wait(25)), 'native acknowledgement timeout'
  2986. assert not state['failed'], state['failed']
  2987. def do_POST(self):
  2988. with condition: state['active'] += 1
  2989. auth_check = False
  2990. try:
  2991. with condition: state['requests'] += 1; assert state['requests'] <= 128
  2992. auth_check = True
  2993. assert self.headers.get('Authorization') == ('Bearer ' + 'TEST-loopback-not-a-secret')
  2994. auth_check = False
  2995. assert self.headers.get('Content-Encoding','identity') in ['identity','gzip']
  2996. assert self.headers.get('Transfer-Encoding','').lower() in ['', 'chunked']
  2997. data = body(self); capture({'path':self.path,'bodyHex':data.hex(),'syntheticAuthMatches':True})
  2998. if self.path in w.unary_responses(): self.answer(200,w.unary_responses()[self.path]); return
  2999. if self.path == '/aiserver.v1.BidiService/BidiAppend':
  3000. rid,seq,msg = append(data); logical = classify(msg)
  3001. self.answer(200,b''); consume(rid,seq,logical); return
  3002. if self.path == '/agent.v1.AgentService/RunSSE':
  3003. with condition: assert not state['sse']; state['sse'] = True
  3004. assert len(data) >= 5 and data[0] in [0,1] and struct.unpack('>I',data[1:5])[0] == len(data)-5
  3005. payload = data[5:]
  3006. if data[0] == 1:
  3007. with gzip.GzipFile(fileobj=io.BytesIO(payload)) as f: payload = f.read(LIMIT+1)
  3008. assert len(payload) <= LIMIT; rid = w.first(payload,1).decode()
  3009. self.send_response(200); self.send_header('Content-Type','application/connect+proto')
  3010. self.send_header('Transfer-Encoding','chunked'); self.end_headers()
  3011. self.await_state(lambda:state['run'] is not None); run = state['run']; assert run['requestId'] == rid
  3012. with condition: state['sent'] = True
  3013. self.chunk(w.stop_frame(run['conversation'],run['generation']))
  3014. capture({'stopSent':True,'conversation':run['conversation'],'generation':run['generation']})
  3015. self.await_state(lambda:state['stopResult'] and state['close'])
  3016. self.chunk(w.text_frame()); self.chunk(w.terminal_frames()); self.wfile.write(b'0\r\n\r\n'); self.wfile.flush()
  3017. with condition: state['terminal'] = True
  3018. capture({'terminalSent':True}); return
  3019. capture({'unsupportedRPC':self.path})
  3020. self.answer(501,b'{"code":"unimplemented","message":"TEST finite allowlist"}','application/json')
  3021. assert self.path in REFUSALS, 'unknown server effects'
  3022. except Exception as e: fail(e,self if auth_check else None)
  3023. finally:
  3024. with condition: state['active'] -= 1; condition.notify_all()
  3025. def do_GET(self):
  3026. fail(ValueError('unsupported HTTP method'))
  3027. self.answer(501,b'{"code":"unimplemented","message":"TEST finite allowlist"}','application/json')
  3028. class Server(http.server.ThreadingHTTPServer):
  3029. daemon_threads = True
  3030. def process_request(self,request,address):
  3031. t = threading.Thread(target=self.process_request_thread,args=(request,address),daemon=True)
  3032. with condition:
  3033. all_handlers.add(t); handlers[t] = request
  3034. if len(handlers) > 72 or len(all_handlers) > 128: fail(RuntimeError('HTTP connection budget'))
  3035. t.start() # register before scheduling; shutdown then joins every created callback thread
  3036. def process_request_thread(self,request,address):
  3037. try:
  3038. with condition:
  3039. if state['failed'] is not None: raise AssertionError(state['failed'])
  3040. tid = threading.get_native_id(); local = trace_task_identity(tid)
  3041. if local['pid'] != tid or local['tgid'] != os.getpid(): raise AssertionError('owned HTTP local thread identity')
  3042. held = {'tid':tid,'birth':local['birth']}
  3043. reply = observation.exchange('controller-thread',phase=phase,thread=held)
  3044. if reply.get('controllerThread') != {**held,'phase':phase}: raise AssertionError('owned HTTP thread ACK identity')
  3045. with condition:
  3046. if state['failed'] is not None: raise AssertionError(state['failed'])
  3047. except Exception as error:
  3048. fail(error)
  3049. try: self.shutdown_request(request)
  3050. finally:
  3051. with condition: handlers.pop(threading.current_thread(),None); condition.notify_all()
  3052. return
  3053. super().process_request_thread(request,address)
  3054. def handle_error(self,*a):
  3055. error = sys.exc_info()[1]
  3056. fail(error if error is not None else RuntimeError('HTTP handler error'))
  3057. server = Server(('127.0.0.1',0),H)
  3058. serve_thread = threading.Thread(target=server.serve_forever,daemon=True)
  3059. env = {'HOME':str(root/'home'),'USER':'TEST','LOGNAME':'TEST','PATH':'/usr/bin:/bin','LANG':'C.UTF-8',
  3060. 'TMPDIR':str(root/'tmp'),'XDG_CACHE_HOME':str(root/'cache'),'AGENT_CLI_CREDENTIAL_STORE':'file',
  3061. 'CURSOR_AUTH_TOKEN':'TEST-loopback-not-a-secret', **SESSION_ENV}
  3062. argv = [str(artifact/'cursor-agent'),'--endpoint','http://127.0.0.1:'+str(server.server_port),
  3063. '--workspace',str(root/'workspace'),'--model','TEST-native-stop',
  3064. '--trust','--print','--output-format','json','TEST deterministic stop mechanics']
  3065. (evidence/'command.json').write_text(json.dumps({'argv':argv,'cwd':str(root/'workspace'),'envKeys':list(env),
  3066. 'network':'new PID+net namespace loopback only','realCredentials':False,'testConsent':CONSENT},indent=2))
  3067. native_before = {'home':bounded_tree(root/'home'),'profile':bounded_tree(root/'home/.cursor'),'cache':bounded_tree(root/'cache')}
  3068. start = time.monotonic(); clock.native_started(); runtime_deadline = clock.work
  3069. birth_floor = int(time.clock_gettime(time.CLOCK_BOOTTIME)*os.sysconf('SC_CLK_TCK'))
  3070. failure = None; clean = False; cleanup_signal = False; natural = False
  3071. namespace = os.readlink('/proc/self/ns/pid'); network = os.readlink('/proc/self/ns/net'); leader = None; roles = []; snapshots = []; cleanup_start = None
  3072. native_seconds = None; cleanup_seconds = None; active_previous = {}; active_checks = 0
  3073. native = subprocess.Popen(argv,cwd=root/'workspace',env=env,stdin=subprocess.DEVNULL,
  3074. stdout=subprocess.PIPE,stderr=subprocess.PIPE,start_new_session=True)
  3075. local_leader = proc_identity(native.pid)
  3076. observation.exchange('leader',phase=phase,localLeader=local_leader,nativeStart=start)
  3077. serve_thread.start() # Bind before responses.
  3078. def observe_active(phase):
  3079. return capture_active(evidence,own_processes(),namespace,phase,active_previous,active_checks,birth_floor)
  3080. def writable_budget():
  3081. assert sum(p.stat().st_size for p in root.rglob('*') if p.is_file()) <= 1024**3, 'writable bytes budget'
  3082. def drain(stream, name):
  3083. size = 0
  3084. try:
  3085. with (evidence/name).open('xb') as f:
  3086. while True:
  3087. b = stream.read1(8192)
  3088. if not b: break
  3089. size += len(b); assert size <= 131072, 'native output budget'; f.write(b)
  3090. except Exception as e: fail(e)
  3091. finally: stream.close()
  3092. pumps = [threading.Thread(target=drain,args=(pipe,name),daemon=True)
  3093. for pipe,name in [(native.stdout,'native.stdout'),(native.stderr,'native.stderr')]]
  3094. for t in pumps: t.start()
  3095. def check_effects():
  3096. nonlocal native_observation
  3097. assert native.returncode == 0 and not state['failed'], 'native exit or protocol failure'
  3098. assert state['run'] and state['sent'] and state['stopResult'] and state['close'] and state['terminal']
  3099. assert state['active'] == 0 and not messages, 'HTTP callback/pending append join'
  3100. if clean:
  3101. native_observation = validate_installed_effects(root,state['run'],installed,observation,phase,local_leader,clock,cleanup_signal,roles)
  3102. assert not any(q['unsupportedRPC'] not in REFUSALS for q in rows if 'unsupportedRPC' in q)
  3103. try:
  3104. observe_active('active')
  3105. leader = next(p for p in own_processes() if p[0] == native.pid)
  3106. assert leader[0] == leader[2] == leader[4], 'native group/session not unique'
  3107. while native.poll() is None:
  3108. snapshot, active_previous = observe_owned_active(evidence,leader,namespace,network,root,active_previous,
  3109. active_checks,birth_floor,runtime_deadline,native,installed)
  3110. assert not state['failed'], state['failed']
  3111. active_checks += 1; writable_budget(); time.sleep(clock.wait(.1))
  3112. native_seconds = time.monotonic()-start
  3113. assert native_seconds <= 90, 'native runtime budget'; natural = native.returncode == 0
  3114. cleanup_start = time.monotonic(); deadline = clock.cleanup_deadline()
  3115. with condition: assert condition.wait_for(lambda:state['active'] == 0 or state['failed'],min(clock.wait(1,cleanup=True),max(0,deadline-time.monotonic())))
  3116. for t in pumps: t.join(timeout=min(clock.wait(1,cleanup=True),max(0,deadline-time.monotonic())))
  3117. assert all(not t.is_alive() for t in pumps), 'native output pump join'
  3118. check_effects(); validate_output(evidence,state['run'])
  3119. observe_cleanup_facts(evidence,namespace,network,root,active_previous,active_checks,birth_floor,deadline)
  3120. # 8s kernel retry.
  3121. procs = own_processes(); snapshots.append({'phase':'before','processes':procs})
  3122. roles = worker_roles(owned_survivors(procs,leader,1,namespace),artifact,root,namespace)
  3123. writable_budget()
  3124. # Observe first.
  3125. cleanup_signal = request_owned_cleanup(own_processes(),leader,1,namespace,deadline)
  3126. clean = join_owned(native,leader,1,namespace,deadline,budget=writable_budget)
  3127. cleanup_seconds = time.monotonic()-cleanup_start
  3128. assert clean, 'owned descendant join timeout'
  3129. snapshots.append({'phase':'after','processes':own_processes()})
  3130. check_effects(); validate_output(evidence,state['run']); writable_budget()
  3131. for pin in artifact_pins: assert hashlib.sha256((artifact/pin['file']).read_bytes()).hexdigest() == pin['sha256']
  3132. assert hashlib.sha256((artifact/'node').read_bytes()).hexdigest() == node_hash, 'vendor node changed'
  3133. except Exception as e:
  3134. failure = type(e).__name__+':'+str(e)[:240]
  3135. try:
  3136. print('native-observation-failure',type(e).__name__[:64],
  3137. 'outerRemaining',round(clock.outer-time.monotonic(),6),
  3138. source_failure_frames(e,native_run.__code__),file=sys.stderr,flush=True)
  3139. except Exception:
  3140. pass
  3141. finally:
  3142. # Fail teardown.
  3143. if serve_thread.ident is not None: server.shutdown()
  3144. server.server_close()
  3145. if cleanup_start is None: cleanup_start = time.monotonic(); deadline = clock.cleanup_deadline()
  3146. if serve_thread.ident is not None: serve_thread.join(timeout=min(clock.wait(1,cleanup=True),max(0,deadline-time.monotonic())))
  3147. with condition: pending_handlers = list(handlers.items())
  3148. for thread,conn in pending_handlers:
  3149. try: conn.shutdown(socket.SHUT_RDWR); conn.close()
  3150. except OSError: pass
  3151. http_deadline = min(deadline,time.monotonic()+clock.wait(1,cleanup=True))
  3152. for thread in all_handlers: thread.join(timeout=max(0,http_deadline-time.monotonic()))
  3153. failure = failure or state['failed']
  3154. if handlers or any(t.is_alive() for t in all_handlers) or serve_thread.is_alive() or state['active'] or messages or any(t.is_alive() for t in pumps):
  3155. failure = failure or 'output/HTTP join incomplete'
  3156. (evidence/'cleanup-process-snapshot.json').write_text(json.dumps({'nativePid':native.pid,'controllerPid':1,
  3157. 'leaderIdentity':leader,'pidNamespace':namespace,'roles':roles,'snapshots':snapshots},indent=2))
  3158. clock.charge_cleanup(cleanup_start)
  3159. result = {'status':'PASS' if failure is None and clean else 'FAIL','failure':failure,
  3160. 'nativeExit':native.returncode,'parentNaturalExit':natural,
  3161. 'ownedGroupSIGTERMRequested':cleanup_signal,'ownedNamespaceDescendantsJoined':clean,
  3162. 'actualNativeRun':state['run'],'nativeStopAck':state['stopResult'],
  3163. 'nativeExecClose':state['close'],'terminalSent':state['terminal'],
  3164. 'entry':'installed-USER','GUIVisibility':'NOT_RUN'}
  3165. (evidence/'result.json').write_text(json.dumps(result,indent=2)+'\n')
  3166. native_after = {'home':bounded_tree(root/'home',vendor_root=root),'profile':bounded_tree(root/'home/.cursor',vendor_root=root),'cache':bounded_tree(root/'cache')}
  3167. boundary_bytes = (json.dumps({'before':native_before,'after':native_after},indent=2)+'\n').encode()
  3168. assert len(boundary_bytes) <= 16*LIMIT, 'full native boundary evidence file bound'
  3169. (evidence/'native-retained-object-boundaries.json').write_bytes(boundary_bytes)
  3170. return {'result':result,'observation':native_observation,'nativeObjectsBefore':native_before,'nativeObjectsAfter':native_after}
  3171. def main(args):
  3172. global CASE_CLOCK, SESSION_ENV, READBACK_INPUTS
  3173. if args.validate:
  3174. compile(HERE.joinpath('native_case.py').read_bytes(), str(HERE/'native_case.py'), 'exec')
  3175. compile(WIRE_BYTES, 'R14/wire_plan.py', 'exec')
  3176. return 0
  3177. assert args.execute and args.inputs, 'select pure --validate or root --execute with real inputs'
  3178. assert args.consent == CONSENT, 'root ONE-case authorization required'
  3179. CASE_CLOCK = CaseClock(args.outer_deadline if args.inside else time.monotonic()+110)
  3180. inputs = execution_inputs(args.inputs, args.inside)
  3181. READBACK_INPUTS = inputs
  3182. require_native_observation_contract(inputs,CASE_CLOCK,args.inside)
  3183. root, artifact = pathlib.Path(inputs['root']), pathlib.Path(inputs['artifact'])
  3184. if not args.inside:
  3185. assert os.geteuid() == 0 and not root.exists()
  3186. qualified_runner(root/'home/.cursor', inputs['machineID'])
  3187. os.umask(0o077)
  3188. root.mkdir(mode=0o700)
  3189. for n in ['home','cache','tmp','workspace','evidence','recipe']:
  3190. (root/n).mkdir(mode=0o700)
  3191. (root/'home/.cursor').mkdir(mode=0o700)
  3192. (root/'recipe/native_case.py').write_bytes((HERE/'native_case.py').read_bytes())
  3193. (root/'recipe/authoritative_readback.go').write_bytes(READBACK_SOURCE_BYTES)
  3194. outer_peer,inner_peer = socket.socketpair(socket.AF_UNIX,socket.SOCK_STREAM)
  3195. command = ['/usr/bin/unshare','--net','--pid','--fork','--mount-proc','--kill-child=KILL',
  3196. '/usr/bin/python3','-B','-S',str(root/'recipe/native_case.py'),'--execute','--inside',
  3197. '--inputs',args.inputs,'--consent',CONSENT,'--old-net',os.readlink('/proc/self/ns/net'),
  3198. '--old-pid',os.readlink('/proc/self/ns/pid'),'--control-fd',str(inner_peer.fileno()),
  3199. '--outer-deadline',str(CASE_CLOCK.outer)]
  3200. subprocess.run(['/usr/bin/chown','-R','1000:1000',str(root)],check=True,timeout=CASE_CLOCK.wait(5))
  3201. with (root/'evidence/harness.stdout').open('xb') as out, (root/'evidence/harness.stderr').open('xb') as err:
  3202. child = subprocess.Popen(command,env={'PATH':'/usr/bin:/bin','HOME':str(root/'home'),'LANG':'C.UTF-8'},
  3203. stdout=out,stderr=err,start_new_session=True,cwd=root/'workspace',pass_fds=(inner_peer.fileno(),))
  3204. inner_peer.close()
  3205. observer = OuterObservation(child,outer_peer,inputs,CASE_CLOCK)
  3206. forced = False
  3207. outer_error = None
  3208. try:
  3209. while child.poll() is None:
  3210. assert time.monotonic() < CASE_CLOCK.outer, 'original outer T0+110 deadline'
  3211. if observer.trace is not None and getattr(observer.trace,'error',None):
  3212. raise observer.trace.first_error or AssertionError(observer.trace.error)
  3213. if observer.session is not None and getattr(observer.session,'error',None):
  3214. raise AssertionError(observer.session.error)
  3215. if observer.closed:
  3216. child.wait(timeout=max(.001,CASE_CLOCK.outer-time.monotonic()))
  3217. break
  3218. if select.select([outer_peer],[],[],min(.05,max(0,CASE_CLOCK.outer-time.monotonic())))[0]:
  3219. observer.request()
  3220. code = child.returncode
  3221. forced = code != 0 or not observer.closed
  3222. except Exception as error:
  3223. outer_error = type(error).__name__+':'+str(error)[:240]
  3224. forced = True
  3225. try:
  3226. print('outer-observation-failure',type(error).__name__[:64],source_failure_frames(error,main.__code__),file=sys.stderr,flush=True)
  3227. except Exception:
  3228. pass
  3229. if child.poll() is None: os.killpg(child.pid,signal.SIGKILL)
  3230. if observer.trace is not None and hasattr(observer.trace,'tracer'):
  3231. observer.trace.force_contain(error)
  3232. child.wait(timeout=max(.001,CASE_CLOCK.outer+5-time.monotonic())); code = 1
  3233. finally:
  3234. outer_peer.close()
  3235. # FAIL samples; no PASS/budget.
  3236. if forced:
  3237. owned = []
  3238. if observer.trace is not None and hasattr(observer.trace,'tracer'):
  3239. owned.append((observer.trace.child,observer.trace.tracer))
  3240. if observer.session is not None:
  3241. owned += [(p['child'],p['identity']) for p in getattr(observer.session,'processes',[])+getattr(observer.session,'control_processes',[])]
  3242. def terminal_owned(process,identity):
  3243. if process.pid != identity['pid']: raise AssertionError('owned cleanup Popen PID drift')
  3244. with (pathlib.Path('/proc')/str(process.pid)/'stat').open('rb') as held_stat: raw = held_stat.read(8193)
  3245. if len(raw) > 8192: raise AssertionError('owned cleanup stat budget')
  3246. text = raw.decode('ascii','strict'); tail = text[text.rindex(')')+2:].split()
  3247. if int(text[:text.index('(')].strip()) != identity['pid'] or int(tail[19]) != identity['birth']: raise AssertionError('owned cleanup birth drift')
  3248. return tail[0] == 'Z'
  3249. for process,identity in owned:
  3250. if process.poll() is None and not terminal_owned(process,identity):
  3251. try:
  3252. if identity.get('startup') is True:
  3253. startup_identity(identity['pid'],identity)
  3254. else:
  3255. proc_identity(identity['pid'],identity)
  3256. except Exception:
  3257. if not terminal_owned(process,identity): raise
  3258. else:
  3259. if process.poll() is None: os.kill(identity['pid'],signal.SIGKILL)
  3260. process.wait(timeout=max(.001,CASE_CLOCK.outer+5-time.monotonic()))
  3261. if observer.trace is not None and hasattr(observer.trace,'tracer'):
  3262. observer.trace.failure_join(CASE_CLOCK.outer+5)
  3263. monitor_worker = getattr(observer.session,'monitor_pump',None)
  3264. if monitor_worker is not None:
  3265. monitor_worker.join(timeout=max(0,CASE_CLOCK.outer+5-time.monotonic()))
  3266. if monitor_worker.is_alive(): outer_error = (outer_error or '')+';monitor drain timeout'
  3267. for t in getattr(observer.session,'pumps',[]):
  3268. t.join(timeout=max(0,CASE_CLOCK.outer+5-time.monotonic()))
  3269. if t.is_alive(): outer_error = (outer_error or '')+';stderr drain timeout'
  3270. if not (root/'evidence/result.json').exists():
  3271. (root/'evidence/result.json').write_text(json.dumps({'status':'FAIL','failure':outer_error or 'isolation/startup before native receipt'}))
  3272. assert time.monotonic() <= CASE_CLOCK.outer+5, 'forced containment maximum T0+115'
  3273. if code != 0 or forced:
  3274. result = strict_json((root/'evidence/result.json').read_text())
  3275. result['status'] = 'FAIL'; result['failure'] = result.get('failure') or outer_error or 'outer namespace containment/join failure'
  3276. (root/'evidence/result.json').write_text(json.dumps(result,indent=2))
  3277. (root/'evidence/namespace-join.json').write_text(json.dumps({'outerExit':code,'namespaceJoined':child.poll() is not None,'forcedContainment':forced}))
  3278. return code if code != 0 else int(forced or strict_json((root/'evidence/result.json').read_bytes()).get('status') != 'PASS')
  3279. assert os.geteuid() == 0 and os.getpid() == 1
  3280. assert os.readlink('/proc/self/ns/net') != args.old_net and os.readlink('/proc/self/ns/pid') != args.old_pid
  3281. subprocess.run(['/usr/sbin/ip','link','set','lo','up'],check=True,timeout=CASE_CLOCK.wait(5))
  3282. assert [q['ifname'] for q in strict_json(subprocess.check_output(['/usr/sbin/ip','-j','link'],timeout=CASE_CLOCK.wait(5)))] == ['lo']
  3283. assert strict_json(subprocess.check_output(['/usr/sbin/ip','-j','route'],timeout=CASE_CLOCK.wait(5))) == []
  3284. assert strict_json(subprocess.check_output(['/usr/sbin/ip','-j','-6','route'],timeout=CASE_CLOCK.wait(5))) == []
  3285. os.setgroups([]); os.setgid(1000); os.setuid(1000); os.umask(0o077)
  3286. assert ctypes.CDLL(None).prctl(36,1,0,0,0) == 0
  3287. # Primary 25264136B; cap N+1.
  3288. assert (pathlib.Path(inputs['stage'])/'claude-notifications-linux-amd64').stat().st_size <= TEST_RUNTIME_FILE_LIMIT, 'runtime copy exceeds fixed per-file cap'
  3289. resource.setrlimit(resource.RLIMIT_CORE,(0,0)); resource.setrlimit(resource.RLIMIT_FSIZE,(TEST_RUNTIME_FILE_LIMIT,TEST_RUNTIME_FILE_LIMIT))
  3290. observation = ControllerObservation(socket.socket(fileno=args.control_fd),CASE_CLOCK)
  3291. server, thread, records, webhook_url = owned_webhook(root)
  3292. try:
  3293. installed, foreign = install_and_confirm(root, artifact, inputs, webhook_url)
  3294. assert own_processes() == [next(p for p in own_processes() if p[0] == 1)], 'setup children unresolved'
  3295. primary,selector,binding,generation = installed
  3296. reply = observation.exchange('prepare',controller=proc_identity(1),primary=str(primary),selector=str(selector),binding=binding,generation=generation)
  3297. SESSION_ENV = reply['environment']
  3298. assert set(SESSION_ENV) == {'DBUS_SESSION_BUS_ADDRESS','DISPLAY','XAUTHORITY'}
  3299. enabled = native_run(root, artifact, installed, 'enabled-native',CASE_CLOCK,observation)
  3300. assert enabled['result']['status'] == 'PASS', enabled['result']['failure']
  3301. restarted = finish_lifecycle(root,artifact,inputs['package'],installed,enabled,observation,CASE_CLOCK,records,foreign)
  3302. assert own_processes() == [next(p for p in own_processes() if p[0] == 1)], 'final native/CLI descendants unresolved'
  3303. closed = observation.exchange('close')
  3304. CASE_CLOCK.cleanup_used = closed['cleanupUsed']
  3305. (root/'evidence/result.json').write_text(json.dumps({'status':'PASS','phases':[enabled['result'],restarted['result']],
  3306. 'entry':'installed-USER','GUIVisibility':'NOT_RUN'},indent=2)+'\n')
  3307. return 0
  3308. finally:
  3309. began = time.monotonic(); deadline = CASE_CLOCK.cleanup_deadline()
  3310. server.shutdown(); server.server_close(); thread.join(timeout=min(1,max(0,deadline-time.monotonic())))
  3311. assert not thread.is_alive(), 'owned webhook join'
  3312. assert not server.case_failures, 'owned webhook failed; do not retry unknown effects'
  3313. CASE_CLOCK.charge_cleanup(began)
  3314. if __name__ == '__main__':
  3315. parser = argparse.ArgumentParser()
  3316. operation = parser.add_mutually_exclusive_group(required=True)
  3317. operation.add_argument('--execute', action='store_true')
  3318. operation.add_argument('--validate', action='store_true')
  3319. parser.add_argument('--inputs')
  3320. parser.add_argument('--consent')
  3321. parser.add_argument('--inside', action='store_true')
  3322. parser.add_argument('--old-net'); parser.add_argument('--old-pid')
  3323. parser.add_argument('--control-fd',type=int); parser.add_argument('--outer-deadline',type=float)
  3324. try:
  3325. sys.exit(main(parser.parse_args()))
  3326. except IncompleteInstalledContract as error:
  3327. print(json.dumps({'status':'INCOMPLETE_INSTALLED_OBSERVATION','nativeE':'NOT_RUN',
  3328. 'reason':str(error)}), file=sys.stderr)
  3329. sys.exit(2)
.github/fixtures/cursor-installed-e/proof-source/native_case.py · Bundled script · 3,710 lines · 1 finding marked
  1. """Goal17 SAME R340 installed USER carrier, under construction; NOT_RUN here.
  2. Source-bound outer observer/session, two planned phases and public readback bridge.
  3. Native/OS/E NOT_RUN. Root build qualification and exact independent review apply.
  4. """
  5. import argparse, ast, base64, ctypes, datetime, gzip, hashlib, http.server, io, json, os, pathlib, re, copy, unicodedata
  6. import platform, resource, shlex, signal, socket, stat, struct, subprocess, sys, threading, time, types, zipfile, tarfile, fcntl, select, termios
  7. HERE = pathlib.Path(__file__).resolve().parent
  8. SOURCE_SHA = '9f014e72af510783d58d00ad3d2db455a2f8117b'
  9. WIRE_SHA = 'c0033c7b5a01b252815e0c9bf0ea47062150a03bc857b71d4a2e9317127b6ea2'
  10. INDEX_SHA = '45d9b1df85d0165cb2e690f96fa5fbe4b59e8a71ddd22176a301ba7e5b18a0b9'
  11. LAUNCHER_SHA = '2ccc9a8e167797641448b5e5c936f006ba137a2555f117f38c5eb76a5238a233'
  12. CURSOR_ARCHIVE_SHA = '6e4cd936a4866b8a77c50ff51a564460d715772fabc477a01aa0f0455d9559f0'
  13. CONSENT = 'TEST-only-public-sdk-stop-and-workspace-trust'
  14. LIMIT = 1048576
  15. TEST_RUNTIME_FILE_LIMIT = 25264137
  16. REFUSALS = ['/aiserver.v1.DashboardService/ListMarketplaces',
  17. '/aiserver.v1.DashboardService/GetCliDownloadUrl',
  18. '/aiserver.v1.DashboardService/GetGlobalCommands', '/aiserver.v1.AnalyticsService/SubmitLogs']
  19. w = None
  20. CASE_CLOCK = None
  21. SESSION_ENV = {}
  22. READBACK_INPUTS = None
  23. AUTHORITY_BASELINE = {}
  24. READBACK_SOURCE_SHA256 = '77030250348f8af0ee99878627b59c39cc7d658974c11adca67f7d98a4d4c8fc'
  25. READBACK_SOURCE_BYTES = base64.b64decode('Ly8gUmVhZC1vbmx5IGJyaWRnZSB0byB0aGUgU0FNRSBwaW5uZWQgcHVibGljIEFQSXMuIFJvb3QgYnVpbGRzIHRoaXMgcGFja2V0IGZpbGUKLy8gaW4gdGhlIGV4YWN0IHNvdXJjZSBtb2R1bGU7IG5vIHByb2R1Y3QgY29tbWFuZCwgaG9vaywgY2FsbGJhY2sgb3IgQUNLIGlzIGFkZGVkLgovLyBUaGlzIHdvcmtlciBkb2VzIG5vdCBidWlsZCBvciBleGVjdXRlIGl0LiBBbGwgbXV0YXRpb25zIHN0YXkgd2l0aCB0aGUgd2l6YXJkLgpwYWNrYWdlIG1haW4KaW1wb3J0ICgKImJ5dGVzIgoiY29udGV4dCIKImNyeXB0by9zaGEyNTYiCiJlbmNvZGluZy9qc29uIgoiZXJyb3JzIgoiZm10IgoiaW8iCiJvcyIKInBhdGgvZmlsZXBhdGgiCiJydW50aW1lL2RlYnVnIgoidGltZSIKImdpdGh1Yi5jb20vNzc3Z2VuaXVzL2FnZW50LW5vdGlmaWNhdGlvbnMvaW50ZXJuYWwvYWdlbnRub3RpZnkvcG9ydGFibGUiCiJnaXRodWIuY29tLzc3N2dlbml1cy9hZ2VudC1ub3RpZmljYXRpb25zL2ludGVybmFsL2NvcGlsb3R2c2NvZGVpbnN0YWxsIgoiZ2l0aHViLmNvbS83NzdnZW5pdXMvYWdlbnQtbm90aWZpY2F0aW9ucy9pbnRlcm5hbC9jdXJzb3JpbnN0YWxsIgoiZ2l0aHViLmNvbS83NzdnZW5pdXMvYWdlbnQtbm90aWZpY2F0aW9ucy9pbnRlcm5hbC9pbnN0YWxscnVudGltZSIKImdpdGh1Yi5jb20vNzc3Z2VuaXVzL3BsdWdpbi1raXQtYWkvaW5zdGFsbC9pbnRlZ3JhdGlvbmN0bC9hZGFwdGVycy9wYXRocG9saWN5IgoiZ2l0aHViLmNvbS83NzdnZW5pdXMvcGx1Z2luLWtpdC1haS9pbnN0YWxsL2ludGVncmF0aW9uY3RsL2FnZW50cGx1Z2lucy9hZGFwdGVycy9uYXRpdmVjb25maWciCiJnaXRodWIuY29tLzc3N2dlbml1cy9wbHVnaW4ta2l0LWFpL2luc3RhbGwvaW50ZWdyYXRpb25jdGwvYWdlbnRwbHVnaW5zL2FkYXB0ZXJzL3Byb2ZpbGVhdXRob3JpdHkiCiJnaXRodWIuY29tLzc3N2dlbml1cy9wbHVnaW4ta2l0LWFpL2luc3RhbGwvaW50ZWdyYXRpb25jdGwvYWdlbnRwbHVnaW5zL2FkYXB0ZXJzL3N0YXRldjIiCiJnaXRodWIuY29tLzc3N2dlbml1cy9wbHVnaW4ta2l0LWFpL2luc3RhbGwvaW50ZWdyYXRpb25jdGwvYWdlbnRwbHVnaW5zL2NsaWVudHMiCiJnaXRodWIuY29tLzc3N2dlbml1cy9wbHVnaW4ta2l0LWFpL2luc3RhbGwvaW50ZWdyYXRpb25jdGwvYWdlbnRwbHVnaW5zL2N1cnNvcmhvb2tzIgoiZ2l0aHViLmNvbS83NzdnZW5pdXMvcGx1Z2luLWtpdC1haS9pbnN0YWxsL2ludGVncmF0aW9uY3RsL2FnZW50cGx1Z2lucy9kb21haW4iCnVhcCAiZ2l0aHViLmNvbS83NzdnZW5pdXMvcGx1Z2luLWtpdC1haS9pbnN0YWxsL2ludGVncmF0aW9uY3RsL2FnZW50cGx1Z2lucy9pbnN0YWxsZXIiCikKLy8gUmVxdWlyZWQgbGRmbGFnOyBoYXNoZWQgZXhhY3QgYnJpZGdlIHNvdXJjZSBpcyBpbmRlcGVuZGVudGx5IGJvdW5kIGJ5IGNhcnJpZXIuCnZhciBwYWNrZXRTb3VyY2VTSEEyNTYgc3RyaW5nCmNvbnN0IHByb2R1Y3RSZXZpc2lvbiA9ICI5ZjAxNGU3MmFmNTEwNzgzZDU4ZDAwYWQzZDJkYjQ1NWEyZjgxMTdiIgp0eXBlIHJlcXVlc3Qgc3RydWN0IHsKCU1vZGUgc3RyaW5nIGBqc29uOiJtb2RlImAKCVNlbGVjdG9yIHN0cmluZyBganNvbjoic2VsZWN0b3IiYAoJQmluZGluZyBwb3J0YWJsZS5CaW5kaW5nIGBqc29uOiJiaW5kaW5nImAKCU9yaWdpbmFsQXV0aG9yaXR5ICpkb21haW4uUHJvZmlsZUF1dGhvcml0eSBganNvbjoib3JpZ2luYWxBdXRob3JpdHkiYAoJT3JpZ2luYWxOYW1lc3BhY2Ugc3RyaW5nIGBqc29uOiJvcmlnaW5hbE5hbWVzcGFjZSJgCglGaXhlZCAqY3Vyc29yaW5zdGFsbC5BdXRob3JpdHkgYGpzb246ImZpeGVkImAKCVRlbXBSb290IHN0cmluZyBganNvbjoidGVtcFJvb3QiYAoJVGltZW91dE1pbGxpcyBpbnQgYGpzb246InRpbWVvdXRNaWxsaXMiYAoJU291cmNlU0hBMjU2IHN0cmluZyBganNvbjoic291cmNlU0hBMjU2ImAKfQpmdW5jIHJlcXVpcmUob2sgYm9vbCwgbWVzc2FnZSBzdHJpbmcpIGVycm9yIHsKCWlmICFvayB7CgkJcmV0dXJuIGVycm9ycy5OZXcobWVzc2FnZSkKCX07CglyZXR1cm4gbmlsCn0KZnVuYyByZWFkYmFjayhyIHJlcXVlc3QpIChtYXBbc3RyaW5nXWFueSxlcnJvcikgewoJaWYgZXJyIDo9IHJlcXVpcmUoci5Tb3VyY2VTSEEyNTYgIT0gIiIgJiYgci5Tb3VyY2VTSEEyNTYgPT0gcGFja2V0U291cmNlU0hBMjU2ICYmIHIuVGltZW91dE1pbGxpcyA+IDAgJiYgci5UaW1lb3V0TWlsbGlzIDw9IDUwMDAsICJwYWNrZXQvZGVhZGxpbmUgYmluZGluZyIpOwoJZXJyICE9IG5pbCB7CgkJcmV0dXJuIG5pbCxlcnIKCX0KCWluZm8sb2s6PWRlYnVnLlJlYWRCdWlsZEluZm8oKTsKCWlmICFvayB7CgkJcmV0dXJuIG5pbCxlcnJvcnMuTmV3KCJidWlsZCBwcm92ZW5hbmNlIG1pc3NpbmciKQoJfQoJcmV2aXNpb24sbW9kaWZpZWQ6PSIiLCIiCglmb3IgXyxzOj1yYW5nZSBpbmZvLlNldHRpbmdzIHsKCQlpZiBzLktleT09InZjcy5yZXZpc2lvbiIgewoJCQlyZXZpc2lvbj1zLlZhbHVlCgkJfTsKCQlpZiBzLktleT09InZjcy5tb2RpZmllZCIgewoJCQltb2RpZmllZD1zLlZhbHVlCgkJfX0KCWlmIGVycjo9cmVxdWlyZShyZXZpc2lvbj09cHJvZHVjdFJldmlzaW9uICYmIG1vZGlmaWVkPT0iZmFsc2UiLCAiZXhhY3QgcHVibGljIGJ1aWxkIHJldmlzaW9uIik7CgllcnIhPW5pbCB7CgkJcmV0dXJuIG5pbCxlcnIKCX0KCWN0eCxjYW5jZWw6PWNvbnRleHQuV2l0aFRpbWVvdXQoY29udGV4dC5CYWNrZ3JvdW5kKCksdGltZS5EdXJhdGlvbihyLlRpbWVvdXRNaWxsaXMpKnRpbWUuTWlsbGlzZWNvbmQpOwoJZGVmZXIgY2FuY2VsKCkKCWI6PXIuQmluZGluZwoJaWYgci5Nb2RlIT0iYWJzZW50IiB7CgkJbGl2ZSxlcnI6PXBvcnRhYmxlLlJlYWRDdXJzb3JCaW5kaW5nKHIuU2VsZWN0b3IpOwoJCWlmIGVyciE9bmlsIHsKCQkJcmV0dXJuIG5pbCxlcnIKCQl9CgkJaWYgYi5WZXJzaW9uIT0wICYmIGxpdmUhPWIgewoJCQlyZXR1cm4gbmlsLGVycm9ycy5OZXcoIm9yaWdpbmFsIHBvcnRhYmxlIGJpbmRpbmcgY2hhbmdlZCIpCgkJfTsKCQliPWxpdmUKCX0KCWlmIGVycjo9cmVxdWlyZShiLkludGVncmF0aW9uPT1wb3J0YWJsZS5DdXJzb3IgJiYgZmlsZXBhdGguSXNBYnMoci5UZW1wUm9vdCkgJiYgZmlsZXBhdGguQ2xlYW4oci5UZW1wUm9vdCk9PXIuVGVtcFJvb3QsImV4cGxpY2l0IEN1cnNvciBsYXlvdXQiKTsKCWVyciE9bmlsIHsKCQlyZXR1cm4gbmlsLGVycgoJfQoJc25hcCxlcnI6PWluc3RhbGxydW50aW1lLlJlYWRJbnN0YWxsZWRTbmFwc2hvdChiLkNvbnRyb2xSb290KTsKCWlmIGVyciE9bmlsIHsKCQlyZXR1cm4gbmlsLGVycgoJfQoJaWYgZXJyPXJlcXVpcmUoIXNuYXAuUmVjb3ZlcnkgJiYgc25hcC5MZWRnZXIuUGVuZGluZ011dGF0aW9uPT1uaWwsInBlbmRpbmcgY29yZSBtdXRhdGlvbi9yZWNvdmVyeSIpOwoJZXJyIT1uaWwgewoJCXJldHVybiBuaWwsZXJyCgl9Cglyb290Oj1maWxlcGF0aC5Kb2luKGZpbGVwYXRoLkRpcihiLkNvbnRyb2xSb290KSwidWFwIikKCWNmZzo9dWFwLkNvbmZpZ3tTdGF0ZVJvb3Q6ZmlsZXBhdGguSm9pbihyb290LCJzdGF0ZSIpLFN0YXRlRmlsZTpmaWxlcGF0aC5Kb2luKHJvb3QsInN0YXRlIiwic3RhdGUtdjIuanNvbiIpLExvY2tGaWxlOmZpbGVwYXRoLkpvaW4ocm9vdCwic3RhdGUiLCJtdXRhdGlvbi5sb2NrIiksT3BlcmF0aW9uc0RpcjpmaWxlcGF0aC5Kb2luKHJvb3QsInN0YXRlIiwib3BlcmF0aW9ucyIpLFBsdWdpbkRhdGFCYXNlOmZpbGVwYXRoLkpvaW4ocm9vdCwicGx1Z2luLWRhdGEiKSxNYW5hZ2VkUm9vdDpmaWxlcGF0aC5Kb2luKHJvb3QsIm1hbmFnZWQiKSxUZW1wUm9vdDpyLlRlbXBSb290LE9wZW5Db2RlUHJvYmVFbnZpcm9ubWVudDpbXXN0cmluZ3siUEFUSD0ifX0KCXN0YXRlLGVycjo9KHN0YXRldjIuU3RvcmV7UGF0aDpjZmcuU3RhdGVGaWxlfSkuTG9hZCgpOwoJaWYgZXJyIT1uaWwgewoJCXJldHVybiBuaWwsZXJyCgl9CglpZiBlcnI9cmVxdWlyZShzdGF0ZS5TY2hlbWFWZXJzaW9uPT1kb21haW4uU3RhdGVTY2hlbWFWZXJzaW9uLCJub25jdXJyZW50IHN0YXRlIHNjaGVtYSIpOwoJZXJyIT1uaWwgewoJCXJldHVybiBuaWwsZXJyCgl9Cgl2YXIgc2VsZWN0ZWQgKmRvbWFpbi5DbGllbnRCaW5kaW5nCglmb3IgXyxpOj1yYW5nZSBzdGF0ZS5JbnN0YWxsYXRpb25zIHsKCQlpZiBpLk5lZWRzUmViaW5kIHsKCQkJcmV0dXJuIG5pbCxlcnJvcnMuTmV3KCJwZW5kaW5nIHJlYmluZCIpCgkJfQoJCWZvciBfLGM6PXJhbmdlIGkuQ2xpZW50cyB7CgkJCWlmIGMuUGVuZGluZ05hdGl2ZUludGVudCE9bmlsIHx8IGMuTmF0aXZlQWN0aXZhdGlvbkF0dGVtcHQhPSIiIHx8IGMuTG9jYWxFbnRyeU9ic2VydmF0aW9uIT1uaWwgewoJCQkJcmV0dXJuIG5pbCxlcnJvcnMuTmV3KCJwZW5kaW5nL3Vua25vd24gbmF0aXZlIHN0YXRlIikKCQkJfQoJCQlpZiBpLkluc3RhbGxhdGlvbklEPT1iLkluc3RhbGxhdGlvbklEICYmIGMuQ2xpZW50QmluZGluZ0lEPT1iLkJpbmRpbmdJRCB7CgkJCQlpZiBzZWxlY3RlZCE9bmlsIHsKCQkJCQlyZXR1cm4gbmlsLGVycm9ycy5OZXcoImR1cGxpY2F0ZSBzZWxlY3RlZCBiaW5kaW5nIikKCQkJCX07CgkJCQl2Oj1jOwoJCQkJc2VsZWN0ZWQ9JnZ9CgkJfQoJfQoJZml4ZWQ6PXIuRml4ZWQKCWlmIHIuTW9kZSE9ImFic2VudCIgewoJCWlmIHNlbGVjdGVkPT1uaWwgfHwgc2VsZWN0ZWQuUHJvZmlsZUF1dGhvcml0eT09bmlsIHsKCQkJcmV0dXJuIG5pbCxlcnJvcnMuTmV3KCJzZWxlY3RlZCBvcmlnaW5hbCB0b2tlbiBtaXNzaW5nIikKCQl9CgkJYzo9KnNlbGVjdGVkCgkJaWYgZXJyPXJlcXVpcmUoYy5Qcm9maWxlTmFtZXNwYWNlPT1jZmcuU3RhdGVSb290ICYmIGMuUHJvZmlsZUF1dGhvcml0eS5GYWN0cygpLkNhbm9uaWNhbFJvb3Q9PWIuU2NvcGVSb290LCJmdWxsIHByb2ZpbGUgbmFtZXNwYWNlL3Jvb3QiKTsKCQllcnIhPW5pbCB7CgkJCXJldHVybiBuaWwsZXJyCgkJfQoJCWlmIHIuT3JpZ2luYWxBdXRob3JpdHkhPW5pbCAmJiAoIXIuT3JpZ2luYWxBdXRob3JpdHkuRXF1YWwoKmMuUHJvZmlsZUF1dGhvcml0eSkgfHwgci5PcmlnaW5hbE5hbWVzcGFjZSE9Yy5Qcm9maWxlTmFtZXNwYWNlKSB7CgkJCXJldHVybiBuaWwsZXJyb3JzLk5ldygib3JpZ2luYWwgZnVsbCB0b2tlbi9uYW1lc3BhY2UgY2hhbmdlZCIpCgkJfQoJCWYsb2s6PWMuU2VsZWN0ZWREZWxpdmVyeS5DdXJzb3JGYWN0cygpOwoJCWlmICFvayB7CgkJCXJldHVybiBuaWwsZXJyb3JzLk5ldygic2VsZWN0ZWQgQ3Vyc29yIHBhY2tldCBtaXNzaW5nIikKCQl9CgkJZXhlY3V0YWJsZSxlOj1wb3J0YWJsZS5SZXNvbHZlUHJpbWFyeUV4ZWN1dGFibGUoc25hcC5MZWRnZXIsYi5QcmltYXJ5KTsKCQlpZiBlIT1uaWwgewoJCQlyZXR1cm4gbmlsLGUKCQl9CgkJYWN0dWFsOj1jdXJzb3JpbnN0YWxsLkF1dGhvcml0eXtQcm9maWxlUm9vdDpmLlByb2ZpbGVSb290LEN1cnNvclZlcnNpb246Zi5DdXJzb3JWZXJzaW9uLFF1YWxpZmljYXRpb25JRDpmLlF1YWxpZmljYXRpb25JRCxFeGVjdXRhYmxlOmV4ZWN1dGFibGUsRXhlY3V0YWJsZURpZ2VzdDoic2hhMjU2OiIrc25hcC5MZWRnZXIuRmlsZXNbZXhlY3V0YWJsZV0uU0hBMjU2LFNlbGVjdG9yOmYuU2VsZWN0b3IsT2JqZWN0SUQ6Zi5PYmplY3RJRH0KCQlpZiBmaXhlZCE9bmlsICYmICpmaXhlZCE9YWN0dWFsIHsKCQkJcmV0dXJuIG5pbCxlcnJvcnMuTmV3KCJvcmlnaW5hbCBmaXhlZCBzZWxlY3Rpb24gY2hhbmdlZCIpCgkJfTsKCQlmaXhlZD0mYWN0dWFsCgkJaWYgZXJyPWIuQ2hlY2tTbmFwc2hvdChzbmFwKTsKCQllcnIhPW5pbCB7CgkJCXJldHVybiBuaWwsZXJyCgkJfQoJfSBlbHNlIHsKCQlpZiBzZWxlY3RlZCE9bmlsIHx8IHIuT3JpZ2luYWxBdXRob3JpdHk9PW5pbCB8fCByLk9yaWdpbmFsTmFtZXNwYWNlIT1jZmcuU3RhdGVSb290IHx8IGZpeGVkPT1uaWwgewoJCQlyZXR1cm4gbmlsLGVycm9ycy5OZXcoInNlbGVjdGVkIGJpbmRpbmcgcmVtYWlucy9hYnNlbnQgb3JpZ2luYWwgYXV0aG9yaXR5IikKCQl9CgkJaWYgZXJyPXByb2ZpbGVhdXRob3JpdHkuUmV2YWxpZGF0ZShjdHgsKnIuT3JpZ2luYWxBdXRob3JpdHkpOwoJCWVyciE9bmlsIHsKCQkJcmV0dXJuIG5pbCxlcnIKCQl9CgkJa2V5LF8sXyxlOj1iLlJlZ2lzdHJhdGlvbigpOwoJCWlmIGUhPW5pbCB7CgkJCXJldHVybiBuaWwsZQoJCX0KCQlpZiBfLG9rOj1zbmFwLkxlZGdlci5Db25zdW1lcnNba2V5XTsKCQlvayB7CgkJCXJldHVybiBuaWwsZXJyb3JzLk5ldygic2VsZWN0ZWQgY29uc3VtZXIgcmVtYWlucyIpCgkJfQoJCWlmIF8sZT1vcy5Mc3RhdChyLlNlbGVjdG9yKTsKCQkhZXJyb3JzLklzKGUsb3MuRXJyTm90RXhpc3QpIHsKCQkJcmV0dXJuIG5pbCxlcnJvcnMuTmV3KCJzZWxlY3RlZCBsb2NhdG9yIHJlbWFpbnMvdW5rbm93biIpCgkJfQoJfQoJYWRhcHRlcixlcnI6PWN1cnNvcmluc3RhbGwuTmV3KG5hdGl2ZWNvbmZpZy5OZXcoKSxwYXRocG9saWN5LlBvbGljeXt9LGZpeGVkKTsKCWlmIGVyciE9bmlsIHsKCQlyZXR1cm4gbmlsLGVycgoJfQoJcmVnaXN0cnksZXJyOj1jbGllbnRzLk5ld1JlZ2lzdHJ5KGFkYXB0ZXIpOwoJaWYgZXJyIT1uaWwgewoJCXJldHVybiBuaWwsZXJyCgl9OwoJY2ZnLlJlZ2lzdHJ5PXJlZ2lzdHJ5CgllbmdpbmUsZXJyOj11YXAuTmV3KGNmZyk7CglpZiBlcnIhPW5pbCB7CgkJcmV0dXJuIG5pbCxlcnIKCX0KCWluc3BlY3Rpb24sZXJyOj1lbmdpbmUuSW5zcGVjdChjdHgpOwoJaWYgZXJyIT1uaWwgewoJCXJldHVybiBuaWwsZXJyCgl9CglyZWNvdmVyeTo9aW5zcGVjdGlvbi5SZWNvdmVyeQoJaWYgcmVjb3ZlcnkuUmVxdWlyZWQgfHwgcmVjb3ZlcnkuUmVhc29uIT0iIiB8fCBsZW4ocmVjb3ZlcnkuSm91cm5hbHMpK2xlbihyZWNvdmVyeS5SZWNlaXB0cykrbGVuKHJlY292ZXJ5Lk5hdGl2ZUludGVudHMpIT0wIHsKCQlyZXR1cm4gbmlsLGVycm9ycy5OZXcoInBlbmRpbmcgcHVibGljIHJlY292ZXJ5IikKCX0KCW91dDo9bWFwW3N0cmluZ11hbnl7InN0YXRlIjpzdGF0ZSwiaW5zcGVjdGlvbiI6aW5zcGVjdGlvbiwiZml4ZWQiOmZpeGVkLCJiaW5kaW5nIjpiLCJtb2RlIjpyLk1vZGUsImJyaWRnZVNvdXJjZVNIQTI1NiI6cGFja2V0U291cmNlU0hBMjU2fQoJaWYgci5Nb2RlIT0iYWJzZW50IiB7CgkJaWYgZXJyPWVuZ2luZS5WZXJpZnlQcm9maWxlQXV0aG9yaXR5KGN0eCxiLkluc3RhbGxhdGlvbklELGIuQmluZGluZ0lEKTsKCQllcnIhPW5pbCB7CgkJCXJldHVybiBuaWwsZXJyCgkJfQoJCWlmIGVycj1wcm9maWxlYXV0aG9yaXR5LlJldmFsaWRhdGUoY3R4LCpzZWxlY3RlZC5Qcm9maWxlQXV0aG9yaXR5KTsKCQllcnIhPW5pbCB7CgkJCXJldHVybiBuaWwsZXJyCgkJfQoJCWlmIHIuT3JpZ2luYWxBdXRob3JpdHkhPW5pbCB7CgkJCWlmIGVycj1wcm9maWxlYXV0aG9yaXR5LlJldmFsaWRhdGUoY3R4LCpyLk9yaWdpbmFsQXV0aG9yaXR5KTsKCQkJZXJyIT1uaWwgewoJCQkJcmV0dXJuIG5pbCxlcnIKCQkJfX0KCQlnYXRlLGU6PWNvcGlsb3R2c2NvZGVpbnN0YWxsLk5ld0N1cnNvckdhdGUoYixjZmcsKmZpeGVkKTsKCQlpZiBlIT1uaWwgewoJCQlyZXR1cm4gbmlsLGUKCQl9CgkJY29uc3VtZXIsZTo9Z2F0ZS5Db25zdW1lckJpbmRpbmcoY3R4KTsKCQlpZiBlIT1uaWwgewoJCQlyZXR1cm4gbmlsLGUKCQl9CgkJZWZmZWN0aXZlLGU6PWdhdGUuRWZmZWN0aXZlQ29uZmlnKGN0eCk7CgkJaWYgZSE9bmlsIHsKCQkJcmV0dXJuIG5pbCxlCgkJfQoJCW91dFsic2VsZWN0ZWQiXT1zZWxlY3RlZDsKCQlvdXRbIm9yaWdpbmFsQXV0aG9yaXR5Il09c2VsZWN0ZWQuUHJvZmlsZUF1dGhvcml0eTsKCQlvdXRbIm9yaWdpbmFsTmFtZXNwYWNlIl09c2VsZWN0ZWQuUHJvZmlsZU5hbWVzcGFjZQoJCW91dFsiY29uc3VtZXJCaW5kaW5nIl09Y29uc3VtZXI7CgkJb3V0WyJjaGFubmVscyJdPWdhdGUuQ2hhbm5lbHMoY3R4LGNvbnN1bWVyKTsKCQlvdXRbImVmZmVjdGl2ZUNvbmZpZyJdPWVmZmVjdGl2ZQoJCWlmIGNvbnN1bWVyLkdlbmVyYXRpb24hPXNuYXAuTGVkZ2VyLkdlbmVyYXRpb24gewoJCQlyZXR1cm4gbmlsLGVycm9ycy5OZXcoImFjdHVhbCBjb21taXR0ZWQgZ2VuZXJhdGlvbiBjaGFuZ2VkIikKCQl9CgkJaWYgci5Nb2RlPT0icmVtb3ZlLXBsYW4iIHsKCQkJdmFyIHJlY2VpcHQgKmN1cnNvcmhvb2tzLlJlY2VpcHQKCQkJZm9yIF8sb2JqZWN0Oj1yYW5nZSBzZWxlY3RlZC5OYXRpdmVPYmplY3RzIHsKCQkJCWlmIG9iamVjdC5LaW5kPT0iY3Vyc29yX3VzZXJfc3RvcCIgewoJCQkJCWlmIHJlY2VpcHQhPW5pbCB7CgkJCQkJCXJldHVybiBuaWwsZXJyb3JzLk5ldygiZHVwbGljYXRlIHN0b3Agb3duZXJzaGlwIikKCQkJCQl9OwoJCQkJCXY6PW9iamVjdC5DdXJzb3JSZWNlaXB0OwoJCQkJCXJlY2VpcHQ9JmN1cnNvcmhvb2tzLlJlY2VpcHR7VmVyc2lvbjp2LlZlcnNpb24sRXZlbnQ6di5FdmVudCxTaGVsbDpjdXJzb3Job29rcy5TaGVsbENvbnRyYWN0KHYuU2hlbGwpLFNwZWM6Y3Vyc29yaG9va3MuSG9va1NwZWN7RXhlY3V0YWJsZTp2LkV4ZWN1dGFibGUsU2VsZWN0b3I6di5TZWxlY3Rvcn0sRW50cnlEaWdlc3Q6di5FbnRyeURpZ2VzdCxSZW1haW5kZXJEaWdlc3Q6di5SZW1haW5kZXJEaWdlc3R9fX0KCQkJaWYgcmVjZWlwdD09bmlsIHsKCQkJCXJldHVybiBuaWwsZXJyb3JzLk5ldygiYWNrbm93bGVkZ2VkIHN0b3Agb3duZXJzaGlwIG1pc3NpbmciKQoJCQl9CgkJCWZpbGUsZTo9bmF0aXZlY29uZmlnLk5ldygpLlJlYWRFeGFjdEZpbGUoZmlsZXBhdGguSm9pbihiLlNjb3BlUm9vdCwiaG9va3MuanNvbiIpKTsKCQkJaWYgZSE9bmlsIHsKCQkJCXJldHVybiBuaWwsZQoJCQl9CgkJCS8vIEV4cG9ydGVkIHB1cmUgUGxhbihSZW1vdmUpIGlzIHRoaXMgc291cmNlJ3MgUGxhblJlbW92ZTsgbmV2ZXIgQXBwbHkvQUNLLgoJCQlwbGFuLGU6PWN1cnNvcmhvb2tzLlBsYW4oY3Vyc29yaG9va3MuUmVxdWVzdHtEb2N1bWVudDpmaWxlLkJvZHksT3BlcmF0aW9uOmN1cnNvcmhvb2tzLlJlbW92ZSxQcmV2aW91czpyZWNlaXB0LFNoZWxsOnJlY2VpcHQuU2hlbGx9KTsKCQkJaWYgZSE9bmlsIHsKCQkJCXJldHVybiBuaWwsZQoJCQl9CgkJCWlmIHBsYW4uQ29uZmxpY3QgfHwgcGxhbi5SZWNlaXB0IT1uaWwgewoJCQkJcmV0dXJuIG5pbCxlcnJvcnMuTmV3KCJ1bnByb3ZlZCBwdXJlIHJlbW92YWwiKQoJCQl9CgkJCW91dFsiZXhwZWN0ZWRIb29rQnl0ZXMiXT1wbGFuLkRlc2lyZWQ7CgkJCW91dFsiZXhwZWN0ZWRIb29rU0hBMjU2Il09Zm10LlNwcmludGYoIiV4IixzaGEyNTYuU3VtMjU2KHBsYW4uRGVzaXJlZCkpCgkJfQoJfQoJaWYgZXJyPWN0eC5FcnIoKTsKCWVyciE9bmlsIHsKCQlyZXR1cm4gbmlsLGVycgoJfTsKCXJldHVybiBvdXQsbmlsCn0KZnVuYyBtYWluKCkgewoJcmF3LGVycjo9aW8uUmVhZEFsbChpby5MaW1pdFJlYWRlcihvcy5TdGRpbiwoMjw8MjApKzEpKTsKCWlmIGVyciE9bmlsIHx8IGxlbihyYXcpPjI8PDIwIHsKCQlmbXQuRnByaW50bG4ob3MuU3RkZXJyLCJib3VuZGVkIHJlcXVlc3QgcmVxdWlyZWQiKTsKCQlvcy5FeGl0KDIpCgl9CglkZWNvZGVyOj1qc29uLk5ld0RlY29kZXIoYnl0ZXMuTmV3UmVhZGVyKHJhdykpOwoJZGVjb2Rlci5EaXNhbGxvd1Vua25vd25GaWVsZHMoKTsKCXZhciByIHJlcXVlc3QKCWlmIGVycj1kZWNvZGVyLkRlY29kZSgmcik7CgllcnI9PW5pbCB7dmFyIGV4dHJhIGFueTsKCQlpZiBlOj1kZWNvZGVyLkRlY29kZSgmZXh0cmEpOwoJCSFlcnJvcnMuSXMoZSxpby5FT0YpIHsKCQkJZXJyPWVycm9ycy5OZXcoInRyYWlsaW5nIHJlcXVlc3QiKQoJCX19CglpZiBlcnI9PW5pbCAmJiByLk1vZGUhPSJsaXZlIiAmJiByLk1vZGUhPSJyZW1vdmUtcGxhbiIgJiYgci5Nb2RlIT0iYWJzZW50IiB7CgkJZXJyPWVycm9ycy5OZXcoInVua25vd24gcmVhZGJhY2sgbW9kZSIpCgl9Cgl2YXIgcmVzdWx0IG1hcFtzdHJpbmddYW55OwoJaWYgZXJyPT1uaWwgewoJCXJlc3VsdCxlcnI9cmVhZGJhY2socikKCX0KCWlmIGVyciE9bmlsIHsKCQlmbXQuRnByaW50bG4ob3MuU3RkZXJyLGVycik7CgkJb3MuRXhpdCgyKQoJfQoJZW5jb2RlZCxlcnI6PWpzb24uTWFyc2hhbChyZXN1bHQpOwoJaWYgZXJyIT1uaWwgfHwgbGVuKGVuY29kZWQpPjE2PDwyMCB7CgkJZm10LkZwcmludGxuKG9zLlN0ZGVyciwiYm91bmRlZCByZWFkYmFjayByZXF1aXJlZCIpOwoJCW9zLkV4aXQoMikKCX0KCWZtdC5QcmludGxuKHN0cmluZyhlbmNvZGVkKSkKfQo=')
    • Dismissed after review: Contains a long base64-looking blob — not necessarily malicious, but worth inspecting what it decodes to
    • Line 25 on GitHub
  26. WIRE_BYTES = b'"""Source-pinned wire recipe only. Does not import vendor code or launch anything.\nCoordinator may import these local helpers into a finite loopback HTTP fixture.\nThis module has no main block, network access, credentials, or native execution.\n"""\nimport struct\n\ndef varint(value):\n assert value >= 0\n result = bytearray()\n while value > 127:\n result.append((value & 127) | 128)\n value >>= 7\n result.append(value)\n return bytes(result)\n\ndef uint(field, value):\n return varint(field << 3) + varint(value)\n\ndef blob(field, value):\n if isinstance(value, str):\n value = value.encode(\'utf-8\')\n return varint((field << 3) | 2) + varint(len(value)) + value\n\ndef frame(payload, flags=0):\n return bytes([flags]) + struct.pack(\'>I\', len(payload)) + payload\n\ndef read_varint(data, at):\n value = 0\n for shift in range(0, 70, 7):\n if at >= len(data):\n raise ValueError(\'truncated varint\')\n byte = data[at]\n at += 1\n value |= (byte & 127) << shift\n if byte < 128:\n return value, at\n raise ValueError(\'oversized varint\')\n\ndef fields(data):\n """Bounded wire scanner; repeated fields remain repeated. No vendor schema eval."""\n if len(data) > 1024 * 1024:\n raise ValueError(\'body budget\')\n at = 0\n result = []\n while at < len(data):\n tag, at = read_varint(data, at)\n number, wire = tag >> 3, tag & 7\n if number == 0:\n raise ValueError(\'zero tag\')\n if wire == 0:\n value, at = read_varint(data, at)\n elif wire == 2:\n size, at = read_varint(data, at)\n value = data[at:at + size]\n at += size\n elif wire in (1, 5):\n size = 8 if wire == 1 else 4\n value = data[at:at + size]\n at += size\n else:\n raise ValueError(\'unsupported wire type\')\n if at > len(data):\n raise ValueError(\'truncated field\')\n result.append((number, wire, value))\n return result\n\ndef first(data, number, default=None):\n return next((value for n, wire, value in fields(data) if n == number), default)\n\ndef model_details(model_id=\'TEST-native-stop\'):\n return b\'\'.join(blob(n, model_id) for n in (1, 3, 4, 5))\n\ndef unary_responses():\n """Only the native HTTP/1.1 Connect/protobuf callsites traced in this audit.\n GetUsableModels/DefaultModel here are AiService paths, despite AgentService\n descriptors also exposing identically named methods.\n """\n return {\n \'/aiserver.v1.ServerConfigService/GetServerConfig\': uint(7, 1),\n \'/aiserver.v1.AiService/GetUsableModels\': blob(1, model_details()),\n \'/aiserver.v1.AiService/GetDefaultModelForCli\': blob(1, model_details()),\n \'/aiserver.v1.AiService/AvailableModels\': b\'\',\n \'/aiserver.v1.DashboardService/GetMe\': blob(1, \'TEST-loopback-identity\') + uint(2, 1),\n \'/aiserver.v1.DashboardService/GetUserPrivacyMode\': b\'\',\n \'/aiserver.v1.DashboardService/GetTeamAdminSettingsOrEmptyIfNotInTeam\': b\'\',\n \'/aiserver.v1.DashboardService/GetEffectiveUserPlugins\': b\'\',\n \'/aiserver.v1.DashboardService/GetManagedSkills\': b\'\',\n }\n\ndef decode_append(body):\n """Input is unframed unary BidiAppendRequest protobuf (decompress first)."""\n request_id = first(first(body, 2), 1).decode()\n sequence = first(body, 3, 0)\n data = first(body, 4) or bytes.fromhex(first(body, 1, b\'\').decode(\'ascii\'))\n return request_id, sequence, data\n\ndef stop_frame(conversation_id, generation_id, model_id=\'TEST-native-stop\'):\n query = (blob(1, \'completed\') + uint(2, 0) + blob(3, conversation_id)\n + (blob(4, generation_id) if generation_id else b\'\')\n + blob(5, model_id) + blob(6, model_id))\n # AgentServerMessage.execServerMessage(2) -> ExecServerMessage:\n # id(1), execId(15), executeHookArgs(27) -> request(1) -> stop(11).\n args = blob(1, blob(11, query))\n message = uint(1, 1) + blob(15, \'TEST-stop-1\') + blob(27, args)\n return frame(blob(2, message))\n\ndef text_frame(text=\'TEST deterministic turn complete\'):\n # AgentServerMessage.interactionUpdate(1) -> textDelta(1) -> text(1).\n return frame(blob(1, blob(1, blob(1, text))))\n\ndef terminal_frames():\n # interactionUpdate(1) -> turnEnded(14), followed by Connect EndStream JSON.\n return frame(blob(1, blob(14, b\'\'))) + frame(b\'{}\', 2)\n\ndef classify_client_message(data):\n run = first(data, 1)\n if run is not None:\n return {\'kind\': \'run\', \'conversation\': first(run, 5, b\'\').decode(),\n \'generation\': first(run, 25, b\'\').decode(),\n \'model\': first(first(run, 3, b\'\'), 1, b\'\').decode()}\n exec_result = first(data, 2)\n if exec_result is not None:\n hook = first(exec_result, 27)\n if hook is None:\n return {\'kind\': \'unexpected-exec-result\'}\n stop_response = first(first(hook, 1, b\'\'), 11)\n return {\'kind\': \'stop-result\', \'id\': first(exec_result, 1, 0),\n \'execId\': first(exec_result, 15, b\'\').decode(),\n \'hasStop\': stop_response is not None,\n \'followup\': first(stop_response or b\'\', 1, b\'\').decode()}\n control = first(data, 5)\n if control is not None:\n if first(control, 2) is not None:\n return {\'kind\': \'exec-throw\'}\n close = first(control, 1)\n return {\'kind\': \'exec-close\', \'id\': first(close, 1, 0)} if close is not None else {\'kind\': \'exec-control\'}\n if first(data, 7) is not None:\n return {\'kind\': \'heartbeat\'}\n return {\'kind\': \'unexpected-client-message\'}\n'
  27. ARTIFACT_PINS = [{'file': 'index.js', 'sha256': '45d9b1df85d0165cb2e690f96fa5fbe4b59e8a71ddd22176a301ba7e5b18a0b9', 'byteLength': 7549229}, {'file': '1538.index.js', 'sha256': '62f61c0b6ccba0f43e79eaf947e33aa33640969050f6459aeec17360aefa1b60', 'byteLength': 5940}, {'file': '4114.index.js', 'sha256': '43386ebdc3a4af020c5398fd020083d8103ef7fbf286970d2d71d3ef9dade9df', 'byteLength': 5699}, {'file': '9725.index.js', 'sha256': '2d2c791377dfe432b3ff1f3173e5218efad7deee76e35a1fc632a577f7fe4440', 'byteLength': 6062}, {'file': 'diff-patch-worker.js', 'sha256': '8de87d1ba7886c6135522679c5d29756afcefb0fe91bdec2023cd42c911a4d0d', 'byteLength': 6646}, {'file': '7450.index.js', 'sha256': '703707729125fa35af87c15c640285d9b90b4a4cd099cfecff0e28c79c8f5f56', 'byteLength': 1341}, {'file': '478.index.js', 'sha256': '663ed1eb66a692521cc7c8bd89ed352ada8ce32da3c8138ca2813958afb9bd00', 'byteLength': 14521}, {'file': '8914.index.js', 'sha256': '0e48ce732c3866c95e3956c52cad892a74a8e7aca9d65090edc6227aad604902', 'byteLength': 671}, {'file': '3541.index.js', 'sha256': '57b1e8de43deb2e3cb8da14522189a21964ff83f915582b20c4073eb03969dc4', 'byteLength': 4469}, {'file': 'unified-diff-worker.js', 'sha256': '0191e7623aab46a080eb5752018aeb209723645558a33203e31d98d419694188', 'byteLength': 6786}, {'file': 'pdf-worker.js', 'sha256': '34cc2e8b9c321799f7d55997c42c8ccc6abc9ea902fd7c7845da5accb136a948', 'byteLength': 480099}, {'file': '5092.index.js', 'sha256': 'cdb601e4e52224c8e36885130c33241a903b87b1f0e1b897b47f1ff79ae66d4e', 'byteLength': 16085}, {'file': '6136.index.js', 'sha256': 'e1000a10d7d6b2b0ad897abcadd43177267d1c18baa907861dd19eb9708eddca', 'byteLength': 97261}, {'file': '8391.index.js', 'sha256': 'bb1f809662186fa081a1e365ce57202797bf44db1f31c071af9edbe56c9ef49a', 'byteLength': 3435}, {'file': '3575.index.js', 'sha256': '3470b1d226b47d6148f4586cabe05aebd77feeafb14d5c854c90483066406da5', 'byteLength': 13815}, {'file': '4760.index.js', 'sha256': 'a08b490045a975d5e86dd849e8b7c3c7c8c2773e27a2e9e4580b68dc425e0485', 'byteLength': 2099}, {'file': '8096.index.js.LICENSE.txt', 'sha256': '806fb10cfb2aed86c6b7b5a179ea01c9c3d736183a3de70ef1e355259bf4b52e', 'byteLength': 2659}, {'file': '3244.index.js', 'sha256': '4566b4210aef42ee023901a74a0318b5e61eb755ffbe6cf52497b67f73e17665', 'byteLength': 899}, {'file': 'cursor-askpass.js', 'sha256': 'ffb6b47c511bdbe2cab68e52ef6e3d37b5bf0ac1e632c78725e30ddb2dbde590', 'byteLength': 5653}, {'file': '8891.index.js', 'sha256': 'b9d93a11a3e4bdad0ddab4e7e5a88d2aba678a0ef42f2bbb5c4a37ff1fa871bc', 'byteLength': 3241578}, {'file': '8644.index.js', 'sha256': 'ec890f0f3073142cba2a6b14541e17f5966b68733a198b6a40be7f60f437fa02', 'byteLength': 7271}, {'file': '3284.index.js', 'sha256': '373a713f8b9f6dad4c2542885905bbb58a7b7c858250628f3088b29649448eaf', 'byteLength': 573}, {'file': '2576.index.js', 'sha256': 'e73fc1ae6529a431ccd5278b39e4cb6bb86fbe0eed6a76684950a2b3611e3717', 'byteLength': 2224}, {'file': '5336.index.js', 'sha256': '7d9543dd6ee0e75c69a18950022cd93031343c29bb8d36f678b5d8b6606a7ce0', 'byteLength': 25190}, {'file': '7923.index.js', 'sha256': 'b5333ad5328c6aa394fd6631822b5caf63a67019c1b9521e861a522ddefbbc4a', 'byteLength': 15734}, {'file': '5818.index.js', 'sha256': 'c94b3f56ed6a8555169088cb186cc2ee0917d7f4412b1921a177817f0df1258e', 'byteLength': 9840}, {'file': '190.index.js', 'sha256': '73c1e9693be17a8b6087d62a11a2159d962371d13c69869f1816a95a1cae547d', 'byteLength': 115505}, {'file': '6918.index.js', 'sha256': 'ba224f3f4d27ca1b5243a75d667b4698543993b379c9551bf9e012317845cad5', 'byteLength': 3587}, {'file': '8096.index.js', 'sha256': '99b2da77d52174213307274bf428c95ca3f7c1216c27630e49c928cfef1b2442', 'byteLength': 2723244}, {'file': '3550.index.js', 'sha256': 'e7636cd64f760f486773640de92cdd11350597e323f1981ce4ac8f401fc00111', 'byteLength': 4849}, {'file': '1429.index.js', 'sha256': '8543b0e5c57f0e33350a64707b341d949432409136ff45b0c97cdf66f6edad29', 'byteLength': 43650}, {'file': '5531.index.js', 'sha256': '3b97993589db91c120031cbb838fb8b32f4b53f611dbb9e954e01b212e2888f3', 'byteLength': 899}, {'file': '2290.index.js', 'sha256': '9f23f7dcfb33f41666f03a4235acfa63a9dbade1889946eca92c31aea3f6096a', 'byteLength': 35299}, {'file': '159.index.js', 'sha256': '66469a19bbe5023910ea7024ecbb54d3985a4a536657b4f4ca2b160b641ef1ac', 'byteLength': 341387}, {'file': '2911.index.js', 'sha256': '863ea507c6237d077c41a5feb5561acca0b95a6d13e3d80e0644ebe9d0ff773c', 'byteLength': 6282}, {'file': '4343.index.js', 'sha256': 'b02e2b0971ed8ea980a1d311fa4b2d314c365daee468944c85328cc126e1298a', 'byteLength': 665}, {'file': '1326.index.js', 'sha256': '24c9f33e87969bf629e8f9ffef267373d120bf55ef8d91375d29cd693399eae7', 'byteLength': 36858}, {'file': '5993.index.js', 'sha256': '25502e95a9b84c20dbf1e4d12daefad5cd162ae9f0fec6c59be8533524dc538f', 'byteLength': 1706}, {'file': '1623.index.js', 'sha256': '6e393636a7898efe8b9a52463682d7cddf211e668334aed58f6864b37eaef60d', 'byteLength': 116131}, {'file': '2721.index.js', 'sha256': '16ba2d3946cb1df6bfad6dbc4d7c974ca697627081ff1834da73a1b4f04c8a15', 'byteLength': 89633}, {'file': '7000.index.js', 'sha256': '749a10b62a2094860d219683b5c5bb36e12c1fb036fcd31e08789f0085b2f5bd', 'byteLength': 981259}, {'file': '6643.index.js', 'sha256': 'c7b9d6d3c3713dc213e81e26b8c5649d28cfbc368ededcc3ec29684e513b9b6e', 'byteLength': 1499}, {'file': '4155.index.js', 'sha256': '1180c477779e5c338b4264b0d671c8c458d4e444188d1e3bd74b5b482f6b5c75', 'byteLength': 9134}, {'file': '9322.index.js', 'sha256': 'ef4157396957372c84013c508e89bed33c20b020185b63ab307cd3929fca9766', 'byteLength': 8866}, {'file': '6536.index.js', 'sha256': 'd777b3cfcc2aa3f42eb0b22cb91480c31482a1c669c6942dc475c89491db9fd3', 'byteLength': 35558}, {'file': 'package.json', 'sha256': '625a6b5d64e45fd989706ab6fd21a95f454d4e70cab7c0c1c151d37582d8bee2', 'byteLength': 64}, {'file': '2761.index.js', 'sha256': 'd3bb797ae5229578f33adbe6413e151ba4ee50c022c054eb6f68a93f47f683d8', 'byteLength': 5825}, {'file': 'pdf-worker.js.LICENSE.txt', 'sha256': 'b5e8c493d516d9b156045ec3b83cc3e26785363af56db22bd52382942b394242', 'byteLength': 795}, {'file': '2422.index.js', 'sha256': 'cc119c5eccfbcf35112697c442c7bfba6670065f8c664a05d5040cce8dfc3528', 'byteLength': 1966}, {'file': '4945.index.js', 'sha256': 'e6b1a2a2d0a7974dd9ad5920483cecbcc1c3c76a9dc1978d11a081cab62e2df6', 'byteLength': 5987}, {'file': '3144.index.js', 'sha256': 'a66c828d56fdb0aee05e2d3023a8a66fe0e058a48b201f03b31d056b8e0cc591', 'byteLength': 793}, {'file': '9106.index.js', 'sha256': '4ce5d0eedcb45448c7a99350864f50122e739aaa9d9ecd12e25babd75dcda55a', 'byteLength': 387131}, {'file': '6174.index.js', 'sha256': '6bddd90df806756c130b3ebf4e74b0062cf0c030e6caa6e6537bf844e86d9496', 'byteLength': 15810}, {'file': '3857.index.js', 'sha256': '2bc55395422ae75b29d2ed5e21881cd12a060c16b5c3e913ea528eb28e117283', 'byteLength': 6881}, {'file': 'mac-webp-runtime.cjs', 'sha256': '4a6041caf835ff53c58caf36e679f65fe6c04722661f315de036ceddd107a770', 'byteLength': 309}, {'file': '3464.index.js', 'sha256': '030e649c6f5550ce08bfd657a9f07802ceecae568603e558e7fdac723cf86188', 'byteLength': 2438}, {'file': '8192.index.js', 'sha256': '06cb735afe2dd4a44d4be16d7e27bf724efbab6158aacb50c6880c4ed4cc50f2', 'byteLength': 70472}, {'file': '4632.index.js', 'sha256': '4600e9ea74d09c839889bc225530f55b9d104c8f4b2608081cd505b266f7c9e8', 'byteLength': 21998}, {'file': '9063.index.js', 'sha256': 'c425976b1aaf6963966103a3d6a7f24fdb9a38a3028daeac0e88f1509356bd95', 'byteLength': 9811}, {'file': '2734.index.js', 'sha256': 'a7c877a8dbaac4d1db3171939f9f7d6f397e9efcdbc2662d35fe0ffc054a56ec', 'byteLength': 26555}, {'file': '272.index.js', 'sha256': 'f996e8b2ec65ca48aaaa5adf9b1cd167c04c32b9a278342ceadafc8bf3a23180', 'byteLength': 6881}, {'file': 'a22718674812ee697cf3.js', 'sha256': 'ba885e166fb261506969fab7703b665d96998e6f995c8c4e8172c696f58574d6', 'byteLength': 2821}, {'file': '7351.index.js', 'sha256': '86745bbc5f2c74890e3cd5358ab4b02b0995db7558c9717abebe66a0beace206', 'byteLength': 1972}, {'file': 'diff-worker.js', 'sha256': 'f8145d47eb97535413a4ae9426c2562801ec0cffa3a4734d3bf444f7a74ca994', 'byteLength': 5945}, {'file': 'index.js.LICENSE.txt', 'sha256': 'ef63fcca608d4374bbfc9d807e32d54d272976a9ea53651471b1ed4f711bcf2b', 'byteLength': 1719}, {'file': '6436.index.js', 'sha256': '592623afe824b6db6b315e0d6a62b0279b75d8d3a4e4b297c3b28a81f08f2f54', 'byteLength': 11976}, {'file': '5740.index.js', 'sha256': 'e902aaa02a8596697eb069f2089767e61a07c168bea26db1143ea160ff7c77f2', 'byteLength': 5657}, {'file': '8991.index.js', 'sha256': 'd9645dfed24e004fe9f0d4e81df707832f2e9f0d3e4c74d7fabfc5f58cc25f3c', 'byteLength': 5435}, {'file': '2601.index.js', 'sha256': 'cf21effd409e730cc29155e5e81b76fef1ce836bfa00a1b1ef498e9065898000', 'byteLength': 14540}, {'file': '9147.index.js', 'sha256': '5fbf0cb6086f7556bf969d015bd6d3c5c209d63edf3256811145bad65716d858', 'byteLength': 340}, {'file': '5380.index.js', 'sha256': '25af69ecff6f7b1e8c12b7138122dbf040eb01144bd1b58a699c1ad75b0ce16e', 'byteLength': 58595}, {'file': '5434.index.js', 'sha256': '94b9bd7a100ac91499c1aaf7af4ec705ab1171ccec5144ace7bd824cb4ba902e', 'byteLength': 1085}, {'file': '7945.index.js', 'sha256': '399ffc412f6d14332bf44b51aa28cff40db56c25974d50fa58adefd468bb3a3b', 'byteLength': 364902}, {'file': '5720.index.js', 'sha256': '48b1bf10573d26f1cef098e5b19e2bd71177e336c1a70fc4edb9aa68991c8e0c', 'byteLength': 2419}, {'file': '5469.index.js', 'sha256': 'bccf3d9433cce7eb2a314835ffd68260158c86d1b5a85ccda7b28661f8c13039', 'byteLength': 336}, {'file': '3190.index.js', 'sha256': 'c6b0007358a0d92c1df1aa7e20c2863f94ba4732ca88334a686799b4fa4ca37e', 'byteLength': 1795}, {'file': '7373.index.js', 'sha256': '95f1e630a2fe054882701d86d447d9da645e9cdfbe25fe45123843f78f7db273', 'byteLength': 12363}, {'file': '6134.index.js', 'sha256': '356de23c9365c444bffe8e3f65982e49f6f3b181ffbfb38938e4aa3d77d1b261', 'byteLength': 7910}, {'file': '1499.index.js', 'sha256': 'c3905ad7c580b8fcc3e559ca316e3e125b7adc7a832c9dff5c7a9f10c41b5728', 'byteLength': 9146}, {'file': '2240.index.js', 'sha256': 'a6a95525446982366afb71c09241a6e7e8f31c0d409458e9928b4cf469d4830c', 'byteLength': 221412}, {'file': '6870.index.js', 'sha256': '8cd41ad250670e7162ce25daeb4b52a04356bd4a609ebf23eda719968e3ce18c', 'byteLength': 234}, {'file': '4161.index.js', 'sha256': '02a3a1a75d7951917815c42bc6e0b08d7f3af47fc0e9c1789fcb9b1c127e2810', 'byteLength': 5594}, {'file': '9494.index.js', 'sha256': '93ae84b5f457e1447331367d90ebc36f89e4d1754fba040e729b2e5ad73e1260', 'byteLength': 47082}, {'file': '7627.index.js', 'sha256': 'aa61aa5788a135dcf95dded5a94ce03f29586d53438e25877340d38260290f35', 'byteLength': 4893}, {'file': '903.index.js', 'sha256': '98537c9b472fb235ee58268a7612b9d86885851074af1274962ec012089d6c8a', 'byteLength': 9590}, {'file': 'node_modules/node-gyp-build/index.js', 'sha256': 'a7ed0d5ae218a19bdbdf15a590d0893790ddf536313b66a787554693cfaae078', 'byteLength': 390}, {'file': 'node_modules/node-gyp-build/build-test.js', 'sha256': '34c19ff8b6675d6d27c63a7df44d77a442805eeea8756d1c89e0264f4a3028f6', 'byteLength': 398}, {'file': 'node_modules/node-gyp-build/optional.js', 'sha256': 'e0b3a3a04166e6ecf1020cb31c0c4a54432c16d6d88714bd4de2214cf67dec81', 'byteLength': 143}, {'file': 'node_modules/node-gyp-build/package.json', 'sha256': '9e8def3fbf123e28aa1ca4b6aa557fba4e66eecf6e86d170b61ec1c7ed51305d', 'byteLength': 1004}, {'file': 'node_modules/node-gyp-build/bin.js', 'sha256': 'dc022adc093b9b79e1a0ef4b6bc3e6a52e3d627102113dad4afacbbe81f13a26', 'byteLength': 2094}, {'file': 'node_modules/node-gyp-build/node-gyp-build.js', 'sha256': '134f0585f7c665db89f332a379158c6f113274422e42aaf54e0aa9d5ac37f577', 'byteLength': 6078}, {'file': 'node_modules/file-uri-to-path/index.js', 'sha256': 'e62293e871bdd5a7449ff3c7956c9536ec1d2ea7369461de77322b5256bb93e7', 'byteLength': 1723}, {'file': 'node_modules/file-uri-to-path/package.json', 'sha256': '71eb1e24bb9694f89c613fa0aa307f977dd43f41d11794c7b48fabf6c55f66b0', 'byteLength': 717}, {'file': 'node_modules/better-sqlite3/package.json', 'sha256': '4665126292eff5dffe6c0ffabf98c4de18e479aa0b53edd775028eb567b3ecc1', 'byteLength': 1436}, {'file': 'node_modules/tree-sitter-bash/grammar.js', 'sha256': 'e1e7ed6840a2a692a1bd5f352ff85b38d065cdca200f95b1288230fb621ff2d7', 'byteLength': 30081}, {'file': 'node_modules/tree-sitter-bash/package.json', 'sha256': 'ee9d6515031266905123792f891fc9c3db75f55c5d9c1e027a315a60a09557c4', 'byteLength': 1616}, {'file': 'node_modules/piscina/package.json', 'sha256': '2a51b866d734d494f814027cbf422db40f8a2f14e8ac1e1b8f5b471f9bb83d52', 'byteLength': 2842}, {'file': 'node_modules/tree-sitter/index.js', 'sha256': 'ba5e8461e5068f2b58ea860aea331ed0c6d8a25f21142d75a6145a1544fc9ffe', 'byteLength': 25716}, {'file': 'node_modules/tree-sitter/package.json', 'sha256': '8cca5044dd3381dbf958dea36ef6d9f81f379886d32ef845919cf07679c6e42c', 'byteLength': 1757}, {'file': 'node_modules/bindings/bindings.js', 'sha256': '8e32a0d37f20bd6f7d5bdbf99d041aa27be47cbbe5172ac13ebf7380a10b3bf6', 'byteLength': 5986}, {'file': 'node_modules/bindings/package.json', 'sha256': 'a87721fe406e1f1798fef44d697b46ea1efe346fda118010334713346ee4207c', 'byteLength': 660}, {'file': 'node_modules/file-uri-to-path/test/tests.json', 'sha256': 'b48c50c1328ab8522fc0bf91923ea42fb59e63e847b967dac88123cb5e5b185d', 'byteLength': 810}, {'file': 'node_modules/file-uri-to-path/test/test.js', 'sha256': '223c25dba6fefbb7cb491b026a32f070b1425475d3cd2d04627be5d71a07fd38', 'byteLength': 666}, {'file': 'node_modules/better-sqlite3/deps/copy.js', 'sha256': '05a2bd41dbd96e33e2fc6cf4bcbc722b4bc8c529813b882f92113d7dbbbece67', 'byteLength': 897}, {'file': 'node_modules/better-sqlite3/lib/index.js', 'sha256': '82db11c4ee43a41d859988c5db42c3771dff565371f94bacbd1e4d8d6ceb47cd', 'byteLength': 110}, {'file': 'node_modules/better-sqlite3/lib/sqlite-error.js', 'sha256': '2582d61c27680dead168543f392eb102be621dfbef282a4ca4c7c21aa5e7c75d', 'byteLength': 717}, {'file': 'node_modules/better-sqlite3/lib/database.js', 'sha256': '02ea23bdd23d7ac5de0675a2f32fc686e76d5c6a32bd3e3891f360e72e07f61f', 'byteLength': 4149}, {'file': 'node_modules/better-sqlite3/lib/util.js', 'sha256': '92b2e39e2151b43a2252e10b6d6de876ecaf0008336a4fa1dfe1317b20f1916f', 'byteLength': 331}, {'file': 'node_modules/better-sqlite3/lib/methods/serialize.js', 'sha256': '7a10ee5c2735384b7f0c361811bc6d017db29f62b203fd3c68a35f667e2c2605', 'byteLength': 625}, {'file': 'node_modules/better-sqlite3/lib/methods/function.js', 'sha256': 'f431d49303b8bbdc044b1f1b455bdad21fc9b74b007de0acb22f08f25b4febd3', 'byteLength': 1396}, {'file': 'node_modules/better-sqlite3/lib/methods/backup.js', 'sha256': 'ea29d34992bb02e006d0fdeda9675ac5d2bb227aaf57468decd997e9fc9c7dbf', 'byteLength': 2380}, {'file': 'node_modules/better-sqlite3/lib/methods/table.js', 'sha256': '97c42d9ded1aa96c7d916b5b92f96b4e59581d50eaf629cd2c7afb78ff26a9ea', 'byteLength': 7144}, {'file': 'node_modules/better-sqlite3/lib/methods/wrappers.js', 'sha256': 'a150a6271d23f4e5f8953b129f370ff096c7cdc4b812afbf080a6cf4ab741bcf', 'byteLength': 1145}, {'file': 'node_modules/better-sqlite3/lib/methods/aggregate.js', 'sha256': 'e9f74eb919ec93fe089c95ddf25a98f1f631c80418fa34fb2346ca1bc29f1b82', 'byteLength': 1932}, {'file': 'node_modules/better-sqlite3/lib/methods/pragma.js', 'sha256': '8b1c54475bd4340b15e25c50d53d06308be65f8f919ecbe4aa9d285ca859ad5a', 'byteLength': 536}, {'file': 'node_modules/better-sqlite3/lib/methods/transaction.js', 'sha256': 'bc8624a3ef689d8f78e5669020ad121e17acbc93b1d5ee5afe26860b1084c66c', 'byteLength': 2792}, {'file': 'node_modules/better-sqlite3/lib/methods/inspect.js', 'sha256': '4975a78daee850adee62ba98719d0f223819a0ec135a07c0e302994bd8dbff61', 'byteLength': 174}, {'file': 'node_modules/tree-sitter-bash/src/node-types.json', 'sha256': '39763582e682b132eb5349af6e1d7be78aed98decf808ffa6bcf92cfed4ac5dc', 'byteLength': 49267}, {'file': 'node_modules/tree-sitter-bash/src/grammar.json', 'sha256': '899dc858b05efefb478dcefc5491b5653e2df5d2aca16292d6def5c0746ac820', 'byteLength': 179302}, {'file': 'node_modules/tree-sitter-bash/bindings/node/index.js', 'sha256': '609bdf22b8fd183025b3c24e8587f6211d50358e8f2e4c526b9217349ed9dbc0', 'byteLength': 201}, {'file': 'node_modules/piscina/benchmark/simple-benchmark-fixed-queue.js', 'sha256': '66ab8b3ee623b26d77460a3aa954890605e3407944654891bf1919d22582ce1a', 'byteLength': 801}, {'file': 'node_modules/piscina/benchmark/simple-benchmark.js', 'sha256': '10ec3fdba4616419d0d6ca8984c3d16db2d65543f19fe539eff08655e3fcc50c', 'byteLength': 743}, {'file': 'node_modules/piscina/benchmark/queue-comparison.js', 'sha256': '0f2a3d44e1f3c64b2cd7223c484b49bafb98a5c8dfd1fe34c6d327ebebc14910', 'byteLength': 758}, {'file': 'node_modules/piscina/benchmark/piscina-queue-comparison.js', 'sha256': '621d25cf2645f11be9df950199e43ab7b46a0f78cc8730f54a6484be8c6298d8', 'byteLength': 1093}, {'file': 'node_modules/piscina/dist/index.js', 'sha256': 'c47bd61dbafa0d5cada595709f0d688666402e8d53968659394fb76579c88b1f', 'byteLength': 33387}, {'file': 'node_modules/piscina/dist/worker.js', 'sha256': '081e85839bad17b8d895bae9e39ebb890933148185a9a547eb11cf4f3b410ceb', 'byteLength': 8248}, {'file': 'node_modules/piscina/dist/abort.js', 'sha256': '96bda77290b59f3f05f054fc67f8dd3c911c5b41615c767653f9c5be1100f181', 'byteLength': 690}, {'file': 'node_modules/piscina/dist/types.js', 'sha256': 'd6a24e27e1b415e8b9a6861d070c599c2fc71a86513c3a1b7d22c96798c9e14f', 'byteLength': 220}, {'file': 'node_modules/piscina/dist/errors.js', 'sha256': '8a1ba396c508b3981573e61d9d7c46c311a50f1a94891e3951b4a8a1e58d488d', 'byteLength': 551}, {'file': 'node_modules/piscina/dist/common.js', 'sha256': '7408b87975c0b2daf9f82f13b201f4e53b6f4a571ab1b4e997cbfe4204690695', 'byteLength': 3159}, {'file': 'node_modules/piscina/dist/main.js', 'sha256': '66553ddfb435a0093214eacb1c44971dc862e896f222ce9251cc6a9a15212bb6', 'byteLength': 272}, {'file': 'node_modules/piscina/dist/symbols.js', 'sha256': 'd0e30b1d318751183ffab01979895bc0fc45f1db6c6db36f83d58f2329f0011a', 'byteLength': 686}, {'file': 'node_modules/piscina/benchmark/fixtures/add.js', 'sha256': '48c3b9da5c294a707f11cfd562fe1092c68d50d52c124ac0f5305d81f874d726', 'byteLength': 52}, {'file': 'node_modules/piscina/dist/task_queue/index.js', 'sha256': 'e0bab14fc4f6e3e84adc1ed9d9190de1cda03af0894c21e7d8697382dd8741df', 'byteLength': 3723}, {'file': 'node_modules/piscina/dist/task_queue/common.js', 'sha256': 'efa0b2439294e1510ac01e9e254e9fbd509834ed9c4fdc73559c6b62f69a8264', 'byteLength': 113}, {'file': 'node_modules/piscina/dist/task_queue/array_queue.js', 'sha256': '29fe6991e3eab05119782880776adac3813e693b6c82ed8cbeab68296dca3921', 'byteLength': 862}, {'file': 'node_modules/piscina/dist/task_queue/fixed_queue.js', 'sha256': '626b1062fcfccd7568a349cd3ca2c0cb224dde65ddd98099d5b618d594c9eb10', 'byteLength': 6594}, {'file': 'node_modules/piscina/dist/worker_pool/index.js', 'sha256': 'b784db251a8f114d3ca0410468d25d05b1889050fbd266425bafc8d59664a867', 'byteLength': 6654}, {'file': 'node_modules/piscina/test/fixtures/send-buffer-then-get-length.js', 'sha256': 'b6646486752c157f6822ad178dea9bbf16c98611404afcaa773afc6ab61410f5', 'byteLength': 313}, {'file': 'node_modules/piscina/test/fixtures/vm.js', 'sha256': 'e1682e3cb237dbc16d19f28c0950d8978858d5b5d8b385997a8c5e963ac2e974', 'byteLength': 164}, {'file': 'node_modules/piscina/test/fixtures/resource-limits.js', 'sha256': '7dfd8f172c3328b7626399e2041a3d2c67a95bd5046a7a781628fa8a8342d7cf', 'byteLength': 109}, {'file': 'node_modules/piscina/test/fixtures/eval.js', 'sha256': 'ad103ef0038cda945182d95f2e8a610b44a1e46ef07771ced2e61b498567331a', 'byteLength': 93}, {'file': 'node_modules/piscina/test/fixtures/send-transferrable-then-get-length.js', 'sha256': 'fa8a63779d65ee6d41f329a948f9e75acb663c1956e0c0e84f1c11caf4985628', 'byteLength': 642}, {'file': 'node_modules/piscina/test/fixtures/eval-async.js', 'sha256': '01ff257a8f50fd0ae46531a7240dead492be9dae82c5cc0dd8537120c8a91cc8', 'byteLength': 267}, {'file': 'node_modules/piscina/test/fixtures/sleep.js', 'sha256': '53133a2a5ef9bd1ece0d0a3ea276cdf598d7cfcb6c295bcec2152819787fedf0', 'byteLength': 277}, {'file': 'node_modules/piscina/test/fixtures/multiple.js', 'sha256': '60c74291d42de9f7310de63c25a21d667ccf6b1dfe46adb87af80b70f4e7fabb', 'byteLength': 116}, {'file': 'node_modules/piscina/test/fixtures/notify-then-sleep-or.js', 'sha256': '1e3baabedf56a7af1cd2d1411334d9fe361bae91b0a87e64ffeb7704415e04bd', 'byteLength': 347}, {'file': 'node_modules/tree-sitter/jest-tests/parse_input.js', 'sha256': 'c822a080455cc0991ed04918a58a57b8ff736c62382155f3d868f27db489e800', 'byteLength': 243}, {'file': 'node_modules/tree-sitter/jest-tests/test3.test.js', 'sha256': 'dd89cb5d72894e26dd0535e326fbfc83582a5161a4b6970b8fa6bc17d117b3f3', 'byteLength': 624}, {'file': 'node_modules/tree-sitter/jest-tests/constants.js', 'sha256': 'da2f35a1728f8c6e376b87a66c9a1fc9f5c466f3103c38c01f43075f6081f138', 'byteLength': 657}, {'file': 'node_modules/tree-sitter/jest-tests/test.test.js', 'sha256': '9fb07c9ff5d3cc31298fd561f4f2f8828e713e0b75cb2208cbe204726c940716', 'byteLength': 5985}, {'file': 'node_modules/tree-sitter/jest-tests/runit.js', 'sha256': '61eabd4d64149552ff42b4f2dfe1827fef16aa104e33e5d18678e2af8852d494', 'byteLength': 298}, {'file': 'node_modules/tree-sitter/jest-tests/test2.test.js', 'sha256': 'ce68dd4056372dafa9617b7472098a3a50a9bbd61bc4792f35642263cc42f528', 'byteLength': 614}, {'file': 'node_modules/tree-sitter/test/lookahead_iterable_test.js', 'sha256': '7091be46ce22a6e76f322742e9b92d792e6916117ee1969fd39f80666db58083', 'byteLength': 1434}, {'file': 'node_modules/tree-sitter/test/parser_test.js', 'sha256': '6e9529e6d2213caf55bf8b8f4ad5293e376aad4759b836b96bcb4a20ad0def9c', 'byteLength': 24623}, {'file': 'node_modules/tree-sitter/test/node_test.js', 'sha256': '7dbf4cf445d47731fb5c7e283e74695ceb1221d5af0db465b7dabd52baf811d4', 'byteLength': 36780}, {'file': 'node_modules/tree-sitter/test/query_test.js', 'sha256': '407aed8a46d381128803ae22ce4e61441373f9a4bc0b4c9c9d61dc0fbb72f851', 'byteLength': 36549}, {'file': 'node_modules/tree-sitter/test/tree_test.js', 'sha256': 'ba487df54014f31dbf5e027bca465d4f891b7bc09943d55dbf686926ea79f838', 'byteLength': 19983}, {'file': 'node_modules/tree-sitter/vendor/tree-sitter/lib/src/wasm/stdlib-symbols.txt', 'sha256': '1162b06514d583b0e94fe9b59ddcc36257f587047cacf7944e87b01722109294', 'byteLength': 253}, {'file': 'node_modules/@jsquash/webp/index.js', 'sha256': '281f1d048db337aaa2412503423b2ca99eeb8ec104b471618ee3845930a27688', 'byteLength': 98}, {'file': 'node_modules/@jsquash/webp/package.json', 'sha256': 'bfd9f9b7ec0d51421623e92185b3b994d6430068de323dacaa1a29b8a1c9c83c', 'byteLength': 978}, {'file': 'node_modules/@jsquash/webp/decode.js', 'sha256': 'b15d9abe76ad4b07214739fe81a99a47f25d01a1e0b0a329a3bec706509cd9e2', 'byteLength': 1432}, {'file': 'node_modules/@jsquash/webp/encode.js', 'sha256': 'edcd883d10e955655946b8fe733bb139faa8b7036092827b1849a4b34d727d6b', 'byteLength': 1946}, {'file': 'node_modules/@jsquash/webp/utils.js', 'sha256': 'e71535eeee820d68b68ece7c8af761c39f3ddec93d3d957d2f83b19191339e0d', 'byteLength': 1272}, {'file': 'node_modules/@jsquash/webp/meta.js', 'sha256': '3d70163a00e6264fc5a8fa7c8f3b1fa21a50a00d910f4d2de3ef1bbd2fdc98ab', 'byteLength': 749}, {'file': 'node_modules/@jsquash/webp/codec/pre.js', 'sha256': 'b4d7da800804a2390eefa7805bb5f4e20cf349681334eb9a1715d2c58a1822b2', 'byteLength': 847}, {'file': 'node_modules/@jsquash/webp/codec/dec/webp_dec.js', 'sha256': 'c57971611f4d9ec04e4636ce7bb4a35c031b24cbdb013518f0a017d9f6014370', 'byteLength': 34823}, {'file': 'node_modules/@jsquash/webp/codec/enc/webp_enc.js', 'sha256': '5fd62301662e37785aec38e38807926f72933d4c8b919018a43faf1b1ca760f6', 'byteLength': 38665}, {'file': 'node_modules/@jsquash/webp/codec/enc/webp_enc_simd.js', 'sha256': '3038e60ebba6252baba08c691e31d1efe5036a185435daa7b4afaef3cc9273f9', 'byteLength': 38646}]
  28. def strict_json(data):
  29. def pairs(values):
  30. result = dict(values); assert len(result) == len(values), 'duplicate JSON key'; return result
  31. return json.loads(data, object_pairs_hook=pairs, parse_constant=lambda _: (_ for _ in ()).throw(ValueError('nonfinite JSON')))
  32. def append(data):
  33. fields = w.fields(data); numbers = [n for n,t,v in fields]
  34. assert len(numbers) == len(set(numbers)) and set(numbers) <= {1,2,3,4}, 'unknown/duplicate append field'
  35. assert 2 in numbers and (1 in numbers) != (4 in numbers), 'ambiguous/missing append payload'
  36. assert all(t == (0 if n == 3 else 2) for n,t,v in fields), 'append wire type'
  37. request = w.first(data,2); assert w.fields(request) == [(1,2,w.first(request,1))], 'append request identity'
  38. rid,seq,msg = w.decode_append(data); assert rid and 0 <= seq <= 127
  39. return rid,seq,msg
  40. def classify(msg):
  41. fields = w.fields(msg); assert len(fields) == 1 and fields[0][1] == 2, 'unknown client envelope'
  42. if fields[0][0] == 5 and [n for n,t,v in w.fields(fields[0][2])] == [3]:
  43. return {'kind': 'heartbeat'} # approved ExecClientControl heartbeat
  44. q = w.classify_client_message(msg)
  45. assert q['kind'] in ['run','stop-result','exec-close','heartbeat'], 'unknown native protocol'
  46. if q['kind'] == 'run':
  47. run = w.first(msg,1)
  48. q['requestedModel'] = w.first(w.first(run,9,b''),1,b'').decode()
  49. q['selectedModel'] = w.first(w.first(run,15,b''),1,b'').decode()
  50. assert q['requestedModel'] == q['selectedModel'] == 'TEST-native-stop'
  51. assert q['conversation'] and q['generation']
  52. if q['kind'] == 'stop-result':
  53. result = w.first(msg,2)
  54. assert len(w.fields(result)) == len({n for n,t,v in w.fields(result)})
  55. assert set(n for n,t,v in w.fields(result)) <= {1,15,27,39}, 'unknown Stop result'
  56. assert all(t == (2 if n in [15,27] else 0) for n,t,v in w.fields(result)), 'Stop result wire type'
  57. assert 0 <= w.first(result,39,0) <= 5000, 'local hook execution time'
  58. hook = w.first(result,27); assert w.fields(hook) == [(1,2,w.first(hook,1))]
  59. response = w.first(hook,1); assert w.fields(response) == [(11,2,b'')], 'nonneutral Stop response'
  60. assert q['id'] == 1 and q['execId'] == '' and q['hasStop'] and not q['followup']
  61. if q['kind'] == 'exec-close':
  62. assert msg == w.blob(5,w.blob(1,w.uint(1,1))), 'unexpected close'
  63. return q
  64. def body(h):
  65. # r5 Connect unary framing.
  66. if h.headers.get('Transfer-Encoding', '').lower() == 'chunked':
  67. data = bytearray()
  68. while True:
  69. size = int(h.rfile.readline(128).split(b';')[0], 16)
  70. if not size:
  71. assert h.rfile.readline(128) == b'\r\n'
  72. break
  73. assert 0 <= size <= LIMIT-len(data)
  74. data.extend(h.rfile.read(size)); assert h.rfile.read(2) == b'\r\n'
  75. data = bytes(data)
  76. else:
  77. size = int(h.headers.get('Content-Length', '0'))
  78. assert 0 <= size <= LIMIT
  79. data = h.rfile.read(size); assert len(data) == size
  80. if h.headers.get('Content-Encoding') == 'gzip':
  81. with gzip.GzipFile(fileobj=io.BytesIO(data)) as f: data = f.read(LIMIT+1)
  82. assert len(data) <= LIMIT
  83. return data
  84. def own_processes():
  85. result = []
  86. for p in pathlib.Path('/proc').glob('[0-9]*/stat'):
  87. try:
  88. fields = p.read_text().rsplit(')', 1)[1].split()
  89. result.append((int(p.parent.name), int(fields[1]), int(fields[2]), int(fields[21])*os.sysconf('SC_PAGE_SIZE'), int(fields[3]), int(fields[19])))
  90. except (FileNotFoundError, ProcessLookupError): pass
  91. return result
  92. def owned_survivors(procs, leader, controller, namespace):
  93. # stat; no names/env.
  94. assert os.getpid() == controller and os.readlink('/proc/self/ns/pid') == namespace
  95. assert any(p[0] == controller for p in procs), 'controller absent from snapshot'
  96. assert leader[0] == leader[2] == leader[4] and leader[0] != os.getpgrp(), 'unique owned group'
  97. children = [p for p in procs if p[0] != controller]
  98. ids = {p[0] for p in children} | {controller, leader[0]}
  99. for p in children:
  100. assert p[2] == p[4] == leader[0] and p[5] >= leader[5], 'unexpected outgroup/identity'
  101. assert p[1] in ids, 'unexpected descendant parent'
  102. if p[0] == leader[0]: assert p[5] == leader[5], 'native leader identity changed'
  103. try: assert os.readlink('/proc/'+str(p[0])+'/ns/pid') == namespace, 'PID namespace changed'
  104. except FileNotFoundError: pass # exited during fresh observation; join still required
  105. assert len(children) <= 65 and sum(p[3] for p in children) <= 4*1024**3, 'native process/RSS budget'
  106. assert len(procs) <= 72 and sum(p[3] for p in procs) <= 5*1024**3, 'owned namespace process/RSS budget'
  107. return children
  108. def request_owned_cleanup(procs, leader, controller, namespace, deadline, sig=signal.SIGTERM):
  109. children = owned_survivors(procs, leader, controller, namespace)
  110. assert time.monotonic() < deadline, 'cleanup deadline'
  111. for p in children:
  112. try:
  113. assert os.getpgid(p[0]) == os.getsid(p[0]) == leader[0], 'fresh group identity'
  114. except ProcessLookupError: continue
  115. assert time.monotonic() < deadline, 'cleanup deadline'
  116. if not children: return False
  117. try: os.killpg(leader[0], sig); return True
  118. except ProcessLookupError: return False
  119. def join_owned(native, leader, controller, namespace, deadline, snapshot=own_processes, budget=lambda: None):
  120. while time.monotonic() < deadline:
  121. native.poll()
  122. try:
  123. while os.waitpid(-1, os.WNOHANG)[0]: pass
  124. except ChildProcessError: pass
  125. children = owned_survivors(snapshot(), leader, controller, namespace); budget()
  126. if not children: return time.monotonic() < deadline
  127. time.sleep(min(.1, max(0, deadline-time.monotonic())))
  128. return False
  129. def cmdline_facts(raw):
  130. args = raw[:8192].decode('utf8','surrogateescape').split('\0')
  131. if args[-1] == '': args.pop()
  132. return {'argv':args, 'cmdlineBytes':len(raw), 'argvOverflow':len(raw)>8192,
  133. 'argvMalformed':bool(raw) and not raw.endswith(b'\0')}
  134. def process_snapshot(procs, namespace):
  135. # Bound facts; no env/auth.
  136. rows = []
  137. for p in procs[:73]:
  138. row = {'stat':p}; proc = pathlib.Path('/proc',str(p[0])); stage = 'cmdline'
  139. try:
  140. with (proc/'cmdline').open('rb') as f: raw = f.read(8193)
  141. row.update(cmdline_facts(raw))
  142. links = {}
  143. for field,link in (('exe','exe'),('cwd','cwd'),('namespace','ns/pid'),('netNamespace','ns/net')):
  144. stage = field
  145. links[field] = os.readlink(proc/link)
  146. row.update(links)
  147. stage = 'status'
  148. with (proc/'status').open() as f: status = f.read(8193)
  149. row['uid'] = next(l for l in status.splitlines() if l.startswith('Uid:')).split()[1:]
  150. stage = 'stat'
  151. with (proc/'stat').open() as f: fields = f.read(8193).rsplit(')',1)[1].split()
  152. row['freshIdentity'] = [int(fields[i]) for i in [1,2,3,19]]
  153. except (OSError,ValueError,StopIteration) as e:
  154. row.update(readFailure=type(e).__name__,refusalStage=stage)
  155. try:
  156. with (proc/'stat').open() as f: raw = f.read(8193)
  157. fields = raw.rsplit(')',1)[1].split()
  158. row['failureStat'] = {'pid':raw.split('(',1)[0].strip()[:32],
  159. 'birth':fields[19][:32],'state':fields[0][:1]}
  160. except (OSError,ValueError,IndexError) as diagnostic_error:
  161. row['failureStatReadFailure'] = type(diagnostic_error).__name__
  162. if len(json.dumps(row).encode()) > 12000:
  163. row = {'stat':p,'readFailure':'ProcessMetadataBudget', **{k:str(row.get(k,''))[:64] for k in ['exe','cwd','namespace','uid']},
  164. 'argv':[a[:64] for a in row.get('argv',[])[:8]]}
  165. rows.append(row)
  166. return {'namespace':namespace,'totalProcesses':len(procs),'totalRSS':sum(p[3] for p in procs),
  167. 'bornUpperTicks':int(time.clock_gettime(time.CLOCK_BOOTTIME)*os.sysconf('SC_CLK_TCK')),
  168. 'netNamespace':os.readlink('/proc/self/ns/net'),'rows':rows}
  169. def capture_active(evidence, procs, namespace, phase, previous, checks, birth_floor):
  170. snapshot = process_snapshot(procs,namespace)
  171. snapshot.update(phase=phase,previous={str(k):v for k,v in previous.items()},checks=checks,
  172. birthFloorTicks=birth_floor,ownershipContract='native-descendants')
  173. raw = json.dumps(snapshot,indent=2); assert len(raw.encode()) <= LIMIT, 'actual snapshot bytes budget'
  174. name = 'active-process-snapshot.json' if phase == 'active' else 'cleanup-actual-process-snapshot.json'
  175. (evidence/name).write_text(raw+'\n'); return snapshot
  176. class ProcessObservationRace(AssertionError): pass
  177. def active_resource_bounds(snapshot):
  178. rows = snapshot['rows']; children = [r for r in rows if r['stat'][0] != 1]
  179. # Bound totals/incomplete; no retry.
  180. assert all(len(r['stat']) == 6 and r['stat'][3] >= 0 for r in rows), 'invalid process RSS'
  181. assert snapshot['totalProcesses'] <= 72 and snapshot['totalRSS'] <= 5*1024**3, 'namespace process/RSS budget'
  182. assert len(children) <= 65 and sum(r['stat'][3] for r in children) <= 4*1024**3, 'descendant process/RSS budget'
  183. assert len(rows) == snapshot['totalProcesses'] and snapshot['totalRSS'] == sum(r['stat'][3] for r in rows), 'incomplete process totals'
  184. def complete_process_facts(snapshot, namespace):
  185. race = None
  186. for row in snapshot['rows']:
  187. p = row['stat']
  188. if 'uid' in row: assert row['uid'] == ['1000']*4, 'foreign UID'
  189. if 'namespace' in row: assert row['namespace'] == namespace, 'foreign PID namespace'
  190. if 'netNamespace' in row: assert row['netNamespace'] == snapshot['netNamespace'], 'foreign network namespace'
  191. assert not row.get('argvOverflow',False) and not row.get('argvMalformed',False), 'overflow/malformed actual cmdline'
  192. if row.get('readFailure') in ['FileNotFoundError','ProcessLookupError']:
  193. race = ProcessObservationRace('process exited during metadata snapshot'); continue
  194. assert 'readFailure' not in row and not row['argvOverflow'], 'incomplete actual process facts'
  195. assert row['uid'] == ['1000']*4 and row['namespace'] == namespace
  196. assert 0 <= row['cmdlineBytes'] <= 8192, 'actual cmdline byte budget'
  197. if row['freshIdentity'] != [p[1],p[2],p[4],p[5]]:
  198. assert row['freshIdentity'][3] == p[5], 'PID reused during metadata snapshot'
  199. race = ProcessObservationRace('process changed during metadata snapshot')
  200. if row['cmdlineBytes'] == 0:
  201. assert row['argv'] == [], 'inconsistent empty actual cmdline'
  202. race = ProcessObservationRace('empty cmdline during metadata snapshot')
  203. if race: raise race
  204. def active_descendants(snapshot, leader, namespace, root, previous, birth_floor, deadline, cwd_allowances=None):
  205. active_resource_bounds(snapshot)
  206. assert time.monotonic() < deadline, 'native runtime budget'
  207. rows = snapshot['rows']; bypid = {r['stat'][0]:r for r in rows}
  208. assert snapshot['namespace'] == namespace and len(bypid) == len(rows), 'foreign namespace/duplicate PID'
  209. assert 1 in bypid and leader[0] == leader[2] == leader[4] > 1, 'unique native leader'
  210. assert birth_floor <= leader[5] <= snapshot['bornUpperTicks'], 'fresh native leader birth'
  211. identities = dict(previous)
  212. for row in rows:
  213. p = row['stat']; old = previous.get(p[0])
  214. assert len(p) == 6 and p[0] > 0 and p[3] >= 0 and p[5] > 0, 'invalid process stat'
  215. assert not old or old['start'] == p[5], 'PID start identity changed'
  216. if 'uid' in row: assert row['uid'] == ['1000']*4, 'foreign UID'
  217. if 'namespace' in row: assert row['namespace'] == namespace, 'foreign PID namespace'
  218. if p[0] != 1:
  219. assert leader[5] <= p[5] <= snapshot['bornUpperTicks'], 'monotonic process birth bound'
  220. if 'cwd' in row: assert row['cwd'] == (cwd_allowances or {}).get((p[0],p[5]),str(root/'workspace')), 'foreign process cwd'
  221. identities[p[0]] = {'start':p[5]}
  222. assert bypid[1]['stat'][1] == 0, 'private namespace controller'
  223. assert leader[0] in bypid, 'native leader missing'
  224. observed = bypid[leader[0]]['stat']
  225. assert observed[1] == 1 and observed[2] == observed[4] == leader[0] and observed[5] == leader[5], 'native leader identity'
  226. for pid in bypid.keys()-{1}:
  227. cursor = pid; visited = set()
  228. while cursor != leader[0]:
  229. assert cursor in bypid and cursor not in visited, 'disconnected/cyclic active ancestry'
  230. visited.add(cursor); p = bypid[cursor]['stat']; parent = p[1]
  231. if parent == 1:
  232. assert previous.get(cursor) == {'start':p[5]}, 'unobserved controller adoption'
  233. break
  234. assert parent in bypid and bypid[parent]['stat'][5] <= p[5], 'foreign/reused active parent'
  235. cursor = parent
  236. complete_process_facts(snapshot,namespace)
  237. return identities # retain validated PID/start pairs across exits and shell/Node execs
  238. def active_namespace(snapshot, network, root):
  239. assert snapshot['netNamespace'] == network, 'controller network namespace changed'
  240. assert all(r['netNamespace'] == network for r in snapshot['rows']), 'foreign network namespace'
  241. assert next(r for r in snapshot['rows'] if r['stat'][0] == 1)['cwd'] == str(root/'workspace'), 'controller TEST cwd'
  242. def record_refusal(evidence, snapshot, error):
  243. raw = (json.dumps({'failure':type(error).__name__+':'+str(error),'snapshot':snapshot})+'\n').encode()
  244. target = evidence/'active-process-refusals.jsonl'
  245. assert len(raw)+(target.stat().st_size if target.exists() else 0) <= 16*LIMIT, 'refusal diagnostics budget'
  246. with target.open('ab') as f: f.write(raw)
  247. def observe_owned_active(evidence, leader, namespace, network, root, previous, checks, birth_floor, deadline, parent, installed=None):
  248. observed_previous = dict(previous)
  249. for attempt in range(32):
  250. snapshot = capture_active(evidence,own_processes(),namespace,'active',observed_previous,checks,birth_floor)
  251. try:
  252. active_resource_bounds(snapshot)
  253. assert time.monotonic() < deadline, 'native runtime budget'
  254. for row in snapshot['rows']:
  255. p = row['stat']; old = observed_previous.get(p[0])
  256. assert not old or old['start'] == p[5], 'PID start identity changed during fresh observations'
  257. if not old: observed_previous[p[0]] = {'start':p[5], 'validated':False}
  258. if parent.poll() is not None: return snapshot, observed_previous # unchanged strict postparent checks
  259. identities = active_descendants(snapshot,leader,namespace,root,observed_previous,birth_floor,deadline, native_cwd_allowances(snapshot,root,installed) if installed else None)
  260. active_namespace(snapshot,network,root)
  261. (evidence/'last-validated-active-process-snapshot.json').write_text(json.dumps(snapshot,indent=2)+'\n')
  262. return snapshot, identities
  263. except Exception as e:
  264. record_refusal(evidence,snapshot,e)
  265. if not isinstance(e,ProcessObservationRace) or attempt == 31: raise
  266. assert time.monotonic() < deadline, 'native runtime budget'
  267. time.sleep(min(.01,max(0,deadline-time.monotonic())))
  268. def observe_cleanup_facts(evidence, namespace, network, root, previous, checks, birth_floor, deadline):
  269. for attempt in range(4):
  270. snapshot = capture_active(evidence,own_processes(),namespace,'after-natural-before-strict-cleanup',previous,checks,birth_floor)
  271. try:
  272. active_resource_bounds(snapshot)
  273. assert time.monotonic() < deadline, 'cleanup deadline'
  274. complete_process_facts(snapshot,namespace); active_namespace(snapshot,network,root)
  275. return snapshot
  276. except Exception as e:
  277. record_refusal(evidence,snapshot,e)
  278. if not isinstance(e,ProcessObservationRace) or attempt == 3: raise
  279. assert time.monotonic() < deadline, 'cleanup deadline'
  280. time.sleep(min(.01,max(0,deadline-time.monotonic())))
  281. def validate_stop(root,run):
  282. evidence = root/'evidence'; record = strict_json((evidence/'native-stop.json').read_text())
  283. assert set(record) == {'event','ctxActive','cwd','home','pid','ppid'}, 'unknown SDK callback output'
  284. event = {'hook_event_name':'stop','status':'completed','conversation_id':run['conversation'],
  285. 'generation_id':run['generation'],'model':'TEST-native-stop','model_id':'TEST-native-stop',
  286. 'workspace_roots':[str(root/'workspace')],'cursor_version':'2026.09.28-64d2043',
  287. 'loop_count':0,'transcript_path':None,'user_email':''}
  288. assert json.dumps(record['event'],sort_keys=True) == json.dumps(event,sort_keys=True) and record['ctxActive'] is True
  289. assert record['home'] == str(root/'home') and record['cwd'] == str(root/'workspace')
  290. facts = strict_json((evidence/'native-fd-facts.json').read_text())
  291. assert record['pid'] == facts['observerPid'] and record['ppid'] == facts['probePid']
  292. for fd in ['0','1','2']:
  293. assert facts[fd]['socket'] and not facts[fd]['pipe'] and facts[fd]['domain'] == 1 and facts[fd]['socketType'] == 1
  294. def validate_output(evidence,run):
  295. output = strict_json((evidence/'native.stdout').read_text())
  296. assert set(output) == {'type','subtype','is_error','result','session_id','request_id','duration_ms','duration_api_ms'}, 'unknown native output'
  297. assert all(type(output[k]) is int and 0 <= output[k] <= 90000 for k in ['duration_ms','duration_api_ms'])
  298. assert output['type'] == 'result' and output['subtype'] == 'success' and output['is_error'] is False
  299. assert output['result'] == 'TEST deterministic turn complete'
  300. assert output['session_id'] == run['conversation'] and output['request_id'] == run['requestId']
  301. assert (evidence/'native.stderr').read_bytes() == b'', 'native stderr'
  302. def worker_roles(children,artifact,root,namespace):
  303. roles = []
  304. for p in children:
  305. try:
  306. proc = pathlib.Path('/proc',str(p[0]))
  307. with (proc/'cmdline').open('rb') as f: raw = f.read(4097)
  308. assert len(raw) <= 4096, 'owned argv budget'
  309. assert raw == b'\0'.join([str(artifact/'node').encode(),str(artifact/'index.js').encode(),b'worker-server',b''])
  310. assert os.readlink(proc/'exe') == str(artifact/'node') and os.readlink(proc/'cwd') == str(root/'workspace')
  311. assert os.readlink(proc/'ns/pid') == namespace
  312. assert next(l for l in (proc/'status').read_text().splitlines() if l.startswith('Uid:')).split()[1:] == ['1000']*4
  313. fresh = next(q for q in own_processes() if q[0] == p[0]); assert fresh[2] == p[2] and fresh[4:] == p[4:], 'fresh worker identity'
  314. roles.append({'pid':p[0],'workerServerArgvMatches':True,'executableIsPinnedNode':True,
  315. 'cwdMatches':True,'uid':1000,'startTicks':p[5],'pgid':p[2],'sid':p[4]})
  316. except (FileNotFoundError,ProcessLookupError,StopIteration):
  317. roles.append({'pid':p[0],'exitedBeforeRoleSnapshot':True})
  318. return roles
  319. class IncompleteInstalledContract(RuntimeError): pass
  320. class CaseClock:
  321. """One outer/work deadline and eight seconds of cumulative joining work."""
  322. def __init__(self, outer_deadline):
  323. self.outer = outer_deadline
  324. self.work = None
  325. self.cleanup_used = 0.0
  326. def native_started(self):
  327. if self.work is None:
  328. self.work = min(time.monotonic()+90, self.outer-8)
  329. self.wait(90)
  330. def wait(self, local_cap, cleanup=False):
  331. end = self.outer if cleanup else min(self.outer-8, self.work or self.outer-8)
  332. remaining = end-time.monotonic()
  333. if cleanup:
  334. remaining = min(remaining, 8-self.cleanup_used)
  335. assert remaining > 0, 'original absolute/cumulative deadline exhausted'
  336. return min(local_cap, remaining)
  337. def cleanup_deadline(self):
  338. return time.monotonic()+self.wait(8, cleanup=True)
  339. def charge_cleanup(self, began):
  340. self.cleanup_used += time.monotonic()-began
  341. assert self.cleanup_used <= 8 and time.monotonic() < self.outer, 'cumulative cleanup allowance'
  342. def startup_identity(pid, expected=None):
  343. """Provisional own-child tuple; never full executable qualification."""
  344. def sample():
  345. raw = (pathlib.Path('/proc')/str(pid)/'stat').read_text()
  346. tail = raw[raw.rindex(')')+2:].split()
  347. return {'pid':int(raw[:raw.index('(')].strip()),'birth':int(tail[19]),
  348. 'ppid':int(tail[1]),'pgid':int(tail[2]),'sid':int(tail[3]),'startup':True}
  349. facts = sample()
  350. assert facts == sample(), 'startup tuple race'
  351. assert facts['pid'] == pid and facts['ppid'] == os.getpid() and facts['pgid'] == facts['sid'] == pid, 'own startup child tuple'
  352. if expected is not None:
  353. assert facts == expected, 'startup tuple changed'
  354. return facts
  355. def proc_identity(pid, expected=None, startup=False, leader_parent=None):
  356. """Ancestor-visible identities; no inferred birth or PID-only ownership."""
  357. p = pathlib.Path('/proc')/str(pid)
  358. raw = (p/'stat').read_text()
  359. tail = raw[raw.rindex(')')+2:].split()
  360. status = {}
  361. for line in (p/'status').read_text().splitlines():
  362. key, sep, value = line.partition(':')
  363. if sep: status[key] = value.strip()
  364. cmdline = (p/'cmdline').read_bytes()
  365. if startup:
  366. assert expected is not None and expected.get('startup') is True, 'startup sample requires retained tuple'
  367. assert int(tail[19]) == expected['birth'] and int(tail[1]) == expected['ppid'] and int(tail[2]) == expected['pgid'] and int(tail[3]) == expected['sid'], 'startup sampled tuple changed'
  368. startup_identity(pid,expected)
  369. if cmdline == b'':
  370. assert tail[0] not in ('Z','X','x'), 'startup process terminal'
  371. return None
  372. immutable = ('pid','birth','ppid','tgid','uids','gids','groups','nspid','tracer','ns','uidMap','gidMap')
  373. if leader_parent is not None and cmdline == b'':
  374. fresh = trace_task_identity(pid)
  375. assert expected is not None and all(fresh[key] == expected[key] for key in immutable), 'leader observation authority drift'
  376. assert tail[0] not in ('Z','X','x') and fresh['ppid'] == leader_parent and fresh['pgid'] == fresh['sid'] == pid, 'leader observation parent/session/terminal'
  377. assert (int(raw[:raw.index('(')].strip()),int(tail[19]),int(tail[1]),int(tail[2]),int(tail[3])) == tuple(fresh[key] for key in ('pid','birth','ppid','pgid','sid')), 'leader observation stat bookend'
  378. assert int(status['Tgid']) == fresh['tgid'] and int(status['TracerPid']) == fresh['tracer'] and all(list(map(int,status[field].split())) == fresh[key] for field,key in (('Uid','uids'),('Gid','gids'),('Groups','groups'),('NSpid','nspid'))), 'leader observation status bookend'
  379. raise ProcessObservationRace('empty selected leader cmdline observation')
  380. if not (0 < len(cmdline) <= 8192 and cmdline.endswith(b'\0')):
  381. try:
  382. print('argv-budget-refusal', {'pid':int(pid), 'cmdlineBytes':len(cmdline),
  383. 'endsNUL':cmdline.endswith(b'\0'), 'state':tail[0][:1], 'birth':tail[19][:32],
  384. 'expectedBirth':str(expected.get('birth',''))[:32] if expected is not None else None},
  385. file=sys.stderr,flush=True)
  386. except Exception:
  387. pass
  388. assert 0 < len(cmdline) <= 8192 and cmdline.endswith(b'\0'), 'actual argv budget'
  389. facts = {'pid':int(pid), 'birth':int(tail[19]), 'ppid':int(tail[1]),
  390. 'pgid':int(tail[2]), 'sid':int(tail[3]), 'tgid':int(status['Tgid']),
  391. 'uids':list(map(int,status['Uid'].split())), 'gids':list(map(int,status['Gid'].split())),
  392. 'groups':list(map(int,status['Groups'].split())), 'nspid':list(map(int,status['NSpid'].split())),
  393. 'tracer':int(status['TracerPid']), 'argv':[v.decode('utf-8','strict') for v in cmdline[:-1].split(b'\0')],
  394. 'exe':os.readlink(p/'exe'), 'cwd':os.readlink(p/'cwd'),
  395. 'ns':{k:os.readlink(p/'ns'/k) for k in ('pid','net','user')},
  396. 'uidMap':(p/'uid_map').read_text(), 'gidMap':(p/'gid_map').read_text()}
  397. assert (p/'stat').read_text().split(') ')[-1].split()[19] == str(facts['birth']), 'birth race'
  398. if expected is not None:
  399. assert facts['pid'] == expected['pid'] and facts['birth'] == expected['birth'], 'PID reuse'
  400. if leader_parent is not None:
  401. assert expected is not None and all(facts[key] == expected[key] for key in immutable), 'leader complete authority drift'
  402. return facts
  403. def trace_task_identity(pid):
  404. """Fresh generic lineage metadata, never selected executable qualification."""
  405. p = pathlib.Path('/proc')/str(pid)
  406. def sample():
  407. raw = (p/'stat').read_text()
  408. tail = raw[raw.rindex(')')+2:].split()
  409. return (int(raw[:raw.index('(')].strip()),int(tail[19]),int(tail[1]),int(tail[2]),int(tail[3])),tail[0]
  410. before,state = sample()
  411. assert before[0] == pid and state not in ('Z','X','x'), 'live trace task required'
  412. status = {}
  413. for line in (p/'status').read_text().splitlines():
  414. key,sep,value = line.partition(':')
  415. if sep: status[key] = value.strip()
  416. facts = {'pid':before[0], 'birth':before[1], 'ppid':before[2],
  417. 'pgid':before[3], 'sid':before[4], 'tgid':int(status['Tgid']),
  418. 'uids':list(map(int,status['Uid'].split())), 'gids':list(map(int,status['Gid'].split())),
  419. 'groups':list(map(int,status['Groups'].split())), 'nspid':list(map(int,status['NSpid'].split())),
  420. 'tracer':int(status['TracerPid']), 'ns':{k:os.readlink(p/'ns'/k) for k in ('pid','net','user')},
  421. 'uidMap':(p/'uid_map').read_text(), 'gidMap':(p/'gid_map').read_text()}
  422. after,state = sample()
  423. assert after == before and state not in ('Z','X','x'), 'trace task metadata race'
  424. return facts
  425. def decoded_hex_string(token):
  426. assert re.fullmatch(r'"(?:\\x[0-9a-fA-F]{2})*"', token), 'abbreviated/unknown strace string'
  427. return bytes.fromhex(token[1:-1].replace('\\x',''))
  428. def captured_stop_bytes(raw):
  429. assert type(raw) is bytes and 0 < len(raw) <= LIMIT, 'native payload budget'
  430. text = raw.decode('utf-8', 'strict')
  431. def pairs(items):
  432. result = {}
  433. for key, value in items:
  434. assert key not in result, 'duplicate native JSON key'
  435. result[key] = value
  436. return result
  437. def constant(value): raise AssertionError('nonfinite JSON number')
  438. value, end = json.JSONDecoder(object_pairs_hook=pairs,parse_constant=constant).raw_decode(text)
  439. assert re.fullmatch(r'[ \t\r\n]*',text[end:]), 'trailing non-JSON native payload bytes'
  440. assert type(value) is dict and value.get('hook_event_name') == 'stop', 'actual Cursor Stop required'
  441. for key in ('conversation_id','generation_id'):
  442. s = value.get(key)
  443. assert type(s) is str and 0 < len(s.encode('utf-8')) <= 256, 'native ID bounds'
  444. assert not any(unicodedata.category(c) == 'Cc' for c in s), 'native ID control character'
  445. assert value.get('status') in ('completed','aborted','error'), 'unknown stopping status'
  446. count = value.get('loop_count')
  447. assert count is None or type(count) is int and 0 <= count <= 2147483647, 'native loop count'
  448. return {'conversation':value['conversation_id'], 'generation':value['generation_id'],
  449. 'status':value['status'], 'loopCountKnown':count is not None, 'loopCount':count or 0}
  450. def stdin_endpoint_facts(link, mode, inode, unix):
  451. """Passive /proc endpoint qualification; Node pipes may be Unix sockets."""
  452. match = re.fullmatch(r'(pipe|socket):\[(\d+)\]',link)
  453. assert match and int(match[2]) == inode, 'stdin endpoint inode/link mismatch'
  454. if match[1] == 'pipe':
  455. assert stat.S_ISFIFO(mode), 'stdin pipe mode mismatch'
  456. return {'kind':'pipe','link':link,'inode':inode,'mode':mode}
  457. assert stat.S_ISSOCK(mode) and len(unix) <= LIMIT, 'stdin socket mode/table bound'
  458. rows = []
  459. for line in unix.decode('ascii','strict').splitlines()[1:]:
  460. fields = line.split(maxsplit=7)
  461. assert len(fields) >= 7, 'unknown Unix socket table row'
  462. if fields[6] == str(inode): rows.append(fields)
  463. assert len(rows) == 1 and rows[0][4] == '0001' and rows[0][5] == '03', 'stdin is not a proven connected AF_UNIX SOCK_STREAM'
  464. return {'kind':'socket','link':link,'inode':inode,'mode':mode,
  465. 'family':'AF_UNIX','type':'SOCK_STREAM','state':'connected'}
  466. def live_stdin_endpoint(tid):
  467. proc = pathlib.Path('/proc')/str(tid)
  468. fd = proc/'fd/0'
  469. link = os.readlink(fd); first = fd.stat()
  470. unix = b''
  471. if link.startswith('socket:'):
  472. with (proc/'net/unix').open('rb') as table: unix = table.read(LIMIT+1)
  473. result = stdin_endpoint_facts(link,first.st_mode,first.st_ino,unix)
  474. last = fd.stat()
  475. assert os.readlink(fd) == link and (first.st_mode,first.st_dev,first.st_ino) == (last.st_mode,last.st_dev,last.st_ino), 'stdin endpoint replacement during qualification'
  476. result['device'] = first.st_dev
  477. return result
  478. class StdinAliasTrace:
  479. """Consume ordinary -xx syscall text. Only selected helper evidence survives.
  480. A task key is (outer TID, actual birth). Shared clone tables have reference
  481. identity; copied tables do not. Exec unshares and removes CLOEXEC descriptors.
  482. No descriptor number is a lineage fact until a selected live exec and dup(0).
  483. """
  484. MAX_STREAM = 512*LIMIT
  485. MAX_LINE = 5*LIMIT # strace's \xHH output expands each byte to four ASCII bytes.
  486. MAX_EVENTS = 1000000
  487. def __init__(self, identity, helper_argv, helper_hash, controller, tracer, root):
  488. self.identity = identity
  489. self.helper_argv = helper_argv
  490. self.helper_hash = helper_hash
  491. self.controller = controller
  492. self.tracer = tracer
  493. self.root = pathlib.Path(root)
  494. self.tasks = {}
  495. self.pending = {}
  496. self.pending_reads = {}
  497. self.acked_fd_entries = {}
  498. self.selected = []
  499. self.total = self.events = 0
  500. self.fragment = b''
  501. self.error = None
  502. self.checkpoints = set()
  503. self.clone_edges = {}
  504. self.remap_history = {}
  505. self.lock = threading.RLock()
  506. self.changed = threading.Condition(self.lock)
  507. def held_clone(self, parent_tid, child_tid, parent_birth, child_birth, raw_flags):
  508. """Admit only the actual paired kernel stops, before either resumes."""
  509. parent = self.register(parent_tid)
  510. assert parent['key'] == (parent_tid,parent_birth), 'held parent birth'
  511. prefix = self.pending.get(parent_tid,'')
  512. assert prefix.startswith(('clone(','clone3(','fork(','vfork(')), 'held clone entry absent'
  513. flags = set(re.findall(r'\bCLONE_[A-Z0-9_]+\b',prefix))
  514. assert ('CLONE_FILES' in flags) == bool(raw_flags & 0x400), 'held CLONE_FILES mismatch'
  515. assert ('CLONE_THREAD' in flags) == bool(raw_flags & 0x10000), 'held CLONE_THREAD mismatch'
  516. fresh = trace_task_identity(child_tid)
  517. assert fresh['birth'] == child_birth, 'held child birth'
  518. outer = self.namespace_child(fresh['nspid'][-1],parent,flags,child_tid)
  519. child = self.tasks[outer]
  520. assert child.get('parent') is None and not child.get('capture'), 'held child already admitted'
  521. for field in ('uids','gids','groups','tracer','ns','uidMap','gidMap'):
  522. assert fresh[field] == parent['facts'][field], 'held child authority/inheritance'
  523. fd_proof = self.clone_fds(parent_tid,child_tid,flags)
  524. child['parent'] = parent['key']
  525. child['fds'] = parent['fds'] if 'CLONE_FILES' in flags else copy.deepcopy(parent['fds'])
  526. capture = parent.get('capture')
  527. if capture: assert {'CLONE_FILES','CLONE_THREAD'} <= flags, 'unexpected selected helper fork/FD unshare'
  528. if 'CLONE_THREAD' in flags: child['capture'] = capture
  529. assert parent['key'] not in self.clone_edges, 'unreconciled clone edge'
  530. self.clone_edges[parent['key']] = {'key':child['key'],'local':fresh['nspid'][-1],
  531. 'flags':flags,'prefix':prefix,'fds':fd_proof}
  532. assert trace_task_identity(parent_tid) == parent['facts'], 'held parent drift'
  533. assert trace_task_identity(child_tid) == fresh, 'held child drift'
  534. for recorded in child.pop('earlyChildCalls',[]): self.line(str(child_tid)+' '+recorded)
  535. def clone_fds(self, parent_tid, child_tid, flags):
  536. assert platform.machine() == 'x86_64', 'qualified Linux clone/table ABI'
  537. libc = ctypes.CDLL(None,use_errno=True)
  538. same_table = libc.syscall(312,parent_tid,child_tid,2,0,0) # Linux/amd64 kcmp(KCMP_FILES).
  539. assert same_table >= 0 and (same_table == 0) == ('CLONE_FILES' in flags), 'actual clone FD table sharing'
  540. def fd_numbers(tid):
  541. values = {int(p.name) for p in (pathlib.Path('/proc')/str(tid)/'fd').iterdir()}
  542. assert len(values) <= 4096, 'held inheritance FD cap'
  543. return values
  544. inherited_fds = fd_numbers(parent_tid)
  545. assert fd_numbers(child_tid) == inherited_fds and set(self.tasks[parent_tid]['fds']) <= inherited_fds, 'held complete FD inheritance'
  546. proof = {}
  547. for fd in inherited_fds:
  548. def endpoint(tid):
  549. entry = pathlib.Path('/proc')/str(tid)/'fd'/str(fd)
  550. before = entry.stat(); link = os.readlink(entry); after = entry.stat()
  551. assert (before.st_dev,before.st_ino,before.st_mode) == (after.st_dev,after.st_ino,after.st_mode), 'inherited fd replacement'
  552. info = (pathlib.Path('/proc')/str(tid)/'fdinfo'/str(fd)).read_text()
  553. flags_at_stop = re.search(r'^flags:\s+([0-7]+)$',info,re.M)
  554. assert flags_at_stop, 'inherited fd flags'
  555. return (link,before.st_dev,before.st_ino,before.st_mode,int(flags_at_stop[1],8))
  556. before = endpoint(parent_tid)
  557. assert endpoint(child_tid) == before == endpoint(parent_tid), 'actual held FD inheritance'
  558. proof[fd] = before
  559. assert fd_numbers(parent_tid) == fd_numbers(child_tid) == inherited_fds, 'inherited FD set drift'
  560. return proof
  561. def task_for_key(self, key):
  562. task = self.tasks.get(key[0])
  563. if task is None or task['key'] != key: task = self.remap_history.get(key)
  564. assert task is not None and task['key'] == key, 'unknown historical task birth'
  565. return task
  566. def exec_remap(self, tid, old_tid):
  567. old = self.tasks[old_tid]; leader = self.tasks[tid]
  568. assert old_tid != tid and old['facts']['tgid'] == tid, 'actual exec TID remap group'
  569. assert not old.get('capture') and not leader.get('capture') and not leader.get('nativeLeader'), 'selected helper/leader unexpected thread exec'
  570. prefix = self.pending.pop(old_tid,'')
  571. assert prefix.startswith(('execve(','execveat(')), 'remap without admitted exec entry'
  572. facts = trace_task_identity(tid)
  573. for field in ('uids','gids','groups','tracer','ns','uidMap','gidMap'):
  574. assert facts[field] == old['facts'][field], 'fresh exec-remap authority'
  575. assert facts['tgid'] == tid and facts['nspid'] == leader['facts']['nspid'] and facts['ppid'] == leader['facts']['ppid'], 'fresh exec-remap local/parent mapping'
  576. for task in (old,leader): self.remap_history[task['key']] = dict(task)
  577. remapped = dict(old,key=(tid,facts['birth']),facts=facts,parent=leader['parent'])
  578. remapped.pop('exited',None)
  579. remapped['execRemap'] = {'old':old['key'],'superseded':leader['key'],'fresh':remapped['key']}
  580. old['exited'] = True
  581. leader['exited'] = True
  582. leader['supersededPending'] = self.pending.pop(tid,None)
  583. assert tid not in self.pending_reads, 'exec remap cannot cancel selected read custody'
  584. self.tasks[tid] = remapped
  585. self.pending[tid] = prefix
  586. assert trace_task_identity(tid) == facts, 'exec-remap bookend'
  587. def bus_fd(self, tid, fd, connected=False):
  588. proc = pathlib.Path('/proc')/str(tid)
  589. entry = proc/'fd'/str(fd)
  590. link = os.readlink(entry); before = entry.stat()
  591. match = re.fullmatch(r'socket:\[(\d+)\]',link)
  592. assert match and stat.S_ISSOCK(before.st_mode) and int(match[1]) == before.st_ino, 'actual bus socket fd'
  593. with (proc/'net/unix').open('rb') as table: raw = table.read(LIMIT+1)
  594. assert len(raw) <= LIMIT, 'bus socket table cap'
  595. rows = [row.split() for row in raw.decode('ascii').splitlines()[1:]]
  596. rows = [row for row in rows if len(row) >= 7 and row[6] == str(before.st_ino)]
  597. assert len(rows) == 1 and rows[0][4] == '0001', 'fresh AF_UNIX stream socket'
  598. if connected: assert rows[0][5] == '03', 'tracked bus socket is not freshly connected'
  599. after = entry.stat()
  600. assert os.readlink(entry) == link and (before.st_dev,before.st_ino,before.st_mode) == (after.st_dev,after.st_ino,after.st_mode), 'bus fd replacement'
  601. return (before.st_dev,before.st_ino)
  602. def held_entry(self, task, name, arguments, session):
  603. """Closed connect intent and destruction; existing FD ledger is authority."""
  604. capture = task.get('capture')
  605. if not capture:
  606. assert not any(value.get('bus') for value in task['fds'].values()), 'unselected table cannot own watched socket authority'
  607. return None
  608. self.register(task['key'][0])
  609. prefix = self.pending.get(task['key'][0],'')
  610. assert prefix.startswith(name+'('), 'held entry lacks its actual decoded prefix'
  611. unsupported = ('unshare','setns','pidfd_getfd','io_uring_setup','io_uring_enter','io_uring_register',
  612. 'setuid','setgid','setreuid','setregid','setresuid','setresgid','setgroups','capset')
  613. assert name not in unsupported and name not in ('execve','execveat'), 'selected descriptor/identity bypass'
  614. connections = capture.setdefault('busConnections',[])
  615. if name == 'connect' and 'sa_family=AF_UNIX' in prefix:
  616. match = re.search(r'sun_path=("(?:\\x[0-9a-fA-F]{2})*")',prefix)
  617. assert match, 'complete real AF_UNIX connect address'
  618. address = decoded_hex_string(match[1])
  619. assert address == str(session.directory/'bus').encode(), 'selected AF_UNIX connect outside owned bus address'
  620. session.assert_continuous()
  621. assert not connections, 'multiple/ambiguous selected bus connections'
  622. fd = arguments[0]
  623. slot = task['fds'].get(fd)
  624. assert slot is not None and not slot.get('lineage'), 'connect fd has no admitted socket lineage'
  625. conn = {'owner':capture['identity'],'intent':task['key'],'fd':fd,
  626. 'socket':self.bus_fd(task['key'][0],fd),'tables':[task['fds']],
  627. 'connected':False,'outcome':None,'acked':False,'name':None}
  628. slot['bus'] = conn
  629. connections.append(conn) # Watching exists BEFORE connect can execute.
  630. return None
  631. if not connections: return None
  632. assert len(connections) == 1, 'one selected socket incarnation'
  633. conn = connections[0]; table = task['fds']
  634. assert any(table is known for known in conn['tables']), 'unknown bus FD table incarnation'
  635. aliases = [fd for fd,value in table.items() if value.get('bus') is conn]
  636. for fd in aliases: assert self.bus_fd(task['key'][0],fd,conn['connected']) == conn['socket'], 'tracked bus fd reused'
  637. entries = list((pathlib.Path('/proc')/str(task['key'][0])/'fd').iterdir())
  638. assert len(entries) <= 4096, 'fresh bus alias FD cap'
  639. live_aliases = set()
  640. for entry in entries:
  641. if os.readlink(entry) == 'socket:['+str(conn['socket'][1])+']':
  642. assert self.bus_fd(task['key'][0],int(entry.name),conn['connected']) == conn['socket'], 'fresh watched alias identity'
  643. live_aliases.add(int(entry.name))
  644. assert live_aliases == set(aliases), 'unconsumed/unknown watched socket alias'
  645. for other in self.tasks.values():
  646. if other.get('exited'): continue
  647. if other['fds'] is table and other['key'] != task['key']:
  648. pending = self.pending.get(other['key'][0],'')
  649. assert not pending.startswith(('dup(','dup2(','dup3(','fcntl(','close(','close_range(',
  650. 'socket(','socketpair(','open(','openat(','openat2(','pipe(','pipe2(','accept(','accept4(')), 'lagging alias/table record'
  651. fd = arguments[0]
  652. destroys = (name in ('close','shutdown') and fd in aliases or
  653. name in ('dup2','dup3') and arguments[1] in aliases and fd != arguments[1] or
  654. name == 'close_range' and any((fd & 0xffffffff) <= alias <= (arguments[1] & 0xffffffff) for alias in aliases) or
  655. name == 'exit_group' or name == 'exit' and task['facts']['tgid'] == task['key'][0])
  656. if name == 'exit' and not destroys:
  657. owner = self.register(conn['owner']['pid'])
  658. assert owner['fds'] is table and not owner.get('exited') and owner['key'][1] == conn['owner']['birth'], 'thread exit lacks surviving owner/table'
  659. assert self.identity(owner['key'][0]) == conn['owner'], 'surviving peer identity drift'
  660. return conn if destroys and not conn['acked'] else None
  661. def namespace_child(self, local, parent, flags, outer_hint=None):
  662. assert 'CLONE_PARENT' not in flags, 'unsupported clone parent relation'
  663. before = self.register(parent['key'][0])['facts']
  664. scope = pathlib.Path('/proc')/str(before['tgid'])/'task'
  665. tids = {int(p.name) for p in scope.iterdir()} if 'CLONE_THREAD' in flags else {int(p.name) for p in pathlib.Path('/proc').iterdir() if p.name.isdecimal()}
  666. assert len(tids) <= self.MAX_EVENTS, 'clone discovery task budget'
  667. if outer_hint is not None:
  668. assert outer_hint in tids, 'translated child outside original task scope'
  669. tids = {outer_hint}
  670. matches = []
  671. discovery_counts = dict.fromkeys(('statusGone','depthMismatch','localMismatch','parentMismatch','pidnsMismatch','matched'),0)
  672. for tid in sorted(tids):
  673. ids = [] # Failure context must not carry the preceding candidate's IDs.
  674. proc = pathlib.Path('/proc')/str(tid)
  675. try:
  676. rows = (proc/'status').read_text().splitlines()
  677. except FileNotFoundError:
  678. discovery_counts['statusGone'] += 1
  679. if 'CLONE_THREAD' in flags: raise
  680. continue # An unqualified enumeration entry disappeared.
  681. status = dict(row.split(':',1) for row in rows if ':' in row)
  682. ids = list(map(int,status['NSpid'].split()))
  683. if len(ids) == len(before['nspid']) and ids[-1] == local and ('CLONE_THREAD' in flags or int(status['PPid']) == before['tgid']):
  684. if os.readlink(proc/'ns/pid') != before['ns']['pid']:
  685. discovery_counts['pidnsMismatch'] += 1
  686. continue
  687. child = self.register(tid)
  688. assert child['facts']['nspid'] == ids, 'clone namespace mapping race'
  689. matches.append(child)
  690. discovery_counts['matched'] += 1
  691. else:
  692. reason = 'depthMismatch' if len(ids) != len(before['nspid']) else 'localMismatch' if ids[-1] != local else 'parentMismatch'
  693. discovery_counts[reason] += 1
  694. assert len(matches) == 1, 'one exact namespace child mapping required'
  695. self.register(parent['key'][0])
  696. facts = matches[0]['facts']
  697. if 'CLONE_THREAD' in flags:
  698. assert facts['tgid'] == before['tgid'], 'clone thread parent group'
  699. else:
  700. assert facts['tgid'] == facts['pid'] and facts['ppid'] == before['tgid'], 'clone process parent group'
  701. if outer_hint is not None:
  702. assert facts['pid'] == outer_hint, 'translated child mapping mismatch'
  703. return facts['pid']
  704. def register(self, tid, parent=None, shared=False):
  705. facts = trace_task_identity(tid)
  706. assert facts['ns'] == self.controller['ns'], 'trace namespace drift'
  707. assert facts['uids'] == facts['gids'] == [1000]*4 and facts['groups'] == [], 'trace credential drift'
  708. assert facts['tracer'] == self.tracer['pid'], 'untraced task'
  709. key = (tid, facts['birth'])
  710. if tid in self.tasks:
  711. assert self.tasks[tid]['key'] == key, 'trace PID reuse'
  712. old = self.tasks[tid]['facts']
  713. assert all(facts[field] == old[field] for field in ('tgid','uids','gids','groups','nspid','tracer','ns','uidMap','gidMap')), 'fresh task authority drift'
  714. return self.tasks[tid]
  715. table = parent['fds'] if parent is not None and shared else copy.deepcopy(parent['fds']) if parent else {}
  716. task = {'key':key,'facts':facts,'fds':table,'parent':parent['key'] if parent else None,
  717. 'capture':parent.get('capture') if parent and shared else None}
  718. self.tasks[tid] = task
  719. return task
  720. def feed(self, chunk):
  721. with self.lock:
  722. assert self.error is None, self.error
  723. self.total += len(chunk)
  724. assert self.total <= self.MAX_STREAM, 'total raw trace/hex-expansion budget'
  725. self.fragment += chunk
  726. while b'\n' in self.fragment:
  727. line, self.fragment = self.fragment.split(b'\n',1)
  728. assert len(line) <= self.MAX_LINE, 'trace line budget'
  729. self.line(line.decode('ascii','strict'))
  730. self.changed.notify_all()
  731. assert len(self.fragment) <= self.MAX_LINE, 'partial trace line budget'
  732. def line(self, line):
  733. marker = re.fullmatch(r'# R1353 ([1-9][0-9]{0,6})',line)
  734. if marker:
  735. sequence = int(marker[1])
  736. assert sequence <= self.MAX_EVENTS and sequence not in self.checkpoints, 'checkpoint sequence'
  737. self.checkpoints.add(sequence)
  738. return
  739. self.events += 1
  740. assert self.events <= self.MAX_EVENTS, 'trace record budget'
  741. m = re.fullmatch(r'(?:\[pid\s+)?(\d+)(?:\])?\s+(.+)',line)
  742. assert m, 'unqualified trace record'
  743. tid, call = int(m[1]), m[2]
  744. remap = re.fullmatch(r'\+\+\+ superseded by execve in pid ([1-9][0-9]*) \+\+\+',call)
  745. if remap:
  746. self.exec_remap(tid,int(remap[1]))
  747. return
  748. task = self.tasks.get(tid) or self.register(tid)
  749. if task.get('parent') is None and task['facts']['tgid'] != self.controller['pid'] and not task.get('nativeLeader'):
  750. clones = [prefix for prefix in self.pending.values() if prefix.startswith(('clone(','clone3(','fork(','vfork('))]
  751. if clones:
  752. queued = task.setdefault('earlyChildCalls',[])
  753. assert len(queued) < 256 and sum(len(value) for value in queued)+len(call) <= LIMIT, 'early child trace bound'
  754. queued.append(call)
  755. return
  756. if call.startswith('--- SIG'):
  757. assert tid in self.tasks and not self.tasks[tid].get('exited') and (task.get('parent') or task.get('nativeLeader') or task['facts']['tgid'] == self.controller['pid']), 'signal from unknown/terminal task'
  758. assert 'SIGKILL' not in call, 'forced native termination'
  759. return
  760. if call.startswith('+++ killed by '):
  761. assert call == '+++ killed by SIGTERM +++' and tid in self.tasks, 'unknown/forced terminal signal'
  762. task = self.tasks[tid]
  763. assert not task.get('exited') and not task.get('capture') and not task.get('nativeLeader'), 'helper/leader/control termination cannot pass'
  764. ancestor = task
  765. while ancestor.get('parent'):
  766. key = ancestor['parent']; ancestor = self.task_for_key(key)
  767. assert ancestor['key'] == key, 'terminal ancestry birth mismatch'
  768. if ancestor.get('nativeLeader'): break
  769. assert ancestor.get('nativeLeader'), 'non-native terminal signal'
  770. group = self.tasks.get(task['facts']['tgid'])
  771. assert group is not None, 'unknown terminal process birth'
  772. task['terminalCancellation'] = {'record':call,'pendingSyscall':self.pending.pop(tid,None),
  773. 'pendingRead':self.pending_reads.pop(tid,None),'leader':ancestor['key'],'worker':group['key']}
  774. # Immutable cancel; owned cleanup.
  775. pending_read = task['terminalCancellation']['pendingRead']
  776. if pending_read is not None: task['terminalCancellation']['pendingRead'] = {'fd':pending_read[0],'lineageAtEntry':pending_read[1]}
  777. task['exited'] = True
  778. return
  779. if call.startswith('+++ exited with '):
  780. assert tid in self.tasks and tid not in self.pending and (task.get('parent') or task.get('nativeLeader') or task['facts']['tgid'] == self.controller['pid']), 'unobserved/unfinished exit'
  781. task = self.tasks[tid]
  782. capture = task.get('capture')
  783. if capture and task['facts']['tgid'] == tid:
  784. assert call == '+++ exited with 0 +++', 'helper natural exit required'
  785. assert capture['eof'] and capture['bytes'] and capture['dupSeen'], 'incomplete consumed stdin'
  786. capture['exited'] = True
  787. task['exited'] = True
  788. return
  789. task = self.tasks.get(tid) or self.register(tid)
  790. assert not task.get('exited'), 'trace after terminal identity'
  791. if '<unfinished ...>' in call:
  792. assert tid not in self.pending and call.endswith(' <unfinished ...>'), 'ambiguous unfinished syscall'
  793. prefix = call[:-len(' <unfinished ...>')]
  794. if prefix.startswith('read('):
  795. fd = int(prefix.split('(',1)[1].split(',',1)[0])
  796. self.pending_reads[tid] = (fd,dict(task['fds'][fd]) if fd in task['fds'] else None,task['fds'])
  797. if task.get('capture') and task['fds'].get(fd,{}).get('lineage'):
  798. capture = task['capture']
  799. assert capture['reading'] is None, 'concurrent stdin reads have ambiguous ordering'
  800. capture['reading'] = tid
  801. self.pending[tid] = prefix
  802. return
  803. fd_entry = None
  804. resumed = re.fullmatch(r'<\.\.\. (\w+) resumed>(.*)',call)
  805. if resumed:
  806. assert tid in self.pending, 'resumed without unfinished'
  807. prefix = self.pending.pop(tid)
  808. assert prefix.startswith(resumed[1]+'('), 'resumed syscall mismatch'
  809. fd_entry = self.acked_fd_entries.get(tid)
  810. if fd_entry is not None:
  811. assert fd_entry['key'] == task['key'] and fd_entry['prefix'] == prefix and fd_entry['table'] is task['fds'], 'ACKed FD return incarnation'
  812. call = prefix+resumed[2]
  813. if tid in self.pending_reads:
  814. fd,old,table = self.pending_reads.pop(tid)
  815. assert task['fds'] is table and task['fds'].get(fd) == old, 'unfinished read FD lineage changed'
  816. else:
  817. assert tid not in self.pending, 'missing resumed record'
  818. m = re.fullmatch(r'(\w+)\((.*)\)\s+=\s+(.+)',call)
  819. assert m, 'unknown syscall text'
  820. name, args, result = m.groups()
  821. ret = re.match(r'(-?(?:0x[0-9a-f]+|\d+))(?:\s|$)',result)
  822. restart = re.fullmatch(r'\? ERESTART(?:SYS|NOINTR|NOHAND|_RESTARTBLOCK).*',result)
  823. assert ret or result == '?' and name in ('exit','exit_group') or restart and name == 'read', 'unknown syscall result'
  824. number = int(ret[1],0) if ret else None
  825. capture = task.get('capture')
  826. if name in ('execve','execveat') and number == 0:
  827. strings = re.findall(r'"(?:\\x[0-9a-fA-F]{2})*"',args)
  828. assert strings, 'missing exec argv'
  829. # Env abbreviated; HOME /proc proof.
  830. left, sep, rest = args.partition('[')
  831. argtext, close, tail = rest.partition(']')
  832. assert sep and close and '...' not in argtext, 'incomplete exec argv'
  833. argv = [decoded_hex_string(s).decode('utf-8','strict') for s in re.findall(r'"(?:\\x[0-9a-fA-F]{2})*"',argtext)]
  834. assert len(b'\0'.join(a.encode() for a in argv))+1 <= 8192, 'exec argv budget'
  835. task['fds'] = {fd:dict(v) for fd,v in task['fds'].items() if not v.get('cloexec')}
  836. if argv == self.helper_argv:
  837. ancestor = task
  838. assert ancestor.get('parent') is not None, 'unobserved helper ancestry'
  839. while ancestor.get('parent'):
  840. parent_key = ancestor['parent']
  841. ancestor = self.task_for_key(parent_key)
  842. assert ancestor['key'] == parent_key, 'ancestor birth mismatch'
  843. if ancestor.get('nativeLeader'): break
  844. if not ancestor.get('nativeLeader'):
  845. assert ancestor['facts']['tgid'] == self.controller['pid'], 'unknown nonnative helper ancestry'
  846. task['excludedControllerHelper'] = True
  847. return # Exact observed replay/control descendant; never selected native evidence.
  848. facts = self.identity(tid)
  849. assert facts['birth'] == task['key'][1] and facts['argv'] == argv, 'exec live identity/argv mismatch'
  850. assert facts['exe'] == argv[0] and facts['cwd'] == str(self.root/'home/.cursor'), 'source-qualified USER helper executable/cwd'
  851. assert facts['ns'] == self.controller['ns'] and facts['uids'] == facts['gids'] == [1000]*4
  852. assert facts['groups'] == [] and facts['tracer'] == self.tracer['pid']
  853. assert digest(argv[0]) == self.helper_hash, 'actual helper executable hash'
  854. env = (pathlib.Path('/proc')/str(tid)/'environ').read_bytes()
  855. assert len(env) <= 65536 and b'HOME='+str(self.root/'home').encode()+b'\0' in env, 'actual helper HOME'
  856. endpoint = live_stdin_endpoint(tid)
  857. capture = {'identity':facts,'endpoint':endpoint,'bytes':bytearray(),'eof':False,
  858. 'dupSeen':False,'exited':False,'reading':None,
  859. 'events':[{'tidBirth':task['key'],'syscall':call}],'leader':ancestor['key']}
  860. assert len(self.selected) < 2, 'one genuine helper per planned phase'
  861. self.selected.append(capture)
  862. task['capture'] = capture
  863. task['fds'][0] = {'lineage':True,'cloexec':False}
  864. elif capture:
  865. raise AssertionError('selected helper unexpected exec')
  866. elif name in ('clone','clone3','fork','vfork') and number is not None and number > 0:
  867. translated = re.fullmatch(r"([1-9][0-9]{0,9})(?: /\* ([1-9][0-9]{0,9}) in strace's PID NS \*/)?",result)
  868. assert translated and int(translated[1]) == number and number <= 2147483647 and (translated[2] is None or int(translated[2]) <= 2147483647), 'unknown fork PID namespace return'
  869. outer_hint = int(translated[2]) if translated[2] is not None else None
  870. edge = self.clone_edges.pop(task['key'],None)
  871. assert edge is not None and edge['local'] == number, 'return without held clone admission'
  872. assert edge['flags'] == set(re.findall(r'\bCLONE_[A-Z0-9_]+\b',args)), 'clone flags changed at return'
  873. number = edge['key'][0]
  874. assert outer_hint in (None,number), 'held return outer namespace mismatch'
  875. child = self.tasks[number]
  876. assert child['key'] == edge['key'] and child['parent'] == task['key'], 'held return lineage mismatch'
  877. # vfork child exec/exit may precede return: only reconcile the edge
  878. # admitted while both tasks were freshly live, never dead admission.
  879. queued = child.pop('earlyChildCalls',[])
  880. for recorded in queued: self.line(str(number)+' '+recorded)
  881. elif name == 'connect':
  882. conn = task['fds'].get(int(args.split(',',1)[0]),{}).get('bus')
  883. if conn is not None:
  884. assert conn['intent'] == task['key'] and conn['outcome'] is None, 'connect outcome incarnation'
  885. conn['outcome'] = call
  886. conn['connected'] = number == 0
  887. elif name in ('dup','dup2','dup3') and number is not None and number >= 0:
  888. old = int(args.split(',',1)[0])
  889. if name != 'dup': assert number == int(args.split(',')[1]), 'dup target mismatch'
  890. if name == 'dup2' and old == number:
  891. if fd_entry is not None: self.acked_fd_entries.pop(tid)
  892. return # POSIX no-op preserves FD_CLOEXEC.
  893. task['fds'][number] = dict(task['fds'].get(old,{'lineage':False}))
  894. task['fds'][number]['cloexec'] = 'O_CLOEXEC' in args
  895. if capture and old == 0 and task['fds'][number].get('lineage') and number != 0:
  896. capture['dupSeen'] = True
  897. elif name == 'fcntl' and number is not None and number >= 0:
  898. parts = args.split(','); fd = int(parts[0]); op = parts[1].strip()
  899. if op in ('F_DUPFD','F_DUPFD_CLOEXEC'):
  900. task['fds'][number] = dict(task['fds'].get(fd,{'lineage':False}))
  901. task['fds'][number]['cloexec'] = op.endswith('CLOEXEC')
  902. if capture and fd == 0 and number != 0 and task['fds'][number].get('lineage'): capture['dupSeen'] = True
  903. elif op == 'F_SETFD':
  904. if fd in task['fds']: task['fds'][fd]['cloexec'] = 'FD_CLOEXEC' in args
  905. else:
  906. assert op in ('F_GETFD','F_GETFL','F_SETFL','F_SETLK','F_SETLKW','F_GETLK','F_OFD_SETLK'), 'unaccounted fcntl'
  907. elif name == 'close' and number == 0:
  908. task['fds'].pop(int(args),None)
  909. elif name == 'close_range' and number == 0:
  910. parts = args.split(','); first = int(parts[0]); last = 4294967295 if '~0U' in parts[1] else int(parts[1])
  911. if 'CLOSE_RANGE_UNSHARE' in args:
  912. task['fds'] = {fd:dict(value) for fd,value in task['fds'].items()}
  913. for conn in (capture or {}).get('busConnections',[]):
  914. assert len(conn['tables']) < 4096, 'bus table lineage cap'
  915. conn['tables'].append(task['fds'])
  916. for fd in list(task['fds']):
  917. if first <= fd <= last:
  918. if 'CLOSE_RANGE_CLOEXEC' in args: task['fds'][fd]['cloexec'] = True
  919. else: task['fds'].pop(fd)
  920. elif name in ('open','openat','openat2','socket','accept','accept4','eventfd','eventfd2','epoll_create','epoll_create1','memfd_create') and number is not None and number >= 0:
  921. task['fds'][number] = {'lineage':False,'cloexec':'CLOEXEC' in args}
  922. elif name in ('pipe','pipe2','socketpair') and number == 0:
  923. fds = re.findall(r'\[(\d+),\s*(\d+)\]',args)
  924. assert len(fds) == 1, 'unknown descriptor pair'
  925. for fd in map(int,fds[0]): task['fds'][fd] = {'lineage':False,'cloexec':'CLOEXEC' in args}
  926. elif name == 'read':
  927. assert not any(any(value.startswith('read(') for value in other.get('earlyChildCalls',[])) for other in self.tasks.values()), 'ambiguous consumed order across unresolved child clone'
  928. fd = int(args.split(',',1)[0])
  929. if capture and task['fds'].get(fd,{}).get('lineage'):
  930. assert capture['dupSeen'] and fd != 0 and not capture['eof'], 'read outside consumed alias/completion'
  931. assert capture['reading'] in (None,tid), 'ambiguous read order'
  932. capture['reading'] = None
  933. if restart: pass
  934. elif number == -1:
  935. assert any(result.startswith('-1 '+e) for e in ('EINTR','EAGAIN')), 'failed stdin read'
  936. else:
  937. m = re.fullmatch(r'\d+,\s*("(?:\\x[0-9a-fA-F]{2})*"),\s*(\d+)',args)
  938. assert m and number is not None and 0 <= number <= int(m[2]), 'partial/unknown stdin read'
  939. raw = decoded_hex_string(m[1])
  940. assert len(raw) == number, 'decoded return count mismatch/truncation'
  941. capture['bytes'].extend(raw)
  942. assert len(capture['bytes']) <= LIMIT, 'consumed stdin payload budget'
  943. capture['eof'] = number == 0
  944. assert len(capture['events']) < 4096, 'selected read/lineage event budget'
  945. capture['events'].append({'tidBirth':task['key'],'syscall':call})
  946. elif capture and name in ('readv','pread64','preadv','preadv2','recvfrom','recvmsg','recvmmsg'):
  947. fd = int(args.split(',',1)[0])
  948. assert not task['fds'].get(fd,{}).get('lineage'), 'unknown read on proven stdin lineage: '+name
  949. if name in ('recvmsg','recvmmsg') and number is not None and number >= 0:
  950. assert 'SCM_RIGHTS' not in args and ('msg_controllen=0' in args or 'msg_control=NULL' in args or 'msg_control=[]' in args), 'unknown received descriptor lineage'
  951. elif capture and name in ('splice','tee','vmsplice','io_uring_setup','io_uring_enter','io_uring_register','pidfd_getfd','unshare','setns','setuid','setgid','setreuid','setregid','setresuid','setresgid','setgroups','capset'):
  952. raise AssertionError('unaccounted selected read/FD/identity operation: '+name)
  953. if capture and name in ('dup','dup2','dup3','fcntl','close','close_range','clone','clone3','fork','vfork','exit','exit_group'):
  954. assert len(capture['events']) < 4096, 'selected lineage event budget'
  955. capture['events'].append({'tidBirth':task['key'],'syscall':call})
  956. if fd_entry is not None: self.acked_fd_entries.pop(tid)
  957. def finish(self):
  958. with self.lock:
  959. assert not self.fragment and not self.pending and not self.pending_reads and not self.acked_fd_entries and self.error is None and not self.clone_edges and not self.checkpoints and not any(task.get('earlyChildCalls') for task in self.tasks.values()), 'partial trace stream/unknown child ancestry'
  960. assert all(c['exited'] and c['eof'] and c['reading'] is None for c in self.selected), 'unfinished helper stream'
  961. return self.selected
  962. def task_key(task):
  963. return (task['facts']['pid'],task['facts']['birth'])
  964. TRACE_SYSCALLS = (
  965. 'read,readv,pread64,preadv,preadv2,recvfrom,recvmsg,recvmmsg,splice,tee,vmsplice,'
  966. 'dup,dup2,dup3,fcntl,close,close_range,open,openat,openat2,pipe,pipe2,socket,socketpair,'
  967. 'accept,accept4,eventfd,eventfd2,epoll_create,epoll_create1,memfd_create,pidfd_getfd,connect,shutdown,'
  968. 'execve,execveat,clone,clone3,fork,vfork,exit,exit_group,wait4,waitid,'
  969. 'setns,unshare,setuid,setgid,setreuid,setregid,setresuid,setresgid,setgroups,capset,'
  970. 'io_uring_setup,io_uring_enter,io_uring_register')
  971. def control_send(peer, value, clock):
  972. raw = json.dumps(value,separators=(',',':')).encode()
  973. assert len(raw) <= 2*LIMIT, 'control record bound including base64 expansion'
  974. peer.settimeout(clock.wait(5))
  975. peer.sendall(struct.pack('>I',len(raw))+raw)
  976. def control_receive(peer, clock):
  977. def exact(n):
  978. parts = bytearray()
  979. while len(parts) < n:
  980. peer.settimeout(clock.wait(5))
  981. part = peer.recv(n-len(parts))
  982. assert part, 'owned control peer EOF'
  983. parts.extend(part)
  984. return bytes(parts)
  985. size = struct.unpack('>I',exact(4))[0]
  986. assert 0 < size <= 2*LIMIT, 'control record size including base64 expansion'
  987. return strict_json(exact(size))
  988. class ControllerObservation:
  989. def __init__(self, peer, clock):
  990. self.peer, self.clock = peer, clock
  991. self.sequence = 0
  992. self.nonce = os.urandom(32).hex()
  993. self.exchange_lock = threading.Lock()
  994. def exchange(self, action, **facts):
  995. if not self.exchange_lock.acquire(timeout=self.clock.wait(1)): raise AssertionError('control exchange lock deadline')
  996. try: return self._exchange_locked(action,**facts)
  997. finally: self.exchange_lock.release()
  998. def _exchange_locked(self, action, **facts):
  999. self.sequence += 1
  1000. control_send(self.peer,{'action':action,'sequence':self.sequence,'nonce':self.nonce,'cleanupUsed':self.clock.cleanup_used,**facts},self.clock)
  1001. reply = control_receive(self.peer,self.clock)
  1002. assert reply.get('sequence') == self.sequence and reply.get('nonce') == self.nonce, 'control synchronization identity'
  1003. assert reply.get('ok') is True, reply.get('error','unknown outer observation')
  1004. return reply
  1005. def source_failure_frames(error, trusted_code):
  1006. frames, tb, visited = [], error.__traceback__, 0
  1007. while tb is not None and visited < 64:
  1008. code = tb.tb_frame.f_code
  1009. if code.co_filename == trusted_code.co_filename:
  1010. frames = (frames+[(code.co_name[:64],tb.tb_lineno)])[-8:]
  1011. tb = tb.tb_next; visited += 1
  1012. return frames
  1013. class PassiveStrace:
  1014. def __init__(self, controller, installed, root, clock, tools, session):
  1015. # Provisional own-child/FD custody is cleanup only, never admission.
  1016. self.owned_children, self.owned_streams, self.owned_fds = [], [], set()
  1017. self.threads, self.held_workers = [], []
  1018. self.session, self.controller, self.clock = session, controller, clock
  1019. self.root = pathlib.Path(root)
  1020. self.error = self.first_error = None
  1021. self.stopping = False
  1022. try:
  1023. with session.records_changed:
  1024. session.trace = self
  1025. assert session.error is None, session.error
  1026. self._construct(controller, installed, root, clock, tools, session)
  1027. except BaseException as error:
  1028. self.refuse_held(error)
  1029. try:
  1030. self.force_contain(error)
  1031. except BaseException as cleanup_error:
  1032. error.add_note('observer constructor containment unproved: '+type(cleanup_error).__name__)
  1033. try: self.failure_join(clock.outer+5)
  1034. except BaseException as cleanup_error:
  1035. error.add_note('observer constructor cleanup unproved: '+type(cleanup_error).__name__)
  1036. raise self.first_error
  1037. def _construct(self, controller, installed, root, clock, tools, session):
  1038. self.session = session
  1039. self.incarnation = os.urandom(32).hex()
  1040. self.observer_sequence = 0
  1041. self.acked_keys = set()
  1042. self.pending_acks = {}
  1043. self.custody_keys = set()
  1044. self.held_workers = []
  1045. self.stopping = False
  1046. self.observer_peer, inherited = socket.socketpair(socket.AF_UNIX,socket.SOCK_SEQPACKET)
  1047. self.owned_streams.extend((self.observer_peer,inherited))
  1048. self.clock = clock
  1049. self.controller = controller
  1050. self.root = pathlib.Path(root)
  1051. self.options = None
  1052. self.seize_stops = set()
  1053. self.debug_bytes = 0
  1054. self.debug_fragment = b''
  1055. self.started_tids = set()
  1056. self.closing_tids = set()
  1057. readfd, writefd = os.pipe()
  1058. self.owned_fds.update((readfd,writefd))
  1059. primary, selector, binding, generation = installed
  1060. argv = [tools['strace']['path'],'-d','-f','-xx','--decode-pids=pidns','-s',str(LIMIT+1),
  1061. '-e','trace='+TRACE_SYSCALLS,'-o','/proc/self/fd/'+str(writefd),'-p',str(controller['pid'])]
  1062. self.child = subprocess.Popen(argv,stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,
  1063. stderr=subprocess.PIPE,pass_fds=(writefd,inherited.fileno()),env={'PATH':'/usr/bin:/bin','LANG':'C',
  1064. 'TMPDIR':str(self.root/'tmp'),'TEST_R1353_FD':str(inherited.fileno()),
  1065. 'TEST_R1353_INCARNATION':self.incarnation},start_new_session=True,bufsize=0)
  1066. self.owned_children.append(self.child)
  1067. inherited.close()
  1068. os.close(writefd)
  1069. self.owned_fds.remove(writefd)
  1070. self.tracer = startup_identity(self.child.pid)
  1071. self.tracer = proc_identity(self.child.pid)
  1072. assert self.tracer['argv'] == argv and self.tracer['exe'] == tools['strace']['path']
  1073. assert self.tracer['uids'] == self.tracer['gids'] == [0]*4
  1074. assert self.tracer['ns']['pid'] != controller['ns']['pid'] and self.tracer['ns']['user'] == controller['ns']['user']
  1075. assert self.tracer['uidMap'] == controller['uidMap'] and self.tracer['gidMap'] == controller['gidMap']
  1076. assert self.tracer['ns']['pid'] == os.readlink('/proc/self/ns/pid') == os.readlink('/proc/1/ns/pid'), 'tracer/parser proc PID namespace mismatch'
  1077. self.tracer_admitted = True
  1078. self.parser = StdinAliasTrace(proc_identity,[str(primary),'cursor-event','stop','--binding',str(selector)],
  1079. digest(primary),controller,self.tracer,root)
  1080. self.trace_pipe = os.fdopen(readfd,'rb',buffering=0)
  1081. self.owned_fds.remove(readfd)
  1082. self.owned_streams.append(self.trace_pipe)
  1083. self.threads = []
  1084. def pump(stream, consume):
  1085. try:
  1086. while True:
  1087. part = stream.read(8192)
  1088. if not part: break
  1089. with self.parser.changed:
  1090. try: consume(part)
  1091. except Exception as error:
  1092. self.refuse_held(error)
  1093. raise
  1094. except Exception as error:
  1095. self.refuse_held(error)
  1096. tb = error.__traceback__
  1097. try:
  1098. print('trace-pump-failure',type(error).__name__[:64],'firstStored',error is self.first_error,source_failure_frames(error,pump.__code__),file=sys.stderr,flush=True)
  1099. call_name = None
  1100. while tb is not None:
  1101. if tb.tb_frame.f_code is self.parser.line.__func__.__code__:
  1102. name = tb.tb_frame.f_locals.get('name')
  1103. if name in ('clone','clone3','fork','vfork'): call_name = name
  1104. if tb.tb_frame.f_code is self.parser.namespace_child.__func__.__code__:
  1105. context = tb.tb_frame.f_locals
  1106. parent = context['parent']; before = context.get('before',parent['facts'])
  1107. reported_flags = tuple(flag for flag in ('CLONE_THREAD','CLONE_FILES','CLONE_VM','CLONE_VFORK',
  1108. 'CLONE_PARENT','CLONE_PARENT_SETTID','CLONE_CHILD_SETTID','CLONE_CHILD_CLEARTID',
  1109. 'CLONE_NEWPID','CLONE_NEWUSER','CLONE_NEWNS','CLONE_NEWNET') if flag in context['flags'])
  1110. hint_snapshot = None
  1111. hint = context.get('outer_hint')
  1112. if error is self.first_error and type(error) is AssertionError and str(error) == 'translated child outside original task scope' and type(hint) is int and hint > 0 and hint not in context.get('tids',()):
  1113. try:
  1114. snapshot = []
  1115. for field in ('stat','status'):
  1116. with (pathlib.Path('/proc')/str(hint)/field).open('rb') as hint_stream: raw = hint_stream.read(8193)
  1117. if len(raw) > 8192: raise ValueError('diagnostic byte budget')
  1118. snapshot.append(raw.decode('ascii','strict'))
  1119. raw, status_raw = snapshot; tail = raw[raw.rindex(')')+2:].split()
  1120. number = lambda value: int(value) if re.fullmatch(r'[0-9]{1,20}',value) and int(value) <= 18446744073709551615 else (_ for _ in ()).throw(ValueError('diagnostic integer'))
  1121. pid, birth = number(raw[:raw.index('(')].strip()), number(tail[19])
  1122. if pid != hint or tail[0] not in ('R','S','D','Z','T','t','X','x','K','W','P','I'): raise ValueError('diagnostic stat')
  1123. status = {}
  1124. for line in status_raw.splitlines():
  1125. key, sep, value = line.partition(':')
  1126. if sep and key in ('Tgid','NSpid','Uid','TracerPid'):
  1127. if key in status: raise ValueError('diagnostic duplicate')
  1128. status[key] = value.split()
  1129. if set(status) != {'Tgid','NSpid','Uid','TracerPid'} or len(status['Tgid']) != 1 or len(status['TracerPid']) != 1 or len(status['Uid']) != 4 or not 1 <= len(status['NSpid']) <= 32: raise ValueError('diagnostic status')
  1130. hint_snapshot = {'pid':pid,'birth':birth,'state':tail[0],'tgid':number(status['Tgid'][0]),'nspid':[number(v) for v in status['NSpid']],'uids':[number(v) for v in status['Uid']],'tracer':number(status['TracerPid'][0])}
  1131. except Exception as diagnostic_error:
  1132. hint_snapshot = {'error':type(diagnostic_error).__name__[:64],'errno':diagnostic_error.errno if isinstance(diagnostic_error,OSError) and type(diagnostic_error.errno) is int else None}
  1133. print('namespace-registration-failure',
  1134. 'syscall',call_name,'cloneFlags',reported_flags,'otherFlagCount',len(context['flags'])-len(reported_flags),
  1135. 'refusals',context.get('discovery_counts'),
  1136. 'registrationTid',tb.tb_next.tb_frame.f_locals.get('tid') if tb.tb_next is not None else None,
  1137. 'outerHint',context.get('outer_hint') if type(context.get('outer_hint')) is int else None,
  1138. 'outerHintSnapshot',hint_snapshot,
  1139. 'candidate',(context['local'],context.get('tid'),context.get('ids',[])[:32]),
  1140. 'discovery',(len(context.get('tids',())),sorted(context.get('tids',()))[:16],len(context.get('matches',())),[task['key'] for task in context.get('matches',())[:16]]),
  1141. 'parent',(parent['key'],before['tgid'],before['nspid'][:32]),
  1142. 'CLONE_THREAD','CLONE_THREAD' in context['flags'],
  1143. 'roles',(bool(parent.get('nativeLeader')),bool(parent.get('capture'))),file=sys.stderr,flush=True)
  1144. tb = tb.tb_next
  1145. except Exception:
  1146. pass
  1147. if error is self.first_error and type(error) is AssertionError and str(error) == 'trace namespace drift':
  1148. try:
  1149. tb, visited = error.__traceback__, 0
  1150. while tb is not None and visited < 64:
  1151. if tb.tb_frame.f_code is self.parser.register.__func__.__code__:
  1152. context = tb.tb_frame.f_locals
  1153. facts, expected = context['facts'], context['self'].controller['ns']
  1154. pid, birth = context['tid'], facts['birth']
  1155. if type(pid) is not int or not 0 < pid <= 2147483647 or type(birth) is not int or not 0 <= birth <= 18446744073709551615:
  1156. raise ValueError('diagnostic identity budget')
  1157. namespaces = {}
  1158. for side, values in (('actual',facts['ns']),('expected',expected)):
  1159. namespaces[side] = {}
  1160. for kind in ('pid','net','user'):
  1161. value = values[kind]
  1162. if type(value) is not str or len(value) > 64: raise ValueError('diagnostic namespace budget')
  1163. match = re.fullmatch(kind+r':\[(0|[1-9][0-9]{0,19})\]',value)
  1164. if match is None or int(match[1]) > 18446744073709551615: raise ValueError('diagnostic namespace identity')
  1165. namespaces[side][kind] = value
  1166. print('trace-register-namespace-refusal',{'pid':pid,'birth':birth,**namespaces},file=sys.stderr,flush=True)
  1167. break
  1168. tb = tb.tb_next; visited += 1
  1169. except Exception:
  1170. pass
  1171. finally:
  1172. try: stream.close()
  1173. except Exception as error: self.refuse_held(error)
  1174. if not self.stopping and self.error is None:
  1175. self.refuse_held(AssertionError('trace/debug reader EOF before owned close'))
  1176. for stream, consume in ((self.trace_pipe,self.consume_trace),(self.child.stderr,self.consume_debug)):
  1177. t = threading.Thread(target=pump,args=(stream,consume),daemon=True)
  1178. self.threads.append(t); t.start()
  1179. dispatcher = threading.Thread(target=self.dispatch_held,daemon=True)
  1180. self.threads.append(dispatcher); dispatcher.start()
  1181. self.ready()
  1182. (self.root/'evidence/trace-readiness.json').write_text(json.dumps({
  1183. 'controller':controller,'tracer':self.tracer,'currentTids':sorted(self.started_tids),
  1184. 'seizeStopTids':sorted(self.seize_stops),'ptraceOptions':self.options,'argv':argv,
  1185. 'toolProvenance':tools['strace'],'incarnation':self.incarnation,
  1186. 'kernelACKCompletedKeys':sorted(self.acked_keys)},indent=2)+'\n')
  1187. def refuse_held(self, error):
  1188. first = self.session.publish_failure(error,refuse=False)
  1189. if hasattr(self,'parser'):
  1190. with self.parser.changed:
  1191. if self.error is None:
  1192. self.first_error, self.error = first, self.session.error
  1193. self.parser.error = self.error
  1194. self.parser.changed.notify_all()
  1195. elif self.error is None:
  1196. self.first_error, self.error = first, self.session.error
  1197. with self.session.records_changed:
  1198. if self.session.trace_failure is None: self.session.trace_failure = self.error
  1199. self.session.records_changed.notify_all()
  1200. if hasattr(self,'observer_peer'):
  1201. try: self.observer_peer.shutdown(socket.SHUT_RDWR)
  1202. except OSError: pass
  1203. def dispatch_held(self):
  1204. try:
  1205. while not self.stopping:
  1206. assert self.error is None and self.session.error is None, self.error or self.session.error
  1207. if not select.select([self.observer_peer],[],[],self.clock.wait(.25))[0]: continue
  1208. packet, ancillary, flags, _ = self.observer_peer.recvmsg(516)
  1209. if self.stopping: break
  1210. assert packet and not ancillary and not flags, 'held channel EOF/truncation/ancillary'
  1211. if packet.startswith(b'DONE '):
  1212. request = packet[5:]
  1213. with self.parser.changed:
  1214. keys = self.pending_acks.pop(request,None)
  1215. assert keys is not None, 'unrequested/duplicate kernel restart receipt'
  1216. self.acked_keys.update(keys)
  1217. self.parser.changed.notify_all()
  1218. continue
  1219. self.ack_held(packet)
  1220. except Exception as error:
  1221. if not self.stopping: self.refuse_held(error)
  1222. def ack_held(self, packet):
  1223. """Closed checkpoint dispatcher. No lock spans monitor/channel waiting."""
  1224. try:
  1225. assert type(packet) is bytes and 0 < len(packet) < 512, 'held request packet cap/EOF'
  1226. fields = packet.decode('ascii','strict').split()
  1227. assert len(fields) == 17 and fields[:3] == ['R1353',self.incarnation,str(self.tracer['pid'])], 'held tracer incarnation'
  1228. assert all(re.fullmatch(r'0|[1-9][0-9]{0,19}',fields[i]) for i in (3,5,6,7,8,10,11,12,13,14,15,16)), 'held numeric fields'
  1229. seq,phase,tid,birth,child,child_birth = int(fields[3]),fields[4],*map(int,fields[5:9])
  1230. assert seq == self.observer_sequence+1 and seq <= self.parser.MAX_EVENTS, 'held sequence'
  1231. assert phase in ('task','clone','entry','record') and re.fullmatch(r'[a-z][a-z0-9_]{0,31}',fields[9]), 'closed held phase/syscall'
  1232. assert 0 < tid <= 2147483647 and 0 < birth < 1<<64 and 0 <= child <= 2147483647 and 0 <= child_birth < 1<<64, 'held task/birth cap'
  1233. assert (child > 0 and child_birth > 0) if phase == 'clone' else (child == child_birth == 0), 'held pair fields'
  1234. arguments = list(map(int,fields[11:])); assert all(v < 1<<64 for v in arguments), 'held ABI argument cap'
  1235. assert int(fields[10]) < 1<<64, 'held clone flags cap'
  1236. self.observer_sequence = seq
  1237. with self.parser.changed:
  1238. assert self.parser.changed.wait_for(lambda:self.error or seq in self.parser.checkpoints,self.clock.wait(1)), 'complete real trace checkpoint deadline'
  1239. assert self.error is None and self.session.error is None, self.error or self.session.error
  1240. self.parser.checkpoints.remove(seq)
  1241. task = self.parser.register(tid)
  1242. assert task['key'] == (tid,birth), 'held task birth'
  1243. raw = (pathlib.Path('/proc')/str(tid)/'stat').read_text()
  1244. assert raw[raw.rindex(')')+2:].split()[0] == 't', 'actual held kernel stop'
  1245. self.custody_keys.add(task['key'])
  1246. if phase == 'clone':
  1247. fresh_child = trace_task_identity(child)
  1248. assert fresh_child['birth'] == child_birth and fresh_child['tracer'] == self.tracer['pid'], 'owned held child birth/tracer'
  1249. for field in ('uids','gids','groups','ns','uidMap','gidMap'):
  1250. assert fresh_child[field] == self.controller[field], 'owned held child authority'
  1251. assert fresh_child['tgid'] == task['facts']['tgid'] or fresh_child['ppid'] == task['facts']['tgid'], 'owned held child parent/group'
  1252. self.custody_keys.add((child,child_birth))
  1253. table = task['fds']
  1254. if phase == 'clone':
  1255. # The trace pump must consume returns before fresh FD snapshots.
  1256. # Only exact ACKed entries can run; unACKed held work must not wait.
  1257. assert self.parser.changed.wait_for(lambda:self.error or not any(
  1258. entry['table'] is table for entry in self.parser.acked_fd_entries.values()),
  1259. self.clock.wait(1)), 'ACKed shared FD return deadline'
  1260. assert self.error is None and self.session.error is None, self.error or self.session.error
  1261. self.parser.held_clone(tid,child,birth,child_birth,int(fields[10]))
  1262. conn = self.parser.held_entry(task,fields[9],arguments,self.session) if phase == 'entry' else None
  1263. capture = task.get('capture')
  1264. if phase == 'clone':
  1265. self.complete_held((packet,seq,phase,tid,birth,fields[9],arguments,table,capture,None))
  1266. return # Keep both FD proofs and ACK atomic against other entry ACKs.
  1267. context = (packet,seq,phase,tid,birth,fields[9],arguments,table,capture,conn)
  1268. if conn is not None:
  1269. with self.parser.changed:
  1270. assert len(self.held_workers) < 4096, 'held credential worker cap'
  1271. worker = threading.Thread(target=self.complete_held,args=(context,),daemon=True)
  1272. self.held_workers.append(worker); worker.start()
  1273. else: self.complete_held(context)
  1274. except Exception as error:
  1275. self.refuse_held(error)
  1276. raise
  1277. def complete_held(self, context):
  1278. packet,seq,phase,tid,birth,syscall,arguments,table,capture,conn = context
  1279. try:
  1280. name = self.session.held_credentials(capture,conn) if conn is not None else None
  1281. # Revalidate the real stopped task, table and every alias AFTER the
  1282. # monitor wait. The callback's cached credential alone cannot ACK.
  1283. with self.parser.changed:
  1284. try:
  1285. assert self.error is None and self.session.error is None, self.error or self.session.error
  1286. task = self.parser.register(tid)
  1287. assert task['key'] == (tid,birth) and task['fds'] is table, 'held task/table incarnation changed'
  1288. raw = (pathlib.Path('/proc')/str(tid)/'stat').read_text()
  1289. assert raw[raw.rindex(')')+2:].split()[0] == 't', 'held stop lost before ACK'
  1290. if capture: assert proc_identity(capture['identity']['pid'],capture['identity']) == capture['identity'], 'fresh selected ACK identity'
  1291. if conn is not None:
  1292. assert self.parser.held_entry(task,syscall,arguments,self.session) is conn, 'held socket/table changed after credential wait'
  1293. assert conn['name'] == name and conn['connected'], 'held name/connection incarnation changed'
  1294. keys = [task['key']]
  1295. if phase == 'clone':
  1296. child_tid,child_birth = map(int,packet.decode('ascii').split()[7:9])
  1297. child = self.parser.register(child_tid)
  1298. assert child['key'] == (child_tid,child_birth), 'child birth lost before ACK'
  1299. child_stat = (pathlib.Path('/proc')/str(child_tid)/'stat').read_text()
  1300. assert child_stat[child_stat.rindex(')')+2:].split()[0] == 't', 'child stop lost before ACK'
  1301. edge = self.parser.clone_edges[task['key']]
  1302. assert self.parser.clone_fds(tid,child_tid,edge['flags']) == edge['fds'], 'fresh inherited FD proof changed before ACK'
  1303. assert trace_task_identity(tid) == task['facts'] and trace_task_identity(child_tid) == child['facts'], 'fresh clone authority bookends before ACK'
  1304. keys.append(child['key'])
  1305. with self.session.records_lock:
  1306. try:
  1307. if conn is not None:
  1308. assert name in self.session.active_names and self.session.credentials.get(name) == capture['identity'], 'active monitored name incarnation'
  1309. assert all(self.session.roundtrip_present(call) for call in self.session.credential_receipts[name]), 'consumed original credential roundtrips lost'
  1310. assert self.clock.wait(1) > 0 and self.error is None and self.session.error is None, 'held ACK deadline/first error'
  1311. assert packet not in self.pending_acks, 'duplicate ACK authority'
  1312. fd_entry = None
  1313. if phase == 'entry' and syscall in ('close','close_range','dup2','dup3'):
  1314. prefix = self.parser.pending.get(tid,'')
  1315. assert prefix.startswith(syscall+'(') and tid not in self.parser.acked_fd_entries, 'exact held FD entry ACK'
  1316. fd_entry = {'sequence':seq,'key':task['key'],'prefix':prefix,'table':table}
  1317. self.pending_acks[packet] = keys
  1318. assert self.observer_peer.send(b'ACK '+packet,socket.MSG_DONTWAIT) == len(packet)+4, 'exact held ACK write'
  1319. if fd_entry is not None: self.parser.acked_fd_entries[tid] = fd_entry
  1320. if conn is not None:
  1321. conn['acked'] = True # Publish only after the exact ACK is accepted by the channel.
  1322. capture.setdefault('busLifetimeReceipts',[]).append({'sequence':seq,'tidBirth':task['key'],
  1323. 'fd':conn['fd'],'socket':conn['socket'],'name':name,
  1324. 'controls':self.session.credential_receipts[name]})
  1325. self.parser.changed.notify_all()
  1326. except Exception as error:
  1327. self.session.publish_failure(error,refuse=False)
  1328. raise
  1329. except Exception as error:
  1330. self.refuse_held(error) # Store failure before releasing validation/send locks.
  1331. raise
  1332. except Exception as error:
  1333. self.refuse_held(error)
  1334. raise
  1335. def consume_trace(self, raw):
  1336. # Require syscall readiness.
  1337. self.parser.feed(raw)
  1338. def consume_debug(self, raw):
  1339. self.debug_bytes += len(raw)
  1340. assert self.debug_bytes <= 256*LIMIT, 'bounded strace diagnostic stream'
  1341. self.debug_fragment += raw
  1342. while b'\n' in self.debug_fragment:
  1343. rawline,self.debug_fragment = self.debug_fragment.split(b'\n',1)
  1344. assert len(rawline) <= 8192, 'strace diagnostic line bound'
  1345. line = rawline.decode('ascii','strict')
  1346. if 'ptrace_setoptions = ' in line:
  1347. self.options = int(line.rsplit(' = ',1)[1],16)
  1348. assert self.options == 0x5f, 'source follow-fork option set'
  1349. stop = re.search(r'\[wait\(0x[0-9a-f]+\) = (\d+)\].*EVENT_STOP \(128\)',line)
  1350. if stop: self.seize_stops.add(int(stop[1]))
  1351. startup = re.search(r'pid (\d+) has TCB_STARTUP, initializing it',line)
  1352. if startup: self.started_tids.add(int(startup[1]))
  1353. if 'detached' in line:
  1354. detach = re.search(r'Process (\d+) detached',line)
  1355. assert detach and int(detach[1]) in self.closing_tids, 'trace detached before native join'
  1356. assert not any(s in line for s in ('PTRACE_SEIZE doesn\'t work','setting opts ','Operation not permitted',
  1357. 'Permission denied','attach: ptrace(','unknown pid','No such process')), 'strace attach/fallback uncertainty'
  1358. assert len(self.debug_fragment) <= 8192, 'partial strace diagnostic budget'
  1359. def ready(self):
  1360. end = time.monotonic()+self.clock.wait(5)
  1361. while time.monotonic() < end:
  1362. assert self.error is None and self.child.poll() is None, self.error or 'tracer exited before readiness'
  1363. current = proc_identity(self.controller['pid'],self.controller)
  1364. assert current['ns'] == self.controller['ns'] and current['uids'] == current['gids'] == [1000]*4 and current['groups'] == []
  1365. tids = {int(p.name) for p in (pathlib.Path('/proc')/str(current['pid'])/'task').iterdir()}
  1366. traced = []
  1367. for tid in tids:
  1368. facts = proc_identity(tid)
  1369. if facts['tracer'] == self.tracer['pid']: traced.append(tid)
  1370. if self.options == 0x5f and tids <= self.seize_stops and tids <= self.started_tids and set(traced) == tids:
  1371. with self.parser.changed:
  1372. assert self.parser.changed.wait_for(lambda:self.error or all(
  1373. (tid,trace_task_identity(tid)['birth']) in self.acked_keys for tid in tids),
  1374. max(.001,end-time.monotonic())), 'derived held TEST ACK readiness deadline'
  1375. assert self.error is None, self.error
  1376. with self.parser.lock:
  1377. for tid in tids: self.parser.register(tid)
  1378. return
  1379. time.sleep(min(.01,max(0,end-time.monotonic())))
  1380. raise IncompleteInstalledContract('no complete source-qualified SEIZE/TID readiness; native not launched')
  1381. def select_leader(self, local, end):
  1382. assert self.error is None and self.child.poll() is None
  1383. matches = []
  1384. for task in list(self.parser.tasks.values()):
  1385. f = task['facts']
  1386. if f['birth'] == local['birth'] and f['nspid'][-1] == local['pid'] and f['tgid'] == f['pid']:
  1387. matches.append(task)
  1388. assert len(matches) == 1, 'exact trace/native leader mapping missing'
  1389. task = matches[0]
  1390. for attempt in range(1000):
  1391. assert self.error is None and self.child.poll() is None
  1392. assert time.monotonic() < end, 'trace/native leader synchronization deadline'
  1393. try:
  1394. actual = proc_identity(task['facts']['pid'],task['facts'],leader_parent=self.controller['pid'])
  1395. break
  1396. except ProcessObservationRace:
  1397. if attempt == 999: raise
  1398. time.sleep(min(.001,max(0,end-time.monotonic())))
  1399. assert time.monotonic() < end, 'trace/native leader synchronization deadline'
  1400. assert actual['ppid'] == self.controller['pid'] and actual['ns'] == local['ns']
  1401. assert actual['pgid'] == actual['sid'] == actual['pid']
  1402. with self.parser.changed:
  1403. assert self.error is None and self.session.error is None, self.error or self.session.error
  1404. fresh = trace_task_identity(actual['pid'])
  1405. assert fresh == {field:actual[field] for field in fresh}, 'selected leader metadata bookend'
  1406. assert all(fresh[field] == task['facts'][field] for field in fresh if field not in ('pgid','sid')), 'selected leader immutable metadata drift'
  1407. assert time.monotonic() < end, 'trace/native leader synchronization deadline'
  1408. task['facts'].update(pgid=fresh['pgid'],sid=fresh['sid'])
  1409. task['nativeLeader'] = True
  1410. return actual
  1411. def begin_phase(self):
  1412. assert self.error is None and self.child.poll() is None
  1413. tids = {int(p.name) for p in (pathlib.Path('/proc')/str(self.controller['pid'])/'task').iterdir()}
  1414. with self.parser.lock:
  1415. assert set(self.parser.pending) <= tids, 'previous native exit stream incomplete'
  1416. for tid, task in list(self.parser.tasks.items()):
  1417. if tid not in tids:
  1418. assert task.get('exited'), 'previous native/control trace task not terminal'
  1419. del self.parser.tasks[tid]
  1420. def phase(self, local_leader, cleanup_signal, cleanup_roles):
  1421. assert self.error is None and self.child.poll() is None, self.error
  1422. with self.parser.lock:
  1423. captures = [c for c in self.parser.selected if c['leader'][1] == local_leader['birth']]
  1424. assert len(captures) == 1 and captures[0]['exited'] and captures[0]['eof'], 'actual native helper capture absent/incomplete'
  1425. capture = captures[0]
  1426. terminal = [task for task in self.parser.tasks.values() if task.get('terminalCancellation',{}).get('leader') == capture['leader']]
  1427. approved = {(row['pid'],row['startTicks']) for row in cleanup_roles if row.get('workerServerArgvMatches') is True and row.get('executableIsPinnedNode') is True and row.get('cwdMatches') is True and row.get('uid') == 1000}
  1428. for task in terminal:
  1429. worker = self.parser.tasks[task['terminalCancellation']['worker'][0]]
  1430. assert worker['key'] == task['terminalCancellation']['worker'], 'terminal worker PID reuse'
  1431. assert cleanup_signal is True and (worker['facts']['nspid'][-1],worker['key'][1]) in approved, 'SIGTERM lacks exact original approved worker cleanup'
  1432. capture['ownedTerminalCancellations'] = [task['terminalCancellation'] for task in terminal]
  1433. assert capture['reading'] is None
  1434. raw = bytes(capture['bytes']); facts = captured_stop_bytes(raw)
  1435. return capture,raw,facts
  1436. def force_contain(self, error):
  1437. """Refuse, kill qualified owned PID1, let C reap, then prove absence.
  1438. No supervisor join is a prerequisite for terminal ptrace reaping.
  1439. An unreaped own Popen is provisional custody, never task admission;
  1440. it is waited, never killed while tracees might survive.
  1441. """
  1442. self.refuse_held(error)
  1443. self.stopping = True
  1444. end = self.clock.outer+5 # Existing forced T0+115 ceiling, not a reset.
  1445. assert self.controller['nspid'][-1] == 1, 'containment requires owned namespace PID1'
  1446. assert self.controller['ns']['pid'] != os.readlink('/proc/self/ns/pid'), 'refuse containing own/foreign namespace'
  1447. try:
  1448. raw = (pathlib.Path('/proc')/str(self.controller['pid'])/'stat').read_text()
  1449. except FileNotFoundError: raw = None
  1450. if raw is not None:
  1451. tail = raw[raw.rindex(')')+2:].split()
  1452. assert int(tail[19]) == self.controller['birth'], 'controller containment refuses PID reuse'
  1453. if tail[0] not in ('Z','X','x'):
  1454. actual = trace_task_identity(self.controller['pid'])
  1455. for field in ('pid','birth','ppid','tgid','uids','gids','groups','nspid','ns','uidMap','gidMap'):
  1456. assert actual[field] == self.controller[field], 'owned controller containment authority'
  1457. tracer_pid = self.child.pid if self.owned_children else 0
  1458. assert actual['tracer'] in (0,tracer_pid), 'foreign controller tracer at containment'
  1459. assert trace_task_identity(actual['pid']) == actual, 'fresh PID1 containment bookend'
  1460. os.kill(actual['pid'],signal.SIGKILL)
  1461. self.fatal_containment_requested = True
  1462. # C's refusing guard consumes real irreversible exit events and final
  1463. # waits. Wait for that completion before PID1/supervisor joins. Neither
  1464. # a dispatched SIGKILL nor an empty/unconstructed parser authorizes
  1465. # ending the tracer. Failed waits retain its streams and descriptors.
  1466. for child in self.owned_children:
  1467. child.wait(timeout=max(.001,end-time.monotonic()))
  1468. while True:
  1469. survivors = []
  1470. for process in pathlib.Path('/proc').iterdir():
  1471. if not process.name.isdecimal(): continue
  1472. try: tids = list((process/'task').iterdir())
  1473. except (FileNotFoundError,ProcessLookupError): continue
  1474. for entry in tids:
  1475. try: same = os.readlink(entry/'ns/pid') == self.controller['ns']['pid']
  1476. except (FileNotFoundError,ProcessLookupError): continue
  1477. if same: survivors.append(int(entry.name))
  1478. if not survivors: break
  1479. assert time.monotonic() < end, 'owned namespace survives terminal ptrace reap'
  1480. time.sleep(min(.005,max(0,end-time.monotonic())))
  1481. self.terminal_contained = True
  1482. def failure_join(self, end):
  1483. """After terminal ptrace completion; the owner separately joins PID1's supervisor.
  1484. Containment is failure evidence. Neither channel EOF nor ESRCH is a
  1485. successful ACK or natural join; a foreign/reused birth refuses cleanup.
  1486. """
  1487. error = self.first_error or AssertionError('owned forced namespace containment')
  1488. self.refuse_held(error)
  1489. self.stopping = True
  1490. failures = []
  1491. if not getattr(self,'terminal_contained',False):
  1492. failures.append(AssertionError('terminal namespace containment unproved'))
  1493. keys = set(getattr(self,'custody_keys',()))
  1494. if hasattr(self,'parser'):
  1495. with self.parser.changed:
  1496. keys.update(t['key'] for t in self.parser.tasks.values())
  1497. keys.update(self.parser.remap_history)
  1498. self.parser.changed.notify_all()
  1499. for tid,birth in keys:
  1500. try:
  1501. path = pathlib.Path('/proc')/str(tid)
  1502. if path.exists():
  1503. raw = (path/'stat').read_text(); tail = raw[raw.rindex(')')+2:].split()
  1504. assert int(tail[19]) == birth, 'failure join refuses reused PID'
  1505. raise AssertionError('owned namespace task survives terminal ptrace completion')
  1506. except Exception as failure: failures.append(failure)
  1507. for child in self.owned_children:
  1508. try: child.wait(timeout=max(.001,end-time.monotonic()))
  1509. except Exception as failure: failures.append(failure)
  1510. # A failed terminal wait cannot be compensated by closing live tracer
  1511. # pipes or killing it. Preserve uncertain owned custody for the owner.
  1512. if any(child.poll() is None for child in self.owned_children):
  1513. raise failures[0] if failures else AssertionError('live tracer terminal teardown unresolved')
  1514. for fd in tuple(self.owned_fds):
  1515. try: os.close(fd); self.owned_fds.remove(fd)
  1516. except OSError as failure: failures.append(failure)
  1517. streams = self.owned_streams+[s for child in self.owned_children
  1518. for s in (child.stdin,child.stdout,child.stderr) if s is not None]
  1519. for stream in streams:
  1520. try: stream.close()
  1521. except Exception as failure: failures.append(failure)
  1522. for worker in getattr(self,'threads',[])+getattr(self,'held_workers',[]):
  1523. try:
  1524. if worker.ident is not None: worker.join(timeout=max(0,end-time.monotonic()))
  1525. assert not worker.is_alive(), 'owned failed observer worker join deadline'
  1526. except Exception as failure: failures.append(failure)
  1527. if failures: raise failures[0]
  1528. (self.root/'evidence/trace-failure-join.json').write_text(json.dumps({
  1529. 'firstFailure':self.error,'forcedContainment':getattr(self,'fatal_containment_requested',False),
  1530. 'terminalFailureCleanup':True,'naturalCompletion':False,
  1531. 'ownedBirthsAbsent':sorted(keys),'tracerExit':self.child.returncode if self.owned_children else None,
  1532. 'allObserverWorkersJoined':True},indent=2)+'\n')
  1533. def close(self):
  1534. began = time.monotonic(); end = self.clock.cleanup_deadline()
  1535. # Native-empty P1: C TIDs.
  1536. cpid = self.controller['pid']
  1537. for p in pathlib.Path('/proc').iterdir():
  1538. if not p.name.isdecimal(): continue
  1539. try: same = os.readlink(p/'ns/pid') == self.controller['ns']['pid']
  1540. except FileNotFoundError: continue
  1541. if same: assert int(p.name) == cpid, 'native descendants survive before trace join'
  1542. proc_identity(self.child.pid,self.tracer)
  1543. with self.parser.changed:
  1544. assert not self.pending_acks and all(not t.is_alive() for t in self.held_workers), 'held ACK/credential joins incomplete'
  1545. self.stopping = True
  1546. self.closing_tids = {int(p.name) for p in (pathlib.Path('/proc')/str(cpid)/'task').iterdir()}
  1547. os.kill(self.child.pid,signal.SIGINT)
  1548. self.child.wait(timeout=min(self.clock.wait(2,cleanup=True),max(.001,end-time.monotonic())))
  1549. self.observer_peer.close()
  1550. for t in self.threads+self.held_workers: t.join(timeout=max(0,end-time.monotonic()))
  1551. assert all(not t.is_alive() for t in self.threads+self.held_workers) and self.error is None, 'trace pump/join failure'
  1552. with self.parser.lock:
  1553. assert set(self.parser.pending) <= self.closing_tids, 'unjoined native unfinished syscall'
  1554. assert set(self.parser.pending_reads) <= self.closing_tids, 'unjoined native pending read'
  1555. self.parser.pending_reads.clear()
  1556. self.parser.pending.clear() # C's blocked control read ends on this intentional detach.
  1557. self.parser.finish()
  1558. self.clock.charge_cleanup(began)
  1559. def dbus_types(signature):
  1560. assert type(signature) is str and len(signature) <= 255, 'DBus signature budget'
  1561. def parse(at, depth, dictionary=False):
  1562. assert depth <= 16 and at < len(signature), 'DBus signature truncation/depth'
  1563. ch = signature[at]
  1564. if ch in 'ybnqiuxtdhsogv': return ch, at+1
  1565. if ch == 'a':
  1566. item, end = parse(at+1,depth+1,True)
  1567. return ('a',item), end
  1568. assert ch == '(' or ch == '{' and dictionary, 'unsupported DBus signature'
  1569. closing = ')' if ch == '(' else '}'
  1570. values = []; at += 1
  1571. while at < len(signature) and signature[at] != closing:
  1572. value, at = parse(at,depth+1)
  1573. values.append(value)
  1574. assert len(values) <= 32, 'DBus struct signature budget'
  1575. assert at < len(signature) and values, 'unclosed/empty DBus struct'
  1576. if ch == '{':
  1577. assert len(values) == 2 and type(values[0]) is str and values[0] in 'ybnqiuxtdhsog', 'DBus dictionary key'
  1578. return (ch,tuple(values)), at+1
  1579. values = []; at = 0
  1580. while at < len(signature):
  1581. value, at = parse(at,0)
  1582. values.append(value)
  1583. return values
  1584. class DBusValueReader:
  1585. def __init__(self, raw, endian, at=0, end=None):
  1586. self.raw, self.endian, self.at = raw, endian, at
  1587. self.end = len(raw) if end is None else end
  1588. self.entries = 0
  1589. def align(self, n):
  1590. end = (self.at+n-1)//n*n
  1591. assert end <= self.end and not any(self.raw[self.at:end]), 'DBus alignment/padding'
  1592. self.at = end
  1593. def take(self, n):
  1594. assert 0 <= n <= self.end-self.at, 'partial DBus value'
  1595. value = self.raw[self.at:self.at+n]; self.at += n
  1596. return value
  1597. def number(self, fmt, align):
  1598. self.align(align)
  1599. return struct.unpack(self.endian+fmt,self.take(struct.calcsize(fmt)))[0]
  1600. def value(self, typ, depth=0):
  1601. self.entries += 1
  1602. assert self.entries <= 4096 and depth <= 16, 'DBus entry/depth bounds'
  1603. if type(typ) is str:
  1604. if typ in 'ybnqiuxtdh':
  1605. fmt, alignment = {'y':('B',1),'b':('I',4),'n':('h',2),'q':('H',2),
  1606. 'i':('i',4),'u':('I',4),'x':('q',8),'t':('Q',8),'d':('d',8),'h':('I',4)}[typ]
  1607. value = self.number(fmt,alignment)
  1608. if typ == 'b':
  1609. assert value in (0,1), 'invalid DBus boolean'
  1610. return bool(value)
  1611. return value
  1612. if typ in 'sog':
  1613. size = self.number('B',1) if typ == 'g' else self.number('I',4)
  1614. assert size <= 65536, 'DBus string bound'
  1615. raw = self.take(size)
  1616. assert b'\0' not in raw and self.take(1) == b'\0', 'DBus string terminator'
  1617. value = raw.decode('ascii' if typ == 'g' else 'utf-8','strict')
  1618. if typ == 'g': dbus_types(value)
  1619. if typ == 'o': assert value.startswith('/') and (value == '/' or all(re.fullmatch(r'[A-Za-z0-9_]+',p) for p in value[1:].split('/'))), 'DBus object path'
  1620. return value
  1621. assert typ == 'v', 'unsupported DBus basic type'
  1622. signature = self.value('g',depth+1); types_ = dbus_types(signature)
  1623. assert len(types_) == 1, 'DBus variant must have one type'
  1624. return {'signature':signature,'value':self.value(types_[0],depth+1)}
  1625. kind, items = typ
  1626. if kind == 'a':
  1627. size = self.number('I',4)
  1628. assert size <= LIMIT, 'DBus array bound'
  1629. alignment = dbus_alignment(items); self.align(alignment)
  1630. end = self.at+size; assert end <= self.end, 'partial DBus array'
  1631. old_end = self.end; self.end = end
  1632. values = []
  1633. while self.at < end:
  1634. values.append(self.value(items,depth+1))
  1635. assert len(values) <= 1024, 'DBus array entry bound'
  1636. self.end = old_end
  1637. if type(items) is tuple and items[0] == '{':
  1638. result = {}
  1639. for key,value in values:
  1640. assert key not in result, 'duplicate DBus dictionary key'
  1641. result[key] = value
  1642. return result
  1643. return values
  1644. assert kind in ('(','{'), 'unsupported DBus composite'
  1645. self.align(8)
  1646. return tuple(self.value(item,depth+1) for item in items)
  1647. def dbus_alignment(typ):
  1648. if type(typ) is tuple: return 4 if typ[0] == 'a' else 8
  1649. return {'y':1,'b':4,'n':2,'q':2,'i':4,'u':4,'x':8,'t':8,'d':8,'h':4,'s':4,'o':4,'g':1,'v':1}[typ]
  1650. class DBusBinaryStream:
  1651. """dbus-monitor --binary emits ordinary messages, without PCAP headers."""
  1652. def __init__(self, consume):
  1653. self.consume = consume
  1654. self.raw = b''
  1655. self.total = self.count = 0
  1656. def feed(self, chunk):
  1657. self.total += len(chunk)
  1658. assert self.total <= 16*LIMIT, 'complete DBus monitor stream bound'
  1659. self.raw += chunk
  1660. while len(self.raw) >= 16:
  1661. assert self.raw[0] in (ord('l'),ord('B')), 'DBus byte order'
  1662. endian = '<' if self.raw[0] == ord('l') else '>'
  1663. typ, flags, version = self.raw[1:4]
  1664. bodylen, serial, headers = struct.unpack(endian+'III',self.raw[4:16])
  1665. assert 1 <= typ <= 4 and flags & ~7 == 0 and version == 1 and serial > 0, 'DBus fixed header'
  1666. assert bodylen <= LIMIT and headers <= 65536, 'DBus frame budget'
  1667. start = (16+headers+7)//8*8; length = start+bodylen
  1668. if len(self.raw) < length: break
  1669. raw, self.raw = self.raw[:length],self.raw[length:]
  1670. reader = DBusValueReader(raw,endian,12,16+headers)
  1671. fields = reader.value(('a',('(',('y','v'))))
  1672. assert reader.at == 16+headers, 'DBus header boundary'
  1673. header = {}
  1674. expected = {1:'o',2:'s',3:'s',4:'s',5:'u',6:'s',7:'s',8:'g',9:'u'}
  1675. for code, variant in fields:
  1676. assert code in expected and code not in header and variant['signature'] == expected[code], 'unknown/duplicate DBus header field'
  1677. header[code] = variant['value']
  1678. assert not any(raw[16+headers:start]), 'DBus body alignment'
  1679. if typ == 1: assert {1,3} <= set(header), 'DBus method-call headers'
  1680. if typ in (2,3): assert 5 in header and header[5] > 0, 'DBus reply serial'
  1681. if typ == 3: assert 4 in header, 'DBus error header'
  1682. if typ == 4: assert {1,2,3} <= set(header), 'DBus signal headers'
  1683. signature = header.get(8,'')
  1684. body_reader = DBusValueReader(raw,endian,start)
  1685. values = [body_reader.value(t) for t in dbus_types(signature)]
  1686. assert body_reader.at == length, 'DBus trailing body bytes/signature mismatch'
  1687. self.count += 1; assert self.count <= 4096, 'DBus message count'
  1688. self.consume({'type':typ,'serial':serial,'header':header,'signature':signature,'body':values})
  1689. assert len(self.raw) <= LIMIT+65552, 'DBus partial frame bound'
  1690. def finish(self):
  1691. assert not self.raw, 'partial DBus monitor frame at join'
  1692. class NotificationsExchange:
  1693. """Pure matching logic. Identity/GUID are established by the real session."""
  1694. def __init__(self, owner):
  1695. assert re.fullmatch(r':\d+\.\d+',owner), 'actual Notifications unique owner required'
  1696. self.owner = owner
  1697. self.pending = {}
  1698. self.ready = set()
  1699. self.receipts = []
  1700. def call(self, message, helper_name):
  1701. h = message['header']
  1702. assert message['type'] == 1 and h.get(7) == helper_name, 'wrong helper sender'
  1703. method = h.get(3)
  1704. if method == 'NameHasOwner':
  1705. assert h.get(6) == 'org.freedesktop.DBus' and h.get(2) == 'org.freedesktop.DBus' and h.get(1) == '/org/freedesktop/DBus'
  1706. assert message['signature'] == 's' and message['body'] == ['org.freedesktop.Notifications']
  1707. else:
  1708. assert method in ('GetCapabilities','Notify') and h.get(6) in ('org.freedesktop.Notifications',self.owner)
  1709. assert h.get(2) == 'org.freedesktop.Notifications' and h.get(1) == '/org/freedesktop/Notifications'
  1710. if method == 'GetCapabilities': assert message['signature'] == '' and message['body'] == []
  1711. if method == 'Notify':
  1712. assert (helper_name,'NameHasOwner') in self.ready and (helper_name,'GetCapabilities') in self.ready, 'Notify before real readiness replies'
  1713. assert message['signature'] == 'susssasa{sv}i', 'Notify argument signature'
  1714. b = message['body']
  1715. assert len(b) == 8 and b[:6] == ['agent-notifications',0,'','Cursor CLI','Cursor CLI is stopping',[]], 'Notify actual source arguments'
  1716. assert b[6] == {'suppress-sound':{'signature':'b','value':True}} and type(b[7]) is int and 1 <= b[7] <= 15000
  1717. key = (helper_name,message['serial'])
  1718. assert key not in self.pending, 'duplicate DBus call serial'
  1719. self.pending[key] = {'method':method,'call':message}
  1720. def reply(self, message):
  1721. h = message['header']; key = (h.get(6),h.get(5))
  1722. assert key in self.pending, 'wrong reply serial/destination'
  1723. pending = self.pending.pop(key); method = pending['method']
  1724. assert message['type'] == 2, 'DBus ERROR/partial/missing reply is uncertainty'
  1725. sender = 'org.freedesktop.DBus' if method == 'NameHasOwner' else self.owner
  1726. assert h.get(7) == sender, 'reply from foreign/replaced Notifications owner'
  1727. if method == 'NameHasOwner': assert message['signature'] == 'b' and message['body'] == [True], 'NameHasOwner not true'
  1728. if method == 'GetCapabilities':
  1729. assert message['signature'] == 'as' and len(message['body']) == 1 and type(message['body'][0]) is list
  1730. assert all(type(s) is str for s in message['body'][0]), 'invalid GetCapabilities reply'
  1731. if method == 'Notify':
  1732. assert message['signature'] == 'u' and len(message['body']) == 1 and type(message['body'][0]) is int and 0 <= message['body'][0] <= 4294967295, 'missing actual uint32 notification ID'
  1733. self.receipts.append({'sender':key[0],'callSerial':key[1],'notificationID':message['body'][0],
  1734. 'call':pending['call'],'reply':message})
  1735. else: self.ready.add((key[0],method))
  1736. def finish(self):
  1737. assert not self.pending, 'missing notification readiness/submission reply'
  1738. class OwnedNotificationsSession:
  1739. """Standard services in P0/N1/U0; no process enters the native PID namespace."""
  1740. def __init__(self, controller, root, clock, tools, display_number):
  1741. self.controller, self.root, self.clock, self.tools = controller,pathlib.Path(root),clock,tools
  1742. self.error = None
  1743. self.processes = []
  1744. self.control_processes = []
  1745. self.pumps = []
  1746. self.messages = []
  1747. self.control_names = set()
  1748. self.credentials = {}
  1749. self.rpc_lock = threading.RLock()
  1750. self.records_lock = threading.RLock()
  1751. self.records_changed = threading.Condition(self.records_lock)
  1752. self.first_error = None
  1753. self.trace = None
  1754. self.trace_failure = None
  1755. self.credential_receipts = {}
  1756. self.active_names = set()
  1757. self.exchange = None
  1758. self.closing = False
  1759. self.owned_fds = set()
  1760. try:
  1761. self._construct(controller,root,clock,tools,display_number)
  1762. except BaseException as error:
  1763. self.publish_failure(error)
  1764. try: self.failure_join(clock.outer+5)
  1765. except BaseException as cleanup_error:
  1766. error.add_note('session constructor cleanup unproved: '+type(cleanup_error).__name__)
  1767. raise self.first_error
  1768. def _construct(self, controller, root, clock, tools, display_number):
  1769. self.netfd = os.open('/proc/'+str(controller['pid'])+'/ns/net',os.O_RDONLY)
  1770. self.owned_fds.add(self.netfd)
  1771. assert 'net:['+str(os.fstat(self.netfd).st_ino)+']' == controller['ns']['net'], 'pinned C netns handle'
  1772. self.directory = self.root/'session'
  1773. self.directory.mkdir(mode=0o700)
  1774. os.chown(self.directory,1000,1000)
  1775. self.address = 'unix:path='+str(self.directory/'bus')
  1776. assert type(display_number) is int and 90 <= display_number <= 4096
  1777. self.display = ':'+str(display_number)
  1778. self.xsocket = pathlib.Path('/tmp/.X11-unix')/('X'+str(display_number))
  1779. self.xlock = pathlib.Path('/tmp')/('.X'+str(display_number)+'-lock')
  1780. assert not self.xsocket.exists() and not self.xlock.exists(), 'accepted display already in use; no retry'
  1781. self.xauthority = self.directory/'Xauthority'
  1782. self.env = {'HOME':str(self.root/'home'),'XDG_CONFIG_HOME':str(self.root/'home/.config'),
  1783. 'XDG_CACHE_HOME':str(self.root/'cache'),'TMPDIR':str(self.root/'tmp'),
  1784. 'PATH':'/usr/bin:/bin','LANG':'C.UTF-8','DBUS_SESSION_BUS_ADDRESS':self.address,
  1785. 'DISPLAY':self.display,'XAUTHORITY':str(self.xauthority)}
  1786. cookie = os.urandom(16).hex() # TEST display cookie, never an ambient credential.
  1787. self.command('xauth',['-f',str(self.xauthority)],input=f'add {self.display} MIT-MAGIC-COOKIE-1 {cookie}\n'.encode('ascii'))
  1788. self.display_process = self.start('Xvfb',[self.display,'-screen','0','800x600x24','-nolisten','tcp','-auth',str(self.xauthority)])
  1789. self.bus = self.start('dbus-daemon',['--session','--nofork','--nopidfile','--address='+self.address,'--print-address=1'])
  1790. self.wait(lambda:(self.directory/'bus').exists(),5)
  1791. sock = (self.directory/'bus').lstat()
  1792. assert stat.S_ISSOCK(sock.st_mode) and sock.st_uid == sock.st_gid == 1000, 'owned TEST bus socket'
  1793. self.socket_identity = {'inode':sock.st_ino,'device':sock.st_dev,'mode':sock.st_mode,'uid':sock.st_uid,'gid':sock.st_gid}
  1794. self.monitor = self.start('dbus-monitor',['--address',self.address,'--binary'],binary=True)
  1795. self.stream = DBusBinaryStream(self.message)
  1796. self.monitor_pump = threading.Thread(target=self.monitor_read,daemon=True)
  1797. self.monitor_pump.start()
  1798. self.wait(lambda:self.xsocket.exists() and self.xlock.exists(),5)
  1799. xs = self.xsocket.lstat(); xl = self.xlock.lstat()
  1800. assert stat.S_ISSOCK(xs.st_mode) and xs.st_uid == xs.st_gid == 1000 and xl.st_uid == xl.st_gid == 1000
  1801. self.display_identity = {'socket':{'inode':xs.st_ino,'device':xs.st_dev,'mode':xs.st_mode},
  1802. 'lock':{'inode':xl.st_ino,'device':xl.st_dev,'mode':xl.st_mode}}
  1803. self.dunst = self.start('dunst',['-config','/dev/null'])
  1804. # Dunst owner first.
  1805. self.wait(lambda:any(m['type'] == 4 and m['header'].get(3) == 'NameOwnerChanged' and
  1806. m['body'][:1] == ['org.freedesktop.Notifications'] and len(m['body']) == 3 and m['body'][2]
  1807. for m in self.messages),5)
  1808. self.guid,self.guid_call = self.rpc('org.freedesktop.DBus.GetId',[], 's')
  1809. assert re.fullmatch(r'[0-9a-f]{32}',self.guid), 'actual owned bus GUID'
  1810. self.owner,self.owner_call = self.rpc('org.freedesktop.DBus.GetNameOwner',['string:org.freedesktop.Notifications'],'s')
  1811. self.exchange = NotificationsExchange(self.owner)
  1812. pid,_ = self.rpc('org.freedesktop.DBus.GetConnectionUnixProcessID',['string:'+self.owner],'u')
  1813. uid,_ = self.rpc('org.freedesktop.DBus.GetConnectionUnixUser',['string:'+self.owner],'u')
  1814. assert pid == self.dunst['identity']['pid'] and uid == 1000, 'real Notifications owner/daemon PID'
  1815. self.credentials[self.owner] = proc_identity(pid,self.dunst['identity'])
  1816. exists, name_call = self.rpc('org.freedesktop.DBus.NameHasOwner',['string:org.freedesktop.Notifications'],'b')
  1817. assert exists is True
  1818. capabilities, caps_call = self.rpc('org.freedesktop.Notifications.GetCapabilities',[], 'as',notifications=True)
  1819. assert type(capabilities) is list and all(type(c) is str for c in capabilities)
  1820. # Monitor roundtrips.
  1821. for call in (self.guid_call,self.owner_call,name_call,caps_call): self.observed_roundtrip(call)
  1822. self.assert_continuous()
  1823. (self.root/'evidence/session-readiness.json').write_text(json.dumps({
  1824. 'busGUID':self.guid,'notificationsOwner':self.owner,'daemon':self.dunst['identity'],
  1825. 'socket':self.socket_identity,'display':self.display,'displayIdentity':self.display_identity,
  1826. 'processes':[p['identity'] for p in self.processes],'tools':tools,
  1827. 'actualControlRoundtrips':[self.guid_call,self.owner_call,name_call,caps_call],
  1828. 'GUIVisibility':'NOT_RUN'},indent=2)+'\n')
  1829. def argv(self, name, args):
  1830. return [self.tools['nsenter']['path'],'--net=/proc/self/fd/'+str(self.netfd),
  1831. self.tools['setpriv']['path'],'--reuid=1000','--regid=1000','--clear-groups',
  1832. self.tools[name]['path'],*args]
  1833. def wait(self, predicate, cap):
  1834. end = time.monotonic()+self.clock.wait(cap)
  1835. while not predicate():
  1836. assert self.error is None, self.error
  1837. for p in self.processes: assert p['child'].poll() is None, 'owned standard session process exited'
  1838. assert time.monotonic() < end, 'session/readiness absolute deadline'
  1839. time.sleep(min(.01,max(0,end-time.monotonic())))
  1840. def live(self, child, name, args, identity, end):
  1841. while time.monotonic() < end:
  1842. assert child.poll() is None, 'standard process failed before identity'
  1843. if os.readlink(pathlib.Path('/proc')/str(child.pid)/'exe') != self.tools[name]['path']:
  1844. time.sleep(min(.001,max(0,end-time.monotonic())))
  1845. continue
  1846. facts = proc_identity(child.pid,identity,startup=True)
  1847. if facts is None:
  1848. time.sleep(min(.001,max(0,end-time.monotonic())))
  1849. continue
  1850. if facts['exe'] == self.tools[name]['path']:
  1851. if facts['argv'] != [self.tools[name]['path'],*args]:
  1852. print('standard-argv-rejected', child.pid, facts['birth'], facts['exe'], facts['uids'],
  1853. len(facts['argv']), [v[:120] for v in facts['argv'][:2]],
  1854. len(args)+1, [v[:120] for v in [self.tools[name]['path'],*args[:1]]], file=sys.stderr, flush=True)
  1855. assert facts['argv'] == [self.tools[name]['path'],*args], 'actual standard process argv'
  1856. assert facts['uids'] == facts['gids'] == [1000]*4 and facts['groups'] == []
  1857. assert facts['ns']['pid'] == os.readlink('/proc/self/ns/pid') and facts['ns']['pid'] != self.controller['ns']['pid']
  1858. assert facts['ns']['net'] == self.controller['ns']['net'] and facts['ns']['user'] == self.controller['ns']['user']
  1859. assert facts['uidMap'] == self.controller['uidMap'] and facts['gidMap'] == self.controller['gidMap']
  1860. assert facts['ppid'] == os.getpid(), 'outer service ownership'
  1861. assert digest(facts['exe']) == self.tools[name]['sha256']
  1862. return facts
  1863. time.sleep(min(.001,max(0,end-time.monotonic())))
  1864. raise IncompleteInstalledContract('standard session identity not established')
  1865. def diagnostic_pump(self, pipe, path):
  1866. def drain():
  1867. try:
  1868. with path.open('xb') as f:
  1869. size = 0
  1870. while True:
  1871. chunk = pipe.read(8192)
  1872. if not chunk: break
  1873. size += len(chunk); assert size <= LIMIT, 'session diagnostic bytes'
  1874. f.write(chunk)
  1875. except Exception as error: self.publish_failure(error)
  1876. finally:
  1877. try: pipe.close()
  1878. except Exception as error: self.publish_failure(error)
  1879. t = threading.Thread(target=drain,daemon=True); self.pumps.append(t); t.start()
  1880. def start(self, name, args, binary=False):
  1881. assert self.error is None and not self.closing, self.error or 'session closing'
  1882. end = time.monotonic()+self.clock.wait(1)
  1883. child = subprocess.Popen(self.argv(name,args),stdin=subprocess.DEVNULL,stdout=subprocess.PIPE,stderr=subprocess.PIPE,
  1884. pass_fds=(self.netfd,),env=self.env,cwd=self.root/'workspace',start_new_session=True,bufsize=0)
  1885. # Pre-exec birth/ppid/sid.
  1886. record = {'name':name,'child':child,'identity':None,'admitted':False}
  1887. self.processes.append(record)
  1888. assert self.error is None and not self.closing, self.error or 'session closing'
  1889. record['identity'] = startup_identity(child.pid)
  1890. self.diagnostic_pump(child.stderr,self.root/'evidence'/('session-'+name+'.stderr'))
  1891. facts = self.live(child,name,args,record['identity'],end)
  1892. assert facts['birth'] == record['identity']['birth'], 'standard process birth changed across exec'
  1893. record['identity'] = facts
  1894. record['admitted'] = True
  1895. if not binary: self.diagnostic_pump(child.stdout,self.root/'evidence'/('session-'+name+'.stdout'))
  1896. return record
  1897. def command(self, name, args, input=None):
  1898. held = name == 'dbus-send'
  1899. try:
  1900. assert self.error is None and not self.closing, self.error or 'session closing'
  1901. if held:
  1902. assert proc_identity(self.bus['identity']['pid'],self.bus['identity']) == self.bus['identity'], 'owned bus changed before hold'
  1903. os.kill(self.bus['identity']['pid'],signal.SIGSTOP)
  1904. self.wait(lambda:(pathlib.Path('/proc')/str(self.bus['identity']['pid'])/'stat').read_text().split(') ')[-1].split()[0] == 'T',1)
  1905. end = time.monotonic()+self.clock.wait(1)
  1906. child = subprocess.Popen(self.argv(name,args),stdin=subprocess.PIPE if input is not None else subprocess.DEVNULL,stdout=subprocess.PIPE,stderr=subprocess.PIPE,
  1907. pass_fds=(self.netfd,),env=self.env,cwd=self.root/'workspace',start_new_session=True)
  1908. record = {'name':name,'child':child,'identity':None,'admitted':False}
  1909. self.control_processes.append(record)
  1910. assert self.error is None and not self.closing, self.error or 'session closing'
  1911. record['identity'] = startup_identity(child.pid)
  1912. facts = self.live(child,name,args,record['identity'],end)
  1913. assert facts['birth'] == record['identity']['birth'], 'control process birth changed across exec'
  1914. record['identity'] = facts
  1915. record['admitted'] = True
  1916. except BaseException as error:
  1917. self.publish_failure(error)
  1918. raise
  1919. finally:
  1920. if held:
  1921. original = sys.exc_info()[1]
  1922. try:
  1923. assert proc_identity(self.bus['identity']['pid'],self.bus['identity']) == self.bus['identity'], 'owned bus changed before resume'
  1924. os.kill(self.bus['identity']['pid'],signal.SIGCONT)
  1925. except BaseException as error:
  1926. self.publish_failure(error)
  1927. if original is None: raise
  1928. original.add_note('bus hold cleanup unproved: '+type(error).__name__)
  1929. output,error = child.communicate(input=input,timeout=self.clock.wait(1))
  1930. assert child.returncode == 0 and len(output) <= 65536 and len(error) <= 65536, 'standard session control failed'
  1931. assert len(self.control_processes) <= 128, 'bounded separate control connection count'
  1932. (self.root/'evidence/session-controls.json').write_text(json.dumps([
  1933. {'name':p['name'],'identity':p['identity'],'exit':p['child'].returncode,
  1934. 'provenance':self.tools[p['name']]} for p in self.control_processes],indent=2)+'\n')
  1935. return output
  1936. def rpc(self, method, args, signature, notifications=False):
  1937. with self.rpc_lock:
  1938. name = 'org.freedesktop.Notifications' if notifications else 'org.freedesktop.DBus'
  1939. path = '/org/freedesktop/Notifications' if notifications else '/org/freedesktop/DBus'
  1940. reply_timeout = max(1,int(self.clock.wait(1)*1000))
  1941. stdout = self.command('dbus-send',['--bus='+self.address,'--type=method_call','--print-reply',
  1942. '--reply-timeout='+str(reply_timeout),'--dest='+name,path,method,*args]).decode('utf-8','strict')
  1943. lines = stdout.splitlines()
  1944. assert lines and lines[0].startswith('method return '), 'control DBus ERROR/unknown response'
  1945. match = re.search(r'sender=(\S+) -> destination=(:\d+\.\d+).*reply_serial=(\d+)',lines[0])
  1946. assert match, 'control reply headers'
  1947. sender,destination,serial = match[1],match[2],int(match[3])
  1948. self.control_names.add(destination)
  1949. assert sender == (self.owner if notifications else 'org.freedesktop.DBus'), 'control owner drift'
  1950. if signature == 's':
  1951. assert len(lines) == 2 and lines[1].strip().startswith('string ')
  1952. value = json.loads(lines[1].strip()[7:])
  1953. elif signature == 'u':
  1954. assert len(lines) == 2 and re.fullmatch(r'\s*uint32 \d+',lines[1])
  1955. value = int(lines[1].split()[1])
  1956. elif signature == 'b':
  1957. assert len(lines) == 2 and lines[1].strip() in ('boolean true','boolean false')
  1958. value = lines[1].strip() == 'boolean true'
  1959. else:
  1960. assert signature == 'as' and lines[1].strip() == 'array [' and lines[-1].strip() == ']'
  1961. value = []
  1962. for line in lines[2:-1]:
  1963. assert line.strip().startswith('string ')
  1964. value.append(json.loads(line.strip()[7:]))
  1965. return value,{'sender':destination,'callSerial':serial,'replySender':sender,'method':method,
  1966. 'arguments':list(args),'signature':signature,'value':value}
  1967. def roundtrip_present(self, control):
  1968. with self.records_lock:
  1969. calls = [m for m in self.messages if m['type'] == 1 and m['header'].get(7) == control['sender'] and m['serial'] == control['callSerial']]
  1970. replies = [m for m in self.messages if m['type'] in (2,3) and m['header'].get(6) == control['sender'] and m['header'].get(5) == control['callSerial']]
  1971. if not calls or not replies: return False
  1972. assert len(calls) == len(replies) == 1 and replies[0]['type'] == 2, 'monitor control reply ambiguity'
  1973. assert calls[0]['header'].get(3) == control['method'].rsplit('.',1)[1]
  1974. assert all(arg.startswith('string:') for arg in control['arguments']), 'closed original control argument types'
  1975. assert calls[0]['signature'] == 's'*len(control['arguments']) and calls[0]['body'] == [
  1976. arg.split(':',1)[1] for arg in control['arguments']], 'original monitored credential name arguments'
  1977. assert replies[0]['header'].get(7) == control['replySender']
  1978. assert replies[0]['signature'] == control['signature'] and replies[0]['body'] == [control['value']]
  1979. return True
  1980. def observed_roundtrip(self, control):
  1981. self.wait(lambda:self.roundtrip_present(control),1)
  1982. def held_credentials(self, capture, conn):
  1983. """Independent dispatcher; the monitor never waits for its own records."""
  1984. helper = capture['identity']
  1985. key = (helper['pid'],helper['birth'])
  1986. def ready():
  1987. if self.error is not None or self.trace_failure is not None:
  1988. raise AssertionError(self.error or self.trace_failure)
  1989. names = [name for name,facts in self.credentials.items() if name in self.active_names and (facts['pid'],facts['birth']) == key]
  1990. assert len(names) <= 1, 'ambiguous helper unique names'
  1991. if not names: return False
  1992. name = names[0]
  1993. receipts = self.credential_receipts.get(name)
  1994. if receipts is None or not all(self.roundtrip_present(call) for call in receipts): return False
  1995. hellos = [m for m in self.messages if m['type'] == 1 and m['header'].get(7) == name and
  1996. m['header'].get(2) == 'org.freedesktop.DBus' and m['header'].get(3) == 'Hello']
  1997. assert len(hellos) <= 1, 'ambiguous helper Hello'
  1998. if not hellos: return False
  1999. replies = [m for m in self.messages if m['type'] in (2,3) and m['header'].get(6) == name and m['header'].get(5) == hellos[0]['serial']]
  2000. if not replies: return False
  2001. assert len(replies) == 1 and replies[0]['type'] == 2 and replies[0]['signature'] == 's' and replies[0]['body'] == [name], 'failed/ambiguous Hello'
  2002. if conn['outcome'] is None: return False
  2003. assert conn['connected'], 'connect intent/outcome is not connection proof'
  2004. assert receipts[0]['value'] == helper['pid'] and receipts[1]['value'] == 1000, 'original credential RPC values'
  2005. assert [call['method'] for call in receipts] == ['org.freedesktop.DBus.GetConnectionUnixProcessID',
  2006. 'org.freedesktop.DBus.GetConnectionUnixUser'] and all(call['arguments'] == ['string:'+name]
  2007. for call in receipts), 'original credential RPC name/method incarnation'
  2008. return name
  2009. with self.records_changed:
  2010. assert self.records_changed.wait_for(ready,self.clock.wait(1)), 'held credential/monitor deadline'
  2011. name = ready()
  2012. peer = self.credentials[name]
  2013. # No trace/rpc/records lock spans a control RPC, Condition or channel wait.
  2014. self.assert_continuous()
  2015. current = proc_identity(helper['pid'],helper)
  2016. assert current == helper == peer and current['tracer'] == capture['identity']['tracer'], 'fresh exact selected bus peer'
  2017. assert len(capture['busConnections']) == 1 and capture['busConnections'][0] is conn, 'sole socket/name incarnation'
  2018. conn['name'] = name
  2019. return name
  2020. def message(self, message):
  2021. new_credential = None
  2022. h = message['header']
  2023. ownership = message['type'] == 4 and h.get(2) == 'org.freedesktop.DBus' and h.get(3) == 'NameOwnerChanged'
  2024. with self.records_changed:
  2025. # Publish the real departure and remove its ACK authority atomically.
  2026. # The separate credential RPC below never holds the records lock.
  2027. if ownership:
  2028. assert h.get(7) == 'org.freedesktop.DBus' and h.get(1) == '/org/freedesktop/DBus', 'actual bus name authority'
  2029. assert message['signature'] == 'sss' and len(message['body']) == 3
  2030. name,old,new = message['body']
  2031. if name.startswith(':'):
  2032. assert re.fullmatch(r':\d+\.\d+',name), 'actual unique bus name'
  2033. if old == '' and new == name: self.active_names.add(name)
  2034. elif old == name and new == '': self.active_names.discard(name)
  2035. else: raise AssertionError('unique bus name replacement')
  2036. self.messages.append(message)
  2037. assert len(self.messages) <= 4096 and len(json.dumps(self.messages)) <= 16*LIMIT, 'bounded TEST monitor records'
  2038. self.records_changed.notify_all()
  2039. if ownership:
  2040. if name == 'org.freedesktop.Notifications' and self.exchange is not None:
  2041. assert self.closing or old == '' and new == self.owner, 'Notifications owner loss/replacement'
  2042. if name.startswith(':') and old == '' and new == name:
  2043. with self.rpc_lock:
  2044. if name not in self.control_names:
  2045. pid,pid_call = self.rpc('org.freedesktop.DBus.GetConnectionUnixProcessID',['string:'+name],'u')
  2046. uid,uid_call = self.rpc('org.freedesktop.DBus.GetConnectionUnixUser',['string:'+name],'u')
  2047. assert uid == 1000, 'bus peer UID'
  2048. facts = proc_identity(pid)
  2049. assert facts['uids'] == facts['gids'] == [1000]*4 and facts['groups'] == []
  2050. assert facts['ns']['net'] == self.controller['ns']['net'] and facts['ns']['user'] == self.controller['ns']['user']
  2051. if facts['ns']['pid'] != self.controller['ns']['pid']:
  2052. assert any(p['admitted'] and p['identity']['pid'] == pid and p['identity']['birth'] == facts['birth'] for p in self.processes), 'unknown outer session peer'
  2053. else:
  2054. assert facts['argv'][1:4] == ['cursor-event','stop','--binding'] and len(facts['argv']) == 5, 'unknown native bus peer'
  2055. new_credential = (name,facts,(pid_call,uid_call))
  2056. if name in self.credentials and old == name and new == '' and self.exchange is not None:
  2057. assert not any(key[0] == name for key in self.exchange.pending), 'helper disconnect before matching reply'
  2058. if self.exchange is not None:
  2059. sender = h.get(7)
  2060. credential = self.credentials.get(sender)
  2061. if message['type'] == 1 and credential and credential['ns']['pid'] == self.controller['ns']['pid']:
  2062. self.exchange.call(message,sender)
  2063. if message['type'] in (2,3) and (h.get(6),h.get(5)) in self.exchange.pending:
  2064. self.exchange.reply(message)
  2065. with self.records_changed:
  2066. if new_credential is not None:
  2067. name,facts,receipts = new_credential
  2068. assert name in self.active_names and name not in self.credentials, 'credential callback name incarnation'
  2069. self.credentials[name] = facts
  2070. self.credential_receipts[name] = receipts
  2071. self.records_changed.notify_all()
  2072. def monitor_read(self):
  2073. try:
  2074. pipe = self.monitor['child'].stdout
  2075. while True:
  2076. raw = pipe.read(8192)
  2077. if not raw: break
  2078. self.stream.feed(raw)
  2079. self.stream.finish()
  2080. assert self.closing, 'monitor continuity ended early'
  2081. except Exception as error:
  2082. self.publish_failure(error)
  2083. finally:
  2084. try: self.monitor['child'].stdout.close()
  2085. except Exception as error: self.publish_failure(error)
  2086. def publish_failure(self, error, refuse=True):
  2087. # The final nonblocking ACK send uses this same short lock. Never
  2088. # acquire the parser lock here until publication releases it.
  2089. with self.records_changed:
  2090. if self.error is None:
  2091. self.first_error = error
  2092. self.error = type(error).__name__+':'+str(error)[:240]
  2093. first = self.first_error
  2094. self.records_changed.notify_all()
  2095. if refuse and self.trace is not None: self.trace.refuse_held(first)
  2096. return first
  2097. def failure_join(self, end):
  2098. self.closing = True
  2099. failures = []
  2100. # Let an already running bounded control finish registering its child.
  2101. # This is not the failure-publication/ACK lock, and is released before
  2102. # any Popen wait or reader join.
  2103. locked = self.rpc_lock.acquire(timeout=max(0,end-time.monotonic()))
  2104. try:
  2105. records = list(self.processes+self.control_processes)
  2106. if not locked: failures.append(AssertionError('owned control cleanup lock deadline'))
  2107. finally:
  2108. if locked: self.rpc_lock.release()
  2109. # These Popen records are own-child cleanup custody. Provisional
  2110. # records supply no proc, bus-peer or observer admission authority.
  2111. for record in records:
  2112. child = record['child']
  2113. if record['identity'] is not None and child.poll() is None:
  2114. try:
  2115. identity = record['identity']
  2116. assert child.pid == identity['pid'], 'owned cleanup Popen PID drift'
  2117. with (pathlib.Path('/proc')/str(child.pid)/'stat').open('rb') as held_stat: raw = held_stat.read(8193)
  2118. assert len(raw) <= 8192, 'owned cleanup stat budget'
  2119. text = raw.decode('ascii','strict'); tail = text[text.rindex(')')+2:].split()
  2120. assert int(text[:text.index('(')].strip()) == identity['pid'] and int(tail[19]) == identity['birth'], 'owned cleanup birth drift'
  2121. if tail[0] != 'Z':
  2122. if identity.get('startup') is True: startup_identity(child.pid,identity)
  2123. else: proc_identity(child.pid,identity)
  2124. except Exception as failure: failures.append(failure)
  2125. try:
  2126. child.kill()
  2127. child.wait(timeout=max(.001,end-time.monotonic()))
  2128. except Exception as failure: failures.append(failure)
  2129. finally:
  2130. for pipe in (child.stdin,child.stdout,child.stderr):
  2131. if pipe is not None:
  2132. try: pipe.close()
  2133. except Exception as failure: failures.append(failure)
  2134. for fd in tuple(self.owned_fds):
  2135. try: os.close(fd); self.owned_fds.remove(fd)
  2136. except OSError as failure: failures.append(failure)
  2137. workers = self.pumps+[self.monitor_pump] if hasattr(self,'monitor_pump') else self.pumps
  2138. for worker in workers:
  2139. try:
  2140. if worker.ident is not None: worker.join(timeout=max(0,end-time.monotonic()))
  2141. assert not worker.is_alive(), 'owned failed session worker join deadline'
  2142. except Exception as failure: failures.append(failure)
  2143. if failures: raise failures[0]
  2144. def assert_continuous(self):
  2145. assert self.error is None and self.monitor_pump.is_alive(), self.error or 'monitor missing'
  2146. for p in self.processes:
  2147. assert p['child'].poll() is None, 'session process not live'
  2148. current = proc_identity(p['identity']['pid'],p['identity'])
  2149. assert current['ns'] == p['identity']['ns'] and current['uids'] == current['gids'] == [1000]*4 and current['groups'] == []
  2150. s = (self.directory/'bus').lstat()
  2151. assert {'inode':s.st_ino,'device':s.st_dev,'mode':s.st_mode,'uid':s.st_uid,'gid':s.st_gid} == self.socket_identity
  2152. def checkpoint(self, helper=None, enabled=False):
  2153. self.assert_continuous()
  2154. guid,call = self.rpc('org.freedesktop.DBus.GetId',[],'s')
  2155. assert guid == self.guid
  2156. self.observed_roundtrip(call) # binary stream passed through this boundary.
  2157. self.exchange.finish()
  2158. if helper is not None:
  2159. names = [name for name,f in self.credentials.items() if f['pid'] == helper['pid'] and f['birth'] == helper['birth']]
  2160. assert len(names) == (1 if enabled else 0), 'actual helper sender identity missing/disabled helper reached bus'
  2161. if enabled:
  2162. receipts = [r for r in self.exchange.receipts if r['sender'] == names[0]]
  2163. assert len(receipts) == 1, 'one correlated real Notify reply required'
  2164. credential = self.credentials[names[0]]
  2165. assert credential['nspid'] == helper['nspid'] and credential['ns'] == helper['ns'] and credential['argv'] == helper['argv']
  2166. assert len(self.exchange.receipts) == 1, 'duplicate/disabled Notify effect'
  2167. (self.root/'evidence/notifications-actual.json').write_text(json.dumps({
  2168. 'busGUID':self.guid,'owner':self.owner,'credentials':self.credentials,
  2169. 'receipts':self.exchange.receipts,'messages':self.messages,'GUIVisibility':'NOT_RUN'},indent=2)+'\n')
  2170. def close(self):
  2171. began = time.monotonic(); deadline = self.clock.cleanup_deadline()
  2172. self.assert_continuous(); self.exchange.finish()
  2173. assert all(p['child'].poll() == 0 for p in self.control_processes), 'separate control connection join incomplete'
  2174. self.closing = True
  2175. # Join native/RPC; close.
  2176. for p in (self.monitor,self.dunst,self.bus,self.display_process):
  2177. proc_identity(p['identity']['pid'],p['identity'])
  2178. os.kill(p['identity']['pid'],signal.SIGTERM)
  2179. p['child'].wait(timeout=max(.001,min(2,deadline-time.monotonic())))
  2180. self.monitor_pump.join(timeout=max(0,deadline-time.monotonic()))
  2181. for t in self.pumps: t.join(timeout=max(0,deadline-time.monotonic()))
  2182. assert not self.monitor_pump.is_alive() and all(not t.is_alive() for t in self.pumps) and self.error is None, 'standard session join incomplete'
  2183. self.stream.finish()
  2184. os.close(self.netfd)
  2185. self.owned_fds.remove(self.netfd)
  2186. self.clock.charge_cleanup(began)
  2187. class OuterObservation:
  2188. def __init__(self, child, peer, inputs, clock):
  2189. self.child, self.peer, self.inputs, self.clock = child,peer,inputs,clock
  2190. self.controller = None
  2191. self.trace = self.session = None
  2192. self.sequence = 0
  2193. self.nonce = None
  2194. self.phases = []
  2195. self.closed = False
  2196. self.active_phase = None
  2197. def controller_identity(self, local):
  2198. assert local['pid'] == local['tgid'] == 1 and local['uids'] == local['gids'] == [1000]*4 and local['groups'] == []
  2199. matches = []
  2200. for p in pathlib.Path('/proc').iterdir():
  2201. if not p.name.isdecimal(): continue
  2202. try:
  2203. if os.readlink(p/'ns/pid') != local['ns']['pid']: continue
  2204. facts = proc_identity(int(p.name))
  2205. except FileNotFoundError: continue
  2206. if facts['birth'] == local['birth'] and facts['nspid'][-1] == 1: matches.append(facts)
  2207. assert len(matches) == 1, 'one exact ancestor-visible C identity'
  2208. actual = matches[0]
  2209. assert actual['ppid'] == self.child.pid and actual['ns'] == local['ns']
  2210. assert actual['uids'] == actual['gids'] == [1000]*4 and actual['groups'] == []
  2211. assert actual['uidMap'] == local['uidMap'] and actual['gidMap'] == local['gidMap']
  2212. assert actual['ns']['user'] == os.readlink('/proc/self/ns/user')
  2213. assert actual['ns']['pid'] != os.readlink('/proc/self/ns/pid')
  2214. assert actual['ns']['net'] != os.readlink('/proc/self/ns/net')
  2215. return actual
  2216. def empty_native(self):
  2217. for p in pathlib.Path('/proc').iterdir():
  2218. if not p.name.isdecimal(): continue
  2219. try: same = os.readlink(p/'ns/pid') == self.controller['ns']['pid']
  2220. except FileNotFoundError: continue
  2221. if same: assert int(p.name) == self.controller['pid'], 'CLI/native descendants remain at phase boundary'
  2222. def request(self):
  2223. message = control_receive(self.peer,self.clock)
  2224. assert message['sequence'] == self.sequence+1, 'outer control sequence'
  2225. self.sequence += 1
  2226. if self.nonce is None: self.nonce = message['nonce']
  2227. assert message['nonce'] == self.nonce and re.fullmatch(r'[0-9a-f]{64}',self.nonce), 'case control nonce'
  2228. self.clock.cleanup_used = max(self.clock.cleanup_used,message['cleanupUsed'])
  2229. assert 0 <= self.clock.cleanup_used < 8, 'shared cumulative cleanup ledger'
  2230. reply = {'sequence':self.sequence,'nonce':self.nonce,'ok':True}
  2231. action = message['action']
  2232. if action == 'controller-thread':
  2233. expected = 'enabled-native' if not self.phases else 'disabled-restart'
  2234. if self.trace is None or self.controller is None or self.closed or self.clock.work is None or len(self.phases) >= 2 or message.get('phase') != self.active_phase or self.active_phase != expected: raise AssertionError('controller thread inactive phase')
  2235. local = message.get('thread')
  2236. if type(local) is not dict or set(local) != {'tid','birth'} or type(local['tid']) is not int or not 0 < local['tid'] <= 2147483647 or type(local['birth']) is not int or not 0 <= local['birth'] <= 18446744073709551615: raise AssertionError('controller thread tuple budget')
  2237. parser = self.trace.parser
  2238. def matching():
  2239. return [t for t in parser.tasks.values() if t.get('parent') and not t.get('exited') and not t.get('capture') and not t.get('nativeLeader') and t['key'][1] == local['birth'] and t['facts']['tgid'] == self.controller['pid'] and len(t['facts']['nspid']) == len(self.controller['nspid']) and t['facts']['nspid'][-1] == local['tid']]
  2240. with parser.changed:
  2241. if not parser.changed.wait_for(lambda:self.trace.error is not None or bool(matching()),self.clock.wait(1)): raise AssertionError('controller thread live trace deadline')
  2242. known = matching()
  2243. if self.trace.error is not None or len(known) != 1: raise AssertionError(self.trace.error or 'controller thread mapping ambiguity')
  2244. task = known[0]; parent_key = task['parent']
  2245. parent = parser.register(parent_key[0]); child = parser.register(task['key'][0])
  2246. parent_fresh = trace_task_identity(parent_key[0]); child_fresh = trace_task_identity(task['key'][0])
  2247. for fresh,retained in ((parent_fresh,parent),(child_fresh,child)):
  2248. if (fresh['pid'],fresh['birth']) != retained['key'] or fresh['ns'] != self.controller['ns'] or fresh['uids'] != fresh['gids'] or fresh['uids'] != [1000]*4 or fresh['groups'] != [] or fresh['tracer'] != self.trace.tracer['pid'] or fresh['nspid'] != retained['facts']['nspid']: raise AssertionError('controller thread fresh metadata drift')
  2249. if parent['key'] != parent_key or parent_fresh['tgid'] != self.controller['pid'] or child['key'] != task['key'] or child['parent'] != parent_key or child_fresh['tgid'] != self.controller['pid'] or len(child_fresh['nspid']) != len(self.controller['nspid']) or child_fresh['nspid'][-1] != local['tid'] or child_fresh['birth'] != local['birth']: raise AssertionError('controller thread fresh identity drift')
  2250. reply['controllerThread'] = {'tid':local['tid'],'birth':local['birth'],'phase':self.active_phase}
  2251. control_send(self.peer,reply,self.clock)
  2252. return
  2253. if action == 'prepare':
  2254. assert self.controller is None and self.trace is None and self.session is None
  2255. self.controller = self.controller_identity(message['controller'])
  2256. self.empty_native()
  2257. installed = (pathlib.Path(message['primary']),pathlib.Path(message['selector']),message['binding'],message['generation'])
  2258. # Allocate before containment.
  2259. self.session = OwnedNotificationsSession.__new__(OwnedNotificationsSession)
  2260. self.session.__init__(self.controller,self.inputs['root'],self.clock,self.inputs['tools'],self.inputs['displayNumber'])
  2261. self.empty_native() # All services are outside P1; no setup CLI remains.
  2262. self.trace = PassiveStrace.__new__(PassiveStrace)
  2263. self.trace.__init__(self.controller,installed,self.inputs['root'],self.clock,self.inputs['tools'],self.session)
  2264. reply['environment'] = {k:self.session.env[k] for k in ('DBUS_SESSION_BUS_ADDRESS','DISPLAY','XAUTHORITY')}
  2265. reply['controller'] = self.controller
  2266. reply['tracer'] = self.trace.tracer
  2267. elif action == 'begin-phase':
  2268. assert message['phase'] == ('enabled-native' if not self.phases else 'disabled-restart') and len(self.phases) < 2
  2269. self.empty_native(); self.session.assert_continuous(); self.trace.begin_phase()
  2270. self.active_phase = message['phase']
  2271. elif action == 'leader':
  2272. assert message['phase'] == ('enabled-native' if not self.phases else 'disabled-restart')
  2273. if self.clock.work is None: self.clock.work = min(message['nativeStart']+90,self.clock.outer-8)
  2274. self.clock.wait(5)
  2275. end = time.monotonic()+self.clock.wait(1)
  2276. while True:
  2277. assert self.trace.error is None, self.trace.error
  2278. with self.trace.parser.lock:
  2279. known = [t for t in self.trace.parser.tasks.values() if t['facts']['birth'] == message['localLeader']['birth'] and t['facts']['nspid'][-1] == message['localLeader']['pid']]
  2280. if len(known) == 1: break
  2281. assert time.monotonic() < end, 'trace/native leader synchronization deadline'
  2282. time.sleep(min(.001,max(0,end-time.monotonic())))
  2283. reply['leader'] = self.trace.select_leader(message['localLeader'],end)
  2284. self.session.assert_continuous()
  2285. elif action == 'phase':
  2286. phase = message['phase']
  2287. assert phase == ('enabled-native' if not self.phases else 'disabled-restart') and len(self.phases) < 2
  2288. self.empty_native()
  2289. end = time.monotonic()+self.clock.wait(1)
  2290. while True:
  2291. assert self.trace.error is None, self.trace.error
  2292. with self.trace.parser.lock:
  2293. completed = [c for c in self.trace.parser.selected if c['leader'][1] == message['localLeader']['birth'] and c['exited'] and c['eof']]
  2294. terminal = all(t.get('exited') or t['facts']['tgid'] == self.controller['pid'] for t in self.trace.parser.tasks.values())
  2295. if len(completed) == 1 and terminal: break
  2296. assert time.monotonic() < end, 'native exit/alias trace completion deadline'
  2297. time.sleep(min(.001,max(0,end-time.monotonic())))
  2298. capture,raw,facts = self.trace.phase(message['localLeader'],message['cleanupSignal'],message['cleanupRoles'])
  2299. self.session.checkpoint(capture['identity'],enabled=phase == 'enabled-native')
  2300. if self.phases:
  2301. assert facts['conversation'] != self.phases[0]['facts']['conversation'] and facts['generation'] != self.phases[0]['facts']['generation'], 'planned restart has stale native identities'
  2302. evidence = pathlib.Path(self.inputs['root'])/'evidence'/phase
  2303. sha = hashlib.sha256(raw).hexdigest()
  2304. (evidence/'native-outer-consumed-stdin.bin').write_bytes(raw)
  2305. (evidence/'native-outer-consumed-stdin.sha256').write_text(sha+'\n')
  2306. (evidence/'stdin-alias-trace.json').write_text(json.dumps({k:v for k,v in capture.items() if k not in ('bytes','busConnections')},indent=2)+'\n')
  2307. self.phases.append({'phase':phase,'facts':facts,'nativeSHA256':sha,'helperIdentity':capture['identity']})
  2308. reply.update(nativeBytes=base64.b64encode(raw).decode(),facts=facts,nativeSHA256=sha,helperIdentity=capture['identity'])
  2309. elif action == 'checkpoint':
  2310. assert self.phases
  2311. self.empty_native(); self.session.checkpoint()
  2312. elif action == 'close':
  2313. assert len(self.phases) == 2
  2314. self.empty_native(); self.session.checkpoint()
  2315. self.trace.close(); self.session.close()
  2316. self.closed = True
  2317. reply['cleanupUsed'] = self.clock.cleanup_used
  2318. else: raise AssertionError('unknown outer control action')
  2319. control_send(self.peer,reply,self.clock)
  2320. def digest(path):
  2321. with pathlib.Path(path).open('rb') as stream:
  2322. return hashlib.file_digest(stream, 'sha256').hexdigest()
  2323. def physical(path):
  2324. path = pathlib.Path(path)
  2325. assert path.is_absolute() and path.resolve(strict=True) == path, 'physical absolute input required'
  2326. return path
  2327. def execution_inputs(filename, inside=False):
  2328. data = strict_json(physical(filename).read_bytes())
  2329. assert set(data) == {'sourceSHA', 'root', 'artifact', 'stage', 'package', 'cursorArchive', 'buildInfo', 'machineID', 'sha256', 'tools', 'displayNumber', 'readbackHelper', 'readbackBuildInfo'}, 'execution input fields'
  2330. assert data['sourceSHA'] == SOURCE_SHA and data['machineID'], 'fixed final source/runner required'
  2331. root = pathlib.Path(data['root'])
  2332. assert root.is_absolute() and root.name.startswith('TEST-cursor-installed-') and (root.is_dir() if inside else not root.exists()) and not root.is_symlink(), 'fresh TEST root required'
  2333. physical(root.parent)
  2334. for key in ['artifact', 'stage', 'package', 'cursorArchive', 'buildInfo', 'readbackHelper', 'readbackBuildInfo']: physical(data[key])
  2335. primary = pathlib.Path(data['stage'])/'claude-notifications-linux-amd64'
  2336. assert digest(primary) == data['sha256']['primary'] and digest(data['package']) == data['sha256']['package']
  2337. with zipfile.ZipFile(data['package']) as archive:
  2338. names = archive.namelist()
  2339. assert len(names) == len(set(names)) and {'plugin.json', 'mcp.json', 'bin/claude-notifications'} <= set(names)
  2340. for member in archive.infolist():
  2341. path = pathlib.PurePosixPath(member.filename)
  2342. assert not path.is_absolute() and '..' not in path.parts and '\\' not in member.filename
  2343. assert not stat.S_ISLNK(member.external_attr >> 16) and member.file_size <= 80 << 20
  2344. assert sum(m.file_size for m in archive.infolist()) <= 96 << 20
  2345. assert hashlib.sha256(archive.read('bin/claude-notifications')).hexdigest() == data['sha256']['primary']
  2346. build_info = pathlib.Path(data['buildInfo']).read_bytes()
  2347. assert len(build_info) <= 65536 and hashlib.sha256(build_info).hexdigest() == data['sha256']['buildInfo']
  2348. assert ('vcs.revision='+SOURCE_SHA).encode() in build_info and b'vcs.modified=false' in build_info
  2349. assert b'github.com/777genius/plugin-kit-ai/sdk\tv1.2.1-0.20261002230153-01f7fced8098' in build_info
  2350. assert b'=>\t' not in build_info, 'local module replacement forbidden'
  2351. assert digest(data['readbackHelper']) == data['sha256']['readbackHelper'], 'source-built read-only bridge bytes'
  2352. bridge_info = pathlib.Path(data['readbackBuildInfo']).read_bytes()
  2353. assert len(bridge_info) <= 65536 and hashlib.sha256(bridge_info).hexdigest() == data['sha256']['readbackBuildInfo']
  2354. assert ('vcs.revision='+SOURCE_SHA).encode() in bridge_info and b'vcs.modified=false' in bridge_info
  2355. assert ('main.packetSourceSHA256='+READBACK_SOURCE_SHA256).encode() in bridge_info and b'=>\t' not in bridge_info
  2356. assert hashlib.sha256(READBACK_SOURCE_BYTES).hexdigest() == READBACK_SOURCE_SHA256
  2357. archive = pathlib.Path(data['cursorArchive'])
  2358. dist = pathlib.Path(data['artifact'])
  2359. assert archive.stat().st_size == 182618248 and digest(archive) == CURSOR_ARCHIVE_SHA
  2360. with tarfile.open(archive) as opened:
  2361. members = opened.getmembers()
  2362. assert len(members) == 580
  2363. assert len({m.name for m in members}) == len(members)
  2364. for member in members:
  2365. name = pathlib.PurePosixPath(member.name)
  2366. assert not name.is_absolute() and '..' not in name.parts and (member.isfile() or member.isdir())
  2367. files = [m for m in members if m.isfile()]
  2368. paths = [pathlib.PurePosixPath(m.name).parts for m in files]
  2369. strip = 1 if len({parts[0] for parts in paths}) == 1 and all(len(parts) > 1 for parts in paths) else 0
  2370. expected = set()
  2371. for member in files:
  2372. relative = pathlib.Path(*pathlib.PurePosixPath(member.name).parts[strip:])
  2373. assert str(relative) not in expected
  2374. expected.add(str(relative))
  2375. target = physical(dist/relative)
  2376. assert target.is_file()
  2377. assert target.read_bytes() == opened.extractfile(member).read()
  2378. assert target.stat().st_mode & 0o111 == member.mode & 0o111
  2379. actual = set()
  2380. for target in dist.rglob('*'):
  2381. assert not target.is_symlink() and (target.is_dir() or stat.S_ISREG(target.lstat().st_mode))
  2382. if target.is_file(): actual.add(str(target.relative_to(dist)))
  2383. assert actual == expected, 'complete fixed runtime tree required'
  2384. assert digest(pathlib.Path(data['artifact'])/'cursor-agent') == LAUNCHER_SHA
  2385. assert digest(pathlib.Path(data['artifact'])/'index.js') == INDEX_SHA
  2386. for pin in ARTIFACT_PINS:
  2387. assert digest(pathlib.Path(data['artifact'])/pin['file']) == pin['sha256']
  2388. return data
  2389. def require_native_observation_contract(inputs, clock, inside=False):
  2390. """Checks grant prerequisites only; readiness is a later actual roundtrip."""
  2391. raise IncompleteInstalledContract('R1360 TEST increment: full Linux proof/exact review/carrier qualification pending; native ineligible')
  2392. clock.wait(5)
  2393. assert inputs['sourceSHA'] == SOURCE_SHA, 'immutable current helper source'
  2394. assert hashlib.sha256(WIRE_BYTES).hexdigest() == WIRE_SHA, 'original wire protection'
  2395. assert set(inputs['tools']) == {'strace','dbus-daemon','dbus-monitor','dbus-send','dunst','Xvfb','xauth','nsenter','setpriv'}
  2396. for name, tool in inputs['tools'].items():
  2397. assert set(tool) == {'path','sha256','package','version','installedMetadataSHA256'}, 'actual standard package provenance fields'
  2398. path = physical(tool['path'])
  2399. assert path == pathlib.Path('/usr/bin')/name and path.is_file(), 'standard immutable tool path'
  2400. assert digest(path) == tool['sha256'] and stat.S_IMODE(path.stat().st_mode) & 0o111, 'actual standard binary bytes'
  2401. assert tool['package'] and tool['version'] and re.fullmatch(r'[0-9a-f]{64}',tool['installedMetadataSHA256'])
  2402. assert inputs['tools']['strace']['version'] == '6.8-0ubuntu2', 'source-qualified strace version'
  2403. assert inputs['tools']['strace']['package'] == 'strace'
  2404. if inside:
  2405. # P1 root checks/drop; setup/passive attach.
  2406. assert os.getpid() == 1 and os.geteuid() == 0
  2407. return
  2408. assert os.geteuid() == 0, 'outer capability owner required'
  2409. status = pathlib.Path('/proc/self/status').read_text()
  2410. values = dict(line.split(':',1) for line in status.splitlines() if ':' in line)
  2411. capabilities = int(values['CapEff'].strip(),16)
  2412. assert capabilities & (1<<19) and capabilities & (1<<21), 'existing SYS_PTRACE/SYS_ADMIN required'
  2413. assert values['Seccomp'].strip() == '0', 'unknown outer syscall filter permission'
  2414. assert pathlib.Path('/proc/sys/kernel/yama/ptrace_scope').read_text().strip() in ('0','1','2'), 'existing Yama attach permission'
  2415. assert pathlib.Path('/proc/self/attr/current').read_text().strip() == 'unconfined', 'unknown LSM permission'
  2416. for name, tool in inputs['tools'].items():
  2417. command = ['/usr/bin/dpkg-query','--show','--showformat=${binary:Package}\t${Version}\t${db:Status-Status}\n',tool['package']]
  2418. metadata = subprocess.check_output(command,timeout=clock.wait(5),env={'PATH':'/usr/bin:/bin','LANG':'C'})
  2419. assert metadata.decode().strip() == tool['package']+'\t'+tool['version']+'\tinstalled'
  2420. assert hashlib.sha256(metadata).hexdigest() == tool['installedMetadataSHA256'], 'actual installed package metadata'
  2421. def qualified_runner(profile, machine_id):
  2422. assert pathlib.Path('/etc/machine-id').read_text().strip() == machine_id, 'actual frozen runner identity'
  2423. assert platform.system() == 'Linux' and platform.machine() == 'x86_64'
  2424. assert pathlib.Path('/proc/sys/kernel/osrelease').read_text().strip() == '6.17.0-1022-azure'
  2425. release = pathlib.Path('/etc/os-release').read_text()
  2426. assert '\nID=ubuntu\n' in '\n'+release and 'VERSION="24.04.5 LTS' in release
  2427. mounts = pathlib.Path('/proc/self/mountinfo').read_text()
  2428. assert len(mounts.encode()) <= LIMIT
  2429. decode = lambda s: s.replace('\\040', ' ').replace('\\011', '\t').replace('\\012', '\n').replace('\\134', '\\')
  2430. for path in [profile, *profile.parents]:
  2431. matches = []
  2432. for row in mounts.splitlines():
  2433. left, sep, right = row.partition(' - ')
  2434. if not sep or len(left.split()) < 6 or len(right.split()) < 3: continue
  2435. mount = decode(left.split()[4])
  2436. if mount == '/' or str(path) == mount or str(path).startswith(mount+'/'):
  2437. matches.append((len(mount), right.split()[0]))
  2438. longest = max(n for n, fs in matches)
  2439. selected = [fs for n, fs in matches if n == longest]
  2440. assert selected == ['ext4'], 'every actual ancestor must be unambiguously ext4'
  2441. # No grants/foreign/token; capture+revalidate.
  2442. def case_env(root):
  2443. return {'HOME':str(root/'home'), 'XDG_CONFIG_HOME':str(root/'home/.config'),
  2444. 'TMPDIR':str(root/'tmp'), 'XDG_CACHE_HOME':str(root/'cache'),
  2445. 'AGENT_NOTIFICATIONS_CONFIG':str(root/'home/.config/agent-notifications/config.json'),
  2446. 'PATH':'/usr/bin:/bin', 'LANG':'C.UTF-8', **SESSION_ENV}
  2447. def cli(root, primary, argv, name, payload=None, terminal=False):
  2448. command = [str(primary), *argv]
  2449. if terminal:
  2450. master, slave = os.openpty()
  2451. def controlling_pty():
  2452. os.setsid()
  2453. fcntl.ioctl(0, termios.TIOCSCTTY, 0)
  2454. child = None
  2455. raw = bytearray()
  2456. answered = False
  2457. deadline = time.monotonic()+CASE_CLOCK.wait(30)
  2458. try:
  2459. child = subprocess.Popen(command, stdin=slave, stdout=slave, stderr=slave,
  2460. cwd=root/'workspace', env=case_env(root), preexec_fn=controlling_pty)
  2461. os.close(slave)
  2462. slave = None
  2463. while child.poll() is None:
  2464. assert time.monotonic() < deadline, 'real controlling-PTY confirmation deadline'
  2465. if not select.select([master], [], [], min(.05,CASE_CLOCK.wait(.05)))[0]: continue
  2466. try: part = os.read(master, 8192)
  2467. except OSError as error:
  2468. if error.errno == 5: break
  2469. raise
  2470. raw.extend(part)
  2471. assert len(raw) <= LIMIT, 'bounded confirmation output'
  2472. if not answered and b'Apply this plan?' in raw:
  2473. # ONE fresh Yes via PTY.
  2474. os.write(master, b'y\n')
  2475. answered = True
  2476. assert answered and child.wait(timeout=min(CASE_CLOCK.wait(30),max(.001,deadline-time.monotonic()))) == 0
  2477. result = subprocess.CompletedProcess(command, child.returncode)
  2478. (root/'evidence'/str(name+'.pty')).write_bytes(raw)
  2479. finally:
  2480. if slave is not None: os.close(slave)
  2481. os.close(master)
  2482. # PTY: no retry; contain unknown children.
  2483. if child is not None and child.poll() is None: raise IncompleteInstalledContract('PTY join incomplete')
  2484. else:
  2485. result = subprocess.run(command, input=payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  2486. cwd=root/'workspace', env=case_env(root), timeout=CASE_CLOCK.wait(30))
  2487. assert len(result.stdout) <= LIMIT and len(result.stderr) <= LIMIT
  2488. (root/'evidence'/str(name+'.stdout')).write_bytes(result.stdout)
  2489. (root/'evidence'/str(name+'.stderr')).write_bytes(result.stderr)
  2490. assert result.returncode == 0, 'public CLI failed; do not retry'
  2491. return result.stdout if not terminal else None
  2492. def wizard(root, primary, artifact, package, action, enabled, extra=(), json_output=True):
  2493. control = root/'home/.config/agent-notifications'
  2494. args = ['setup-notifications', 'wizard', '--action', action, '--agents', 'cursor',
  2495. '--hooks', 'false', '--agent-notify', str(enabled).lower(), '--control-root', str(control),
  2496. '--scope-root', str(root/'home/.cursor'), '--client-executable', str(artifact/'cursor-agent'), '--yes']
  2497. if package is not None:
  2498. ledger = strict_json((control/'ownership.json').read_bytes())
  2499. args += ['--package', str(package), '--runtime-root', ledger['RuntimeRoot'],
  2500. '--global-config', case_env(root)['AGENT_NOTIFICATIONS_CONFIG']]
  2501. args += list(extra)
  2502. if json_output: args += ['--json']
  2503. return args
  2504. def inventory_object_refusal(directory, current, facts):
  2505. """Best-effort bounded TEST-only metadata from the already-read lstat."""
  2506. try:
  2507. test_root = next(p for p in (directory, *directory.parents) if p.name.startswith('TEST-'))
  2508. relative = current.relative_to(test_root)
  2509. assert not relative.is_absolute() and '..' not in relative.parts
  2510. path = str(relative)
  2511. row = {'path':path[:512], 'pathTruncated':len(path) > 512,
  2512. 'pathSHA256':hashlib.sha256(path.encode('utf-8','surrogatepass')).hexdigest(),
  2513. 'mode':int(facts.st_mode), 'type':stat.S_IFMT(facts.st_mode),
  2514. 'device':int(facts.st_dev), 'inode':int(facts.st_ino)}
  2515. assert all(0 <= row[k] < 2**64 for k in ('mode','type','device','inode'))
  2516. message = json.dumps(row,ensure_ascii=True,separators=(',',':'))
  2517. assert len(message) <= 4096
  2518. print('inventory-object-refusal '+message,file=sys.stderr,flush=True)
  2519. except Exception:
  2520. pass
  2521. def vendor_worker_socket_path(root):
  2522. """Lexical pinned45d9 path derivation; only this isolated TEST case."""
  2523. root = pathlib.Path(root)
  2524. assert root.name == 'TEST-cursor-installed-one' and root.parent.name.startswith('TEST-cursor-installed-packet-')
  2525. assert root.parent.parent == pathlib.Path('/tmp') and '..' not in root.parts
  2526. data = root/'home/.cursor'
  2527. base = data/'projects'
  2528. if len(str(base)) > 84: base = data
  2529. if len(str(base)) > 84: return None # vendor /tmp/.cursor fallback is outside this owned TEST root
  2530. workspace = re.sub(r'^-+|-+$','',re.sub(r'-+','-',re.sub(r'[^a-zA-Z0-9]','-',str(root/'workspace'))))
  2531. joined = str(base/workspace)
  2532. if len(joined) > 92: joined = joined[:84]+'-'+hashlib.sha256(joined.encode()).hexdigest()[:7]
  2533. socket_path = pathlib.Path(joined)/'worker.sock'
  2534. return socket_path if socket_path.is_relative_to(data) else None
  2535. def bounded_tree(directory, vendor_root=None):
  2536. """Full no-follow path, member, byte and identity sets; no suffix guessing."""
  2537. directory = pathlib.Path(directory)
  2538. result = {}; total = 0
  2539. vendor_socket = vendor_worker_socket_path(vendor_root) if vendor_root is not None else None
  2540. if not os.path.lexists(directory): return result
  2541. stack = [directory]
  2542. while stack:
  2543. current = stack.pop()
  2544. facts = current.lstat()
  2545. assert len(result) < 16384, 'full object membership bound'
  2546. value = {'mode':facts.st_mode, 'uid':facts.st_uid, 'gid':facts.st_gid,
  2547. 'device':facts.st_dev,'inode':facts.st_ino,'nlink':facts.st_nlink}
  2548. if stat.S_ISLNK(facts.st_mode):
  2549. value['link'] = os.readlink(current)
  2550. assert len(value['link'].encode()) <= 4096, 'raw link bound'
  2551. elif stat.S_ISREG(facts.st_mode):
  2552. assert facts.st_size <= TEST_RUNTIME_FILE_LIMIT, 'full object file bound'
  2553. body = current.read_bytes(); assert len(body) == facts.st_size
  2554. total += len(body); assert total <= 1024**3, 'full writable-case bound'
  2555. value['sha256'] = hashlib.sha256(body).hexdigest(); value['byteLength'] = len(body)
  2556. if current.suffix == '.json':
  2557. parsed = strict_json(body)
  2558. value['jsonMembers'] = json_members(parsed)
  2559. elif stat.S_ISSOCK(facts.st_mode) and current == vendor_socket:
  2560. parent = result.get(str(current.parent.relative_to(directory)),{})
  2561. assert (facts.st_uid,facts.st_gid,facts.st_dev) == (parent.get('uid'),parent.get('gid'),parent.get('device')), 'foreign vendor socket ownership'
  2562. value['type'] = stat.S_IFSOCK
  2563. else:
  2564. if not stat.S_ISDIR(facts.st_mode):
  2565. inventory_object_refusal(directory,current,facts)
  2566. assert stat.S_ISDIR(facts.st_mode), 'unknown filesystem object'
  2567. stack.extend(sorted(current.iterdir(),reverse=True))
  2568. final = current.lstat()
  2569. assert (facts.st_mode,facts.st_uid,facts.st_gid,facts.st_dev,facts.st_ino,facts.st_nlink,facts.st_size,facts.st_mtime_ns,facts.st_ctime_ns) == (final.st_mode,final.st_uid,final.st_gid,final.st_dev,final.st_ino,final.st_nlink,final.st_size,final.st_mtime_ns,final.st_ctime_ns), 'object changed during full inventory'
  2570. result[str(current.relative_to(directory))] = value
  2571. assert len(json.dumps(result)) <= 4*LIMIT, 'bounded full tree evidence/hex expansion'
  2572. return result
  2573. def json_members(value, path=''):
  2574. result = []
  2575. def visit(node, location, depth):
  2576. assert depth <= 64 and len(result) < 65536, 'full JSON member bound'
  2577. result.append(location)
  2578. if type(node) is dict:
  2579. for key in sorted(node): visit(node[key],location+'/'+key.replace('~','~0').replace('/','~1'),depth+1)
  2580. elif type(node) is list:
  2581. for i,child in enumerate(node): visit(child,location+'/'+str(i),depth+1)
  2582. visit(value,path,0)
  2583. return result
  2584. def authoritative_readback(root, primary, selector, binding, phase, mode='live'):
  2585. """Actual public Load/Inspect/Gate/Revalidate; the first token is never recaptured."""
  2586. assert READBACK_INPUTS is not None
  2587. key = str(root)
  2588. frozen = AUTHORITY_BASELINE.get(key)
  2589. request = {'mode':mode,'selector':str(selector),'binding':binding,'tempRoot':str(root/'tmp'),
  2590. 'timeoutMillis':max(1,int(CASE_CLOCK.wait(5)*1000)), 'sourceSHA256':READBACK_SOURCE_SHA256,
  2591. 'originalAuthority':frozen['originalAuthority'] if frozen else None,
  2592. 'originalNamespace':frozen['originalNamespace'] if frozen else '',
  2593. 'fixed':frozen['fixed'] if frozen else None}
  2594. observed = strict_json(cli(root,pathlib.Path(READBACK_INPUTS['readbackHelper']),[],phase+'-public-authority',json.dumps(request).encode()))
  2595. assert observed['mode'] == mode and observed['bridgeSourceSHA256'] == READBACK_SOURCE_SHA256
  2596. assert observed['binding'] == binding
  2597. recovery = observed['inspection']['Recovery']
  2598. assert recovery['Required'] is False and not recovery['Reason']
  2599. assert not recovery['Journals'] and not recovery['Receipts'] and not recovery['NativeIntents']
  2600. state_path = root/'home/.config/uap/state/state-v2.json'
  2601. raw = strict_json(state_path.read_bytes())
  2602. assert raw['schema_version'] == 4 and raw.get('installations',[]) == (observed['state'].get('installations') or []), 'actual Load versus raw state membership'
  2603. operations = state_path.parent/'operations'
  2604. if operations.exists():
  2605. assert not list(operations.iterdir()), 'raw operation remainder is unknown'
  2606. if mode != 'absent':
  2607. selected = observed['selected']
  2608. assert selected['target_locator'] == str(root/'home/.cursor/plugins/local'/selector.parent.name), 'selected managed MCP target changed'
  2609. authority = selected['profile_authority']
  2610. assert authority == observed['originalAuthority'] and selected['profile_namespace'] == observed['originalNamespace']
  2611. assert set(authority) == {'version','canonical_root','ancestry'} and authority['version'] == 1
  2612. assert authority['canonical_root'] == binding['scopeRoot'] and authority['ancestry']
  2613. assert all(set(entry) == {'canonical_path','scheme','volume_id','object_id'} for entry in authority['ancestry'])
  2614. assert selected['materialization'] == 'materialized' and selected['activation'] == 'prepared' and selected['verification'] == 'package_validated', 'registration readback remains prepared/package-valid'
  2615. assert selected['policy'] == 'allowed' and not selected.get('pending_native_intent') and not selected.get('native_activation_attempt')
  2616. objects = selected['native_objects']
  2617. assert len(objects) == 2 and sorted(o['kind'] for o in objects) == ['cursor_user_stop','managed_package_directory']
  2618. expected_protection = {'cursor_user_stop':'owned_selector','managed_package_directory':'managed'}
  2619. assert all(not o.get('user_modified',False) and o['protection_class'] == expected_protection[o['kind']] for o in objects)
  2620. if frozen:
  2621. assert authority == frozen['originalAuthority'] and observed['originalNamespace'] == frozen['originalNamespace'], 'original raw complete ordered authority changed'
  2622. assert observed['fixed'] == frozen['fixed']
  2623. else:
  2624. AUTHORITY_BASELINE[key] = {k:copy.deepcopy(observed[k]) for k in ('originalAuthority','originalNamespace','fixed')}
  2625. (root/'evidence/original-profile-authority.json').write_text(json.dumps(AUTHORITY_BASELINE[key],indent=2)+'\n')
  2626. channels = observed['channels']
  2627. expected = phase in ('enabled','native-enabled','duplicate')
  2628. assert channels == {'Desktop':expected,'Webhook':expected}, 'actual effective channel consent readback'
  2629. assert observed['consumerBinding']['Generation'] == strict_json((root/'home/.config/agent-notifications/ownership.json').read_bytes())['Generation']
  2630. (root/'evidence'/(phase+'-authoritative-readback.json')).write_text(json.dumps(observed,indent=2)+'\n')
  2631. return observed
  2632. def installed_readback(root, primary, artifact, phase, selector=None):
  2633. control = root/'home/.config/agent-notifications'
  2634. raw = {str(p.relative_to(root)):p.read_bytes() for p in
  2635. [control/'ownership.json', control/'agent-notifications.json',
  2636. control.parent/'uap/state/state-v2.json', root/'home/.cursor/hooks.json']}
  2637. assert not (control/'transaction.json').exists(), 'recovery is not resolved'
  2638. ledger = strict_json(raw[str((control/'ownership.json').relative_to(root))])
  2639. assert ledger['Owner'] == 'existing-installer' and ledger['Generation'] > 0 and not ledger.get('PendingMutation')
  2640. assert ledger['RuntimeRoot'] == str(root/'home/.local')
  2641. assert primary == pathlib.Path(ledger['RuntimeRoot'])/'bin/claude-notifications-linux-amd64'
  2642. identity = ledger['Files'][str(primary)]
  2643. assert identity['Exists'] is True and not identity['Link'] and identity['SHA256'] == digest(primary)
  2644. assert identity['Mode'] == stat.S_IMODE(primary.stat().st_mode)
  2645. hooks = strict_json(raw['home/.cursor/hooks.json'])
  2646. assert hooks['version'] == 1
  2647. entries = []
  2648. for hook in hooks['hooks']['stop']:
  2649. argv = shlex.split(hook['command'])
  2650. if argv[:4] == [str(primary), 'cursor-event', 'stop', '--binding']:
  2651. assert len(argv) == 5 and hook['timeout'] == 5 and hook.get('failClosed') is False
  2652. entries.append(argv)
  2653. assert len(entries) == 1, 'exact USER owned helper hook required'
  2654. actual = physical(entries[0][4])
  2655. binding = strict_json(actual.read_bytes())
  2656. assert selector is None or actual == selector, 'same installed selector required'
  2657. assert binding['integration'] == 'cursor' and binding['scopeRoot'] == str(root/'home/.cursor')
  2658. assert binding['version'] == 1 and binding['owner'] == ledger['Owner'] and binding['componentID'] == ledger['ID']
  2659. assert binding['controlRoot'] == str(control) and binding['runtimeRoot'] == ledger['RuntimeRoot']
  2660. assert binding['primary'] == 'bin/claude-notifications-linux-amd64'
  2661. assert binding['globalConfig'] == case_env(root)['AGENT_NOTIFICATIONS_CONFIG']
  2662. assert physical(binding['dataRoot']) == actual.parent
  2663. # Hash committed; raw has no authority/ACK.
  2664. consumers = [(key, value) for key, value in ledger['Consumers'].items()
  2665. if key.startswith('portable:') and strict_json(value['Registration']) == binding]
  2666. assert len(consumers) == 1, 'one exact selected registered consumer required'
  2667. key, consumer = consumers[0]
  2668. registration = consumer['Registration'].encode('utf-8')
  2669. assert key == 'portable:'+hashlib.sha256(registration).hexdigest()
  2670. assert actual.name == 'agent-notify-'+key[len('portable:'):]+'.json'
  2671. assert actual.read_bytes() == registration and consumer['RuntimeRoot'] == ledger['RuntimeRoot']
  2672. assert consumer['Commands'] == [str(primary)]
  2673. # Readback authority/ACK/receipt gated.
  2674. report = strict_json(cli(root, primary, wizard(root, primary, artifact, None, 'inspect', True), phase+'-inspect'))
  2675. assert report['action'] == 'inspect' and report['outcome'] == 'completed', 'inspect exit 0 is insufficient'
  2676. assert report['installationID'] == binding['installationID']
  2677. selected = [row for row in report['targets'] if row['client'] == 'cursor' and row['unit'] == 'agent-notify']
  2678. assert len(selected) == 1 and selected[0]['outcome'] == 'installed'
  2679. assert selected[0]['reason'] == binding['bindingID'] and selected[0]['treeDigest']
  2680. assert selected[0]['profile'] == binding['scopeRoot']
  2681. assert not any(row['outcome'] in ('unknown', 'incomplete') for row in report['targets'])
  2682. assert not any(row['kind'] in ('recover', 'resume', 'activate', 'external-uninstall') for row in report.get('nextActions', []))
  2683. authoritative_readback(root,primary,actual,binding,phase)
  2684. saved = {name:base64.b64encode(data).decode() for name, data in raw.items()}
  2685. (root/'evidence'/str(phase+'-readback.json')).write_text(json.dumps(saved, indent=2)+'\n')
  2686. return actual, binding, ledger['Generation']
  2687. def install_and_confirm(root, artifact, inputs, webhook_url):
  2688. stage = pathlib.Path(inputs['stage'])
  2689. control = root/'home/.config/agent-notifications'
  2690. # Pinned native file-reader fixture, retained in the initial foreign HOME inventory.
  2691. home = root/'home'; home_facts = home.lstat()
  2692. if not stat.S_ISDIR(home_facts.st_mode) or stat.S_IMODE(home_facts.st_mode) != 0o700 or (home_facts.st_uid,home_facts.st_gid) != (1000,1000):
  2693. raise ValueError('TEST credential HOME identity')
  2694. config = home/'.config'; config.mkdir(mode=0o700)
  2695. credentials = config/'cursor'; credentials.mkdir(mode=0o700)
  2696. directory_facts = credentials.lstat()
  2697. if not stat.S_ISDIR(directory_facts.st_mode) or stat.S_IMODE(directory_facts.st_mode) != 0o700 or (directory_facts.st_uid,directory_facts.st_gid,directory_facts.st_dev) != (1000,1000,home_facts.st_dev):
  2698. raise ValueError('TEST credential directory identity')
  2699. credential_path = credentials/'auth.json'
  2700. synthetic_token = 'TEST-loopback-not-a-secret'
  2701. with os.fdopen(os.open(credential_path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600),'w') as credential_file:
  2702. file_facts = os.fstat(credential_file.fileno())
  2703. if not stat.S_ISREG(file_facts.st_mode) or stat.S_IMODE(file_facts.st_mode) != 0o600 or file_facts.st_nlink != 1 or (file_facts.st_uid,file_facts.st_gid,file_facts.st_dev) != (1000,1000,home_facts.st_dev):
  2704. raise ValueError('TEST credential file identity')
  2705. credential_file.write(json.dumps({'accessToken':synthetic_token,'refreshToken':synthetic_token},indent=2))
  2706. final_facts = credential_path.lstat()
  2707. if (final_facts.st_mode,final_facts.st_uid,final_facts.st_gid,final_facts.st_dev,final_facts.st_ino,final_facts.st_nlink) != (file_facts.st_mode,file_facts.st_uid,file_facts.st_gid,file_facts.st_dev,file_facts.st_ino,1):
  2708. raise ValueError('TEST credential file replaced')
  2709. (root/'evidence/credential-fixture.json').write_text(json.dumps({'kind':'TEST-synthetic-file-credentials',
  2710. 'relativePath':'.config/cursor/auth.json','directoryMode':0o700,'fileMode':0o600,'uid':1000,'gid':1000,
  2711. 'fields':['accessToken','refreshToken'],'beforeForeignBaseline':True},separators=(',',':'))+'\n')
  2712. target = root/'home/.local/bin'
  2713. target.mkdir(mode=0o700, parents=True)
  2714. primary = stage/'claude-notifications-linux-amd64'
  2715. cli(root, primary, ['internal-install-runtime', '--stage', str(stage), '--target', str(target),
  2716. '--entry', primary.name, '--control-root', str(control)], 'core-register')
  2717. ledger = strict_json((control/'ownership.json').read_bytes())
  2718. assert ledger['RuntimeRoot'] == str(target.parent), 'core RuntimeRoot is parent of stable bin target'
  2719. primary = target/primary.name
  2720. assert digest(primary) == inputs['sha256']['primary'], 'committed core helper bytes'
  2721. cli(root, primary, ['config', 'init', '--json'], 'config-init')
  2722. inspection = strict_json(cli(root, primary, ['config', 'inspect', '--json'], 'config-inspect'))
  2723. assert inspection['valid'] is True and inspection['revision']
  2724. edits = {'set':{'/notifications/desktop/enabled':True, '/notifications/webhook/enabled':True,
  2725. '/notifications/webhook/url':webhook_url, '/notifications/webhook/preset':'custom', '/notifications/webhook/format':'json',
  2726. '/statuses/agent_stopping/enabled':True, '/statuses/agent_stopping/desktop/enabled':True,
  2727. '/statuses/agent_stopping/webhook/enabled':True}}
  2728. cli(root, primary, ['config', 'edit', '--stdin', '--expect-revision', inspection['revision']],
  2729. 'config-edit', json.dumps(edits).encode())
  2730. with os.fdopen(os.open(control/'agent-notifications.json', os.O_WRONLY|os.O_CREAT|os.O_EXCL, 0o600), 'wb') as policy: policy.write(b'{"schemaVersion":1,"enabled":false}\n')
  2731. assert strict_json((control/'ownership.json').read_bytes()) == ledger, 'TEST policy initialization must not change core ledger'
  2732. (root/'evidence/policy-init.json').write_text(json.dumps({'path':str(control/'agent-notifications.json'), 'policy':strict_json((control/'agent-notifications.json').read_bytes()), 'mode':(control/'agent-notifications.json').stat().st_mode, 'generation':ledger['Generation']})+'\n')
  2733. foreign = foreign_preimage(root)
  2734. installed_report = strict_json(cli(root, primary, wizard(root, primary, artifact, inputs['package'], 'install', True), 'install'))
  2735. assert installed_report['action'] == 'install' and installed_report['outcome'] == 'completed', 'cancelled exit 0 is insufficient'
  2736. selector, binding, generation = installed_readback(root, primary, artifact, 'install')
  2737. assert installed_report['installationID'] == binding['installationID'] and installed_report['generation'] == generation
  2738. selected = [row for row in installed_report['targets'] if row['client'] == 'cursor' and row['unit'] == 'agent-notify']
  2739. assert len(selected) == 1 and selected[0]['outcome'] == 'completed' and selected[0]['reason'] == binding['bindingID']
  2740. intent = primary.parent/'TEST-cursor-confirmed-intent.json'
  2741. assert not intent.exists()
  2742. channel_args = ['--products', 'cursor', '--agent-notify', '--desktop', '--webhook']
  2743. cli(root, primary, ['setup-products', 'confirm', '--plain', *channel_args, '--scope-root', str(root/'home/.cursor'),
  2744. '--client-executable', str(artifact/'cursor-agent'), '--control-root', str(control),
  2745. '--intent-file', str(intent)], 'confirm', terminal=True)
  2746. cli(root, primary, ['setup-products', 'intent-args', '--intent-file', str(intent)], 'intent-args')
  2747. cli(root, primary, ['setup-products', 'preflight', '--intent-file', str(intent), *channel_args], 'preflight')
  2748. frozen = strict_json(intent.read_bytes())
  2749. assert frozen['provenance']['SourceCommit'] == SOURCE_SHA and frozen['provenance']['SHA256'] == digest(primary)
  2750. scopes = {name:base64.b64decode(value, validate=True).decode() for name, value in frozen['scopes'].items()}
  2751. assert scopes['scope-root'] == str(root/'home/.cursor') and scopes['client-executable'] == str(artifact/'cursor-agent')
  2752. args = ['setup-notifications', 'wizard', '--action', 'install', '--install-or-update', '--agents', 'cursor',
  2753. '--hooks', 'false', '--agent-notify', 'true', '--yes', '--package', inputs['package'],
  2754. '--bootstrap-intent-file', str(intent)]
  2755. for key in ['control-root', 'runtime-root', 'global-config', 'scope-root', 'client-executable']:
  2756. args += ['--'+key, scopes[key]]
  2757. # Update before consent CAS.
  2758. cli(root, primary, args, 'update-before-consent')
  2759. selector, binding, generation = installed_readback(root, primary, artifact, 'enabled', selector)
  2760. foreign['ownedOperatorObjects'] = {str(intent.relative_to(root/'home')):bounded_tree(intent)['.']}
  2761. return (primary, selector, binding, generation), foreign
  2762. def webhook_source_body(payload):
  2763. value = strict_json(payload)
  2764. expected = {'schema_version':'1.0','notification_type':'agent_stopping','status':'agent_stopping',
  2765. 'agent_source':'cursor','message':'Cursor CLI is stopping','title':'Cursor CLI',
  2766. 'session_id':'','source':'claude-notifications'}
  2767. assert type(value) is dict and set(value) == set(expected)|{'timestamp'}, 'unknown webhook source fields'
  2768. assert all(value[key] == wanted for key,wanted in expected.items()), 'wrong fixed Cursor stopping webhook copy'
  2769. assert type(value['timestamp']) is str and re.fullmatch(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:\d{2})',value['timestamp']), 'unknown source RFC3339 timestamp'
  2770. if value['timestamp'][-1] != 'Z':
  2771. assert int(value['timestamp'][-5:-3]) <= 23 and int(value['timestamp'][-2:]) <= 59, 'invalid RFC3339 numeric offset'
  2772. datetime.datetime.fromisoformat(value['timestamp'])
  2773. return value
  2774. def owned_webhook(root):
  2775. records = []
  2776. lock = threading.Lock()
  2777. class Webhook(http.server.BaseHTTPRequestHandler):
  2778. def setup(self):
  2779. super().setup()
  2780. self.connection.settimeout(CASE_CLOCK.wait(1))
  2781. def do_GET(self):
  2782. raise AssertionError('unsupported webhook method')
  2783. def log_message(self, *args): pass
  2784. def do_POST(self):
  2785. assert self.path == '/TEST-cursor-stop' and self.client_address[0] == '127.0.0.1'
  2786. assert self.headers.get('Content-Type', '').startswith('application/json')
  2787. size = int(self.headers.get('Content-Length', '-1'))
  2788. assert 0 <= size <= 65536
  2789. payload = self.rfile.read(size)
  2790. assert len(payload) == size
  2791. with lock:
  2792. assert len(records) < 2, 'no repeated channel effects allowed'
  2793. record = {'bodyHex':payload.hex(), 'json':webhook_source_body(payload), 'responseAccepted':False}
  2794. records.append(record)
  2795. (root/'evidence/webhook-actual.json').write_text(json.dumps(records, indent=2)+'\n')
  2796. self.send_response(200)
  2797. self.send_header('Content-Length', '0')
  2798. self.end_headers()
  2799. self.wfile.flush()
  2800. with lock:
  2801. record['responseAccepted'] = True
  2802. (root/'evidence/webhook-actual.json').write_text(json.dumps(records,indent=2)+'\n')
  2803. class OwnedServer(http.server.HTTPServer):
  2804. def handle_error(self, request, address):
  2805. assert len(self.case_failures) < 2, 'webhook failure budget'
  2806. self.case_failures.append(type(sys.exc_info()[1]).__name__)
  2807. (root/'evidence/webhook-failures.json').write_text(json.dumps(self.case_failures)+'\n')
  2808. server = OwnedServer(('127.0.0.1', 0), Webhook)
  2809. server.case_failures = []
  2810. thread = threading.Thread(target=server.serve_forever, daemon=True)
  2811. thread.start()
  2812. return server, thread, records, 'http://127.0.0.1:'+str(server.server_port)+'/TEST-cursor-stop'
  2813. def foreign_preimage(root):
  2814. profile = root/'home/.cursor'
  2815. control = root/'home/.config/agent-notifications'
  2816. ledger = strict_json((control/'ownership.json').read_bytes())
  2817. config = pathlib.Path(case_env(root)['AGENT_NOTIFICATIONS_CONFIG'])
  2818. state_path = control.parent/'uap/state/state-v2.json'
  2819. return {'home':bounded_tree(root/'home'),'profile':bounded_tree(profile), 'cache':bounded_tree(root/'cache'),
  2820. 'globalConfig':bounded_tree(config),'otherConsumers':ledger['Consumers'],
  2821. 'uapState':strict_json(state_path.read_bytes()) if state_path.exists() else {'schema_version':4,'installations':[]},
  2822. 'policy':strict_json((control/'agent-notifications.json').read_bytes())}
  2823. def same_preserved_object(before, after, directory_members_changed=False):
  2824. if before == after: return True
  2825. if directory_members_changed and stat.S_ISDIR(before['mode']) and stat.S_ISDIR(after['mode']):
  2826. return {k:v for k,v in before.items() if k != 'nlink'} == {k:v for k,v in after.items() if k != 'nlink'}
  2827. return False
  2828. def installation_map(state):
  2829. rows = state.get('installations') or []
  2830. assert type(rows) is list and len(rows) <= 1024, 'installation membership bound'
  2831. result = {}
  2832. for row in rows:
  2833. key = row['installation_id']
  2834. assert type(key) is str and key and key not in result, 'duplicate/unknown installation identity'
  2835. result[key] = row
  2836. return result
  2837. def removal_memberships(before, after, binding, foreign_state):
  2838. """Exact foreign membership; only source-defined selected removal changes."""
  2839. old,new,foreign = installation_map(before),installation_map(after),installation_map(foreign_state)
  2840. assert list(old) == list(new), 'ordered installation addition/deletion during removal'
  2841. selected_id = binding['installationID']
  2842. assert selected_id in old and selected_id not in foreign, 'selected installation preimage'
  2843. for key in old:
  2844. if key != selected_id: assert old[key] == new[key], 'foreign installation/client/dataReceipt changed'
  2845. for key in foreign: assert key in old and old[key] == new[key] == foreign[key], 'original foreign installation membership changed'
  2846. left,right = copy.deepcopy(old[selected_id]),copy.deepcopy(new[selected_id])
  2847. clients = left['clients']
  2848. selected = [(key,value) for key,value in clients.items() if value['client_binding_id'] == binding['bindingID']]
  2849. assert len(selected) == 1 and len(clients) == 1, 'SAME one selected client removal'
  2850. client_key,client = selected[0]
  2851. assert right['clients'] == {} and right.get('data_retained') is True, 'selected binding/retained data disposition'
  2852. assert left.get('data_receipts') and left.get('data_receipts') == right.get('data_receipts'), 'complete selected acknowledged data receipt membership'
  2853. preferences = copy.deepcopy(left.get('install_preferences',[]))
  2854. assert client.get('install_intent','') in ('','prepare'), 'unknown source install intent'
  2855. if client.get('install_intent','') != '':
  2856. preference = {'client_id':client['client_id'],'scope':client['scope'],'install_intent':client.get('install_intent','')}
  2857. matches = [i for i,row in enumerate(preferences) if row['client_id'] == preference['client_id'] and row['scope'] == preference['scope']]
  2858. assert len(matches) <= 1, 'ambiguous selected install preference'
  2859. if matches: preferences[matches[0]] = preference
  2860. else: preferences.append(preference)
  2861. assert right.get('install_preferences',[]) == preferences, 'foreign/selected preference membership'
  2862. assert type(right.get('operation_group_id')) is str and 0 < len(right['operation_group_id'].encode()) <= 256, 'actual committed removal operation group'
  2863. assert type(right['updated_at']) is str and right['updated_at'] >= left['updated_at'], 'actual removal time'
  2864. for field in ('clients','data_retained','updated_at','operation_group_id','install_preferences'):
  2865. left.pop(field,None);right.pop(field,None)
  2866. assert left == right, 'unknown selected installation mutation'
  2867. top_before = {key:value for key,value in before.items() if key != 'installations'}
  2868. top_after = {key:value for key,value in after.items() if key != 'installations'}
  2869. assert top_before == top_after, 'unknown state top-level/transaction receipt mutation'
  2870. return {'installationIDsBefore':list(old),'installationIDsAfter':list(new),'foreignInstallationsPreserved':{key:new[key] for key in new if key != selected_id},
  2871. 'selectedClientRemoved':client,'selectedDataReceiptsRetained':new[selected_id]['data_receipts'],
  2872. 'selectedCommittedAfter':new[selected_id],'stateJSONMembersBefore':json_members(before),'stateJSONMembersAfter':json_members(after)}
  2873. def classify_home_removal(root,binding,foreign,before,after,native,classified,memberships):
  2874. """Cover every HOME path, including complete control/UAP and foreign sets."""
  2875. home = root/'home'
  2876. mapped = {}
  2877. roots = {'profile':home/'.cursor','data':pathlib.Path(binding['dataRoot']),'projection':None}
  2878. for row in classified:
  2879. base = roots.get(row['area'])
  2880. if base is not None and (base == home or home in base.parents):
  2881. path = str((base/row['path']).relative_to(home))
  2882. assert path not in mapped or mapped[path] == row['disposition'], 'ambiguous full HOME classification'
  2883. mapped[path] = row['disposition']
  2884. control = pathlib.Path(binding['controlRoot'])
  2885. state = control.parent/'uap/state'
  2886. semantic = {str((control/'agent-notifications.json').relative_to(home)):'owned selected disabled channels retained; exact other policy members preserved',
  2887. str((control/'ownership.json').relative_to(home)):'owned ledger exact selected consumer removal and actual generation changes',
  2888. str((state/'state-v2.json').relative_to(home)):'owned state exact selected client removal with complete retained/foreign receipt membership'}
  2889. result = []
  2890. for path in sorted(set(before)|set(after)):
  2891. old,new = before.get(path),after.get(path)
  2892. disposition = mapped.get(path)
  2893. if disposition is None and path in semantic:
  2894. assert old and new and all(old[k] == new[k] for k in ('mode','uid','gid','device','nlink')), 'committed metadata ownership changed'
  2895. assert stat.S_ISREG(new['mode']) and 'link' not in old and 'link' not in new, 'semantic file is not regular'
  2896. disposition = semantic[path]
  2897. if disposition is None and path in foreign['home']:
  2898. assert new is not None and same_preserved_object(foreign['home'][path],new,True), 'foreign full HOME preimage changed'
  2899. disposition = 'foreign full HOME object/member set retained'
  2900. if disposition is None and path in foreign.get('ownedOperatorObjects',{}):
  2901. assert new == old == foreign['ownedOperatorObjects'][path], 'owned TEST intent altered'
  2902. disposition = 'owned retained explicit TEST consent intent'
  2903. if disposition is None and path in native:
  2904. assert old and new and same_preserved_object(native[path],old,True) and same_preserved_object(old,new,True), 'native HOME retained artifact changed/purged'
  2905. disposition = 'owned retained natural Cursor HOME artifact from native boundaries'
  2906. if disposition is None and old and new and stat.S_ISDIR(new['mode']):
  2907. assert same_preserved_object(old,new,True), 'owned structural directory metadata drift'
  2908. children = [key for key in set(before)|set(after) if key != path and key.startswith(path.rstrip('/')+'/')]
  2909. fixed = {'.config/uap','.config/uap/state','.config/uap/state/operations','.config/uap/managed','.config/uap/plugin-data'}
  2910. assert children or path in fixed, 'unknown empty retained HOME directory'
  2911. disposition = 'owned retained structural directory; all concrete child memberships classified'
  2912. if disposition is None and path == '.config/uap/state/mutation.lock':
  2913. assert old == new and new and stat.S_ISREG(new['mode']), 'mutation lock unknown identity/membership'
  2914. disposition = 'owned retained source-standard mutation lock'
  2915. assert disposition is not None, 'unclassified full HOME object addition/deletion/remainder: '+path
  2916. result.append({'area':'home','path':path,'disposition':disposition,'before':old,'after':new})
  2917. return result
  2918. def classify_removal(root,binding,selected,foreign,before,after,phases,expected_hook,state,original_state,before_ledger,after_ledger,before_policy,after_policy):
  2919. """Every concrete path has one observed owner/disposition; unknown refuses."""
  2920. target = pathlib.Path(selected['target_locator'])
  2921. profile = root/'home/.cursor'
  2922. projection_prefix = str(target.relative_to(profile)) if profile in target.parents else None
  2923. native = {'home':{},'profile':{},'cache':{}}
  2924. for phase in phases:
  2925. for area in native:
  2926. left,right = phase['nativeObjectsBefore'][area],phase['nativeObjectsAfter'][area]
  2927. for path,facts in right.items():
  2928. if left.get(path) != facts:
  2929. assert facts['uid'] == facts['gid'] == 1000, 'native retained object credential drift'
  2930. native[area][path] = facts
  2931. result = []
  2932. for area in ('profile','cache','data','projection'):
  2933. left,right = before[area],after[area]
  2934. for path in sorted(set(left)|set(right)):
  2935. old,new = left.get(path),right.get(path)
  2936. disposition = None
  2937. is_projection = area == 'projection' or area == 'profile' and projection_prefix is not None and (path == projection_prefix or path.startswith(projection_prefix+'/'))
  2938. if is_projection:
  2939. assert old is not None and new is None, 'selected owned projection remainder/addition'
  2940. disposition = 'owned projection removed including MCP/skills/binding membership'
  2941. if disposition is None and area == 'data':
  2942. selector = pathlib.Path(binding['dataRoot'])/path
  2943. if selector == pathlib.Path(AUTHORITY_BASELINE[str(root)]['fixed']['Selector']):
  2944. assert old is not None and new is None, 'selected owned selector remainder'
  2945. disposition = 'owned selected selector removed'
  2946. if disposition is None and area == 'profile' and path == 'hooks.json':
  2947. assert old is not None and new is not None and new['sha256'] == hashlib.sha256(expected_hook).hexdigest() and new['byteLength'] == len(expected_hook)
  2948. assert all(old[k] == new[k] for k in ('mode','uid','gid','device','nlink')), 'remaining hooks permissions/ownership'
  2949. disposition = 'owned stop member removed; exact public pure removal remainder retained'
  2950. if disposition is None and area == 'data':
  2951. assert old is not None and new is not None and same_preserved_object(old,new,True), 'PLUGIN_DATA/receipt/cache purge or unknown addition'
  2952. disposition = 'owned retained PLUGIN_DATA/receipt/observation cache'
  2953. if disposition is None and path in foreign.get(area,{}):
  2954. original = foreign[area][path]
  2955. assert new is not None and same_preserved_object(original,new,True), 'foreign preimage object/member/bytes changed'
  2956. disposition = 'foreign preimage retained'
  2957. if disposition is None and path in native.get(area,{}):
  2958. assert old is not None and new is not None and same_preserved_object(old,new,True), 'natural native data removed/changed'
  2959. assert same_preserved_object(native[area][path],old,True), 'native phase receipt does not match pre-remove object'
  2960. disposition = 'owned retained natural Cursor trust/cache/session object from observed native boundary'
  2961. if disposition is None and new is not None and stat.S_ISDIR(new['mode']):
  2962. # ACK/receipt identity/creds.
  2963. known = [p for p in native.get(area,{}) if p.startswith(path+'/')]
  2964. if area == 'profile' and projection_prefix and projection_prefix.startswith(path+'/'): known.append(projection_prefix)
  2965. assert known and old is not None and same_preserved_object(old,new,True), 'unknown retained directory'
  2966. disposition = 'owned retained structural parent with classified child membership'
  2967. assert disposition is not None, 'unclassified removal object: '+area+'/'+path
  2968. result.append({'area':area,'path':path,'disposition':disposition,'before':old,'after':new})
  2969. memberships = removal_memberships(original_state,state,binding,foreign['uapState'])
  2970. ledger_before = copy.deepcopy(before_ledger); ledger_after = copy.deepcopy(after_ledger)
  2971. selected_keys = [key for key,value in before_ledger['Consumers'].items() if strict_json(value['Registration']) == binding]
  2972. assert len(selected_keys) == 1, 'exact pre-remove actual selected consumer'
  2973. selected_key = selected_keys[0]
  2974. expected_consumers = {key:value for key,value in before_ledger['Consumers'].items() if key != selected_key}
  2975. assert after_ledger['Consumers'] == expected_consumers == foreign['otherConsumers'], 'full foreign consumer/binding membership'
  2976. delta = after_ledger['Generation']-before_ledger['Generation']
  2977. assert type(delta) is int and delta > 0 and after_ledger['PolicyGeneration']-before_ledger['PolicyGeneration'] == delta, 'actual removal generations'
  2978. for field in ('Generation','PolicyGeneration','Consumers'):
  2979. ledger_before.pop(field); ledger_after.pop(field)
  2980. assert ledger_before == ledger_after and not after_ledger.get('PendingMutation'), 'unknown ledger mutation/membership'
  2981. assert before_policy == after_policy, 'uninstall may not mutate foreign/disabled policy members'
  2982. foreign_policy = copy.deepcopy(foreign['policy']); retained_policy = copy.deepcopy(after_policy)
  2983. assert retained_policy.get('route',{}).get('cursorNotifications') == {'desktop':False,'webhook':False}, 'removed selected channels must remain disabled'
  2984. for document in (foreign_policy,retained_policy):
  2985. if 'route' in document:
  2986. document['route'].pop('cursorNotifications',None)
  2987. if not document['route']: document.pop('route')
  2988. assert foreign_policy == retained_policy, 'foreign policy JSON members/values changed'
  2989. home_result = classify_home_removal(root,binding,foreign,before['home'],after['home'],native['home'],result,memberships)
  2990. return {'objects':result+home_result,'stateMembership':memberships,
  2991. 'consumerMembership':{'before':before_ledger['Consumers'],'after':after_ledger['Consumers'],'selectedRemoved':selected_key},
  2992. 'ledgerSemanticChanges':{'Generation':delta,'PolicyGeneration':delta},'policyMembersPreserved':json_members(after_policy),
  2993. 'unknownRemainders':[]}
  2994. def finish_lifecycle(root, artifact, package, installed, first_phase, observation, clock, records, foreign):
  2995. primary, selector, binding, generation = installed
  2996. native_bytes = first_phase['observation']['nativeBytes']
  2997. assert type(native_bytes) is bytes and 0 < len(native_bytes) <= LIMIT, 'actual native bytes required'
  2998. assert first_phase['result']['status'] == 'PASS'
  2999. assert len(records) == 1 and records[0]['responseAccepted'] is True, 'one actual accepted webhook response'
  3000. baseline = copy.deepcopy(records)
  3001. def check_no_new_effects():
  3002. observation.exchange('checkpoint')
  3003. assert records == baseline, 'duplicate/disabled webhook delivery'
  3004. installed_readback(root, primary, artifact, 'native-enabled', selector)
  3005. cli(root, primary, ['cursor-event', 'stop', '--binding', str(selector)], 'duplicate', native_bytes)
  3006. check_no_new_effects()
  3007. installed_readback(root, primary, artifact, 'duplicate', selector)
  3008. cli(root, primary, wizard(root, primary, artifact, None, 'install', False), 'disable')
  3009. installed_readback(root, primary, artifact, 'disabled', selector)
  3010. policy = strict_json((root/'home/.config/agent-notifications/agent-notifications.json').read_bytes())
  3011. assert policy['route']['cursorNotifications'] == {'desktop':False, 'webhook':False}
  3012. cli(root, primary, ['cursor-event', 'stop', '--binding', str(selector)], 'disabled-stop', native_bytes)
  3013. check_no_new_effects()
  3014. cli(root, primary, wizard(root, primary, artifact, package, 'update', True), 'update')
  3015. installed_readback(root, primary, artifact, 'updated', selector)
  3016. policy = strict_json((root/'home/.config/agent-notifications/agent-notifications.json').read_bytes())
  3017. assert policy['route']['cursorNotifications'] == {'desktop':False, 'webhook':False}
  3018. restarted = native_run(root, artifact, installed, 'disabled-restart', clock, observation)
  3019. assert restarted['result']['status'] == 'PASS', restarted['result']['failure']
  3020. assert restarted['observation']['facts']['conversation'] != first_phase['observation']['facts']['conversation']
  3021. assert restarted['observation']['facts']['generation'] != first_phase['observation']['facts']['generation']
  3022. check_no_new_effects()
  3023. installed_readback(root, primary, artifact, 'restarted', selector)
  3024. installed_readback(root, primary, artifact, 'pre-remove', selector)
  3025. before = authoritative_readback(root,primary,selector,binding,'pre-remove','remove-plan')
  3026. selected = before['selected']
  3027. target = pathlib.Path(selected['target_locator'])
  3028. assert physical(target) == target and target != root and root in target.parents, 'selected actual projection boundary'
  3029. before_trees = {'home':bounded_tree(root/'home'),'profile':bounded_tree(root/'home/.cursor'),'cache':bounded_tree(root/'cache'),
  3030. 'data':bounded_tree(binding['dataRoot']),'projection':bounded_tree(target)}
  3031. before_ledger = strict_json((pathlib.Path(binding['controlRoot'])/'ownership.json').read_bytes())
  3032. before_policy = strict_json((pathlib.Path(binding['controlRoot'])/'agent-notifications.json').read_bytes())
  3033. removal = strict_json(cli(root, primary, wizard(root, primary, artifact, None, 'uninstall', True), 'remove'))
  3034. assert removal['action'] == 'uninstall' and removal['outcome'] == 'completed' and not removal.get('nextActions')
  3035. after_public = authoritative_readback(root,primary,selector,binding,'removed','absent')
  3036. inspect = strict_json(cli(root,primary,wizard(root,primary,artifact,None,'inspect',True),'removed-inspect'))
  3037. selected_rows = [row for row in inspect['targets'] if row['client'] == 'cursor' and row['unit'] == 'agent-notify']
  3038. assert inspect['outcome'] == 'completed' and len(selected_rows) == 1 and selected_rows[0]['outcome'] == 'absent'
  3039. assert not inspect.get('nextActions') and not any(row['outcome'] in ('unknown','incomplete','installed') for row in inspect['targets'])
  3040. after = foreign_preimage(root)
  3041. assert after['globalConfig'] == foreign['globalConfig'], 'full foreign global config bytes/mode/UIDGID/raw-link identity'
  3042. assert after['otherConsumers'] == foreign['otherConsumers'], 'other actual core ledger bindings preserved'
  3043. assert not selector.exists() and not target.exists(), 'selected consumer/selector/projection/MCP/skills removal'
  3044. assert not (root/'home/.config/agent-notifications/transaction.json').exists()
  3045. after_trees = {'home':after['home'],'profile':after['profile'],'cache':after['cache'],'data':bounded_tree(binding['dataRoot']),
  3046. 'projection':bounded_tree(target)}
  3047. after_ledger = strict_json((pathlib.Path(binding['controlRoot'])/'ownership.json').read_bytes())
  3048. after_policy = strict_json((pathlib.Path(binding['controlRoot'])/'agent-notifications.json').read_bytes())
  3049. expected_hook = base64.b64decode(before['expectedHookBytes'],validate=True)
  3050. assert hashlib.sha256(expected_hook).hexdigest() == before['expectedHookSHA256']
  3051. assert (root/'home/.cursor/hooks.json').read_bytes() == expected_hook, 'actual pure Plan(Remove) remaining bytes'
  3052. classification = classify_removal(root,binding,selected,foreign,before_trees,after_trees,
  3053. [first_phase,restarted],expected_hook,after_public['state'],before['state'],before_ledger,after_ledger,before_policy,after_policy)
  3054. classified_bytes = (json.dumps(classification,indent=2)+'\n').encode()
  3055. assert len(classified_bytes) <= 16*LIMIT, 'full removal evidence file bound'
  3056. (root/'evidence/removal-full-membership.json').write_bytes(classified_bytes)
  3057. check_no_new_effects()
  3058. return restarted
  3059. def validate_installed_effects(root, run, installed, observation, phase, leader, clock, cleanup_signal, cleanup_roles):
  3060. reply = observation.exchange('phase',phase=phase,localLeader=leader,cleanupUsed=clock.cleanup_used,cleanupSignal=cleanup_signal,cleanupRoles=cleanup_roles)
  3061. raw = base64.b64decode(reply['nativeBytes'],validate=True)
  3062. assert hashlib.sha256(raw).hexdigest() == reply['nativeSHA256'], 'actual stream bytes/hash transport'
  3063. facts = captured_stop_bytes(raw)
  3064. assert strict_json(raw).get('cursor_version') == '2026.09.28-64d2043', 'actual source-pinned native version'
  3065. assert facts == reply['facts'] and facts['conversation'] == run['conversation'] and facts['generation'] == run['generation'], 'provider correlation is not byte generation'
  3066. assert facts['status'] == 'completed' and facts['loopCountKnown'] and facts['loopCount'] == 0, 'pinned native completed Stop body'
  3067. path = root/'evidence'/phase/'native-consumed-stdin.json'
  3068. path.write_bytes(raw)
  3069. path.with_suffix('.sha256').write_text(reply['nativeSHA256']+'\n')
  3070. return {'nativeBytes':raw,'facts':facts,'identity':reply['helperIdentity']}
  3071. def native_cwd_allowances(snapshot, root, installed):
  3072. # R189/R14 UID/ns/PID+birth/adoption.
  3073. primary,selector,binding,generation = installed
  3074. target = root/'home/.cursor/plugins/local'/selector.parent.name
  3075. mcp_argv = [str(target/'bin/claude-notifications'),'portable-launch','--locator',selector.name]
  3076. primary_argv = [str(primary),'portable-primary','--locator',selector.name,'--runtime-sha256',AUTHORITY_BASELINE[str(root)]['fixed']['ExecutableDigest'].removeprefix('sha256:')]
  3077. expected = [str(primary),'cursor-event','stop','--binding',str(selector)]
  3078. document = strict_json((root/'home/.cursor/hooks.json').read_bytes())
  3079. entries = [h['command'] for h in document['hooks']['stop'] if shlex.split(h['command']) == expected]
  3080. assert len(entries) == 1 and binding['scopeRoot'] == str(root/'home/.cursor')
  3081. command = entries[0]; allowed = {}
  3082. for row in snapshot['rows']:
  3083. if row.get('cwd') == str(target) and row.get('exe') == mcp_argv[0] and row.get('argv') == mcp_argv:
  3084. p = row['stat']; allowed[(p[0],p[5])] = str(target)
  3085. continue
  3086. if row.get('cwd') != binding['scopeRoot']: continue
  3087. argv = row.get('argv',[])
  3088. fixed_helper = argv == expected
  3089. fixed_shell = (len(argv) == 7 and row.get('exe') == argv[0]
  3090. and argv[0] in ('/usr/bin/bash','/bin/bash') and argv[1:4] == ['-O','extglob','-c']
  3091. and argv[5] == '--' and argv[6] == command
  3092. and hashlib.sha256(argv[4].encode()).hexdigest() ==
  3093. 'f4c3183f20f16337ef8df116657d288385fd88ca5551c69126c63d26969dbc29')
  3094. assert fixed_helper or fixed_shell, 'unqualified native USER cwd/argv'
  3095. p = row['stat']; allowed[(p[0],p[5])] = binding['scopeRoot']
  3096. for row in snapshot['rows']:
  3097. if row.get('cwd') != binding['runtimeRoot'] or row.get('exe') != str(primary) or row.get('argv') != primary_argv: continue
  3098. p = row['stat']; parents = [r['stat'] for r in snapshot['rows'] if r['stat'][0] == p[1]]
  3099. assert len(parents) == 1 and allowed.get((p[1],parents[0][5])) == str(target), 'unqualified portable primary parent'
  3100. allowed[(p[0],p[5])] = binding['runtimeRoot']
  3101. return allowed
  3102. def native_run(root, artifact, installed, phase, clock, observation):
  3103. global w
  3104. native_observation = None
  3105. assert phase in ('enabled-native','disabled-restart')
  3106. observation.exchange('begin-phase',phase=phase)
  3107. assert hashlib.sha256(WIRE_BYTES).hexdigest() == WIRE_SHA
  3108. w = types.ModuleType("accepted_wire")
  3109. exec(compile(WIRE_BYTES, "R14/wire_plan.py", "exec"), w.__dict__)
  3110. evidence = root/'evidence'/phase; evidence.mkdir(mode=0o700)
  3111. condition = threading.Condition(); messages = {}; rows = []
  3112. state = {'seq':0,'run':None,'stopResult':False,'close':False,'sent':False,'terminal':False,
  3113. 'sse':False,'failed':None,'requests':0,'active':0}
  3114. handlers = {}; all_handlers = set(); serve_thread = None
  3115. artifact_pins = list(ARTIFACT_PINS)
  3116. artifact_pins += [{'file':'cursor-agent','sha256':LAUNCHER_SHA}]
  3117. for pin in artifact_pins: assert hashlib.sha256((artifact/pin['file']).read_bytes()).hexdigest() == pin['sha256']
  3118. node_hash = hashlib.sha256((artifact/'node').read_bytes()).hexdigest()
  3119. def auth_refusal_metadata(handler):
  3120. path = handler.path
  3121. unary_operation = None
  3122. if path == '/agent.v1.AgentService/RunSSE': category = 'run-sse'
  3123. elif path == '/aiserver.v1.BidiService/BidiAppend': category = 'bidi-append'
  3124. elif path in w.unary_responses(): category = 'known-unary'; unary_operation = path.rsplit('/',1)[1]
  3125. elif path in REFUSALS: category = 'known-refused'
  3126. elif path == '/aiserver.v1.AnalyticsService/BootstrapStatsig': category = 'analytics-bootstrap'
  3127. else: category = 'other'
  3128. authorization = handler.headers.get('Authorization')
  3129. parts = authorization[:7].split(None,1) if authorization is not None else []
  3130. scheme = parts[0].lower() if parts else ''
  3131. return {'method':'POST','pathCategory':category,'unaryOperation':unary_operation,'authPresent':authorization is not None,
  3132. 'schemeCategory':('absent' if authorization is None else scheme if scheme in ('bearer','basic') else 'other'),
  3133. 'authLength':min(len(authorization),4096) if authorization is not None else 0}
  3134. def fail(e, auth_handler=None):
  3135. with condition:
  3136. first = state['failed'] is None
  3137. state['failed'] = state['failed'] or type(e).__name__ + ':' + str(e)[:240]; condition.notify_all()
  3138. if first:
  3139. try:
  3140. print('native-callback-first-failure',type(e).__name__[:64],source_failure_frames(e,native_run.__code__),file=sys.stderr,flush=True)
  3141. except Exception:
  3142. pass
  3143. if auth_handler is not None:
  3144. try:
  3145. print('native-auth-refusal',auth_refusal_metadata(auth_handler),file=sys.stderr,flush=True)
  3146. except Exception:
  3147. pass
  3148. def capture(q):
  3149. with condition:
  3150. rows.append(q); assert len(json.dumps(rows)) <= LIMIT
  3151. (evidence/'protocol.json').write_text(json.dumps(rows,indent=2))
  3152. def consume(rid,seq,logical):
  3153. with condition:
  3154. assert seq >= state['seq'] and seq not in messages, 'duplicate/old sequence'
  3155. messages[seq] = (rid,logical); assert len(messages) <= 16, 'pending append budget'
  3156. while state['seq'] in messages:
  3157. request,q = messages.pop(state['seq']); state['seq'] += 1
  3158. if state['run'] is not None: assert request == state['run']['requestId'], 'request identity'
  3159. capture({'seq':state['seq']-1,'requestId':request,**q})
  3160. if q['kind'] == 'run':
  3161. assert state['run'] is None; state['run'] = {'requestId':request,**q}
  3162. elif q['kind'] == 'stop-result':
  3163. assert state['sent'] and not state['stopResult'] and not state['close']; state['stopResult'] = True
  3164. elif q['kind'] == 'exec-close':
  3165. assert state['stopResult'] and not state['close']; state['close'] = True
  3166. else: assert q['kind'] == 'heartbeat'
  3167. condition.notify_all()
  3168. class H(http.server.BaseHTTPRequestHandler):
  3169. protocol_version = 'HTTP/1.1'
  3170. def setup(self):
  3171. super().setup(); self.connection.settimeout(clock.wait(35))
  3172. with condition:
  3173. handlers[threading.current_thread()] = self.connection
  3174. all_handlers.add(threading.current_thread())
  3175. if len(handlers) > 72 or len(all_handlers) > 128: fail(RuntimeError('HTTP connection budget'))
  3176. def finish(self):
  3177. try: super().finish()
  3178. finally:
  3179. with condition: handlers.pop(threading.current_thread(),None); condition.notify_all()
  3180. def log_message(self,*a): pass
  3181. def send_error(self,*a,**kw):
  3182. fail(ValueError('HTTP parse/method error')); super().send_error(*a,**kw)
  3183. def answer(self,status,data,typ='application/proto'):
  3184. self.send_response(status); self.send_header('Content-Type',typ); self.send_header('Content-Length',str(len(data)))
  3185. self.end_headers(); self.wfile.write(data); self.wfile.flush()
  3186. def chunk(self,data):
  3187. assert len(data) <= LIMIT+5, 'frame budget'
  3188. self.wfile.write(hex(len(data))[2:].encode()+b'\r\n'+data+b'\r\n'); self.wfile.flush()
  3189. def await_state(self,predicate):
  3190. with condition:
  3191. assert condition.wait_for(lambda:predicate() or state['failed'],clock.wait(25)), 'native acknowledgement timeout'
  3192. assert not state['failed'], state['failed']
  3193. def do_POST(self):
  3194. with condition: state['active'] += 1
  3195. auth_check = False
  3196. try:
  3197. with condition: state['requests'] += 1; assert state['requests'] <= 128
  3198. auth_check = True
  3199. assert self.headers.get('Authorization') == ('Bearer ' + 'TEST-loopback-not-a-secret')
  3200. auth_check = False
  3201. assert self.headers.get('Content-Encoding','identity') in ['identity','gzip']
  3202. assert self.headers.get('Transfer-Encoding','').lower() in ['', 'chunked']
  3203. data = body(self); capture({'path':self.path,'bodyHex':data.hex(),'syntheticAuthMatches':True})
  3204. if self.path in w.unary_responses(): self.answer(200,w.unary_responses()[self.path]); return
  3205. if self.path == '/aiserver.v1.BidiService/BidiAppend':
  3206. rid,seq,msg = append(data); logical = classify(msg)
  3207. self.answer(200,b''); consume(rid,seq,logical); return
  3208. if self.path == '/agent.v1.AgentService/RunSSE':
  3209. with condition: assert not state['sse']; state['sse'] = True
  3210. assert len(data) >= 5 and data[0] in [0,1] and struct.unpack('>I',data[1:5])[0] == len(data)-5
  3211. payload = data[5:]
  3212. if data[0] == 1:
  3213. with gzip.GzipFile(fileobj=io.BytesIO(payload)) as f: payload = f.read(LIMIT+1)
  3214. assert len(payload) <= LIMIT; rid = w.first(payload,1).decode()
  3215. self.send_response(200); self.send_header('Content-Type','application/connect+proto')
  3216. self.send_header('Transfer-Encoding','chunked'); self.end_headers()
  3217. self.await_state(lambda:state['run'] is not None); run = state['run']; assert run['requestId'] == rid
  3218. with condition: state['sent'] = True
  3219. self.chunk(w.stop_frame(run['conversation'],run['generation']))
  3220. capture({'stopSent':True,'conversation':run['conversation'],'generation':run['generation']})
  3221. self.await_state(lambda:state['stopResult'] and state['close'])
  3222. self.chunk(w.text_frame()); self.chunk(w.terminal_frames()); self.wfile.write(b'0\r\n\r\n'); self.wfile.flush()
  3223. with condition: state['terminal'] = True
  3224. capture({'terminalSent':True}); return
  3225. capture({'unsupportedRPC':self.path})
  3226. self.answer(501,b'{"code":"unimplemented","message":"TEST finite allowlist"}','application/json')
  3227. assert self.path in REFUSALS, 'unknown server effects'
  3228. except Exception as e: fail(e,self if auth_check else None)
  3229. finally:
  3230. with condition: state['active'] -= 1; condition.notify_all()
  3231. def do_GET(self):
  3232. fail(ValueError('unsupported HTTP method'))
  3233. self.answer(501,b'{"code":"unimplemented","message":"TEST finite allowlist"}','application/json')
  3234. class Server(http.server.ThreadingHTTPServer):
  3235. daemon_threads = True
  3236. def process_request(self,request,address):
  3237. t = threading.Thread(target=self.process_request_thread,args=(request,address),daemon=True)
  3238. with condition:
  3239. all_handlers.add(t); handlers[t] = request
  3240. if len(handlers) > 72 or len(all_handlers) > 128: fail(RuntimeError('HTTP connection budget'))
  3241. t.start() # register before scheduling; shutdown then joins every created callback thread
  3242. def process_request_thread(self,request,address):
  3243. try:
  3244. with condition:
  3245. if state['failed'] is not None: raise AssertionError(state['failed'])
  3246. tid = threading.get_native_id(); local = trace_task_identity(tid)
  3247. if local['pid'] != tid or local['tgid'] != os.getpid(): raise AssertionError('owned HTTP local thread identity')
  3248. held = {'tid':tid,'birth':local['birth']}
  3249. reply = observation.exchange('controller-thread',phase=phase,thread=held)
  3250. if reply.get('controllerThread') != {**held,'phase':phase}: raise AssertionError('owned HTTP thread ACK identity')
  3251. with condition:
  3252. if state['failed'] is not None: raise AssertionError(state['failed'])
  3253. except Exception as error:
  3254. fail(error)
  3255. try: self.shutdown_request(request)
  3256. finally:
  3257. with condition: handlers.pop(threading.current_thread(),None); condition.notify_all()
  3258. return
  3259. super().process_request_thread(request,address)
  3260. def handle_error(self,*a):
  3261. error = sys.exc_info()[1]
  3262. fail(error if error is not None else RuntimeError('HTTP handler error'))
  3263. server = Server(('127.0.0.1',0),H)
  3264. serve_thread = threading.Thread(target=server.serve_forever,daemon=True)
  3265. env = {'HOME':str(root/'home'),'USER':'TEST','LOGNAME':'TEST','PATH':'/usr/bin:/bin','LANG':'C.UTF-8',
  3266. 'TMPDIR':str(root/'tmp'),'XDG_CACHE_HOME':str(root/'cache'),'AGENT_CLI_CREDENTIAL_STORE':'file',
  3267. 'CURSOR_AUTH_TOKEN':'TEST-loopback-not-a-secret', **SESSION_ENV}
  3268. argv = [str(artifact/'cursor-agent'),'--endpoint','http://127.0.0.1:'+str(server.server_port),
  3269. '--workspace',str(root/'workspace'),'--model','TEST-native-stop',
  3270. '--trust','--print','--output-format','json','TEST deterministic stop mechanics']
  3271. (evidence/'command.json').write_text(json.dumps({'argv':argv,'cwd':str(root/'workspace'),'envKeys':list(env),
  3272. 'network':'new PID+net namespace loopback only','realCredentials':False,'testConsent':CONSENT},indent=2))
  3273. native_before = {'home':bounded_tree(root/'home'),'profile':bounded_tree(root/'home/.cursor'),'cache':bounded_tree(root/'cache')}
  3274. start = time.monotonic(); clock.native_started(); runtime_deadline = clock.work
  3275. birth_floor = int(time.clock_gettime(time.CLOCK_BOOTTIME)*os.sysconf('SC_CLK_TCK'))
  3276. failure = None; clean = False; cleanup_signal = False; natural = False
  3277. namespace = os.readlink('/proc/self/ns/pid'); network = os.readlink('/proc/self/ns/net'); leader = None; roles = []; snapshots = []; cleanup_start = None
  3278. native_seconds = None; cleanup_seconds = None; active_previous = {}; active_checks = 0
  3279. native = subprocess.Popen(argv,cwd=root/'workspace',env=env,stdin=subprocess.DEVNULL,
  3280. stdout=subprocess.PIPE,stderr=subprocess.PIPE,start_new_session=True)
  3281. local_leader = proc_identity(native.pid)
  3282. observation.exchange('leader',phase=phase,localLeader=local_leader,nativeStart=start)
  3283. serve_thread.start() # Bind before responses.
  3284. def observe_active(phase):
  3285. return capture_active(evidence,own_processes(),namespace,phase,active_previous,active_checks,birth_floor)
  3286. def writable_budget():
  3287. assert sum(p.stat().st_size for p in root.rglob('*') if p.is_file()) <= 1024**3, 'writable bytes budget'
  3288. def drain(stream, name):
  3289. size = 0
  3290. try:
  3291. with (evidence/name).open('xb') as f:
  3292. while True:
  3293. b = stream.read1(8192)
  3294. if not b: break
  3295. size += len(b); assert size <= 131072, 'native output budget'; f.write(b)
  3296. except Exception as e: fail(e)
  3297. finally: stream.close()
  3298. pumps = [threading.Thread(target=drain,args=(pipe,name),daemon=True)
  3299. for pipe,name in [(native.stdout,'native.stdout'),(native.stderr,'native.stderr')]]
  3300. for t in pumps: t.start()
  3301. def check_effects():
  3302. nonlocal native_observation
  3303. assert native.returncode == 0 and not state['failed'], 'native exit or protocol failure'
  3304. assert state['run'] and state['sent'] and state['stopResult'] and state['close'] and state['terminal']
  3305. assert state['active'] == 0 and not messages, 'HTTP callback/pending append join'
  3306. if clean:
  3307. native_observation = validate_installed_effects(root,state['run'],installed,observation,phase,local_leader,clock,cleanup_signal,roles)
  3308. assert not any(q['unsupportedRPC'] not in REFUSALS for q in rows if 'unsupportedRPC' in q)
  3309. try:
  3310. observe_active('active')
  3311. leader = next(p for p in own_processes() if p[0] == native.pid)
  3312. assert leader[0] == leader[2] == leader[4], 'native group/session not unique'
  3313. while native.poll() is None:
  3314. snapshot, active_previous = observe_owned_active(evidence,leader,namespace,network,root,active_previous,
  3315. active_checks,birth_floor,runtime_deadline,native,installed)
  3316. assert not state['failed'], state['failed']
  3317. active_checks += 1; writable_budget(); time.sleep(clock.wait(.1))
  3318. native_seconds = time.monotonic()-start
  3319. assert native_seconds <= 90, 'native runtime budget'; natural = native.returncode == 0
  3320. cleanup_start = time.monotonic(); deadline = clock.cleanup_deadline()
  3321. with condition: assert condition.wait_for(lambda:state['active'] == 0 or state['failed'],min(clock.wait(1,cleanup=True),max(0,deadline-time.monotonic())))
  3322. for t in pumps: t.join(timeout=min(clock.wait(1,cleanup=True),max(0,deadline-time.monotonic())))
  3323. assert all(not t.is_alive() for t in pumps), 'native output pump join'
  3324. check_effects(); validate_output(evidence,state['run'])
  3325. observe_cleanup_facts(evidence,namespace,network,root,active_previous,active_checks,birth_floor,deadline)
  3326. # 8s kernel retry.
  3327. procs = own_processes(); snapshots.append({'phase':'before','processes':procs})
  3328. roles = worker_roles(owned_survivors(procs,leader,1,namespace),artifact,root,namespace)
  3329. writable_budget()
  3330. # Observe first.
  3331. cleanup_signal = request_owned_cleanup(own_processes(),leader,1,namespace,deadline)
  3332. clean = join_owned(native,leader,1,namespace,deadline,budget=writable_budget)
  3333. cleanup_seconds = time.monotonic()-cleanup_start
  3334. assert clean, 'owned descendant join timeout'
  3335. snapshots.append({'phase':'after','processes':own_processes()})
  3336. check_effects(); validate_output(evidence,state['run']); writable_budget()
  3337. for pin in artifact_pins: assert hashlib.sha256((artifact/pin['file']).read_bytes()).hexdigest() == pin['sha256']
  3338. assert hashlib.sha256((artifact/'node').read_bytes()).hexdigest() == node_hash, 'vendor node changed'
  3339. except Exception as e:
  3340. failure = type(e).__name__+':'+str(e)[:240]
  3341. try:
  3342. print('native-observation-failure',type(e).__name__[:64],
  3343. 'outerRemaining',round(clock.outer-time.monotonic(),6),
  3344. source_failure_frames(e,native_run.__code__),file=sys.stderr,flush=True)
  3345. except Exception:
  3346. pass
  3347. finally:
  3348. # Fail teardown.
  3349. if serve_thread.ident is not None: server.shutdown()
  3350. server.server_close()
  3351. if cleanup_start is None: cleanup_start = time.monotonic(); deadline = clock.cleanup_deadline()
  3352. if serve_thread.ident is not None: serve_thread.join(timeout=min(clock.wait(1,cleanup=True),max(0,deadline-time.monotonic())))
  3353. with condition: pending_handlers = list(handlers.items())
  3354. for thread,conn in pending_handlers:
  3355. try: conn.shutdown(socket.SHUT_RDWR); conn.close()
  3356. except OSError: pass
  3357. http_deadline = min(deadline,time.monotonic()+clock.wait(1,cleanup=True))
  3358. for thread in all_handlers: thread.join(timeout=max(0,http_deadline-time.monotonic()))
  3359. failure = failure or state['failed']
  3360. if handlers or any(t.is_alive() for t in all_handlers) or serve_thread.is_alive() or state['active'] or messages or any(t.is_alive() for t in pumps):
  3361. failure = failure or 'output/HTTP join incomplete'
  3362. (evidence/'cleanup-process-snapshot.json').write_text(json.dumps({'nativePid':native.pid,'controllerPid':1,
  3363. 'leaderIdentity':leader,'pidNamespace':namespace,'roles':roles,'snapshots':snapshots},indent=2))
  3364. clock.charge_cleanup(cleanup_start)
  3365. result = {'status':'PASS' if failure is None and clean else 'FAIL','failure':failure,
  3366. 'nativeExit':native.returncode,'parentNaturalExit':natural,
  3367. 'ownedGroupSIGTERMRequested':cleanup_signal,'ownedNamespaceDescendantsJoined':clean,
  3368. 'actualNativeRun':state['run'],'nativeStopAck':state['stopResult'],
  3369. 'nativeExecClose':state['close'],'terminalSent':state['terminal'],
  3370. 'entry':'installed-USER','GUIVisibility':'NOT_RUN'}
  3371. (evidence/'result.json').write_text(json.dumps(result,indent=2)+'\n')
  3372. native_after = {'home':bounded_tree(root/'home',vendor_root=root),'profile':bounded_tree(root/'home/.cursor',vendor_root=root),'cache':bounded_tree(root/'cache')}
  3373. boundary_bytes = (json.dumps({'before':native_before,'after':native_after},indent=2)+'\n').encode()
  3374. assert len(boundary_bytes) <= 16*LIMIT, 'full native boundary evidence file bound'
  3375. (evidence/'native-retained-object-boundaries.json').write_bytes(boundary_bytes)
  3376. return {'result':result,'observation':native_observation,'nativeObjectsBefore':native_before,'nativeObjectsAfter':native_after}
  3377. def main(args):
  3378. global CASE_CLOCK, SESSION_ENV, READBACK_INPUTS
  3379. if args.validate:
  3380. compile(HERE.joinpath('native_case.py').read_bytes(), str(HERE/'native_case.py'), 'exec')
  3381. compile(WIRE_BYTES, 'R14/wire_plan.py', 'exec')
  3382. return 0
  3383. assert args.execute and args.inputs, 'select pure --validate or root --execute with real inputs'
  3384. assert args.consent == CONSENT, 'root ONE-case authorization required'
  3385. CASE_CLOCK = CaseClock(args.outer_deadline if args.inside else time.monotonic()+110)
  3386. inputs = execution_inputs(args.inputs, args.inside)
  3387. READBACK_INPUTS = inputs
  3388. require_native_observation_contract(inputs,CASE_CLOCK,args.inside)
  3389. root, artifact = pathlib.Path(inputs['root']), pathlib.Path(inputs['artifact'])
  3390. if not args.inside:
  3391. assert os.geteuid() == 0 and not root.exists()
  3392. qualified_runner(root/'home/.cursor', inputs['machineID'])
  3393. os.umask(0o077)
  3394. root.mkdir(mode=0o700)
  3395. for n in ['home','cache','tmp','workspace','evidence','recipe']:
  3396. (root/n).mkdir(mode=0o700)
  3397. (root/'home/.cursor').mkdir(mode=0o700)
  3398. (root/'recipe/native_case.py').write_bytes((HERE/'native_case.py').read_bytes())
  3399. (root/'recipe/authoritative_readback.go').write_bytes(READBACK_SOURCE_BYTES)
  3400. outer_peer,inner_peer = socket.socketpair(socket.AF_UNIX,socket.SOCK_STREAM)
  3401. command = ['/usr/bin/unshare','--net','--pid','--fork','--mount-proc','--kill-child=KILL',
  3402. '/usr/bin/python3','-B','-S',str(root/'recipe/native_case.py'),'--execute','--inside',
  3403. '--inputs',args.inputs,'--consent',CONSENT,'--old-net',os.readlink('/proc/self/ns/net'),
  3404. '--old-pid',os.readlink('/proc/self/ns/pid'),'--control-fd',str(inner_peer.fileno()),
  3405. '--outer-deadline',str(CASE_CLOCK.outer)]
  3406. subprocess.run(['/usr/bin/chown','-R','1000:1000',str(root)],check=True,timeout=CASE_CLOCK.wait(5))
  3407. with (root/'evidence/harness.stdout').open('xb') as out, (root/'evidence/harness.stderr').open('xb') as err:
  3408. child = subprocess.Popen(command,env={'PATH':'/usr/bin:/bin','HOME':str(root/'home'),'LANG':'C.UTF-8'},
  3409. stdout=out,stderr=err,start_new_session=True,cwd=root/'workspace',pass_fds=(inner_peer.fileno(),))
  3410. inner_peer.close()
  3411. observer = OuterObservation(child,outer_peer,inputs,CASE_CLOCK)
  3412. forced = False
  3413. outer_error = None
  3414. try:
  3415. while child.poll() is None:
  3416. assert time.monotonic() < CASE_CLOCK.outer, 'original outer T0+110 deadline'
  3417. if observer.trace is not None and getattr(observer.trace,'error',None):
  3418. raise observer.trace.first_error or AssertionError(observer.trace.error)
  3419. if observer.session is not None and getattr(observer.session,'error',None):
  3420. raise AssertionError(observer.session.error)
  3421. if observer.closed:
  3422. child.wait(timeout=max(.001,CASE_CLOCK.outer-time.monotonic()))
  3423. break
  3424. if select.select([outer_peer],[],[],min(.05,max(0,CASE_CLOCK.outer-time.monotonic())))[0]:
  3425. observer.request()
  3426. code = child.returncode
  3427. forced = code != 0 or not observer.closed
  3428. except Exception as error:
  3429. outer_error = type(error).__name__+':'+str(error)[:240]
  3430. forced = True
  3431. try:
  3432. print('outer-observation-failure',type(error).__name__[:64],source_failure_frames(error,main.__code__),file=sys.stderr,flush=True)
  3433. except Exception:
  3434. pass
  3435. if observer.trace is not None:
  3436. try: observer.trace.force_contain(observer.trace.first_error or error)
  3437. except Exception as cleanup_error:
  3438. outer_error += ';observer terminal containment unproved:'+type(cleanup_error).__name__
  3439. if child.poll() is None: os.killpg(child.pid,signal.SIGKILL)
  3440. child.wait(timeout=max(.001,CASE_CLOCK.outer+5-time.monotonic())); code = 1
  3441. finally:
  3442. outer_peer.close()
  3443. # FAIL samples; no PASS/budget.
  3444. if forced:
  3445. cleanup_end = CASE_CLOCK.outer+5
  3446. if observer.trace is not None:
  3447. try:
  3448. observer.trace.force_contain(observer.trace.first_error or AssertionError(outer_error or 'owned forced containment'))
  3449. except Exception as error:
  3450. outer_error = (outer_error or '')+';observer containment unproved:'+type(error).__name__
  3451. try: observer.trace.failure_join(cleanup_end)
  3452. except Exception as error:
  3453. outer_error = (outer_error or '')+';observer join unproved:'+type(error).__name__
  3454. if observer.session is not None:
  3455. try: observer.session.failure_join(cleanup_end)
  3456. except Exception as error:
  3457. outer_error = (outer_error or '')+';session join unproved:'+type(error).__name__
  3458. if not (root/'evidence/result.json').exists():
  3459. (root/'evidence/result.json').write_text(json.dumps({'status':'FAIL','failure':outer_error or 'isolation/startup before native receipt'}))
  3460. assert time.monotonic() <= CASE_CLOCK.outer+5, 'forced containment maximum T0+115'
  3461. if code != 0 or forced:
  3462. result = strict_json((root/'evidence/result.json').read_text())
  3463. result['status'] = 'FAIL'; result['failure'] = result.get('failure') or outer_error or 'outer namespace containment/join failure'
  3464. (root/'evidence/result.json').write_text(json.dumps(result,indent=2))
  3465. (root/'evidence/namespace-join.json').write_text(json.dumps({'outerExit':code,'namespaceJoined':child.poll() is not None,'forcedContainment':forced}))
  3466. return code if code != 0 else int(forced or strict_json((root/'evidence/result.json').read_bytes()).get('status') != 'PASS')
  3467. assert os.geteuid() == 0 and os.getpid() == 1
  3468. assert os.readlink('/proc/self/ns/net') != args.old_net and os.readlink('/proc/self/ns/pid') != args.old_pid
  3469. subprocess.run(['/usr/sbin/ip','link','set','lo','up'],check=True,timeout=CASE_CLOCK.wait(5))
  3470. assert [q['ifname'] for q in strict_json(subprocess.check_output(['/usr/sbin/ip','-j','link'],timeout=CASE_CLOCK.wait(5)))] == ['lo']
  3471. assert strict_json(subprocess.check_output(['/usr/sbin/ip','-j','route'],timeout=CASE_CLOCK.wait(5))) == []
  3472. assert strict_json(subprocess.check_output(['/usr/sbin/ip','-j','-6','route'],timeout=CASE_CLOCK.wait(5))) == []
  3473. os.setgroups([]); os.setgid(1000); os.setuid(1000); os.umask(0o077)
  3474. assert ctypes.CDLL(None).prctl(36,1,0,0,0) == 0
  3475. # Primary 25264136B; cap N+1.
  3476. assert (pathlib.Path(inputs['stage'])/'claude-notifications-linux-amd64').stat().st_size <= TEST_RUNTIME_FILE_LIMIT, 'runtime copy exceeds fixed per-file cap'
  3477. resource.setrlimit(resource.RLIMIT_CORE,(0,0)); resource.setrlimit(resource.RLIMIT_FSIZE,(TEST_RUNTIME_FILE_LIMIT,TEST_RUNTIME_FILE_LIMIT))
  3478. observation = ControllerObservation(socket.socket(fileno=args.control_fd),CASE_CLOCK)
  3479. server, thread, records, webhook_url = owned_webhook(root)
  3480. try:
  3481. installed, foreign = install_and_confirm(root, artifact, inputs, webhook_url)
  3482. assert own_processes() == [next(p for p in own_processes() if p[0] == 1)], 'setup children unresolved'
  3483. primary,selector,binding,generation = installed
  3484. reply = observation.exchange('prepare',controller=proc_identity(1),primary=str(primary),selector=str(selector),binding=binding,generation=generation)
  3485. SESSION_ENV = reply['environment']
  3486. assert set(SESSION_ENV) == {'DBUS_SESSION_BUS_ADDRESS','DISPLAY','XAUTHORITY'}
  3487. enabled = native_run(root, artifact, installed, 'enabled-native',CASE_CLOCK,observation)
  3488. assert enabled['result']['status'] == 'PASS', enabled['result']['failure']
  3489. restarted = finish_lifecycle(root,artifact,inputs['package'],installed,enabled,observation,CASE_CLOCK,records,foreign)
  3490. assert own_processes() == [next(p for p in own_processes() if p[0] == 1)], 'final native/CLI descendants unresolved'
  3491. closed = observation.exchange('close')
  3492. CASE_CLOCK.cleanup_used = closed['cleanupUsed']
  3493. (root/'evidence/result.json').write_text(json.dumps({'status':'PASS','phases':[enabled['result'],restarted['result']],
  3494. 'entry':'installed-USER','GUIVisibility':'NOT_RUN'},indent=2)+'\n')
  3495. return 0
  3496. finally:
  3497. began = time.monotonic(); deadline = CASE_CLOCK.cleanup_deadline()
  3498. server.shutdown(); server.server_close(); thread.join(timeout=min(1,max(0,deadline-time.monotonic())))
  3499. assert not thread.is_alive(), 'owned webhook join'
  3500. assert not server.case_failures, 'owned webhook failed; do not retry unknown effects'
  3501. CASE_CLOCK.charge_cleanup(began)
  3502. if __name__ == '__main__':
  3503. parser = argparse.ArgumentParser()
  3504. operation = parser.add_mutually_exclusive_group(required=True)
  3505. operation.add_argument('--execute', action='store_true')
  3506. operation.add_argument('--validate', action='store_true')
  3507. parser.add_argument('--inputs')
  3508. parser.add_argument('--consent')
  3509. parser.add_argument('--inside', action='store_true')
  3510. parser.add_argument('--old-net'); parser.add_argument('--old-pid')
  3511. parser.add_argument('--control-fd',type=int); parser.add_argument('--outer-deadline',type=float)
  3512. try:
  3513. sys.exit(main(parser.parse_args()))
  3514. except IncompleteInstalledContract as error:
  3515. print(json.dumps({'status':'INCOMPLETE_INSTALLED_OBSERVATION','nativeE':'NOT_RUN',
  3516. 'reason':str(error)}), file=sys.stderr)
  3517. sys.exit(2)
bin/setup.sh · Bundled script · 454 lines · 1 finding marked
  1. #!/usr/bin/env bash
  2. # Usage: curl -fsSL https://777genius.github.io/agent-notifications/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 2 on GitHub
  3. # Keep this entry point small: installation runs from one exact release commit.
  4. # This entry point runs once in its own Bash process. Keep signal cleanup in
  5. # that process so its caller observes exit only after owned children are joined.
  6. main() {
  7. set -euo pipefail
  8. # A terminal can retain an unlinked cwd. Recover before downloads or child
  9. # shells inherit it; keep valid caller-relative paths unchanged.
  10. if ! builtin pwd -P >/dev/null 2>&1; then
  11. cd -P / 2>/dev/null || { echo 'Cannot recover the installer working directory.' >&2; exit 1; }
  12. fi
  13. # Only opt into loader parsing when the new selector is present. Every
  14. # existing invocation is forwarded verbatim to the released bootstrap.
  15. original_args=("$@")
  16. multi=0
  17. new_setup=0
  18. ui_mode=""
  19. ui_args=()
  20. activity_args=()
  21. activity_mode=""
  22. activity_limit=""
  23. selector=""
  24. singleton=""
  25. channels=0
  26. json=0
  27. pending=0
  28. unknown_arg=""
  29. seen=""
  30. route_seen=""
  31. nav="" app="" team="" caller_unknown="" caller_asserted="" notify=""
  32. scope_root="" client_exec="" pi_scope=0
  33. cursor_args=()
  34. pi_args=()
  35. # Classify questions and validate new flags before the first download.
  36. while [ "$#" -gt 0 ]; do
  37. key=${1%%=*}
  38. case "$key" in
  39. --ui|--plain|--product|--products|--desktop|--webhook|--json|--scope-root|--client-executable|--pi-agent-dir|--pi-executable)
  40. case "$key" in
  41. --ui|--plain) ;;
  42. *) case ",$seen," in *",$key,"*) echo "Use $key once." >&2; exit 1 ;; esac
  43. seen=${seen:+$seen,}$key ;;
  44. esac ;;
  45. esac
  46. case "$1" in
  47. --ui|--ui=*|--plain)
  48. case "$1" in
  49. --plain) mode=plain; shift ;;
  50. --ui) [ "$#" -ge 2 ] || { echo "--ui requires a mode." >&2; exit 1; }; mode=$2; shift 2 ;;
  51. *) mode=${1#--ui=}; shift ;;
  52. esac
  53. case "$mode" in auto|rich|plain) ;; *) echo "Invalid UI mode." >&2; exit 1 ;; esac
  54. [ -z "$ui_mode" ] || [ "$ui_mode" = "$mode" ] || { echo "Conflicting UI modes." >&2; exit 1; }
  55. ui_mode=$mode; ui_args=(--ui "$mode") ;;
  56. --activity|--activity=*|--activity-limit|--activity-limit=*)
  57. case "$1" in *=*) value=${1#*=}; shift ;; *) [ "$#" -ge 2 ] || { echo "$1 requires a value." >&2; exit 1; }; value=$2; shift 2 ;; esac
  58. if [ "$key" = --activity ]; then
  59. case "$value" in compact|expanded|off) ;; *) echo "Invalid activity mode." >&2; exit 1 ;; esac
  60. [ -z "$activity_mode" ] || [ "$activity_mode" = "$value" ] || { echo "Conflicting activity modes." >&2; exit 1; }
  61. activity_mode=$value
  62. else
  63. case "$value" in [1-9]|1[0-6]) ;; *) echo "Activity limit must be 1..16." >&2; exit 1 ;; esac
  64. [ -z "$activity_limit" ] || [ "$activity_limit" = "$value" ] || { echo "Conflicting activity limits." >&2; exit 1; }
  65. activity_limit=$value
  66. fi ;;
  67. --product|--products|--product=*|--products=*)
  68. [ -z "$selector" ] || { echo "Use one product selector once." >&2; exit 1; }
  69. selector=$key
  70. case "$1" in
  71. *=*) singleton=${1#*=}; shift ;;
  72. *) [ "$#" -ge 2 ] || { echo "$1 requires a value." >&2; exit 1; }; singleton=$2; shift 2 ;;
  73. esac
  74. [ -n "$singleton" ] || { echo "Empty product selector." >&2; exit 1; }
  75. if [ "$selector" = --product ]; then
  76. case "$singleton" in claude|codex|both|opencode|gemini|qoder|cursor|pi) ;; *) echo "Invalid product." >&2; exit 1 ;; esac
  77. fi ;;
  78. --scope-root|--scope-root=*|--client-executable|--client-executable=*)
  79. case "$1" in
  80. *=*) value=${1#*=}; shift ;;
  81. *) [ "$#" -ge 2 ] || { echo "Missing value for $key." >&2; exit 1; }; value=$2; shift 2 ;;
  82. esac
  83. case "$value" in /*|[A-Za-z]:/*|[A-Za-z]:\\*) ;; *) echo "Path must be absolute." >&2; exit 1 ;; esac
  84. case "$key" in --scope-root) scope_root=$value ;; *) client_exec=$value ;; esac ;;
  85. --pi-agent-dir|--pi-agent-dir=*|--pi-executable|--pi-executable=*)
  86. case "$1" in
  87. *=*) value=${1#*=}; shift ;;
  88. *) [ "$#" -ge 2 ] || { echo "Missing value for $key." >&2; exit 1; }; value=$2; shift 2 ;;
  89. esac
  90. case "$value" in /*|[A-Za-z]:/*|[A-Za-z]:\\*) ;; *) echo "Path must be absolute." >&2; exit 1 ;; esac
  91. pi_scope=1 ;;
  92. --desktop|--webhook|--desktop=true|--desktop=false|--webhook=true|--webhook=false) channels=$((channels + 1)); shift ;;
  93. --json) json=1; shift ;;
  94. --agent-notify|--skip-agent-notify|--request-permission|--preserve-policy|--navigation|--navigation=*|--app|--app=*|--team-id|--team-id=*|--allow-unknown-caller|--allow-unknown-caller=*|--allow-caller-asserted|--allow-caller-asserted=*|--codex-home|--codex-home=*)
  95. case ",$route_seen," in *",$key,"*) echo "Use $key once." >&2; exit 1 ;; esac
  96. route_seen=${route_seen:+$route_seen,}$key
  97. case "$key" in
  98. --agent-notify|--skip-agent-notify)
  99. [ -z "$notify" ] || { echo "Use one agent-notify option once." >&2; exit 1; }
  100. notify=$key; shift; continue ;;
  101. --request-permission|--preserve-policy) shift; continue ;;
  102. esac
  103. case "$1" in
  104. *=*) value=${1#*=}; shift ;;
  105. *) [ "$#" -ge 2 ] || { echo "Missing value for $1." >&2; exit 1; }; value=$2; shift 2 ;;
  106. esac
  107. case "$key" in
  108. --navigation) [ "$value" = none ] || { echo "Invalid navigation." >&2; exit 1; }; nav=$value ;;
  109. --app|--codex-home)
  110. case "$value" in /*) ;; *) echo "Path must be absolute." >&2; exit 1 ;; esac
  111. if [ "$key" = --app ]; then
  112. case "$value" in *..*) echo "App path must be physical." >&2; exit 1 ;; esac
  113. app=$value
  114. fi ;;
  115. --team-id) [ -n "$value" ] || exit 1; team=$value ;;
  116. --allow-unknown-caller|--allow-caller-asserted)
  117. case "$value" in true|false) ;; *) echo "Invalid caller bool." >&2; exit 1 ;; esac
  118. if [ "$key" = --allow-unknown-caller ]; then caller_unknown=$value; else caller_asserted=$value; fi ;;
  119. esac ;;
  120. --help|-h) shift ;;
  121. *) unknown_arg=$1; shift ;;
  122. esac
  123. done
  124. if { [ -n "$scope_root" ] && [ -z "$client_exec" ]; } || { [ -z "$scope_root" ] && [ -n "$client_exec" ]; }; then
  125. echo "--scope-root and --client-executable are required together." >&2; exit 1
  126. fi
  127. if [ -n "$scope_root" ] && [ "$selector" = --product ] && [ "$singleton" != cursor ]; then
  128. echo "Selected scope/client arguments require Cursor." >&2; exit 1
  129. fi
  130. if [ "$pi_scope" -eq 1 ] && [ "$selector" = --product ] && [ "$singleton" != pi ]; then
  131. echo "Pi profile arguments require Pi selection." >&2; exit 1
  132. fi
  133. if [ -n "$nav$app$team$caller_unknown$caller_asserted" ]; then
  134. if [ "$nav" = none ]; then
  135. [ -z "$app$team" ] && [ -n "$caller_unknown" ] && [ -n "$caller_asserted" ] || { echo "Incomplete or conflicting route." >&2; exit 1; }
  136. else
  137. [ -n "$app" ] && [ -n "$team" ] && [ -n "$caller_unknown" ] && [ -n "$caller_asserted" ] || { echo "Incomplete route." >&2; exit 1; }
  138. fi
  139. fi
  140. if [ "$notify" = --skip-agent-notify ]; then
  141. case ",$route_seen," in *,--navigation,*|*,--app,*|*,--team-id,*|*,--allow-unknown-caller,*|*,--allow-caller-asserted,*|*,--preserve-policy,*|*,--request-permission,*) echo "Route flags require agent-notify." >&2; exit 1 ;; esac
  142. fi
  143. if [ "$selector" = --product ] && { [ "$singleton" = gemini ] || [ "$singleton" = opencode ] || [ "$singleton" = qoder ] || [ "$singleton" = pi ]; }; then
  144. [ -z "$route_seen" ] && [ "$json" -eq 0 ] || { echo "Observers use channel flags only." >&2; exit 1; }
  145. fi
  146. [ -z "$activity_mode" ] || activity_args+=(--activity "$activity_mode")
  147. [ -z "$activity_limit" ] || activity_args+=(--activity-limit "$activity_limit")
  148. set -- ${original_args[@]+"${original_args[@]}"}
  149. if [ -z "$selector" ]; then
  150. pending=1
  151. fi
  152. if [ "$pending" -eq 1 ] && [ -n "$unknown_arg" ]; then
  153. echo "Unknown option: $unknown_arg." >&2; exit 1
  154. fi
  155. if [ "$pending" -eq 1 ] && [ "$json" -eq 1 ]; then
  156. echo "Pending questions require complete explicit product/route input with --json." >&2; exit 1
  157. fi
  158. previous=""
  159. # No arguments delegates interactive selection to the released bootstrap.
  160. for arg in "$@"; do
  161. case "$arg" in
  162. --products|--products=*) multi=1; new_setup=1 ;;
  163. --product=gemini|--product=qoder|--product=cursor|--product=pi) new_setup=1 ;;
  164. gemini|qoder|cursor|pi) [ "$previous" != --product ] || new_setup=1 ;;
  165. esac
  166. previous=$arg
  167. done
  168. legacy_product=""
  169. legacy_args=()
  170. opencode_args=()
  171. opencode_channels=0
  172. if [ "$multi" -eq 1 ]; then
  173. selector_seen=0
  174. claude=0 codex=0 opencode=0 gemini=0 qoder=0 cursor=0 pi=0
  175. notify=""
  176. help=0
  177. while [ "$#" -gt 0 ]; do
  178. case "$1" in
  179. --products|--products=*)
  180. [ "$selector_seen" -eq 0 ] || { echo "Use --products once." >&2; exit 1; }
  181. selector_seen=1
  182. case "$1" in
  183. --products)
  184. [ "$#" -ge 2 ] || { echo "--products requires a comma-separated selection." >&2; exit 1; }
  185. selection=$2; shift ;;
  186. *) selection=${1#--products=} ;;
  187. esac
  188. case "$selection" in
  189. ''|,*|*,|*,,*) echo "--products contains an empty product." >&2; exit 1 ;;
  190. esac
  191. remaining=$selection
  192. while :; do
  193. product=${remaining%%,*}
  194. case "$product" in
  195. claude) [ "$claude" -eq 0 ] || { echo "Duplicate product: claude." >&2; exit 1; }; claude=1 ;;
  196. codex) [ "$codex" -eq 0 ] || { echo "Duplicate product: codex." >&2; exit 1; }; codex=1 ;;
  197. opencode) [ "$opencode" -eq 0 ] || { echo "Duplicate product: opencode." >&2; exit 1; }; opencode=1 ;;
  198. gemini) [ "$gemini" -eq 0 ] || { echo "Duplicate product: gemini." >&2; exit 1; }; gemini=1 ;;
  199. qoder) [ "$qoder" -eq 0 ] || { echo "Duplicate product: qoder." >&2; exit 1; }; qoder=1 ;;
  200. cursor) [ "$cursor" -eq 0 ] || { echo "Duplicate product: cursor." >&2; exit 1; }; cursor=1 ;;
  201. pi) [ "$pi" -eq 0 ] || { echo "Duplicate product: pi." >&2; exit 1; }; pi=1 ;;
  202. *) echo "Unknown product: $product." >&2; exit 1 ;;
  203. esac
  204. case "$remaining" in
  205. *,*) remaining=${remaining#*,} ;;
  206. *) break ;;
  207. esac
  208. done ;;
  209. --product|--product=*) echo "--product and --products cannot be combined." >&2; exit 1 ;;
  210. --agent-notify|--skip-agent-notify)
  211. [ -z "$notify" ] || { echo "Use one agent-notify option once." >&2; exit 1; }
  212. notify=$1
  213. legacy_args+=("$1") ;;
  214. --desktop|--webhook|--desktop=true|--desktop=false|--webhook=true|--webhook=false)
  215. for channel in ${opencode_args[@]+"${opencode_args[@]}"}; do
  216. [ "$channel" != "$1" ] || { echo "Use each observer channel once." >&2; exit 1; }
  217. done
  218. opencode_args+=("$1")
  219. opencode_channels=$((opencode_channels + 1)) ;;
  220. --scope-root|--client-executable)
  221. cursor_args+=("$1" "$2"); shift ;;
  222. --scope-root=*|--client-executable=*) cursor_args+=("$1") ;;
  223. --pi-agent-dir|--pi-executable) pi_args+=("$1" "$2"); shift ;;
  224. --pi-agent-dir=*|--pi-executable=*) pi_args+=("$1") ;;
  225. --activity|--activity-limit) shift ;;
  226. --activity=*|--activity-limit=*) ;;
  227. --ui|--ui=*)
  228. if [ "$1" = --ui ]; then shift; fi ;;
  229. --plain) ;;
  230. --help|-h) help=1 ;;
  231. *) echo "Unsupported --products option: $1." >&2; exit 1 ;;
  232. esac
  233. shift
  234. done
  235. if [ "$help" -eq 1 ]; then
  236. echo "Usage: bash install.sh --products claude,codex,opencode,gemini,qoder,cursor,pi [--agent-notify|--skip-agent-notify] [--desktop] [--webhook]"
  237. echo "Choose any nonempty subset. Agent-notify options apply to Claude/Codex/Cursor; channel flags apply to OpenCode/Gemini/Qoder/Cursor/Pi. Cursor defaults to ~/.cursor and cursor-agent on PATH; advanced overrides require both --scope-root and --client-executable."
  238. exit 0
  239. fi
  240. if [ "$claude" -eq 1 ] && [ "$codex" -eq 1 ]; then
  241. legacy_product=both
  242. elif [ "$claude" -eq 1 ]; then
  243. legacy_product=claude
  244. elif [ "$codex" -eq 1 ]; then
  245. legacy_product=codex
  246. fi
  247. [ -z "$notify" ] || [ -n "$legacy_product" ] || [ "$cursor" -eq 1 ] || {
  248. echo "Agent-notify options require Claude, Codex or Cursor in --products." >&2; exit 1;
  249. }
  250. if [ -n "$scope_root" ] && [ "$cursor" -eq 0 ]; then
  251. echo "Selected scope/client arguments require Cursor." >&2; exit 1
  252. fi
  253. if [ "$pi_scope" -eq 1 ] && [ "$pi" -eq 0 ]; then
  254. echo "Pi profile arguments require Pi selection." >&2; exit 1
  255. fi
  256. if [ "$opencode" -eq 0 ] && [ "$gemini" -eq 0 ] && [ "$qoder" -eq 0 ] && [ "$cursor" -eq 0 ] && [ "$pi" -eq 0 ] && [ "$opencode_channels" -gt 0 ]; then
  257. echo "--desktop/--webhook require OpenCode, Gemini, Qoder, Cursor or Pi in --products." >&2; exit 1
  258. fi
  259. fi
  260. command -v curl >/dev/null 2>&1 || {
  261. echo "curl is required to install Agent Notifications." >&2
  262. exit 1
  263. }
  264. repo=777genius/agent-notifications
  265. if [ -n "${BOOTSTRAP_MARKETPLACE_SOURCE:-}" ] && [ "$BOOTSTRAP_MARKETPLACE_SOURCE" != "$repo" ]; then
  266. echo 'Custom source retained. Use its matching pinned bootstrap instead of the platform installer.' >&2
  267. exit 1
  268. fi
  269. stage=$(mktemp -d "${TMPDIR:-/tmp}/agent-notifications-setup.XXXXXX")
  270. loader_progress_pid=""
  271. loader_download_pid=""
  272. loader_owner_subshell=$BASH_SUBSHELL
  273. loader_child_stop() {
  274. local target="$1" running
  275. # A child already reaped by wait is no longer ours to signal, even if
  276. # its numeric PID has since been reused by another process.
  277. for running in $(jobs -pr); do
  278. if [ "$running" = "$target" ]; then
  279. kill "$target" 2>/dev/null || true
  280. break
  281. fi
  282. done
  283. wait "$target" 2>/dev/null || true
  284. }
  285. loader_download_stop() {
  286. [ -n "$loader_download_pid" ] || return 0
  287. loader_child_stop "$loader_download_pid"
  288. loader_download_pid=""
  289. }
  290. loader_progress_stop() {
  291. [ -n "$loader_progress_pid" ] || return 0
  292. loader_child_stop "$loader_progress_pid"
  293. loader_progress_pid=""
  294. printf '\r\033[2K' >&2
  295. }
  296. loader_cleanup() {
  297. # Bash can run an inherited EXIT trap when a just-forked renderer is
  298. # terminated before it installs its own signal traps. Only the loader
  299. # that created this stage may stop its children or remove its files.
  300. [ "$BASH_SUBSHELL" -eq "$loader_owner_subshell" ] || return 0
  301. loader_download_stop
  302. loader_progress_stop
  303. rm -rf "$stage"
  304. }
  305. trap 'loader_cleanup' EXIT
  306. trap 'exit 130' INT
  307. trap 'exit 143' TERM
  308. trap 'exit 129' HUP
  309. # A thin observer works before the verified Go helper is available.
  310. # loader_fetch stays synchronous. Own the external curl PID and use wait so
  311. # signal traps can cancel it immediately, before joining the display child.
  312. loader_fetch() {
  313. local label="$1" output="$2" status=0
  314. shift 2
  315. # Record the transport before any visible activity. No installer function
  316. # runs in a subshell, and no verified artifact is used before wait succeeds.
  317. curl -fsSL "$@" -o "$output" 2> "$stage/download.stderr" &
  318. loader_download_pid=$!
  319. if [ "${BOOTSTRAP_VERBOSE:-0}" != 1 ] && [ "$ui_mode" != plain ] &&
  320. [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != dumb ] && [ -t 2 ]; then
  321. (
  322. trap 'exit 0' INT TERM HUP
  323. frame=0 frames='|/-\'
  324. while :; do
  325. bytes=""
  326. if [ -f "$output" ]; then
  327. bytes=$(wc -c < "$output" 2>/dev/null | tr -d '[:space:]') || bytes=""
  328. [ -z "$bytes" ] || bytes=" ($bytes bytes received)"
  329. fi
  330. printf '\r\033[2K %s %s%s' "${frames:frame:1}" "$label" "$bytes" >&2
  331. frame=$(((frame + 1) % 4))
  332. sleep 0.1
  333. done
  334. ) </dev/null >/dev/null &
  335. loader_progress_pid=$!
  336. else
  337. printf '%s...\n' "$label" >&2
  338. fi
  339. wait "$loader_download_pid" || status=$?
  340. loader_download_pid=""
  341. loader_progress_stop
  342. cat "$stage/download.stderr" >&2
  343. return "$status"
  344. }
  345. controller="${BOOTSTRAP_CONTROLLER_COMMIT:-}"
  346. if [ -z "$controller" ]; then
  347. loader_fetch "Resolving release channel" "$stage/controller" -H 'Accept: application/vnd.github.sha' "https://api.github.com/repos/$repo/commits/main"
  348. [ "$(wc -c < "$stage/controller" | tr -d '[:space:]')" = 40 ] || { echo 'Invalid controller response.' >&2; exit 1; }
  349. controller=$(cat "$stage/controller")
  350. fi
  351. [[ "$controller" =~ ^[0-9a-f]{40}$ ]] || { echo 'Invalid channel controller commit.' >&2; exit 1; }
  352. controller_raw="https://raw.githubusercontent.com/$repo/$controller"
  353. loader_fetch "Downloading release channel resolver" "$stage/release-channel.sh" "$controller_raw/bin/release-channel.sh"
  354. loader_fetch "Downloading release channel manifest" "$stage/channels.tsv" "$controller_raw/release-channels.tsv"
  355. source "$stage/release-channel.sh"
  356. platform=$(release_channel_platform)
  357. IFS=$'\t' read -r os arch <<< "$platform"
  358. row=$(release_channel_select "$stage/channels.tsv" "$os" "$arch")
  359. IFS=$'\t' read -r tag release_commit source_commit source_ref <<< "$row"
  360. if [ "$multi" -eq 1 ] && [ "$opencode" -eq 1 ]; then
  361. version=${tag#v}
  362. major=${version%%.*}
  363. version=${version#*.}
  364. minor=${version%%.*}
  365. # Compare only small numbers, so arbitrary valid semver components
  366. # cannot overflow Bash arithmetic. OpenCode first shipped in v1.46.0.
  367. if [ "$major" = 0 ] || { [ "$major" = 1 ] && [ "${#minor}" -le 2 ] && [ "$minor" -lt 46 ]; }; then
  368. echo "OpenCode requires stable release v1.46.0 or newer; latest is $tag. No products were installed." >&2
  369. exit 1
  370. fi
  371. fi
  372. loader_fetch "Verifying release provenance" "$stage/commit" -H 'Accept: application/vnd.github.sha' "https://api.github.com/repos/$repo/commits/$tag"
  373. [ "$(wc -c < "$stage/commit" | tr -d '[:space:]')" = 40 ] || { echo 'Invalid release commit response.' >&2; exit 1; }
  374. commit=$(cat "$stage/commit")
  375. [ "$commit" = "$release_commit" ] || { echo 'Release provenance mismatch.' >&2; exit 1; }
  376. raw="https://raw.githubusercontent.com/$repo/$source_commit/bin"
  377. loader_fetch "Downloading pinned bootstrap" "$stage/bootstrap.sh" "$raw/bootstrap.sh"
  378. run_bootstrap() {
  379. env BOOTSTRAP_RELEASE_TAG="$tag" BOOTSTRAP_RELEASE_COMMIT="$commit" \
  380. BOOTSTRAP_RELEASE_CHANNEL=1 BOOTSTRAP_SOURCE_COMMIT="$source_commit" \
  381. BOOTSTRAP_SOURCE_REF="$source_ref" INSTALL_SCRIPT_URL="$raw/install.sh" \
  382. bash "$stage/bootstrap.sh" "$@"
  383. }
  384. presentation=0
  385. if run_bootstrap --presentation-capabilities > "$stage/presentation-capabilities" 2>/dev/null &&
  386. printf 'bootstrap-presentation-v1\n' | cmp -s - "$stage/presentation-capabilities"; then
  387. presentation=1
  388. BOOTSTRAP_PROMOTION_FILE="$stage/promotion.txt"
  389. : > "$BOOTSTRAP_PROMOTION_FILE"
  390. chmod 600 "$BOOTSTRAP_PROMOTION_FILE"
  391. export BOOTSTRAP_PROMOTION_FILE
  392. summary="$stage/summary.txt"
  393. BOOTSTRAP_SUMMARY_FILE="$summary"
  394. export BOOTSTRAP_SUMMARY_FILE
  395. elif [ "${#activity_args[@]}" -gt 0 ]; then
  396. echo "This published release lacks installer activity presentation support. No products were installed. Use an updated release." >&2
  397. exit 1
  398. fi
  399. if [ "$pending" -eq 1 ]; then
  400. feature_status=0
  401. run_bootstrap --selector-capabilities >"$stage/selector-capabilities" 2>/dev/null || feature_status=$?
  402. if [ "$feature_status" -ne 0 ] || ! printf 'terminal-selector-v1\n' | cmp -s - "$stage/selector-capabilities"; then
  403. echo "This published release needs terminal selector support. No products were installed. Use complete explicit input or an updated release." >&2
  404. exit 1
  405. fi
  406. fi
  407. if [ "$new_setup" -eq 1 ]; then
  408. capability_status=0
  409. run_bootstrap --capabilities >"$stage/capabilities" 2>/dev/null || capability_status=$?
  410. if [ "$capability_status" -ne 0 ] || ! printf 'bootstrap-products-v1\n' | cmp -s - "$stage/capabilities"; then
  411. if [ "$multi" -eq 1 ] && [ "$gemini" -eq 0 ] && [ "$qoder" -eq 0 ] && [ "$cursor" -eq 0 ] && [ "$pi" -eq 0 ] && [ "$pending" -eq 0 ] && [ -z "$ui_mode" ]; then
  412. # Older releases accept one legacy product group per invocation.
  413. # Stop on either failure; the second group may fail after the first installed.
  414. if [ -n "$legacy_product" ]; then
  415. run_bootstrap --product "$legacy_product" ${legacy_args[@]+"${legacy_args[@]}"}
  416. fi
  417. if [ "$opencode" -eq 1 ]; then
  418. run_bootstrap --product opencode ${opencode_args[@]+"${opencode_args[@]}"}
  419. fi
  420. exit 0
  421. fi
  422. echo "This published release lacks multi-product setup. No products were installed. Use an updated release when available." >&2
  423. exit 1
  424. fi
  425. fi
  426. if [ "$multi" -eq 0 ]; then
  427. run_bootstrap "$@"
  428. if [ "$presentation" -eq 1 ] && [ -s "$summary" ]; then
  429. printf '\nInstallation complete\n\n'
  430. cat "$summary"
  431. printf '\nDetailed installer output: rerun with BOOTSTRAP_VERBOSE=1.\n'
  432. fi
  433. else
  434. summary="$stage/summary.txt"
  435. export BOOTSTRAP_SUMMARY_FILE="$summary"
  436. # Check every selected prerequisite before the first mutation.
  437. run_bootstrap --products "$selection" ${cursor_args[@]+"${cursor_args[@]}"} ${pi_args[@]+"${pi_args[@]}"} ${legacy_args[@]+"${legacy_args[@]}"} ${opencode_args[@]+"${opencode_args[@]}"} ${ui_args[@]+"${ui_args[@]}"} ${activity_args[@]+"${activity_args[@]}"}
  438. if [ -s "$summary" ]; then
  439. printf '\nInstallation complete\n\n'
  440. cat "$summary"
  441. printf '\nDetailed installer output: rerun with BOOTSTRAP_VERBOSE=1.\n'
  442. fi
  443. fi
  444. if [ "$presentation" -eq 1 ]; then
  445. if [ -s "$BOOTSTRAP_PROMOTION_FILE" ] && [ -f "$BOOTSTRAP_PROMOTION_FILE" ] && [ ! -L "$BOOTSTRAP_PROMOTION_FILE" ]; then
  446. cat "$BOOTSTRAP_PROMOTION_FILE"
  447. elif [ -s "${summary:-}" ]; then
  448. printf '\n----------------------------------------\nBoost your productivity\n Check out Agent Teams AI, a desktop app for AI agent teams\n with Claude, Codex and more, from the creator of this plugin:\n https://github.com/777genius/agent-teams-ai\n----------------------------------------\n'
  449. fi
  450. fi
  451. }
  452. # All loader code is parsed before the piped entry point performs any work.
  453. main "$@"
bin/testdata/setup-9039815833ed8d16a11ee4a45de62bb0119c874f.sh · Bundled script · 85 lines · 1 finding marked
  1. #!/usr/bin/env bash
  2. # Usage: curl -fsSL https://raw.githubusercontent.com/777genius/agent-notifications/main/bin/setup.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 2 on GitHub
  3. # Keep this entry point small: installation runs from one exact release commit.
  4. # Prefer isolated python3; Node is the supported fallback (Claude Code ships it).
  5. # Presence on PATH is not enough: Windows Store/WSL python3 stubs must not win.
  6. usable_python3() {
  7. command -v python3 >/dev/null 2>&1 || return 1
  8. python3 -I -c 'import json' </dev/null >/dev/null 2>&1
  9. }
  10. usable_node() {
  11. command -v node >/dev/null 2>&1 || return 1
  12. NODE_OPTIONS= NODE_PATH= node --no-warnings -e 'JSON.parse("{}")' </dev/null >/dev/null 2>&1
  13. }
  14. decode_github_json() {
  15. if usable_python3; then
  16. python3 -I -c "$1"
  17. elif usable_node; then
  18. NODE_OPTIONS= NODE_PATH= node --no-warnings -e "$2"
  19. else
  20. echo "python3 or node is required to install Agent Notifications." >&2
  21. exit 1
  22. fi
  23. }
  24. main() (
  25. set -euo pipefail
  26. command -v curl >/dev/null 2>&1 || {
  27. echo "curl is required to install Agent Notifications." >&2
  28. exit 1
  29. }
  30. usable_python3 || usable_node || {
  31. echo "python3 or node is required to install Agent Notifications." >&2
  32. exit 1
  33. }
  34. repo=777genius/agent-notifications
  35. tag=$(curl -fsSL "https://api.github.com/repos/$repo/releases/latest" | decode_github_json '
  36. import json, re, sys
  37. value = json.load(sys.stdin).get("tag_name")
  38. if not isinstance(value, str) or not re.fullmatch(r"v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)", value):
  39. sys.exit("Invalid stable release tag")
  40. sys.stdout.buffer.write((value + "\n").encode("ascii"))
  41. ' '
  42. const fs = require("fs");
  43. let value;
  44. try { value = JSON.parse(fs.readFileSync(0, "utf8")).tag_name; } catch (e) { process.exit(1); }
  45. if (typeof value !== "string" || !/^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/.test(value)) {
  46. process.stderr.write("Invalid stable release tag\n");
  47. process.exit(1);
  48. }
  49. process.stdout.write(value + "\n");
  50. ')
  51. commit=$(curl -fsSL "https://api.github.com/repos/$repo/commits/$tag" | decode_github_json '
  52. import json, re, sys
  53. value = json.load(sys.stdin).get("sha")
  54. if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{40}", value):
  55. sys.exit("Invalid release commit")
  56. sys.stdout.buffer.write((value + "\n").encode("ascii"))
  57. ' '
  58. const fs = require("fs");
  59. let value;
  60. try { value = JSON.parse(fs.readFileSync(0, "utf8")).sha; } catch (e) { process.exit(1); }
  61. if (typeof value !== "string" || !/^[0-9a-f]{40}$/.test(value)) {
  62. process.stderr.write("Invalid release commit\n");
  63. process.exit(1);
  64. }
  65. process.stdout.write(value + "\n");
  66. ')
  67. raw="https://raw.githubusercontent.com/$repo/$commit/bin"
  68. stage=$(mktemp -d "${TMPDIR:-/tmp}/agent-notifications-setup.XXXXXX")
  69. trap 'rm -rf "$stage"' EXIT
  70. trap 'exit 130' INT
  71. trap 'exit 143' TERM
  72. trap 'exit 129' HUP
  73. # A failed or interrupted download must never execute a partial script.
  74. curl -fsSL "$raw/bootstrap.sh" -o "$stage/bootstrap.sh"
  75. env BOOTSTRAP_RELEASE_TAG="$tag" BOOTSTRAP_RELEASE_COMMIT="$commit" \
  76. INSTALL_SCRIPT_URL="$raw/install.sh" bash "$stage/bootstrap.sh" "$@"
  77. )
  78. # All loader code is parsed before the piped entry point performs any work.
  79. main "$@"

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.