diff --git a/.github/workflows/prepared-release.yml b/.github/workflows/prepared-ui-release.yml similarity index 76% rename from .github/workflows/prepared-release.yml rename to .github/workflows/prepared-ui-release.yml index fb202870..d8115207 100644 --- a/.github/workflows/prepared-release.yml +++ b/.github/workflows/prepared-ui-release.yml @@ -1,4 +1,4 @@ -name: Prepared release +name: Prepared UI release on: workflow_run: @@ -38,12 +38,13 @@ jobs: GH_TOKEN: ${{ github.token }} run: | test "$(git rev-parse HEAD)" = "$RELEASE_SHA" + python3 -c "from tools.build_release_artifacts import RELEASE_MANIFEST_VERSION; assert RELEASE_MANIFEST_VERSION == 2" state=$(python3 tools/prepare_release_publication.py "$RELEASE_SHA") echo "state=$state" >> "$GITHUB_OUTPUT" - - name: Build UI and qualify pinned worker images + - name: Build distributable UI and qualify local worker recipes if: steps.publication.outputs.state == 'build' run: python3 tools/build_release_artifacts.py --output "$RUNNER_TEMP/forge-prepared" - - name: Qualify exported images in classic and containerd stores + - name: Verify prepared UI archive and dependency notices if: steps.publication.outputs.state == 'build' run: sudo python3 tools/qualify_release_roundtrip.py --assets "$RUNNER_TEMP/forge-prepared" - name: Publish the complete release @@ -54,9 +55,7 @@ jobs: gh release create "forge-build-$RELEASE_SHA" \ --target "$RELEASE_SHA" --draft \ --title "Forge $RELEASE_SHA" \ - --notes "Prepared Linux amd64 assets for the exact commit that passed CI. Worker images passed build-environment and isolation canaries, and exported archives passed loading and execution in classic and containerd Docker stores. Installations verify asset checksums and repeat host qualification." \ + --notes "Prepared Linux amd64 UI for the exact commit that passed CI, including third-party notices. Worker recipes passed environment and isolation canaries in CI. Workers are built and qualified on the operator host; no worker binaries are distributed." \ "$RUNNER_TEMP/forge-prepared/manifest.json" \ - "$RUNNER_TEMP/forge-prepared/forge-ui-linux-amd64.tar.gz" \ - "$RUNNER_TEMP/forge-prepared/forge-runner-linux-amd64.tar.gz" \ - "$RUNNER_TEMP/forge-prepared/forge-runner-full-linux-amd64.tar.gz" + "$RUNNER_TEMP/forge-prepared/forge-ui-linux-amd64.tar.gz" gh release edit "forge-build-$RELEASE_SHA" --draft=false diff --git a/README.md b/README.md index ec03a98e..fb4f4846 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ for supported hosts, credential storage and troubleshooting. - **Settings → Repositories:** add repositories and choose whether Forge needs your approval before merging. The default is to require approval. - **Settings → Connections:** manage GitHub access, coding accounts and external agents. +- **Settings → General → Updates:** check published GitHub releases and open update instructions. Label an issue `ready` to make it eligible for work. To group related issues, open **Plan repository work**, request triage and approve the proposed group. diff --git a/SECURITY.md b/SECURITY.md index b414890e..88272f78 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,88 +1,88 @@ # Security -Do not open a public issue with exploit details, credentials, private repository -content, or unredacted worker output. Use GitHub's private vulnerability reporting -for this repository when available. If it is unavailable, request a private -reporting channel from the maintainer without including sensitive details. - -Forge is experimental operator software. Coding agents execute tools with the -credentials and filesystem access their deployment grants. Workers run in -disposable containers with repository-scoped credentials; see -[implementation status](docs/implementation.md) and [isolation status](#isolation-status) -for what those boundaries do and do not establish. - -The dashboard exposes private operational details. Existing installations retain -trusted-private-network access until [operator sign-in](docs/operator-sign-in.md) -is configured. Configured instances require GitHub operator sign-in for every -operational API read and mutation. Use verified HTTPS and an explicit operator -allowlist before permitting additional users to reach the dashboard. The local -host account and UI-to-API proxy secret remain trusted; authentication does not -protect against a compromised controller host. Critical changes require qualifying human -approval; an audit PASS, a shared agent identity, or a cached summary is not human -approval. Do not weaken ownership, current-candidate, or cleanup checks to increase -throughput. +## Report a vulnerability + +Use [GitHub's private vulnerability report](https://github.com/XRPL-Commons/forge/security/advisories/new) +when available. Private reporting availability has **not yet been verified for +this release**. If GitHub does not offer **Report a vulnerability**, open a +[Security contact request](https://github.com/XRPL-Commons/forge/issues/new?title=Security%20contact%20request) +asking the maintainers for a private channel. Include no vulnerability details +in that public request; wait for the private channel before sending them. + +Do not publish exploit details, credentials, private source or raw worker output. +A private report should identify the affected Forge revision, deployment type, +impact and minimal reproduction. Use synthetic data and redact credentials. + +## Supported boundary + +Forge is experimental operator software. The supported installer targets a +dedicated Linux host. The service account, Docker daemon, host kernel and +administrators are trusted. Docker workers share the host kernel: this is **not +VM isolation** and is not a claim that arbitrary hostile workloads cannot escape. +Do not share this host with workloads that require a separate trust boundary. + +Fresh installations register one Forge GitHub App. Its private key and GitHub +installation tokens stay on the host. Jobs receive source through a read-only +mirror and return artifacts; the host publishes changes and merges approved +candidates. “No GitHub credentials in jobs” does **not** mean “no credentials of +any kind in jobs”: provider authentication depends on the selected account mode. ## Runtime trust boundaries -“Live” below means implemented by the supported factory runtime. Host and provider -qualification still apply to each installation. A compromised service account, -Docker daemon or host kernel is outside the worker isolation boundary. - -| Boundary | Principal and credentials | Enforcing control and limit | -| --- | --- | --- | -| Browser → Nitro UI | Authorized operator; browser holds a session cookie and an action token | Verified HTTPS, allowed Host, same-origin mutation checks and bounded JSON requests. Python validates the operator session and action token. Before sign-in is configured, private-network access and the local control capability remain trusted. | -| Nitro → Python API | Trusted UI proxy; configured with the upstream secret and transiently relays browser cookies/action tokens or approved client bearer tokens. App keys and the identity-app secret are not mounted into it | Python binds to loopback and checks the upstream secret and trusted Host. The UI forwards only allowed headers and routes. This is a service boundary, not protection from the host service account. | -| External CLI/agent → Forge | Operator-approved connection, scoped to capabilities and repository identities; client credentials in the local OS keyring | Verified HTTPS, expiring credentials, server-side token hashes, explicit approval and revocation. Browser cookies cannot substitute for client credentials. Local `gh` administration tokens are used against GitHub locally and are never uploaded to Forge. | -| Local administration CLI → host | Operator's SSH account, with permission to manage Forge and its Docker services | SSH host verification and host filesystem permissions. `forge server setup` transfers only the identity-app secret required by that setup; it is hidden input, not an argument. `forge migrate` performs the explicit maintenance/cutover protocol. Host administration is more privileged than a scoped Forge connection. | -| Controller → private state | Dedicated service account; owns the selected SQLite store, App keys, provider credentials and identity-app secret | Private directories/files, schema and instance checks, qualified SQLite, transactions and revision checks. Long-lived App keys, provider authentication and the identity-app secret remain private referenced files. Token hashes, CSRF values and pending OAuth verifiers are private database state. The browser and worker do not receive database access. | -| Controller → Docker worker | Trusted controller owns the Docker socket; worker receives an assignment and short-lived repository/role credentials | Disposable volume, UID 1000, read-only root, dropped capabilities, no-new-privileges, private namespaces, seccomp and the qualified runner AppArmor policy. No host directory, Docker socket or App private key is mounted into a job. Recovery receives a separate read-only token from the Controller App, not its merge-capable token. Docker access itself is administrative authority. | -| Worker harness → repository tools | Provider client can authenticate; repository code is untrusted | Native tool sandbox, image-owned policy and credential scrubbing restrict repository tools. Each adapter needs a real sandbox canary; a model success message is insufficient. Resource limits do not establish credential isolation. | -| Worker → network | Worker on an internal Docker network; separate egress proxy has no role App key | HTTPS CONNECT allowlist on port 443 and rejection of private/non-global destinations. The runner refuses a non-internal worker network. An allowed public service can still receive data a worker sends to it. | -| Controller/worker → GitHub | Four role Apps; installation tokens scoped to the selected repository and role | Worker Review/Audit tokens are downscoped to read-only; Recovery uses a read-only Controller App token. Build can publish work. The controller validates candidate evidence and uses its own token for merge. GitHub protections and expected-head checks apply. App grants are repository-scoped, not per-issue or per-branch restrictions; prompts cannot enforce narrower API authority. | - -Implementation: [proxy guards](ui/server/utils/proxy.ts), -[API admission](legacy/forge-status.py), [client connections](docs/agent-connections.md), -[host sign-in setup](docs/cli-server-setup.md), [runner](forge/factory/runner.py), -and [runtime configuration and GitHub gates](docs/factory-runtime-reference.md). +| Boundary | Enforcement and limits | +| --- | --- | +| Operator → web app | Configured instances require an authorized operator session for operational reads and mutations. Identity comes from GitHub or a linked Tailscale user through the trusted Serve/UI proxy. HTTPS, host validation, session expiry and action tokens protect browser actions. The factory name is public sign-in metadata. | +| UI → Python API | Loopback API, private upstream secret, restricted forwarded headers and routes. App keys and provider credentials are not mounted into the UI. The host service account can cross this boundary. | +| External agent → Forge | Explicit operator approval, repository/capability scope, expiring credentials and revocation. Personal GitHub administration credentials stay in the agent's local CLI. These grants do not give direct host or worker control. | +| Installation CLI → host | Explicit administrative SSH destination, verified host identity and saved installation intent. App credentials are transferred privately; personal GitHub administration tokens remain local. This authority is broader than an external agent connection. | +| Controller → worker | Disposable workspace, unprivileged UID, read-only root, dropped capabilities, no-new-privileges, namespaces, seccomp/AppArmor and resource limits. A read-only job-input directory is mounted; the Docker socket, controller state and App credentials are not. Trusted frontends bridge narrowly scoped host services. | +| Worker → Git mirror | Job-bound authority, pinned source revisions, current installation access and a repository deny list. Declared dependencies and permitted organization repositories can be fetched on demand; a deny entry overrides those allowances. Requests and outcomes are associated with the job. The mirror does not accept pushes. | +| Worker → publication | Workers return retained artifacts, not GitHub writes. The host validates assignment, target ownership, expected revision, publication permissions and signing qualification before publishing. Workflow edits require the repository's explicit permission and App grant. Uncertain writes are reconciled rather than assumed successful. | +| Worker → coding provider | Claude API-key mode uses a host proxy: the worker gets a job capability restricted by model, route, account generation, execution ownership and deadline. Other modes, including browser logins, still provide authentication to the harness inside the container and depend on the qualified native tool sandbox and credential scrubbing. Do not assume the proxy covers every provider or login mode. | +| Worker → network | Internal per-job network and controlled frontends/egress. The egress proxy restricts HTTPS destinations and rejects private/non-global addresses. An allowed service can still receive data sent by a worker; an allowlist is not a data-loss prevention system. | +| Controller → GitHub merge | The supervisor requires current Review/Audit evidence and applicable operator approval before its own merges. It observes existing GitHub protections and checks the expected head. Forge does not create a mandatory GitHub ruleset or govern merges performed outside Forge. GitHub App grants remain broader than an individual issue or branch. | + +Older configurations may retain separate role Apps or a separate sign-in App. +Those compatibility paths do not change the job credential boundary. Before +operator authentication is configured, legacy deployments may still allow +private-network reads; browser mutations require a signed-in operator. Complete +sign-in setup before granting other users network access. + +Relevant implementation: [worker boundary](forge/factory/worker_boundary.py), +[runner](forge/factory/runner.py), [mirror policy](forge/mirror/policy.py), +[publisher](forge/factory/publisher.py), [provider mode selection](forge/provider_runtime.py), +[UI proxy](ui/server/utils/proxy.ts), [API admission](legacy/forge-status.py) +and [operator identity](docs/operator-sign-in.md). ## Isolation status -| Mechanism | Status | Meaning | -| --- | --- | --- | -| Disposable Docker worker, native tool sandbox, runner seccomp/AppArmor and internal egress network | Live | Used by the supported factory runner after host/provider qualification. | -| SQLite runtime authority, managed launcher and legacy-writer fence | Live after explicit selection | Missing, incompatible or invalid selected state stops startup; it does not select JSON as a fallback. | -| `safe-build`, memory admission, cgroup limits and build locks | Live resource controls | Bound resource usage and execution time. They do not isolate credentials or confer authorization. | -| tmux fleet supervisor and its `legacy` onboarding phase | Retired | Supported launchers start the durable factory; old phase values become setup. There is no supported tmux startup path. | -| JSON lifecycle/configuration stores | Pre-cutover compatibility only; retired on selected instances | The selected runtime fences old readers/writers. Frozen pre-migration data is private diagnosis material, not a recovery backend. | +The mechanisms above are implemented contracts, not a claim that every host, +provider or repository has passed live qualification. Setup checks the installed +runner and provider; publication requires evidence for its current target and +App context. Synthetic tests and sandbox canaries do not prove a complete +production issue-to-merge journey. Track that acceptance separately in the +[onboarding release audit](docs/onboarding-release-audit.md). + +Resource admission, timeouts and memory limits reduce resource exhaustion. They +do not isolate credentials or establish authorization. Do not weaken ownership, +current-revision, human-approval or cleanup checks to increase throughput. ## Storage, retention and recovery -The selected store uses WAL with `synchronous=FULL`, private `0700` directories and -`0600` files. The private, write-once `state/storage` marker binds its location -and instance. -Managed `forge.launch` entrypoints select a qualified SQLite library and validate -schema checksums before opening runtime adapters. Selected state has one authority; -staging databases cannot accept normal runtime writes. Qualification checks the -SQLite library linked to Python, not the `sqlite3` shell version; use -`bin/forge setup initialize` when the managed launcher reports an unqualified runtime. - -Fresh installations use `forge setup new`: the client owns privileged SSH host -operations and initializes selected SQLite before starting services. Role App -manifest handoffs require the configured operator and bind owner, role, server, -generation and expiry. Personal GitHub administration stays local; only the -server’s own App and provider credentials reach it. See -[fresh-host setup](docs/cli-fresh-host.md). - -The migration from the JSON runtime was one-way and is complete; there is no JSON -switch-back. Schema changes are applied with `forge migrate upgrade`, which drains -workers and stops writers before one migration transaction. See the -[upgrade procedure](docs/store-migration.md). - -Events and structured results are retained. Eligible raw job logs expire after -30 days through bounded supervisor pruning; active work, current evidence, -recovery/cleanup and pinned references are retained. Audit history is append-only -and survives reset on selected SQLite instances. Private artifacts remain -sensitive even after best-effort redaction. Back up the selected database using a consistent SQLite backup, with -its private instance metadata and referenced credential files. Copying only the -main database while WAL writers run is not a coherent backup. Do not initialize -an empty store over unreconciled workers or GitHub publications. +Persistent state uses one selected SQLite database with WAL and +`synchronous=FULL`, private directories/files and a marker binding its location +and instance. Managed launchers qualify the SQLite runtime and reject missing +or incompatible selected state. There is no JSON runtime fallback. Long-lived +App/provider credentials remain private referenced files outside the database; +session hashes, CSRF values and pending OAuth verifiers are private database state. + +Back up the database using a consistent SQLite backup, together with its private +instance metadata and referenced credential files. Copying only the main file +while WAL writers run is not a coherent backup. Disposable workspaces and VM +snapshots are not substitutes for those backups. See [upgrades and recovery](docs/store-migration.md). + +Events and structured results are retained. Eligible raw logs expire after +30 days; active work, current evidence and pinned recovery/cleanup references +are retained. Reset preserves lifecycle and audit history. Artifacts remain +sensitive after best-effort redaction. Never replace the selected store with an +empty one while workers or GitHub publications remain unreconciled. diff --git a/docs/cli-server-setup.md b/docs/cli-server-setup.md index bee518a7..0115d93c 100644 --- a/docs/cli-server-setup.md +++ b/docs/cli-server-setup.md @@ -4,11 +4,10 @@ host**. Run it once per server. After setup, operators sign in through the UI; adding repositories does not require repeating this command. -For a fresh VM, start with [`forge setup new`](cli-fresh-host.md). That wizard -handles installation, private networking, sign-in, role Apps, a coding account, -repository checks and explicit Start, then follows the first issue to a verified -merge. It runs host commands and file transfers through the CLI; no separate -remote terminal is required. Each stage also has a noninteractive JSON command. +For a fresh VM, use [`forge install`](cli-fresh-host.md). That flow registers one +App for repository access and GitHub sign-in, links the installing Tailscale +operator and hands preparation to the web app. The command documented here is +for existing servers using a separate sign-in App. The local CLI uses your SSH authority for host configuration and your local GitHub CLI to resolve operator usernames to numeric IDs. GitHub administrative @@ -30,11 +29,9 @@ controller state, outside workers and the UI container. `*.ts.net` name. This command supports private Serve on port 443. - Sign in to `gh` locally. Operator names are resolved using GitHub's user API. -`forge server setup` covers sign-in and HTTPS only. For a host installed through -`forge setup new`, use `forge setup sign-in --ssh HOST` for the guided sign-in -stage, then `forge setup continue --ssh HOST` for role Apps, coding account and -repository setup. These commands resume the saved installation. GitHub, -Tailscale and provider browser approvals remain explicit operator handoffs. +`forge server setup` covers sign-in and HTTPS only. For an installation started +with `forge install`, use `forge install --ssh HOST --resume` to continue its +saved setup. GitHub, Tailscale and provider approvals remain explicit. ## Inspect the plan @@ -53,7 +50,8 @@ Without a client ID, an unconfigured server returns `identity_app_required`, a GitHub registration link, and the exact homepage and callback fields. Create or reuse a **dedicated identity-only GitHub OAuth App** with those fields. Complete GitHub's registration, consent and passkey checks in your browser. This App is -separate from Forge's four role Apps and requests no OAuth scopes. +separate from the repository-access App used by that installation and requests +no OAuth scopes. Repeat the command with `--client-id YOUR_IDENTITY_APP_CLIENT_ID` to inspect the setup steps. Repeat `--operator` for additional operator accounts. Planning @@ -99,7 +97,7 @@ configuration, or public Funnel configuration. It serializes concurrent bootstraps and rejects changed plans or reset generations. It never automatically replaces a conflicting identity or proxy configuration. -To intentionally replace a client secret or change authorized operators, use -the [host recovery command](operator-sign-in.md#sessions-and-recovery). That -separate operation revokes sessions. There is no web endpoint accepting bootstrap -secrets and no anonymous first-visitor claim. +This legacy bootstrap command cannot rotate a configured secret or replace its +operator list. Preserve the existing state and arrange identity maintenance if +those settings must change. There is no web endpoint accepting bootstrap secrets +and no anonymous first-visitor claim. diff --git a/docs/dependency-review.md b/docs/dependency-review.md new file mode 100644 index 00000000..4b277a03 --- /dev/null +++ b/docs/dependency-review.md @@ -0,0 +1,19 @@ +# UI dependency review — 2026-11-07 + +Scope: the six open GitHub Dependabot alerts for `ui/package-lock.json`, plus the additional minimatch advisory returned by a current npm audit. No forced overrides, production changes, or advisory dismissals. + +## Fixed + +- **happy-dom 20.14.6 → 21.0.4** (direct development dependency). Addresses [GHSA-834v-8h66-3h79](https://github.com/advisories/GHSA-834v-8h66-3h79) (host code execution through import aliases) and [GHSA-c8p4-j97h-3vg8](https://github.com/advisories/GHSA-c8p4-j97h-3vg8) (SSRF from HTML parsing). Used by the Vitest/Nuxt component test environment, not the deployed server. Both installed test-tool peer ranges accept 21.0.4; its Node >=20 floor is below Forge's Node 24 build runtime. +- **mermaid 11.17.2 → 12.2.0**, resolving **katex 0.16.47 → 0.18.10** through Mermaid's supported `^0.18.0` dependency. Addresses [GHSA-238p-pmpm-9mq7](https://github.com/advisories/GHSA-238p-pmpm-9mq7). The vulnerable path requires existing prototype pollution to bypass KaTeX trust checks. Mermaid is client-side and lazy-loaded for bundled help-document diagrams; `help-diagrams.ts` sets strict security and `htmlLabels:false`. Patched dependency is preferable to treating those constraints as a fix. Latest Mermaid 11 still requires vulnerable KaTeX ^0.16.47; no incompatible override used. [Mermaid 12 release notes](https://github.com/mermaid-js/mermaid/releases/tag/mermaid%4012.0.0): Node >=22.12, Safari >=17.4/ES2024, new layout/look defaults. Forge preserves existing appearance with `layout:'dagre'`, `look:'classic'` and validates help diagrams. Existing initialize/render APIs remain supported. + +## Remaining upstream advisories + +- **glob 13.0.6 and 10.5.0** — [GHSA-3g3m-2fjr-6pw4](https://github.com/advisories/GHSA-3g3m-2fjr-6pw4), moderate, fixed in 14.0.2. Paths: `@vue/test-utils → js-beautify → glob`; `nuxt → @nuxt/nitro-server → nitropack → @vercel/nft → glob`; `nitropack → archiver → archiver-utils → glob`. Latest js-beautify 2.0.3 requires ^13.0.6 and @vercel/nft 1.11.1 requires ^13.0.0, so no supported complete upgrade exists. Vulnerability is traversal continuing after AbortSignal cancellation. Inspected NFT's two calls in `out/analyze.js`: no signal option. js-beautify's CLI calls globSync without signal; Vue's formatter uses the beautify library, not that CLI. These are build/test paths, not UI request handlers. Nitro 2.13.6 would remove the old archiver/glob10 subtree but leaves glob13, so omitted incidental churn from this release change. No claim that arbitrary uses of glob are safe. +- **esbuild 0.27.7** — [GHSA-g7r4-m6w7-qqqr](https://github.com/advisories/GHSA-g7r4-m6w7-qqqr), low, fixed in 0.28.1. `@nuxt/ui → @nuxt/fonts 0.14.0 → fontless 0.2.1 → esbuild ^0.27.0`; other build tools share it. Even latest @nuxt/ui 4.12 retains @nuxt/fonts ^0.14.0. Advisory requires esbuild's development server using `servedir` on **Windows**. Forge builds its UI in a Node24 Linux container and runs the bundled Nitro server; it does not serve production with esbuild. Nitro separately already has esbuild0.28.2. Updating Vite/unplugin would not remove fontless's constraint, so no unrelated upgrades or forced0.28 override. +- **deepmerge 4.3.1** — [GHSA-gcqx-w48m-w2h4](https://github.com/advisories/GHSA-gcqx-w48m-w2h4), low, no patched release. `nuxt → @nuxt/nitro-server → nitropack → @rollup/plugin-node-resolve16.0.3 → deepmerge`. Inspected the resolver's only call: `deepFreeze(deepMerge({}, defaults))`, where defaults is a source-code literal containing fixed arrays/booleans. User opts use object spread separately. The reported malicious-source-object premise is absent at this call. Build dependency; no untrusted request object reaches it. Keep tracked until upstream fixes/removes it; npm audit's suggested Nuxt downgrade is inappropriate. +- **minimatch 9.0.9 and 10.2.6** — [GHSA-g3hv-75wg-m249](https://github.com/advisories/GHSA-g3hv-75wg-m249), moderate, newly returned by npm audit, fixed in11.0.1. Paths: `vue-tsc2.2.12 → @vue/language-core → minimatch9`; `js-beautify → editorconfig3.0.2 → minimatch10`; `glob13 → minimatch10` and `archiver-utils → glob10 → minimatch9`. Globparts amplification can exhaust resources with adversarial patterns. Inspected Vue usages take patterns from Vue compiler config; editorconfig takes repository config patterns. Build/typecheck/format paths, not operator web requests. Upstream ranges exclude11; upgrading only vue-tsc would still leave others and adds an unrelated major-version change. No override. + +## Validation and release limits + +The combined validation used Node 24 and a fresh `npm ci`. Typechecking and the production build passed. Of 623 component tests, 622 passed initially; the remaining help-length check passed after shortening the runtime guide (31 help tests passed on rerun). All 47 browser suites passed, including Help diagrams, onboarding, account recovery and settings. The mobile Help rendering was also inspected. The current npm audit still reports 19 affected dependency nodes (3 low, 16 moderate), representing the four underlying advisories above. This is not a clean audit or a substitute for reviewing third-party distribution terms. diff --git a/docs/factory-runtime-reference.md b/docs/factory-runtime-reference.md index 2e47e93b..e74c0463 100644 --- a/docs/factory-runtime-reference.md +++ b/docs/factory-runtime-reference.md @@ -32,7 +32,7 @@ interrupted after a fresh GitHub read; they are not replayed. Review the current issue, then resubmit the intended action or explicitly resume its migration pause. The [security guide](../SECURITY.md#isolation-status) holds the canonical -live/staged/retired inventory. Supported `bin/forge` commands enter +current isolation boundaries and qualification limits. Supported `bin/forge` commands enter `forge.launch`; the setup service selects the SQLite controller after cutover. A saved `legacy` onboarding phase becomes `setup`, never a tmux supervisor. Existing evidence: [launcher routing](../bin/forge), diff --git a/docs/factory-runtime.md b/docs/factory-runtime.md index 211660e2..09c2718a 100644 --- a/docs/factory-runtime.md +++ b/docs/factory-runtime.md @@ -18,14 +18,10 @@ flowchart TD ## Workers and slots -**Build** owns implementation and the assigned pull request. For an approved group, -one logical builder plans tracked tasks, releases its planning lease, then -resumes integration after accepted outputs and verified task cleanup. A task may -cover several issues, and several tasks may contribute to one issue. The builder -can execute a prerequisite task itself, delegate it to a child, or keep work for -final integration. Every task uses an isolated checkout and exact prerequisite -outputs. Independent tasks and separate deliveries share the same role slots, -memory and account limits. +**Build** owns implementation and the assigned pull request. One builder can +coordinate an approved group of issues, delegate independent tasks to children, +then integrate their accepted outputs. Each task has its own checkout. Builders +and children share the same role slots, memory and account limits. **Review** checks the complete candidate, **Audit** checks security, and **Recovery** investigates a failed attempt before the next decision. @@ -56,8 +52,8 @@ flowchart TD C --> T[Provider native tool sandbox] T --> F[Writable workspace and temporary files] T --> N[Allowed network destinations through proxy] - T -. denied .-> H[Host filesystem and Docker socket] - T -. denied .-> Secrets[Private provider credentials and agent configuration] + T -. denied .-> H[Unassigned host files and Docker socket] + T -. denied .-> Secrets[Controller credentials and persistent state] ``` Repository commands run inside the provider's native sandbox as well as the container boundary. Workers get their own workspace and limited network access; they do not get the host's Docker socket or the Controller credential. @@ -69,7 +65,8 @@ the supervisor checks before publishing role verdicts through the Forge App. Untracked native provider delegation is disabled; the supported fallback is Forge-managed children. -The current production runner requires Linux, Docker and the installed isolation policies. If a project needs unavailable tools or a database environment, Forge reports a setup problem instead of treating it as a code defect. +The supported runner requires Linux, Docker and the installed isolation policies. +Containers share the host kernel; they do not provide a VM boundary. If a project needs unavailable tools or a database environment, Forge reports a setup problem instead of treating it as a code defect. For exact mounts, network rules and limits, read the [runtime reference](factory-runtime-reference.md) and the [isolation status](../SECURITY.md#isolation-status). @@ -77,7 +74,12 @@ For exact mounts, network rules and limits, read the [runtime reference](factory Coding accounts authenticate the model providers. They are separate from the GitHub Apps that access repositories, and from your operator sign-in. -Open **Settings → Coding accounts** to connect or repair an account using the displayed host instructions. Workers receive the selected account for their assignment; repository tool commands cannot read its private credential files. +Open **Settings → Connections → Coding accounts**. Codex browser sign-in can +connect or recover in the web app; other modes use the CLI. Claude API-key jobs +use a host proxy with a job-scoped capability. Other modes supply provider +authentication to the harness in the container and rely on the qualified native +tool sandbox to keep repository commands away from it. See the +[credential boundaries](../SECURITY.md#runtime-trust-boundaries). A quota or sign-in problem can make an account unavailable. Forge shows the reason and, when known, when it can retry; waiting for a provider does not charge the issue a failed code attempt. @@ -104,20 +106,13 @@ flowchart TD D -->|No| Wait ``` -Repository setup is also a delivery blocker. Implementation admission uses the -same repository identity, App connection revision and fresh protection report -shown in Settings. An unreadable observation or an -expired report shows **Repository setup** on the affected issues, with a link to -restore access or recheck the repository. The ordinary setup refresh and issue -observation clear this blocker after verified readiness; independent holds stay -in place. Dispatch saves its final protection read through that same report -boundary, so a newly discovered failure is visible immediately. - -This readiness check does not change repository permissions or enablement. -Protection report expiry does not revoke a running worker or its output. New -work waits, and publication/merge retain their live policy checks. Auxiliary -repository planning and failure diagnosis require access, without requiring -publication readiness; loss of access still blocks them. +If repository access or its latest check is unavailable or stale, affected issues +show **Repository setup** with a link to restore access or recheck. Verified +readiness clears this blocker; other holds remain. New implementation work waits, +but an expired report does not cancel running workers or discard their outputs. +Planning and diagnosis can continue while repository access remains available. +Publication and merging still recheck current conditions. These checks do not +change permissions or enable automation. A green worker result alone is not merge permission. Forge checks its App-bound Review and Audit evidence, required CI, verification, repository protections and current ownership; unresolved changes requested also prevent merging. diff --git a/docs/implementation.md b/docs/implementation.md index 091d22c7..23403133 100644 --- a/docs/implementation.md +++ b/docs/implementation.md @@ -1,107 +1,83 @@ # Implementation status -`forge/factory` implements the [durable factory contract](software-factory-spec.md). -It is Forge's only operating mode; the earlier tmux fleet supervisor has been removed. -See [runtime setup](factory-runtime-reference.md) for the exact configuration and host policy. - -## Implemented - -- Guided three-screen onboarding with GitHub App manifests, staged configuration, - server-owned readiness checks, and supervisor-applied Start and full reset. -- Reset retains selected SQLite lifecycle and audit history after verified teardown. - Its journal survives restarts, and old reset intents cannot affect a newer installation. - -- Supervisor-owned issue history and assignments, with serialized durable - reservations before launch and checked ownership invariants on load/save. -- Sequential candidate Review, Audit and merge routing; one shared three-failure delivery budget, - mandatory bounded investigations, repeat-pattern holds and explicit human retry. -- Exact PR submission metadata, revision-bound verdicts, role App publication, - shared repository admission and supervisor-owned gates for Forge merge requests. -- Disposable container runners with native Codex policy, external reset, verified - teardown, stale-execution fencing and bounded evidence capture. -- GitHub App discovery and multiple installations per role, repository-scoped - execution tokens, explicit activation, and versioned configuration shared with Settings through the selected storage authority. -- A factory view with compact actions, confirmation dialogs, current attention - separated from historical failures, runner cleanup and issue history. +`forge/factory` is Forge's supported operating mode. It uses a durable supervisor, +SQLite state and disposable Linux workers. The tmux supervisor and operational +JSON stores are retired. See [runtime configuration](factory-runtime-reference.md). + +## Installation and operation + +- `forge install` saves the approved plan, checks prerequisites, installs the host + and creates one GitHub App. Host preparation still precedes some browser consent. +- The CLI hands work to the web app after the server confirms ownership. Web + progress shows preparation, account actions and the first-merge test. Codex + browser sign-in and recovery are available there; other account modes use the CLI. +- Repository selection and activation are explicit. Per-repository settings cover + merge approval, review scope, planning and execution requirements. +- GitHub branch protections are observed, not created by Forge. A paid GitHub plan + is not a general prerequisite. Existing repository rules can still block a merge. +- Reset uses durable operations, verified teardown and generation checks. It + preserves lifecycle and audit history. + +## Execution and publication + +- The supervisor reserves assignments before launch, checks ownership and fences + stale work. Cleanup must be verified before resources are reused. +- Jobs use disposable containers with native tool policy, seccomp/AppArmor, + resource limits and an internal network. Containers share the Linux host kernel; + no VM isolation or macOS worker is claimed by this implementation. +- Source and private Git dependencies come through the host's read-only mirror. + Jobs hold no GitHub App keys or installation tokens. Mirror policy combines + declared dependencies, permitted organization installations, live access and + per-project deny entries. +- Workers return artifacts. A host publisher validates them against the reserved + assignment and authorized target, then performs revision-checked GitHub writes. + Publication signing requires a qualification receipt for the current context; + workflow edits require explicit permission. +- Independent Review and Audit produce revision-bound evidence. The supervisor + checks that evidence, applicable human approval and existing GitHub rules before + its own merge. Human-authored PR reviews also have visible work records. +- New installations use one App for publication, checks and GitHub sign-in fallback. + Existing role-App identities remain recognized for compatibility and history. +- Claude API-key execution has a host provider proxy with job-scoped capabilities. + Other providers/login modes still supply provider authentication to the harness + and rely on the native tool sandbox. Do not generalize the GitHub credential + boundary to all provider credentials; see [Security](../SECURITY.md). ## Repository planning and combined delivery -- Persistent repository rules, revisioned notes and proposal rows. Manual, nightly and - relevant-event triage use a read-only worker, with sourced notes and a bounded - handoff retained after cleanup. Acceptance pins fresh requirements, - membership, source PRs and operator decisions before durable effects run. -- Operator-approved compositions with existing-PR choices, one logical builder, - tracked owner and child tasks with isolated checkouts, exact retained prerequisite - outputs, owner integration and one candidate for independent Review and Audit. - Task scope may span issues or split one issue across several tasks; approved - delivery membership remains separate from that execution plan. -- Exact member-scoped holds, environment choices and execution projections. - Shared failure budgets, fencing and verified cleanup survive rework or changed - membership; ordinary issue closure cannot silently close a grouped delivery. -- Lazy delivery progress in Issue Details and repository-scoped CLI reads; - explicit membership operations preview their affected scope before approval. -- Per-repository `human`/`auto` merge policy, with authenticated operator UI changes and - separately authorized CLI changes. External prerequisites distinguish completed - issues, merged PRs, other closure reasons and inaccessible identities. - -These describe implemented contracts. They do not establish that a real combined -PR has completed the installation-to-merge qualification. The integrated regression -matrix and normal two-issue GitHub merge remain the release acceptance gate. - -## Qualification and deployment - -The code has synthetic full-pipeline/restart tests and real credential-free runner -and native sandbox canaries. The image policy was tested for successful workspace -writes and denial of a synthetic provider authentication file. Those checks do not -prove an authenticated production workflow against a particular repository. - -Production cutover still requires operator-owned App installations/keys, provider -authentication, the named runner host policy/internal network, protected branches, -and a successful setup readiness check. No global sandbox setting is relaxed. -External-agent repository setup uses the operator's local GitHub CLI for -administration; elevated GitHub tokens stay local. Forge receives the scoped -role App credentials and dedicated identity-app secret it needs. The first -adapter handles classic branch protection and conservative -wildcard human CODEOWNERS gates; ruleset-only/merge-queue alternatives are held. - -The standalone client supports [fresh-host setup](cli-fresh-host.md), including -selected SQLite initialization, operator-bound role App registration, coding -accounts, repository verification and explicit Start. Its first-merge receipt -requires the normal Build/Review/Audit pipeline and independent GitHub evidence. -Existing hosts retain the [sign-in setup](cli-server-setup.md) and scoped -repository workflows. - -## Retired components - -A setup state left in the retired `legacy` phase is read as `setup`, and reset no longer inventories -or stops tmux sessions. - -## Selected SQLite runtime - -The one-way migration selects one private SQLite database for lifecycle, -configuration, identity and supporting state. The database uses WAL and FULL -durability; transactions, revisions and constraints protect local state. Managed -launchers qualify the SQLite runtime and reject missing or incompatible selected -state. JSON readers and writers are fenced after selection. See -[schema upgrades](store-migration.md). - -This is not a distributed claim service. Do not operate separate controller roots -against the same repositories. Long-lived App/provider credentials remain -private referenced files outside the database. Session/token hashes, CSRF values and pending OAuth verifiers are -private database state. Back up the selected database coherently with its -instance metadata and credential references; a live copy of only the main database file omits WAL -state. Do not use the old JSON directory as a current backup. - -The supervisor expires eligible raw logs after 30 days in bounded batches, while -retaining active/pinned evidence, events and structured results. Reset retains SQL -history. Logs remain private diagnostic data even after redaction. - -GitHub grants are coarser than individual builder actions; role prompts are -cooperative restrictions for those writes, while submission acceptance and -protected-target merge authority are independently checked. See the -[live/staged/retired security inventory](../SECURITY.md#isolation-status). - -Storage cutover and synthetic delivery tests do not by themselves establish -#209's latency target or real ordinary/combined issue-to-merge qualification. -Track those acceptance receipts separately; time from CLI installation to first -normal merge remains the north-star metric. +- Revisioned repository notes, rules and proposals support manual, scheduled and + event-triggered triage. Acceptance checks current membership, prerequisites, + source PRs and operator decisions before applying durable effects. +- An approved group has one logical builder and one candidate PR. Tracked child + tasks use isolated checkouts; the owner integrates their results before Review + and Audit. Execution tasks and approved issue membership remain distinct. +- Member-specific holds, execution requirements, failure budgets and cleanup + survive rework. Closing one issue does not silently complete a grouped delivery. +- Activity and issue details expose progress, decisions and retained history. + +## Persistence + +One selected SQLite store holds lifecycle, configuration, operator identity and +supporting state. WAL with FULL durability, transactions, revisions and constraints +protect local state. Managed launchers qualify the runtime and reject incompatible +state. Long-lived credentials remain private referenced files. The earlier JSON +migration was one-way; its archived input is not a current backup. + +Do not run independent controller roots against the same repositories. Back up +SQLite consistently with its instance metadata and credential references. The +supervisor prunes eligible raw logs after 30 days while retaining events, +structured results and active/pinned evidence. See [schema upgrades](store-migration.md). + +## What remains to prove + +Implemented behavior is distinct from release qualification. Synthetic lifecycle, +restart and boundary tests and real sandbox canaries provide specific evidence; +they do not prove an authenticated production workflow for every deployment. + +The release acceptance batch must follow the public setup instructions on a clean +supported host, recover interrupted consent and login, complete the first-merge +test, and finish ordinary and combined work with the intended approval policy. +Measure the full operator journey separately from the saved installation timer, +which currently starts after the interview. Track receipts and remaining gaps in +the [onboarding release audit](onboarding-release-audit.md). This document does not +claim that those live acceptance runs or the historical latency target have passed. diff --git a/docs/installation.md b/docs/installation.md index 0d7ed494..e89f0fb9 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -309,3 +309,33 @@ For host requirements, isolation qualification, capacity and upgrades, see Official login references: [Codex authentication](https://learn.chatgpt.com/docs/auth) and [Claude Code CLI](https://code.claude.com/docs/en/cli-reference). + +## Factory name + +Forge remains the main product name. The header and sign-in screen show the +deployment name chosen during `forge install` as a smaller secondary label, +for example **Anvil**. Browser titles include both: **Settings · Forge · Anvil**. Older factories without a saved display name show **Forge**. + +After updating an existing Anvil installation using the standard service paths, +copy its original installation name into the runtime once: + +```sh +ssh anvil 'sudo -u forge /home/forge/forge/bin/forge setup initialize --root /home/forge/.local/share/forge --name Anvil' +``` + +Use the original name from the approved installation, not an inferred hostname. +This preserves existing factory data. Repeating the same name has no effect; +a different name is refused. Reload the web page afterward. + +## Check for updates + +Open **Settings → General → Updates** to see the installed revision and the +latest complete published build from `XRPL-Commons/forge`. **Check for updates** +refreshes the result; release notes and the supported upgrade instructions are +linked there. Checking does not install anything or interrupt workers. + +Checks use GitHub’s public API without credentials. The server caches results +for an hour, with a one-minute minimum between manual checks. Private repository +access, rate limits and network failures are reported as unavailable. Forge +compares commit ancestry before offering an update, so a development build is +not mistaken for an older release. diff --git a/docs/operator-sign-in.md b/docs/operator-sign-in.md index e32729de..0b830d90 100644 --- a/docs/operator-sign-in.md +++ b/docs/operator-sign-in.md @@ -4,42 +4,49 @@ Operator sign-in is the authorization prerequisite for external agent connection (#15, #122). It protects dashboard data and actions; external CLI connection approval and scoped client tokens are described in [agent connections](agent-connections.md). -## Configure an existing server once +## Setup and identity -For a private Tailscale host, use the local -[`forge server setup` command](cli-server-setup.md). It resolves operator IDs, -transfers the identity secret privately over SSH, configures services and HTTPS, -and supports retries without revoking sessions. +Start a fresh server with [`forge install`](cli-fresh-host.md). It registers one +Forge App, uses that App for GitHub sign-in fallback, and links the installing +operator's observed Tailscale identity to their authorized GitHub ID. -This is once per Forge server, not per repository. Routine sign-in and sign-out -happen in the UI. The [fresh-host wizard](cli-fresh-host.md) includes this stage -and then guides role App registration under the configured operator session. -`forge server setup` continues to require an existing host. +In Tailscale mode, the UI accepts identity only through its trusted local Serve +proxy. The API checks the UI's upstream secret and the stored operator link; +client-supplied identity headers and tagged devices do not authorize an operator. +GitHub sign-in remains available when the Tailscale identity is absent or unlinked. +The service account and local proxy remain trusted administrative boundaries. + +An older server with a separate identity App can continue using +[`forge server setup`](cli-server-setup.md). That command configures an existing +host; it is not the default fresh-install path. Sign-in is configured per factory, +not per repository. No personal GitHub administration token is uploaded to Forge. ## Sessions and recovery -Sessions expire after eight hours and use Secure, HttpOnly, SameSite=Lax, -`__Host-` cookies. Sign-in state expires after ten minutes, is bound to the browser, -and is consumed before code exchange. PKCE binds that exchange to the sign-in -attempt. GitHub identity tokens are used transiently for `/user`; Forge stores -only the resulting ID/login, a session-token hash, expiry and CSRF value. - -`forge server setup` configures sign-in once and refuses to replace a different -existing configuration; there is no command to replace the operator list or the -identity App (#259 moves operator identity to Tailscale). Explicit sign-out also revokes client connections -approved by that operator; automatic browser-session expiry does not. The host account remains the administrative recovery -boundary. On the selected SQLite runtime, identity, sessions, grants and audit -history live in the private database. The identity client secret is a private, -digest-checked file under its `credentials/` directory. Follow the -[store backup procedure](factory-runtime-reference.md); copying an active WAL database as -one ordinary file is not a consistent backup. Missing or invalid initialized -state fails closed. Reconfigure through the CLI to recover access; do not delete -the database. Before SQLite selection, the legacy private `state/operator-auth` -directory remains the identity authority. - -Until first configuration, existing deployments retain their previous private -network access model. Once configured, missing/corrupt state does not silently -restore that mode. Do not expose an unconfigured instance publicly. +GitHub sessions expire after eight hours and use Secure, HttpOnly, SameSite=Lax, +`__Host-` cookies. Sign-in state expires after ten minutes, is browser-bound and +consumed before code exchange. PKCE binds that exchange to the sign-in attempt. +GitHub identity tokens are used transiently for `/user`; Forge stores the +resulting identity and private session state, not that GitHub token. + +Linked Tailscale sessions use eight-hour windows. Their derived tokens remain on +the server and cannot be presented as browser session cookies. Explicit sign-out +removes the active Tailscale link and revokes agent connections approved by that +operator; automatic browser-session expiry does not revoke those connections. +GitHub sign-in can establish the link again. + +Identity, sessions, grants and audit history live in the selected SQLite store. +The sign-in client secret is a private, digest-checked credential file. Back up +both consistently; do not delete the database to recover access. The host account +is the administrative recovery boundary. The existing-server setup command +refuses to overwrite a different identity configuration. + +Configured instances require operator authentication for operational reads and +mutations. Public session metadata includes whether sign-in is enabled and the +factory display name. Legacy unconfigured instances may retain private-network +read access, but browser mutations require an operator session. Finish sign-in +setup before allowing other users onto that network. Invalid selected state fails +closed; it does not restore a JSON authority or anonymous write capability. ## Request attribution @@ -81,16 +88,17 @@ local CLI/host configuration changes carry the actor `local:host` and have no HTTP request receipt. Reset preserves this history. One-way migration preserves legacy admission -records as `admitted`; it does not invent outcomes for them. Before SQLite -selection, legacy requests continue using the private JSONL admission log. No -new operational JSONL audit writer is used after selection. +records as `admitted`; it does not invent outcomes for them. The supported +runtime has no operational JSONL audit writer. ## Credential boundary GitHub operator identity and approved Forge client credentials authorize actions inside Forge. The external agent's local GitHub administrative identity stays in its local CLI credential store. This change adds no endpoint accepting that -identity or its token. Worker role Apps and coding provider logins are unchanged. +identity or its token. Workers receive source from the read-only Git mirror, +while the host holds GitHub publication authority. Provider authentication is a +separate boundary; see [Security](../SECURITY.md#runtime-trust-boundaries). Protocol reference: [GitHub OAuth web application flow](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps#web-application-flow). diff --git a/docs/prepared-releases.md b/docs/prepared-releases.md index a938e154..f5136377 100644 --- a/docs/prepared-releases.md +++ b/docs/prepared-releases.md @@ -1,89 +1,153 @@ # Prepared release assets -Published Forge releases include the operator UI and worker images. A fresh -Linux amd64 host downloads these assets instead of running `npm ci`, compiling -the UI or building worker images. The CLI stages the standard and full worker -archives so later environment preparation can continue without local GitHub -access. The full worker is loaded and qualified when database services are needed. +New Forge releases distribute the built operator UI. The installer builds the +standard and full worker images on the operator's host from the exact release +source and pinned inputs. Worker binaries are not uploaded to GitHub. Provider +selection, credentials and host qualification keep their existing behavior. -Each release is named `forge-build-`. Its `manifest.json` records: +Each release is named `forge-build-`. Manifest version 2 records: - the exact source commit and Linux amd64 platform; -- the pinned Node and Python base images; -- fingerprints of the UI, documentation and worker build inputs; -- asset sizes and SHA-256 checksums; -- the configuration and OCI manifest digests for the base and full workers. - -The installer reads assets only from releases in `XRPL-Commons/forge`. It checks -the source, platform, pinned toolchain and build inputs, then verifies each -archive before extracting the UI or loading an image. Classic Docker identifies -images by configuration digest; the containerd store uses the manifest digest. -The publisher binds both to the same exported image. Loaded images must match -one of those exact digests and the declared platform. The existing host isolation and environment -canaries still run before workers are enabled. A failed or unavailable download -never silently starts a source build. - -The release publisher is the GitHub repository already trusted for Forge source. -The checksums establish artifact integrity and the manifest binds assets to their -source and build inputs; this is not a separate artifact signing authority. +- pinned Node and Python base images; +- the UI archive's build fingerprint, size and SHA-256 checksum; +- `delivery: local-build` and the input fingerprint for each worker recipe. + +The installer verifies these pins against the checked-out source before using +the UI or building workers. Build caches reuse matching local worker inputs. +Isolation and environment canaries still run before workers are enabled. A +missing UI download never silently starts a source build. + +Version 1 manifests remain readable for existing published releases and pinned +recovery. Those releases contain worker archives; their checksums, platform and +image identities are still verified. Historical assets are not deleted by this +change. ## Publishing -The **Prepared release** workflow runs after **CI** succeeds for a push to this -repository's `main` branch. It checks out that CI run's exact commit, builds the -UI with the pinned Node container, builds both workers, and runs their environment -and isolation canaries. It also loads both exported worker archives into fresh -classic and containerd image stores and runs an offline execution probe in each. -It creates a draft release with all assets and publishes -only after uploads succeed. Published releases are never overwritten. A retry -replaces an incomplete draft only when the draft belongs to `github-actions[bot]` -and names the exact tested commit. Human-owned drafts are left for inspection. -Each compressed asset must fit GitHub's 2 GiB release asset limit; the producer -checks this before publishing. +The **Prepared UI release** workflow runs after **CI** succeeds for a push to this +repository's `main` branch. It checks out that exact commit, builds the UI with +the pinned Node container, builds both worker recipes and runs their isolation +and environment canaries. It then verifies that the UI archive can be consumed +through the installer's extraction path and contains dependency notices. Worker +images remain in the ephemeral CI job; no image export occurs. + +The workflow uploads only `manifest.json` and `forge-ui-linux-amd64.tar.gz`, then +publishes the draft after both uploads succeed. Published releases are never +overwritten. A retry replaces an incomplete draft only when it belongs to +`github-actions[bot]` and names the exact tested commit. Human-owned drafts remain +untouched. The UI archive must fit GitHub's 2 GiB release asset limit. + +### Retiring the binary-publishing workflow + +The current workflow rejects source revisions whose producer does not declare +manifest version 2. This stops an old CI completion event from using the new +workflow to publish version 1 artifacts. + +**This does not secure a rerun of an old workflow execution.** GitHub reruns can +execute historical workflow code, including its former publication permissions. +The new publisher has a separate workflow identity, +`.github/workflows/prepared-ui-release.yml`. At cutover, a maintainer with Actions +write/admin access must cancel active runs of the retired `prepared-release.yml` +workflow and disable that old workflow ID using GitHub administration. Confirm +that the new UI workflow is active, the old one reports disabled, and attempting +to rerun a historical publisher is refused. Record that result. Do not assume +that changing today's YAML disables historical executions. + +This prevents accidental use of the retired publisher; an authorized maintainer +can deliberately re-enable it. No workflow-run history, historical releases or +assets are deleted by this change. If GitHub still allows a disabled workflow to +rerun, stop publication cutover and choose an explicit administrative remedy +before declaring the old path retired. Changing default token permissions or +adding an environment only to the new workflow is not sufficient. + +### UI dependency notices + +The UI archive includes `/third-party-notices.txt`. It records package names, +versions, license metadata, registry source URLs and integrity hashes, upstream +repositories, and the license/notice files from the exact installed build tree. +It conservatively includes build and test dependencies, since generated UI code +can contain assets from packages outside the runtime dependency set. Packages +without separate license text are listed explicitly with available README +information; a metadata label alone is not a substitute for a license notice. + +Missing text for packages copied into the server output stops preparation. +Four small upstream license supplements cover Lucide, Embla, wheel-gestures and +vaul-vue, whose npm packages omit license files. Their package versions, upstream +commit URLs, evidence and file hashes are recorded under +`ui/third-party-licenses/`; changing a covered package version requires reviewing +that supplement. The Lucide text includes its retained Feather attribution. + +ELK (`elkjs` 0.9.3, used by Mermaid) includes the EPL-2.0 license plus an explicit +source-availability statement. It links to the immutable elkjs source revision, +ELK0.9.1 source and additional PR955 patch identified in upstream's release +notes. No upstream source edits are made by Forge. DOMPurify includes its +MPL-2.0/Apache-2.0 choice and full license text. + +The present built output contains Lucide icons and the elkjs server dependency; +no Embla component was found in the current generated chunks, so its supplements +also cover future use. Remaining packages with no standalone text are reported +as an installed-build superset, principally tooling. Absence of an identifiable +name in minified code alone is not proof of exclusion: the complete installed +notice inventory remains included, and package/version changes require renewed +bundle review. This records the actual evidence and preserved terms without +claiming comprehensive legal clearance from an inventory alone. + +## Upgrading an older CLI + +A version 1-only CLI expects all three prepared assets. Its existing +`forge self-update` can stay on an old release or fail to select a version 2 +release; it cannot bootstrap support for the new manifest by itself. + +First reinstall the CLI directly from an exact, published version 2-capable +Forge commit (replace `` with that release's full commit): -With no explicit revision, `forge install` and `forge self-update` select the -latest complete published prepared release and verify its manifest. An explicit -full commit SHA remains available for pinned recovery and development. +```sh +uv tool install --force --refresh 'git+https://github.com/XRPL-Commons/forge.git@' +``` -Only revisions with a published prepared release are ready for installation. -After merging, wait for the Prepared release workflow before installing that -revision. +Then use the upgraded `forge install` or update flow. Do this before removing +legacy release availability. The repository's fresh-install instructions already +use current source; this extra bootstrap is for existing older CLIs. -## Private repository access +## Installation and private repository access + +With no explicit revision, `forge install` and `forge self-update` choose the +latest complete published prepared release. An explicit full commit SHA remains +available for recovery and development. Wait for the Prepared UI release workflow +before installing a newly merged revision. The CLI uses your local GitHub CLI login to read private release metadata and -obtain short-lived, read-only links for the exact assets. It sends those links -over the existing SSH connection. Your personal GitHub token stays local; it is -never sent to the server. Links stay in memory and are excluded from journals, -command arguments and normal output. - -The host immediately downloads and verifies each archive into a private cache -at `~/.cache/forge/prepared/`. Fresh installation stages the cache under -the installer before the Forge service account exists, then transfers the -verified files to that account. Interrupted transfers do not become usable cache -entries. Resume reuses verified files and obtains fresh download links for any -remaining transfers. Worker and UI activation still checks the manifest against -the exact source, toolchain and build inputs. - -Use the local CLI for installing or updating a private Forge release. A direct -host-side update needs an already staged cache or an explicitly selected source -build; the host cannot fetch private releases using your personal credentials. +obtain short-lived, read-only links for the UI. It sends those links over SSH; +your personal GitHub token stays local. Links stay in memory and are excluded +from journals, command arguments and normal output. + +The host downloads verified files into a private cache at +`~/.cache/forge/prepared/`. Fresh installation stages this cache before +the Forge service account exists, then transfers verified files to that account. +Interrupted transfers do not become usable cache entries. Resume reuses valid +files and requests fresh links for unfinished transfers. Worker builds use the +existing pinned Docker recipes on the host and can reuse its local build cache. + +Use the local CLI to install or update a private Forge release. A direct host +update requires an already staged cache or an explicitly selected source build; +it cannot fetch private releases using your personal credentials. ## Development builds -Maintainers can deliberately build a local source checkout by setting -`FORGE_BUILD_FROM_SOURCE=1` for the host-side setup/update command. The release -producer uses the same explicit setting while building assets. This mode retains -the existing build and host qualification path; it is slower and is not an -automatic fallback for an unpublished release. Other platforms currently need -this development path. +Maintainers can deliberately build all assets from a source checkout by setting +`FORGE_BUILD_FROM_SOURCE=1` for the host-side setup/update command. This remains +an explicit development choice, not a fallback for missing release assets. +Other platforms currently require this path. -To build release files on a clean Linux amd64 checkout with Docker, sudo and +To prepare release files on a clean Linux amd64 checkout with Docker, sudo and AppArmor available: ```sh python3 tools/build_release_artifacts.py --output /tmp/forge-prepared +sudo python3 tools/qualify_release_roundtrip.py --assets /tmp/forge-prepared ``` -The destination must be empty. The command prepares and tests files locally; it -does not publish a release or change GitHub permissions. +The destination must be empty. These commands build and verify files locally; +they do not publish a release or change GitHub permissions. The roundtrip tool +also retains legacy version 1 image-store qualification for maintainers examining +an existing release. diff --git a/forge/factory_identity.py b/forge/factory_identity.py new file mode 100644 index 00000000..88edc486 --- /dev/null +++ b/forge/factory_identity.py @@ -0,0 +1,22 @@ +"""The operator's factory name, separate from machine and credential identity.""" +import re + +from .store.configuration import Configuration +from .store.runtime import required + + +def initialize(root, name): + if not isinstance(name, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9 ._-]{0,63}', name): + raise ValueError('Choose a factory name of 1–64 letters, digits, spaces, dots, underscores or hyphens') + configuration = Configuration(required(root)) + current = configuration.get('factory_identity') + if current: + if current['settings']['name'] != name: + raise ValueError('This factory already has a different name; initialization cannot rename it') + return + configuration.replace('factory_identity', {'name': name}, expected_revision=0) + + +def display_name(root): + value = Configuration(required(root)).get('factory_identity') + return value['settings']['name'] if value else None diff --git a/forge/host_setup.py b/forge/host_setup.py index 3cabc357..6e2eb56d 100644 --- a/forge/host_setup.py +++ b/forge/host_setup.py @@ -74,7 +74,7 @@ def user_manager(): '(sudo loginctl enable-linger ' + getpass.getuser() + '), then rerun setup; see docs/installation.md') from None -def initialize(root): +def initialize(root, name=None): """Prepare the qualified SQLite authority before fresh-install services.""" from .store.db import qualified_sqlite if not qualified_sqlite(): @@ -82,9 +82,12 @@ def initialize(root): prepared = prepare(root) environment = {**os.environ, 'LD_LIBRARY_PATH': prepared['library_directory']} os.execve(sys.executable, [sys.executable, '-m', 'forge.launch', 'forge.host_setup', - 'initialize', '--root', str(root)], environment) + 'initialize', '--root', str(root), *(['--name', name] if name is not None else [])], environment) from .store.fresh import initialize as initialize_store store = initialize_store(root) + if name is not None: + from .factory_identity import initialize as initialize_identity + initialize_identity(root, name) print('SQLite initialized for instance ' + store.instance_id) @@ -378,6 +381,7 @@ def main(): parser.add_argument('action', nargs='?', choices=['initialize', 'install', 'update', 'login', 'check', 'status', 'full-environment'], default=None) parser.add_argument('provider', nargs='?', choices=list(manifests())) parser.add_argument('--root', default=str(Path.home() / '.local/share/forge')) + parser.add_argument('--name', help='initialize: factory display name; cannot rename an existing factory') parser.add_argument('--bind', help='Operator UI address: loopback (default) or a private tailnet address; kept across updates') parser.add_argument('--no-pull', action='store_true', help='update: apply the checkout as it is, without fetching') parser.add_argument('--yes', action='store_true', help='Replace service or policy files that were edited outside Forge') @@ -388,11 +392,13 @@ def main(): auth.add_argument('--import-login') parser.add_argument('--model', action='append', help='Repeat to rotate equally between models of this harness') args = parser.parse_args() + if args.name is not None and args.action != 'initialize': + parser.error('--name is only supported with initialize') os.umask(0o077) try: root = private_root(args.root) if args.action == 'initialize': - initialize(root) + initialize(root, args.name) if args.action == 'update': if not args.no_pull and host_update.pull(): # Run the reconciliation that shipped with the new source, not this one. diff --git a/forge/host_update.py b/forge/host_update.py index 6cfed38c..135ec0ae 100644 --- a/forge/host_update.py +++ b/forge/host_update.py @@ -268,7 +268,7 @@ def artifact_inputs(): assets = sorted(str(path.relative_to(SOURCE)) for path in (SOURCE / 'docs/assets').glob('*.svg')) return {'runner': tree_digest(RUNNER_INPUTS, NODE_IMAGE, PYTHON_IMAGE), 'full': tree_digest((*RUNNER_INPUTS, *FULL_RUNNER_INPUTS), NODE_IMAGE, PYTHON_IMAGE), - 'ui': tree_digest(('ui', *guides, *assets), NODE_IMAGE, skip=UI_SKIP)} + 'ui': tree_digest(('ui', 'tools/ui_dependency_notices.py', *guides, *assets), NODE_IMAGE, skip=UI_SKIP)} def prepared_release(): @@ -281,7 +281,8 @@ def prepared_release(): def runner_image(): release = prepared_release() - if release: + from .release_artifacts import local_worker + if release and not local_worker(release.manifest, 'runner'): return release.image('runner', run=subprocess.run) tag = 'forge-runner:' + tree_digest(RUNNER_INPUTS, NODE_IMAGE, PYTHON_IMAGE)[:16] inspect = ['docker', 'image', 'inspect', tag, '--format', '{{.Id}}'] @@ -296,7 +297,8 @@ def runner_image(): def full_runner_image(base): release = prepared_release() - if release: + from .release_artifacts import local_worker + if release and not local_worker(release.manifest, 'full'): descriptor = release.manifest['artifacts']['runner'] if base not in {descriptor[key] for key in ('image_id', 'image_manifest_id') if key in descriptor}: raise ValueError('Prepared full worker does not match the selected base image.') @@ -340,7 +342,7 @@ def ui_release(root): root = Path(root) guides = sorted(str(path.relative_to(SOURCE)) for path in (SOURCE / 'docs').glob('*.md')) assets = sorted(str(path.relative_to(SOURCE)) for path in (SOURCE / 'docs/assets').glob('*.svg')) - release = tree_digest(('ui', *guides, *assets), NODE_IMAGE, skip=UI_SKIP)[:16] + release = tree_digest(('ui', 'tools/ui_dependency_notices.py', *guides, *assets), NODE_IMAGE, skip=UI_SKIP)[:16] target = root / 'ui/releases' / release if (target / 'server/index.mjs').exists(): return release diff --git a/forge/release_artifacts.py b/forge/release_artifacts.py index 15eee0a7..7782b77d 100644 --- a/forge/release_artifacts.py +++ b/forge/release_artifacts.py @@ -1,8 +1,9 @@ """Prepared release assets from the Forge repository, verified before use. The publisher is the same GitHub repository trusted for Forge source. A manifest -binds each asset's checksum, build inputs and image ID to one exact source commit. -Host-specific runner qualification still runs after an image is loaded. +binds each asset's checksum and build inputs to one exact source commit. Version 1 +ships worker images; version 2 declares local worker builds and ships only the UI. +Host-specific runner qualification runs for both delivery methods. """ from functools import lru_cache import hashlib @@ -55,13 +56,35 @@ def asset_url(revision, name): return 'https://github.com/' + REPOSITORY + '/releases/download/' + release_tag(revision) + '/' + name +def artifact_kinds(value): + """Prepared payloads are explicit; v2 builds both workers on the host.""" + require(isinstance(value, dict) and type(value.get('version')) is int + and value['version'] in (1, 2), 'Unsupported prepared manifest version.') + return tuple(ASSETS) if value['version'] == 1 else ('ui',) + + +def local_worker(value, kind): + require(kind in ('runner', 'full'), 'Invalid worker kind.') + return value['version'] == 2 and value['workers'][kind]['delivery'] == 'local-build' + + def validate_manifest(value, revision, inputs, node_image, python_image): - require(isinstance(value, dict) and set(value) == {'version', 'source', 'platform', 'node_image', 'python_image', 'artifacts'}, + kinds = artifact_kinds(value) + keys = {'version', 'source', 'platform', 'node_image', 'python_image', 'artifacts'} + require(set(value) == keys | ({'workers'} if value['version'] == 2 else set()), 'Invalid prepared artifact manifest.') - require(value['version'] == 1 and value['source'] == revision and value['platform'] == 'linux/amd64' + require(value['source'] == revision and value['platform'] == 'linux/amd64' and value['node_image'] == node_image and value['python_image'] == python_image, 'Prepared artifacts do not match this source revision, platform or pinned toolchain.') - require(isinstance(value['artifacts'], dict) and set(value['artifacts']) == set(ASSETS), 'Incomplete prepared release.') + require(isinstance(value['artifacts'], dict) and set(value['artifacts']) == set(kinds), 'Incomplete prepared release.') + if value['version'] == 2: + require(isinstance(value['workers'], dict) and set(value['workers']) == {'runner', 'full'}, + 'Incomplete local worker build policy.') + for kind, worker in value['workers'].items(): + require(isinstance(worker, dict) and set(worker) == {'delivery', 'inputs'} + and worker['delivery'] == 'local-build', 'Invalid local worker build policy.') + require(isinstance(worker['inputs'], str) and SHA256.fullmatch(worker['inputs']) + and worker['inputs'] == inputs[kind], 'Local ' + kind + ' build inputs differ from the checked-out source.') for kind, asset in value['artifacts'].items(): keys = {'filename', 'sha256', 'size', 'inputs'} | ({'image_id'} if kind != 'ui' else set()) allowed_keys = (keys, keys | {'image_manifest_id'}) if kind != 'ui' else (keys,) @@ -69,7 +92,8 @@ def validate_manifest(value, revision, inputs, node_image, python_image): require(isinstance(asset['sha256'], str) and SHA256.fullmatch(asset['sha256']) and type(asset['size']) is int and 0 < asset['size'] < 2 * 1024**3, 'Invalid prepared asset checksum or size.') - require(asset['inputs'] == inputs[kind], 'Prepared ' + kind + ' build inputs differ from the checked-out source. ' + require(isinstance(asset['inputs'], str) and SHA256.fullmatch(asset['inputs']) + and asset['inputs'] == inputs[kind], 'Prepared ' + kind + ' build inputs differ from the checked-out source. ' 'Use a clean published revision or explicitly set FORGE_BUILD_FROM_SOURCE=1 for development.') if kind != 'ui': require(isinstance(asset['image_id'], str) and IMAGE_ID.fullmatch(asset['image_id']), 'Invalid prepared runner image ID.') @@ -110,6 +134,7 @@ def __init__(self, revision, manifest): self.revision, self.manifest = revision, manifest def download(self, kind, destination): + require(kind in artifact_kinds(self.manifest), 'This release builds the worker locally.') asset = self.manifest['artifacts'][kind] digest, size = hashlib.sha256(), 0 cached = cache_directory(self.revision) / asset['filename'] @@ -130,6 +155,7 @@ def download(self, kind, destination): require(size == asset['size'] and digest.hexdigest() == asset['sha256'], 'Prepared ' + kind + ' artifact checksum mismatch.') def image(self, kind, *, run=subprocess.run): + require(kind in artifact_kinds(self.manifest), 'This release builds the worker locally.') asset = self.manifest['artifacts'][kind] # Docker's classic store identifies images by config digest; containerd # uses the OCI manifest digest. Both pins come from the published archive. @@ -199,12 +225,18 @@ def private_directory(path, *, uid=None, gid=None): def manifest_shape(value, revision): - require(isinstance(value, dict) and isinstance(value.get('artifacts'), dict) - and set(value['artifacts']) == set(ASSETS), 'Invalid prepared artifact manifest.') + kinds = artifact_kinds(value) + require(isinstance(value.get('artifacts'), dict) and set(value['artifacts']) == set(kinds), + 'Invalid prepared artifact manifest.') require(isinstance(value.get('node_image'), str) and isinstance(value.get('python_image'), str), 'Invalid prepared toolchain descriptor.') + descriptors = dict(value['artifacts']) + if value['version'] == 2: + require(isinstance(value.get('workers'), dict) and set(value['workers']) == {'runner', 'full'}, + 'Incomplete local worker build policy.') + descriptors.update(value['workers']) inputs = {} - for kind, item in value['artifacts'].items(): + for kind, item in descriptors.items(): require(isinstance(item, dict) and isinstance(item.get('inputs'), str) and SHA256.fullmatch(item['inputs']), 'Invalid prepared build inputs.') inputs[kind] = item['inputs'] @@ -278,7 +310,7 @@ def stage(access, cache_root=None): 'Invalid prepared asset handoff.') revision = access['revision']; directory = cache_directory(revision, cache_root) manifest = manifest_shape(access['manifest'], revision) - require(isinstance(access['urls'], dict) and set(access['urls']) <= set(ASSETS), 'Invalid prepared asset selection.') + require(isinstance(access['urls'], dict) and set(access['urls']) <= set(artifact_kinds(manifest)), 'Invalid prepared asset selection.') urls = {kind: _signed_url(url) for kind, url in access['urls'].items()} raw = json.dumps(manifest, sort_keys=True, separators=(',', ':')).encode() require(len(raw) <= 128 * 1024, 'Prepared artifact manifest is too large.') diff --git a/forge/updates.py b/forge/updates.py new file mode 100644 index 00000000..c062450d --- /dev/null +++ b/forge/updates.py @@ -0,0 +1,115 @@ +"""Read-only discovery of published Forge builds; never installs or fetches Git refs.""" +import http.client +import json +from pathlib import Path +import re +import subprocess +import threading +import time +import urllib.request + +from .app_access import AppClient, AccessError +from .release_artifacts import ASSETS, REPOSITORY, artifact_kinds, asset_url, manifest_shape +from .request_metrics import request_scope, request_attempt, RequestBudgetExhausted + +SOURCE = Path(__file__).resolve().parents[1] +SHA = re.compile(r'[a-f0-9]{40}') +RELEASES = 'https://github.com/' + REPOSITORY + '/releases' + + +def installed_revision(): + try: + result = subprocess.run(['git', '-C', str(SOURCE), 'rev-parse', 'HEAD'], + capture_output=True, text=True, timeout=5, check=True) + value = result.stdout.strip() + return value if SHA.fullmatch(value) else None + except (OSError, subprocess.SubprocessError): + return None + + +def public_manifest(revision): + """Validate the public release envelope without operator credentials or cache writes.""" + with request_attempt() as (timeout, receipt): + with urllib.request.urlopen(asset_url(revision, 'manifest.json'), timeout=timeout) as response: + receipt.update(status=response.status, headers=response.headers) + raw = response.read(128 * 1024 + 1) + if len(raw) > 128 * 1024: + raise ValueError('Release manifest exceeded the size limit') + return json.loads(raw) + + +class UpdateCheck: + def __init__(self, request=None, clock=time.time, monotonic=time.monotonic, fetch_manifest=None): + self.request = request or AppClient().request + self.fetch_manifest = fetch_manifest or public_manifest + self.clock, self.monotonic = clock, monotonic + self.lock = threading.Lock() + self.cached = None + self.checked = 0 + + def view(self, installed, *, refresh=False): + with self.lock: + now = self.monotonic() + # Share one check across tabs/operators. Manual checks have a one-minute cooldown. + age = now - self.checked + if self.cached and self.cached['installed_revision'] == installed and age < (60 if refresh else 3600): + return dict(self.cached) + result = dict(ok=True, installed_revision=installed, latest=None, + status='unavailable', checked_at=self.clock(), error=None, releases_url=RELEASES) + try: + with request_scope(until=time.monotonic() + 10): + self._check(result) + except (AccessError, RequestBudgetExhausted, ValueError, TypeError, KeyError, OSError, http.client.HTTPException) as error: + result['error'] = ('GitHub releases are not publicly accessible yet.' + if isinstance(error, AccessError) and error.status == 404 else + 'Could not check GitHub. Try again later.') + self.cached, self.checked = result, now + return dict(result) + + def _check(self, result): + releases = self.request('GET', '/repos/' + REPOSITORY + '/releases?per_page=100', None) + if not isinstance(releases, list): + raise ValueError('Invalid release list') + candidates = [] + for release in releases: + tag = release.get('tag_name', '') + revision = tag.removeprefix('forge-build-') + if (release.get('draft') or release.get('prerelease') or not tag.startswith('forge-build-') + or not SHA.fullmatch(revision) or not release.get('published_at')): + continue + assets = {item['name'] for item in release.get('assets', [])} + # Both delivery versions include the UI and a manifest; verify the + # selected release's declared artifact set below before offering it. + if not {ASSETS['ui'], 'manifest.json'} <= assets: + continue + candidates.append((release['published_at'], revision, tag, assets)) + if not candidates: + result['status'] = 'no_release' + return + published, revision, tag, assets = max(candidates, key=lambda row: row[:3]) + manifest = manifest_shape(self.fetch_manifest(revision), revision) + if not {ASSETS[kind] for kind in artifact_kinds(manifest)} <= assets: + raise ValueError('Release is missing declared artifacts') + result['latest'] = dict(revision=revision, published_at=published, url=RELEASES + '/tag/' + tag) + installed = result['installed_revision'] + if installed == revision: + result['status'] = 'current' + elif installed is None: + result['status'] = 'unknown' + else: + try: + comparison = self.request('GET', '/repos/' + REPOSITORY + '/compare/' + installed + '...' + revision, None) + except AccessError as error: + if error.status != 404: + raise + result['status'] = 'unknown' + return + result['status'] = {'ahead': 'available', 'behind': 'ahead', 'identical': 'current', + 'diverged': 'diverged'}.get(comparison.get('status'), 'unknown') + + +checks = UpdateCheck() + + +def view(*, refresh=False): + return checks.view(installed_revision(), refresh=refresh) diff --git a/forge_client/_install_host.py b/forge_client/_install_host.py index 272c6fba..f3dee1ba 100644 --- a/forge_client/_install_host.py +++ b/forge_client/_install_host.py @@ -9,6 +9,7 @@ import hashlib import json import os +import platform from pathlib import Path import pwd import re @@ -69,6 +70,7 @@ def facts(): need(sys.platform == 'linux' and os.geteuid() == 0, 'administrator_required') release = dict(line.split('=', 1) for line in Path('/etc/os-release').read_text().splitlines() if '=' in line) need(release.get('ID', '').strip('"') == 'ubuntu' and release.get('VERSION_ID', '').strip('"') == '24.04', 'unsupported_os') + need(platform.machine() == 'x86_64', 'unsupported_architecture') enabled = Path('/sys/module/apparmor/parameters/enabled') need(enabled.exists() and enabled.read_text().strip() == 'Y', 'apparmor_required') need(Path('/run/systemd/system').is_dir(), 'systemd_required') @@ -334,7 +336,14 @@ def install_step(step, data): prepare_service_cache(data) need(service(['git', '-C', str(SOURCE), 'rev-parse', 'HEAD'], capture=True) == data['intent']['revision'], 'source_conflict') need(not service(['git', '-C', str(SOURCE), 'status', '--porcelain', '--untracked-files=no'], capture=True), 'source_conflict') - service([str(SOURCE / 'bin/forge'), 'setup', 'initialize', '--root', str(ROOT)]) + # The client may install an older, explicitly pinned release. Discover + # options from that checkout before supplying the newer display name. + setup = [str(SOURCE / 'bin/forge'), 'setup'] + options = service(setup + ['--help'], capture=True) + initialize = setup + ['initialize', '--root', str(ROOT)] + if re.search(r'(?m)^\s+--name(?:[ =]|$)', options): + initialize += ['--name', data['intent']['name']] + service(initialize) service([str(SOURCE / 'bin/forge'), 'setup', 'install', '--root', str(ROOT), '--bind', '127.0.0.1']) for name in ('forge-status', 'forge-ui', 'forge-supervisor'): need(service(['systemctl', '--user', 'is-active', name], capture=True) == 'active', 'services_unavailable') diff --git a/forge_client/install.py b/forge_client/install.py index a2cf2e8b..d8337928 100644 --- a/forge_client/install.py +++ b/forge_client/install.py @@ -42,6 +42,7 @@ 'account_handoff_unconfirmed': 'A different login is now connected. Inspect it before replacing provider credentials.', 'administrator_required': 'Use root or an SSH account with noninteractive sudo for this VM.', 'unsupported_os': 'Fresh installation currently supports Ubuntu 24.04. Select a supported VM.', + 'unsupported_architecture': 'Fresh installation requires an x86-64 (amd64) Ubuntu 24.04 server. ARM64 servers are not supported; select an x86-64 VM.', 'apparmor_required': 'Use a VM with AppArmor enabled in its kernel.', 'systemd_required': 'Use a VM running systemd.', 'existing_installation': 'This host already has a forge account or installation. Use the existing-server commands or select a fresh VM.', @@ -133,7 +134,7 @@ def revision(value=None, *, run=run_bounded, fetch_manifest=None): return value executable = shutil.which('gh') require(executable, 'github_cli_missing', 'Install the GitHub CLI locally before selecting a prepared Forge release.') - from forge.release_artifacts import ASSETS, ArtifactError + from forge.release_artifacts import ASSETS, ArtifactError, manifest_shape, artifact_kinds from .release_delivery import read_manifest try: raw = run([executable, 'api', '--hostname', 'github.com', '--method', 'GET', @@ -141,7 +142,7 @@ def revision(value=None, *, run=run_bounded, fetch_manifest=None): 'repos/XRPL-Commons/forge/releases?per_page=100']) releases = json.loads(raw) require(isinstance(releases, list), 'prepared_release_unavailable') - required_assets = {'manifest.json', *ASSETS.values()} + required_assets = {'manifest.json', ASSETS['ui']} candidates = [item for item in releases if isinstance(item, dict) and item.get('draft') is False and item.get('prerelease') is False and isinstance(item.get('tag_name'), str) @@ -153,14 +154,10 @@ def revision(value=None, *, run=run_bounded, fetch_manifest=None): selected = max(candidates, key=lambda item: item['published_at']) commit = selected['tag_name'].removeprefix('forge-build-') manifest = fetch_manifest(commit) if fetch_manifest else read_manifest(commit, run=run) - require(isinstance(manifest, dict) and manifest.get('version') == 1 and manifest.get('source') == commit - and manifest.get('platform') == 'linux/amd64' and isinstance(manifest.get('artifacts'), dict) - and set(manifest['artifacts']) == set(ASSETS), 'prepared_release_unavailable') - for kind, filename in ASSETS.items(): - asset = manifest['artifacts'][kind] - require(isinstance(asset, dict) and asset.get('filename') == filename - and isinstance(asset.get('sha256'), str) and re.fullmatch(r'[a-f0-9]{64}', asset['sha256']) - and type(asset.get('size')) is int and asset['size'] > 0, 'prepared_release_unavailable') + manifest_shape(manifest, commit) + require({ASSETS[kind] for kind in artifact_kinds(manifest)} <= + {asset.get('name') for asset in selected['assets'] if isinstance(asset, dict)}, + 'prepared_release_unavailable') return commit except (SetupError, ArtifactError, ValueError, TypeError): raise SetupError('prepared_release_unavailable', diff --git a/forge_client/release_delivery.py b/forge_client/release_delivery.py index a8a4d190..efc8626a 100644 --- a/forge_client/release_delivery.py +++ b/forge_client/release_delivery.py @@ -10,7 +10,7 @@ import urllib.parse import urllib.request -from forge.release_artifacts import ASSETS, ArtifactError, release_tag, validate_manifest +from forge.release_artifacts import ASSETS, ArtifactError, release_tag, manifest_shape, artifact_kinds from .contracts import SetupError, require from .github import run_bounded @@ -43,7 +43,7 @@ def metadata(revision, *, run=run_bounded): and type(asset.get('size')) is int and 0 < asset['size'] < 2 * 1024**3, 'prepared_release_unavailable') selected[name] = asset - require(set(selected) == needed and selected['manifest.json']['size'] <= MANIFEST_LIMIT, + require({'manifest.json', ASSETS['ui']} <= set(selected) and selected['manifest.json']['size'] <= MANIFEST_LIMIT, 'prepared_release_unavailable') return selected except (SetupError, ArtifactError, ValueError, TypeError): @@ -60,14 +60,9 @@ def read_manifest(revision, *, assets=None, run=run_bounded): output_limit=MANIFEST_LIMIT) require(len(raw) == assets['manifest.json']['size'], 'prepared_release_unavailable') manifest = json.loads(raw) - require(isinstance(manifest, dict) and isinstance(manifest.get('artifacts'), dict) - and set(manifest['artifacts']) == set(ASSETS) - and all(isinstance(value, dict) for value in manifest['artifacts'].values()), + manifest_shape(manifest, revision) + require({ASSETS[kind] for kind in artifact_kinds(manifest)} <= set(assets), 'prepared_release_unavailable') - # Structural checks here. The host separately compares these fingerprints - # and toolchain pins with its exact checked-out source before use. - inputs = {kind: descriptor['inputs'] for kind, descriptor in manifest['artifacts'].items()} - validate_manifest(manifest, revision, inputs, manifest['node_image'], manifest['python_image']) for kind, descriptor in manifest['artifacts'].items(): asset = assets[ASSETS[kind]] require(asset['size'] == descriptor['size'], 'prepared_release_unavailable') @@ -115,11 +110,12 @@ def access(revision, kinds=None, *, run=run_bounded, opener=None): Redirects are stopped locally, so that token never reaches an asset host. The returned URLs grant time-limited access only to these release files. """ - kinds = tuple(ASSETS) if kinds is None else tuple(kinds) - require(len(set(kinds)) == len(kinds) and all(kind in ASSETS for kind in kinds), - 'invalid_prepared_assets', 'Select UI, runner or full prepared assets.') assets = metadata(revision, run=run) manifest = read_manifest(revision, assets=assets, run=run) + available = artifact_kinds(manifest) + kinds = available if kinds is None else tuple(kinds) + require(len(set(kinds)) == len(kinds) and all(kind in available for kind in kinds), + 'invalid_prepared_assets', 'Select only artifacts delivered by this release.') if not kinds: return {'revision': revision, 'manifest': manifest, 'urls': {}} try: diff --git a/legacy/forge-status.py b/legacy/forge-status.py index 25200acb..636f03d6 100755 --- a/legacy/forge-status.py +++ b/legacy/forge-status.py @@ -240,9 +240,11 @@ def _signed_in(self): def _auth_get(self, url): from forge.operator_auth import read_cookie, FLOW_COOKIE, cookie, failure_reason if url.path == '/api/auth/session': + from forge.factory_identity import display_name mode = self._auth.identity_settings()['mode'] if self._auth_config else None self._send(json.dumps({'ok': True, 'enabled': bool(self._auth_config), 'operator': self._session['operator'] if self._session else None, + 'factory_name': display_name(WD), **({'mode': mode} if self._auth_config else {}), **({'controls_token': self._action_token, 'via': self._session.get('via', 'github')} if self._session else {})})) return True @@ -714,6 +716,9 @@ def _get(self, u): self._send(json.dumps({'ok': True, **result, 'controls_token': self._action_token})) except (ValueError, OSError, RuntimeError): self._send(json.dumps({'ok': False, 'reason': 'Installation progress is unavailable. Refresh to try again.'})) + elif u.path == '/api/updates': + from forge.updates import view + self._send(json.dumps(view(refresh=parse_qs(u.query).get('refresh') == ['1']))) elif u.path == '/api/onboarding': from forge.onboarding import Onboarding try: diff --git a/tests/test_factory_identity.py b/tests/test_factory_identity.py new file mode 100644 index 00000000..83a65a46 --- /dev/null +++ b/tests/test_factory_identity.py @@ -0,0 +1,80 @@ +"""Factory display names are explicit configuration, independent of hostnames.""" +from contextlib import redirect_stdout +from io import StringIO +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +from forge.factory_identity import initialize, display_name +from forge.store.fresh import initialize as initialize_store +from forge.store.configuration import Configuration + + +class FactoryIdentityTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + self.store = initialize_store(self.root) + + def test_missing_name_stays_missing_without_using_hostname(self): + self.assertIsNone(display_name(self.root)) + self.assertIsNone(Configuration(self.store).get('factory_identity')) + + def test_initialize_is_idempotent_and_cannot_rename_or_change_unrelated_settings(self): + configuration = Configuration(self.store) + configuration.replace('unrelated', {'keep': 'value'}, expected_revision=0) + initialize(self.root, 'Anvil') + initialize(self.root, 'Anvil') + self.assertEqual(display_name(self.root), 'Anvil') + self.assertEqual(configuration.get('factory_identity')['revision'], 1) + with self.assertRaisesRegex(ValueError, 'cannot rename'): + initialize(self.root, 'Another factory') + self.assertEqual(display_name(self.root), 'Anvil') + self.assertEqual(configuration.get('unrelated')['settings'], {'keep': 'value'}) + + def test_invalid_names_are_rejected(self): + for name in ('', 'x' * 65, '\nAnvil', 'Anvil', None): + with self.subTest(name=name), self.assertRaises(ValueError): + initialize(self.root, name) + self.assertIsNone(display_name(self.root)) + + def test_host_initialize_publishes_approved_name(self): + from forge.host_setup import initialize as initialize_host + with patch('forge.store.db.qualified_sqlite', return_value=True), redirect_stdout(StringIO()): + initialize_host(self.root, 'Anvil') + self.assertEqual(display_name(self.root), 'Anvil') + + def test_sqlite_runtime_reexec_preserves_name(self): + from forge.host_setup import initialize as initialize_host + with patch('forge.store.db.qualified_sqlite', return_value=False), \ + patch('forge.store.migration.runtime.prepare', return_value={'library_directory': '/test/sqlite'}), \ + patch('forge.host_setup.os.execve', side_effect=RuntimeError('exec')) as execute: + with self.assertRaisesRegex(RuntimeError, 'exec'): + initialize_host(self.root, 'Anvil') + self.assertEqual(execute.call_args.args[1][-2:], ['--name', 'Anvil']) + + def test_fresh_installer_discovers_name_support_in_each_pinned_target(self): + from forge_client import _install_host as remote + from unittest.mock import Mock + for revision, help_text, supports_name in ( + ('a' * 40, 'options:\n --root ROOT\n --name NAME factory display name\n', True), + ('b' * 40, 'options:\n --root ROOT\n --hostname HOST network name\n', False), + ): + with self.subTest(revision=revision): + def respond(argv, **kwargs): + if 'rev-parse' in argv: return revision + if 'is-active' in argv: return 'active' + if '--help' in argv: return help_text + return '' + service = Mock(side_effect=respond) + with patch.object(remote, 'prepare_service_cache'), patch.object(remote, 'service', service): + remote.install_step('host', {'intent': {'name': 'Anvil', 'revision': revision}}) + calls = [call.args[0] for call in service.call_args_list] + setup = [str(remote.SOURCE / 'bin/forge'), 'setup'] + initialize = setup + ['initialize', '--root', str(remote.ROOT)] + if supports_name: initialize += ['--name', 'Anvil'] + self.assertEqual([call for call in calls if 'initialize' in call], [initialize]) + self.assertLess(calls.index(setup + ['--help']), calls.index(initialize)) + self.assertIn(setup + ['install', '--root', str(remote.ROOT), '--bind', '127.0.0.1'], calls) diff --git a/tests/test_fresh_install.py b/tests/test_fresh_install.py index ff08d0ec..e0c4d61b 100644 --- a/tests/test_fresh_install.py +++ b/tests/test_fresh_install.py @@ -240,6 +240,52 @@ def test_jump_host_scan_does_not_mistake_public_address_for_target(self): self.assertEqual(run.call_count, 1) +class HostArchitectureTests(unittest.TestCase): + def setUp(self): + for target, options in ( + ('sys.platform', {'new': 'linux'}), + ('os.geteuid', {'return_value': 0}), + ('os.cpu_count', {'return_value': 4}), + ('os.statvfs', {'return_value': SimpleNamespace(f_bavail=40000, f_frsize=1048576)}), + ('Path.exists', {'return_value': True}), + ('Path.is_dir', {'return_value': True}), + ('Path.read_text', {'autospec': True, 'side_effect': lambda path: { + '/etc/os-release': 'ID=ubuntu\nVERSION_ID="24.04"\n', + '/sys/module/apparmor/parameters/enabled': 'Y\n', + '/proc/meminfo': 'MemTotal: 8388608 kB\n', + }[str(path)]}), + ): + context = patch('forge_client._install_host.' + target, **options) + context.start(); self.addCleanup(context.stop) + + def test_x86_64_ubuntu_facts_match_supported_contract(self): + with patch.object(remote.platform, 'machine', return_value='x86_64'): + self.assertEqual(remote.facts(), FACTS) + + def test_arm64_is_refused_before_planning_or_host_mutations(self): + for architecture in ('aarch64', 'arm64', 'i686'): + for action in ('plan', 'apply', 'resume'): + with self.subTest(architecture=architecture, action=action), \ + patch.object(remote.platform, 'machine', return_value=architecture), \ + patch.object(remote, 'read') as read, \ + patch.object(remote, 'private_directory') as directory, \ + patch.object(remote, 'write') as write, patch.object(remote, 'run') as run: + with self.assertRaisesRegex(remote.InstallError, '^unsupported_architecture$'): + remote.dispatch({'version': 1, 'action': action, 'intent': INTENT, + 'source': PACK if action != 'plan' else None, + 'upgrade_installer': False}, 'payload') + read.assert_not_called(); directory.assert_not_called() + write.assert_not_called(); run.assert_not_called() + + def test_cli_preserves_architecture_error_and_explains_supported_host(self): + host = InstallerHost('anvil', run=Mock(return_value=b'{"ok":false,"error":"unsupported_architecture"}')) + with self.assertRaises(SetupError) as caught: + host.rpc('payload', {}) + self.assertEqual(caught.exception.code, 'unsupported_architecture') + self.assertIn('x86-64 (amd64) Ubuntu 24.04', str(caught.exception)) + self.assertIn('ARM64 servers are not supported', str(caught.exception)) + + class RemoteInstallerTests(unittest.TestCase): def setUp(self): self.temporary = tempfile.TemporaryDirectory() diff --git a/tests/test_operator_auth.py b/tests/test_operator_auth.py index 4db657e6..5bc5aa6e 100644 --- a/tests/test_operator_auth.py +++ b/tests/test_operator_auth.py @@ -233,20 +233,38 @@ def request(self, path, body=None, signed=False, **headers): def test_signed_out_reads_and_mutations_are_protected_before_services(self): with patch.object(dashboard, 'settings_service') as service: - for path in ('/api/settings', '/api/factory', '/api/factory/output?id=x', '/api/onboarding', '/onboarding/github/callback', '/api/issues'): + for path in ('/api/updates', '/api/settings', '/api/factory', '/api/factory/output?id=x', '/api/onboarding', '/onboarding/github/callback', '/api/issues'): with self.subTest(path=path): self.request(path).send_error.assert_called_once_with(401) for path in ('/api/settings/sync', '/api/onboarding', '/api/repositories/enable', '/api/factory/action', '/api/runtime'): self.request(path, {}).send_error.assert_called_once_with(401) service.assert_not_called() + def test_update_check_requires_operator_and_is_read_only(self): + with patch('forge.updates.view', return_value={'ok': True, 'status': 'current'}) as view: + self.request('/api/updates').send_error.assert_called_once_with(401) + view.assert_not_called() + handler = self.request('/api/updates?refresh=1', signed=True) + self.assertEqual(json.loads(handler._send.call_args.args[0])['status'], 'current') + view.assert_called_once_with(refresh=True) + def test_public_session_has_no_action_capability_or_config(self): handler = self.request('/api/auth/session') result = json.loads(handler._send.call_args.args[0]) - self.assertEqual(result, {'ok': True, 'enabled': True, 'operator': None, 'mode': 'github'}) + self.assertEqual(result, {'ok': True, 'enabled': True, 'operator': None, 'mode': 'github', 'factory_name': None}) handler = self.request('/api/auth/session', signed=True) self.assertEqual(json.loads(handler._send.call_args.args[0])['controls_token'], self.session['csrf']) + def test_factory_name_is_available_before_signin_without_private_configuration(self): + from forge.factory_identity import initialize + initialize(dashboard.WD, 'Anvil') + handler = self.request('/api/auth/session') + result = json.loads(handler._send.call_args.args[0]) + self.assertEqual(result, {'ok': True, 'enabled': True, 'operator': None, + 'mode': 'github', 'factory_name': 'Anvil'}) + handler = self.request('/api/auth/session', signed=True) + self.assertEqual(json.loads(handler._send.call_args.args[0])['factory_name'], 'Anvil') + def test_github_callback_accepts_optional_matching_issuer(self): from urllib.parse import urlencode original = OperatorAuth.callback diff --git a/tests/test_prepared_image_identity.py b/tests/test_prepared_image_identity.py index a7a98f70..9da3bc20 100644 --- a/tests/test_prepared_image_identity.py +++ b/tests/test_prepared_image_identity.py @@ -1,51 +1,50 @@ -import hashlib +"""New releases qualify workers but never export or publish their binaries.""" import io import json from pathlib import Path import tempfile import unittest import tarfile - -from tools.build_release_artifacts import image_identity - - -class PreparedImageIdentityTests(unittest.TestCase): - def archive(self, directory, *, architecture='amd64', wrong_config=False, corrupt_manifest=False): - config = json.dumps({'os': 'linux', 'architecture': architecture}).encode() - config_digest = hashlib.sha256(config).hexdigest() - manifest = json.dumps({'schemaVersion': 2, 'config': {'digest': 'sha256:' + ('0'*64 if wrong_config else config_digest)}, 'layers': []}).encode() - manifest_digest = hashlib.sha256(manifest).hexdigest() - members = { - 'blobs/sha256/' + config_digest: config, - 'blobs/sha256/' + manifest_digest: manifest + (b' ' if corrupt_manifest else b''), - 'manifest.json': json.dumps([{'Config': 'blobs/sha256/' + config_digest}]).encode(), - 'index.json': json.dumps({'manifests': [{'digest': 'sha256:' + manifest_digest}]}).encode(), - } - path = Path(directory) / 'worker.tar.gz' - with tarfile.open(path, 'w:gz') as archive: - for name, raw in members.items(): - info = tarfile.TarInfo(name); info.size = len(raw) - archive.addfile(info, io.BytesIO(raw)) - return path, 'sha256:' + config_digest, 'sha256:' + manifest_digest - - def test_identity_is_portable_across_builder_stores(self): - with tempfile.TemporaryDirectory() as directory: - path, config, manifest = self.archive(directory) - expected = {'image_id': config, 'image_manifest_id': manifest} - self.assertEqual(image_identity(path, config), expected) - self.assertEqual(image_identity(path, manifest), expected) - - def test_rejects_export_from_another_built_image(self): - with tempfile.TemporaryDirectory() as directory: - path, _, _ = self.archive(directory) - with self.assertRaises(ValueError): image_identity(path, 'sha256:' + 'f'*64) - - def test_rejects_wrong_platform_or_unbound_metadata(self): - for change in ({'architecture': 'arm64'}, {'wrong_config': True}, {'corrupt_manifest': True}): - with self.subTest(change=change), tempfile.TemporaryDirectory() as directory: - path, config, _ = self.archive(directory, **change) - with self.assertRaises(ValueError): image_identity(path, config) - - -if __name__ == '__main__': - unittest.main() +from unittest.mock import patch + +from tools import build_release_artifacts as tool + + +class PreparedBuildTests(unittest.TestCase): + def test_v2_only_archives_ui_with_notices_and_records_worker_recipes(self): + inputs = {name: str(index) * 64 for index, name in enumerate(('ui', 'runner', 'full'))} + def ui_release(root): + ui = root / 'ui/releases/test/server' + ui.mkdir(parents=True) + (ui / 'index.mjs').write_text('server') + return 'test' + def notices(root, target, **kwargs): + target.parent.mkdir(parents=True) + target.write_text('dependency attribution') + with tempfile.TemporaryDirectory() as temporary, \ + patch.object(tool.platform, 'system', return_value='Linux'), \ + patch.object(tool.platform, 'machine', return_value='x86_64'), \ + patch.object(tool.host_update, 'source_revision', return_value='a' * 40), \ + patch.object(tool.subprocess, 'check_output', return_value=b''), \ + patch.object(tool.subprocess, 'run') as run, \ + patch.object(tool.host_update, 'runner_image', return_value='runner'), \ + patch.object(tool.host_update, 'full_runner_image', return_value='full'), \ + patch.object(tool.host_update, 'qualify_runner') as qualify, \ + patch.object(tool.host_update, 'ui_release', side_effect=ui_release), \ + patch.object(tool.host_update, 'artifact_inputs', return_value=inputs), \ + patch.object(tool.urllib.request, 'urlopen', return_value=io.BytesIO(b'{}')), \ + patch.object(tool.runpy, 'run_path', return_value={'generate': lambda *args: {}}), \ + patch.object(tool, 'write_notices', side_effect=notices), \ + patch.dict(tool.os.environ, {}): + destination = Path(temporary) / 'assets' + tool.build(destination) + manifest = json.loads((destination / 'manifest.json').read_text()) + self.assertEqual(manifest['version'], 2) + self.assertEqual(set(manifest['artifacts']), {'ui'}) + self.assertEqual(manifest['workers'], {kind: {'delivery': 'local-build', 'inputs': inputs[kind]} + for kind in ('runner', 'full')}) + self.assertEqual({p.name for p in destination.iterdir()}, {'manifest.json', tool.ASSETS['ui']}) + self.assertEqual(qualify.call_count, 2) + self.assertFalse(any('save' in call.args[0] for call in run.call_args_list)) + with tarfile.open(destination / tool.ASSETS['ui']) as archive: + self.assertEqual(archive.extractfile('public/third-party-notices.txt').read(), b'dependency attribution') diff --git a/tests/test_release_artifacts.py b/tests/test_release_artifacts.py index 3125a4af..12820c12 100644 --- a/tests/test_release_artifacts.py +++ b/tests/test_release_artifacts.py @@ -23,6 +23,14 @@ def manifest(payload=b'archive'): for kind, filename in artifacts.ASSETS.items()}} +def local_manifest(payload=b'archive'): + value = manifest(payload) + value['version'] = 2 + value['workers'] = {kind: {'delivery': 'local-build', 'inputs': INPUTS[kind]} for kind in ('runner', 'full')} + value['artifacts'] = {'ui': value['artifacts']['ui']} + return value + + def validated(value): return artifacts.validate_manifest(value, REVISION, INPUTS, 'node@sha256:fixed', 'python@sha256:fixed') @@ -65,6 +73,75 @@ def test_unsupported_platform_is_explicit(self): fetch.assert_not_called() +class LocalWorkerReleaseTests(unittest.TestCase): + def test_policy_is_complete_explicit_and_bound_to_source_inputs(self): + value = local_manifest() + self.assertEqual(validated(value), value) + self.assertEqual(artifacts.manifest_shape(value, REVISION), value) + self.assertEqual(artifacts.artifact_kinds(value), ('ui',)) + for mutate in ( + lambda v: v.pop('workers'), + lambda v: v['workers'].pop('full'), + lambda v: v['workers']['runner'].update(delivery='prepared'), + lambda v: v['workers']['runner'].update(inputs='e' * 64), + lambda v: v['artifacts'].update(runner=manifest()['artifacts']['runner']), + lambda v: v['artifacts'].pop('ui'), + ): + candidate = local_manifest(); mutate(candidate) + with self.subTest(candidate=candidate), self.assertRaises(artifacts.ArtifactError): + validated(candidate) + + def test_host_builds_workers_but_keeps_prepared_ui(self): + release = artifacts.Release(REVISION, validated(local_manifest())) + missing = subprocess.CompletedProcess([], 1, '', '') + built = subprocess.CompletedProcess([], 0, BASE + '\n', '') + def unpack(target): + (target / 'server').mkdir(parents=True) + (target / 'server/index.mjs').write_text('prepared') + with tempfile.TemporaryDirectory() as temporary, \ + patch.object(host_update, 'prepared_release', return_value=release), \ + patch.object(host_update.subprocess, 'run', return_value=missing), \ + patch.object(host_update, 'command', return_value=built) as command, \ + patch.object(release, 'image') as image, patch.object(release, 'ui', side_effect=unpack): + self.assertEqual(host_update.runner_image(), BASE) + self.assertEqual(host_update.full_runner_image(BASE), BASE) + key = host_update.ui_release(Path(temporary)) + self.assertEqual((Path(temporary) / 'ui/releases' / key / 'server/index.mjs').read_text(), 'prepared') + builds = [call.args[0] for call in command.call_args_list if call.args[0][:2] == ['docker', 'build']] + self.assertEqual(len(builds), 2) + self.assertTrue(any('Dockerfile.full' in str(argv) for argv in builds)) + image.assert_not_called() + + def test_missing_or_corrupt_ui_never_becomes_a_source_ui_build(self): + release = artifacts.Release(REVISION, validated(local_manifest())) + with tempfile.TemporaryDirectory() as temporary, \ + patch.object(host_update, 'prepared_release', return_value=release), \ + patch.object(artifacts.urllib.request, 'urlopen', return_value=io.BytesIO(b'bad')), \ + patch.object(host_update, 'command') as command: + with self.assertRaises(artifacts.ArtifactError): + host_update.ui_release(Path(temporary)) + command.assert_not_called() + with self.assertRaises(artifacts.ArtifactError): + release.image('runner') + + def test_only_ui_is_staged_promoted_and_reused(self): + payload = b'archive' + access = {'revision': REVISION, 'manifest': local_manifest(payload), 'urls': { + 'ui': 'https://release-assets.githubusercontent.com/release/ui?sig=temporary'}} + opener = Mock(); opener.open.side_effect = lambda *a, **kw: io.BytesIO(payload) + with tempfile.TemporaryDirectory() as temporary, \ + patch.object(artifacts.urllib.request, 'build_opener', return_value=opener): + cache, promoted = Path(temporary) / 'cache', Path(temporary) / 'service' + self.assertEqual(artifacts.stage(access, cache)['cached'], ['ui']) + self.assertEqual(artifacts.stage(access, cache)['cached'], ['ui']) + self.assertEqual(opener.open.call_count, 1) + self.assertEqual(artifacts.copy_cache(REVISION, cache, promoted)['cached'], ['ui']) + self.assertEqual(artifacts.cached_manifest(REVISION, promoted), access['manifest']) + access['urls']['runner'] = access['urls']['ui'] + with self.assertRaises(artifacts.ArtifactError): + artifacts.stage(access, cache) + + class ConsumptionTests(unittest.TestCase): def test_corrupt_download_is_never_loaded_into_docker(self): release = artifacts.Release(REVISION, manifest()) diff --git a/tests/test_release_delivery.py b/tests/test_release_delivery.py index c46f38be..d4daf33a 100644 --- a/tests/test_release_delivery.py +++ b/tests/test_release_delivery.py @@ -9,15 +9,15 @@ from forge_client.contracts import SetupError from forge_client.install import revision from tests.test_prepared_release_selection import release -from tests.test_release_artifacts import REVISION, manifest +from tests.test_release_artifacts import REVISION, manifest, local_manifest -def fixture(): - value = manifest() +def fixture(value=None): + value = manifest() if value is None else value raw = json.dumps(value).encode() assets = [{'id': index + 10, 'name': name, 'size': value['artifacts'][kind]['size'], 'digest': 'sha256:' + value['artifacts'][kind]['sha256']} - for index, (kind, name) in enumerate(ASSETS.items())] + for index, (kind, name) in enumerate(ASSETS.items()) if kind in value['artifacts']] assets.append({'id': 42, 'name': 'manifest.json', 'size': len(raw)}) return value, raw, release(assets=assets) @@ -37,6 +37,34 @@ def test_default_revision_uses_authenticated_manifest_read_for_private_repositor self.assertIn('Accept: application/octet-stream', manifest_call.args[0]) self.assertEqual(manifest_call.kwargs['output_limit'], 128 * 1024) + def test_local_workers_release_selects_and_transfers_only_ui(self): + value, raw, metadata = fixture(local_manifest()) + run = Mock(side_effect=[json.dumps([metadata]).encode(), json.dumps(metadata).encode(), raw]) + with patch('shutil.which', return_value='gh'): + self.assertEqual(revision(run=run), REVISION) + run = Mock(side_effect=[json.dumps(metadata).encode(), raw, b'gho_local_only']) + opener = Mock(); opener.open.side_effect = redirect() + with patch('shutil.which', return_value='gh'): + result = delivery.access(REVISION, run=run, opener=opener) + self.assertEqual(set(result['urls']), {'ui'}) + self.assertEqual(opener.open.call_count, 1) + self.assertEqual(result['manifest']['workers'], value['workers']) + + def test_worker_download_requires_a_published_worker_not_a_local_recipe(self): + value, raw, metadata = fixture(local_manifest()) + run = Mock(side_effect=[json.dumps(metadata).encode(), raw]) + with patch('shutil.which', return_value='gh'), self.assertRaises(SetupError) as raised: + delivery.access(REVISION, ['runner'], run=run) + self.assertEqual(raised.exception.code, 'invalid_prepared_assets') + self.assertEqual(run.call_count, 2) + + def test_incomplete_v1_does_not_become_local_build(self): + value, raw, metadata = fixture() + metadata['assets'] = [asset for asset in metadata['assets'] if asset['name'] != ASSETS['runner']] + run = Mock(side_effect=[json.dumps(metadata).encode(), raw]) + with patch('shutil.which', return_value='gh'), self.assertRaises(SetupError): + delivery.read_manifest(REVISION, run=run) + def test_scoped_access_returns_only_selected_assets_and_no_personal_token(self): value, raw, metadata = fixture() run = Mock(side_effect=[json.dumps(metadata).encode(), raw, b'gho_local_only\n']) diff --git a/tests/test_release_publication.py b/tests/test_release_publication.py index c815a0f4..9e0098b7 100644 --- a/tests/test_release_publication.py +++ b/tests/test_release_publication.py @@ -5,6 +5,7 @@ from unittest.mock import Mock from tools.prepare_release_publication import prepare +from tests.test_release_artifacts import local_manifest, manifest REVISION = 'a' * 40 @@ -28,9 +29,23 @@ def test_missing_release_can_build_but_network_failure_cannot(self): self.assertEqual(run.call_count, 1) def test_published_release_is_never_modified_or_rebuilt(self): - run = Mock(return_value=response(draft(draft=False))) + assets = [{'name': name} for name in ('manifest.json', 'forge-ui-linux-amd64.tar.gz')] + run = Mock(side_effect=[response(draft(draft=False, assets=assets)), response(local_manifest())]) self.assertEqual(prepare(REVISION, run=run), 'published') - self.assertEqual(run.call_count, 1) + self.assertEqual(run.call_count, 2) + self.assertEqual(run.call_args.args[0][0:3], ['gh', 'release', 'download']) + + def test_published_worker_assets_and_legacy_manifest_cannot_pass_ui_only_policy(self): + assets = [{'name': name} for name in ('manifest.json', 'forge-ui-linux-amd64.tar.gz')] + for extra in ('forge-runner-linux-amd64.tar.gz', 'unexpected.bin'): + run = Mock(return_value=response(draft(draft=False, assets=assets + [{'name': extra}]))) + with self.assertRaisesRegex(ValueError, 'unexpected assets'): + prepare(REVISION, run=run) + self.assertEqual(run.call_count, 1) + run = Mock(side_effect=[response(draft(draft=False, assets=assets)), response(manifest())]) + with self.assertRaisesRegex(ValueError, 'local worker builds'): + prepare(REVISION, run=run) + self.assertEqual(run.call_count, 2) def test_partial_owned_draft_is_replaced_without_deleting_tag(self): run = Mock(side_effect=[response(draft()), response({})]) diff --git a/tests/test_release_roundtrip.py b/tests/test_release_roundtrip.py index 32ceb94d..95dae71c 100644 --- a/tests/test_release_roundtrip.py +++ b/tests/test_release_roundtrip.py @@ -5,10 +5,12 @@ import signal import subprocess import tempfile +import tarfile +import hashlib import unittest from unittest.mock import Mock, patch -from tests.test_release_artifacts import BASE, FULL, manifest +from tests.test_release_artifacts import BASE, FULL, INPUTS, REVISION, manifest, local_manifest spec = importlib.util.spec_from_file_location('release_roundtrip', Path(__file__).resolve().parents[1] / 'tools/qualify_release_roundtrip.py') @@ -97,11 +99,45 @@ def test_corrupt_export_stops_before_load_or_execution(self): self.assertFalse(any(item.args[0][1] in ('run', 'load') or item.args[0][1:3] == ['image', 'load'] for item in docker.call_args_list)) + def test_v2_ui_roundtrip_checks_notices_without_starting_docker(self): + for has_notices in (True, False): + with self.subTest(notices=has_notices), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + value = local_manifest() + archive = root / value['artifacts']['ui']['filename'] + with tarfile.open(archive, 'w:gz') as bundle: + files = {'server/index.mjs': b'server'} + if has_notices: + files['public/third-party-notices.txt'] = b'license text' + for name, content in files.items(): + info = tarfile.TarInfo(name); info.size = len(content) + bundle.addfile(info, io.BytesIO(content)) + value['artifacts']['ui'].update(size=archive.stat().st_size, + sha256=hashlib.sha256(archive.read_bytes()).hexdigest()) + (root / 'manifest.json').write_text(json.dumps(value)) + with patch.object(tool.platform, 'system', return_value='Linux'), \ + patch.object(tool.platform, 'machine', return_value='x86_64'), \ + patch.object(tool.os, 'geteuid', return_value=0), \ + patch.object(tool.subprocess, 'check_output', return_value=REVISION), \ + patch.object(tool.host_update, 'artifact_inputs', return_value=INPUTS), \ + patch.object(tool.host_update, 'NODE_IMAGE', value['node_image']), \ + patch.object(tool.host_update, 'PYTHON_IMAGE', value['python_image']), \ + patch.object(tool, 'isolated_daemon') as daemon: + if has_notices: + tool.qualify(root) + else: + with self.assertRaisesRegex(ValueError, 'no dependency notices'): + tool.qualify(root) + daemon.assert_not_called() + def test_workflow_requires_roundtrip_before_publication(self): - workflow = (Path(__file__).resolve().parents[1] / '.github/workflows/prepared-release.yml').read_text() + workflow = (Path(__file__).resolve().parents[1] / '.github/workflows/prepared-ui-release.yml').read_text() self.assertLess(workflow.index('tools/build_release_artifacts.py'), workflow.index('tools/qualify_release_roundtrip.py')) self.assertLess(workflow.index('tools/qualify_release_roundtrip.py'), workflow.index('gh release create')) + self.assertIn('assert RELEASE_MANIFEST_VERSION == 2', workflow) + self.assertNotIn('forge-runner-linux-amd64.tar.gz', workflow) + self.assertNotIn('forge-runner-full-linux-amd64.tar.gz', workflow) if __name__ == '__main__': diff --git a/tests/test_ui_dependency_notices.py b/tests/test_ui_dependency_notices.py new file mode 100644 index 00000000..36cfe517 --- /dev/null +++ b/tests/test_ui_dependency_notices.py @@ -0,0 +1,85 @@ +import json +import hashlib +from pathlib import Path +import tempfile +import unittest + +from tools.ui_dependency_notices import write_notices + + +class NoticeTests(unittest.TestCase): + def fixture(self, root): + package = root / 'node_modules/example' + package.mkdir(parents=True) + (package / 'package.json').write_text(json.dumps({'name': 'example', 'version': '1.0.0', + 'license': 'MIT', 'repository': 'https://example.com/source'})) + (root / 'package-lock.json').write_text(json.dumps({'packages': {'': {}, 'node_modules/example': { + 'version': '1.0.0', 'resolved': 'https://registry.npmjs.org/example/-/example-1.0.0.tgz', 'integrity': 'sha512-x'}, + 'node_modules/other-platform': {'version': '1.0.0', 'optional': True}}})) + return package + + def test_collects_actual_notices_and_source_without_other_platforms(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + package = self.fixture(root) + (package / 'LICENSE').write_text('Copyright Example. Permission granted.') + (package / 'NOTICE').write_text('Embedded attribution') + output = root / 'public/third-party-notices.txt' + self.assertEqual(write_notices(root, output), []) + text = output.read_text() + for expected in ('example@1.0.0', 'Copyright Example', 'Embedded attribution', + 'https://example.com/source', 'sha512-x'): + self.assertIn(expected, text) + self.assertNotIn('other-platform', text) + + def test_missing_text_is_explicit_and_keeps_readme_evidence(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + package = self.fixture(root) + (package / 'README.md').write_text('Licensed under MIT by Example') + output = root / 'notices.txt' + self.assertEqual(write_notices(root, output), ['example@1.0.0']) + self.assertIn('upstream review required', output.read_text()) + self.assertIn('Licensed under MIT by Example', output.read_text()) + + def test_different_dependency_bytes_are_not_described_as_locked_version(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + package = self.fixture(root) + (package / 'package.json').write_text('{"name":"example","version":"2.0.0"}') + with self.assertRaisesRegex(ValueError, 'differs from its lock'): + write_notices(root, root / 'notices.txt') + + def test_supplement_matches_version_and_hash_and_fills_missing_text(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self.fixture(root) + supplemental = root / 'third-party-licenses' + supplemental.mkdir() + text = b'Copyright and permission from exact upstream revision.' + (supplemental / 'example.txt').write_bytes(text) + entry = {'file': 'example.txt', 'sha256': hashlib.sha256(text).hexdigest(), + 'packages': {'example': '1.0.0'}, 'source': 'https://example.com/pinned/LICENSE'} + provenance = supplemental / 'provenance.json' + provenance.write_text(json.dumps([entry])) + output = root / 'notices.txt' + self.assertEqual(write_notices(root, output), []) + self.assertIn(text.decode(), output.read_text()) + self.assertIn(entry['source'], output.read_text()) + entry['packages']['example'] = '2.0.0' + provenance.write_text(json.dumps([entry])) + with self.assertRaisesRegex(ValueError, 'needs review'): + write_notices(root, output) + (supplemental / 'example.txt').write_text('changed') + with self.assertRaisesRegex(ValueError, 'checksum mismatch'): + write_notices(root, output) + + def test_missing_redistributed_server_license_stops_publication(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self.fixture(root) + runtime = root / 'output/server/node_modules/example' + runtime.mkdir(parents=True) + (runtime / 'package.json').write_text('{"name":"example","version":"1.0.0"}') + with self.assertRaisesRegex(ValueError, 'Redistributed server package'): + write_notices(root, root / 'notices.txt', runtime=runtime.parent) diff --git a/tests/test_updates.py b/tests/test_updates.py new file mode 100644 index 00000000..76930d4c --- /dev/null +++ b/tests/test_updates.py @@ -0,0 +1,122 @@ +import io +import json +import unittest +from unittest.mock import Mock, patch + +from forge.app_access import AccessError +from forge.release_artifacts import ASSETS +from forge.updates import UpdateCheck, public_manifest +from tests.test_release_artifacts import manifest, local_manifest + +OLD, NEW = 'a' * 40, 'b' * 40 + + +def release(revision=NEW, **changes): + return dict(tag_name='forge-build-' + revision, published_at='2026-11-07T12:00:00Z', + assets=[{'name': name} for name in [*ASSETS.values(), 'manifest.json']], **changes) + + +class UpdateTests(unittest.TestCase): + def published_manifest(self, revision): + value = manifest(); value['source'] = revision + return value + + def check(self, responses, fetch_manifest=None): + request = Mock(side_effect=responses) + checker = UpdateCheck(request=request, clock=lambda: 100, monotonic=lambda: 100, + fetch_manifest=fetch_manifest or self.published_manifest) + return checker, request + + def test_only_complete_published_builds_are_offered(self): + incomplete = release(); incomplete['assets'] = [] + checker, request = self.check([[release(OLD), release(draft=True), release(prerelease=True), incomplete]]) + view = checker.view(OLD) + self.assertEqual(view['status'], 'current') + self.assertEqual(view['latest']['revision'], OLD) + self.assertEqual(request.call_count, 1) + self.assertIsNone(request.call_args.args[2], 'checks do not send personal or App credentials') + + def test_ui_only_release_is_discovered_for_manifest_validation_by_installer(self): + candidate = release(OLD) + candidate['assets'] = [{'name': 'manifest.json'}, {'name': ASSETS['ui']}] + value = local_manifest(); value['source'] = OLD + checker, _ = self.check([[candidate]], fetch_manifest=lambda revision: value) + self.assertEqual(checker.view(OLD)['status'], 'current') + + def test_incomplete_v1_is_not_offered_as_a_local_worker_release(self): + candidate = release(OLD) + candidate['assets'] = [{'name': 'manifest.json'}, {'name': ASSETS['ui']}] + checker, _ = self.check([[candidate]]) + result = checker.view(OLD) + self.assertEqual(result['status'], 'unavailable') + self.assertIsNone(result['latest']) + + def test_corrupt_or_unavailable_manifest_is_not_an_update(self): + for value in ({}, {'version': 3}): + checker, _ = self.check([[release()]], fetch_manifest=lambda revision: value) + result = checker.view(OLD) + self.assertEqual(result['status'], 'unavailable') + self.assertIsNone(result['latest']) + checker, _ = self.check([[release()]], fetch_manifest=Mock(side_effect=OSError('network'))) + self.assertEqual(checker.view(OLD)['status'], 'unavailable') + + def test_public_manifest_is_bounded_and_has_no_credentials(self): + response = io.BytesIO(json.dumps(manifest()).encode()) + response.status, response.headers = 200, {} + with patch('forge.updates.urllib.request.urlopen', return_value=response) as fetch: + self.assertEqual(public_manifest(OLD), manifest()) + self.assertEqual(fetch.call_args.args, ('https://github.com/XRPL-Commons/forge/releases/download/forge-build-' + OLD + '/manifest.json',)) + self.assertIn('timeout', fetch.call_args.kwargs) + response = io.BytesIO(b'x' * (128 * 1024 + 1)); response.status, response.headers = 200, {} + with patch('forge.updates.urllib.request.urlopen', return_value=response), self.assertRaises(ValueError): + public_manifest(OLD) + + def test_comparison_prevents_offering_a_downgrade(self): + for github, status in [('ahead', 'available'), ('behind', 'ahead'), ('diverged', 'diverged')]: + with self.subTest(github=github): + checker, request = self.check([[release()], {'status': github}]) + self.assertEqual(checker.view(OLD)['status'], status) + self.assertIn(OLD + '...' + NEW, request.call_args.args[1]) + self.assertIsNone(request.call_args.args[2]) + + def test_unknown_local_build_does_not_claim_up_to_date(self): + checker, request = self.check([[release()]]) + self.assertEqual(checker.view(None)['status'], 'unknown') + self.assertEqual(request.call_count, 1) + checker, _ = self.check([[release()], AccessError('missing commit', status=404)]) + self.assertEqual(checker.view(OLD)['status'], 'unknown') + + def test_private_repo_and_rate_limits_are_not_success(self): + for status in [404, 403, 429]: + checker, _ = self.check([AccessError('private upstream details', status=status)]) + view = checker.view(OLD) + self.assertEqual(view['status'], 'unavailable') + self.assertIsNone(view['latest']) + self.assertNotIn('private upstream details', view['error']) + + def test_missing_releases_is_explicit(self): + checker, _ = self.check([[]]) + self.assertEqual(checker.view(OLD)['status'], 'no_release') + + def test_checks_are_cached_and_manual_refresh_is_bounded(self): + now = [100] + request = Mock(return_value=[release(OLD)]) + checker = UpdateCheck(request=request, clock=lambda: now[0], monotonic=lambda: now[0], fetch_manifest=self.published_manifest) + checker.view(OLD) + now[0] += 30 + checker.view(OLD, refresh=True) + self.assertEqual(request.call_count, 1) + now[0] += 31 + checker.view(OLD) + self.assertEqual(request.call_count, 1) + self.assertEqual(checker.view(OLD, refresh=True)['checked_at'], now[0]) + self.assertEqual(request.call_count, 2) + now[0] += 3601 + checker.view(OLD) + self.assertEqual(request.call_count, 3) + + def test_installed_version_change_invalidates_cache(self): + checker, request = self.check([[release()], {'status': 'ahead'}, [release()]]) + self.assertEqual(checker.view(OLD)['status'], 'available') + self.assertEqual(checker.view(NEW)['status'], 'current') + self.assertEqual(request.call_count, 3) diff --git a/tools/build_release_artifacts.py b/tools/build_release_artifacts.py index e792a713..1aead10e 100644 --- a/tools/build_release_artifacts.py +++ b/tools/build_release_artifacts.py @@ -1,15 +1,12 @@ #!/usr/bin/env python3 """Build and qualify release assets for the exact checked-out commit (Linux amd64).""" import argparse -import gzip import hashlib import json import os from pathlib import Path import platform -import re import runpy -import shutil import subprocess import sys import tarfile @@ -19,74 +16,20 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from forge import host_update from forge.release_artifacts import ASSETS, release_tag, validate_manifest +from tools.ui_dependency_notices import write_notices +RELEASE_MANIFEST_VERSION = 2 -def descriptor(path, inputs, image=None): + +def descriptor(path, inputs): digest = hashlib.sha256() with path.open('rb') as stream: while chunk := stream.read(1024 * 1024): digest.update(chunk) result = {'filename': path.name, 'sha256': digest.hexdigest(), 'size': path.stat().st_size, 'inputs': inputs} - if image: - result.update(image) return result -def image_identity(path, built_image): - """Pin config and manifest identities from the actual exported image. - - Classic Docker identifies an image by its config; containerd uses its - manifest. Both identities must describe the same exported configuration. - Read small JSON metadata in one pass without extracting image layers. - """ - metadata = {} - with tarfile.open(path, 'r|gz') as archive: - for member in archive: - if not member.isfile() or member.size > 256 * 1024: - continue - if member.name not in ('index.json', 'manifest.json') and not re.fullmatch(r'blobs/sha256/[0-9a-f]{64}', member.name): - continue - raw = archive.extractfile(member).read() - try: - value = json.loads(raw) - except (ValueError, UnicodeError): - continue - metadata[member.name] = (raw, value) - try: - entries = metadata['manifest.json'][1] - index = metadata['index.json'][1] - if len(entries) != 1 or len(index['manifests']) != 1: - raise ValueError('Prepared workers require one exported image.') - config_raw, config = metadata[entries[0]['Config']] - config_id = 'sha256:' + hashlib.sha256(config_raw).hexdigest() - manifest_id = index['manifests'][0]['digest'] - if not re.fullmatch(r'sha256:[0-9a-f]{64}', manifest_id): - raise ValueError('Invalid exported manifest digest.') - manifest_raw, manifest = metadata['blobs/sha256/' + manifest_id.removeprefix('sha256:')] - if ('sha256:' + hashlib.sha256(manifest_raw).hexdigest() != manifest_id - or manifest['config']['digest'] != config_id - or entries[0]['Config'] != 'blobs/sha256/' + config_id.removeprefix('sha256:') - or config['os'] != 'linux' or config['architecture'] != 'amd64' - or built_image not in (config_id, manifest_id)): - raise ValueError('Exported worker identity differs from the qualified image.') - except (KeyError, TypeError, IndexError) as error: - raise ValueError('Exported worker metadata is incomplete.') from error - return {'image_id': config_id, 'image_manifest_id': manifest_id} - - -def save_image(image, destination): - with destination.open('wb') as output, gzip.GzipFile(fileobj=output, mode='wb', mtime=0, compresslevel=6) as compressed: - process = subprocess.Popen(['docker', 'image', 'save', image], stdout=subprocess.PIPE) - try: - shutil.copyfileobj(process.stdout, compressed, 1024 * 1024) - if process.wait(): - raise RuntimeError('Docker image export failed') - finally: - process.stdout.close() - if process.poll() is None: - process.kill(); process.wait() - - def build(destination): if platform.system() != 'Linux' or platform.machine() != 'x86_64': raise ValueError('Prepared releases are built on Linux amd64.') @@ -114,18 +57,16 @@ def build(destination): host_update.qualify_runner(base, policy, host_update.APPARMOR_PROFILE) host_update.qualify_runner(full, policy, host_update.APPARMOR_PROFILE, full=True) ui = root / 'ui/releases' / host_update.ui_release(root) + write_notices(root / 'ui/build', ui / 'public/third-party-notices.txt', runtime=ui / 'server/node_modules') with tarfile.open(destination / ASSETS['ui'], 'w:gz') as archive: for child in sorted(ui.iterdir()): archive.add(child, arcname=child.name) - save_image(base, destination / ASSETS['runner']) - save_image(full, destination / ASSETS['full']) - identities = {kind: image_identity(destination / ASSETS[kind], image) - for kind, image in (('runner', base), ('full', full))} inputs = host_update.artifact_inputs() - manifest = {'version': 1, 'source': revision, 'platform': 'linux/amd64', 'node_image': host_update.NODE_IMAGE, + manifest = {'version': RELEASE_MANIFEST_VERSION, 'source': revision, 'platform': 'linux/amd64', 'node_image': host_update.NODE_IMAGE, 'python_image': host_update.PYTHON_IMAGE, - 'artifacts': {kind: descriptor(destination / filename, inputs[kind], identities.get(kind)) - for kind, filename in ASSETS.items()}} + 'artifacts': {'ui': descriptor(destination / ASSETS['ui'], inputs['ui'])}, + 'workers': {kind: {'delivery': 'local-build', 'inputs': inputs[kind]} + for kind in ('runner', 'full')}} validate_manifest(manifest, revision, inputs, host_update.NODE_IMAGE, host_update.PYTHON_IMAGE) (destination / 'manifest.json').write_text(json.dumps(manifest, indent=2, sort_keys=True) + '\n') print('Prepared and qualified artifacts for ' + revision) diff --git a/tools/prepare_release_publication.py b/tools/prepare_release_publication.py index 2f3e756f..4aea16f5 100644 --- a/tools/prepare_release_publication.py +++ b/tools/prepare_release_publication.py @@ -7,7 +7,7 @@ import sys sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from forge.release_artifacts import REPOSITORY, release_tag +from forge.release_artifacts import ASSETS, REPOSITORY, manifest_shape, release_tag def prepare(revision, *, run=subprocess.run): @@ -26,13 +26,28 @@ def prepare(revision, *, run=subprocess.run): if not isinstance(release, dict) or release.get('tag_name') != tag: raise ValueError('GitHub returned a different release; no publication state was changed.') if release.get('draft') is False: + assets = release.get('assets') + expected = {'manifest.json', ASSETS['ui']} + if (not isinstance(assets, list) or len(assets) != len(expected) + or {item.get('name') for item in assets if isinstance(item, dict)} != expected): + raise ValueError('Published release contains unexpected assets; it is not a UI-only release.') + result = run(['gh', 'release', 'download', tag, '--repo', REPOSITORY, + '--pattern', 'manifest.json', '--output', '-'], capture_output=True, text=True) + if result.returncode: + raise ValueError('Could not verify the published UI-only manifest.') + try: + manifest = manifest_shape(json.loads(result.stdout), revision) + except (ValueError, TypeError): + raise ValueError('Could not verify the published UI-only manifest.') from None + if manifest['version'] != 2: + raise ValueError('Published release does not declare local worker builds.') return 'published' if (release.get('draft') is not True or release.get('target_commitish') != revision or not isinstance(release.get('author'), dict) or release['author'].get('login') != 'github-actions[bot]'): raise ValueError('Only this workflow’s unpublished draft for the exact commit can be retried.') # A failed upload can leave a partial draft. Rebuild all assets together, - # because rebuilding pinned source can still produce different image IDs. + # because rebuilding pinned UI source can still produce different asset bytes. # Keep the tag. Published releases and drafts owned by humans are untouched. run(['gh', 'release', 'delete', tag, '--repo', REPOSITORY, '--yes'], check=True, capture_output=True, text=True) diff --git a/tools/qualify_release_roundtrip.py b/tools/qualify_release_roundtrip.py index c081091c..6cf8d727 100644 --- a/tools/qualify_release_roundtrip.py +++ b/tools/qualify_release_roundtrip.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Load exported release images into isolated classic and containerd Docker stores. +"""Verify prepared UI archives; retain exported-image qualification for legacy v1 releases. Run with sudo on the Linux CI host. Uses its installed dockerd binary and never connects to, stops, or changes the builder's Docker daemon. @@ -144,6 +144,21 @@ def qualify(directory): revision = subprocess.check_output(['git', '-c', 'safe.directory=' + str(host_update.SOURCE), '-C', str(host_update.SOURCE), 'rev-parse', 'HEAD'], text=True).strip() validate_manifest(manifest, revision, inputs, host_update.NODE_IMAGE, host_update.PYTHON_IMAGE) + if manifest['version'] == 2: + with tempfile.TemporaryDirectory(prefix='forge-ui-roundtrip-') as temporary: + release = Release(manifest['source'], manifest) + def download(kind, target): + source = directory / manifest['artifacts'][kind]['filename'] + verify_archive(source, manifest['artifacts'][kind]) + shutil.copyfile(source, target) + release.download = download + target = Path(temporary) / 'ui' + release.ui(target) + notices = target / 'public/third-party-notices.txt' + if not notices.is_file() or not notices.read_text().strip(): + raise ValueError('Prepared UI has no dependency notices.') + print('Prepared UI archive and notices roundtrip passed; workers build on the operator host.', flush=True) + return for containerd in (False, True): name = 'containerd' if containerd else 'classic' print('Qualifying exported images in the ' + name + ' Docker store…', flush=True) diff --git a/tools/ui_dependency_notices.py b/tools/ui_dependency_notices.py new file mode 100644 index 00000000..1d83450e --- /dev/null +++ b/tools/ui_dependency_notices.py @@ -0,0 +1,79 @@ +"""Collect license evidence from the exact installed UI build dependency tree. + +This deliberately includes build/test packages as a conservative superset of +bundled code. It does not infer licenses or claim that metadata is legal text. +""" +import json +import hashlib +from pathlib import Path + +LEGAL_NAMES = ('license', 'licence', 'copying', 'notice', 'copyright') + + +def write_notices(build, destination, *, runtime=None): + build, destination = Path(build), Path(destination) + lock = json.loads((build / 'package-lock.json').read_text()) + supplements = {} + provenance = build / 'third-party-licenses/provenance.json' + if provenance.exists(): + for item in json.loads(provenance.read_text()): + path = provenance.parent / item['file'] + raw = path.read_bytes() + if hashlib.sha256(raw).hexdigest() != item['sha256']: + raise ValueError('Supplemental UI license checksum mismatch: ' + item['file']) + for name, version in item['packages'].items(): + supplements.setdefault(name, []).append((version, item, raw.decode())) + sections = ['Forge UI third-party notices\n\n' + 'Collected from the locked npm installation used for this build. ' + 'Includes build dependencies that may not be shipped at runtime. ' + 'Packages retain their own licenses. Registry tarballs and upstream ' + 'repositories identify the unchanged upstream sources.\n'] + missing = [] + for relative, locked in sorted(lock['packages'].items()): + if not relative: + continue + package = build / relative + metadata = package / 'package.json' + if not metadata.exists(): + # npm omits optional binaries for other platforms. + if locked.get('optional'): + continue + raise ValueError('UI notice dependency was not installed: ' + relative) + value = json.loads(metadata.read_text()) + if value.get('version') != locked['version']: + raise ValueError('UI notice dependency differs from its lock: ' + relative) + name = value['name'] + '@' + value['version'] + sections.append('\n' + '=' * 72 + '\n' + name + '\n') + for label, datum in [('License metadata', value.get('license', locked.get('license', 'unspecified'))), + ('Repository', value.get('repository', 'unspecified')), + ('Package source', locked.get('resolved', 'unspecified')), + ('Integrity', locked.get('integrity', 'unspecified'))]: + sections.append(label + ': ' + (datum if isinstance(datum, str) else json.dumps(datum, sort_keys=True)) + '\n') + files = sorted(path for path in package.rglob('*') + if path.is_file() and 'node_modules' not in path.relative_to(package).parts + and path.name.lower().startswith(LEGAL_NAMES)) + extra = supplements.get(value['name'], []) + for version, item, text in extra: + if version != value['version']: + raise ValueError('Supplemental UI license needs review for ' + name) + sections.append('\nSupplement source: ' + item['source'] + '\nSHA-256: ' + item['sha256'] + + '\n' + item.get('version_evidence', '') + '\n' + text.rstrip() + '\n') + if not files and not extra: + if runtime is not None and (Path(runtime) / value['name'] / 'package.json').exists(): + raise ValueError('Redistributed server package has no license text: ' + name) + missing.append(name) + sections.append('No license text in package; inspect upstream license before redistribution.\n') + files = sorted(path for path in package.iterdir() + if path.is_file() and path.name.lower().startswith('readme')) + # Icon sets sometimes carry attribution/licensing in structured metadata. + if value['name'].startswith('@iconify-json/') and (package / 'info.json').is_file(): + files.append(package / 'info.json') + for path in files: + sections.append('\n--- ' + str(path.relative_to(package)) + ' ---\n') + sections.append(path.read_text(errors='replace').rstrip() + '\n') + if missing: + sections.insert(1, '\nPackages without separate license text (upstream review required):\n' + + '\n'.join(missing) + '\n') + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(''.join(sections)) + return missing diff --git a/ui/app/app.vue b/ui/app/app.vue index 5acf3c17..2eeab53e 100644 --- a/ui/app/app.vue +++ b/ui/app/app.vue @@ -1,3 +1,7 @@ +