diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9a22f520..234091c1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -184,7 +184,8 @@ jobs: # Managed Secure Access readiness (0.69): the heartbeat block's parser # (closed keys and values, cli agreeing with the keys, nothing that is # not the installed exe) and the readiness decision — every rule, and - # 622,080 combinations of facts with no managed state among them. + # 1,244,160 combinations of facts with no managed fact and no managed + # state among them (0.72: the managed states only from a managed fact). - name: MSA readiness tests run: node apps/api/scripts/unit-msa-readiness.mjs @@ -195,6 +196,13 @@ jobs: - name: MSA grant tests run: node apps/api/scripts/unit-msa-grants.mjs + # Managed Secure Access enforcement (0.72): the vocabulary the portal and + # the agent share (keys, outcomes, events, the view-only ceiling), the + # rotation hold, the strict report body, and the grant-key target's one + # name and schema across the portal, the agent and the release host. + - name: MSA managed tests + run: node apps/api/scripts/unit-msa-managed.mjs + # Diagnostics catalog (0.31): the closed catalog, result sanitising, # redaction and the size cap against the compiled module, the agent's # dispatch switch against the catalog — and, with the runner's pwsh, both diff --git a/.github/workflows/lab-windows.yml b/.github/workflows/lab-windows.yml index 1ecf4fcd..1a4f8b25 100644 --- a/.github/workflows/lab-windows.yml +++ b/.github/workflows/lab-windows.yml @@ -76,6 +76,24 @@ jobs: $env:REM0TE_LAB_AGENT_EXE = "$env:RUNNER_TEMP\rem0te-agent.exe" go test -tags labwindows -count=1 -v -timeout 15m -run '^TestLabRustdeskPreflight$' . exit $LASTEXITCODE + # Managed Secure Access enforcement (0.72): the agent's enforcement exec + # site against the real RustDesk — save, apply a view-only grant and + # read every setting back, the one-time password ("Done"), end the + # session (random password, stop-service Y then N), restore — as the + # administrator and as SYSTEM in session 0. It changes RustDesk's + # settings on this throwaway runner and puts them back. + - name: Agent MSA enforcement ${{ matrix.version }} (apply, readback, end, restore) + if: matrix.version != '1.3.9' + working-directory: tools/windows-installer + shell: powershell + env: + REM0TE_LAB: '1' + REM0TE_LAB_RUSTDESK: ${{ matrix.version }} + REM0TE_LAB_EVIDENCE: ${{ runner.temp }}\lab-part\enforce-evidence-${{ matrix.version }}.jsonl + run: | + New-Item -ItemType Directory -Force -Path "$env:RUNNER_TEMP\lab-part" | Out-Null + go test -tags labwindows -count=1 -v -timeout 20m -run '^TestLabRustdeskEnforce$' . + exit $LASTEXITCODE - name: Keep the part if: always() uses: actions/upload-artifact@v7 diff --git a/CHANGELOG.md b/CHANGELOG.md index bc2a9a57..6b41769d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,142 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). --- +## [0.72.0] — 2026-11-20 · *Helm* + +**Managed Secure Access build step 4: agent enforcement, the managed test session, cutover and rollback — +behind `MSA_GRANTS`, which is off.** (docs/managed-secure-access.md §3.11; check-security-invariants §82, with +§56, §62, §80 and §81 amended.) + +> **This is a new signed agent build.** When it is published the fleet's signed agents update to 0.72 the way +> they always do. **On a Legacy computer — which is every computer until a Platform Admin moves one — the 0.72 +> agent behaves exactly as 0.71's**: the heartbeat never says `msaPoll`, the new `msa-poller` never starts, and +> no RustDesk setting or password is touched. With `MSA_GRANTS` off (production) nothing new happens anywhere: +> every new route answers `404 MSA_NOT_ENABLED` and the heartbeat never tells an agent to poll. + +Even with the switch on, **nothing on a computer changes until a Platform Admin moves that one computer into +Managed (pending)** with a fresh confirmation. There is no group, business or fleet cutover and nothing moves a +computer by itself. Managed Secure Access has run only in the Windows lab (GitHub's Windows Server runners, +RustDesk 1.4.1–1.5.3), never on a Windows 10/11 desktop or on the fleet. + +### Grant keys reach agents only through the signed release + +- New on the release host: `rem0te-signed-grant-key add | list | retire` (installed by + `rem0te-signed-setup.sh`). It records grant **public** keys in `$STATE_DIR/msa-grant-keys.json` (at most 8) + and refuses key material (`PRIVATE`, `-----BEGIN`), anything that is not 32 bytes of standard base64, and a + key id that is not the first 16 hex of the key's SHA-256. +- `rem0te-signed-publish` signs the list in on every publish as the target `msa/grant-keys.json` (schema + `rem0te-msa-grant-keys/1`); `rem0te-signed-status` shows its digest. `retire` + `--republish` publishes the + shorter list, so agents refuse grants under the retired key. +- The agent reads keys only from that verified target (`agent.MsaTrust`, with the signed pause). No target, an + empty list or an unknown key id is a refusal (`no_keys`, `unknown_key`) — the portal never sends a key. +- The console's Managed Secure Access card shows a Platform Admin the exact two commands + (`sudo rem0te-signed-grant-key add --key-id … --public-key …`, `sudo rem0te-signed-publish --republish`) until + the published release lists the active key; `POST /msa/grants/keys` (`msa.grant`) creates the key if none + exists. The two strings are constants in `apps/api/src/msa/grant-key-commands.ts`, which §56 matches exactly. + +### Per-computer mode, cutover, verification and rollback (migration 0089) + +- `MsaManagedComputer`: no row is Legacy; `pending`, `verified`, `enforcement_failure`, `rollback_pending`. + Written only by `MsaManagedService`. A trigger refuses a row for an unassigned computer. +- `POST /msa/managed/:endpointId/cutover` — Platform Admin, `assertFresh` naming the new catalog key + `msa.cutover` (default off, as every key since 0.64). Refused: unassigned (`ENDPOINT_UNASSIGNED`), not the + signed Windows agent (`MSA_SIGNED_AGENT_REQUIRED`), readiness not *Compatible* (`MSA_NOT_COMPATIBLE`), an + agent older than 0.72 (`MSA_AGENT_TOO_OLD`), a `remote` pause (`CONTAINED`), already managed + (`MSA_ALREADY_MANAGED`), or the grant key not in the published release (`MSA_GRANT_KEY_NOT_PUBLISHED`). + `MSA_CUTOVER` is written with `logOrFail` before the row. +- `POST …/confirm` (`msa.cutover`) moves `pending` → `verified` only after a test session since cutover that read + back and connected (`MSA_NO_TEST_SESSION` otherwise). The agent then sets a permanent password nobody is + told (`MSA_LEGACY_SECURED`). +- `POST …/rollback` — Platform Admin, **never** asks for a fresh confirmation, audited. Cancels issued grants, + stages a fresh sealed permanent password through the existing rotation path (`stageRotationForMsa`, which + shares `stagePendingPassword` with Rotate), and wakes the agent, which ends any session, restores the saved + settings and reads them back (`restored` deletes the row; `restore_failed` keeps it, with the keys). + `force: true` finishes a rollback only for a computer already rolling back whose agent is gone. +- Readiness gains *Managed (pending)*, *Managed and verified* and *Enforcement failure*, produced only from the + row and the agent's reports. `verified: true` only for *Managed and verified*, and only while the agent's last + full readback is inside the report window; older, it reads *Unknown*. +- A **verified** computer's legacy password is refused everywhere: Reveal, Connect (`msa_managed`), Rotate and + Set password (`409 MSA_MANAGED`). A staged legacy rotation waits while the computer is verified, failing, + rolling back, or has a grant in flight (`managed.ts` `rotationHeld`, bounded by the grant's window / 9 h). + **Technician Connect through grants is step 5**, so a verified computer is reachable only through Platform + Admin test grants until then: roll it back to connect the ordinary way. Turning `MSA_GRANTS` off with a verified + computer stops its poller but keeps refusing its legacy password (fail closed) — roll back first. + +### The heartbeat and the poller + +- The heartbeat answers `msaPoll: true` only to an authenticated signed heartbeat that may act (§64), after the + not-may-act and pooled returns, with the switch on and a managed row. The signed heartbeat script then starts + `rem0te-agent.exe msa-poller` (no arguments; one instance under `msa\poller.lock`; it exits after an idle hour, + or as soon as the portal says Legacy / 404 / 403). +- `internal/msa/enforce` (portable, fakes under test) + `msa_poller_windows.go`. For each grant: verify under the + published keys, this computer's own endpoint id (pinned on first answer) and RustDesk ID, the persisted replay + set, the signed pause, and the **compiled ceiling: view only, nothing beyond** — no keyboard, clipboard, files, + audio, tunnel or remote restart. The portal refuses a managed grant above it first (`MSA_ABOVE_CEILING`). +- The replay set is written before anything changes; before the first change ever, every current setting is + saved to `StateDir\msa\enforce\saved.json` (SYSTEM-only DACL). A save that fails refuses the grant + (`save_failed`). +- Apply: `verification-method=use-permanent-password` first, then the §3.3 settings, each read back (an empty + readback is RustDesk's default, per the 0.68.3 lab), then the one-time password last, which must print `Done`. + Any disagreement ends the session at once and reports `failed` with closed key names (`readback_mismatch`, + `password_not_applied`); nothing weaker is applied. +- Session end (connection closed, `maxMinutes`, nobody connected by `notAfter`, rollback): a random 24-character + password nobody is told, `stop-service Y`, 3 s, `N`, and `stop-service` read back `N`. While pending, the saved + settings are restored after each test session and the portal stages a legacy rotation, so Legacy Connect keeps + working between test sessions. At rest a verified computer is read back hourly; drift is *Enforcement failure*. +- `POST /msa/agent/report` (public, rate-limited): a strict zod body with closed events, outcomes and keys and no + password field, then the device secret, before anything is read. +- One exec site (`enforceRunner.Run`): only what `enforce.Valid` accepts, only the installed `rustdesk.exe` that + the RustDesk service runs, argument array, no shell, no window, output capped, arguments never logged. §80's + "only the preflight names `--option`" is now an exact list: the preflight's two files and `enforce/args.go`; + only `enforce/args.go` names `--password`. The password is in no log, report or audit row. + +### The managed test session + +`POST /msa/grants/test/:endpointId` on a pending computer sends a view-only grant (consent required). Once the +agent reports it applied, **Reveal one-time password** (`POST /msa/managed/grants/:grantId/reveal`, Platform +Admin, new catalog key `msa.reveal`) shows it once: scope, applied and not yet revealed, then +`MSA_PASSWORD_REVEALED` (ids only) with `logOrFail`, then a conditional claim, then the password is opened. The +admin connects with RustDesk; the agent reports `connected` (`rustdesk.exe --cm`) and `ended`. + +### Console (Platform Admins only, nothing visible with the switch off) + +The readiness card gains *Move to Managed (pending)*, *Send test grant*, *Reveal one-time password*, *Confirm +verified*, *Roll back to Legacy* and *Finish rollback without the agent*, with the evidence behind each state and +the grant-key commands. Labels say what was observed, never what was merely saved. + +With the switch off the console makes **no request to a gated route**: the readiness answers carry +`managedControls` (the switch), and the card mounts the managed controls only when it is true (an earlier build +of this branch asked `GET /msa/managed/:id` on every device page and got a 404 each time; `e2e-ui.mjs` now asserts +no `/msa/managed` or `/msa/grants` request is made). *Remote access readiness* shows the four readiness tiles while +the switch is off — a managed tile appears only for a state some computer is really in — and all seven, with a +testing note, when it is on. + +### Not in this release (step 5) + +Connect issuing grants for technicians; `control` mode or any permission above view-only; group or business +cutover; revocation and the session-evidence timeline; a console switch for `MSA_GRANTS`. + +### Tests + +- `apps/api/scripts/e2e-msa-managed.mjs` (new, port 3961, in `run-e2e.sh`): 106 checks — the switch off, every + cutover refusal, the published-key gate against a stand-in signed repository, msaPoll only for the managed + computer, reports, reveal once, confirm, rollback and force, legacy refusals, the CHECKs. +- `unit-msa-managed.mjs` (new, in CI, 42), `unit-msa-readiness.mjs` (102), `e2e-msa-grants.mjs` (69), + `e2e-msa-readiness.mjs` (52), `unit-signed-release.mjs` and `e2e-signed-release.mjs` (grant-key add, refusals, + publish, status, retire). +- Go: `internal/msa/enforce` (20 tests, a fake RustDesk: apply order, fail-closed readback, `Done`, replay, + bad keys, ceiling, pause, endpoint pin, save failure, no connection / max minutes, rollback, drift). +- Windows lab: `TestLabRustdeskEnforce` in every RustDesk job (1.4.1–1.5.3) — save, apply, readback, password, + end session, restore, as the administrator and as SYSTEM. The WSUS `127.0.0.1:8530` trick is unchanged. + +### Deploying (only with the owner's approval) + +Migration 0089 (and the Prisma client at the target, per CLAUDE.md). Leave `MSA_GRANTS` unset. Publish the signed +agent as usual. To try one computer later: set `MSA_GRANTS=on`, create the key in the console, run the two +commands it shows on the release host, then move one computer. + +--- + ## [0.71.0] — 2026-11-20 · *Tether* **Managed Secure Access build step 3: the portal can sign a session grant and hold it for a computer's signed diff --git a/CLAUDE.md b/CLAUDE.md index 9d52fdf7..a49c03ab 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1567,8 +1567,9 @@ computer and nothing can be Managed. - **The agent only reads.** `rem0te-agent.exe rustdesk-preflight` builds its argv only through `msa.ReadArgs` — exactly `{"--option", key}` for the eleven keys of `msa.Keys`, the same list as the portal's `PREFLIGHT_KEYS` — - and nothing in the preflight names `--password`. Only the preflight names - `--option`. + and nothing in the preflight names `--password`. From 0.72 `--option` is + named only by the preflight and `internal/msa/enforce/args.go`, and + `--password` only by `args.go` (§82). - **One exec site** (`preflightRunner.Read`): the installed `%ProgramFiles%\RustDesk\rustdesk.exe` (`installedRustdeskExe()`) by absolute path, an argument array, no shell, no window, output capped. It @@ -1620,9 +1621,10 @@ agent binary is unchanged. poll hands nothing over. - **The document.** `msa/grant.ts` imports only `node:crypto` and zod. Its `GRANT_PREFIX` (`rem0te-msa-grant-v1\n`) and `REASONS` order are the Go - verifier's (`internal/msa/grant`). That package is pure and imported by - nothing: it lives outside `internal/msa` because the agent imports that - package for the preflight. + verifier's (`internal/msa/grant`). That package is pure (no clock, file, + network or process). It lives outside `internal/msa` because the agent + imports that package for the preflight; from 0.72 only + `internal/msa/enforce` and `internal/agent` import it (§82). - **0088** CHECKs the four states, the five-minute window, the limits and the sealed columns, and holds one active key (partial unique index). @@ -1633,6 +1635,60 @@ test-only keys) and asserts every case, and the Go `internal/msa/grant` tests, which assert the same file. **No agent polls, and none of it has run on Windows.** +§82 (0.72) is Managed Secure Access enforcement, the managed test session, +cutover and rollback: build step 4, **behind `MSA_GRANTS`, off**. This is a +new signed agent build, but a computer changes only when a Platform Admin +moves that **one** computer; a Legacy computer behaves exactly as 0.71. + +- **The heartbeat** says `msaPoll: true` only to an authenticated signed + agent that may act, only with the switch on and a `MsaManagedComputer` + row. The signed heartbeat starts `rem0te-agent.exe msa-poller` (no + argument) only on that answer. One poller at a time (`poller.lock`); it + exits when idle or told the computer is Legacy. +- **Writers.** Only `MsaManagedService` writes `MsaManagedComputer` (0089), + and every public method asserts the switch first. `MsaManagedService` + moves grants only by conditional `updateMany`; only `MsaGrantService` + creates them. +- **Who.** Cutover and confirming verified are a Platform Admin's with + `assertFresh` naming `msa.cutover`; revealing a test session's one-time + password (once) names `msa.reveal`; rollback never asks. No route takes a + group or a business. +- **Cutover**, in order: scope, the pool, not already managed, every blocker + (Compatible readiness, an agent that can enforce, no `remote` pause, a + grant key in the published release), the audit row, then the row. +- **The ceiling** is view-only with no permissions, on both sides + (`enforce.Ceiling` compiled into the agent, the portal's + `MANAGED_CEILING`), never taken from the portal. +- **The agent.** One enforcement exec site (`enforceRunner.Run`) runs only + what `enforce.Valid` accepts, the installed `rustdesk.exe` by absolute + path, an argument array, no shell, and only when the RustDesk service runs + that file. Grant keys come only from the signed `msa/grant-keys.json` + target of the verified update chain. The replay set is written before + anything changes. Settings are saved (SYSTEM-only DACL) before the first + apply, every value is read back, and a mismatch ends the session with a + password nobody is told. No password reaches a log, journal or report. +- **A device report** is parsed strictly, then the device secret is checked, + before any read. +- **Passwords.** A verified computer's legacy password is never revealed, + launched, rotated or set, and a staged rotation waits (`rotationHeld`). + After a pending test session ends, the portal re-establishes a password it + knows through the existing rotation; rollback stages one too. +- **The release host** publishes grant keys (`rem0te-signed-grant-key + add|list|retire`, then `rem0te-signed-publish`); the portal only shows the + two commands, matched exactly in §56's allowlist + (`msa/grant-key-commands.ts`). +- **Not built (step 5):** Connect through grants, control mode, group or + business cutover, revocation and the session-evidence timeline. Turning + the switch off with a verified computer still refuses its legacy + password: roll back first. + +Behavioural proof: `e2e-msa-managed.mjs` (port 3961, in `run-e2e.sh`). Unit: +`unit-msa-managed.mjs` (in CI) and the Go `internal/msa/enforce` tests (a +fake RustDesk runner). Lab: `TestLabRustdeskEnforce` in the Windows lab's +RustDesk jobs (save, apply, read back, password, end session, restore, as the +administrator and as SYSTEM). **It has run only on Windows Server in the +lab**, never on a desktop, with a real remote connection, or on the fleet. + CI runs it on every push and pull request, alongside `check-versions.mjs`. ## Docs diff --git a/README.md b/README.md index d62c3b86..5b5a30dc 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ people and its own history. Rem0te is the portal around a self-hosted RustDesk server that keeps them organised and separate. [![CI](https://github.com/agit8or1/rem0te/actions/workflows/ci.yml/badge.svg)](https://github.com/agit8or1/rem0te/actions/workflows/ci.yml) -[![Version](https://img.shields.io/badge/version-0.71.0-blue)](https://github.com/agit8or1/rem0te/releases) +[![Version](https://img.shields.io/badge/version-0.72.0-blue)](https://github.com/agit8or1/rem0te/releases) [![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE) [![Stars](https://img.shields.io/github/stars/agit8or1/rem0te?style=flat)](https://github.com/agit8or1/rem0te) diff --git a/apps/api/package.json b/apps/api/package.json index 6b070128..d401b97f 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -1,6 +1,6 @@ { "name": "@reboot-remote/api", - "version": "0.71.0", + "version": "0.72.0", "private": true, "scripts": { "dev": "nest start --watch", diff --git a/apps/api/prisma/migrations/0089_msa_managed/migration.sql b/apps/api/prisma/migrations/0089_msa_managed/migration.sql new file mode 100644 index 00000000..918f9b41 --- /dev/null +++ b/apps/api/prisma/migrations/0089_msa_managed/migration.sql @@ -0,0 +1,106 @@ +-- v0.72: Managed Secure Access build step 4 — agent enforcement, the managed +-- test session, cutover and rollback (docs/managed-secure-access.md §3.3, +-- §3.7, §3.11), behind MSA_GRANTS, off. +-- +-- MsaManagedComputer is a computer's mode when it is not Legacy (no row is +-- Legacy, the default). A Platform Admin moves ONE computer at a time into +-- `pending`; nothing moves a group, a business or the fleet, and nothing moves +-- a computer by itself. +-- +-- MsaGrant gains the agent's outcomes: applied (every setting read back and +-- the one-time password set), failed (refused, or a readback disagreed) and +-- ended (the agent set a password nobody is told and stopped the service). + +ALTER TYPE "ActivityAction" ADD VALUE 'MSA_GRANT_KEY_ENSURED'; +ALTER TYPE "ActivityAction" ADD VALUE 'MSA_CUTOVER'; +ALTER TYPE "ActivityAction" ADD VALUE 'MSA_VERIFIED'; +ALTER TYPE "ActivityAction" ADD VALUE 'MSA_ROLLBACK_REQUESTED'; +ALTER TYPE "ActivityAction" ADD VALUE 'MSA_ROLLED_BACK'; +ALTER TYPE "ActivityAction" ADD VALUE 'MSA_GRANT_APPLIED'; +ALTER TYPE "ActivityAction" ADD VALUE 'MSA_GRANT_FAILED'; +ALTER TYPE "ActivityAction" ADD VALUE 'MSA_SESSION_CONNECTED'; +ALTER TYPE "ActivityAction" ADD VALUE 'MSA_SESSION_ENDED'; +ALTER TYPE "ActivityAction" ADD VALUE 'MSA_ENFORCEMENT_FAILURE'; +ALTER TYPE "ActivityAction" ADD VALUE 'MSA_LEGACY_SECURED'; +ALTER TYPE "ActivityAction" ADD VALUE 'MSA_PASSWORD_REVEALED'; + +-- ── MsaGrant: the agent's outcomes ───────────────────────────────────────── +ALTER TABLE "MsaGrant" ADD COLUMN "appliedAt" TIMESTAMP(3); +ALTER TABLE "MsaGrant" ADD COLUMN "connectedAt" TIMESTAMP(3); +ALTER TABLE "MsaGrant" ADD COLUMN "endedAt" TIMESTAMP(3); +ALTER TABLE "MsaGrant" ADD COLUMN "outcome" TEXT; +ALTER TABLE "MsaGrant" ADD COLUMN "failedKeys" TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[]; +ALTER TABLE "MsaGrant" ADD COLUMN "revealedAt" TIMESTAMP(3); +ALTER TABLE "MsaGrant" ADD COLUMN "revealedById" TEXT; + +ALTER TABLE "MsaGrant" DROP CONSTRAINT "MsaGrant_state_check"; +ALTER TABLE "MsaGrant" ADD CONSTRAINT "MsaGrant_state_check" + CHECK ("state" IN ('issued', 'delivered', 'expired', 'cancelled', 'applied', 'failed', 'ended')); +-- A grant the agent acted on was delivered to it; one never delivered was not. +ALTER TABLE "MsaGrant" DROP CONSTRAINT "MsaGrant_delivered_check"; +ALTER TABLE "MsaGrant" ADD CONSTRAINT "MsaGrant_delivered_check" + CHECK (("state" IN ('issued', 'expired', 'cancelled')) = ("deliveredAt" IS NULL)); +ALTER TABLE "MsaGrant" ADD CONSTRAINT "MsaGrant_applied_check" + CHECK (("state" <> 'applied' OR "appliedAt" IS NOT NULL) AND ("connectedAt" IS NULL OR "appliedAt" IS NOT NULL)); +ALTER TABLE "MsaGrant" ADD CONSTRAINT "MsaGrant_ended_check" CHECK (("state" = 'ended') = ("endedAt" IS NOT NULL)); +ALTER TABLE "MsaGrant" ADD CONSTRAINT "MsaGrant_failed_check" CHECK ("state" <> 'failed' OR "outcome" IS NOT NULL); +-- msa/managed.ts OUTCOMES: closed codes, never text from the computer. +ALTER TABLE "MsaGrant" ADD CONSTRAINT "MsaGrant_outcome_check" CHECK ("outcome" IS NULL OR "outcome" ~ '^[a-z_]{1,40}$'); +-- msa/preflight.ts PREFLIGHT_KEYS plus the password: nothing else is a key. +ALTER TABLE "MsaGrant" ADD CONSTRAINT "MsaGrant_failedKeys_check" CHECK ( + cardinality("failedKeys") <= 12 AND "failedKeys" <@ ARRAY['access-mode', 'enable-keyboard', 'enable-clipboard', 'enable-file-transfer', + 'enable-audio', 'enable-tunnel', 'enable-remote-restart', 'approve-mode', 'verification-method', 'allow-auto-disconnect', + 'auto-disconnect-timeout', 'password']::TEXT[]); +-- Revealed only once the agent applied it, and to someone. +ALTER TABLE "MsaGrant" ADD CONSTRAINT "MsaGrant_revealed_check" + CHECK (("revealedAt" IS NULL) = ("revealedById" IS NULL) AND ("revealedAt" IS NULL OR "appliedAt" IS NOT NULL)); + +-- ── MsaManagedComputer ───────────────────────────────────────────────────── +CREATE TABLE "MsaManagedComputer" ( + "endpointId" TEXT NOT NULL, + "state" TEXT NOT NULL, + "requestedById" TEXT NOT NULL, + "requestedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "verifiedAt" TIMESTAMP(3), + "verifiedById" TEXT, + "legacySecuredAt" TIMESTAMP(3), + "failedAt" TIMESTAMP(3), + "failReason" TEXT, + "failedKeys" TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[], + "rollbackRequestedAt" TIMESTAMP(3), + "rollbackRequestedById" TEXT, + "readbackOkAt" TIMESTAMP(3), + "lastReportAt" TIMESTAMP(3), + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "MsaManagedComputer_pkey" PRIMARY KEY ("endpointId"), + CONSTRAINT "MsaManagedComputer_state_check" CHECK ("state" IN ('pending', 'verified', 'enforcement_failure', 'rollback_pending')), + -- Verified means a Platform Admin confirmed it after a managed test session. + CONSTRAINT "MsaManagedComputer_verified_check" + CHECK (("state" <> 'verified' OR "verifiedAt" IS NOT NULL) AND ("verifiedAt" IS NULL) = ("verifiedById" IS NULL)), + CONSTRAINT "MsaManagedComputer_failure_check" + CHECK ("state" <> 'enforcement_failure' OR ("failedAt" IS NOT NULL AND "failReason" IS NOT NULL)), + CONSTRAINT "MsaManagedComputer_rollback_check" + CHECK (("state" = 'rollback_pending') = ("rollbackRequestedAt" IS NOT NULL) AND ("rollbackRequestedAt" IS NULL) = ("rollbackRequestedById" IS NULL)), + CONSTRAINT "MsaManagedComputer_failReason_check" CHECK ("failReason" IS NULL OR "failReason" ~ '^[a-z_]{1,40}$'), + CONSTRAINT "MsaManagedComputer_failedKeys_check" CHECK ( + cardinality("failedKeys") <= 12 AND "failedKeys" <@ ARRAY['access-mode', 'enable-keyboard', 'enable-clipboard', 'enable-file-transfer', + 'enable-audio', 'enable-tunnel', 'enable-remote-restart', 'approve-mode', 'verification-method', 'allow-auto-disconnect', + 'auto-disconnect-timeout', 'password']::TEXT[]), + CONSTRAINT "MsaManagedComputer_secured_check" CHECK ("legacySecuredAt" IS NULL OR "verifiedAt" IS NOT NULL) +); +ALTER TABLE "MsaManagedComputer" ADD CONSTRAINT "MsaManagedComputer_endpointId_fkey" FOREIGN KEY ("endpointId") REFERENCES "Endpoint"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- Only a computer assigned to a business can be managed (§70: the pool is +-- never reached). The service checks it first; this is the backstop. +CREATE FUNCTION "MsaManagedComputer_assigned"() RETURNS trigger AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM "Endpoint" e WHERE e."id" = NEW."endpointId" AND e."tenantId" IS NOT NULL AND e."customerId" IS NOT NULL + ) THEN + RAISE EXCEPTION 'MsaManagedComputer: % is not assigned to a business', NEW."endpointId"; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER "MsaManagedComputer_assigned" BEFORE INSERT ON "MsaManagedComputer" FOR EACH ROW EXECUTE FUNCTION "MsaManagedComputer_assigned"(); diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 7d123d27..4e3b34a3 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -394,6 +394,20 @@ enum ActivityAction { // and key id only — never the password or the envelope). MSA_GRANT_KEY_CREATED MSA_GRANT_ISSUED + // 0.72 Managed Secure Access build step 4 (behind MSA_GRANTS, off): ids, + // states, closed codes and key names only — never a password. + MSA_GRANT_KEY_ENSURED + MSA_CUTOVER + MSA_VERIFIED + MSA_ROLLBACK_REQUESTED + MSA_ROLLED_BACK + MSA_GRANT_APPLIED + MSA_GRANT_FAILED + MSA_SESSION_CONNECTED + MSA_SESSION_ENDED + MSA_ENFORCEMENT_FAILURE + MSA_LEGACY_SECURED + MSA_PASSWORD_REVEALED } // ─── Tenant ─────────────────────────────────────────────────────────────────── @@ -894,6 +908,8 @@ model Endpoint { /// 0.69: the signed agent's read-only RustDesk preflight (Managed Secure Access readiness). rustdeskPreflight RustdeskPreflight? msaGrants MsaGrant[] + /// 0.72: the Managed Secure Access mode, when not Legacy (no row = Legacy). + msaManaged MsaManagedComputer? /// 0.67: false-positive reports about this computer's alerts, and rules scoped to it. falsePositiveReports AlertFalsePositiveReport[] alertQualityRules AlertQualityRule[] @@ -4832,13 +4848,54 @@ model MsaGrant { notAfter DateTime maxMinutes Int idleMinutes Int - /// issued | delivered | expired | cancelled (0088 CHECK). Step 4 adds applied / failed / revoked. + /// issued | delivered | expired | cancelled (0088); applied | failed | ended (0089). state String @default("issued") envelopeEnc String passwordEnc String deliveredAt DateTime? createdAt DateTime @default(now()) + /// 0.72: the agent read every setting back and set the one-time password. + appliedAt DateTime? + /// 0.72: the agent saw a RustDesk connection (`rustdesk.exe --cm`) while it was applied. + connectedAt DateTime? + /// 0.72: the agent ended the session (random password nobody is told, stop-service Y then N). + endedAt DateTime? + /// 0.72: why it ended or failed — a closed code, never text from the computer. + outcome String? + /// 0.72: the keys whose readback disagreed (closed key names only). + failedKeys String[] @default([]) + /// 0.72: the one-time password was shown, once, to this Platform Admin. + revealedAt DateTime? + revealedById String? @@index([endpointId, state]) @@index([endpointId, createdAt]) } + +/// A computer's Managed Secure Access mode (0.72, build step 4 of +/// docs/managed-secure-access.md). No row is Legacy. A row is written only by +/// MsaManagedService: a Platform Admin's cutover of ONE computer (pending), +/// the agent's reports (enforcement_failure, the rolled-back delete), a +/// Platform Admin's confirmation (verified) and rollback (rollback_pending). +model MsaManagedComputer { + endpointId String @id + endpoint Endpoint @relation(fields: [endpointId], references: [id], onDelete: Cascade) + /// pending | verified | enforcement_failure | rollback_pending (0089 CHECK). + state String + requestedById String + requestedAt DateTime @default(now()) + verifiedAt DateTime? + verifiedById String? + /// The agent set a random permanent password nobody is told (after verification). + legacySecuredAt DateTime? + failedAt DateTime? + /// A closed code, never text from the computer. + failReason String? + failedKeys String[] @default([]) + rollbackRequestedAt DateTime? + rollbackRequestedById String? + /// The agent's last successful readback of every managed setting. + readbackOkAt DateTime? + lastReportAt DateTime? + updatedAt DateTime @updatedAt +} diff --git a/apps/api/scripts/e2e-msa-grants.mjs b/apps/api/scripts/e2e-msa-grants.mjs index 214dd6ec..a11d7b73 100644 --- a/apps/api/scripts/e2e-msa-grants.mjs +++ b/apps/api/scripts/e2e-msa-grants.mjs @@ -249,13 +249,15 @@ async function all() { const gB = r.data; check(await prisma.msaGrantKey.count({ where: { retiredAt: null } }) === 1, 'still one active key'); const ia = await prisma.activityLog.findFirst({ where: { action: 'MSA_GRANT_ISSUED', resourceId: A1.id }, orderBy: { createdAt: 'desc' } }); - check(!!ia && ia.actorId === admin.id && ia.customerId === bizA.id && J(Object.keys(ia.metadata).sort()) === J(['consent', 'endpointId', 'grantId', 'keyId', 'mode', 'source']) + check(!!ia && ia.actorId === admin.id && ia.customerId === bizA.id && J(Object.keys(ia.metadata).sort()) === J(['consent', 'endpointId', 'grantId', 'keyId', 'managed', 'mode', 'source']) && ia.metadata.grantId === g1.grantId && ia.metadata.keyId === g1.keyId, 'MSA_GRANT_ISSUED: filed under the business, ids, mode, consent and key id only', J(ia?.metadata)); r = await req('GET', '/msa/grants/keys', { s: SAdmin }); const pub = (r.data ?? []).find((k) => k.active); check(ok(r) && pub && pub.keyId === keyRow.keyId && G.keyIdOf(Buffer.from(pub.publicKey, 'base64')) === pub.keyId && !J(r.data).includes(keyRow.privateKeyEnc) - && J(Object.keys(pub).sort()) === J(['active', 'algorithm', 'createdAt', 'keyId', 'publicKey', 'retiredAt']), 'GET /msa/grants/keys: the public key, its id its SHA-256 prefix, nothing private', msg(r)); + && J(Object.keys(pub).sort()) === J(['active', 'algorithm', 'commands', 'createdAt', 'keyId', 'publicKey', 'published', 'retiredAt']) + && pub.published === false && pub.commands.length === 2 && pub.commands[0] === `sudo rem0te-signed-grant-key add --key-id ${pub.keyId} --public-key ${pub.publicKey}`, + 'GET /msa/grants/keys: the public key, its id its SHA-256 prefix, not published (no repository), the owner\'s two commands, nothing private', msg(r)); r = await req('GET', '/msa/grants/keys', { s: SA }); check(r.status === 403, 'and a Business Owner may not read it', msg(r)); const keys = new Map([[pub.keyId, Buffer.from(pub.publicKey, 'base64')]]); @@ -378,7 +380,8 @@ async function all() { } catch { return true; } }; check(await tryInsert({ notAfter: new Date(Date.now() + 6 * 60_000) }), 'a six-minute window is refused (CHECK)'); - check(await tryInsert({ state: 'applied' }), 'state "applied" (step 4) is refused (CHECK)'); + check(await tryInsert({ state: 'bogus' }), 'an unknown state is refused (CHECK)'); + check(await tryInsert({ state: 'applied', deliveredAt: new Date() }), 'state "applied" without appliedAt is refused (CHECK, 0.72)'); check(await tryInsert({ state: 'delivered' }), 'delivered without deliveredAt is refused (CHECK)'); check(await tryInsert({ envelopeEnc: '{"keyId":"x"}' }), 'an unsealed envelope is refused (CHECK)'); check(await tryInsert({ permissions: { ...view.permissions, keyboard: true } }), 'an unknown permission is refused (CHECK)'); diff --git a/apps/api/scripts/e2e-msa-managed.mjs b/apps/api/scripts/e2e-msa-managed.mjs new file mode 100644 index 00000000..541dd59b --- /dev/null +++ b/apps/api/scripts/e2e-msa-managed.mjs @@ -0,0 +1,507 @@ +#!/usr/bin/env node +/** + * End-to-end proof of Managed Secure Access build step 4 (0.72, + * check-security-invariants §82) through the real routes: cutover, the + * managed test session, confirmation, enforcement reports and rollback. + * + * - with MSA_GRANTS anything but exactly 'on', every new route is 404 + * MSA_NOT_ENABLED and the heartbeat never says msaPoll, even for a + * computer that has a managed row; + * - cutover is a Platform Admin's, with a fresh confirmation (msa.cutover), + * for ONE computer, and refused for: a Business Owner, a computer that is + * not Compatible, an agent older than 0.72, a pooled computer, a `remote` + * pause, a grant key not yet in the signed release metadata, a computer + * already managed; + * - the heartbeat says msaPoll only to a managed computer's authenticated + * signed agent; a staged legacy rotation waits while a grant is in flight + * and while the computer is verified or rolling back; + * - a test grant to a managed computer is refused above the view-only + * ceiling; the agent's reports (device secret first) move the grant and + * the computer; the one-time password is shown once, to a Platform Admin + * with a fresh confirmation (msa.reveal), only after it was applied; + * confirm needs a session that connected; verified refuses legacy + * Connect and Reveal; drift is an enforcement failure; + * - rollback is a Platform Admin's and never asks; the computer returns to + * Legacy when the agent reports restored (or by force, only once rolling + * back), and a rotation is then handed over; + * - no audit row carries a password, and the database refuses a pooled + * computer and the states the service never writes. + * + * cd apps/api && npx nest build + * DATABASE_URL=postgresql://…/ node scripts/e2e-msa-managed.mjs + * + * Self-starting: its API runs from dist/ on MSA_MANAGED_API_PORT (3961), with + * a stand-in signed update repository (unsigned metadata, as the portal reads + * it: the agents verify, the portal only reads) in a temp directory. + * INTEGRATION, not Windows: the agent's side is posted the way the signed + * agent's poller (internal/msa/enforce) posts it; its RustDesk side is + * proven by the Go tests and the Windows lab (TestLabRustdeskEnforce). + */ +import { PrismaClient } from '@prisma/client'; +import argon2 from 'argon2'; +import { spawn } from 'node:child_process'; +import { createHash, randomBytes } from 'node:crypto'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { confirmEverythingAsks } from './lib/confirm-asks.mjs'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const dist = path.join(here, '..', 'dist'); +const G = createRequire(import.meta.url)(path.join(dist, 'msa', 'grant.js')); +const DB = process.env.DATABASE_URL ?? ''; +const dbName = DB.split('/').pop()?.split('?')[0] ?? ''; +if (!/scratch|test/.test(dbName)) { console.error(`Refusing to run against database "${dbName}": name must contain "scratch" or "test".`); process.exit(2); } +const PORT = Number(process.env.MSA_MANAGED_API_PORT ?? 3961); +if ([3000, 3001, 3201, 3202, 4000, 4001, 443].includes(PORT)) { console.error(`Refusing port ${PORT}`); process.exit(2); } +const API = `http://127.0.0.1:${PORT}/api/v1`; +const prisma = new PrismaClient(); +const sfx = randomBytes(3).toString('hex'); +const PW = 'msa-managed-e2e-password-123'; +const VERSION_FILE = path.resolve(here, '..', '..', '..', 'version.json'); +const REPO = mkdtempSync(path.join(tmpdir(), 'rem0te-msa-managed-repo-')); + +let pass = 0, fail = 0; +const failures = []; +const check = (c, n, d = '') => { if (c) { pass++; console.log(` \x1b[32m✓\x1b[0m ${n}`); } else { fail++; failures.push(`${n} — ${d}`); console.log(` \x1b[31m✗\x1b[0m ${n}\n ${d}`); } }; +const section = (t) => console.log(`\n\x1b[1m${t}\x1b[0m`); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const ip = () => `10.${(Math.random() * 250) | 0}.${(Math.random() * 250) | 0}.${1 + ((Math.random() * 250) | 0)}`; +const sha = (b) => createHash('sha256').update(b).digest('hex'); +const J = (x) => JSON.stringify(x, (_k, v) => (typeof v === 'bigint' ? v.toString() : v)); + +// ── A stand-in published repository: what UpdateTrustService reads ────────── +function writeRepo(grantKeys) { + rmSync(REPO, { recursive: true, force: true }); + mkdirSync(path.join(REPO, 'metadata'), { recursive: true }); + const targets = {}; + if (grantKeys) { + const body = Buffer.from(JSON.stringify({ schema: 'rem0te-msa-grant-keys/1', keys: grantKeys })); + mkdirSync(path.join(REPO, 'targets', 'msa'), { recursive: true }); + writeFileSync(path.join(REPO, 'targets', 'msa', `${sha(body)}.grant-keys.json`), body); + targets['msa/grant-keys.json'] = { length: body.length, hashes: { sha256: sha(body) } }; + } + const m = (f, signed) => writeFileSync(path.join(REPO, 'metadata', f), JSON.stringify({ signed, signatures: [] })); + m('root.json', { _type: 'root', version: 1 }); + m('1.root.json', { _type: 'root', version: 1 }); + m('timestamp.json', { _type: 'timestamp', version: 1, meta: { 'snapshot.json': { version: 1 } } }); + m('1.snapshot.json', { _type: 'snapshot', version: 1, meta: { 'targets.json': { version: 1 } } }); + m('1.targets.json', { _type: 'targets', version: 1, targets }); +} +writeRepo(null); + +const baseEnv = { + ...process.env, NODE_ENV: 'test', PORT: String(PORT), DATABASE_URL: DB, + JWT_SECRET: randomBytes(32).toString('hex'), LAUNCHER_TOKEN_SECRET: randomBytes(32).toString('hex'), + ENCRYPTION_KEY: process.env.ENCRYPTION_KEY ?? randomBytes(32).toString('hex'), TRUSTED_PROXIES: 'loopback', HBBS_PRESENCE_HOST: '127.0.0.2', + VERSION_FILE, MONITOR_SWEEP: 'off', AUDIT_SEALER: 'off', CLIENT_UPDATE_SWEEP: 'off', SNAPSHOT_SWEEP: 'off', PATCH_POLICY_SWEEP: 'off', METRIC_SWEEP: 'off', + AUTO_MIGRATION_SWEEP: 'off', TRAY_SWEEP: 'off', RETENTION_SWEEP: 'off', CHAT_RETENTION_SWEEP: 'off', STALE_SWEEP: 'off', AGENT_AUTO_UPDATE: 'off', + MSA_POLL_HOLD_MS: '1500', UPDATE_REPO_DIR: REPO, + GEOIP_DB_PATH: path.join(here, 'no-such-geoip.mmdb'), +}; +delete baseEnv.PUBLIC_API_URL; +delete baseEnv.MSA_GRANTS; +let api; +async function startApi(extra) { + api = spawn(process.execPath, [path.join(dist, 'main.js')], { env: { ...baseEnv, ...extra }, stdio: ['ignore', 'pipe', 'pipe'] }); + api.log = ''; api.stdout.on('data', (d) => { api.log += d; }); api.stderr.on('data', (d) => { api.log += d; }); + for (let i = 0; i < 150; i++) { try { const r = await fetch(`${API}/health`); if (r.status < 500) return; } catch { /* not yet */ } await sleep(300); } + throw new Error(`api did not come up:\n${api.log.slice(-3000)}`); +} +async function stopApi() { if (!api || api.exitCode !== null || api.signalCode !== null) return; await new Promise((r) => { api.once('exit', r); api.kill('SIGTERM'); }); } + +async function req(method, p, { s, body } = {}) { + await sleep(20); + const h = { 'content-type': 'application/json', 'x-forwarded-for': ip() }; + if (s) h.cookie = s.cookie; + const r = await fetch(`${API}${p}`, { method, headers: h, body: body !== undefined ? JSON.stringify(body) : undefined }); + const text = await r.text(); let j; try { j = JSON.parse(text); } catch { j = text; } + return { status: r.status, body: j, data: j?.data, text }; +} +async function login(email) { + const r = await fetch(`${API}/auth/login`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-forwarded-for': ip() }, body: JSON.stringify({ email, password: PW }) }); + const m = (r.headers.get('set-cookie') ?? '').match(/access_token=([^;]+)/); + if (r.status !== 200 || !m) throw new Error(`login ${email}: ${r.status} ${await r.text()}`); + return { cookie: `access_token=${m[1]}` }; +} +async function stepUp(s) { + const r = await fetch(`${API}/auth/step-up`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-forwarded-for': ip(), cookie: s.cookie }, body: JSON.stringify({ password: PW }) }); + const m = (r.headers.get('set-cookie') ?? '').match(/step_up=([^;]+)/); + if (r.status !== 200 || !m) throw new Error(`step-up: ${r.status} ${await r.text()}`); + return { cookie: `${s.cookie}; step_up=${m[1]}` }; +} +const msg = (r) => `HTTP ${r.status} ${(typeof r.body === 'string' ? r.body : J(r.body)).slice(0, 500)}`; +const code = (r) => r.body?.code ?? r.body?.message?.code ?? r.body?.error?.code; +const ok = (r) => r.status === 200 || r.status === 201; +const notEnabled = (r) => r.status === 404 && code(r) === 'MSA_NOT_ENABLED'; + +const KEYS = ['access-mode', 'enable-keyboard', 'enable-clipboard', 'enable-file-transfer', 'enable-audio', 'enable-tunnel', 'enable-remote-restart', + 'approve-mode', 'verification-method', 'allow-auto-disconnect', 'auto-disconnect-timeout']; +const at = (msAgo) => new Date(Date.now() - msAgo).toISOString().replace(/\.\d{3}Z$/, 'Z'); +const preflight = () => ({ + schema: 'rem0te-rustdesk-preflight/1', checkedAt: at(30_000), installed: true, expectedPath: true, version: '1.4.7+65', build: 'flutter', + service: 'running', cli: 'ok', keys: Object.fromEntries(KEYS.map((k) => [k, 'ok'])), durationMs: 1400, +}); +const live = { loggedOnUser: 'PC\\user', uptimeSeconds: 7200, cpuLoadPercent: 4, memoryTotalMb: 16000, memoryFreeMb: 9000, rustdeskSessions: 0 }; +const signedBeat = (ep, extra = {}) => req('POST', '/enrollment/heartbeat', { body: { + rustdeskId: ep.rid, agentSecret: ep.secret, hostname: ep.hostname, platform: 'Windows', agentVersion: ep.agentVersion ?? '0.72.0', rustdeskVersion: '1.4.7', + updateChannel: 'signed', trustRootVersion: 1, targetsVersion: 7, agentSha256: 'c'.repeat(64), agentActions: ['windows.spooler.start@1'], ...live, ...extra } }); +const standardBeat = (ep, extra = {}) => req('POST', '/enrollment/heartbeat', { body: { + rustdeskId: ep.rid, agentSecret: ep.secret, hostname: ep.hostname, platform: 'Windows', agentVersion: '0.68.3', rustdeskVersion: '1.4.7', + updateChannel: 'legacy', ...live, ...extra } }); +const poll = (ep, extra = {}) => req('POST', '/msa/agent/poll', { body: { rustdeskId: ep.rid, agentSecret: ep.secret, wait: false, ...extra } }); +const report = (ep, body) => req('POST', '/msa/agent/report', { body: { rustdeskId: ep.rid, agentSecret: ep.secret, ...body } }); +const managedRow = (ep) => prisma.msaManagedComputer.findUnique({ where: { endpointId: ep.id } }); + +const created = { businesses: [], users: [], pauses: [], endpoints: [] }; + +async function all() { + const tenant = await prisma.tenant.findFirst({ orderBy: { createdAt: 'asc' } }); + if (!tenant) throw new Error('seed the scratch database first (prisma db seed)'); + const roleOwner = await prisma.role.findFirst({ where: { type: 'BUSINESS_OWNER' } }); + await confirmEverythingAsks(prisma); + + section('Fixtures (synthetic): business A, a Platform Admin, its owner; signed (0.72 and 0.71), standard and pooled computers'); + const bizA = await prisma.customer.create({ data: { tenantId: tenant.id, name: `MSA-M A ${sfx}` } }); + created.businesses.push(bizA.id); + const hash = await argon2.hash(PW, { type: argon2.argon2id }); + const mkUser = async (tag, biz, role, admin = false) => { + const u = await prisma.user.create({ data: { email: `msam-${tag}-${sfx}@test.invalid`, passwordHash: hash, firstName: 'Msam', lastName: tag, status: 'ACTIVE', isPlatformAdmin: admin } }); + created.users.push(u.id); + if (biz) await prisma.membership.create({ data: { userId: u.id, tenantId: tenant.id, customerId: biz.id, roleId: role.id, capabilities: [] } }); + return u; + }; + const admin = await mkUser('admin', null, null, true); + const owner = await mkUser('owner', bizA, roleOwner); + const mkEp = async (hostname, { channel = 'signed', pooled = false, agentVersion = '0.72.0' } = {}) => { + const e = await prisma.endpoint.create({ data: { + tenantId: pooled ? null : tenant.id, customerId: pooled ? null : bizA.id, name: hostname, hostname, platform: 'Windows', status: pooled ? 'PENDING_ENROLLMENT' : 'ACTIVE', + isOnline: true, isManaged: true, accessMode: 'COMPANY_WIDE', lastSeenAt: new Date(), agentVersion, updateChannel: channel, + signedSeenAt: channel === 'signed' ? new Date() : null, deviceClass: 'WORKSTATION' } }); + const rid = String(100000000 + ((Math.random() * 899999999) | 0)); + const secret = randomBytes(24).toString('hex'); + await prisma.rustdeskNode.create({ data: { tenantId: pooled ? null : tenant.id, endpointId: e.id, rustdeskId: rid, version: '1.4.7', agentSecretHash: sha(secret) } }); + created.endpoints.push(e.id); + return { id: e.id, rid, secret, hostname, agentVersion }; + }; + const A1 = await mkEp(`MSAM-A1-${sfx}`); + const A2 = await mkEp(`MSAM-A2-OLD-${sfx}`, { agentVersion: '0.71.0' }); + const A3 = await mkEp(`MSAM-A3-STD-${sfx}`, { channel: 'legacy', agentVersion: '0.68.3' }); + const A4 = await mkEp(`MSAM-A4-${sfx}`); + const P1 = await mkEp(`MSAM-POOL-${sfx}`, { pooled: true }); + + // ── Off ─────────────────────────────────────────────────────────────────── + section('MSA_GRANTS unset: every new route is 404 MSA_NOT_ENABLED; the heartbeat never says msaPoll, even for a managed row'); + await startApi({}); + { + const SAd = await stepUp(await login(admin.email)); + for (const [m, p, b] of [ + ['GET', `/msa/managed/${A1.id}`], ['POST', `/msa/managed/${A1.id}/cutover`], ['POST', `/msa/managed/${A1.id}/confirm`], + ['POST', `/msa/managed/${A1.id}/rollback`, {}], ['POST', `/msa/managed/grants/${'a'.repeat(32)}/reveal`], ['POST', '/msa/grants/keys'], + ]) { + const r = await req(m, p, { s: SAd, body: b }); + check(notEnabled(r), `${m} ${p.replace(A1.id, ':id')} as a confirmed Platform Admin: 404 MSA_NOT_ENABLED`, msg(r)); + } + let r = await report(A1, { event: 'secured' }); + check(notEnabled(r), 'POST /msa/agent/report with the right secret: 404', msg(r)); + r = await req('POST', '/msa/agent/report', { body: { junk: 1 } }); + check(notEnabled(r), 'and with a malformed body: 404, not 400', msg(r)); + await prisma.msaManagedComputer.create({ data: { endpointId: A4.id, state: 'pending', requestedById: admin.id } }); + r = await signedBeat(A4, { rustdeskPreflight: preflight() }); + check(ok(r) && r.data.authenticated === true && r.data.msaPoll === undefined, 'a managed computer\'s signed heartbeat with the switch off: no msaPoll', msg(r)); + r = await req('GET', `/msa/readiness/${A1.id}`, { s: SAd }); + check(ok(r) && r.data.managedControls === false, 'readiness says managedControls: false, so the console never asks a gated route', msg(r)); + r = await req('GET', '/msa/readiness', { s: SAd }); + const st = (r.data?.states ?? []).map((x) => x.state); + check(ok(r) && r.data.managedControls === false && J(st.slice(0, 4)) === J(['unsupported', 'upgrade_available', 'compatible', 'unknown']) + && st.slice(4).every((x) => r.data.counts[x] > 0) && /not available yet/.test(r.data.note), + 'the fleet with the switch off: the four readiness tiles, a managed tile only for a state some computer is really in, the readiness note', J({ st, counts: r.data?.counts })); + await prisma.msaManagedComputer.delete({ where: { endpointId: A4.id } }); + check(await prisma.msaManagedComputer.count({ where: { endpointId: { in: created.endpoints } } }) === 0, 'no managed row was written by any route'); + } + await stopApi(); + + // ── On ──────────────────────────────────────────────────────────────────── + await startApi({ MSA_GRANTS: 'on' }); + const SAdmin = await login(admin.email); + const SAd = await stepUp(SAdmin); + const SO = await login(owner.email); + await prisma.msaGrantKey.updateMany({ where: { retiredAt: null }, data: { retiredAt: new Date() } }); + + section('Cutover: who, and the gates'); + let r = await req('POST', `/msa/managed/${A1.id}/cutover`, { s: SO }); + check(r.status === 403, 'a Business Owner: 403', msg(r)); + r = await req('POST', `/msa/managed/${A1.id}/cutover`, { s: SAdmin }); + check(r.status === 403 && code(r) === 'STEP_UP_REQUIRED' && r.body?.action === 'msa.cutover', 'a Platform Admin without a fresh confirmation: STEP_UP_REQUIRED naming msa.cutover', msg(r)); + r = await req('POST', `/msa/managed/${A1.id}/cutover`, { s: SAd }); + check(r.status === 409 && code(r) === 'MSA_NOT_COMPATIBLE', 'no preflight yet: 409 MSA_NOT_COMPATIBLE', msg(r)); + r = await req('GET', `/msa/managed/${A1.id}`, { s: SAdmin }); + check(ok(r) && r.data.state === 'legacy' && r.data.cutover.allowed === false && r.data.cutover.blockers.some((b) => b.code === 'MSA_GRANT_KEY_NOT_PUBLISHED'), + 'the view says Legacy, and why cutover is not allowed (including the unpublished key)', msg(r)); + for (const ep of [A1, A2]) { + r = await signedBeat(ep, { rustdeskPreflight: preflight() }); + check(ok(r) && r.data.rustdeskPreflightAck && r.data.msaPoll === undefined, `${ep === A1 ? 'A1' : 'A2'}: a signed heartbeat with a preflight; not managed, so no msaPoll`, msg(r)); + } + r = await req('GET', `/msa/readiness/${A1.id}`, { s: SO }); + check(ok(r) && r.data.readiness.state === 'compatible' && r.data.managedControls === true, 'A1 is Compatible now, and readiness says managedControls: true', msg(r)); + r = await req('GET', '/msa/readiness', { s: SO }); + check(ok(r) && r.data.managedControls === true && r.data.states.length === 7 && /switched on for testing/.test(r.data.note), 'the fleet with the switch on: all seven tiles and the testing note', J({ states: r.data?.states?.length, note: r.data?.note })); + r = await req('POST', `/msa/managed/${A1.id}/cutover`, { s: SAd }); + check(r.status === 409 && code(r) === 'MSA_GRANT_KEY_NOT_PUBLISHED', 'Compatible, but no grant key in the signed metadata: 409 MSA_GRANT_KEY_NOT_PUBLISHED', msg(r)); + + r = await req('POST', '/msa/grants/keys', { s: SAdmin }); + check(r.status === 403 && code(r) === 'STEP_UP_REQUIRED', 'making the grant key without a fresh confirmation: refused', msg(r)); + r = await req('POST', '/msa/grants/keys', { s: SAd }); + const key = r.data; + check(ok(r) && G.KEY_ID_RE.test(key?.keyId ?? '') && key.published === false && key.commands.length === 2 + && key.commands[0] === `sudo rem0te-signed-grant-key add --key-id ${key.keyId} --public-key ${key.publicKey}` && key.commands[1] === 'sudo rem0te-signed-publish --republish', + 'POST /msa/grants/keys: the key exists, not published, with the owner\'s two commands', msg(r)); + writeRepo([{ keyId: key.keyId, publicKey: key.publicKey }]); + r = await req('GET', '/msa/grants/keys', { s: SAdmin }); + check(ok(r) && r.data.find((k) => k.keyId === key.keyId)?.published === true && r.data.find((k) => k.keyId === key.keyId)?.commands.length === 0, + 'once msa/grant-keys.json is published with it: published, no commands', msg(r)); + + r = await req('POST', `/msa/managed/${A2.id}/cutover`, { s: SAd }); + check(r.status === 409 && code(r) === 'MSA_AGENT_TOO_OLD', 'A2 (agent 0.71.0, Compatible): 409 MSA_AGENT_TOO_OLD', msg(r)); + r = await req('POST', `/msa/managed/${A3.id}/cutover`, { s: SAd }); + check(r.status === 409 && code(r) === 'MSA_SIGNED_AGENT_REQUIRED', 'A3 (standard agent): 409 MSA_SIGNED_AGENT_REQUIRED', msg(r)); + r = await req('POST', `/msa/managed/${P1.id}/cutover`, { s: SAd }); + check(r.status === 403 || r.status === 404, `a pooled computer: refused (HTTP ${r.status})`, msg(r)); + const pause = await prisma.containmentPause.create({ data: { scope: 'BUSINESS', customerId: bizA.id, kinds: ['remote'], reason: 'e2e msa managed', setById: admin.id, setBy: 'msp' } }); + created.pauses.push(pause.id); + r = await req('POST', `/msa/managed/${A1.id}/cutover`, { s: SAd }); + check(r.status === 403 && code(r) === 'CONTAINED', 'a `remote` pause on the business: 403 CONTAINED', msg(r)); + await prisma.containmentPause.update({ where: { id: pause.id }, data: { clearedAt: new Date(), clearedById: admin.id, clearReason: 'e2e' } }); + check(await prisma.msaManagedComputer.count({ where: { endpointId: { in: created.endpoints } } }) === 0, 'every refusal wrote nothing'); + + r = await req('POST', `/msa/managed/${A1.id}/cutover`, { s: SAd }); + check(ok(r) && r.data.state === 'pending', 'A1: moved to Managed (pending)', msg(r)); + const cut = await prisma.activityLog.findFirst({ where: { action: 'MSA_CUTOVER', resourceId: A1.id }, orderBy: { createdAt: 'desc' } }); + check(!!cut && cut.actorId === admin.id && cut.customerId === bizA.id && cut.metadata.endpointId === A1.id && cut.metadata.before === 'legacy' && cut.metadata.after === 'pending' && Object.keys(cut.metadata).length === 3, 'MSA_CUTOVER audited: who, before and after', J(cut?.metadata)); + r = await req('POST', `/msa/managed/${A1.id}/cutover`, { s: SAd }); + check(r.status === 409 && code(r) === 'MSA_ALREADY_MANAGED', 'a second cutover: 409 MSA_ALREADY_MANAGED', msg(r)); + r = await req('GET', `/msa/readiness/${A1.id}`, { s: SO }); + check(ok(r) && r.data.readiness.state === 'managed' && r.data.readiness.label === 'Managed (pending)' && r.data.readiness.verified === false && /only in the Windows lab/.test(r.data.note), + 'readiness: Managed (pending), not verified, the lab-only note', msg(r)); + + section('The heartbeat: msaPoll only for the managed computer'); + r = await signedBeat(A1); + check(ok(r) && r.data.msaPoll === true, 'A1\'s signed heartbeat: msaPoll true', msg(r)); + r = await signedBeat(A4); + check(ok(r) && r.data.msaPoll === undefined, 'A4 (signed, not managed): no msaPoll', msg(r)); + r = await standardBeat(A3); + check(ok(r) && r.data.msaPoll === undefined, 'A3 (standard): no msaPoll', msg(r)); + r = await req('POST', '/enrollment/heartbeat', { body: { rustdeskId: A1.rid, agentSecret: 'f'.repeat(48), hostname: A1.hostname, platform: 'Windows', updateChannel: 'signed', agentVersion: '0.72.0', ...live } }); + check(r.data?.msaPoll === undefined, `A1 with a wrong secret (HTTP ${r.status}): no msaPoll`, msg(r)); + + section('The managed test session'); + r = await req('POST', `/msa/grants/test/${A1.id}`, { s: SAd, body: { mode: 'control' } }); + check(r.status === 409 && code(r) === 'MSA_ABOVE_CEILING', 'a control grant to a managed computer: 409 MSA_ABOVE_CEILING', msg(r)); + r = await req('POST', `/msa/grants/test/${A1.id}`, { s: SAd, body: { permissions: { files: true } } }); + check(r.status === 409 && code(r) === 'MSA_ABOVE_CEILING', 'view with files: 409 MSA_ABOVE_CEILING', msg(r)); + r = await req('POST', `/msa/grants/test/${A1.id}`, { s: SAd, body: { mode: 'view', consent: 'required', maxMinutes: 30, idleMinutes: 10 } }); + const g1 = r.data; + check(ok(r) && g1.state === 'issued', 'a view-only test grant: issued', msg(r)); + r = await req('POST', `/endpoints/${A1.id}/rotate-credential`, { s: SAdmin }); + check(ok(r), 'a legacy rotation can still be staged while pending', msg(r)); + r = await signedBeat(A1); + check(ok(r) && !r.data.rotate, 'but the heartbeat holds it while a grant is in flight', msg(r)); + + r = await poll(A1); + const env = r.data?.grants?.[0]; + check(ok(r) && r.data.grants.length === 1 && r.data.endpointId === A1.id && J(r.data.managed) === J({ state: 'pending', rollback: false }), 'the poll: the grant, the endpoint id, managed pending', msg(r)); + const keys = new Map([[key.keyId, Buffer.from(key.publicKey, 'base64')]]); + const v = G.verifyEnvelope(env, { keys, endpointId: A1.id, rustdeskId: A1.rid, now: Date.now(), seen: new Set(), remotePaused: false, + ceiling: { mode: 'view', permissions: { clipboard: false, files: false, audio: false, tunnel: false, restart: false } } }); + check(v.ok && v.grant.grantId === g1.grantId, 'it verifies under the published key and the view-only ceiling', J(v)); + const otp = v.grant?.password; + await poll(A1, { ack: [g1.grantId] }); + + r = await req('POST', `/msa/managed/grants/${g1.grantId}/reveal`, { s: SAd }); + check(r.status === 409 && code(r) === 'MSA_GRANT_NOT_APPLIED', 'reveal before the agent applied it: 409 MSA_GRANT_NOT_APPLIED', msg(r)); + r = await req('POST', `/msa/managed/${A1.id}/confirm`, { s: SAd }); + check(r.status === 409 && code(r) === 'MSA_NO_TEST_SESSION', 'confirm before a test session: 409 MSA_NO_TEST_SESSION', msg(r)); + + r = await req('POST', '/msa/agent/report', { body: { rustdeskId: A1.rid, agentSecret: 'f'.repeat(48), event: 'applied', grantId: g1.grantId } }); + check(r.status === 401, 'a report with a wrong secret: 401', msg(r)); + r = await report(A1, { event: 'applied', grantId: g1.grantId, password: otp }); + check(r.status === 400 && code(r) === 'MSA_REPORT_INVALID', 'a report carrying a password field: 400, nothing recorded', msg(r)); + r = await report(A3, { event: 'secured' }); + check(r.status === 403 && code(r) === 'MSA_SIGNED_AGENT_REQUIRED', 'a standard agent\'s report: 403', msg(r)); + r = await report(A4, { event: 'applied', grantId: g1.grantId }); + check(ok(r) && r.data.recorded === false && (await prisma.msaGrant.findUnique({ where: { id: g1.grantId } })).state === 'delivered', 'another computer reporting A1\'s grant: recorded nothing', msg(r)); + r = await report(A1, { event: 'applied', grantId: g1.grantId }); + let g = await prisma.msaGrant.findUnique({ where: { id: g1.grantId } }); + let row = await managedRow(A1); + check(ok(r) && r.data.recorded === true && g.state === 'applied' && g.appliedAt && row.readbackOkAt, 'applied: the grant is applied, the computer\'s readback recorded', msg(r)); + r = await report(A1, { event: 'applied', grantId: g1.grantId }); + check(ok(r) && r.data.recorded === false, 'a repeated report changes nothing', msg(r)); + + r = await req('POST', `/msa/managed/grants/${g1.grantId}/reveal`, { s: SO }); + check(r.status === 403, 'reveal as a Business Owner: 403', msg(r)); + r = await req('POST', `/msa/managed/grants/${g1.grantId}/reveal`, { s: SAdmin }); + check(r.status === 403 && code(r) === 'STEP_UP_REQUIRED' && r.body?.action === 'msa.reveal', 'reveal without a fresh confirmation: STEP_UP_REQUIRED naming msa.reveal', msg(r)); + r = await req('POST', `/msa/managed/grants/${g1.grantId}/reveal`, { s: SAd }); + check(ok(r) && r.data.oneTimePassword === otp && r.data.shownOnce === true, 'reveal: the grant\'s one-time password, once', msg(r)); + r = await req('POST', `/msa/managed/grants/${g1.grantId}/reveal`, { s: SAd }); + check(r.status === 409 && code(r) === 'MSA_PASSWORD_ALREADY_REVEALED', 'a second reveal: 409 MSA_PASSWORD_ALREADY_REVEALED', msg(r)); + const rv = await prisma.activityLog.findFirst({ where: { action: 'MSA_PASSWORD_REVEALED', resourceId: A1.id } }); + check(!!rv && rv.metadata.grantId === g1.grantId && rv.metadata.endpointId === A1.id && Object.keys(rv.metadata).length === 2, 'MSA_PASSWORD_REVEALED audited with ids only', J(rv?.metadata)); + + r = await report(A1, { event: 'connected', grantId: g1.grantId }); + check(ok(r) && r.data.recorded === true, 'connected: a RustDesk connection manager appeared', msg(r)); + r = await req('GET', `/msa/managed/${A1.id}`, { s: SAdmin }); + check(ok(r) && r.data.canConfirm === true && r.data.grants[0].connectedAt && !J(r.data).includes(otp), 'the view: can confirm, the grant connected, no password', msg(r)); + r = await report(A1, { event: 'ended', grantId: g1.grantId, outcome: 'disconnected' }); + g = await prisma.msaGrant.findUnique({ where: { id: g1.grantId } }); + check(ok(r) && g.state === 'ended' && g.outcome === 'disconnected' && g.endedAt, 'ended: disconnected', msg(r)); + const staged = await prisma.activityLog.findFirst({ where: { action: 'ENDPOINT_CREDENTIAL_ROTATION_STAGED', resourceId: A1.id, metadata: { path: ['source'], equals: 'msa_session_ended' } } }); + check(!!staged, 'a pending computer\'s ended session stages a legacy rotation (Legacy keeps working)'); + r = await signedBeat(A1); + check(ok(r) && r.data.rotate?.password && r.data.msaPoll === true, 'and the heartbeat hands it over now that no grant is in flight', msg(r)); + const legacyPw = r.data?.rotate?.password; + r = await req('POST', `/endpoints/${A1.id}/connect`, { s: SAd }); + check(r.status !== 403 || code(r) !== 'MSA_MANAGED', `pending: legacy Connect is not refused for Managed Secure Access (HTTP ${r.status})`, msg(r)); + + section('Confirm: managed and verified'); + r = await req('POST', `/msa/managed/${A1.id}/confirm`, { s: SO }); + check(r.status === 403, 'a Business Owner: 403', msg(r)); + r = await req('POST', `/msa/managed/${A1.id}/confirm`, { s: SAdmin }); + check(r.status === 403 && code(r) === 'STEP_UP_REQUIRED' && r.body?.action === 'msa.cutover', 'without a fresh confirmation: STEP_UP_REQUIRED naming msa.cutover', msg(r)); + r = await req('POST', `/msa/managed/${A1.id}/confirm`, { s: SAd }); + row = await managedRow(A1); + check(ok(r) && row.state === 'verified' && row.verifiedById === admin.id, 'confirmed: verified', msg(r)); + check(!!(await prisma.activityLog.findFirst({ where: { action: 'MSA_VERIFIED', resourceId: A1.id } })), 'MSA_VERIFIED audited'); + r = await poll(A1); + check(ok(r) && J(r.data.managed) === J({ state: 'verified', rollback: false }), 'the poll tells the agent: verified', msg(r)); + r = await report(A1, { event: 'secured' }); + row = await managedRow(A1); + check(ok(r) && r.data.recorded === true && row.legacySecuredAt, 'secured: the legacy password replaced by one nobody is told', msg(r)); + r = await req('GET', `/msa/readiness/${A1.id}`, { s: SO }); + check(ok(r) && r.data.readiness.state === 'managed_verified' && r.data.readiness.verified === true, 'readiness: Managed and verified, verified true', msg(r)); + r = await req('GET', `/endpoints/${A1.id}/password`, { s: SAd }); + check(r.status === 409 && code(r) === 'MSA_MANAGED', 'verified: Reveal password is refused (409 MSA_MANAGED)', msg(r)); + r = await req('POST', `/endpoints/${A1.id}/connect`, { s: SAd }); + check(r.status === 403 && code(r) === 'MSA_MANAGED', 'verified: legacy Connect is refused (MSA_MANAGED)', msg(r)); + r = await req('POST', `/endpoints/${A1.id}/rotate-credential`, { s: SAdmin }); + check(r.status === 409 && code(r) === 'MSA_MANAGED', 'verified: rotating the legacy password is refused', msg(r)); + r = await signedBeat(A1); + check(ok(r) && !r.data.rotate && r.data.msaPoll === true, 'the heartbeat hands over no rotation to a verified computer', msg(r)); + + section('Enforcement failure'); + r = await report(A1, { event: 'checked' }); + check(ok(r) && r.data.recorded === true, 'checked: the hourly readback agreed', msg(r)); + r = await report(A1, { event: 'drift', keys: ['access-mode'] }); + row = await managedRow(A1); + check(ok(r) && row.state === 'enforcement_failure' && row.failReason === 'drift' && J(row.failedKeys) === J(['access-mode']), 'drift: enforcement failure, with the key', msg(r)); + r = await req('GET', `/msa/readiness/${A1.id}`, { s: SO }); + check(ok(r) && r.data.readiness.state === 'enforcement_failure' && /drift \(access-mode\)/.test(r.data.readiness.reasons[0]), 'readiness: Enforcement failure, naming the key', msg(r)); + r = await req('POST', `/endpoints/${A1.id}/connect`, { s: SAd }); + check(r.status === 403 && code(r) === 'MSA_MANAGED', 'an enforcement failure on a verified computer still refuses legacy Connect (nothing weaker)', msg(r)); + r = await req('POST', `/msa/grants/test/${A1.id}`, { s: SAd, body: {} }); + const g2 = r.data; + await poll(A1, { ack: [g2?.grantId] }); + r = await report(A1, { event: 'failed', grantId: g2?.grantId, outcome: 'readback_mismatch', keys: ['approve-mode'] }); + g = await prisma.msaGrant.findUnique({ where: { id: g2.grantId } }); + row = await managedRow(A1); + check(ok(r) && g.state === 'failed' && g.outcome === 'readback_mismatch' && J(g.failedKeys) === J(['approve-mode']) && row.failReason === 'readback_mismatch', + 'a test grant whose readback disagreed: failed, keys recorded, still an enforcement failure', msg(r)); + r = await req('POST', `/msa/grants/test/${A1.id}`, { s: SAd, body: {} }); + const g3 = r.data; + await poll(A1, { ack: [g3?.grantId] }); + r = await report(A1, { event: 'applied', grantId: g3?.grantId }); + row = await managedRow(A1); + check(ok(r) && row.state === 'verified' && row.failReason === null, 'a later grant that applies and reads back: verified again', msg(r)); + await report(A1, { event: 'ended', grantId: g3?.grantId, outcome: 'no_connection' }); + + section('Rollback'); + r = await req('POST', `/msa/managed/${A1.id}/rollback`, { s: SO, body: {} }); + check(r.status === 403, 'a Business Owner: 403', msg(r)); + r = await req('POST', `/msa/grants/test/${A1.id}`, { s: SAd, body: {} }); + const g4 = r.data; + r = await req('POST', `/msa/managed/${A1.id}/rollback`, { s: SAdmin, body: {} }); + row = await managedRow(A1); + check(ok(r) && row.state === 'rollback_pending' && row.rollbackRequestedById === admin.id, 'a Platform Admin with NO fresh confirmation: rolling back', msg(r)); + check((await prisma.msaGrant.findUnique({ where: { id: g4.grantId } })).state === 'cancelled', 'an undelivered grant is cancelled'); + check(!!(await prisma.activityLog.findFirst({ where: { action: 'MSA_ROLLBACK_REQUESTED', resourceId: A1.id } })), 'MSA_ROLLBACK_REQUESTED audited'); + r = await poll(A1); + check(ok(r) && r.data.grants.length === 0 && J(r.data.managed) === J({ state: 'rollback_pending', rollback: true }), 'the poll: no grants, rollback true', msg(r)); + r = await req('POST', `/msa/grants/test/${A1.id}`, { s: SAd, body: {} }); + check(r.status === 409 && code(r) === 'MSA_ROLLBACK_PENDING', 'a test grant while rolling back: 409 MSA_ROLLBACK_PENDING', msg(r)); + r = await signedBeat(A1); + check(ok(r) && !r.data.rotate, 'the staged rotation waits until the agent has restored RustDesk', msg(r)); + r = await req('POST', `/msa/managed/${A1.id}/rollback`, { s: SAdmin, body: {} }); + check(r.status === 409 && code(r) === 'MSA_ROLLBACK_PENDING', 'rollback again without force: 409', msg(r)); + r = await report(A1, { event: 'restore_failed', keys: ['access-mode'] }); + row = await managedRow(A1); + check(ok(r) && row.state === 'rollback_pending' && row.failReason === 'restore_failed', 'restore_failed: still rolling back, recorded', msg(r)); + r = await report(A1, { event: 'restored' }); + check(ok(r) && r.data.recorded === true && !(await managedRow(A1)), 'restored: back to Legacy (no row)', msg(r)); + check(!!(await prisma.activityLog.findFirst({ where: { action: 'MSA_ROLLED_BACK', resourceId: A1.id, metadata: { path: ['forced'], equals: false } } })), 'MSA_ROLLED_BACK audited'); + r = await signedBeat(A1); + check(ok(r) && r.data.rotate?.password && r.data.rotate.password !== legacyPw && r.data.msaPoll === undefined, 'the heartbeat: a fresh legacy password, and no msaPoll', msg(r)); + r = await poll(A1); + check(ok(r) && r.data.managed === null, 'the poll: managed null (the poller exits)', msg(r)); + r = await req('GET', `/msa/readiness/${A1.id}`, { s: SO }); + check(ok(r) && r.data.readiness.state === 'compatible', 'readiness: Compatible again', msg(r)); + + section('Forced rollback, only once rolling back'); + r = await req('POST', `/msa/managed/${A1.id}/cutover`, { s: SAd }); + check(ok(r) && r.data.state === 'pending', 'cut over again', msg(r)); + r = await req('POST', `/msa/managed/${A1.id}/rollback`, { s: SAdmin, body: { force: true } }); + check(ok(r) && (await managedRow(A1))?.state === 'rollback_pending', 'force on a pending computer only starts a rollback', msg(r)); + r = await req('POST', `/msa/managed/${A1.id}/rollback`, { s: SAdmin, body: { force: true } }); + check(ok(r) && !(await managedRow(A1)), 'force while rolling back: Legacy without the agent', msg(r)); + check(!!(await prisma.activityLog.findFirst({ where: { action: 'MSA_ROLLED_BACK', resourceId: A1.id, metadata: { path: ['forced'], equals: true } } })), 'audited as forced'); + + section('No password anywhere it should not be'); + const rows = await prisma.activityLog.findMany({ where: { resourceId: { in: created.endpoints } } }); + const text = J(rows); + check(!text.includes(otp) && (!legacyPw || !text.includes(legacyPw)), `${rows.length} audit rows: neither the one-time nor the legacy password`); + const allGrants = J(await prisma.msaGrant.findMany({ where: { endpointId: { in: created.endpoints } } })); + check(!allGrants.includes(otp), 'the grant rows hold the password only sealed'); + + section('The database holds the rules too'); + const tryIns = async (data) => { try { await prisma.msaManagedComputer.create({ data: { requestedById: admin.id, ...data } }); await prisma.msaManagedComputer.delete({ where: { endpointId: data.endpointId } }); return false; } catch { return true; } }; + check(await tryIns({ endpointId: P1.id, state: 'pending' }), 'a pooled computer is refused (trigger)'); + check(await tryIns({ endpointId: A4.id, state: 'managed' }), 'an unknown state is refused (CHECK)'); + check(await tryIns({ endpointId: A4.id, state: 'verified' }), 'verified without verifiedAt is refused (CHECK)'); + check(await tryIns({ endpointId: A4.id, state: 'rollback_pending' }), 'rolling back without who asked is refused (CHECK)'); + check(await tryIns({ endpointId: A4.id, state: 'enforcement_failure', failedAt: new Date(), failReason: 'Free text!' }), 'a free-text failure reason is refused (CHECK)'); + check(await tryIns({ endpointId: A4.id, state: 'pending', failedKeys: ['custom-rendezvous-server'] }), 'an unknown key is refused (CHECK)'); + + section('Switch off with a verified row: nothing new happens, and nothing weaker either'); + await prisma.msaManagedComputer.create({ data: { endpointId: A4.id, state: 'verified', requestedById: admin.id, verifiedAt: new Date(), verifiedById: admin.id } }); + await stopApi(); + await startApi({}); + { + const S = await stepUp(await login(admin.email)); + r = await signedBeat(A4); + check(ok(r) && r.data.msaPoll === undefined, 'no msaPoll with the switch off', msg(r)); + r = await poll(A4); + check(notEnabled(r), 'the poll: 404 (the agent ends any session and exits)', msg(r)); + r = await req('GET', `/endpoints/${A4.id}/password`, { s: S }); + check(r.status === 409 && code(r) === 'MSA_MANAGED', 'Reveal still refused: its password is one nobody is told (turn the switch on and roll back)', msg(r)); + } +} + +try { + await all(); +} catch (err) { + fail++; failures.push(String(err?.stack ?? err)); + console.error(err); + if (api?.log) console.error(api.log.slice(-2000)); +} finally { + await stopApi(); + const ids = created.endpoints; + await prisma.msaManagedComputer.deleteMany({ where: { endpointId: { in: ids } } }).catch(() => {}); + await prisma.msaGrant.deleteMany({ where: { endpointId: { in: ids } } }).catch(() => {}); + await prisma.containmentPause.deleteMany({ where: { id: { in: created.pauses } } }).catch(() => {}); + await prisma.endpoint.updateMany({ where: { id: { in: ids } }, data: { status: 'ARCHIVED', isOnline: false, lastSeenAt: new Date(Date.now() - 24 * 3600_000) } }).catch(() => {}); + rmSync(REPO, { recursive: true, force: true }); + await prisma.$disconnect(); +} +console.log(`\nmsa managed: ${pass} passed, ${fail} failed`); +if (fail) { for (const f of failures) console.error(` ✗ ${f}`); process.exit(1); } diff --git a/apps/api/scripts/e2e-msa-readiness.mjs b/apps/api/scripts/e2e-msa-readiness.mjs index 2628e20c..1a2b2f33 100644 --- a/apps/api/scripts/e2e-msa-readiness.mjs +++ b/apps/api/scripts/e2e-msa-readiness.mjs @@ -238,13 +238,17 @@ async function all() { check(ok(r) && [A1, A2, A3, A4].every((e) => ids.includes(e.id)) && !ids.includes(B1.id) && !ids.includes(P1.id), 'owner A: A1–A4, not B1, not the pooled computer', msg(r)); const sum = Object.values(r.data?.counts ?? {}).reduce((a, b) => a + b, 0); check(sum === r.data?.total && r.data.total === ids.length && r.data.counts.compatible >= 1 && r.data.counts.unsupported >= 1 && r.data.counts.upgrade_available >= 1, 'counts add up to the list', JSON.stringify(r.data?.counts)); - check(JSON.stringify(r.data?.states?.map((s) => s.state)) === JSON.stringify(['unsupported', 'upgrade_available', 'compatible', 'unknown']), 'four states, none managed', JSON.stringify(r.data?.states)); + check(JSON.stringify(r.data?.states?.map((s) => s.state)) === JSON.stringify(['unsupported', 'upgrade_available', 'compatible', 'unknown']) + && r.data?.managedControls === false && Object.keys(r.data?.counts ?? {}).length === 7, + 'MSA_GRANTS off: the four readiness tiles only (nothing can be Managed), managedControls false; counts still name all seven', JSON.stringify(r.data?.states)); check((r.data?.computers ?? []).every((c) => !['managed', 'managed_verified', 'enforcement_failure'].includes(c.state)), 'no computer is managed'); check(/not available yet; nothing has changed on any computer|not available yet; nothing has changed on this computer/.test(r.data?.note ?? ''), 'the note is there', r.data?.note); r = await req('GET', '/msa/readiness?state=compatible', { s: SA }); check(ok(r) && r.data.computers.length >= 1 && r.data.computers.every((c) => c.state === 'compatible') && r.data.computers.some((c) => c.id === A1.id), '?state=compatible lists only compatible ones', msg(r)); r = await req('GET', '/msa/readiness?state=managed', { s: SA }); - check(ok(r) && r.data.computers.length === r.data.total, '?state=managed is not a filter (ignored), never an error', msg(r)); + check(ok(r) && r.data.computers.length === 0, '?state=managed is a filter (0.72) and lists none: nothing was cut over', msg(r)); + r = await req('GET', '/msa/readiness?state=bogus', { s: SA }); + check(ok(r) && r.data.computers.length === r.data.total, '?state=bogus is not a filter (ignored), never an error', msg(r)); r = await req('GET', '/msa/readiness', { s: SU }); const uids = (r.data?.computers ?? []).map((c) => c.id); check(ok(r) && uids.includes(A1.id) && !uids.includes(A2.id) && !uids.includes(A3.id) && !uids.includes(B1.id), 'a Business User granted A1: only A1', JSON.stringify(uids)); diff --git a/apps/api/scripts/e2e-signed-release.mjs b/apps/api/scripts/e2e-signed-release.mjs index 71293013..0f295e0e 100755 --- a/apps/api/scripts/e2e-signed-release.mjs +++ b/apps/api/scripts/e2e-signed-release.mjs @@ -228,7 +228,7 @@ async function main() { 'state and key directories 0700, every key 0600', `${mode(STATE)} ${mode(KEYS)}`); check(mode(PUB) === '2750', 'published directory 2750 (setgid: files take the portal group)', mode(PUB)); check(mode(CONF) === '644' && /^PUB_DIR=/m.test(readFileSync(CONF, 'utf8')), 'configuration written, 0644', mode(CONF)); - check(['rem0te-signed-publish', 'rem0te-signed-status', 'rem0te-signed-export-root', 'rem0te-signed-refresh'].every((c) => existsSync(path.join(BIN, c))) && existsSync(TOOL), + check(['rem0te-signed-publish', 'rem0te-signed-status', 'rem0te-signed-export-root', 'rem0te-signed-refresh', 'rem0te-signed-grant-key'].every((c) => existsSync(path.join(BIN, c))) && existsSync(TOOL), 'commands and the release tool installed', readdirSync(BIN).join(' ')); check(readFileSync(ENVF, 'utf8').includes(`\nUPDATE_REPO_DIR=${PUB}\n`), '--apply-env adds UPDATE_REPO_DIR to the portal env file', readFileSync(ENVF, 'utf8')); const root = JSON.parse(readFileSync(path.join(STATE, 'repo/metadata/1.root.json'), 'utf8')); @@ -391,6 +391,43 @@ async function main() { check(r2.code === 0 && servedTargets()['approval/keys.json']?.hashes?.sha256 === sha(readFileSync(good)), 'a later publish signs it again from the kept copy', r2.out.slice(-600)); } + section('0.72: rem0te-signed-grant-key records Managed Secure Access grant public keys, and publish signs them in as msa/grant-keys.json'); + { + const gk = (args) => run(path.join(BIN, 'rem0te-signed-grant-key'), args); + const raw = generateKeyPairSync('ed25519').publicKey.export({ format: 'der', type: 'spki' }).subarray(-32); + const pubB64 = raw.toString('base64'); + const kid = sha(raw).slice(0, 16); + const before = tree(PUB); + let r = note(await gk(['list'])); + check(r.code === 0 && /no grant keys/.test(r.out), 'list with nothing recorded: says agents refuse every grant', r.out.slice(-400)); + r = note(await gk(['add', '--key-id', kid, '--public-key', '-----BEGIN PRIVATE KEY-----'])); + check(r.code !== 0 && /looks like key material/.test(r.out), 'key material is refused', r.out.slice(-400)); + r = note(await gk(['add', '--key-id', '0'.repeat(16), '--public-key', pubB64])); + check(r.code !== 0 && /not the id of that key/.test(r.out), 'a key id that is not the key\'s own SHA-256 prefix is refused', r.out.slice(-400)); + r = note(await gk(['add', '--key-id', kid, '--public-key', 'short'])); + check(r.code !== 0 && /32-byte Ed25519 public key/.test(r.out), 'something that is not 32 bytes of base64 is refused', r.out.slice(-400)); + check(sameTree(before, tree(PUB)) && !existsSync(path.join(STATE, 'msa-grant-keys.json')), 'refusals record and publish nothing', ''); + r = note(await gk(['add', '--key-id', kid, '--public-key', pubB64])); + check(r.code === 0 && /done\. Publish it: sudo rem0te-signed-publish --republish/.test(r.out), 'add records the key and names the publish command', r.out.slice(-400)); + check(sameTree(before, tree(PUB)), 'add alone publishes nothing', ''); + r = note(await gk(['add', '--key-id', kid, '--public-key', pubB64])); + check(r.code === 0 && /already listed; nothing changed/.test(r.out), 'adding it again changes nothing', r.out.slice(-400)); + r = note(await gk(['list'])); + check(r.code === 0 && r.out.includes(`${kid} ${pubB64}`), 'list shows the key id and public key', r.out.slice(-400)); + r = note(await publish(['--republish'])); + const want = { schema: 'rem0te-msa-grant-keys/1', keys: [{ keyId: kid, publicKey: pubB64 }] }; + const t = servedTargets()['msa/grant-keys.json']; + check(r.code === 0 && t?.hashes?.sha256 === sha(Buffer.from(`${JSON.stringify(want)}\n`)), 'publish signs msa/grant-keys.json in with the recorded list\'s digest', JSON.stringify(t ?? null) + r.out.slice(-800)); + check(/verified: root v1/.test(verifyMirror()), 'verify -mirror accepts the release that carries it'); + const st = note(await run(path.join(BIN, 'rem0te-signed-status'))); + check(st.out.includes(`msa/grant-keys.json ${t?.hashes?.sha256?.slice(0, 12)}`), 'rem0te-signed-status shows the published grant keys', st.out.slice(-1200)); + r = note(await gk(['retire', '--key-id', kid])); + check(r.code === 0 && /retire [0-9a-f]{16}: done/.test(r.out), 'retire removes it from the list', r.out.slice(-400)); + r = note(await publish(['--republish'])); + const t2 = servedTargets()['msa/grant-keys.json']; + check(r.code === 0 && t2?.hashes?.sha256 === sha(Buffer.from(`${JSON.stringify({ schema: 'rem0te-msa-grant-keys/1', keys: [] })}\n`)), 'the next publish signs the empty list: agents refuse grants under the retired key', JSON.stringify(t2 ?? null) + r.out.slice(-600)); + } + section('The daily refresh: a new timestamp, and nothing else'); { const t0 = tree(PUB); diff --git a/apps/api/scripts/unit-msa-managed.mjs b/apps/api/scripts/unit-msa-managed.mjs new file mode 100644 index 00000000..309a32e9 --- /dev/null +++ b/apps/api/scripts/unit-msa-managed.mjs @@ -0,0 +1,104 @@ +#!/usr/bin/env node +// Managed Secure Access build step 4 (0.72), run against dist: +// +// node apps/api/scripts/unit-msa-managed.mjs +// +// The closed vocabulary the portal and the signed agent share +// (src/msa/managed.ts against tools/windows-installer/internal/msa/enforce), +// the pure decisions (ceiling, rotation hold, legacy refusal, the report +// body) and the grant-key target names (portal, agent, deploy/release). + +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createRequire } from 'node:module'; +import { readFileSync } from 'node:fs'; + +const here = dirname(fileURLToPath(import.meta.url)); +const ROOT = join(here, '..', '..', '..'); +const require = createRequire(import.meta.url); +const m = require(join(here, '..', 'dist', 'msa', 'managed.js')); +const pf = require(join(here, '..', 'dist', 'msa', 'preflight.js')); +const gk = require(join(here, '..', 'dist', 'msa', 'grant-key-commands.js')); +const G = require(join(here, '..', 'dist', 'msa', 'grant.js')); + +let passed = 0; +const failures = []; +const check = (name, ok, detail = '') => { if (ok) passed++; else failures.push(`${name}${detail ? ` — ${detail}` : ''}`); }; +const J = JSON.stringify; +const go = (f) => readFileSync(join(ROOT, 'tools', 'windows-installer', f), 'utf8'); + +// ── The same vocabulary on both sides ─────────────────────────────────────── +{ + const enf = go('internal/msa/enforce/enforce.go'); + const outs = /var Outcomes = \[\]string\{([^}]*)\}/.exec(enf)?.[1] ?? ''; + const consts = Object.fromEntries([...enf.matchAll(/^\s+([A-Z][A-Za-z]+)\s+= "([a-z_]+)"$/gm)].map((x) => [x[1], x[2]])); + const goOutcomes = [...outs.matchAll(/([A-Z][A-Za-z]+)/g)].map((x) => consts[x[1]]); + check('the agent\'s outcome codes are the portal\'s, in order', J(goOutcomes) === J([...m.AGENT_OUTCOMES]), J(goOutcomes)); + const poller = go('internal/msa/enforce/poller.go'); + const goEvents = [...new Set([...poller.matchAll(/Event: "([a-z_]+)"/g)].map((x) => x[1]))].sort(); + check('every event the agent reports is one the portal accepts, and every one is reported', J(goEvents) === J([...m.REPORT_EVENTS].sort()), J(goEvents)); + check('the managed keys are the preflight\'s eleven', J([...m.MANAGED_KEYS]) === J([...pf.PREFLIGHT_KEYS]) && m.MANAGED_KEYS.length === 11); + check('a failed readback may name the password, nothing else', J([...m.REPORT_KEYS]) === J([...pf.PREFLIGHT_KEYS, 'password'])); + check('the agent\'s compiled ceiling is view-only with nothing beyond', /var Ceiling = grant\.Ceiling\{Mode: "view"\}/.test(enf)); + check('the portal\'s ceiling is the same', J(m.MANAGED_CEILING) === J({ mode: 'view', permissions: { clipboard: false, files: false, audio: false, tunnel: false, restart: false } })); + check('every verifier reason fits the outcome charset', G.REASONS.every((x) => /^[a-z_]{1,40}$/.test(x))); +} + +// ── withinCeiling ─────────────────────────────────────────────────────────── +{ + const none = { clipboard: false, files: false, audio: false, tunnel: false, restart: false }; + check('view with nothing beyond is within', m.withinCeiling('view', none)); + check('control is above', !m.withinCeiling('control', none)); + for (const k of Object.keys(none)) check(`view + ${k} is above`, !m.withinCeiling('view', { ...none, [k]: true })); +} + +// ── rotationHeld / legacyRefused ──────────────────────────────────────────── +{ + check('Legacy: a rotation is never held', m.rotationHeld(null, true) === false); + check('pending, nothing in flight: the rotation goes out (Legacy works between test sessions)', m.rotationHeld({ state: 'pending' }, false) === false); + check('pending with a grant in flight: held', m.rotationHeld({ state: 'pending' }, true) === true); + for (const s of ['verified', 'enforcement_failure', 'rollback_pending']) check(`${s}: held`, m.rotationHeld({ state: s }, false) === true); + check('legacy Connect refused only once verified', m.legacyRefused({ verifiedAt: new Date() }) && !m.legacyRefused({ verifiedAt: null }) && !m.legacyRefused(null)); + check('the refusal says how to connect meanwhile', /roll it back to Legacy/.test(m.LEGACY_REFUSED_MESSAGE)); +} + +// ── The report body ───────────────────────────────────────────────────────── +{ + const base = { rustdeskId: '555666777', agentSecret: 'a'.repeat(48) }; + const gid = '00112233445566778899aabbccddeeff'; + const ok = (b) => m.ReportBody.safeParse(b).success; + check('applied with a grant id', ok({ ...base, event: 'applied', grantId: gid })); + check('failed with an outcome and keys', ok({ ...base, event: 'failed', grantId: gid, outcome: 'readback_mismatch', keys: ['access-mode', 'password'] })); + check('secured with no grant id', ok({ ...base, event: 'secured' })); + check('restore_failed with keys', ok({ ...base, event: 'restore_failed', keys: ['approve-mode'] })); + const bad = [ + ['applied without a grant id', { ...base, event: 'applied' }], + ['secured with a grant id', { ...base, event: 'secured', grantId: gid }], + ['an unknown event', { ...base, event: 'password_set' }], + ['a password field', { ...base, event: 'applied', grantId: gid, password: 'ZZZZyyyyXXXXwwww00001111' }], + ['an unknown key', { ...base, event: 'drift', keys: ['custom-rendezvous-server'] }], + ['free text as the outcome', { ...base, event: 'failed', grantId: gid, outcome: 'RustDesk said: no' }], + ['a bad grant id', { ...base, event: 'applied', grantId: 'x' }], + ['a short secret', { ...base, agentSecret: 'short', event: 'secured' }], + ['a non-numeric RustDesk ID', { ...base, rustdeskId: 'abc', event: 'secured' }], + ['a value for a key', { ...base, event: 'drift', keys: ['access-mode'], values: { 'access-mode': 'full' } }], + ]; + for (const [n, b] of bad) check(`refused: ${n}`, !ok(b)); +} + +// ── The grant-key target: one name, one schema, everywhere ────────────────── +{ + const keysGo = go('internal/msa/grant/keys.go'); + check('the agent reads the same target', keysGo.includes(`KeysTarget = "${gk.MSA_GRANT_KEYS_TARGET}"`)); + check('and the same schema', keysGo.includes(`KeysSchema = "${gk.MSA_GRANT_KEYS_SCHEMA}"`)); + const publish = readFileSync(join(ROOT, 'deploy', 'release', 'rem0te-signed-publish'), 'utf8'); + const addKey = readFileSync(join(ROOT, 'deploy', 'release', 'rem0te-signed-grant-key'), 'utf8'); + check('rem0te-signed-publish signs it in under that name', publish.includes(`-add "${gk.MSA_GRANT_KEYS_TARGET}=$msa_build"`)); + check('rem0te-signed-grant-key writes that schema', addKey.includes(`const SCHEMA = "${gk.MSA_GRANT_KEYS_SCHEMA}"`)); + check('the console\'s commands name the installed commands', gk.MSA_GRANT_KEY_ADD_COMMAND === 'sudo rem0te-signed-grant-key add' && gk.MSA_GRANT_KEY_PUBLISH_COMMAND === 'sudo rem0te-signed-publish --republish'); + const setup = readFileSync(join(ROOT, 'deploy', 'release', 'rem0te-signed-setup.sh'), 'utf8'); + check('setup installs rem0te-signed-grant-key', /for c in [^;]*rem0te-signed-grant-key; do/.test(setup)); +} + +console.log(`unit-msa-managed: ${passed} passed, ${failures.length} failed`); +if (failures.length) { for (const f of failures) console.log(` ✗ ${f}`); process.exit(1); } diff --git a/apps/api/scripts/unit-msa-readiness.mjs b/apps/api/scripts/unit-msa-readiness.mjs index 1448d3c1..a6ec4188 100644 --- a/apps/api/scripts/unit-msa-readiness.mjs +++ b/apps/api/scripts/unit-msa-readiness.mjs @@ -134,42 +134,77 @@ const is = (name, f, state, re) => { is('checkedAt as a string', { preflight: pf({ checkedAt: new Date(NOW - 3600_000).toISOString() }) }, 'compatible'); } -// ── Nothing can be managed yet ────────────────────────────────────────────── +// ── Managed states only from a managed fact (0.72) ────────────────────────── { const managed = ['managed', 'managed_verified', 'enforcement_failure']; check('the type names every state of the design', J([...r.MSA_STATES]) === J(['unsupported', 'upgrade_available', 'compatible', 'unknown', ...managed])); - check('the producible states exclude every managed state', r.PRODUCIBLE_STATES.length === 4 && managed.every((m) => !r.PRODUCIBLE_STATES.includes(m))); - // Every combination of facts the function reads. + check('a preflight alone produces only the four readiness states', J([...r.READINESS_STATES]) === J(['unsupported', 'upgrade_available', 'compatible', 'unknown'])); + check('the managed states are exactly the three', J([...r.MANAGED_READINESS_STATES]) === J(managed) && r.PRODUCIBLE_STATES.length === 7); + // Every combination of facts the function reads, with no managed fact: never a managed state. const seen = new Set(); let n = 0; let verifiedEver = false; - for (const platform of ['windows', 'Windows 11', 'linux', 'macos', null, 'solaris']) - for (const signedAgent of [true, false]) - for (const agentVersion of ['0.69.0', '0.68.3', null, '1.0.0', 'garbage']) - for (const isOnline of [true, false]) - for (const lastSeen of [60_000, 3600_000, null]) - for (const pre of [null, 'fresh', 'old']) - for (const version of ['1.4.7+65', '1.3.9', '1.6.0', null]) - for (const build of ['flutter', 'sciter', 'unknown']) - for (const service of ['running', 'stopped', 'missing', 'other']) - for (const cli of ['ok', 'partial', 'failed', 'not_run']) - for (const placed of [[true, true], [true, false], [false, false]]) { - const x = r.decideReadiness({ - platform, signedAgent, agentVersion, isOnline, lastSeenAt: lastSeen === null ? null : new Date(NOW - lastSeen), - preflight: pre === null ? null : { checkedAt: new Date(NOW - (pre === 'old' ? 9 * 86400_000 : 600_000)), installed: placed[0], expectedPath: placed[1], version, build, service, cli, keysOk: cli === 'ok' ? 11 : cli === 'partial' ? 5 : 0 }, - }, NOW); - n++; seen.add(x.state); - if (x.verified !== false) verifiedEver = true; - if (!r.PRODUCIBLE_STATES.includes(x.state)) failures.push(`produced ${x.state} for ${J({ platform, signedAgent, agentVersion, pre, version, build, service, cli })}`); - if (!x.reasons.length || x.label !== r.STATE_LABEL[x.state]) failures.push(`no reason or wrong label: ${J(x)}`); - } - check(`${n} combinations: none managed, managed_verified or enforcement_failure`, managed.every((m) => !seen.has(m)) && seen.size === 4, J([...seen])); - check('verified is false on every answer', !verifiedEver); - // And the source has no path to one. + const combos = function* () { + for (const platform of ['windows', 'Windows 11', 'linux', 'macos', null, 'solaris']) + for (const signedAgent of [true, false]) + for (const agentVersion of ['0.69.0', '0.68.3', null, '1.0.0', 'garbage']) + for (const isOnline of [true, false]) + for (const lastSeen of [60_000, 3600_000, null]) + for (const pre of [null, 'fresh', 'old']) + for (const version of ['1.4.7+65', '1.3.9', '1.6.0', null]) + for (const build of ['flutter', 'sciter', 'unknown']) + for (const service of ['running', 'stopped', 'missing', 'other']) + for (const cli of ['ok', 'partial', 'failed', 'not_run']) + for (const placed of [[true, true], [true, false], [false, false]]) + yield { + platform, signedAgent, agentVersion, isOnline, lastSeenAt: lastSeen === null ? null : new Date(NOW - lastSeen), + preflight: pre === null ? null : { checkedAt: new Date(NOW - (pre === 'old' ? 9 * 86400_000 : 600_000)), installed: placed[0], expectedPath: placed[1], version, build, service, cli, keysOk: cli === 'ok' ? 11 : cli === 'partial' ? 5 : 0 }, + }; + }; + for (const f of combos()) { + for (const m of [undefined, null]) { + const x = r.decideReadiness({ ...f, managed: m }, NOW); + n++; seen.add(x.state); + if (x.verified !== false) verifiedEver = true; + if (!r.READINESS_STATES.includes(x.state)) failures.push(`produced ${x.state} with no managed fact for ${J({ ...f, preflight: !!f.preflight })}`); + if (!x.reasons.length || x.label !== r.STATE_LABEL[x.state]) failures.push(`no reason or wrong label: ${J(x)}`); + } + } + check(`${n} combinations without a managed fact: none managed, managed_verified or enforcement_failure`, managed.every((m) => !seen.has(m)) && seen.size === 4, J([...seen])); + check('verified is false on every one of them', !verifiedEver); + + // With a managed fact. + const reporting = { platform: 'windows', signedAgent: true, agentVersion: '0.72.0', isOnline: true, lastSeenAt: new Date(NOW - 60_000), + preflight: { checkedAt: new Date(NOW - 600_000), installed: true, expectedPath: true, version: '1.4.7+65', build: 'flutter', service: 'running', cli: 'ok', keysOk: 11 } }; + const m = (over) => ({ state: 'pending', requestedAt: new Date(NOW - 3600_000), verifiedAt: null, readbackOkAt: null, failReason: null, failedKeys: [], ...over }); + const d = (managedFact, base = reporting) => r.decideReadiness({ ...base, managed: managedFact }, NOW); + let x = d(m({})); + check('pending: Managed (pending), not verified', x.state === 'managed' && x.verified === false && x.label === 'Managed (pending)' && /Legacy Connect still works/.test(x.reasons[0]), J(x)); + x = d(m({ state: 'rollback_pending', })); + check('rolling back: still managed until the agent restores', x.state === 'managed' && x.verified === false && /Rolling back/.test(x.reasons[0]), J(x)); + x = d(m({ state: 'enforcement_failure', failReason: 'readback_mismatch', failedKeys: ['access-mode'] })); + check('enforcement failure names the reason and keys', x.state === 'enforcement_failure' && x.verified === false && /readback_mismatch \(access-mode\)/.test(x.reasons[0]), J(x)); + x = d(m({ state: 'verified', verifiedAt: new Date(NOW - 7200_000), readbackOkAt: new Date(NOW - 600_000) })); + check('verified with a readback this week: managed_verified, verified true', x.state === 'managed_verified' && x.verified === true, J(x)); + x = d(m({ state: 'verified', verifiedAt: new Date(NOW - 7200_000), readbackOkAt: new Date(NOW - 8 * 86400_000) })); + check('verified but no readback for 8 days: unknown, never shown as enforced', x.state === 'unknown' && x.verified === false, J(x)); + x = d(m({ state: 'verified', verifiedAt: new Date(NOW - 7200_000), readbackOkAt: null })); + check('verified with no readback at all: unknown', x.state === 'unknown' && x.verified === false, J(x)); + x = d(m({ state: 'verified', verifiedAt: new Date(NOW - 7200_000), readbackOkAt: new Date(NOW - 600_000) }), { ...reporting, platform: 'linux' }); + check('a managed fact never overrides rules 1–3 (not Windows)', x.state === 'unsupported' && x.verified === false, J(x)); + x = d(m({ state: 'verified', verifiedAt: new Date(NOW - 7200_000), readbackOkAt: new Date(NOW - 600_000) }), { ...reporting, isOnline: false, lastSeenAt: null }); + check('a managed fact never overrides rules 1–3 (not reporting)', !managed.includes(x.state) && x.verified === false, J(x)); + // Only one line in decideReadiness produces managed_verified, from the verified row. const src = readFileSync(join(here, '..', 'src', 'msa', 'readiness.ts'), 'utf8'); const body = src.slice(src.indexOf('export function decideReadiness')); - check('decideReadiness names no managed state', !/'managed'|'managed_verified'|'enforcement_failure'/.test(body)); - check('the note says nothing changed', /nothing has changed on this computer/.test(r.READINESS_NOTE) && /not available yet/.test(r.READINESS_NOTE)); + check('managed states appear only inside the managed-fact branch', (() => { + const branch = body.slice(body.indexOf('const m = f.managed;'), body.indexOf('// 4. An agent that can report.')); + // The one other mention: `verified` is true exactly for managed_verified. + const rest = body.replace(branch, '').replace("verified: state === 'managed_verified'", ''); + return branch.length > 0 && !/'managed'|'managed_verified'|'enforcement_failure'/.test(rest); + })()); + check('the readiness note still says nothing changed', /nothing has changed on this computer/.test(r.READINESS_NOTE)); + check('the managed note says where it has run', /only in the Windows lab/.test(r.MANAGED_NOTE) && /never on a Windows 10 or 11 desktop or on the fleet/.test(r.MANAGED_NOTE)); } // ── Versions ──────────────────────────────────────────────────────────────── diff --git a/apps/api/scripts/unit-signed-release.mjs b/apps/api/scripts/unit-signed-release.mjs index 1a0ff3d9..80da026e 100755 --- a/apps/api/scripts/unit-signed-release.mjs +++ b/apps/api/scripts/unit-signed-release.mjs @@ -67,6 +67,7 @@ try { meta('3.targets.json', { version: 3, expires: far, targets: { 'windows/rem0te-agent.exe': tgt(s('3'), { version: '1.2.3; rm -rf /', commit: 'nothex' }), 'windows/rustdesk/rustdesk-1.4.9-x86_64.exe': tgt(s('b'), { version: '1.4.9' }), + 'msa/grant-keys.json': tgt(s('c')), } }); meta('2.targets.json', { version: 2, expires: far, targets: { 'windows/rem0te-agent.exe': tgt(s('2')) } }); meta('1.targets.json', { version: 1, expires: far, targets: { 'windows/rem0te-agent.exe': tgt(s('1')) } }); @@ -77,6 +78,7 @@ try { const kv = Object.fromEntries(r.stdout.trim().split('\n').map((l) => [l.slice(0, l.indexOf('=')), l.slice(l.indexOf('=') + 1)])); check(kv.CONFIGURED === '1' && kv.TIMESTAMP_VERSION === '9' && kv.TARGETS_VERSION === '3' && kv.RUSTDESK_VERSIONS === '1.4.9', 'summary follows timestamp → snapshot → targets', r.stdout); check(kv.AGENT_VERSION === '' && kv.AGENT_COMMIT === '' && kv.AGENT_SHA256 === s('3'), 'a version or commit outside its charset is reported as empty, never passed to the shell', JSON.stringify(kv)); + check(kv.MSA_GRANT_KEYS_SHA256 === s('c'), '0.72: the Managed Secure Access grant-key target is reported by its signed digest', kv.MSA_GRANT_KEYS_SHA256); check(Number(kv.TIMESTAMP_LEFT_H) >= 167 && Number(kv.TIMESTAMP_LEFT_H) <= 168, 'hours left computed from expires', kv.TIMESTAMP_LEFT_H); r = node('repo-info.mjs', [repo, 'prune-list']); const stale = r.stdout.trim().split('\n').sort(); diff --git a/apps/api/src/endpoints/endpoints.service.ts b/apps/api/src/endpoints/endpoints.service.ts index 62331824..ad02b258 100644 --- a/apps/api/src/endpoints/endpoints.service.ts +++ b/apps/api/src/endpoints/endpoints.service.ts @@ -25,6 +25,7 @@ import { EndpointInventoryService } from '../endpoint-inventory/endpoint-invento import { likeEscape } from '../common/like'; import { EndpointListService } from './endpoint-list.service'; import { connectivityOf } from '../common/connectivity'; +import { LEGACY_REFUSED_MESSAGE, legacyRefused } from '../msa/managed'; /** * Computers. @@ -626,6 +627,7 @@ export class EndpointsService { async setPassword(actor: ActorContext, id: string, password: string | null): Promise { await this.acl.assertEndpointInScope(actor, id, CAP.COMPUTERS_EDIT); this.acl.assertCapability(actor, CAP.COMPUTERS_EDIT); + await this.refuseMsaManaged(id); await this.assertComputerReachable(actor, id); await this.admitWrite(actor, id); @@ -645,11 +647,27 @@ export class EndpointsService { async assertPasswordAccess(actor: ActorContext, id: string) { const endpoint = await this.acl.assertEndpointInScope(actor, id, CAP.COMPUTERS_EDIT); this.acl.assertCapability(actor, CAP.COMPUTERS_EDIT); + await this.refuseMsaManaged(id); await this.assertComputerReachable(actor, id); await this.admitWrite(actor, id); return endpoint; } + /** + * 0.72 (Managed Secure Access, §82): once a Platform Admin verified a + * computer as managed, its RustDesk password is one nobody is told, and + * the stored legacy password is not a way in. Reveal and the legacy + * Connect paths refuse it (409 MSA_MANAGED); rolling it back to Legacy + * restores both. A computer that is only Managed (pending) keeps Legacy. + */ + async msaLegacyRefused(endpointId: string): Promise { + return legacyRefused(await this.prisma.msaManagedComputer.findUnique({ where: { endpointId }, select: { verifiedAt: true } })); + } + + private async refuseMsaManaged(endpointId: string) { + if (await this.msaLegacyRefused(endpointId)) throw new ConflictException({ code: 'MSA_MANAGED', message: LEGACY_REFUSED_MESSAGE }); + } + /** Whether this person has an active authenticator (TOTP) enrolled. */ async userHasMfa(userId: string): Promise { return (await this.prisma.userMfaMethod.count({ where: { userId, type: 'TOTP', isActive: true } })) > 0; @@ -717,20 +735,53 @@ export class EndpointsService { ); } + // 0.72: a managed computer's RustDesk password is the agent's (§82). + const managed = await this.prisma.msaManagedComputer.findUnique({ where: { endpointId }, select: { state: true } }); + if (managed && managed.state !== 'pending') { + throw new ConflictException({ code: 'MSA_MANAGED', message: 'This computer is in Managed Secure Access: its password is set by the agent. Roll it back to Legacy to rotate it.' }); + } + + await this.stagePendingPassword(node.id); + await this.audit.log({ + tenantId: endpoint.tenantId ?? undefined, customerId: endpoint.customerId ?? undefined, + actorId: actor.userId, actorIp: actor.ip, + action: 'ENDPOINT_CREDENTIAL_ROTATION_STAGED', resource: 'endpoint', resourceId: endpointId, + }); + return { success: true, status: 'PENDING' }; + } + + /** The one place a rotation is staged: a fresh password, sealed, parked as pendingPassword for the heartbeat. */ + private async stagePendingPassword(nodeId: string) { const rnd = crypto.randomBytes(24).toString('base64') .replace(/[+/=]/g, '') .slice(0, 20); - await this.prisma.rustdeskNode.update({ - where: { id: node.id }, + where: { id: nodeId }, data: { pendingPassword: this.encryptPassword(rnd), pendingPasswordAt: new Date() }, }); + } + + /** + * 0.72 (Managed Secure Access): the existing rotation path, staged by the + * system rather than a person — on rollback to Legacy, and when a managed + * test session on a computer still in Managed (pending) ended with a + * password nobody is told. The heartbeat holds it until the computer's + * managed state allows it (msa/managed.ts rotationHeld), then hands it + * over and the computer confirms it exactly as for a console rotation. + * Audited as ENDPOINT_CREDENTIAL_ROTATION_STAGED with the reason. + */ + async stageRotationForMsa(endpointId: string, actorId: string | null, reason: 'msa_rollback' | 'msa_session_ended'): Promise { + const ep = await this.prisma.endpoint.findUnique({ + where: { id: endpointId }, + select: { tenantId: true, customerId: true, rustdeskNode: { select: { id: true, agentSecretHash: true } } }, + }); + if (!ep?.rustdeskNode?.agentSecretHash) return false; + await this.stagePendingPassword(ep.rustdeskNode.id); await this.audit.log({ - tenantId: endpoint.tenantId ?? undefined, customerId: endpoint.customerId ?? undefined, - actorId: actor.userId, actorIp: actor.ip, - action: 'ENDPOINT_CREDENTIAL_ROTATION_STAGED', resource: 'endpoint', resourceId: endpointId, + tenantId: ep.tenantId ?? undefined, customerId: ep.customerId ?? undefined, actorId: actorId ?? undefined, + action: 'ENDPOINT_CREDENTIAL_ROTATION_STAGED', resource: 'endpoint', resourceId: endpointId, meta: { source: reason }, }); - return { success: true, status: 'PENDING' }; + return true; } // ── Connecting ──────────────────────────────────────────────────────────── @@ -772,6 +823,10 @@ export class EndpointsService { if (endpoint.status === 'ARCHIVED') return { ok: false, reason: 'endpoint_archived' }; + // 0.72 (§82): a verified Managed Secure Access computer has no legacy + // password to launch with. Connect for managed computers is step 5. + if (await this.msaLegacyRefused(endpoint.id)) return { ok: false, reason: 'msa_managed', status: 'denied', message: LEGACY_REFUSED_MESSAGE }; + // Business members and admins need computers:connect, as before. A // technician is decided by the launch policy below: a preset grants no // computers:connect at all, and a custom assignment's connect is honoured diff --git a/apps/api/src/enrollment/enrollment.service.ts b/apps/api/src/enrollment/enrollment.service.ts index 20955b2b..0e736f53 100644 --- a/apps/api/src/enrollment/enrollment.service.ts +++ b/apps/api/src/enrollment/enrollment.service.ts @@ -1030,7 +1030,9 @@ export class EnrollmentService { where: { id: node.id }, select: { pendingPassword: true }, }) : null; - if (refreshed?.pendingPassword) { + // 0.72 (§82): a managed computer's RustDesk password is the agent's. A + // staged rotation waits while msa/managed.ts rotationHeld says so. + if (refreshed?.pendingPassword && !(await this.msa.rotationHeld(node.endpointId))) { try { const plain = this.decryptPassword(refreshed.pendingPassword); const sha = createHash('sha256').update(plain).digest('hex'); @@ -1295,6 +1297,19 @@ export class EnrollmentService { } } + // Managed Secure Access (0.72, §82): only an authenticated signed + // heartbeat that may act, with MSA_GRANTS on and the computer in a + // managed state, is told to run the grant poller. Never anyone else: an + // older agent ignores the field, and a Legacy computer never sees it. + let msaPoll = false; + if (authenticated && mayAct && kind === 'signed') { + try { + msaPoll = await this.msa.pollWanted(node.endpointId); + } catch (e) { + this.logger.warn(`MSA step failed for endpoint ${node.endpointId}: ${String(e)}`); + } + } + // Chat (0.34): whether a conversation is open, so the signed agent starts // its chat host. A flag only — no names, no text: the host fetches those // over /enrollment/chat/poll with the device secret. Asked only of an @@ -1332,6 +1347,7 @@ export class EnrollmentService { patchPostureAck, patchScan, ...(rustdeskPreflightAck ? { rustdeskPreflightAck } : {}), + ...(msaPoll ? { msaPoll: true } : {}), monitor, diagnostics, chat, diff --git a/apps/api/src/msa/grant-key-commands.ts b/apps/api/src/msa/grant-key-commands.ts new file mode 100644 index 00000000..9f20fc61 --- /dev/null +++ b/apps/api/src/msa/grant-key-commands.ts @@ -0,0 +1,14 @@ +/** + * The owner's commands that put the portal's grant public key into the signed + * release metadata (0.72, Managed Secure Access §3.2). Text the console shows + * a Platform Admin to run on the release host as root — the portal never runs + * them, and cannot: the release user's state is unreadable to it (§56). These + * two exported strings are the only place apps/api/src names the command + * (§56 matches them exactly). + */ +export const MSA_GRANT_KEY_ADD_COMMAND = 'sudo rem0te-signed-grant-key add'; +export const MSA_GRANT_KEY_PUBLISH_COMMAND = 'sudo rem0te-signed-publish --republish'; + +/** The signed target the agent reads its grant keys from, and its schema. Same strings as the Go agent and deploy/release. */ +export const MSA_GRANT_KEYS_TARGET = 'msa/grant-keys.json'; +export const MSA_GRANT_KEYS_SCHEMA = 'rem0te-msa-grant-keys/1'; diff --git a/apps/api/src/msa/managed.ts b/apps/api/src/msa/managed.ts new file mode 100644 index 00000000..a6990ea7 --- /dev/null +++ b/apps/api/src/msa/managed.ts @@ -0,0 +1,100 @@ +/** + * Managed Secure Access, build step 4 (0.72): the closed vocabulary the + * portal and the signed agent share for cutover, enforcement, the managed + * test session and rollback (docs/managed-secure-access.md §3.3, §3.7, + * §3.11). Pure: zod and two pure sibling modules only. + * + * The agent's side is tools/windows-installer/internal/msa/enforce: the same + * key list (msa/preflight.ts PREFLIGHT_KEYS, Go msa.Keys), the same ceiling, + * the same report events and outcome codes. check-security-invariants §82 + * compares them. + */ +import { z } from 'zod'; +import { GRANT_ID_RE, type GrantMode, type GrantPermissions } from './grant'; +import { PREFLIGHT_KEYS } from './preflight'; + +/** A managed computer's state. No row is Legacy. */ +export const MANAGED_STATES = ['pending', 'verified', 'enforcement_failure', 'rollback_pending'] as const; +export type ManagedState = (typeof MANAGED_STATES)[number]; + +/** + * The ceiling every managed computer has in 0.72: view-only, nothing beyond. + * The agent compiles in the same constant (enforce.Ceiling) and refuses a + * grant above it (mode_not_allowed / permission_not_allowed); the portal + * refuses to issue one to a managed computer first (MSA_ABOVE_CEILING). + * It is not configurable: a portal-supplied ceiling would be a portal + * asking itself for permission. A signed, per-computer ceiling is step 5. + */ +export const MANAGED_CEILING: { mode: GrantMode; permissions: GrantPermissions } = { + mode: 'view', + permissions: { clipboard: false, files: false, audio: false, tunnel: false, restart: false }, +}; + +/** The keys the agent sets (and saves first, and restores on rollback): exactly the preflight's eleven. */ +export const MANAGED_KEYS = PREFLIGHT_KEYS; +/** A failed readback may also name the password (it cannot be read back; RustDesk did not say Done). */ +export const REPORT_KEYS = [...PREFLIGHT_KEYS, 'password'] as const; + +/** What the agent reports, on POST /msa/agent/report with its device secret. */ +export const REPORT_EVENTS = [ + 'applied', // every setting read back, then the one-time password set + 'failed', // the grant was refused, or applying it failed (outcome says why) + 'connected', // a RustDesk connection manager (`rustdesk.exe --cm`) appeared while applied + 'ended', // the session ended: a password nobody is told, stop-service Y then N + 'drift', // a managed setting changed while no session was open + 'checked', // between sessions: every managed setting still reads back as last applied + 'secured', // after verification: the legacy permanent password replaced by one nobody is told + 'restored', // rollback: every saved setting put back and read back + 'restore_failed', // rollback: a saved setting did not read back +] as const; +export type ReportEvent = (typeof REPORT_EVENTS)[number]; + +/** + * Closed outcome codes. A refusal by the verifier is its reason code + * (grant.ts REASONS); the rest are the agent's. + */ +export const AGENT_OUTCOMES = [ + 'readback_mismatch', 'password_not_applied', 'save_failed', 'rustdesk_not_ready', 'no_keys', + 'max_minutes', 'no_connection', 'disconnected', 'rollback', 'superseded', 'not_enabled', 'stop_failed', +] as const; + +const EVENT_NEEDS_GRANT: ReadonlySet = new Set(['applied', 'failed', 'connected', 'ended']); + +export const ReportBody = z.strictObject({ + rustdeskId: z.string().regex(/^[0-9]{6,15}$/), + agentSecret: z.string().min(16).max(128), + event: z.enum(REPORT_EVENTS), + grantId: z.string().regex(GRANT_ID_RE).optional(), + outcome: z.string().regex(/^[a-z_]{1,40}$/).optional(), + keys: z.array(z.enum(REPORT_KEYS)).max(REPORT_KEYS.length).optional(), +}).superRefine((b, ctx) => { + if (EVENT_NEEDS_GRANT.has(b.event) !== (b.grantId !== undefined)) ctx.addIssue({ code: 'custom', message: 'grantId' }); +}); +export type Report = z.infer; + +/** A grant to a managed computer may never exceed MANAGED_CEILING. */ +export function withinCeiling(mode: GrantMode, permissions: GrantPermissions): boolean { + if (mode === 'control' && MANAGED_CEILING.mode !== 'control') return false; + return (Object.keys(permissions) as (keyof GrantPermissions)[]).every((k) => !permissions[k] || MANAGED_CEILING.permissions[k]); +} + +/** + * Whether the portal may hand this computer a staged legacy password + * rotation now. A managed computer's RustDesk password is the agent's: a + * rotation would put a password the portal knows back on it. Held while any + * managed row exists, except Managed (pending) with no grant in flight, + * where Legacy still works and the rotation re-establishes it after a test + * session ended with a password nobody is told. + */ +export function rotationHeld(row: { state: ManagedState } | null, grantInFlight: boolean): boolean { + if (!row) return false; + return row.state !== 'pending' || grantInFlight; +} + +/** Legacy Connect and password reveal are refused once a computer was verified (its password is one nobody is told). */ +export function legacyRefused(row: { verifiedAt: Date | null } | null): boolean { + return !!row?.verifiedAt; +} + +export const LEGACY_REFUSED_MESSAGE = + 'This computer is in Managed Secure Access: its RustDesk password is one nobody is told. Connecting to a managed computer is the next build step; until then roll it back to Legacy to connect.'; diff --git a/apps/api/src/msa/msa-grant.controller.ts b/apps/api/src/msa/msa-grant.controller.ts index 2699148f..adcf6918 100644 --- a/apps/api/src/msa/msa-grant.controller.ts +++ b/apps/api/src/msa/msa-grant.controller.ts @@ -13,6 +13,7 @@ import { CAP } from '../rbac/capabilities'; import { StepUpService } from '../auth/step-up.service'; import { assertFresh } from '../security-controls/review'; import { MsaGrantService } from './msa-grant.service'; +import { MsaManagedService } from './msa-managed.service'; /** * Managed Secure Access grants (0.71, build step 3), console side. Every @@ -35,13 +36,23 @@ export class MsaGrantsController { return { success: true, data: await this.grants.issueTest(a, endpointId, body) }; } - /** The grant public keys (what step 4 publishes in the signed release metadata). Platform Admin. */ + /** The grant public keys, whether each is in the signed release metadata, and the owner's commands to publish it. Platform Admin. */ @Get('keys') @UseGuards(PlatformAdminGuard) async keys() { return { success: true, data: await this.grants.publicKeys() }; } + /** 0.72: make the grant key now, so it can be published before a cutover. Platform Admin, a fresh confirmation (msa.grant). */ + @Post('keys') + @UseGuards(PlatformAdminGuard) + @RateLimit(10) + async ensureKey(@Actor() a: ActorContext, @Req() req: Request) { + const u = req.user as { sub?: string; iat?: number } | undefined; + assertFresh(u?.sub ? this.stepUp.read(req, u.sub, u.iat)?.method ?? null : null, { action: 'msa.grant', message: 'Confirm it is you to make the grant key.' }); + return { success: true, data: await this.grants.ensureKey(a) }; + } + /** A computer's recent grants: no envelope, no password. View computers, in scope. */ @Get('endpoint/:endpointId') @RequireCapability(CAP.COMPUTERS_VIEW) @@ -66,7 +77,7 @@ export class MsaPollDto { */ @Controller('msa/agent') export class MsaAgentController { - constructor(private readonly grants: MsaGrantService) {} + constructor(private readonly grants: MsaGrantService, private readonly managed: MsaManagedService) {} @Post('poll') @Public() @@ -75,4 +86,18 @@ export class MsaAgentController { async poll(@Body() dto: MsaPollDto) { return { success: true, data: await this.grants.poll(dto) }; } + + /** + * 0.72: what a managed computer's signed agent did — applied, failed, + * connected, ended, drift, checked, secured, restored, restore_failed. + * Public, but the device secret is checked before anything else is read + * (after a strict parse: events, closed codes and key names only). + */ + @Post('report') + @Public() + @RateLimit(120) + @HttpCode(HttpStatus.OK) + async report(@Body() body: unknown) { + return { success: true, data: await this.managed.report(body) }; + } } diff --git a/apps/api/src/msa/msa-grant.service.ts b/apps/api/src/msa/msa-grant.service.ts index 98638b4e..26e0ced1 100644 --- a/apps/api/src/msa/msa-grant.service.ts +++ b/apps/api/src/msa/msa-grant.service.ts @@ -16,6 +16,9 @@ import { type Envelope, type Grant, } from './grant'; import { msaGrantsEnabled, MSA_NOT_ENABLED } from './msa-grants-flag'; +import { withinCeiling, type ManagedState } from './managed'; +import { UpdateTrustService } from '../update-trust/update-trust.service'; +import { MSA_GRANT_KEY_ADD_COMMAND, MSA_GRANT_KEY_PUBLISH_COMMAND } from './grant-key-commands'; /** How long a poll is held when nothing is waiting. Under the 30 s most proxies allow. */ export const POLL_HOLD_MS_DEFAULT = 25_000; @@ -73,6 +76,7 @@ export class MsaGrantService implements OnModuleDestroy { private readonly audit: AuditService, private readonly acl: AccessControlService, private readonly enrollment: EnrollmentService, + private readonly updateTrust: UpdateTrustService, config: ConfigService, ) { this.encKey = config.get('ENCRYPTION_KEY'); @@ -128,11 +132,45 @@ export class MsaGrantService implements OnModuleDestroy { return { keyId: k.keyId, privatePem: k.privatePem }; } - /** Public keys only: what step 4 will publish in the signed release metadata. Platform Admin. */ + /** + * Public keys only, and whether each is in the signed release metadata + * the agents verify (msa/grant-keys.json, read as served — the agent + * verifies it itself). For a key not yet published, the two commands the + * owner runs on the release host (§56: text the portal shows, never runs). + * Platform Admin. + */ async publicKeys() { this.assertEnabled(); const rows = await this.prisma.msaGrantKey.findMany({ orderBy: { createdAt: 'desc' }, select: { keyId: true, publicKey: true, createdAt: true, retiredAt: true } }); - return rows.map((r) => ({ keyId: r.keyId, algorithm: 'ed25519', publicKey: r.publicKey, createdAt: r.createdAt, retiredAt: r.retiredAt, active: r.retiredAt === null })); + const published = new Set(this.updateTrust.publishedMsaGrantKeyIds()); + return rows.map((r) => ({ + keyId: r.keyId, algorithm: 'ed25519', publicKey: r.publicKey, createdAt: r.createdAt, retiredAt: r.retiredAt, active: r.retiredAt === null, + published: published.has(r.keyId), + commands: r.retiredAt === null && !published.has(r.keyId) + ? [`${MSA_GRANT_KEY_ADD_COMMAND} --key-id ${r.keyId} --public-key ${r.publicKey}`, MSA_GRANT_KEY_PUBLISH_COMMAND] + : [], + })); + } + + /** + * 0.72: make the grant key now (Platform Admin, a fresh confirmation, + * msa.grant), so it can be published before any computer is cut over. + * Returns the active key's public half; an existing key is returned as is. + */ + async ensureKey(actor: ActorContext) { + this.assertEnabled(); + const k = await this.activeKey(actor); + await this.audit.log({ + action: 'MSA_GRANT_KEY_ENSURED', actorId: actor.userId, actorIp: actor.ip, resource: 'msa_grant_key', resourceId: k.keyId, meta: { keyId: k.keyId }, + }); + return (await this.publicKeys()).find((x) => x.keyId === k.keyId); + } + + /** 0.72: the active key id, when it is in the published signed metadata; else null. */ + async activePublishedKeyId(): Promise { + this.assertEnabled(); + const row = await this.prisma.msaGrantKey.findFirst({ where: { retiredAt: null }, select: { keyId: true } }); + return row && this.updateTrust.publishedMsaGrantKeyIds().includes(row.keyId) ? row.keyId : null; } // ── Issuing ─────────────────────────────────────────────────────────────── @@ -177,6 +215,20 @@ export class MsaGrantService implements OnModuleDestroy { const pause = await activePause(this.prisma, 'remote', ep.customerId); if (pause) throw new ForbiddenException({ code: 'CONTAINED', message: 'Remote connections are paused for this computer: no grant was issued.', pauseId: pause.id, scope: pause.scope.toLowerCase() }); + // 0.72: a managed computer's agent ACTS on a grant. It may not exceed the + // managed ceiling (view-only, nothing beyond), not while it rolls back, + // and not under a key the agents cannot verify. + const managed = await this.prisma.msaManagedComputer.findUnique({ where: { endpointId: ep.id }, select: { state: true } }); + if (managed) { + if ((managed.state as ManagedState) === 'rollback_pending') throw new ConflictException({ code: 'MSA_ROLLBACK_PENDING', message: 'This computer is rolling back to Legacy: no grant was issued.' }); + const perms = { + clipboard: b.permissions?.clipboard ?? false, files: b.permissions?.files ?? false, audio: b.permissions?.audio ?? false, + tunnel: b.permissions?.tunnel ?? false, restart: b.permissions?.restart ?? false, + }; + if (!withinCeiling(b.mode ?? 'view', perms)) throw new ConflictException({ code: 'MSA_ABOVE_CEILING', message: 'A managed computer allows view-only sessions with nothing beyond in this release: no grant was issued.' }); + if (!(await this.activePublishedKeyId())) throw new ConflictException({ code: 'MSA_GRANT_KEY_NOT_PUBLISHED', message: 'The grant key is not in the signed release metadata yet, so the agent would refuse the grant: no grant was issued.' }); + } + const key = await this.activeKey(actor); const nb = Math.floor(now / 1000) * 1000; const grant: Grant = { @@ -197,7 +249,7 @@ export class MsaGrantService implements OnModuleDestroy { await this.audit.logOrFail({ action: 'MSA_GRANT_ISSUED', actorId: actor.userId, actorIp: actor.ip, tenantId: ep.tenantId ?? undefined, customerId: ep.customerId ?? undefined, resource: 'endpoint', resourceId: ep.id, - meta: { grantId: grant.grantId, endpointId: ep.id, mode: grant.mode, consent: grant.consent, keyId: key.keyId, source: 'test' }, + meta: { grantId: grant.grantId, endpointId: ep.id, mode: grant.mode, consent: grant.consent, keyId: key.keyId, source: 'test', managed: !!managed }, }); await this.prisma.$transaction([ // A newer grant replaces any earlier one not yet delivered to this computer. @@ -239,6 +291,7 @@ export class MsaGrantService implements OnModuleDestroy { select: { id: true, endpointId: true, technicianId: true, keyId: true, mode: true, permissions: true, consent: true, notBefore: true, notAfter: true, maxMinutes: true, idleMinutes: true, state: true, deliveredAt: true, createdAt: true, + appliedAt: true, connectedAt: true, endedAt: true, outcome: true, failedKeys: true, revealedAt: true, }, }); return rows.map(({ id, ...r }) => ({ grantId: id, ...r })); @@ -279,10 +332,18 @@ export class MsaGrantService implements OnModuleDestroy { })).count : 0; + // 0.72: the computer's managed state rides on every answer. The agent + // runs only while it has one, and rolls back when it says so. + const managedNow = async () => { + const m = await this.prisma.msaManagedComputer.findUnique({ where: { endpointId: ep.id }, select: { state: true } }); + return m ? { state: m.state as ManagedState, rollback: m.state === 'rollback_pending' } : null; + }; const answer = async () => { const t = Date.now(); await this.expireDue(ep.id, t); if (await activePause(this.prisma, 'remote', ep.customerId)) return { grants: [] as Envelope[], paused: true }; + // Nothing is handed to a computer that is rolling back. + if ((await managedNow())?.rollback) return { grants: [] as Envelope[], paused: false }; const rows = await this.prisma.msaGrant.findMany({ where: { endpointId: ep.id, state: 'issued', notAfter: { gte: new Date(t) } }, orderBy: [{ createdAt: 'asc' }, { id: 'asc' }], take: POLL_MAX_GRANTS, select: { id: true, envelopeEnc: true }, @@ -299,9 +360,11 @@ export class MsaGrantService implements OnModuleDestroy { }; let out = await answer(); - if (out.grants.length || out.paused || dto.wait === false) return { ...out, acked, holdMs: 0 }; + const managed = await managedNow(); + // A computer rolling back is answered at once. + if (out.grants.length || out.paused || dto.wait === false || managed?.rollback) return { ...out, acked, holdMs: 0, endpointId: ep.id, managed }; - if (!this.waiters.has(ep.id) && this.waiters.size >= this.maxPolls) return { ...out, acked, holdMs: 0, retryAfterMs: 5_000 }; + if (!this.waiters.has(ep.id) && this.waiters.size >= this.maxPolls) return { ...out, acked, holdMs: 0, retryAfterMs: 5_000, endpointId: ep.id, managed }; this.waiters.get(ep.id)?.wake('superseded'); const started = Date.now(); const why = await new Promise<'grant' | 'superseded' | 'shutdown' | 'timeout'>((resolve) => { @@ -324,8 +387,47 @@ export class MsaGrantService implements OnModuleDestroy { this.waiters.set(ep.id, me); }); // A superseded poll hands nothing over: grants go only to the newest poll. - if (why === 'superseded') return { grants: [], paused: false, acked, holdMs: Date.now() - started, superseded: true }; + if (why === 'superseded') return { grants: [], paused: false, acked, holdMs: Date.now() - started, superseded: true, endpointId: ep.id, managed: await managedNow() }; out = await answer(); - return { ...out, acked, holdMs: Date.now() - started }; + return { ...out, acked, holdMs: Date.now() - started, endpointId: ep.id, managed: await managedNow() }; + } + + /** 0.72: wake a held poll for this computer (its managed state changed: confirmed, rolled back). */ + wake(endpointId: string) { + this.waiters.get(endpointId)?.wake('grant'); + } + + /** + * 0.72: the managed test session's one-time password, shown ONCE to the + * Platform Admin (a fresh confirmation, msa.reveal, in the controller). + * Only for a grant the agent reported applied, not ended, on a computer + * this person can see. The reveal is audited first (logOrFail, ids only), + * then claimed by one conditional write, and only then is the password + * opened. It is never shown again. + */ + async reveal(actor: ActorContext, grantId: string) { + this.assertEnabled(); + if (!GRANT_ID_RE.test(grantId)) throw new NotFoundException('Grant not found'); + const g = await this.prisma.msaGrant.findUnique({ where: { id: grantId }, select: { id: true, endpointId: true, state: true, revealedAt: true } }); + if (!g) throw new NotFoundException('Grant not found'); + await this.acl.assertEndpointInScope(actor, g.endpointId, 'computers:view'); + const ep = await this.prisma.endpoint.findFirst({ where: { AND: [{ id: g.endpointId }, this.acl.endpointVisibilityWhere(actor)] }, select: { id: true, tenantId: true, customerId: true } }); + if (!ep) throw new NotFoundException('Grant not found'); + if (g.state !== 'applied') throw new ConflictException({ code: 'MSA_GRANT_NOT_APPLIED', message: 'The agent has not reported this grant applied (or its session ended): there is no password to show.' }); + if (g.revealedAt) throw new ConflictException({ code: 'MSA_PASSWORD_ALREADY_REVEALED', message: 'This one-time password was already shown once. Send a new test grant.' }); + await this.audit.logOrFail({ + action: 'MSA_PASSWORD_REVEALED', actorId: actor.userId, actorIp: actor.ip, tenantId: ep.tenantId ?? undefined, customerId: ep.customerId ?? undefined, + resource: 'endpoint', resourceId: ep.id, meta: { grantId: g.id, endpointId: ep.id }, + }); + const claimed = await this.prisma.msaGrant.updateMany({ + where: { id: g.id, state: 'applied', revealedAt: null }, data: { revealedAt: new Date(), revealedById: actor.userId }, + }); + if (claimed.count !== 1) throw new ConflictException({ code: 'MSA_PASSWORD_ALREADY_REVEALED', message: 'This one-time password was already shown once. Send a new test grant.' }); + const row = await this.prisma.msaGrant.findUnique({ where: { id: g.id }, select: { passwordEnc: true } }); + try { + return { grantId: g.id, oneTimePassword: openSecret(this.encKey, 'rem0te-msa-grant-pw-v1', row!.passwordEnc), shownOnce: true }; + } catch { + throw new ServiceUnavailableException({ code: 'MSA_GRANT_KEY_UNAVAILABLE', message: 'The password could not be opened (ENCRYPTION_KEY changed?).' }); + } } } diff --git a/apps/api/src/msa/msa-grants.module.ts b/apps/api/src/msa/msa-grants.module.ts index 643bbd29..f278c667 100644 --- a/apps/api/src/msa/msa-grants.module.ts +++ b/apps/api/src/msa/msa-grants.module.ts @@ -1,22 +1,26 @@ import { Module, type MiddlewareConsumer, type NestModule } from '@nestjs/common'; import { RbacModule } from '../rbac/rbac.module'; import { EnrollmentModule } from '../enrollment/enrollment.module'; +import { EndpointsModule } from '../endpoints/endpoints.module'; import { MsaAgentController, MsaGrantsController } from './msa-grant.controller'; +import { MsaManagedController } from './msa-managed.controller'; import { MsaGrantService } from './msa-grant.service'; +import { MsaManagedService } from './msa-managed.service'; import { MsaGrantsGate } from './msa-grants-flag'; /** * Managed Secure Access grants and the long-poll channel (0.71, build step - * 3), behind MSA_GRANTS, off. Not exported: nothing outside this module — - * Connect included — can issue a grant (§81). + * 3) and cutover, enforcement reports and rollback (0.72, step 4), behind + * MSA_GRANTS, off. Not exported: nothing outside this module — Connect + * included — can issue a grant or move a computer (§81, §82). */ @Module({ - imports: [RbacModule, EnrollmentModule], - controllers: [MsaGrantsController, MsaAgentController], - providers: [MsaGrantService], + imports: [RbacModule, EnrollmentModule, EndpointsModule], + controllers: [MsaGrantsController, MsaAgentController, MsaManagedController], + providers: [MsaGrantService, MsaManagedService], }) export class MsaGrantsModule implements NestModule { configure(consumer: MiddlewareConsumer) { - consumer.apply(MsaGrantsGate).forRoutes(MsaGrantsController, MsaAgentController); + consumer.apply(MsaGrantsGate).forRoutes(MsaGrantsController, MsaAgentController, MsaManagedController); } } diff --git a/apps/api/src/msa/msa-managed.controller.ts b/apps/api/src/msa/msa-managed.controller.ts new file mode 100644 index 00000000..df73b467 --- /dev/null +++ b/apps/api/src/msa/msa-managed.controller.ts @@ -0,0 +1,81 @@ +import { Body, Controller, Get, HttpCode, HttpStatus, Param, Post, Req, UseGuards } from '@nestjs/common'; +import type { Request } from 'express'; +import { JwtAuthGuard } from '../common/guards/jwt-auth.guard'; +import { CapabilitiesGuard } from '../common/guards/capabilities.guard'; +import { PlatformAdminGuard } from '../common/guards/platform-admin.guard'; +import { RequireCapability } from '../common/decorators/require-capability.decorator'; +import { Actor } from '../common/decorators/actor.decorator'; +import { RateLimit } from '../common/throttling'; +import type { ActorContext } from '../rbac/access-control.service'; +import { CAP } from '../rbac/capabilities'; +import { StepUpService } from '../auth/step-up.service'; +import { assertFresh } from '../security-controls/review'; +import { MsaManagedService } from './msa-managed.service'; +import { MsaGrantService } from './msa-grant.service'; + +/** + * Managed Secure Access cutover, the managed test session and rollback + * (0.72, build step 4), console side. Behind MSA_GRANTS (MsaGrantsGate runs + * before anything else). Every change is a Platform Admin's, for ONE + * computer: there is no route for a group, a business or the fleet. + * + * - cutover and confirm need a fresh confirmation (msa.cutover); + * - revealing the one-time password needs one (msa.reveal), once; + * - rollback never does: it only reduces. + */ +@Controller('msa/managed') +@UseGuards(JwtAuthGuard, CapabilitiesGuard) +export class MsaManagedController { + constructor(private readonly managed: MsaManagedService, private readonly grants: MsaGrantService, private readonly stepUp: StepUpService) {} + + private method(req: Request): string | null { + const u = req.user as { sub?: string; iat?: number } | undefined; + return u?.sub ? this.stepUp.read(req, u.sub, u.iat)?.method ?? null : null; + } + + /** The device card's managed view. View computers, in scope. */ + @Get(':endpointId') + @RequireCapability(CAP.COMPUTERS_VIEW) + async view(@Actor() a: ActorContext, @Param('endpointId') endpointId: string) { + return { success: true, data: await this.managed.view(a, endpointId) }; + } + + /** Move ONE computer into Managed (pending). Platform Admin, a fresh confirmation (msa.cutover). */ + @Post(':endpointId/cutover') + @UseGuards(PlatformAdminGuard) + @RateLimit(20) + @HttpCode(HttpStatus.OK) + async cutover(@Actor() a: ActorContext, @Param('endpointId') endpointId: string, @Req() req: Request) { + assertFresh(this.method(req), { action: 'msa.cutover', message: 'Confirm it is you to move this computer into Managed Secure Access.' }); + return { success: true, data: await this.managed.cutover(a, endpointId) }; + } + + /** Confirm a Managed (pending) computer verified after its test session. Platform Admin, a fresh confirmation (msa.cutover). */ + @Post(':endpointId/confirm') + @UseGuards(PlatformAdminGuard) + @RateLimit(20) + @HttpCode(HttpStatus.OK) + async confirm(@Actor() a: ActorContext, @Param('endpointId') endpointId: string, @Req() req: Request) { + assertFresh(this.method(req), { action: 'msa.cutover', message: 'Confirm it is you to mark this computer managed and verified.' }); + return { success: true, data: await this.managed.confirm(a, endpointId) }; + } + + /** Roll ONE computer back to Legacy. Platform Admin; never a fresh confirmation (it only reduces). */ + @Post(':endpointId/rollback') + @UseGuards(PlatformAdminGuard) + @RateLimit(20) + @HttpCode(HttpStatus.OK) + async rollback(@Actor() a: ActorContext, @Param('endpointId') endpointId: string, @Body() body: { force?: unknown } | undefined) { + return { success: true, data: await this.managed.rollback(a, endpointId, body?.force === true) }; + } + + /** Show a managed test grant's one-time password, once. Platform Admin, a fresh confirmation (msa.reveal). */ + @Post('grants/:grantId/reveal') + @UseGuards(PlatformAdminGuard) + @RateLimit(10) + @HttpCode(HttpStatus.OK) + async reveal(@Actor() a: ActorContext, @Param('grantId') grantId: string, @Req() req: Request) { + assertFresh(this.method(req), { action: 'msa.reveal', message: 'Confirm it is you to see the one-time password.' }); + return { success: true, data: await this.grants.reveal(a, grantId) }; + } +} diff --git a/apps/api/src/msa/msa-managed.service.ts b/apps/api/src/msa/msa-managed.service.ts new file mode 100644 index 00000000..c7710b9c --- /dev/null +++ b/apps/api/src/msa/msa-managed.service.ts @@ -0,0 +1,344 @@ +import { BadRequestException, ConflictException, ForbiddenException, Injectable, Logger, NotFoundException } from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service'; +import { AuditService } from '../audit/audit.service'; +import { AccessControlService, type ActorContext } from '../rbac/access-control.service'; +import { EnrollmentService } from '../enrollment/enrollment.service'; +import { EndpointsService } from '../endpoints/endpoints.service'; +import { activePause } from '../containment/pause'; +import { runsSignedAgent } from '../common/agent-identity'; +import { isWindowsPlatform } from '../common/platform'; +import { assertAssigned } from '../common/unassigned'; +import { ENTITY_ID_RE } from './grant'; +import { MsaService } from './msa.service'; +import { MsaGrantService } from './msa-grant.service'; +import { msaGrantsEnabled, MSA_NOT_ENABLED } from './msa-grants-flag'; +import { compareVersion, MIN_ENFORCING_AGENT } from './readiness'; +import { MANAGED_CEILING, ReportBody, type ManagedState, type Report } from './managed'; + +/** The outcomes that mean the agent could not ENFORCE (as opposed to refusing a grant it should refuse). */ +const ENFORCEMENT_OUTCOMES = new Set(['readback_mismatch', 'password_not_applied', 'save_failed', 'stop_failed']); + +/** + * Managed Secure Access cutover, enforcement reports, the managed test + * session and rollback (0.72, build step 4), behind MSA_GRANTS. + * + * The only writer of MsaManagedComputer (§82). Every public method asserts + * the switch first. A computer moves only when a Platform Admin moves that + * ONE computer (cutover, confirm, rollback — the controller requires the + * Platform Admin and the fresh confirmations), or when its own signed agent + * reports what it did (report, device secret first). Nothing here moves a + * group, a business or the fleet, and nothing moves a computer by itself. + */ +@Injectable() +export class MsaManagedService { + private readonly logger = new Logger('MsaManaged'); + + constructor( + private readonly prisma: PrismaService, + private readonly audit: AuditService, + private readonly acl: AccessControlService, + private readonly enrollment: EnrollmentService, + private readonly endpoints: EndpointsService, + private readonly msa: MsaService, + private readonly grants: MsaGrantService, + ) {} + + private assertEnabled() { + if (!msaGrantsEnabled()) throw new NotFoundException({ code: MSA_NOT_ENABLED, message: 'Managed Secure Access grants are not enabled on this server.' }); + } + + /** A computer this person can see, assigned, Windows and the signed agent: the shared front of every console route. */ + private async computer(actor: ActorContext, endpointId: string) { + if (!ENTITY_ID_RE.test(endpointId)) throw new NotFoundException('Computer not found'); + await this.acl.assertEndpointInScope(actor, endpointId, 'computers:view'); + const ep = await this.prisma.endpoint.findFirst({ + where: { AND: [{ id: endpointId }, this.acl.endpointVisibilityWhere(actor)] }, + select: { id: true, tenantId: true, customerId: true, platform: true, updateChannel: true, signedSeenAt: true }, + }); + if (!ep) throw new NotFoundException('Computer not found'); + return ep; + } + + private row(endpointId: string) { + return this.prisma.msaManagedComputer.findUnique({ where: { endpointId } }); + } + + // ── Reading ─────────────────────────────────────────────────────────────── + + /** + * The device card's managed view (View computers, in scope): the managed + * state, the latest grants (never a password or envelope), whether the + * grant key is published, and — when Legacy — whether cutover would be + * allowed and why not. The controls are a Platform Admin's; the card shows + * them only to one. + */ + async view(actor: ActorContext, endpointId: string) { + this.assertEnabled(); + const ep = await this.computer(actor, endpointId); + const row = await this.row(ep.id); + const grants = await this.grants.listForEndpoint(actor, ep.id); + const keyId = await this.grants.activePublishedKeyId(); + const blockers = row ? [] : await this.cutoverBlockers(ep); + return { + enabled: true, + endpointId: ep.id, + state: (row?.state ?? 'legacy') as ManagedState | 'legacy', + managed: row ? { + state: row.state, requestedAt: row.requestedAt, verifiedAt: row.verifiedAt, legacySecuredAt: row.legacySecuredAt, + failedAt: row.failedAt, failReason: row.failReason, failedKeys: row.failedKeys, rollbackRequestedAt: row.rollbackRequestedAt, + readbackOkAt: row.readbackOkAt, lastReportAt: row.lastReportAt, + } : null, + grants: grants.slice(0, 5), + grantKeyPublished: !!keyId, + ceiling: MANAGED_CEILING, + cutover: { allowed: !row && blockers.length === 0, blockers }, + canConfirm: !!row && row.state === 'pending' && (await this.testSessionConnected(ep.id, row.requestedAt)), + evidence: 'Managed Secure Access has run only in the Windows lab (Windows Server, no signed-in user, no live session): never on a Windows 10 or 11 desktop or on the fleet.', + }; + } + + /** Why cutover would be refused now, as codes with sentences. Empty means allowed. */ + private async cutoverBlockers(ep: { id: string; customerId: string | null; tenantId: string | null; platform: string | null; updateChannel: string | null; signedSeenAt: Date | null }) { + const out: { code: string; message: string }[] = []; + if (!ep.customerId || !ep.tenantId) out.push({ code: 'ENDPOINT_UNASSIGNED', message: 'The computer is in the unassigned pool.' }); + if (!isWindowsPlatform(ep.platform) || !runsSignedAgent({ updateChannel: ep.updateChannel, signedSeenAt: ep.signedSeenAt })) { + out.push({ code: 'MSA_SIGNED_AGENT_REQUIRED', message: 'Managed Secure Access needs a Windows computer running the signed agent.' }); + } + const pr = await this.msa.preflightReadiness(ep.id); + if (!pr || pr.readiness.state !== 'compatible') { + out.push({ code: 'MSA_NOT_COMPATIBLE', message: `Readiness is ${pr?.readiness.label ?? 'unknown'}, not Compatible.` }); + } + const v = compareVersion(pr?.agentVersion ?? null, MIN_ENFORCING_AGENT); + if (v === null || v < 0) out.push({ code: 'MSA_AGENT_TOO_OLD', message: `The signed agent must be ${MIN_ENFORCING_AGENT} or later to enforce a grant.` }); + if (ep.customerId && (await activePause(this.prisma, 'remote', ep.customerId))) out.push({ code: 'CONTAINED', message: 'Remote connections are paused for this computer.' }); + if (!(await this.grants.activePublishedKeyId())) { + out.push({ code: 'MSA_GRANT_KEY_NOT_PUBLISHED', message: 'The grant key is not in the signed release metadata yet (Settings shows the two commands to run on the release host).' }); + } + return out; + } + + private async testSessionConnected(endpointId: string, since: Date) { + return (await this.prisma.msaGrant.count({ + where: { endpointId, createdAt: { gte: since }, connectedAt: { not: null }, state: { in: ['applied', 'ended'] } }, + })) > 0; + } + + // ── Cutover, confirmation, rollback (Platform Admin, one computer) ──────── + + /** + * Move ONE computer from Legacy into Managed (pending). The controller has + * required a Platform Admin and a fresh confirmation (msa.cutover). Then: + * scope, every cutover blocker (pool, signed Windows agent, readiness + * Compatible, an enforcing agent, no `remote` pause, a published grant + * key), not already managed, the audit row (logOrFail), the row. Nothing + * changes on the computer yet: Legacy keeps working until a test session + * succeeds and a Platform Admin confirms it. + */ + async cutover(actor: ActorContext, endpointId: string) { + this.assertEnabled(); + const ep = await this.computer(actor, endpointId); + assertAssigned(ep); + if (await this.row(ep.id)) throw new ConflictException({ code: 'MSA_ALREADY_MANAGED', message: 'This computer is already in Managed Secure Access.' }); + const blockers = await this.cutoverBlockers(ep); + if (blockers.length) { + const first = blockers[0]; + if (first.code === 'CONTAINED') throw new ForbiddenException({ code: 'CONTAINED', message: `${first.message} Nothing was changed.` }); + throw new ConflictException({ code: first.code, message: `${first.message} Nothing was changed.`, blockers }); + } + await this.audit.logOrFail({ + action: 'MSA_CUTOVER', actorId: actor.userId, actorIp: actor.ip, tenantId: ep.tenantId ?? undefined, customerId: ep.customerId ?? undefined, + resource: 'endpoint', resourceId: ep.id, meta: { endpointId: ep.id, before: 'legacy', after: 'pending' }, + }); + try { + await this.prisma.msaManagedComputer.create({ data: { endpointId: ep.id, state: 'pending', requestedById: actor.userId } }); + } catch { + throw new ConflictException({ code: 'MSA_ALREADY_MANAGED', message: 'This computer is already in Managed Secure Access.' }); + } + return this.view(actor, ep.id); + } + + /** + * Confirm a Managed (pending) computer verified: only after a managed test + * session on it since cutover was applied (every setting read back) AND + * the agent saw a RustDesk connection. Platform Admin, fresh confirmation + * (msa.cutover), audited. The agent, told `verified` on its next poll, + * replaces the legacy permanent password with one nobody is told and + * reports `secured`; from then on legacy Connect and Reveal refuse it. + */ + async confirm(actor: ActorContext, endpointId: string) { + this.assertEnabled(); + const ep = await this.computer(actor, endpointId); + const row = await this.row(ep.id); + if (!row) throw new ConflictException({ code: 'MSA_NOT_MANAGED', message: 'This computer is in Legacy mode.' }); + if (row.state !== 'pending') throw new ConflictException({ code: 'MSA_NOT_PENDING', message: 'Only a computer in Managed (pending) can be confirmed.' }); + if (!row.readbackOkAt || !(await this.testSessionConnected(ep.id, row.requestedAt))) { + throw new ConflictException({ code: 'MSA_NO_TEST_SESSION', message: 'Confirm only after a managed test session: a test grant the agent applied and read back, and a RustDesk connection it saw.' }); + } + await this.audit.logOrFail({ + action: 'MSA_VERIFIED', actorId: actor.userId, actorIp: actor.ip, tenantId: ep.tenantId ?? undefined, customerId: ep.customerId ?? undefined, + resource: 'endpoint', resourceId: ep.id, meta: { endpointId: ep.id, before: 'pending', after: 'verified' }, + }); + const moved = await this.prisma.msaManagedComputer.updateMany({ + where: { endpointId: ep.id, state: 'pending' }, data: { state: 'verified', verifiedAt: new Date(), verifiedById: actor.userId }, + }); + if (moved.count !== 1) throw new ConflictException({ code: 'MSA_NOT_PENDING', message: 'Only a computer in Managed (pending) can be confirmed.' }); + this.grants.wake(ep.id); + return this.view(actor, ep.id); + } + + /** + * Roll ONE computer back to Legacy. Platform Admin, never a fresh + * confirmation: it only reduces what Managed Secure Access holds. It stages + * a fresh sealed permanent password through the existing rotation path + * (held by the heartbeat until the agent has restored RustDesk's settings), + * cancels grants not yet delivered, and tells the agent to end any session + * and restore the settings it saved before its first apply. The row goes + * when the agent reports `restored`. With `force`, a computer already + * rolling back is returned to Legacy without the agent (it may never + * report again); its RustDesk keeps whatever settings it has, and the + * staged rotation gives the portal a password that works. + */ + async rollback(actor: ActorContext, endpointId: string, force: boolean) { + this.assertEnabled(); + const ep = await this.computer(actor, endpointId); + const row = await this.row(ep.id); + if (!row) throw new ConflictException({ code: 'MSA_NOT_MANAGED', message: 'This computer is already in Legacy mode.' }); + const base = { actorId: actor.userId, actorIp: actor.ip, tenantId: ep.tenantId ?? undefined, customerId: ep.customerId ?? undefined, resource: 'endpoint', resourceId: ep.id }; + if (row.state === 'rollback_pending') { + if (!force) throw new ConflictException({ code: 'MSA_ROLLBACK_PENDING', message: 'This computer is already rolling back; it finishes when the agent reports. Force it only if the agent will not report again.' }); + await this.audit.logOrFail({ ...base, action: 'MSA_ROLLED_BACK', meta: { endpointId: ep.id, before: 'rollback_pending', after: 'legacy', forced: true } }); + await this.prisma.msaManagedComputer.deleteMany({ where: { endpointId: ep.id, state: 'rollback_pending' } }); + return this.view(actor, ep.id); + } + await this.audit.logOrFail({ ...base, action: 'MSA_ROLLBACK_REQUESTED', meta: { endpointId: ep.id, before: row.state, after: 'rollback_pending' } }); + const moved = await this.prisma.msaManagedComputer.updateMany({ + where: { endpointId: ep.id, state: row.state }, data: { state: 'rollback_pending', rollbackRequestedAt: new Date(), rollbackRequestedById: actor.userId }, + }); + if (moved.count !== 1) throw new ConflictException({ code: 'MSA_STATE_CHANGED', message: 'The computer\'s managed state changed meanwhile. Reload and try again.' }); + await this.prisma.msaGrant.updateMany({ where: { endpointId: ep.id, state: 'issued' }, data: { state: 'cancelled' } }); + await this.endpoints.stageRotationForMsa(ep.id, actor.userId, 'msa_rollback'); + this.grants.wake(ep.id); + return this.view(actor, ep.id); + } + + // ── The agent's reports ─────────────────────────────────────────────────── + + /** + * One report from a managed computer's signed agent: the device secret + * first, then only the signed Windows agent of an assigned computer, as + * for the poll. A report about a grant moves only that computer's own + * grant, from the state it must be in (conditional writes: a repeat + * changes nothing). Nothing reported is text: an event, a closed outcome + * code and closed key names. Never a password. + */ + async report(raw: unknown) { + this.assertEnabled(); + const p = ReportBody.safeParse(raw); + if (!p.success) throw new BadRequestException({ code: 'MSA_REPORT_INVALID', message: 'The report is not valid.' }); + const r = p.data; + const dev = await this.enrollment.authenticateDevice(r.rustdeskId, r.agentSecret, 'msa_report_unauthenticated'); + const ep = await this.prisma.endpoint.findUnique({ + where: { id: dev.endpointId }, + select: { id: true, tenantId: true, customerId: true, platform: true, updateChannel: true, signedSeenAt: true }, + }); + if (!ep) throw new NotFoundException('This device is not attached to a computer'); + if (!isWindowsPlatform(ep.platform) || !runsSignedAgent({ updateChannel: ep.updateChannel, signedSeenAt: ep.signedSeenAt })) { + throw new ForbiddenException({ code: 'MSA_SIGNED_AGENT_REQUIRED', message: 'Only the signed Windows agent may report.' }); + } + assertAssigned(ep); + const now = new Date(); + const row = await this.row(ep.id); + const recorded = await this.apply(ep, row, r, now); + if (row) await this.prisma.msaManagedComputer.updateMany({ where: { endpointId: ep.id }, data: { lastReportAt: now } }); + return { recorded }; + } + + private async apply(ep: { id: string; tenantId: string | null; customerId: string | null }, row: Awaited>, r: Report, now: Date): Promise { + const base = { tenantId: ep.tenantId ?? undefined, customerId: ep.customerId ?? undefined, resource: 'endpoint', resourceId: ep.id }; + const keys = [...new Set(r.keys ?? [])]; + const outcome = r.outcome ?? null; + const g = (states: string[]) => ({ id: r.grantId, endpointId: ep.id, state: { in: states } }); + switch (r.event) { + case 'applied': { + const n = (await this.prisma.msaGrant.updateMany({ where: g(['delivered']), data: { state: 'applied', appliedAt: now } })).count + + (await this.prisma.msaGrant.updateMany({ where: g(['issued']), data: { state: 'applied', appliedAt: now, deliveredAt: now } })).count; + if (!n) return false; + if (row && row.state !== 'rollback_pending') { + const back: ManagedState = row.verifiedAt ? 'verified' : 'pending'; + await this.prisma.msaManagedComputer.updateMany({ + where: { endpointId: ep.id, state: { not: 'rollback_pending' } }, + data: { state: back, readbackOkAt: now, failedAt: null, failReason: null, failedKeys: [] }, + }); + } + await this.audit.log({ ...base, action: 'MSA_GRANT_APPLIED', meta: { grantId: r.grantId, endpointId: ep.id } }); + return true; + } + case 'failed': { + const code = outcome ?? 'readback_mismatch'; + const n = (await this.prisma.msaGrant.updateMany({ where: g(['delivered', 'applied']), data: { state: 'failed', outcome: code, failedKeys: keys } })).count + + (await this.prisma.msaGrant.updateMany({ where: g(['issued']), data: { state: 'failed', outcome: code, failedKeys: keys, deliveredAt: now } })).count; + if (!n) return false; + await this.audit.log({ ...base, action: 'MSA_GRANT_FAILED', meta: { grantId: r.grantId, endpointId: ep.id, outcome: code, keys } }); + if (row && ENFORCEMENT_OUTCOMES.has(code)) await this.failure(ep, row, code, keys, now); + return true; + } + case 'connected': { + const n = (await this.prisma.msaGrant.updateMany({ where: { ...g(['applied']), connectedAt: null }, data: { connectedAt: now } })).count; + if (n) await this.audit.log({ ...base, action: 'MSA_SESSION_CONNECTED', meta: { grantId: r.grantId, endpointId: ep.id } }); + return n > 0; + } + case 'ended': { + const n = (await this.prisma.msaGrant.updateMany({ where: g(['applied', 'delivered']), data: { state: 'ended', endedAt: now, outcome: outcome ?? 'max_minutes' } })).count; + if (!n) return false; + await this.audit.log({ ...base, action: 'MSA_SESSION_ENDED', meta: { grantId: r.grantId, endpointId: ep.id, outcome: outcome ?? 'max_minutes' } }); + // Still pending: Legacy must keep working, and the agent just set a + // password nobody is told. Re-establish one through the rotation path + // (the heartbeat hands it over once no grant is in flight). + if (row && !row.verifiedAt && row.state !== 'rollback_pending') await this.endpoints.stageRotationForMsa(ep.id, null, 'msa_session_ended'); + return true; + } + case 'drift': { + if (!row) return false; + await this.failure(ep, row, 'drift', keys, now); + return true; + } + case 'checked': { + if (!row || row.state === 'enforcement_failure' || row.state === 'rollback_pending') return false; + await this.prisma.msaManagedComputer.updateMany({ where: { endpointId: ep.id, state: row.state }, data: { readbackOkAt: now } }); + return true; + } + case 'secured': { + if (!row?.verifiedAt) return false; + const n = (await this.prisma.msaManagedComputer.updateMany({ where: { endpointId: ep.id, verifiedAt: { not: null }, legacySecuredAt: null }, data: { legacySecuredAt: now } })).count; + if (n) await this.audit.log({ ...base, action: 'MSA_LEGACY_SECURED', meta: { endpointId: ep.id } }); + return n > 0; + } + case 'restored': { + if (row?.state !== 'rollback_pending') return false; + const n = (await this.prisma.msaManagedComputer.deleteMany({ where: { endpointId: ep.id, state: 'rollback_pending' } })).count; + if (n) await this.audit.log({ ...base, action: 'MSA_ROLLED_BACK', meta: { endpointId: ep.id, before: 'rollback_pending', after: 'legacy', forced: false } }); + return n > 0; + } + case 'restore_failed': { + if (row?.state !== 'rollback_pending') return false; + await this.prisma.msaManagedComputer.updateMany({ where: { endpointId: ep.id, state: 'rollback_pending' }, data: { failedAt: now, failReason: 'restore_failed', failedKeys: keys } }); + await this.audit.log({ ...base, action: 'MSA_ENFORCEMENT_FAILURE', meta: { endpointId: ep.id, reason: 'restore_failed', keys } }); + return true; + } + } + return false; + } + + private async failure(ep: { id: string; tenantId: string | null; customerId: string | null }, row: { state: string }, reason: string, keys: string[], now: Date) { + if (row.state === 'rollback_pending') return; + await this.prisma.msaManagedComputer.updateMany({ + where: { endpointId: ep.id, state: { not: 'rollback_pending' } }, + data: { state: 'enforcement_failure', failedAt: now, failReason: reason, failedKeys: keys }, + }); + await this.audit.log({ + tenantId: ep.tenantId ?? undefined, customerId: ep.customerId ?? undefined, resource: 'endpoint', resourceId: ep.id, + action: 'MSA_ENFORCEMENT_FAILURE', meta: { endpointId: ep.id, reason, keys }, + }); + this.logger.warn(`Managed Secure Access enforcement failure on ${ep.id}: ${reason}`); + } +} diff --git a/apps/api/src/msa/msa.service.ts b/apps/api/src/msa/msa.service.ts index 4fb7f838..2ebbc2af 100644 --- a/apps/api/src/msa/msa.service.ts +++ b/apps/api/src/msa/msa.service.ts @@ -7,9 +7,11 @@ import type { ServedAgentBuild } from '../common/agent-version-view'; import { UpdateTrustService } from '../update-trust/update-trust.service'; import { parsePreflight, PREFLIGHT_KEYS } from './preflight'; import { - decideReadiness, LAB_TESTED_MAX, LAB_TESTED_MIN, LAB_TESTED_RUSTDESK, MIN_REPORTING_AGENT, PRODUCIBLE_STATES, - READINESS_FLEET_NOTE, READINESS_NOTE, STATE_LABEL, type ProducibleState, type Readiness, + decideReadiness, LAB_TESTED_MAX, LAB_TESTED_MIN, LAB_TESTED_RUSTDESK, MANAGED_NOTE, MIN_REPORTING_AGENT, PRODUCIBLE_STATES, + READINESS_FLEET_MANAGED_NOTE, READINESS_FLEET_NOTE, READINESS_NOTE, READINESS_STATES, STATE_LABEL, type ManagedFacts, type ProducibleState, type Readiness, } from './readiness'; +import { msaGrantsEnabled } from './msa-grants-flag'; +import { rotationHeld, type ManagedState } from './managed'; /** The fleet view's ceiling: the same as the Full agent page's. */ export const FLEET_MAX = 5000; @@ -19,6 +21,7 @@ const READ_SELECT = { id: true, name: true, hostname: true, platform: true, agentVersion: true, updateChannel: true, signedSeenAt: true, agentSha256: true, isOnline: true, lastSeenAt: true, customer: { select: { id: true, name: true } }, rustdeskPreflight: { select: { checkedAt: true, installed: true, expectedPath: true, version: true, build: true, service: true, cli: true, keysOk: true, keys: true } }, + msaManaged: { select: { state: true, requestedAt: true, verifiedAt: true, readbackOkAt: true, failReason: true, failedKeys: true } }, } satisfies Prisma.EndpointSelect; type ReadRow = Prisma.EndpointGetPayload<{ select: typeof READ_SELECT }>; @@ -71,8 +74,9 @@ export class MsaService { return p.checkedAt; } - private decide(r: ReadRow, now: number, served: ServedAgentBuild | null): Readiness { + private decide(r: ReadRow, now: number, served: ServedAgentBuild | null, withManaged = true): Readiness { return decideReadiness({ + managed: withManaged && r.msaManaged ? { ...r.msaManaged, state: r.msaManaged.state as ManagedFacts['state'] } : null, platform: r.platform, signedAgent: runsSignedAgent({ updateChannel: r.updateChannel, signedSeenAt: r.signedSeenAt }, new Date(now)), // 0.70.1: the version the console shows. A signed agent on the published @@ -98,12 +102,55 @@ export class MsaService { checkedAt: pf.checkedAt.toISOString(), installed: pf.installed, expectedPath: pf.expectedPath, version: pf.version, build: pf.build, service: pf.service, cli: pf.cli, keysOk: pf.keysOk, keysTotal: PREFLIGHT_KEYS.length, } : null, - note: READINESS_NOTE, + note: r.msaManaged ? MANAGED_NOTE : READINESS_NOTE, labTested: { versions: [...LAB_TESTED_RUSTDESK], min: LAB_TESTED_MIN, max: LAB_TESTED_MAX }, minAgent: MIN_REPORTING_AGENT, + // 0.72: whether the Managed Secure Access routes exist on this server + // (MSA_GRANTS on). The console asks /msa/managed/:id only when this is + // true, so with the switch off it makes no request to a gated route. + managedControls: msaGrantsEnabled(), }; } + /** + * 0.72: what the preflight alone says about a computer (never a managed + * state), and the agent version the console shows — the cutover gate. + * The caller has already scope-checked the computer. + */ + async preflightReadiness(endpointId: string, now = Date.now()): Promise<{ readiness: Readiness; agentVersion: string | null } | null> { + const r = await this.prisma.endpoint.findUnique({ where: { id: endpointId }, select: READ_SELECT }); + if (!r) return null; + const served = this.updateTrust.servedAgent(); + return { readiness: this.decide(r, now, served, false), agentVersion: this.updateTrust.agentVersionOf(r, served).label }; + } + + /** + * 0.72 (§82): whether the heartbeat tells this computer's signed agent to + * run the grant poller. Only with MSA_GRANTS on and the computer in a + * managed state; the caller has already decided the heartbeat is + * authenticated, signed and may act. With the switch off, no row is read. + */ + async pollWanted(endpointId: string): Promise { + if (!msaGrantsEnabled()) return false; + return !!(await this.prisma.msaManagedComputer.findUnique({ where: { endpointId }, select: { endpointId: true } })); + } + + /** 0.72 (§82): whether a staged legacy password rotation waits (msa/managed.ts rotationHeld). Read whatever the switch says: a row is a row. */ + async rotationHeld(endpointId: string): Promise { + const row = await this.prisma.msaManagedComputer.findUnique({ where: { endpointId }, select: { state: true } }); + if (!row) return false; + const inFlight = row.state === 'pending' + // In flight: handed out and still inside its start window, or applied + // within the longest session a grant allows (a session the agent never + // reported ending stops holding the rotation then). + ? (await this.prisma.msaGrant.count({ where: { endpointId, OR: [ + { state: { in: ['issued', 'delivered'] }, notAfter: { gte: new Date() } }, + { state: 'applied', appliedAt: { gte: new Date(Date.now() - 9 * 3_600_000) } }, + ] } })) > 0 + : true; + return rotationHeld({ state: row.state as ManagedState }, inFlight); + } + /** * The fleet: every computer this person can see (endpointVisibilityWhere, * optionally one business), with counts per state. Read-only. @@ -129,10 +176,17 @@ export class MsaService { state: d.state, label: d.label, reasons: d.reasons, rustdeskVersion: d.rustdeskVersion, checkedAt: d.checkedAt, labTested: d.labTested, }; }); + // 0.72: with MSA_GRANTS off nothing can be moved into Managed, so the + // console shows the four readiness states only — plus a managed state + // that some computer is actually in (a row left from a test server), + // never an empty "Managed" tile that suggests it is available. + const on = msaGrantsEnabled(); + const shown = PRODUCIBLE_STATES.filter((s) => on || (READINESS_STATES as readonly string[]).includes(s) || counts[s] > 0); return { - note: READINESS_FLEET_NOTE, + note: on ? READINESS_FLEET_MANAGED_NOTE : READINESS_FLEET_NOTE, generatedAt: new Date(now).toISOString(), - states: PRODUCIBLE_STATES.map((s) => ({ state: s, label: STATE_LABEL[s] })), + states: shown.map((s) => ({ state: s, label: STATE_LABEL[s] })), + managedControls: on, counts, total: computers.length, truncated, diff --git a/apps/api/src/msa/readiness.ts b/apps/api/src/msa/readiness.ts index 64765f70..8671d528 100644 --- a/apps/api/src/msa/readiness.ts +++ b/apps/api/src/msa/readiness.ts @@ -7,14 +7,15 @@ import { isWindowsPlatform, osName } from '../common/platform'; * MSA state from facts already stored. It imports two constants-and-regex * modules and nothing that reads a database, a file or the network. * - * READINESS ONLY. Managed Secure Access is not built: nothing here, or - * anywhere in 0.69, changes a setting, a password or a session on any - * computer. `managed`, `managed_verified` and `enforcement_failure` are in - * the type so the console and the API speak the design's whole vocabulary, - * and NOTHING can produce them yet: `decideReadiness` returns only - * PRODUCIBLE_STATES, and unit-msa-readiness.mjs and check-security-invariants - * (§80) assert it. A saved or assumed state is never shown as verified: - * `verified` is the literal `false` on every answer. + * Readiness, and since 0.72 the managed states. Nothing here changes a + * computer. `managed` (Managed (pending)), `managed_verified` and + * `enforcement_failure` are produced ONLY from the caller's `managed` fact — + * the MsaManagedComputer row a Platform Admin's cutover wrote, as the agent's + * reports moved it — and only while the computer is reporting now (rules 1–3 + * first: an Unknown computer is never shown as managed). Managed and verified + * also needs the agent's own readback of every managed setting within + * REPORT_MAX_AGE_MS; a saved state alone is never shown as verified, and + * `verified` is true on that answer alone (unit-msa-readiness.mjs, §80). * * The rules, in order (the first that applies decides): * 1. Platform unknown → unknown. Linux or macOS → unsupported. @@ -35,6 +36,11 @@ import { isWindowsPlatform, osName } from '../common/platform'; * the lab covers it. * 9. Service not running, or any `--option` read unanswered → unknown. * 10. Otherwise → compatible. Still Legacy: compatible changes nothing. + * + * With a `managed` fact (0.72), after rule 3: rollback_pending → managed + * (rolling back), enforcement_failure → enforcement_failure, pending → + * managed, verified → managed_verified when the agent read every setting + * back within REPORT_MAX_AGE_MS, else unknown. */ export const MSA_STATES = [ @@ -42,15 +48,19 @@ export const MSA_STATES = [ 'upgrade_available', 'compatible', 'unknown', - // Later build steps (grants, enforcement, readback). Not producible in 0.69. + // 0.72: only from a managed fact (the MsaManagedComputer row) — never from a preflight. 'managed', 'managed_verified', 'enforcement_failure', ] as const; export type MsaState = (typeof MSA_STATES)[number]; -/** The only states decideReadiness can return in this release. */ -export const PRODUCIBLE_STATES = ['unsupported', 'upgrade_available', 'compatible', 'unknown'] as const satisfies readonly MsaState[]; +/** What a preflight alone can produce: never a managed state. */ +export const READINESS_STATES = ['unsupported', 'upgrade_available', 'compatible', 'unknown'] as const satisfies readonly MsaState[]; +/** The managed states (0.72): only from a managed fact. */ +export const MANAGED_READINESS_STATES = ['managed', 'managed_verified', 'enforcement_failure'] as const satisfies readonly MsaState[]; +/** Every state decideReadiness can return. */ +export const PRODUCIBLE_STATES = [...READINESS_STATES, ...MANAGED_READINESS_STATES] as const; export type ProducibleState = (typeof PRODUCIBLE_STATES)[number]; export const STATE_LABEL: Record = { @@ -65,6 +75,8 @@ export const STATE_LABEL: Record = { /** The first signed agent that runs the preflight. */ export const MIN_REPORTING_AGENT = '0.69.0'; +/** The first signed agent that enforces a grant (0.72): cutover needs it. */ +export const MIN_ENFORCING_AGENT = '0.72.0'; /** RustDesk releases the Windows lab ran as SYSTEM (0.68.3, docs/lab-testing.md). */ export const LAB_TESTED_RUSTDESK = ['1.4.1', '1.4.6', '1.4.7', '1.4.9', '1.5.3'] as const; export const LAB_TESTED_MIN = '1.4.1'; @@ -78,6 +90,12 @@ export const READINESS_NOTE = 'Readiness only — Managed Secure Access is not available yet; nothing has changed on this computer.'; export const READINESS_FLEET_NOTE = 'Readiness only — Managed Secure Access is not available yet; nothing has changed on any computer.'; +/** 0.72: the fleet note while MSA_GRANTS is on (a test server). */ +export const READINESS_FLEET_MANAGED_NOTE = + 'Managed Secure Access is switched on for testing: a Platform Admin can move one computer at a time. It has run only in the Windows lab.'; +/** 0.72: the note for a computer a Platform Admin moved into Managed Secure Access. */ +export const MANAGED_NOTE = + 'Managed Secure Access (build step 4) has run only in the Windows lab: never on a Windows 10 or 11 desktop or on the fleet.'; export interface PreflightFacts { checkedAt: Date | string; @@ -90,6 +108,16 @@ export interface PreflightFacts { keysOk: number; } +/** The MsaManagedComputer row (0.72), as the caller read it. No row is Legacy. */ +export interface ManagedFacts { + state: 'pending' | 'verified' | 'enforcement_failure' | 'rollback_pending'; + requestedAt: Date | string; + verifiedAt: Date | string | null; + readbackOkAt: Date | string | null; + failReason: string | null; + failedKeys: string[]; +} + export interface ReadinessFacts { platform: string | null; /** runsSignedAgent(...) — computed by the caller from stored facts. */ @@ -98,6 +126,8 @@ export interface ReadinessFacts { isOnline: boolean; lastSeenAt: Date | string | null; preflight: PreflightFacts | null; + /** 0.72: the managed row, or null / absent for Legacy. */ + managed?: ManagedFacts | null; } export interface Readiness { @@ -105,8 +135,8 @@ export interface Readiness { label: string; /** Plain sentences, the deciding one first. */ reasons: string[]; - /** Always false: readiness is a report, never verified enforcement. */ - verified: false; + /** True only for managed_verified: a Platform Admin's confirmation AND the agent's recent readback. */ + verified: boolean; checkedAt: string | null; rustdeskVersion: string | null; /** True for an exact lab-tested release, false otherwise, null when unknown. */ @@ -154,7 +184,7 @@ export function decideReadiness(f: ReadinessFacts, now: number = Date.now()): Re const checkedAt = iso(pf?.checkedAt ?? null); const rd = pf?.version ?? null; const out = (state: ProducibleState, reasons: string[], labTested: boolean | null = null): Readiness => ({ - state, label: STATE_LABEL[state], reasons, verified: false, checkedAt, rustdeskVersion: rd, labTested, + state, label: STATE_LABEL[state], reasons, verified: state === 'managed_verified', checkedAt, rustdeskVersion: rd, labTested, }); // 1. Platform. @@ -177,6 +207,35 @@ export function decideReadiness(f: ReadinessFacts, now: number = Date.now()): Re : 'The agent has never reported.']); } + // 0.72: a computer a Platform Admin moved into Managed Secure Access. + const m = f.managed; + if (m) { + const keys = m.failedKeys.length ? ` (${m.failedKeys.join(', ')})` : ''; + if (m.state === 'rollback_pending') { + return out('managed', ['Rolling back to Legacy: the agent restores the RustDesk settings it saved before it first applied a grant, then the portal hands it a new permanent password.']); + } + if (m.state === 'enforcement_failure') { + return out('enforcement_failure', [ + `The agent could not enforce Managed Secure Access: ${m.failReason ?? 'a setting did not read back'}${keys}. Nothing weaker was substituted.`, + m.verifiedAt ? 'Connect stays refused until a test grant applies and reads back again, or the computer is rolled back.' : 'Legacy Connect still works (the computer was never verified).', + ]); + } + if (m.state === 'pending') { + return out('managed', [ + 'Moved to Managed (pending) by a Platform Admin. Legacy Connect still works until a managed test session succeeds and a Platform Admin confirms it.', + m.readbackOkAt ? `The agent last read every managed setting back ${ageText(now - new Date(m.readbackOkAt).getTime())}.` : 'No test grant has been applied yet.', + ]); + } + const rb = m.readbackOkAt ? new Date(m.readbackOkAt).getTime() : NaN; + if (!Number.isFinite(rb) || now - rb > REPORT_MAX_AGE_MS) { + return out('unknown', ['Verified as managed, but the agent has not read the managed settings back within 7 days, so it is not shown as enforced.']); + } + return out('managed_verified', [ + `The agent read every managed setting back ${ageText(now - rb)}, a managed test session connected, and a Platform Admin confirmed it.`, + 'Its RustDesk password is one nobody is told; the legacy password no longer connects.', + ]); + } + // 4. An agent that can report. const agentCmp = compareVersion(f.agentVersion, MIN_REPORTING_AGENT); if (agentCmp === null || agentCmp < 0) { diff --git a/apps/api/src/public/windows-script.ts b/apps/api/src/public/windows-script.ts index 54984574..65b3b5ed 100644 --- a/apps/api/src/public/windows-script.ts +++ b/apps/api/src/public/windows-script.ts @@ -470,6 +470,15 @@ try { Start-Process -FilePath $agentExe -ArgumentList @('rustdesk-preflight') -WindowStyle Hidden } } +} catch {} +try { + # Managed Secure Access (0.72): the grant poller runs only when the portal + # says msaPoll (MSA_GRANTS on AND a Platform Admin moved this computer + # into Managed). Never otherwise. A second start while one runs leaves at + # once (it holds a lock). + if ($resp.data.msaPoll -eq $true -and (Test-Path -LiteralPath $agentExe)) { + Start-Process -FilePath $agentExe -ArgumentList @('msa-poller') -WindowStyle Hidden + } } catch {}`, // The tray (0.36): the signed agent installs rem0te-tray.exe itself (a // signed target, verified like the agent), and its tray host starts it in diff --git a/apps/api/src/security-controls/confirm-catalog.ts b/apps/api/src/security-controls/confirm-catalog.ts index d52aa99a..ecb6f158 100644 --- a/apps/api/src/security-controls/confirm-catalog.ts +++ b/apps/api/src/security-controls/confirm-catalog.ts @@ -112,7 +112,14 @@ export const CONFIRM_CATALOG = [ description: "Revealing a computer's stored RustDesk password, or connecting with it." }, { key: 'msa.grant', group: 'Devices & enrolment', label: 'Managed Secure Access test grants', default: 'off', prompt: 'issue a test session grant', - description: 'Issuing a Managed Secure Access test grant to a computer (Platform Admin; only while the server runs with MSA_GRANTS=on, which is off by default).' }, + description: 'Issuing a Managed Secure Access test grant to a computer, or making the grant key (Platform Admin; only while the server runs with MSA_GRANTS=on, which is off by default).' }, + // 0.72: Managed Secure Access build step 4. + { key: 'msa.cutover', group: 'Devices & enrolment', label: 'Managed Secure Access cutover', default: 'off', + prompt: 'move a computer into Managed Secure Access', + description: 'Moving one computer from Legacy into Managed Secure Access, or confirming it verified after a managed test session (Platform Admin; only with MSA_GRANTS=on). Rolling back never asks.' }, + { key: 'msa.reveal', group: 'Devices & enrolment', label: 'Managed test session password', default: 'off', + prompt: 'see the one-time password', + description: "Showing a managed test grant's one-time RustDesk password, once (Platform Admin; only with MSA_GRANTS=on)." }, // 0.57: discovery and adoption. { key: 'devices.adopt', group: 'Devices & enrolment', label: 'Adopting unassigned computers', default: 'off', prompt: 'assign or forget unassigned computers', diff --git a/apps/api/src/update-trust/update-trust.service.ts b/apps/api/src/update-trust/update-trust.service.ts index 2192a77d..0f7e526e 100644 --- a/apps/api/src/update-trust/update-trust.service.ts +++ b/apps/api/src/update-trust/update-trust.service.ts @@ -6,6 +6,7 @@ import { AuditService } from '../audit/audit.service'; import type { ActorContext } from '../rbac/access-control.service'; import { TrustChangeService } from '../security-controls/trust-change.service'; import { agentVersionView, servedVersionOf, type AgentVersionFacts, type AgentVersionView, type ServedAgentBuild } from '../common/agent-version-view'; +import { MSA_GRANT_KEYS_SCHEMA, MSA_GRANT_KEYS_TARGET } from '../msa/grant-key-commands'; /** * The portal's side of the signed update chain: a read-only mirror. @@ -175,6 +176,27 @@ export class UpdateTrustService { } trayTarget() { return this.targetFile(TRAY_TARGET); } + /** + * 0.72 (Managed Secure Access): the grant key ids in the published + * msa/grant-keys.json, read as served and unverified — the console's + * "is it published yet" and the cutover gate. Agents verify the file + * through the signed chain themselves; nothing here is trusted by them. + * Strict: anything that is not the schema yields no ids. + */ + publishedMsaGrantKeyIds(): string[] { + const t = this.targetFile(MSA_GRANT_KEYS_TARGET); + if (!t || t.length > 16_384) return []; + try { + const doc = JSON.parse(fs.readFileSync(t.path, 'utf8')) as { schema?: unknown; keys?: unknown }; + if (doc.schema !== MSA_GRANT_KEYS_SCHEMA || !Array.isArray(doc.keys)) return []; + return doc.keys + .map((k) => (k && typeof k === 'object' ? (k as { keyId?: unknown }).keyId : null)) + .filter((k): k is string => typeof k === 'string' && /^[0-9a-f]{16}$/.test(k)); + } catch { + return []; + } + } + /** Signed RustDesk builds, newest first, from targets custom metadata or name. */ signedRustdeskVersions(): string[] { const s = this.loadServed(); diff --git a/apps/web/app/(app)/endpoints/remote-readiness/page.tsx b/apps/web/app/(app)/endpoints/remote-readiness/page.tsx index eb14cc17..1ff002f5 100644 --- a/apps/web/app/(app)/endpoints/remote-readiness/page.tsx +++ b/apps/web/app/(app)/endpoints/remote-readiness/page.tsx @@ -62,7 +62,7 @@ export default function RemoteReadinessPage() { /> {!allowed ?

This page needs the View computers permission.

: ( <> - + {isLoading &&

Loading…

} {isError &&

Readiness could not be loaded.

} {data && ( diff --git a/apps/web/components/endpoints/msa-managed.tsx b/apps/web/components/endpoints/msa-managed.tsx new file mode 100644 index 00000000..a931f90c --- /dev/null +++ b/apps/web/components/endpoints/msa-managed.tsx @@ -0,0 +1,147 @@ +'use client'; + +import { useState } from 'react'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { msaManagedApi } from '@/lib/api-client'; +import { usePermissions } from '@/lib/auth'; +import { Button } from '@/components/ui/button'; +import { apiError } from '@/components/security-controls/shared'; +import { useToast } from '@/hooks/use-toast'; +import { formatDate } from '@/lib/utils'; + +/** + * Managed Secure Access cutover controls (0.72, build step 4) on the device + * page's readiness card. Platform Admins only, and only while the server + * runs with MSA_GRANTS=on: the readiness card mounts this only when its own + * (ungated) answer says `managedControls: true`, so with the switch off the + * console makes no request to a gated route at all. One computer at a time; the API makes + * every decision (readiness gate, published grant key, pauses). + */ + +interface GrantRow { + grantId: string; state: string; createdAt: string; appliedAt: string | null; connectedAt: string | null; + endedAt: string | null; outcome: string | null; failedKeys: string[]; revealedAt: string | null; +} +interface ManagedView { + enabled: true; + endpointId: string; + state: 'legacy' | 'pending' | 'verified' | 'enforcement_failure' | 'rollback_pending'; + managed: { + requestedAt: string; verifiedAt: string | null; legacySecuredAt: string | null; failedAt: string | null; failReason: string | null; + failedKeys: string[]; rollbackRequestedAt: string | null; readbackOkAt: string | null; lastReportAt: string | null; + } | null; + grants: GrantRow[]; + grantKeyPublished: boolean; + cutover: { allowed: boolean; blockers: { code: string; message: string }[] }; + canConfirm: boolean; + evidence: string; +} + +const STATE_TEXT: Record = { + legacy: 'Legacy', + pending: 'Managed (pending)', + verified: 'Managed and verified', + enforcement_failure: 'Enforcement failure', + rollback_pending: 'Rolling back to Legacy', +}; + +const GRANT_TEXT: Record = { + issued: 'waiting for the agent', delivered: 'delivered', applied: 'applied — settings read back', failed: 'refused or failed', + ended: 'ended', expired: 'expired unused', cancelled: 'cancelled', +}; + +export function MsaManagedControls({ endpointId }: { endpointId: string }) { + const { isPlatformAdmin } = usePermissions(); + const qc = useQueryClient(); + const { toast } = useToast(); + const [password, setPassword] = useState<{ grantId: string; value: string } | null>(null); + const { data } = useQuery({ + queryKey: ['msa-managed', endpointId], + queryFn: () => msaManagedApi.view(endpointId).then((r) => r.data?.data ?? null).catch(() => null), + enabled: isPlatformAdmin, + retry: false, + refetchInterval: 15_000, + }); + const done = () => { + void qc.invalidateQueries({ queryKey: ['msa-managed', endpointId] }); + void qc.invalidateQueries({ queryKey: ['msa-readiness', endpointId] }); + }; + const act = (fn: () => Promise, ok: string) => ({ + mutationFn: fn, + onSuccess: () => { done(); toast({ title: ok }); }, + onError: (e: unknown) => toast({ title: 'Not done', description: apiError(e).message, variant: 'destructive' as const }), + }); + const cutover = useMutation(act(() => msaManagedApi.cutover(endpointId), 'Moved to Managed (pending)')); + const test = useMutation(act(() => msaManagedApi.testGrant(endpointId), 'Test grant sent')); + const confirm = useMutation(act(() => msaManagedApi.confirm(endpointId), 'Confirmed: managed and verified')); + const rollback = useMutation(act(() => msaManagedApi.rollback(endpointId), 'Rolling back to Legacy')); + const force = useMutation(act(() => msaManagedApi.rollback(endpointId, true), 'Returned to Legacy')); + const reveal = useMutation({ + mutationFn: (grantId: string) => msaManagedApi.reveal(grantId).then((r) => r.data?.data as { grantId: string; oneTimePassword: string }), + onSuccess: (r) => { done(); setPassword({ grantId: r.grantId, value: r.oneTimePassword }); }, + onError: (e: unknown) => toast({ title: 'Not shown', description: apiError(e).message, variant: 'destructive' }), + }); + + if (!isPlatformAdmin || !data?.enabled) return null; + const latest = data.grants[0]; + const busy = cutover.isPending || test.isPending || confirm.isPending || rollback.isPending || force.isPending || reveal.isPending; + return ( +
+

+ Managed Secure Access (Platform Admin): {STATE_TEXT[data.state]} +

+

{data.evidence}

+ {data.managed?.failReason && ( +

Last failure: {data.managed.failReason}{data.managed.failedKeys.length ? ` (${data.managed.failedKeys.join(', ')})` : ''}

+ )} + {!data.grantKeyPublished &&

The grant key is not in the signed release metadata yet: the agent would refuse every grant.

} + {latest && ( +

+ Latest test grant: {GRANT_TEXT[latest.state] ?? latest.state} + {latest.connectedAt ? ' · a RustDesk connection was seen' : ''} + {latest.outcome ? ` · ${latest.outcome}` : ''} + {latest.failedKeys.length ? ` (${latest.failedKeys.join(', ')})` : ''} · {formatDate(latest.createdAt)} +

+ )} + {password && ( +

+ One-time password (shown once, not again): {password.value} +

+ )} +
+ {data.state === 'legacy' && ( + + )} + {(data.state === 'pending' || data.state === 'verified' || data.state === 'enforcement_failure') && ( + + )} + {latest && latest.state === 'applied' && !latest.revealedAt && data.state !== 'rollback_pending' && ( + + )} + {data.state === 'pending' && ( + + )} + {data.state !== 'legacy' && data.state !== 'rollback_pending' && ( + + )} + {data.state === 'rollback_pending' && ( + + )} +
+ {data.state === 'legacy' && data.cutover.blockers.length > 0 && ( +
    + {data.cutover.blockers.map((b) =>
  • {b.message}
  • )} +
+ )} +
+ ); +} diff --git a/apps/web/components/endpoints/msa-readiness.tsx b/apps/web/components/endpoints/msa-readiness.tsx index 3c9ccb0e..025b9876 100644 --- a/apps/web/components/endpoints/msa-readiness.tsx +++ b/apps/web/components/endpoints/msa-readiness.tsx @@ -8,6 +8,7 @@ import { Badge } from '@/components/ui/badge'; import { Card, CardContent } from '@/components/ui/card'; import { CardHeading } from '@/components/endpoints/card-heading'; import { cn, formatDate } from '@/lib/utils'; +import { MsaManagedControls } from '@/components/endpoints/msa-managed'; /** * Managed Secure Access readiness (0.69): what the signed agent's read-only @@ -19,7 +20,7 @@ import { cn, formatDate } from '@/lib/utils'; export type MsaState = 'unsupported' | 'upgrade_available' | 'compatible' | 'unknown' | 'managed' | 'managed_verified' | 'enforcement_failure'; export interface MsaReadiness { - state: MsaState; label: string; reasons: string[]; verified: false; + state: MsaState; label: string; reasons: string[]; verified: boolean; checkedAt: string | null; rustdeskVersion: string | null; labTested: boolean | null; } export interface MsaEndpointView { @@ -32,6 +33,8 @@ export interface MsaEndpointView { note: string; labTested: { versions: string[]; min: string; max: string }; minAgent: string; + /** 0.72: MSA_GRANTS is on, so the managed routes exist. Absent or false: never ask them. */ + managedControls?: boolean; } /** The one sentence every readiness view leads with (the API's READINESS_NOTE). */ @@ -43,8 +46,8 @@ const TONE: Record = { upgrade_available: 'border-amber-600/40 text-amber-800 dark:text-amber-300', unsupported: 'border-muted-foreground/40 text-muted-foreground', unknown: 'border-muted-foreground/40 text-muted-foreground', - managed: 'border-muted-foreground/40', - managed_verified: 'border-muted-foreground/40', + managed: 'border-sky-600/40 text-sky-800 dark:text-sky-300', + managed_verified: 'border-emerald-600/40 text-emerald-800 dark:text-emerald-300', enforcement_failure: 'border-destructive/50 text-destructive', }; @@ -81,7 +84,7 @@ export function MsaReadinessCard({ endpointId }: { endpointId: string }) { aside={All computers} /> - + {isLoading &&

Loading…

} {isError &&

Readiness could not be loaded.

} {r && ( @@ -106,11 +109,14 @@ export function MsaReadinessCard({ endpointId }: { endpointId: string }) { )}

- The signed agent reads RustDesk's settings with its own command line every 6 hours, and whenever RustDesk changes. It never writes one. - Compatible means it could be managed later; it is not managed now. + The signed agent reads RustDesk's settings with its own command line every 6 hours, and whenever RustDesk changes. That read never writes one. + {r.state === 'managed' || r.state === 'managed_verified' || r.state === 'enforcement_failure' + ? ' A Platform Admin moved this computer into Managed Secure Access.' + : ' Compatible means it could be managed; it is not managed now.'}

)} + {data?.managedControls === true && }
); diff --git a/apps/web/lib/api-client.ts b/apps/web/lib/api-client.ts index 95c1b4ae..e202a010 100644 --- a/apps/web/lib/api-client.ts +++ b/apps/web/lib/api-client.ts @@ -1049,6 +1049,20 @@ export const msaApi = { forEndpoint: (endpointId: string) => api.get(`/msa/readiness/${endpointId}`), }; +// Managed Secure Access cutover (0.72, build step 4), behind MSA_GRANTS: every +// route answers 404 MSA_NOT_ENABLED while the switch is off, and the card +// then shows nothing new. Changes are a Platform Admin's, one computer at a +// time; cutover, confirm, the test grant and the reveal need fresh +// authentication (the interceptor prompts and retries); rollback never does. +export const msaManagedApi = { + view: (endpointId: string) => api.get(`/msa/managed/${endpointId}`), + cutover: (endpointId: string) => api.post(`/msa/managed/${endpointId}/cutover`), + testGrant: (endpointId: string) => api.post(`/msa/grants/test/${endpointId}`, { mode: 'view', consent: 'required', maxMinutes: 30, idleMinutes: 10 }), + reveal: (grantId: string) => api.post(`/msa/managed/grants/${grantId}/reveal`), + confirm: (endpointId: string) => api.post(`/msa/managed/${endpointId}/confirm`), + rollback: (endpointId: string, force = false) => api.post(`/msa/managed/${endpointId}/rollback`, force ? { force: true } : {}), +}; + export const agentSigningApi = { overview: (businessId?: string) => api.get('/agent-signing/overview', { params: businessId ? { businessId } : undefined }), putAuto: (body: { mode?: 'off' | 'canary_then_all'; soakMinutes?: number }) => api.put('/admin/agent-auto-migration', body), diff --git a/apps/web/package.json b/apps/web/package.json index 844b5792..16be33a9 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "@reboot-remote/web", - "version": "0.71.0", + "version": "0.72.0", "private": true, "scripts": { "dev": "next dev -p 3000", diff --git a/apps/web/scripts/e2e-ui.mjs b/apps/web/scripts/e2e-ui.mjs index af1bfbf5..f61107f5 100644 --- a/apps/web/scripts/e2e-ui.mjs +++ b/apps/web/scripts/e2e-ui.mjs @@ -255,6 +255,9 @@ function startApi() { RETENTION_SWEEP: 'off', REPORT_SCHEDULE_SWEEP: 'off', SCRIPT_OUTPUT_SWEEP: 'off', CHAT_RETENTION_SWEEP: 'off', TRAY_SWEEP: 'off', AUTO_MIGRATION_SWEEP: 'off', WINGET_INDEX_SWEEP: 'off', WARRANTY_SWEEP: 'off', AUTOMATION_SWEEP: 'off', RESTART_WINDOW_SWEEP: 'off', // 0.59: the SSO session safety-net. SSO_SESSION_SWEEP: 'off', + // 0.72: Managed Secure Access is off, as in production; the suite checks + // the console asks no gated /msa/managed or /msa/grants route. + MSA_GRANTS: 'off', // 0.35: the agent-silent fixture is reachable (isOnline) with an old heartbeat; with no hbbs here the stale sweep would take it offline within a minute. STALE_SWEEP: 'off', // 0.35 automatic snapshots: the fixtures' snapshots are the only ones, and @@ -476,8 +479,19 @@ const VIEWPORTS = { * the request itself is what is judged (with its status and code), so only * the echo is dropped. */ +// 0.72: this suite's API runs with MSA_GRANTS unset (off). The console must +// then make no request at all to a gated Managed Secure Access route — each +// would be a 404 on every device page view. +const msaGated = []; +let msaReadinessReads = 0; function instrument(page) { page.problems = []; + page.on('request', (r) => { + if (!r.url().startsWith(WEB)) return; + const u = r.url().slice(WEB.length); + if (/\/api\/v1\/msa\/(managed|grants)(\/|\?|$)/.test(u)) msaGated.push(`${r.method()} ${u}`); + if (/\/api\/v1\/msa\/readiness\//.test(u)) msaReadinessReads++; + }); page.on('console', (m) => { if (m.type() !== 'error') return; const t = m.text(); @@ -2792,6 +2806,9 @@ async function main() { main() .catch((e) => { fail++; failures.push(`fatal: ${e.stack ?? e.message}`); console.error(e); }) .finally(async () => { + check(msaReadinessReads > 0 && msaGated.length === 0, + 'MSA_GRANTS off: device pages read readiness but the console requested no /msa/managed or /msa/grants route', + `readiness reads ${msaReadinessReads}; gated: ${[...new Set(msaGated)].slice(0, 10).join(', ')}`); await cleanup035(); await cleanup(); await prisma.$disconnect(); diff --git a/deploy/release/rem0te-signed-grant-key b/deploy/release/rem0te-signed-grant-key new file mode 100755 index 00000000..24f9cea7 --- /dev/null +++ b/deploy/release/rem0te-signed-grant-key @@ -0,0 +1,110 @@ +#!/bin/bash +# rem0te-signed-grant-key — the Managed Secure Access grant public keys the +# signed release carries (0.72). +# +# sudo rem0te-signed-grant-key add --key-id ID --public-key BASE64 [--conf FILE] +# sudo rem0te-signed-grant-key retire --key-id ID [--conf FILE] +# sudo rem0te-signed-grant-key list [--conf FILE] +# +# The portal signs every session grant with its own Ed25519 key. Agents +# trust that key only when it is in msa/grant-keys.json, a target in the +# signed release metadata — never because the portal sent it. The console +# (Managed Secure Access, Platform Admin) shows this command line with the +# key id and the PUBLIC key filled in; this command records it under the +# release user's state directory, and the next +# +# sudo rem0te-signed-publish --republish +# +# signs it into the release. `retire` removes a key from the list (agents +# then refuse grants signed with it after the next publish). +# +# Public keys only: a key id is the first 16 hex characters of the SHA-256 of +# the 32-byte key, and both are checked here. Anything that looks like key +# material (PRIVATE, -----BEGIN) is refused. At most 8 keys. +set -euo pipefail +LIB=@LIB_DIR@ +[[ $LIB == @*@ ]] && LIB=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +CONF=@CONF@ +[[ $CONF == @*@ ]] && CONF=/etc/rem0te-release/release.conf +# shellcheck source=lib.sh +source "$LIB/lib.sh" + +cmd=${1:-}; [[ $# -gt 0 ]] && shift +key_id='' public_key='' +while [[ $# -gt 0 ]]; do + case $1 in + --conf) CONF=$2; shift 2 ;; + --key-id) key_id=$2; shift 2 ;; + --public-key) public_key=$2; shift 2 ;; + -h|--help) sed -n '2,24p' "$0"; exit 0 ;; + *) die "unknown argument $1" ;; + esac +done +case $cmd in + add|retire|list) ;; + -h|--help|'') sed -n '2,24p' "$0"; exit 0 ;; + *) die "usage: rem0te-signed-grant-key add|retire|list" ;; +esac +load_conf "$CONF" +if [[ -n $RELEASE_USER && $EUID -ne 0 && $(id -un) != "$RELEASE_USER" ]]; then die "run with sudo"; fi + +FILE=$STATE_DIR/msa-grant-keys.json +[[ $key_id == '' || $key_id =~ ^[0-9a-f]{16}$ ]] || die "--key-id wants 16 lowercase hex characters" +if [[ $public_key == *PRIVATE* || $public_key == *-----BEGIN* ]]; then + die "--public-key looks like key material. Only the PUBLIC key (32 bytes, base64) ever leaves the portal." +fi +[[ $public_key == '' || $public_key =~ ^[A-Za-z0-9+/]{43}=$ ]] || die "--public-key wants a 32-byte Ed25519 public key in standard base64 (44 characters)" + +# The JSON is read and written by node with fixed code; the arguments reach +# it only as argv, after the checks above. +EDIT=' +const fs = require("fs"), crypto = require("crypto"); +const [cmd, file, keyId, pub] = process.argv.slice(1); +const SCHEMA = "rem0te-msa-grant-keys/1"; +let doc = { schema: SCHEMA, keys: [] }; +if (fs.existsSync(file)) { + doc = JSON.parse(fs.readFileSync(file, "utf8")); + if (doc.schema !== SCHEMA || !Array.isArray(doc.keys) || Object.keys(doc).length !== 2) { console.error("error: " + file + " is not a grant key list"); process.exit(3); } +} +const idOf = (b64) => crypto.createHash("sha256").update(Buffer.from(b64, "base64")).digest("hex").slice(0, 16); +for (const k of doc.keys) { + if (Object.keys(k).length !== 2 || !/^[0-9a-f]{16}$/.test(k.keyId) || Buffer.from(k.publicKey, "base64").length !== 32 || idOf(k.publicKey) !== k.keyId) { + console.error("error: " + file + " holds an entry that is not a key and its id"); process.exit(3); + } +} +if (cmd === "list") { + if (!doc.keys.length) console.log(" (no grant keys: Managed Secure Access grants are refused by every agent)"); + for (const k of doc.keys) console.log(" " + k.keyId + " " + k.publicKey); + process.exit(0); +} +if (cmd === "add") { + if (Buffer.from(pub, "base64").length !== 32 || Buffer.from(pub, "base64").toString("base64") !== pub) { console.error("error: --public-key is not 32 bytes of standard base64"); process.exit(4); } + if (idOf(pub) !== keyId) { console.error("error: --key-id is not the id of that key (the first 16 hex characters of its SHA-256 are " + idOf(pub) + ")"); process.exit(4); } + if (doc.keys.some((k) => k.keyId === keyId)) { console.log(" " + keyId + " is already listed; nothing changed"); process.exit(0); } + if (doc.keys.length >= 8) { console.error("error: 8 keys are listed; retire one first"); process.exit(4); } + doc.keys.push({ keyId, publicKey: pub }); +} else { + const n = doc.keys.length; + doc.keys = doc.keys.filter((k) => k.keyId !== keyId); + if (doc.keys.length === n) { console.log(" " + keyId + " is not listed; nothing changed"); process.exit(0); } +} +fs.writeFileSync(file + ".new", JSON.stringify(doc) + "\n", { mode: 0o640 }); +fs.renameSync(file + ".new", file); +console.log(" " + cmd + " " + keyId + ": done. Publish it: sudo rem0te-signed-publish --republish"); +' +case $cmd in + list) + as_release 027 "$NODE" -e "$EDIT" list "$FILE" '' '' ;; + add) + [[ -n $key_id && -n $public_key ]] || die "add needs --key-id and --public-key" + exec 9>>"$STATE_DIR/publish.lock"; flock -n 9 || die "a publish is running; try again when it finishes" + start_log "grant-key add $key_id" + as_release 027 "$NODE" -e "$EDIT" add "$FILE" "$key_id" "$public_key" + log "grant key $key_id added" ;; + retire) + [[ -n $key_id ]] || die "retire needs --key-id" + exec 9>>"$STATE_DIR/publish.lock"; flock -n 9 || die "a publish is running; try again when it finishes" + start_log "grant-key retire $key_id" + as_release 027 "$NODE" -e "$EDIT" retire "$FILE" "$key_id" '' + log "grant key $key_id retired" ;; +esac diff --git a/deploy/release/rem0te-signed-publish b/deploy/release/rem0te-signed-publish index 55c87f30..36a9e286 100755 --- a/deploy/release/rem0te-signed-publish +++ b/deploy/release/rem0te-signed-publish @@ -25,6 +25,12 @@ # directory once the publish succeeds, and every later publish signs it again. # A file holding anything that looks like a private key is refused. # +# Managed Secure Access (0.72): when rem0te-signed-grant-key has recorded any +# grant public keys (STATE_DIR/msa-grant-keys.json), every publish signs that +# list in as msa/grant-keys.json, which is the only place agents learn which +# grant key to trust. After `rem0te-signed-grant-key add|retire`, run +# `sudo rem0te-signed-publish --republish`. +# # Refuses a version older than the one published. The same version and commit # again is a no-op unless --republish (e.g. to add a newly pinned RustDesk). # Everything is logged to LOG_FILE (under the release user's state directory). @@ -87,6 +93,16 @@ if [[ -n $approval_src ]]; then elif as_release 077 test -f "$APPROVAL_KEYS"; then approval_build=$APPROVAL_KEYS fi +# Managed Secure Access grant keys (0.72), recorded by rem0te-signed-grant-key. +MSA_KEYS=$STATE_DIR/msa-grant-keys.json +msa_build='' +if as_release 077 test -f "$MSA_KEYS"; then + msa_build=$BUILD/msa-grant-keys.json + as_release 027 cp "$MSA_KEYS" "$msa_build" + if grep -qiE 'PRIVATE|-----BEGIN' "$msa_build"; then die "$MSA_KEYS looks like it holds key material; it must list public keys only"; fi + "$NODE" -e 'const d=JSON.parse(require("fs").readFileSync(process.argv[1],"utf8")); if(d.schema!=="rem0te-msa-grant-keys/1"||!Array.isArray(d.keys)||d.keys.length>8||!d.keys.every(k=>/^[0-9a-f]{16}$/.test(k.keyId)&&/^[A-Za-z0-9+\/]{43}=$/.test(k.publicKey)))process.exit(3)' "$msa_build" \ + || die "$MSA_KEYS is not a grant key list (rem0te-signed-grant-key list)" +fi VERSION=$(json_version "$BUILD/src/version.json") || die "HEAD's version.json has no x.y.z version" say "building $VERSION from commit $COMMIT" pv=${PUBL[AGENT_VERSION]:-} @@ -171,6 +187,7 @@ args=(release -repo "$BUILD/repo" -add "windows/rem0te-tray.exe=$BUILD/out/rem0te-tray.exe" -custom "windows/rem0te-tray.exe=$custom" -add "windows/install.ps1=$BUILD/out/install.ps1") [[ -n $approval_build ]] && args+=(-add "approval/keys.json=$approval_build") +[[ -n $msa_build ]] && args+=(-add "msa/grant-keys.json=$msa_build") if [[ $(repo_info "$WORK_REPO" target "windows/rustdesk/$rd_name") != "${A[SHA256]}" ]]; then args+=(-add "windows/rustdesk/$rd_name=$cache/$rd_name" -custom "windows/rustdesk/$rd_name={\"version\":\"$RD\"}") fi diff --git a/deploy/release/rem0te-signed-setup.sh b/deploy/release/rem0te-signed-setup.sh index 8929e9fd..d68c9e16 100755 --- a/deploy/release/rem0te-signed-setup.sh +++ b/deploy/release/rem0te-signed-setup.sh @@ -231,13 +231,13 @@ R=$BUILD/src/deploy/release [[ -f $R/lib.sh ]] || die "HEAD has no deploy/release (commit it first: the installed commands come from HEAD, like everything else)" for f in lib.sh promote-stage.sh repo-info.mjs rustdesk-asset.mjs portal-pin.mjs; do install -m 0755 "$R/$f" "$LIB_DIR/$f"; done esc() { printf '%s' "$1" | sed 's/[&|\\]/\\&/g'; } -for c in rem0te-signed-publish rem0te-signed-status rem0te-signed-export-root rem0te-signed-refresh; do +for c in rem0te-signed-publish rem0te-signed-status rem0te-signed-export-root rem0te-signed-refresh rem0te-signed-grant-key; do sed -e "s|@LIB_DIR@|$(esc "$LIB_DIR")|" -e "s|@CONF@|$(esc "$CONF_PATH")|" "$R/$c" > "$BIN_DIR/.$c.new" chmod 0755 "$BIN_DIR/.$c.new" mv -f "$BIN_DIR/.$c.new" "$BIN_DIR/$c" done LIB=$LIB_DIR -say " installed rem0te-signed-publish, -status, -export-root, -refresh in $BIN_DIR" +say " installed rem0te-signed-publish, -status, -export-root, -refresh, -grant-key in $BIN_DIR" # ── 3. Keys and the signing repository ───────────────────────────────────── present=0 missing=() diff --git a/deploy/release/rem0te-signed-status b/deploy/release/rem0te-signed-status index a2b0a603..fd5892c2 100755 --- a/deploy/release/rem0te-signed-status +++ b/deploy/release/rem0te-signed-status @@ -55,6 +55,8 @@ if [[ ${P[CONFIGURED]} == 1 ]]; then line " RustDesk" "${P[RUSTDESK_VERSIONS]:-none}" if [[ -n ${P[APPROVAL_KEYS_SHA256]} ]]; then line " approval keys" "approval/keys.json ${P[APPROVAL_KEYS_SHA256]:0:12}" else line " approval keys" "none (approved actions are off: rem0te-signed-publish --approval-keys FILE)"; fi + if [[ -n ${P[MSA_GRANT_KEYS_SHA256]} ]]; then line " grant keys" "msa/grant-keys.json ${P[MSA_GRANT_KEYS_SHA256]:0:12}; rem0te-signed-grant-key list shows the keys" + else line " grant keys" "none (Managed Secure Access grants are refused: rem0te-signed-grant-key add)"; fi for r in TIMESTAMP SNAPSHOT TARGETS ROOT; do h=${P[${r}_LEFT_H]} line " ${r,,}" "v${P[${r}_VERSION]} expires ${P[${r}_EXPIRES]} ($(human "$h"))" diff --git a/deploy/release/repo-info.mjs b/deploy/release/repo-info.mjs index f04ad737..d432b629 100755 --- a/deploy/release/repo-info.mjs +++ b/deploy/release/repo-info.mjs @@ -82,6 +82,8 @@ if (cmd === 'summary') { lines.INSTALLER_SHA256 = SHA_RE.test(inst?.hashes?.sha256 ?? '') ? inst.hashes.sha256 : ''; const ak = entry('approval/keys.json'); lines.APPROVAL_KEYS_SHA256 = SHA_RE.test(ak?.hashes?.sha256 ?? '') ? ak.hashes.sha256 : ''; + const mk = entry('msa/grant-keys.json'); + lines.MSA_GRANT_KEYS_SHA256 = SHA_RE.test(mk?.hashes?.sha256 ?? '') ? mk.hashes.sha256 : ''; lines.RUSTDESK_VERSIONS = Object.keys(c.targets?.signed?.targets ?? {}) .map((n) => /^windows\/rustdesk\/rustdesk-(\d+\.\d+\.\d+)-x86_64\.exe$/.exec(n)?.[1]).filter(Boolean).join(','); for (const [k, val] of Object.entries(lines)) console.log(`${k}=${val}`); diff --git a/docs/API-REFERENCE.md b/docs/API-REFERENCE.md index af087567..440abb4a 100644 --- a/docs/API-REFERENCE.md +++ b/docs/API-REFERENCE.md @@ -3,8 +3,8 @@ _Generated from the controllers by `scripts/gen-api-reference.mjs`. Do not edit by hand._ Every route is prefixed with `/api/v1` unless its path is shown in full (the ticket-rmm-v1 -integration, under `/api/integration/v1`). There are **616** of them across -**93** controllers. +integration, under `/api/integration/v1`). There are **623** of them across +**94** controllers. For request and response shapes, worked examples and error codes, see [PUBLIC-API.md](PUBLIC-API.md) — this page is the complete surface, that one is the guide. @@ -606,6 +606,7 @@ Admins and Business Owners are not confined by it; see | Method | Path | Access | Capability | |---|---|---|---| | `POST` | `/api/v1/msa/agent/poll` | public, throttled | — | +| `POST` | `/api/v1/msa/agent/report` | public, throttled | — | ## Msa grant msagrants @@ -615,8 +616,21 @@ Admins and Business Owners are not confined by it; see |---|---|---|---| | `GET` | `/api/v1/msa/grants/endpoint/:endpointId` | signed in | `COMPUTERS_VIEW` | | `GET` | `/api/v1/msa/grants/keys` | Platform Admin | — | +| `POST` | `/api/v1/msa/grants/keys` | Platform Admin, throttled | — | | `POST` | `/api/v1/msa/grants/test/:endpointId` | Platform Admin, throttled | — | +## Msa managed + +`apps/api/src/msa/msa-managed.controller.ts` + +| Method | Path | Access | Capability | +|---|---|---|---| +| `GET` | `/api/v1/msa/managed/:endpointId` | signed in | `COMPUTERS_VIEW` | +| `POST` | `/api/v1/msa/managed/:endpointId/confirm` | Platform Admin, throttled | — | +| `POST` | `/api/v1/msa/managed/:endpointId/cutover` | Platform Admin, throttled | — | +| `POST` | `/api/v1/msa/managed/:endpointId/rollback` | Platform Admin, throttled | — | +| `POST` | `/api/v1/msa/managed/grants/:grantId/reveal` | Platform Admin, throttled | — | + ## Notes `apps/api/src/notes/notes.controller.ts` diff --git a/docs/lab-testing.md b/docs/lab-testing.md index 562656f1..2757102a 100644 --- a/docs/lab-testing.md +++ b/docs/lab-testing.md @@ -96,6 +96,29 @@ running, build `flutter`, a version beginning with the release (`1.4.7+65`), and (`flutter_windows.dll` or `sciter.dll` beside the exe): the lab can confirm only the Flutter half, since every official x64 build is Flutter. +### The agent's Managed Secure Access enforcement (0.72, in the same RustDesk jobs) + +After the preflight, on the same releases, the job runs `TestLabRustdeskEnforce` (same tag and gates). Unlike the +preflight it **changes RustDesk's settings** on the throwaway runner, and puts them back. Through the agent's own +enforcement exec site (`enforceRunner`, the only code that may pass a value to `--option` or name `--password`) and +`enforce.Enforcer`, one cycle: + +1. save every one of the eleven settings; +2. apply a view-only grant: every setting written and read back, then the one-time password, which must print + `Done`; +3. read every setting back again; +4. end the session: a random password nobody is told, `stop-service Y`, a pause, `N`, and `stop-service` read back + as `N`; +5. restore the saved settings and read every one back. + +- **`admin`**: in the test process, as the runner's elevated administrator. +- **`system`**: the same test binary started by a scheduled task as SYSTEM in session 0 with + `-lab-enforce-out`, which writes the cycle's result to `C:\ProgramData\Rem0te\lab-msa-enforce.json`. + +Ids: `agent/msa-enforce//admin` and `…/system`, in `enforce-evidence-.jsonl`; a release whose +download verified but has no such file is a broken lab. It does not cover the portal, the long-poll, grant +verification (the `internal/msa/enforce` unit tests) or a real remote connection. + ### The agent's Windows code (`agent-lab-windows (agent Go tests)`) Go tests tagged `windows && labwindows` — never built by `go test ./...` — and skipped again unless diff --git a/docs/managed-secure-access.md b/docs/managed-secure-access.md index 0fc570d8..74a0919b 100644 --- a/docs/managed-secure-access.md +++ b/docs/managed-secure-access.md @@ -1,18 +1,20 @@ # Managed Secure Access (MSA) — audit and design -**Status: design, with build step 2 (readiness reporting) built in 0.69 and -build step 3 (grants and the long-poll channel) built in 0.71, behind -`MSA_GRANTS`, off.** The signed agent reports a read-only RustDesk preflight -and the console shows each computer's readiness (§3.9). The portal can sign a -session grant and hold it for a computer's signed agent over a long-poll -(§3.10), but only when the server runs with `MSA_GRANTS=on`, which no -production server does, and no agent polls for one or acts on one yet. -Nothing else on this page is built, and nothing on it is turned on for any -computer: no setting, password or session is changed, and no computer can be -Managed. Every computer stays -in today's mode (*Legacy*) until a Platform Admin moves it, one computer or -group at a time, after it passes a preflight. RustDesk stays the remote -desktop; the technician still selects a computer and presses **Connect**. +**Status: build steps 2–4 built, behind `MSA_GRANTS`, off.** Readiness +reporting (§3.9) shipped in 0.69; grants and the long-poll (§3.10) in 0.71; +agent enforcement, the managed test session, cutover and rollback (§3.11) in +0.72. Everything after readiness runs only when the server's environment has +`MSA_GRANTS=on`, which no production server does. Even then **nothing on a +computer changes until a Platform Admin moves that one computer into +Managed (pending)**, with a fresh confirmation — never a group, a business +or the fleet, and never automatically. Every other computer stays in today's +mode (*Legacy*), and a 0.72 agent on a Legacy computer behaves exactly as +0.71's. Technician Connect through grants, revocation and session evidence +are step 5 and not built. RustDesk stays the remote desktop. + +**Managed Secure Access has run only in the Windows lab** (GitHub's Windows +Server runners, RustDesk 1.4.1–1.5.3): never on a Windows 10 or 11 desktop +and never on the fleet. Written 2026-11-19 against Rem0te 0.68 and RustDesk's source at 1.2.3–1.5.3 (client) and 1.1.16 (hbbs/hbbr OSS). Every RustDesk claim below names the @@ -134,13 +136,14 @@ portal issues a **session grant**: a small JSON document signed with Ed25519 containment pause in its signed pause file. - **Delivery:** a managed computer's signed agent keeps one long-poll request open to the portal (device secret, TLS), so a grant arrives within seconds. - Legacy computers never open it. **The portal side is built in 0.71** - (`POST /msa/agent/poll`, §3.10), behind `MSA_GRANTS`, off; the agent's - poller is step 4. -- **Publishing the key:** in 0.71 the public key is readable only by a - Platform Admin (`GET /msa/grants/keys`). Putting it in the signed release - metadata the agent verifies is step 4, together with the agent change that - reads it; until then no agent trusts any grant key. + Legacy computers never open it. The portal side was built in 0.71 + (`POST /msa/agent/poll`, §3.10); the agent's poller in 0.72 (§3.11). +- **Publishing the key (0.72):** the agent trusts a grant key only when it is + listed in `msa/grant-keys.json`, a target in the signed release metadata + the agent already verifies. The portal never sends a key to an agent. The + console shows a Platform Admin the exact command for the release host + (`sudo rem0te-signed-grant-key add --key-id … --public-key …`, then + `sudo rem0te-signed-publish --republish`); see §3.11. ### 3.3 What the agent does with a grant @@ -203,12 +206,13 @@ verified. - **Preflight** (read-only, any time): signed agent version, RustDesk version and Flutter build, CLI works as SYSTEM, readback works. Result: Compatible / Upgrade available / Unsupported. **Built in 0.69** — see §3.9. -- **Cutover** needs a Platform Admin (fresh sign-in), one computer, a group or - a business at a time, canary first. The legacy password is kept until a - managed test session succeeds; only then is it replaced. Never automatic, - never fleet-wide by default. -- **Rollback** to Legacy is an admin action: the agent sets a new sealed - permanent password and restores the previous RustDesk settings. +- **Cutover** needs a Platform Admin (fresh sign-in) and moves **one + computer** at a time (0.72 has no group or business cutover). The legacy + password is kept until a managed test session succeeds; only then is it + replaced. Never automatic, never fleet-wide. **Built in 0.72** (§3.11). +- **Rollback** to Legacy is an admin action: the agent restores the previous + RustDesk settings and the portal stages a new sealed permanent password + through the ordinary rotation. **Built in 0.72** (§3.11). - Nothing rotates the fleet, reinstalls RustDesk, or moves a computer by itself. @@ -361,7 +365,7 @@ permissions, window, who issued it — never the password or the envelope. `GET /msa/grants/keys` (Platform Admin) lists the public keys. **States** (0088 CHECK): `issued`, `delivered`, `expired`, `cancelled`. -Step 4 adds `applied`, `failed` and `revoked`. +0.72 (0089) adds `applied`, `failed` and `ended`; revocation is step 5. **Evidence.** `apps/api/scripts/e2e-msa-grants.mjs` (68 checks: the switch off and on, every refusal, delivery and verification under the published key, @@ -370,6 +374,105 @@ password anywhere, the database's CHECKs), `unit-msa-grants.mjs`, the Go `internal/msa/grant` tests and check-security-invariants §81. **Nothing of it has run on Windows**, and no agent has polled. +### 3.11 Enforcement, the managed test session, cutover and rollback (built, 0.72, behind `MSA_GRANTS`, off) + +**This is a new signed agent build.** On deploy the fleet's signed agents +update to 0.72 as they always do. On a Legacy computer — every computer, until +a Platform Admin moves one — the 0.72 agent does exactly what 0.71 did: the +heartbeat never says `msaPoll`, the poller never starts, and no RustDesk +setting or password is touched. + +**Grant keys in the signed release.** `rem0te-signed-grant-key add | list | +retire` (installed by `rem0te-signed-setup.sh`) records grant **public** keys +in the release user's state directory (`msa-grant-keys.json`, at most 8; key +material, and a key id that is not the key's own SHA-256 prefix, are +refused). `rem0te-signed-publish` signs the list in as the target +`msa/grant-keys.json` (schema `rem0te-msa-grant-keys/1`) on every publish; +`rem0te-signed-status` shows its digest. The agent reads it only through the +verified TUF chain (`agent.MsaTrust`, which also reads the signed pause). No +list, an empty list, or a key not on it: every grant is refused (`no_keys` / +`unknown_key`). The Managed Secure Access card shows a Platform Admin the two +commands with the active key filled in until the published release lists it, +and cutover is refused until it does (`MSA_GRANT_KEY_NOT_PUBLISHED`). + +**Per-computer mode** (`MsaManagedComputer`, migration 0089; no row is +Legacy): `pending` → `verified`, or `enforcement_failure`, or +`rollback_pending` → row deleted. Only `MsaManagedService` writes it. +Readiness shows *Managed (pending)*, *Managed and verified* (only while the +agent's last full readback is inside the report window) and *Enforcement +failure* from this row and the agent's reports, never from a saved setting. + +**Cutover**, `POST /msa/managed/:endpointId/cutover`: Platform Admin, a fresh +confirmation when `msa.cutover` asks, one computer in scope. Refused when the +computer is unassigned, not the signed Windows agent, not *Compatible*, +running an agent older than 0.72 (`MSA_AGENT_TOO_OLD`), under a `remote` +pause, already managed, or when the grant key is not in the published +release. Audited (`MSA_CUTOVER`) before the row is written. The next +heartbeat says `msaPoll: true`, and the signed heartbeat starts +`rem0te-agent.exe msa-poller` as SYSTEM. + +**The poller** (`internal/msa/enforce`, wired in `msa_poller_windows.go`) +holds the long-poll with the device secret and, on each answer: exits for +Legacy; for each grant verifies it under the published keys, this computer's +identity, the persisted replay set, the compiled **ceiling — view only, +nothing beyond (no keyboard, clipboard, files, audio, tunnel or restart)** — +and the signed pause; writes the replay set and (before the first change +ever) saves every current setting to a SYSTEM-only directory; then sets every +§3.3 setting, reads each back, and sets the one-time password last (RustDesk +must print `Done`). Any disagreement ends the session at once (a random +password nobody is told, `stop-service Y`, a pause, `N`) and reports `failed` +with the closed key names; nothing weaker is applied. It ends the session +when the connection closes, at `maxMinutes`, or when nobody connected by +`notAfter`, and reads the settings back hourly at rest (drift is +*Enforcement failure*). Two exec sites name `--option` (the preflight's reads +and enforcement's closed argument lists) and one names `--password`; both +run only the installed `rustdesk.exe` the RustDesk service runs, as an +argument array with no shell. The password is never logged, reported or +audited. + +**The managed test session** (while *pending*): a Platform Admin sends a +view-only test grant (`POST /msa/grants/test/:endpointId`, consent required), +the agent applies it, **Reveal one-time password** shows it once +(`POST /msa/managed/grants/:grantId/reveal`, `msa.reveal`, audited as +`MSA_PASSWORD_REVEALED` with ids only, claimed by a conditional write), and +the admin connects with RustDesk. The agent reports the connection +(`rustdesk.exe --cm`) and its end. While pending, the agent restores the +saved settings after each test session and the portal stages a legacy +rotation, so Legacy Connect keeps working between test sessions; a staged +rotation waits while a grant is in flight. + +**Verified**, `POST /msa/managed/:endpointId/confirm` (Platform Admin, +`msa.cutover`): only after a test session since cutover that read back and +connected. The agent then replaces the permanent password with one nobody is +told (`secured`). From then on legacy Reveal, Connect, rotation and set +password are refused (`409 MSA_MANAGED` / `msa_managed`). Because technician +Connect through grants is step 5, **a verified computer can be reached only +through Platform Admin test grants until step 5 ships**; roll it back to +connect the ordinary way. + +**Rollback**, `POST /msa/managed/:endpointId/rollback`: Platform Admin, never +asks for a fresh confirmation, audited. It cancels undelivered grants and +stages a fresh sealed permanent password through the existing rotation path; +the agent ends any session, restores the saved settings, reads them back and +reports `restored` (the row is deleted) or `restore_failed`. **Finish +rollback without the agent** (`force: true`) is only for a computer already +rolling back whose agent is gone. Rollback needs the switch on: turning +`MSA_GRANTS` off with a verified computer stops its poller but still refuses +its legacy password (fail closed) — roll back first. + +**Not in 0.72 (step 5):** Connect issuing grants for technicians, `control` +mode or any permission above the view-only ceiling, group or business +cutover, revocation and the session evidence timeline, a console switch for +`MSA_GRANTS`. + +**Evidence.** `apps/api/scripts/e2e-msa-managed.mjs` (port 3961), +`unit-msa-managed.mjs`, `unit-msa-readiness.mjs`, the Go +`internal/msa/enforce` tests (a fake RustDesk), check-security-invariants +§82, and the Windows lab's `TestLabRustdeskEnforce` (save, apply, readback, +password, end session, restore — as the administrator and as SYSTEM, RustDesk +1.4.1–1.5.3). The lab runs the agent's enforcement code against real +RustDesk, but not the portal, the long-poll or a real remote connection. + ## 4. Build order (each a reviewable PR, none deployed without approval) 1. **Lab proof** on GitHub's `windows-latest`: install RustDesk, run the signed @@ -384,7 +487,8 @@ has run on Windows**, and no agent has polled. pure Go verifier no command imports. Publishing the grant key in the signed release metadata is step 4. 4. **Agent enforcement** (signed agent release), managed test session, cutover - and rollback. + and rollback. **Built in 0.72, behind `MSA_GRANTS`, off** (§3.11): one + computer at a time, view-only, grant keys in the signed release. 5. **Revocation, session evidence**, console controls. 6. **Compatibility suite** (below) gates every release from step 2 on. diff --git a/package.json b/package.json index 644b5f65..e6787f06 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "reboot-remote", - "version": "0.71.0", + "version": "0.72.0", "private": true, "packageManager": "pnpm@11.27.0", "engines": { diff --git a/scripts/check-security-invariants.mjs b/scripts/check-security-invariants.mjs index eba92853..b40f592f 100644 --- a/scripts/check-security-invariants.mjs +++ b/scripts/check-security-invariants.mjs @@ -3684,7 +3684,13 @@ const POSIX_PARTS = ['POSIX_SETUP', 'POSIX_TRANSPORT', 'POSIX_HEARTBEAT', 'POSIX // portal shows, never runs: they may appear only as the three exported // constants in agent-migration.ts, each exactly `'sudo …rem0te-signed-…'`. const SIGNED_CMD_CONSTS = /^export const (?:SETUP|PUBLISH|STATUS)_COMMAND = 'sudo (?:\.\/deploy\/release\/rem0te-signed-setup\.sh|rem0te-signed-publish|rem0te-signed-status)';$/gm; - const apiText = (f) => (f === 'apps/api/src/update-trust/agent-migration.ts' ? read(f).replace(SIGNED_CMD_CONSTS, '') : read(f)); + // 0.72: the two Managed Secure Access grant-key commands the console shows a + // Platform Admin (Managed Secure Access §3.2) are the same kind of text, in + // grant-key-commands.ts, each exactly as below. + const GRANT_KEY_CMD_CONSTS = /^export const MSA_GRANT_KEY_(?:ADD|PUBLISH)_COMMAND = 'sudo (?:rem0te-signed-grant-key add|rem0te-signed-publish --republish)';$/gm; + const apiText = (f) => (f === 'apps/api/src/update-trust/agent-migration.ts' ? read(f).replace(SIGNED_CMD_CONSTS, '') + : f === 'apps/api/src/msa/grant-key-commands.ts' ? read(f).replace(GRANT_KEY_CMD_CONSTS, '').replace(/\(§56 matches them exactly\)|rem0te-signed-grant-key add|rem0te-signed-publish/g, (m) => (m.startsWith('(') ? m : '')) + : read(f)); const reaching = apiFiles.filter((f) => /\/var\/lib\/rem0te-release|rem0te-signed-|\b(?:root[123]|targets|snapshot|timestamp)\.pem\b|KEY_DIR|REM0TE_SIGNED/.test(apiText(f))); const spawning = apiFiles.filter((f) => /child_process/.test(read(f)) && /rem0te-release/.test(read(f))); check('the API never names the release key store, a key file or the rem0te-signed commands, and never spawns rem0te-release', @@ -4540,6 +4546,7 @@ const POSIX_PARTS = ['POSIX_SETUP', 'POSIX_TRANSPORT', 'POSIX_HEARTBEAT', 'POSIX 'users/users.controller.ts': ['permissions.change'], 'warranty/warranty.controller.ts': ['warranty.settings'], 'msa/msa-grant.controller.ts': ['msa.grant'], + 'msa/msa-managed.controller.ts': ['msa.cutover', 'msa.reveal'], }; const named = {}; for (const f of files) { @@ -6359,12 +6366,19 @@ const POSIX_PARTS = ['POSIX_SETUP', 'POSIX_TRANSPORT', 'POSIX_HEARTBEAT', 'POSIX if (statSync(join(ROOT, rel)).isDirectory()) gw(rel); else if (n.endsWith('.go') && !n.endsWith('_test.go')) goFiles.push(rel); } })('tools/windows-installer'); + // 0.72 replaced "only the preflight names --option" with the exact list: + // the preflight's reads (internal/msa, its runner) and enforcement's + // closed argument builders (internal/msa/enforce/args.go, §82). Nothing + // in the preflight names --password; only enforce/args.go does. const optionSites = goFiles.filter((f) => /"--option"/.test(strip(read(f)))); - const pwInPreflight = ['tools/windows-installer/internal/msa', 'tools/windows-installer/rustdesk_preflight_windows.go'] - .flatMap((p) => goFiles.filter((f) => f === p || f.startsWith(`${p}/`))).filter((f) => /--password/.test(read(f))); - check('nothing in the preflight names --password, and only the preflight names --option', - pwInPreflight.length === 0 && J(optionSites) === J(['tools/windows-installer/internal/msa/preflight.go', 'tools/windows-installer/rustdesk_preflight_windows.go']), - `--password in ${J(pwInPreflight)}; --option in ${J(optionSites)}`); + const pwInPreflight = ['tools/windows-installer/internal/msa/preflight.go', 'tools/windows-installer/rustdesk_preflight_windows.go'] + .filter((f) => /--password/.test(read(f))); + const pwSites = goFiles.filter((f) => /"--password"/.test(strip(read(f)))); + check('nothing in the preflight names --password; --option is named only by the preflight and enforce/args.go, --password only by enforce/args.go', + pwInPreflight.length === 0 + && J(optionSites) === J(['tools/windows-installer/internal/msa/enforce/args.go', 'tools/windows-installer/internal/msa/preflight.go', 'tools/windows-installer/rustdesk_preflight_windows.go']) + && J(pwSites) === J(['tools/windows-installer/internal/msa/enforce/args.go']), + `--password in the preflight ${J(pwInPreflight)}; --option in ${J(optionSites)}; "--password" in ${J(pwSites)}`); const execs = [...strip(goWin).matchAll(/exec\.\w+\(/g)]; check('one exec site: the installed rustdesk.exe by absolute path with msa.ReadArgs, an argument array, no shell, no window, output capped', execs.length === 1 && /cmd := exec\.CommandContext\(ctx, r\.exe, msa\.ReadArgs\(args\[1\]\)\.\.\.\)/.test(goWin) @@ -6403,11 +6417,19 @@ const POSIX_PARTS = ['POSIX_SETUP', 'POSIX_TRANSPORT', 'POSIX_HEARTBEAT', 'POSIX const rdImports = [...rd.matchAll(/^import [\s\S]*? from '([^']+)';/gm)].map((m) => m[1]); const decide = rd.slice(rd.indexOf('export function decideReadiness')); const pureDeps = ['apps/api/src/common/connectivity.ts', 'apps/api/src/common/platform.ts'].every((f) => !/^import /m.test(read(f))); - check('readiness.ts is pure and cannot produce a managed state, or say verified', + // 0.72: the managed states come only from the caller's managed fact (the + // MsaManagedComputer row), inside one branch after rules 1–3, and + // `verified` is true exactly for managed_verified (§82). + const branch = decide.slice(decide.indexOf('const m = f.managed;'), decide.indexOf('// 4. An agent that can report.')); + const outside = decide.replace(branch, '').replace("verified: state === 'managed_verified'", ''); + check('readiness.ts is pure; a preflight alone cannot produce a managed state, and only a recent readback on a verified row says verified', J(rdImports) === J(['../common/connectivity', '../common/platform']) && pureDeps && !/process\.env|fetch\(|prisma/i.test(rd) - && /export const PRODUCIBLE_STATES = \['unsupported', 'upgrade_available', 'compatible', 'unknown'\] as const/.test(rd) - && /state: ProducibleState;/.test(rd) && /verified: false;/.test(rd) && /state, label: STATE_LABEL\[state\], reasons, verified: false,/.test(decide) - && !/'managed'|'managed_verified'|'enforcement_failure'/.test(decide), + && /export const READINESS_STATES = \['unsupported', 'upgrade_available', 'compatible', 'unknown'\] as const/.test(rd) + && /export const MANAGED_READINESS_STATES = \['managed', 'managed_verified', 'enforcement_failure'\] as const/.test(rd) + && /state: ProducibleState;/.test(rd) && /state, label: STATE_LABEL\[state\], reasons, verified: state === 'managed_verified',/.test(decide) + && branch.length > 0 && decide.indexOf('const m = f.managed;') > decide.indexOf('// 3.') && !/'managed'|'managed_verified'|'enforcement_failure'/.test(outside) + && /if \(!Number\.isFinite\(rb\) \|\| now - rb > REPORT_MAX_AGE_MS\) \{\n\s*return out\('unknown'/.test(branch) + && (branch.match(/out\('managed_verified'/g) ?? []).length === 1, `imports: ${rdImports.join(', ')}`); const routes = [...ctl.matchAll(/@(Get|Post|Put|Patch|Delete)\(/g)].map((m) => m[1]); check('the readiness routes are GETs under computers:view, reading computers only through endpointVisibilityWhere', @@ -6415,15 +6437,17 @@ const POSIX_PARTS = ['POSIX_SETUP', 'POSIX_TRANSPORT', 'POSIX_HEARTBEAT', 'POSIX && /@UseGuards\(JwtAuthGuard, CapabilitiesGuard\)/.test(ctl) && /const vis = this\.acl\.endpointVisibilityWhere\(actor, businessId\);\n\s*const rows = await this\.prisma\.endpoint\.findMany\(\{\n\s*where: \{ AND: \[vis, /.test(svc) && /await this\.acl\.assertEndpointInScope\(actor, endpointId, 'computers:view'\);\n\s*const r = await this\.prisma\.endpoint\.findFirst\(\{ where: \{ AND: \[\{ id: endpointId \}, this\.acl\.endpointVisibilityWhere\(actor\)\] \}/.test(svc) - && (svc.match(/this\.prisma\.endpoint\.find/g) ?? []).length === 2, - 'msa.controller.ts / msa.service.ts'); + && (svc.match(/this\.prisma\.endpoint\.find/g) ?? []).length === 3 + && /const r = await this\.prisma\.endpoint\.findUnique\(\{ where: \{ id: endpointId \}, select: READ_SELECT \}\);/.test(svc.slice(svc.indexOf('async preflightReadiness('))) + && !/@\w+\(/.test(svc.slice(svc.indexOf('async preflightReadiness('), svc.indexOf('async pollWanted('))), + 'msa.controller.ts / msa.service.ts (0.72: preflightReadiness reads by id for MsaManagedService, which scope-checked first; it is not a route)'); check('0087 CHECKs the schema, version, build, service, cli, counts and not_run', ['RustdeskPreflight_schema_check', 'RustdeskPreflight_version_check', 'RustdeskPreflight_build_check', 'RustdeskPreflight_service_check', 'RustdeskPreflight_cli_check', 'RustdeskPreflight_keys_check', 'RustdeskPreflight_keysOk_check', 'RustdeskPreflight_not_run_check'].every((c) => mig.includes(`"${c}" CHECK`)) && /ON DELETE CASCADE/.test(mig), '0087 migration'); check('MSA readiness: the suites prove it', - / msa-readiness;/.test(read('scripts/run-e2e.sh')) && /unit-msa-readiness\.mjs/.test(read('.github/workflows/ci.yml')) + / msa-readiness[ ;]/.test(read('scripts/run-e2e.sh')) && /unit-msa-readiness\.mjs/.test(read('.github/workflows/ci.yml')) && /TestLabRustdeskPreflight/.test(read('.github/workflows/lab-windows.yml')), 'e2e-msa-readiness.mjs in run-e2e.sh, unit-msa-readiness.mjs in CI, TestLabRustdeskPreflight in the Windows lab'); } @@ -6488,18 +6512,27 @@ const POSIX_PARTS = ['POSIX_SETUP', 'POSIX_TRANSPORT', 'POSIX_HEARTBEAT', 'POSIX deployOn.length === 0 && !/MSA_GRANTS/.test(read('scripts/run-e2e.sh')), deployOn.join(', ')); check('a middleware answers 404 MSA_NOT_ENABLED on every grant route before the throttler, the session guard or the handler', /if \(!msaGrantsEnabled\(\)\) throw new NotFoundException\(\{ code: MSA_NOT_ENABLED,/.test(flag) - && /consumer\.apply\(MsaGrantsGate\)\.forRoutes\(MsaGrantsController, MsaAgentController\);/.test(mod) + && /consumer\.apply\(MsaGrantsGate\)\.forRoutes\(MsaGrantsController, MsaAgentController, MsaManagedController\);/.test(mod) && J([...ctl.matchAll(/^export class (\w+Controller)/gm)].map((m) => m[1])) === J(['MsaGrantsController', 'MsaAgentController']), 'msa-grants-flag.ts MsaGrantsGate; msa-grants.module.ts configure'); const publicMethods = [...svc.matchAll(/^ async (\w+)\(/gm)].map((m) => m[1]); const firstLine = (name) => svc.slice(svc.indexOf(` async ${name}(`)).split('\n')[1]?.trim(); check('every public MsaGrantService method asserts the switch first', - J(publicMethods) === J(['publicKeys', 'issueTest', 'listForEndpoint', 'poll']) && publicMethods.every((m) => firstLine(m) === 'this.assertEnabled();') + J(publicMethods) === J(['publicKeys', 'ensureKey', 'activePublishedKeyId', 'issueTest', 'listForEndpoint', 'poll', 'reveal']) && publicMethods.every((m) => firstLine(m) === 'this.assertEnabled();') && /private assertEnabled\(\) \{\n\s*if \(!msaGrantsEnabled\(\)\) throw new NotFoundException\(\{ code: MSA_NOT_ENABLED,/.test(svc), `methods: ${publicMethods.join(', ')}`); const writers = files.filter((f) => /msaGrant(Key)?\.(create|update|updateMany|upsert|delete|deleteMany|createMany)\(/.test(read(f))); - check('only MsaGrantService writes MsaGrant and MsaGrantKey', J(writers.map(rel)) === J(['msa/msa-grant.service.ts']), writers.map(rel).join(', ')); + const keyWriters = files.filter((f) => /msaGrantKey\.(create|update|updateMany|upsert|delete|deleteMany|createMany)\(/.test(read(f))); + const mgd = read(`${SRC}/msa/msa-managed.service.ts`); + // 0.72: MsaManagedService moves a computer's own grants on the agent's + // reports and cancels undelivered ones on rollback — conditional + // updateMany only, never a create, delete or key write (§82). + check('only MsaGrantService creates grants or writes keys; MsaManagedService only moves grants by conditional updateMany', + J(writers.map(rel)) === J(['msa/msa-grant.service.ts', 'msa/msa-managed.service.ts']) && J(keyWriters.map(rel)) === J(['msa/msa-grant.service.ts']) + && !/msaGrant\.(create|update|upsert|delete|deleteMany|createMany)\(/.test(mgd) + && (mgd.match(/msaGrant\.updateMany\(\{ where: (g\(\[|\{ \.\.\.g\(\[|\{ endpointId: ep\.id, state: 'issued' \})/g) ?? []).length === (mgd.match(/msaGrant\.updateMany\(/g) ?? []).length, + writers.map(rel).join(', ')); const purposeUsers = files.filter((f) => /rem0te-msa-grant-(key|pw|envelope)-v1/.test(read(f))).map(rel); check('the grant key, password and envelope purposes are used only in MsaGrantService (and declared in secret-box)', J(purposeUsers.sort()) === J(['common/secret-box.ts', 'msa/msa-grant.service.ts']) @@ -6512,9 +6545,10 @@ const POSIX_PARTS = ['POSIX_SETUP', 'POSIX_TRANSPORT', 'POSIX_HEARTBEAT', 'POSIX const issueRet = svc.slice(svc.indexOf("this.waiters.get(ep.id)?.wake('grant');"), svc.indexOf('// ── Reading')); const listSel = svc.slice(svc.indexOf(' async listForEndpoint('), svc.indexOf('// ── The device long-poll')); check('no audit meta, log line or answer carries the private key, the password or the envelope', - auditCalls.length === 2 && auditCalls.every((c) => !/password|privatePem|privateKeyEnc|envelope|\bsig\b/i.test(c)) - && /meta: \{ keyId: k\.keyId \}/.test(auditCalls.join('\n')) - && /meta: \{ grantId: grant\.grantId, endpointId: ep\.id, mode: grant\.mode, consent: grant\.consent, keyId: key\.keyId, source: 'test' \}/.test(auditCalls.join('\n')) + auditCalls.length === 4 && auditCalls.every((c) => !/password|privatePem|privateKeyEnc|envelope|\bsig\b/i.test(c.replace("'MSA_PASSWORD_REVEALED'", ''))) + && (auditCalls.join('\n').match(/meta: \{ keyId: k\.keyId \}/g) ?? []).length === 2 + && /meta: \{ grantId: grant\.grantId, endpointId: ep\.id, mode: grant\.mode, consent: grant\.consent, keyId: key\.keyId, source: 'test', managed: !!managed \}/.test(auditCalls.join('\n')) + && /meta: \{ grantId: g\.id, endpointId: ep\.id \}/.test(auditCalls.join('\n')) && logLines.length >= 1 && logLines.every((l) => !/password|privatePem|envelope\b|envelopeEnc|passwordEnc/i.test(l)) && !/password/.test(issueRet) && !/envelopeEnc: true|passwordEnc: true/.test(listSel) && !/privateKeyEnc/.test(svc.slice(svc.indexOf(' async publicKeys('), svc.indexOf('// ── Issuing'))), @@ -6541,7 +6575,7 @@ const POSIX_PARTS = ['POSIX_SETUP', 'POSIX_TRANSPORT', 'POSIX_HEARTBEAT', 'POSIX const importers = files.filter((f) => /from '[^']*msa-grant\.service'|from '[^']*msa-grants\.module'/.test(read(f))).map(rel).sort(); check('issuance is not reachable from Connect: one caller (the test route), the module exports nothing, nothing outside it imports the service', J(callers) === J(['msa/msa-grant.controller.ts']) && !/exports:/.test(mod) - && J(importers) === J(['app.module.ts', 'msa/msa-grant.controller.ts', 'msa/msa-grants.module.ts']) + && J(importers) === J(['app.module.ts', 'msa/msa-grant.controller.ts', 'msa/msa-grants.module.ts', 'msa/msa-managed.controller.ts', 'msa/msa-managed.service.ts']) && files.filter((f) => /sessions|launcher|connect/.test(rel(f))).every((f) => !/MsaGrant|msaGrant|msa\/grant/.test(read(f))), `callers ${J(callers)}; importers ${J(importers)}`); @@ -6553,7 +6587,8 @@ const POSIX_PARTS = ['POSIX_SETUP', 'POSIX_TRANSPORT', 'POSIX_HEARTBEAT', 'POSIX const pollCtl = ctl.slice(ctl.indexOf("@Controller('msa/agent')")); check('the poll checks the device secret before reading anything, then admits only the signed Windows agent of an assigned computer', iAuth > 0 && iSigned > iAuth && iPool > iSigned && iFirstGrant > iPool && pollFn.indexOf('this.prisma.') > iAuth - && /@Post\('poll'\)\n\s*@Public\(\)\n\s*@RateLimit\(120\)/.test(pollCtl) && (ctl.match(/@Public\(\)/g) ?? []).length === 1 + && /@Post\('poll'\)\n\s*@Public\(\)\n\s*@RateLimit\(120\)/.test(pollCtl) && (ctl.match(/@Public\(\)/g) ?? []).length === 2 + && /@Post\('report'\)\n\s*@Public\(\)\n\s*@RateLimit\(120\)\n\s*@HttpCode\(HttpStatus\.OK\)\n\s*async report\(@Body\(\) body: unknown\) \{\n\s*return \{ success: true, data: await this\.managed\.report\(body\) \};/.test(pollCtl) && /where: \{ id: \{ in: ackIds \}, endpointId: ep\.id, state: 'issued', notAfter: \{ gte: new Date\(now\) \} \},/.test(pollFn) && /if \(why === 'superseded'\) return \{ grants: \[\]/.test(pollFn), 'msa-grant.service.ts poll; msa-grant.controller.ts MsaAgentController'); @@ -6571,12 +6606,16 @@ const POSIX_PARTS = ['POSIX_SETUP', 'POSIX_TRANSPORT', 'POSIX_HEARTBEAT', 'POSIX const goImports = [...(/import \(([\s\S]*?)\)/.exec(ggo)?.[1] ?? '').matchAll(/"([^"]+)"/g)].map((m) => m[1]); const goImporters = tree('tools/windows-installer', (n) => n.endsWith('.go')) .filter((f) => /"github\.com\/agit8or1\/rem0te\/windows-installer\/internal\/msa\/grant"/.test(read(f))); - check('the Go verifier is pure (no clock, file, network or process) and imported by no command or package', + // 0.72: imported by the enforcement package (to verify each grant) and by + // internal/agent (to parse the signed msa/grant-keys.json): nothing else. + check('the Go verifier is pure (no clock, file, network or process) and imported only by internal/msa/enforce and internal/agent', J(goImports) === J(['bytes', 'crypto/ed25519', 'encoding/base64', 'encoding/json', 'io', 'regexp', 'time']) && !/time\.Now\(/.test(ggo) - && goImporters.length === 0, + && J(goImporters.filter((f) => !f.endsWith('_test.go'))) === J(['tools/windows-installer/internal/agent/agent.go', 'tools/windows-installer/internal/msa/enforce/enforce.go', 'tools/windows-installer/internal/msa/enforce/poller.go']), `imports ${J(goImports)}; imported by ${goImporters.join(', ')}`); - check('0088: the closed state set, the five-minute window, the limits, sealed columns and one active key', + const mig89 = read('apps/api/prisma/migrations/0089_msa_managed/migration.sql'); + check('0088: the closed state set (0089 adds applied, failed, ended), the five-minute window, the limits, sealed columns and one active key', /CHECK \("state" IN \('issued', 'delivered', 'expired', 'cancelled'\)\)/.test(mig) + && /CHECK \("state" IN \('issued', 'delivered', 'expired', 'cancelled', 'applied', 'failed', 'ended'\)\)/.test(mig89) && /CHECK \("notAfter" > "notBefore" AND "notAfter" - "notBefore" <= interval '5 minutes'\)/.test(mig) && /CHECK \("maxMinutes" BETWEEN 1 AND 480\)/.test(mig) && /CHECK \("idleMinutes" BETWEEN 1 AND 120 AND "idleMinutes" <= "maxMinutes"\)/.test(mig) && /CREATE UNIQUE INDEX "MsaGrantKey_one_active" ON "MsaGrantKey" \(\(true\)\) WHERE "retiredAt" IS NULL;/.test(mig) @@ -6588,6 +6627,234 @@ const POSIX_PARTS = ['POSIX_SETUP', 'POSIX_TRANSPORT', 'POSIX_HEARTBEAT', 'POSIX 'e2e-msa-grants.mjs in run-e2e.sh, unit-msa-grants.mjs in CI, the shared fixture'); } +// ── §82 (0.72): Managed Secure Access enforcement, the managed test session, cutover and rollback ── +// Build step 4 of docs/managed-secure-access.md, behind MSA_GRANTS (off). +// A computer changes only when a Platform Admin moves that ONE computer: +// - the heartbeat says msaPoll only to an authenticated signed agent +// that may act, only with the switch on and a managed row, and the +// signed heartbeat starts `msa-poller` (no argument) only on that; +// - only MsaManagedService writes MsaManagedComputer; every public +// method asserts the switch first; cutover and confirm are a Platform +// Admin's with msa.cutover, the reveal with msa.reveal, rollback never +// asks; no route takes a group or a business; +// - cutover: scope, the pool, not already managed, every blocker +// (Compatible readiness, an enforcing agent, no `remote` pause, a +// published grant key), the audit row, then the row; +// - a report is parsed strictly, then the device secret, before any read; +// - the ceiling is view-only on both sides, compiled into the agent; +// - the agent: one enforcement exec site that runs only what +// enforce.Valid accepts, the installed rustdesk.exe, no shell; grant +// keys only from the signed msa/grant-keys.json; the replay set +// written before anything changes; no password in a log or report; +// - a verified computer's legacy password is neither revealed, +// launched, rotated nor set, and a staged rotation waits; +// - the release host publishes the grant keys; the portal only shows +// the two commands (§56). +{ + console.log('\n§82 Managed Secure Access enforcement (MSA_GRANTS, off)'); + const J = JSON.stringify; + const SRC = 'apps/api/src'; + const files = walk(SRC); + const rel = (f) => f.replace(/^.*apps\/api\/src\//, ''); + const enr = read(`${SRC}/enrollment/enrollment.service.ts`); + const msvc = read(`${SRC}/msa/msa.service.ts`); + const mgd = read(`${SRC}/msa/msa-managed.service.ts`); + const mctl = read(`${SRC}/msa/msa-managed.controller.ts`); + const gsvc = read(`${SRC}/msa/msa-grant.service.ts`); + const gctl = read(`${SRC}/msa/msa-grant.controller.ts`); + const managedTs = read(`${SRC}/msa/managed.ts`); + const eps = read(`${SRC}/endpoints/endpoints.service.ts`); + const ws = read(`${SRC}/public/windows-script.ts`); + const cat = read(`${SRC}/security-controls/confirm-catalog.ts`); + const goDir = 'tools/windows-installer'; + const args = read(`${goDir}/internal/msa/enforce/args.go`); + const enf = read(`${goDir}/internal/msa/enforce/enforce.go`); + const pol = read(`${goDir}/internal/msa/enforce/poller.go`); + const win = read(`${goDir}/msa_poller_windows.go`); + const agentGo = read(`${goDir}/internal/agent/agent.go`); + const mainGo = read(`${goDir}/main.go`); + const stripGo = (s) => s.split('\n').filter((l) => !/^\s*\/\//.test(l)).join('\n'); + const body = (src, sig) => { const i = src.indexOf(sig); if (i < 0) return ''; const j = src.indexOf('\n }\n', i); return src.slice(i, j); }; + + // The heartbeat. + const iPoll = enr.indexOf('msaPoll = await this.msa.pollWanted(node.endpointId);'); + const guard = enr.lastIndexOf('if (', iPoll); + check('msaPoll: only from an authenticated signed heartbeat that may act, after the not-may-act and pooled returns, only with the switch on and a managed row', + (enr.match(/this\.msa\.pollWanted\(/g) ?? []).length === 1 && enr.slice(guard, iPoll).startsWith("if (authenticated && mayAct && kind === 'signed') {") + && iPoll > enr.indexOf('if (authenticated && !mayAct) {') && iPoll > enr.indexOf('if (authenticated && pooled) {') + && /\.\.\.\(msaPoll \? \{ msaPoll: true \} : \{\}\),/.test(enr) + && /async pollWanted\(endpointId: string\): Promise \{\n\s*if \(!msaGrantsEnabled\(\)\) return false;\n\s*return !!\(await this\.prisma\.msaManagedComputer\.findUnique\(/.test(msvc) + && files.filter((f) => /\bmsaPoll\b/.test(read(f))).map(rel).every((f) => ['enrollment/enrollment.service.ts', 'public/windows-script.ts'].includes(f)), + 'enrollment.service.ts heartbeat; MsaService.pollWanted'); + check('the signed heartbeat starts msa-poller (no argument) only when told msaPoll, and the subcommand takes no argument', + /if \(\$resp\.data\.msaPoll -eq \$true -and \(Test-Path -LiteralPath \$agentExe\)\) \{\n\s*Start-Process -FilePath \$agentExe -ArgumentList @\('msa-poller'\) -WindowStyle Hidden/.test(ws) + && (ws.match(/'msa-poller'/g) ?? []).length === 1 + && /if args\[0\] == "msa-poller" \{\n\s*return cmdMsaPoller\(args\[1:\]\)/.test(mainGo) + && /if len\(args\) > 0 \{\n\s*fmt\.Fprintln\(logf, " msa-poller: takes no arguments"\)\n\s*return 2/.test(win), + 'windows-script.ts actionHook; main.go; msa_poller_windows.go cmdMsaPoller'); + check('a staged legacy rotation waits while managed/rotationHeld says so (verified, failing, rolling back, or a grant in flight)', + /if \(refreshed\?\.pendingPassword && !\(await this\.msa\.rotationHeld\(node\.endpointId\)\)\) \{/.test(enr) + && /export function rotationHeld\(row: \{ state: ManagedState \} \| null, grantInFlight: boolean\): boolean \{\n\s*if \(!row\) return false;\n\s*return row\.state !== 'pending' \|\| grantInFlight;/.test(managedTs), + 'enrollment.service.ts; managed.ts rotationHeld'); + + // Who writes, who may. + const rowWriters = files.filter((f) => /msaManagedComputer\.(create|update|updateMany|upsert|delete|deleteMany|createMany)\(/.test(read(f))).map(rel); + const pub = [...mgd.matchAll(/^ async (\w+)\(/gm)].map((m) => m[1]); + const first = (name) => mgd.slice(mgd.indexOf(` async ${name}(`)).split('\n')[1]?.trim(); + check('only MsaManagedService writes MsaManagedComputer, and every public method asserts the switch first', + J(rowWriters) === J(['msa/msa-managed.service.ts']) && J(pub) === J(['view', 'cutover', 'confirm', 'rollback', 'report']) + && pub.every((m) => first(m) === 'this.assertEnabled();') + && /private assertEnabled\(\) \{\n\s*if \(!msaGrantsEnabled\(\)\) throw new NotFoundException\(\{ code: MSA_NOT_ENABLED,/.test(mgd), + `writers ${J(rowWriters)}; methods ${J(pub)}`); + const route = (sig) => mctl.slice(mctl.indexOf(sig), mctl.indexOf('\n }\n', mctl.indexOf(sig))); + const cut = route("@Post(':endpointId/cutover')"), conf = route("@Post(':endpointId/confirm')"), rb = route("@Post(':endpointId/rollback')"), rv = route("@Post('grants/:grantId/reveal')"); + const routes = [...mctl.matchAll(/@(Get|Post|Put|Patch|Delete)\('([^']*)'\)/g)].map((m) => `${m[1]} ${m[2]}`); + check('cutover and confirm: Platform Admin + msa.cutover; the reveal: Platform Admin + msa.reveal; rollback: Platform Admin and never asks; no group or business route', + J(routes) === J(['Get :endpointId', 'Post :endpointId/cutover', 'Post :endpointId/confirm', 'Post :endpointId/rollback', 'Post grants/:grantId/reveal']) + && [cut, conf, rv, rb].every((r) => /@UseGuards\(PlatformAdminGuard\)/.test(r)) + && /assertFresh\(this\.method\(req\), \{ action: 'msa\.cutover',/.test(cut) && /assertFresh\(this\.method\(req\), \{ action: 'msa\.cutover',/.test(conf) + && /assertFresh\(this\.method\(req\), \{ action: 'msa\.reveal',/.test(rv) && !/assertFresh|stepUp/.test(rb) + && cut.indexOf('assertFresh(') < cut.indexOf('this.managed.cutover(') && conf.indexOf('assertFresh(') < conf.indexOf('this.managed.confirm(') + && rv.indexOf('assertFresh(') < rv.indexOf('this.grants.reveal(') + && !/businessId|groupId|customerId/.test(mctl) && /@Controller\('msa\/managed'\)/.test(mctl), + `routes ${J(routes)}`); + check('the catalog names msa.cutover and msa.reveal (default off, §62); the always-ask set is unchanged', + /\{ key: 'msa\.cutover', group: 'Devices & enrolment', label: 'Managed Secure Access cutover', default: 'off',/.test(cat) + && /\{ key: 'msa\.reveal', group: 'Devices & enrolment', label: 'Managed test session password', default: 'off',/.test(cat), + 'confirm-catalog.ts'); + + // Cutover order. + const cb = body(mgd, ' async cutover('); + const order = [ + 'this.assertEnabled();', + 'const ep = await this.computer(actor, endpointId);', + 'assertAssigned(ep);', + 'if (await this.row(ep.id)) throw new ConflictException({ code: \'MSA_ALREADY_MANAGED\'', + 'const blockers = await this.cutoverBlockers(ep);', + "action: 'MSA_CUTOVER'", + "await this.prisma.msaManagedComputer.create({ data: { endpointId: ep.id, state: 'pending', requestedById: actor.userId } });", + ].map((x) => cb.indexOf(x)); + const blk = body(mgd, ' private async cutoverBlockers('); + check('cutover: scope, the pool, not already managed, every blocker, the audit row (logOrFail), then the row', + order.every((i, k) => i >= 0 && (k === 0 || i > order[k - 1])) && /await this\.audit\.logOrFail\(\{\n\s*action: 'MSA_CUTOVER'/.test(cb) + && /await this\.acl\.assertEndpointInScope\(actor, endpointId, 'computers:view'\);\n\s*const ep = await this\.prisma\.endpoint\.findFirst\(\{\n\s*where: \{ AND: \[\{ id: endpointId \}, this\.acl\.endpointVisibilityWhere\(actor\)\] \},/.test(mgd) + && ["'ENDPOINT_UNASSIGNED'", "'MSA_SIGNED_AGENT_REQUIRED'", "pr.readiness.state !== 'compatible'", 'compareVersion(pr?.agentVersion ?? null, MIN_ENFORCING_AGENT)', + "activePause(this.prisma, 'remote', ep.customerId)", 'this.grants.activePublishedKeyId()'].every((x) => blk.includes(x)) + && /export const MIN_ENFORCING_AGENT = '0\.72\.0';/.test(read(`${SRC}/msa/readiness.ts`)), + `order ${J(order)}`); + const confirmB = body(mgd, ' async confirm('); + check('confirm needs a test session since cutover that read back and connected; verified is a conditional move from pending', + /if \(!row\.readbackOkAt \|\| !\(await this\.testSessionConnected\(ep\.id, row\.requestedAt\)\)\) \{/.test(confirmB) + && /where: \{ endpointId: ep\.id, state: 'pending' \}, data: \{ state: 'verified', verifiedAt: new Date\(\), verifiedById: actor\.userId \}/.test(confirmB) + && confirmB.indexOf("action: 'MSA_VERIFIED'") < confirmB.indexOf('msaManagedComputer.updateMany('), + 'MsaManagedService.confirm'); + const rbB = body(mgd, ' async rollback('); + check('rollback stages a fresh permanent password through the existing rotation path and forces only a computer already rolling back', + /await this\.endpoints\.stageRotationForMsa\(ep\.id, actor\.userId, 'msa_rollback'\);/.test(rbB) + && /if \(row\.state === 'rollback_pending'\) \{\n\s*if \(!force\) throw/.test(rbB) + && /deleteMany\(\{ where: \{ endpointId: ep\.id, state: 'rollback_pending' \} \}\)/.test(rbB) + && (eps.match(/this\.stagePendingPassword\(/g) ?? []).length === 2, + 'MsaManagedService.rollback; EndpointsService.stageRotationForMsa and rotateCredential share stagePendingPassword'); + + // Reports. + const rep = body(mgd, ' async report('); + const iParse = rep.indexOf('const p = ReportBody.safeParse(raw);'); + const iAuthR = rep.indexOf("const dev = await this.enrollment.authenticateDevice(r.rustdeskId, r.agentSecret, 'msa_report_unauthenticated');"); + check('a report: strict parse, then the device secret, before any read; only the signed Windows agent of an assigned computer; no password field', + iParse > 0 && iAuthR > iParse && rep.indexOf('this.prisma.') > iAuthR && rep.indexOf('assertAssigned(ep);') > rep.indexOf('runsSignedAgent(') + && /export const ReportBody = z\.strictObject\(\{/.test(managedTs) && !/password\s*:/.test(managedTs.slice(managedTs.indexOf('export const ReportBody'), managedTs.indexOf('export type Report '))) + && /keys: z\.array\(z\.enum\(REPORT_KEYS\)\)/.test(managedTs) && /outcome: z\.string\(\)\.regex\(\/\^\[a-z_\]\{1,40\}\$\/\)/.test(managedTs), + 'MsaManagedService.report; managed.ts ReportBody'); + const auditM = [...mgd.matchAll(/this\.audit\.(log|logOrFail)\(\{[\s\S]*?\}\);/g)].map((m) => m[0]); + check('no managed audit row, log line or answer carries a password', + auditM.length >= 8 && auditM.every((c) => !/password|passwordEnc|envelope/i.test(c)) + && [...mgd.matchAll(/this\.logger\.\w+\([^;]*\);/g)].every((m) => !/password/i.test(m[0])) && !/passwordEnc|envelopeEnc/.test(mgd), + `${auditM.length} audit calls`); + const revB = body(gsvc, ' async reveal('); + check('the one-time password: shown once, only for an applied grant on a visible computer, audited first, claimed by a conditional write before it is opened', + revB.indexOf("if (g.state !== 'applied')") > 0 && revB.indexOf('await this.audit.logOrFail({') > revB.indexOf("if (g.state !== 'applied')") + && revB.indexOf("where: { id: g.id, state: 'applied', revealedAt: null }") > revB.indexOf('await this.audit.logOrFail({') + && revB.indexOf("openSecret(this.encKey, 'rem0te-msa-grant-pw-v1'") > revB.indexOf("where: { id: g.id, state: 'applied', revealedAt: null }") + && /this\.acl\.endpointVisibilityWhere\(actor\)/.test(revB), + 'MsaGrantService.reveal'); + + // The ceiling. + check('the ceiling is view-only with nothing beyond, compiled into the agent; the portal refuses a managed grant above it first', + /var Ceiling = grant\.Ceiling\{Mode: "view"\}/.test(enf) && /Ceiling: Ceiling,/.test(pol) + && /mode: 'view',\n\s*permissions: \{ clipboard: false, files: false, audio: false, tunnel: false, restart: false \},/.test(managedTs) + && /if \(!withinCeiling\(b\.mode \?\? 'view', perms\)\) throw new ConflictException\(\{ code: 'MSA_ABOVE_CEILING'/.test(gsvc) + && !/Ceiling\s*=|Ceiling:\s*(ans|a|p\.state|g)\./.test(pol.replace('Ceiling: Ceiling,', '')), + 'enforce.Ceiling; managed.ts MANAGED_CEILING; MsaGrantService.issueTest'); + + // The agent. + const execs = [...stripGo(win).matchAll(/exec\.\w+\(/g)]; + const run = win.slice(win.indexOf('func (r enforceRunner) Run('), win.indexOf('// ── the portal')); + check('one enforcement exec site: enforce.Valid first, the installed rustdesk.exe the RustDesk service runs, an argument array, no shell, no window, capped, never logged', + execs.length === 1 && run.indexOf('if !enforce.Valid(args) {') > 0 && run.indexOf('if !enforce.Valid(args) {') < run.indexOf('exec.CommandContext(') + && /cmd := exec\.CommandContext\(ctx, r\.exe, args\.\.\.\)/.test(run) && /CreationFlags: windows\.CREATE_NO_WINDOW/.test(run) + && /if _, expected := rustdeskService\(r\.exe\); !expected \{/.test(run) && /E: &enforce\.Enforcer\{R: enforceRunner\{exe: installedRustdeskExe\(\)\}\},/.test(win) + && !/cmd\.exe|powershell|"\/c"/i.test(stripGo(win)) && !/Fprint\w*\([^)]*\bargs\b/.test(win.replace('fmt.Fprintln(logf, " msa-poller: takes no arguments")', '')), + 'msa_poller_windows.go enforceRunner.Run'); + const pwArgs = args.slice(args.indexOf('func PasswordArgs('), args.indexOf('}\n', args.indexOf('return []string{"--password", pw}')) + 2); + check('the argument lists are closed: SetArgs a closed value per key, RestoreArgs the preflight charset, PasswordArgs 24 alphanumerics, StopServiceArgs Y or N', + /if !passwordRE\.MatchString\(pw\) \{\n\s*return nil\n\s*\}\n\s*return \[\]string\{"--password", pw\}/.test(pwArgs) + && /"verification-method":\s+\{"use-permanent-password": true\},/.test(args) && /"allow-auto-disconnect": \{"Y": true\},/.test(args) + && /restoreRE = regexp\.MustCompile\(`\^\[A-Za-z0-9_\.:-\]\{0,64\}\$`\)/.test(args) + && (stripGo(args).match(/\[\]string\{"--option"/g) ?? []).length === 5 && (stripGo(args).match(/\[\]string\{"--password"/g) ?? []).length === 1 + && /var Keys = msa\.Keys/.test(args), + 'internal/msa/enforce/args.go'); + const handle = pol.slice(pol.indexOf('func (p *Poller) handle('), pol.indexOf('func (p *Poller) pruneSeen(')); + check('each grant: keys from the signed chain only, verified, the signed pause, the replay set written, the settings saved, before anything changes', + /keys, paused, err := p\.H\.Trust\(ctx\)\n\s*if err != nil \|\| len\(keys\) == 0 \{\n\s*refuse\(NoKeys, nil\)/.test(handle) + && handle.indexOf('grant.Verify(') < handle.indexOf('paused(g.BusinessID, rid)') + && handle.indexOf('if err := p.S.SaveSeen(p.seen); err != nil {') < handle.indexOf('p.E.Apply(ctx, g)') + && handle.indexOf('p.S.SaveSaved(') < handle.indexOf('p.E.Apply(ctx, g)') + && /if s, err := p\.S\.LoadSaved\(\); err != nil \|\| s == nil \{/.test(handle) + && /if _, err := c\.Fetch\(grant\.KeysTarget, dst\); err != nil \{/.test(agentGo) && /keys, err := grant\.ParseKeys\(raw\)/.test(agentGo) + && /keys, pz, err := agent\.MsaTrust\(/.test(win), + 'enforce/poller.go handle; agent.MsaTrust'); + check('apply refuses on any readback disagreement and ends the session; nothing weaker is substituted; the password is never reported or logged', + /if bad := e\.Set\(ctx, Desired\(g\)\); len\(bad\) > 0 \{\n\s*_ = e\.EndSession\(ctx\)\n\s*return Outcome\{Code: ReadbackMismatch, Keys: bad\}/.test(enf) + && /return r\.ok\(\) && bytes\.Contains\(r\.Stdout, \[\]byte\("Done"\)\)/.test(enf) + && !/Password/.test([...pol.matchAll(/Report\{[^}]*\}/g)].map((m) => m[0]).join(' ')) && !/logf\([^)]*[Pp]assword/.test(pol) + && !/Password/.test(pol.slice(pol.indexOf('type Report struct'), pol.indexOf('// Portal is'))), + 'enforce.go Apply/SetPassword; poller.go reports'); + + // Legacy refused once verified. + check('a verified computer: legacy Reveal, Connect, rotate and set are refused (409 MSA_MANAGED / msa_managed)', + /async assertPasswordAccess\(actor: ActorContext, id: string\) \{[\s\S]{0,300}await this\.refuseMsaManaged\(id\);/.test(eps) + && /async setPassword\(actor: ActorContext, id: string, password: string \| null\): Promise \{[\s\S]{0,300}await this\.refuseMsaManaged\(id\);/.test(eps) + && /if \(await this\.msaLegacyRefused\(endpoint\.id\)\) return \{ ok: false, reason: 'msa_managed'/.test(eps) + && /code: 'MSA_MANAGED', message: 'This computer is in Managed Secure Access: its password is set by the agent/.test(eps), + 'endpoints.service.ts'); + + // The release host. + const gk = read('deploy/release/rem0te-signed-grant-key'); + const pubSh = read('deploy/release/rem0te-signed-publish'); + check('the grant keys reach agents only through the signed release: rem0te-signed-grant-key records public keys only, and publish signs them in', + /if \[\[ \$public_key == \*PRIVATE\* \|\| \$public_key == \*-----BEGIN\* \]\]; then/.test(gk) && /idOf\(pub\) !== keyId/.test(gk) && /doc\.keys\.length >= 8/.test(gk) + && /\[\[ -n \$msa_build \]\] && args\+=\(-add "msa\/grant-keys\.json=\$msa_build"\)/.test(pubSh) + && /if grep -qiE 'PRIVATE\|-----BEGIN' "\$msa_build"; then die/.test(pubSh) + && /export const MSA_GRANT_KEYS_TARGET = 'msa\/grant-keys\.json';/.test(read(`${SRC}/msa/grant-key-commands.ts`)), + 'deploy/release/rem0te-signed-grant-key, rem0te-signed-publish'); + + check('0089: the managed states, the verified/failure/rollback CHECKs, closed codes and keys, and a pooled computer refused', + (() => { + const m = read('apps/api/prisma/migrations/0089_msa_managed/migration.sql'); + return /CHECK \("state" IN \('pending', 'verified', 'enforcement_failure', 'rollback_pending'\)\)/.test(m) + && /"MsaManagedComputer_verified_check"/.test(m) && /"MsaManagedComputer_rollback_check"/.test(m) && /"MsaManagedComputer_failReason_check"/.test(m) + && /"MsaGrant_revealed_check"/.test(m) && /"MsaGrant_outcome_check"/.test(m) + && /CREATE TRIGGER "MsaManagedComputer_assigned" BEFORE INSERT ON "MsaManagedComputer"/.test(m); + })(), + '0089 migration'); + check('MSA enforcement: the suites prove it', + / msa-managed[ ;]/.test(read('scripts/run-e2e.sh')) && /unit-msa-managed\.mjs/.test(read('.github/workflows/ci.yml')) + && /TestLabRustdeskEnforce/.test(read('.github/workflows/lab-windows.yml')) + && /func TestReadbackMismatchFailsClosed\(/.test(read(`${goDir}/internal/msa/enforce/enforce_test.go`)) + && /func TestRollbackRestores\(/.test(read(`${goDir}/internal/msa/enforce/enforce_test.go`)), + 'e2e-msa-managed.mjs in run-e2e.sh, unit-msa-managed.mjs in CI, TestLabRustdeskEnforce in the Windows lab, the enforce Go tests'); +} + // ─── §18 addendum (0.59): no behavioural suite defaults to production's API ── // A dozen suites fell back to http://127.0.0.1:3001 when API_BASE was // unset. Run by hand with only DATABASE_URL set, one wrote its fixtures to diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.sh index cfb308f5..25206b7a 100755 --- a/scripts/run-e2e.sh +++ b/scripts/run-e2e.sh @@ -123,7 +123,7 @@ run() { # name, command... } echo "── self-starting suites" -for t in credentials security-features presets monitoring integration dashboard diagnostics-catalog system-inventory device-list endpoint-visibility device-views dynamic-groups add-device auto-updates group-policies reports script-library linux-agent macos-agent enrol-stepup search metric-history retention presence-cache ai-timeline ai-psa email chat tray chat-attachments polish auto-snapshots agent-health agent-auto-update dual-agent software-browse confirm-policy sso-identity alert-tickets alert-quality alert-quality-rules warranty warranty-vendors adoption msa-grants msa-readiness; do run "$t" node "scripts/e2e-$t.mjs"; done +for t in credentials security-features presets monitoring integration dashboard diagnostics-catalog system-inventory device-list endpoint-visibility device-views dynamic-groups add-device auto-updates group-policies reports script-library linux-agent macos-agent enrol-stepup search metric-history retention presence-cache ai-timeline ai-psa email chat tray chat-attachments polish auto-snapshots agent-health agent-auto-update dual-agent software-browse confirm-policy sso-identity alert-tickets alert-quality alert-quality-rules warranty warranty-vendors adoption msa-grants msa-readiness msa-managed; do run "$t" node "scripts/e2e-$t.mjs"; done for t in containment approved-action staged-patching maintenance-actions patch-policies patch-assignment software-deploy software-catalog signed-updates ticket-workflow agent-upgrade auto-migration service-process task-progress restart-windows; do if [[ -n "${RELEASE_BIN:-}" && -n "${ACTION_SIM:-}" ]]; then run "$t" node "scripts/e2e-$t.mjs" else printf '%-22s SKIPPED (RELEASE_BIN / ACTION_SIM not set)\n' "$t"; skipped+=("$t"); fi diff --git a/tools/lab/merge-evidence.mjs b/tools/lab/merge-evidence.mjs index 199f5bd7..613fb3c7 100644 --- a/tools/lab/merge-evidence.mjs +++ b/tools/lab/merge-evidence.mjs @@ -9,6 +9,7 @@ // go-evidence.jsonl one line per Go lab test (internal/labevidence) // go-os.json the Go runner's Windows edition and build // preflight-evidence-.jsonl the agent's RustDesk preflight (0.69.0) against release +// enforce-evidence-.jsonl the agent's MSA enforcement cycle (0.72.0) against release // // Every result is { id, status: pass|fail|skip, detail, real, os }. For the // RustDesk rows, "fail" means RustDesk did not do what was asked — a finding, @@ -139,9 +140,10 @@ for (const f of files.filter((p) => /rustdesk-[^/\\]+\.json$/.test(p))) { `${(net.rustdeskConnections ?? []).length} TCP connections held by rustdesk.exe at the end, ${(net.offHost ?? []).length} to an address that is not loopback ${q(net.offHost)}; firewall drop events naming rustdesk: ${net.firewallBlocks}`, os); } -// ── The agent's RustDesk preflight (0.69.0), one file per installed release ── -for (const f of files.filter((p) => /preflight-evidence-[^/\\]+\.jsonl$/.test(p))) { - const v = f.match(/preflight-evidence-([^/\\]+)\.jsonl$/)[1]; +// ── The agent's RustDesk preflight (0.69.0) and MSA enforcement cycle (0.72.0), +// one file each per installed release ── +for (const f of files.filter((p) => /(?:preflight|enforce)-evidence-[^/\\]+\.jsonl$/.test(p))) { + const v = f.match(/(?:preflight|enforce)-evidence-([^/\\]+)\.jsonl$/)[1]; const os = osOf(rustdesk[v]?.os); for (const line of readFileSync(f, 'utf8').split('\n')) { if (!line.trim()) continue; @@ -153,6 +155,9 @@ for (const v of Object.keys(rustdesk)) { if (rustdesk[v].download?.verified && !files.some((p) => p.endsWith(`preflight-evidence-${v}.jsonl`))) { problems.push(`rustdesk ${v}: no agent preflight evidence (preflight-evidence-${v}.jsonl)`); } + if (rustdesk[v].download?.verified && !files.some((p) => p.endsWith(`enforce-evidence-${v}.jsonl`))) { + problems.push(`rustdesk ${v}: no agent MSA enforcement evidence (enforce-evidence-${v}.jsonl)`); + } } // ── Go ─────────────────────────────────────────────────────────────────────── diff --git a/tools/windows-installer/internal/agent/agent.go b/tools/windows-installer/internal/agent/agent.go index 94952135..93210fa5 100644 --- a/tools/windows-installer/internal/agent/agent.go +++ b/tools/windows-installer/internal/agent/agent.go @@ -17,6 +17,7 @@ package agent import ( + "crypto/ed25519" "crypto/sha256" "encoding/hex" "encoding/json" @@ -33,6 +34,7 @@ import ( "github.com/agit8or1/rem0te/windows-installer/internal/action" "github.com/agit8or1/rem0te/windows-installer/internal/chat" + "github.com/agit8or1/rem0te/windows-installer/internal/msa/grant" "github.com/agit8or1/rem0te/windows-installer/internal/trust" ) @@ -604,6 +606,42 @@ func actionTrust(o Options, p Platform) ([]action.Key, *action.Pause, error) { return keys, signedPause(c, dir, nil), nil } +// MsaTrust (0.72) is the Managed Secure Access grant keys plus the signed +// pause, from one refresh of the signed metadata: msa/grant-keys.json is a +// TUF target the release owner publishes, so a grant key is trusted only +// through the update chain, never because the portal sent it. A key file +// that is not listed, cannot be fetched or does not parse is an error and +// the poller trusts no grant (no_keys). +func MsaTrust(o Options, p Platform) (map[string]ed25519.PublicKey, *action.Pause, error) { + if !ValidPortal(o.PortalHost) { + return nil, nil, fmt.Errorf("%w: portal host %q is not a hostname", ErrRefuse, o.PortalHost) + } + c, err := o.trustClient(p) + if err != nil { + return nil, nil, err + } + dir := filepath.Join(o.Paths.StateDir, "msa") + if err := p.SecureDir(dir); err != nil { + return nil, nil, err + } + dst := filepath.Join(dir, "grant-keys.json") + if _, err := c.Fetch(grant.KeysTarget, dst); err != nil { + return nil, nil, err + } + raw, err := os.ReadFile(dst) + if err != nil { + return nil, nil, err + } + keys, err := grant.ParseKeys(raw) + if err != nil { + return nil, nil, err + } + return keys, signedPause(c, dir, nil), nil +} + +// APIBase is the portal's API root for a pinned portal ("https://HOST/api/v1"). +func (o *Options) APIBase() string { return o.base() } + // RevocationsPath is where the portal relays the approval signer's signed // revocation statement (v0.36). const RevocationsPath = "/public/approval/revocations.json" diff --git a/tools/windows-installer/internal/msa/enforce/args.go b/tools/windows-installer/internal/msa/enforce/args.go new file mode 100644 index 00000000..32bdc802 --- /dev/null +++ b/tools/windows-installer/internal/msa/enforce/args.go @@ -0,0 +1,161 @@ +// Package enforce is the signed agent's Managed Secure Access enforcement +// (0.72, build step 4 in docs/managed-secure-access.md, §3.3, §3.7): it +// applies a verified grant to the installed RustDesk through RustDesk's own +// command line, reads every value back, sets the one-time password, ends a +// session with a password nobody is told, and on rollback restores the +// settings it saved before it first changed anything. +// +// It is portable (no Windows calls) so every decision is tested on every +// platform with a fake RustDesk. The Windows side (msa_poller_windows.go, +// enforceRunner) is its one exec site: the INSTALLED rustdesk.exe by its +// absolute path, an argument array, no shell — exactly the argument lists +// built here and nowhere else. check-security-invariants §82. +// +// The password — the grant's one-time password, or a random one nobody is +// told — goes only into PasswordArgs and the runner. It is never logged, +// journaled, reported or returned. +package enforce + +import ( + "regexp" + + "github.com/agit8or1/rem0te/windows-installer/internal/msa" +) + +// Keys are the settings enforcement changes, saves and restores: exactly the +// preflight's eleven (msa.Keys), in the same order. +var Keys = msa.Keys + +// allowed is the closed set of values enforcement itself ever sets. +var allowed = map[string]map[string]bool{ + "access-mode": {"view": true, "full": true}, + "enable-keyboard": {"Y": true, "N": true}, + "enable-clipboard": {"Y": true, "N": true}, + "enable-file-transfer": {"Y": true, "N": true}, + "enable-audio": {"Y": true, "N": true}, + "enable-tunnel": {"Y": true, "N": true}, + "enable-remote-restart": {"Y": true, "N": true}, + "approve-mode": {"click": true, "password": true}, + "verification-method": {"use-permanent-password": true}, + "allow-auto-disconnect": {"Y": true}, +} + +var ( + timeoutRE = regexp.MustCompile(`^(?:[1-9]|[1-9][0-9]|1[01][0-9]|120)$`) + passwordRE = regexp.MustCompile(`^[A-Za-z0-9]{24}$`) + // restoreRE is the preflight's answer charset: a value RustDesk printed, + // put back as it was (empty included: the option was unset). + restoreRE = regexp.MustCompile(`^[A-Za-z0-9_.:-]{0,64}$`) +) + +func isKey(k string) bool { + for _, x := range Keys { + if x == k { + return true + } + } + return false +} + +// SetArgs is the only way a value enforcement chooses reaches RustDesk: +// {"--option", key, value} for a key on the closed list and a value in that +// key's closed set; nil for anything else. +func SetArgs(key, value string) []string { + if !isKey(key) { + return nil + } + if key == "auto-disconnect-timeout" { + if !timeoutRE.MatchString(value) { + return nil + } + } else if !allowed[key][value] { + return nil + } + return []string{"--option", key, value} +} + +// RestoreArgs puts back a value the agent read before its first apply: +// {"--option", key, saved} for a key on the closed list and a value in the +// preflight's answer charset; nil for anything else. +func RestoreArgs(key, saved string) []string { + if !isKey(key) || !restoreRE.MatchString(saved) { + return nil + } + return []string{"--option", key, saved} +} + +// PasswordArgs is the only way a password reaches RustDesk: {"--password", +// pw} for 24 characters from A–Z a–z 0–9; nil for anything else. +func PasswordArgs(pw string) []string { + if !passwordRE.MatchString(pw) { + return nil + } + return []string{"--password", pw} +} + +// StopServiceArgs: {"--option", "stop-service", "Y"} or "N". RustDesk ends +// every session and stops serving on Y, and serves again on N (0.68.3 lab). +func StopServiceArgs(stop bool) []string { + if stop { + return []string{"--option", "stop-service", "Y"} + } + return []string{"--option", "stop-service", "N"} +} + +// ReadArgs is the preflight's read, {"--option", key} with no value, for the +// eleven keys, plus the one read enforcement adds: stop-service, to confirm +// RustDesk serves again after a session was ended. +func ReadArgs(key string) []string { + if key == "stop-service" { + return []string{"--option", "stop-service"} + } + return msa.ReadArgs(key) +} + +// emptyMeans: RustDesk removes an option set to its default, so reading it +// back prints nothing. For these an empty readback is the default named +// here (the 0.68.3 lab's table, rustdesk-probe.ps1). +var emptyMeans = map[string]string{ + "enable-keyboard": "Y", "enable-clipboard": "Y", "enable-file-transfer": "Y", "enable-audio": "Y", + "enable-tunnel": "Y", "enable-remote-restart": "Y", "allow-auto-disconnect": "N", + "verification-method": "use-both-passwords", "stop-service": "N", +} + +// Matches: the value read back is the value wanted, or empty where empty +// means exactly that default. +func Matches(key, got, want string) bool { + if got == want { + return true + } + return got == "" && emptyMeans[key] != "" && emptyMeans[key] == want +} + +// Valid reports whether args is exactly one of the lists this package +// builds: a read, a set, a restore, a password or a stop-service toggle. The +// Windows runner refuses anything else before it starts a process. +func Valid(args []string) bool { + eq := func(b []string) bool { + if b == nil || len(b) != len(args) { + return false + } + for i := range b { + if b[i] != args[i] { + return false + } + } + return true + } + switch len(args) { + case 2: + if args[0] == "--password" { + return eq(PasswordArgs(args[1])) + } + return eq(ReadArgs(args[1])) + case 3: + if args[1] == "stop-service" { + return eq(StopServiceArgs(true)) || eq(StopServiceArgs(false)) + } + return eq(SetArgs(args[1], args[2])) || eq(RestoreArgs(args[1], args[2])) + } + return false +} diff --git a/tools/windows-installer/internal/msa/enforce/enforce.go b/tools/windows-installer/internal/msa/enforce/enforce.go new file mode 100644 index 00000000..3e6a3add --- /dev/null +++ b/tools/windows-installer/internal/msa/enforce/enforce.go @@ -0,0 +1,315 @@ +package enforce + +import ( + "bytes" + "context" + "crypto/rand" + "errors" + "strconv" + "time" + + "github.com/agit8or1/rem0te/windows-installer/internal/msa" + "github.com/agit8or1/rem0te/windows-installer/internal/msa/grant" +) + +// Ceiling is the most a managed computer allows in 0.72: view-only, nothing +// beyond. Compiled in, not taken from the portal (a portal-supplied ceiling +// would be the portal asking itself). The portal's MANAGED_CEILING is the +// same (§82). +var Ceiling = grant.Ceiling{Mode: "view"} + +// Outcome codes the agent reports (the portal's AGENT_OUTCOMES). +const ( + ReadbackMismatch = "readback_mismatch" + PasswordNotApplied = "password_not_applied" + SaveFailed = "save_failed" + RustdeskNotReady = "rustdesk_not_ready" + NoKeys = "no_keys" + MaxMinutes = "max_minutes" + NoConnection = "no_connection" + Disconnected = "disconnected" + Rollback = "rollback" + Superseded = "superseded" + NotEnabled = "not_enabled" + StopFailed = "stop_failed" +) + +// Outcomes lists them in the portal's order. +var Outcomes = []string{ + ReadbackMismatch, PasswordNotApplied, SaveFailed, RustdeskNotReady, NoKeys, + MaxMinutes, NoConnection, Disconnected, Rollback, Superseded, NotEnabled, StopFailed, +} + +// Bounds. +const ( + // CallTimeout bounds one rustdesk.exe call; the lab measured 80–190 ms. + CallTimeout = 15 * time.Second + // StopPause is how long stop-service stays Y: the lab saw the listener + // close within about 1.3 s. + StopPause = 3 * time.Second +) + +// Result is one rustdesk.exe call's raw outcome. +type Result struct { + Stdout []byte + ExitCode int + TimedOut bool + Err error +} + +func (r Result) ok() bool { return !r.TimedOut && r.Err == nil && r.ExitCode == 0 } + +// Runner runs the installed rustdesk.exe with exactly args — one of the +// lists SetArgs, RestoreArgs, PasswordArgs, StopServiceArgs or ReadArgs +// built. The Windows runner refuses anything else. +type Runner interface { + Run(ctx context.Context, args []string) Result +} + +// Saved is what the agent read before it first changed anything: the value +// of every key, as RustDesk printed it. Kept in a SYSTEM-only file until a +// rollback puts it back. +type Saved struct { + Schema string `json:"schema"` + SavedAt string `json:"savedAt"` + Values map[string]string `json:"values"` +} + +// SavedSchema names the saved file. +const SavedSchema = "rem0te-msa-saved/1" + +// Enforcer applies and undoes. Sleep and Password are test hooks. +type Enforcer struct { + R Runner + Sleep func(time.Duration) + Password func() string +} + +func (e *Enforcer) sleep(d time.Duration) { + if e.Sleep != nil { + e.Sleep(d) + return + } + time.Sleep(d) +} + +func (e *Enforcer) call(ctx context.Context, args []string) Result { + if args == nil { + return Result{Err: errors.New("refused: not an enforcement command")} + } + c, cancel := context.WithTimeout(ctx, CallTimeout) + defer cancel() + r := e.R.Run(c, args) + if c.Err() != nil { + r.TimedOut = true + } + return r +} + +// Read reads one key; ok is false when RustDesk did not answer in the +// preflight's answer charset. +func (e *Enforcer) Read(ctx context.Context, key string) (string, bool) { + r := e.call(ctx, ReadArgs(key)) + if msa.ParseRead(r.Stdout, r.ExitCode, r.TimedOut, len(r.Stdout) > msa.MaxReadBytes, r.Err) != msa.KeyOK { + return "", false + } + return string(bytes.TrimSpace(r.Stdout)), true +} + +// ReadAll reads every key; an unanswered read fails the whole read. +func (e *Enforcer) ReadAll(ctx context.Context) (map[string]string, error) { + out := map[string]string{} + for _, k := range Keys { + v, ok := e.Read(ctx, k) + if !ok { + return nil, errors.New("rustdesk did not answer a read") + } + out[k] = v + } + return out, nil +} + +// Desired is what a verified grant asks of RustDesk (§3.3), for every key. +func Desired(g *grant.Grant) map[string]string { + yn := func(b bool) string { + if b { + return "Y" + } + return "N" + } + access := "view" + if g.Mode == "control" { + access = "full" + } + approve := "password" + if g.Consent == "required" { + approve = "click" + } + return map[string]string{ + "verification-method": "use-permanent-password", + "access-mode": access, + "enable-keyboard": yn(g.Mode == "control"), + "enable-clipboard": yn(g.Permissions.Clipboard), + "enable-file-transfer": yn(g.Permissions.Files), + "enable-audio": yn(g.Permissions.Audio), + "enable-tunnel": yn(g.Permissions.Tunnel), + "enable-remote-restart": yn(g.Permissions.Restart), + "approve-mode": approve, + "allow-auto-disconnect": "Y", + "auto-disconnect-timeout": strconv.Itoa(g.IdleMinutes), + } +} + +// order: the verification method first, so the moment anything changes +// only the permanent password works; the password last of all. +var order = []string{ + "verification-method", "access-mode", "enable-keyboard", "enable-clipboard", "enable-file-transfer", "enable-audio", + "enable-tunnel", "enable-remote-restart", "approve-mode", "allow-auto-disconnect", "auto-disconnect-timeout", +} + +// Outcome of Apply: OK, or a code and the keys that disagreed. +type Outcome struct { + OK bool + Code string + Keys []string +} + +// Set writes values (each through SetArgs) and reads every one back. It +// returns the keys that did not read back as set. +func (e *Enforcer) Set(ctx context.Context, values map[string]string) []string { + var bad []string + for _, k := range order { + if r := e.call(ctx, SetArgs(k, values[k])); !r.ok() { + bad = append(bad, k) + } + } + for _, k := range order { + if contains(bad, k) { + continue + } + got, ok := e.Read(ctx, k) + if !ok || !Matches(k, got, values[k]) { + bad = append(bad, k) + } + } + return bad +} + +// Check reads every key and returns those that no longer read back as +// values (drift between sessions). +func (e *Enforcer) Check(ctx context.Context, values map[string]string) []string { + var bad []string + for _, k := range order { + got, ok := e.Read(ctx, k) + if !ok || !Matches(k, got, values[k]) { + bad = append(bad, k) + } + } + return bad +} + +// SetPassword sets RustDesk's permanent password. RustDesk prints "Done!" +// only when its running service accepted it (0.68.3 lab; the installer +// relies on the same word); anything else is a failure. +func (e *Enforcer) SetPassword(ctx context.Context, pw string) bool { + r := e.call(ctx, PasswordArgs(pw)) + return r.ok() && bytes.Contains(r.Stdout, []byte("Done")) +} + +// Apply enforces a verified grant: every setting, every readback, then the +// one-time password. On any disagreement it refuses — the session is ended +// at once (a password nobody is told) and nothing weaker is substituted. +// The caller has saved the previous values first. +func (e *Enforcer) Apply(ctx context.Context, g *grant.Grant) Outcome { + if bad := e.Set(ctx, Desired(g)); len(bad) > 0 { + _ = e.EndSession(ctx) + return Outcome{Code: ReadbackMismatch, Keys: bad} + } + if !e.SetPassword(ctx, g.Password) { + _ = e.EndSession(ctx) + return Outcome{Code: PasswordNotApplied, Keys: []string{"password"}} + } + return Outcome{OK: true} +} + +// RandomPassword: 24 characters from A–Z a–z 0–9 (rejection sampling), made +// here and told to nobody. +func RandomPassword() string { + const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + out := make([]byte, 0, 24) + buf := make([]byte, 32) + for len(out) < 24 { + if _, err := rand.Read(buf); err != nil { + panic("crypto/rand failed") + } + for _, b := range buf { + if b < 248 && len(out) < 24 { + out = append(out, alphabet[int(b)%62]) + } + } + } + return string(out) +} + +func (e *Enforcer) newPassword() string { + if e.Password != nil { + return e.Password() + } + return RandomPassword() +} + +// Secure replaces the permanent password with one nobody is told. +func (e *Enforcer) Secure(ctx context.Context) bool { + return e.SetPassword(ctx, e.newPassword()) +} + +// EndSession ends every session and leaves no password anyone knows: a +// random password nobody is told, then stop-service Y, a pause, and N. +// Every step runs even when an earlier one failed; the error says which. +func (e *Enforcer) EndSession(ctx context.Context) error { + var errs []error + if !e.Secure(ctx) { + errs = append(errs, errors.New("password")) + } + if r := e.call(ctx, StopServiceArgs(true)); !r.ok() { + errs = append(errs, errors.New("stop-service Y")) + } + e.sleep(StopPause) + if r := e.call(ctx, StopServiceArgs(false)); !r.ok() { + errs = append(errs, errors.New("stop-service N")) + } + if got, ok := e.Read(ctx, "stop-service"); !ok || !Matches("stop-service", got, "N") { + errs = append(errs, errors.New("stop-service did not read back N")) + } + return errors.Join(errs...) +} + +// Restore puts every saved value back and reads it back; the keys that +// disagree are returned. +func (e *Enforcer) Restore(ctx context.Context, s *Saved) []string { + var bad []string + for _, k := range Keys { + v, ok := s.Values[k] + if !ok { + bad = append(bad, k) + continue + } + if r := e.call(ctx, RestoreArgs(k, v)); !r.ok() { + bad = append(bad, k) + continue + } + if got, ok := e.Read(ctx, k); !ok || !Matches(k, got, v) { + bad = append(bad, k) + } + } + return bad +} + +func contains(xs []string, x string) bool { + for _, y := range xs { + if y == x { + return true + } + } + return false +} diff --git a/tools/windows-installer/internal/msa/enforce/enforce_test.go b/tools/windows-installer/internal/msa/enforce/enforce_test.go new file mode 100644 index 00000000..568bff9b --- /dev/null +++ b/tools/windows-installer/internal/msa/enforce/enforce_test.go @@ -0,0 +1,620 @@ +package enforce + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "encoding/base64" + "encoding/json" + "errors" + "reflect" + "strings" + "testing" + "time" + + "github.com/agit8or1/rem0te/windows-installer/internal/msa" + "github.com/agit8or1/rem0te/windows-installer/internal/msa/grant" +) + +// fakeRustdesk is RustDesk's command line as the 0.68.3 lab saw it on +// 1.4.1–1.5.3: --option KEY prints the value (nothing for a default, which +// RustDesk removes), --option KEY VALUE sets it, --password prints Done!. +type fakeRustdesk struct { + opts map[string]string + calls [][]string + ignore map[string]bool // a set of this key does nothing (readback mismatch) + noDone bool // --password prints nothing + password string + stopSeq []string + failRead map[string]bool +} + +var defaults = map[string]string{ + "enable-keyboard": "Y", "enable-clipboard": "Y", "enable-file-transfer": "Y", "enable-audio": "Y", + "enable-tunnel": "Y", "enable-remote-restart": "Y", "allow-auto-disconnect": "N", + "verification-method": "use-both-passwords", "stop-service": "N", +} + +func newFake() *fakeRustdesk { + return &fakeRustdesk{opts: map[string]string{"access-mode": "full", "approve-mode": "password-click"}, ignore: map[string]bool{}, failRead: map[string]bool{}} +} + +func (f *fakeRustdesk) Run(_ context.Context, args []string) Result { + if !Valid(args) { + return Result{Err: errors.New("fake: invalid args")} + } + f.calls = append(f.calls, append([]string(nil), args...)) + switch { + case args[0] == "--password": + f.password = args[1] + if f.noDone { + return Result{} + } + return Result{Stdout: []byte("Done!\r\n")} + case len(args) == 2: + if f.failRead[args[1]] { + return Result{ExitCode: 1} + } + return Result{Stdout: []byte(f.opts[args[1]] + "\r\n")} + default: + k, v := args[1], args[2] + if k == "stop-service" { + f.stopSeq = append(f.stopSeq, v) + } + if f.ignore[k] { + return Result{} + } + if v == "" || defaults[k] == v { + delete(f.opts, k) + } else { + f.opts[k] = v + } + return Result{} + } +} + +func (f *fakeRustdesk) passwordCalls() int { + n := 0 + for _, c := range f.calls { + if c[0] == "--password" { + n++ + } + } + return n +} + +func newEnforcer(f *fakeRustdesk) *Enforcer { + return &Enforcer{R: f, Sleep: func(time.Duration) {}} +} + +// ── args ──────────────────────────────────────────────────────────────────── + +func TestKeysAreThePreflights(t *testing.T) { + if !reflect.DeepEqual(Keys, msa.Keys) || len(Keys) != 11 { + t.Fatalf("keys %v", Keys) + } + for _, k := range order { + if !isKey(k) { + t.Fatalf("order names %s", k) + } + } + if len(order) != len(Keys) { + t.Fatal("order must name every key") + } +} + +func TestArgsAreClosed(t *testing.T) { + refused := [][]string{ + SetArgs("custom-rendezvous-server", "evil"), SetArgs("access-mode", "custom"), SetArgs("verification-method", "use-temporary-password"), + SetArgs("allow-auto-disconnect", "N"), SetArgs("auto-disconnect-timeout", "0"), SetArgs("auto-disconnect-timeout", "121"), + SetArgs("enable-keyboard", "Y N"), RestoreArgs("access-mode", "a b"), RestoreArgs("password", "x"), + PasswordArgs("short"), PasswordArgs("ZZZZyyyyXXXXwwww0000111!"), PasswordArgs("ZZZZyyyyXXXXwwww00001111 --x"), + ReadArgs("password"), + } + for i, a := range refused { + if a != nil { + t.Fatalf("case %d built %v", i, a) + } + } + for _, a := range [][]string{ + {"--option", "access-mode", "view"}, {"--option", "auto-disconnect-timeout", "10"}, {"--password", "ZZZZyyyyXXXXwwww00001111"}, + {"--option", "stop-service", "Y"}, {"--option", "stop-service", "N"}, {"--option", "stop-service"}, {"--option", "enable-audio"}, + {"--option", "approve-mode", "password-click"}, + } { + if !Valid(a) { + t.Fatalf("%v should be valid", a) + } + } + for _, a := range [][]string{ + {"--get-id"}, {"--option", "stop-service", "X"}, {"--password", "x"}, {"--config", "x"}, {"--option", "custom-rendezvous-server", "x"}, + {"--option", "access-mode", "view", "extra"}, {"--cm"}, {"--option"}, {}, + } { + if Valid(a) { + t.Fatalf("%v should be refused", a) + } + } +} + +// ── signing ───────────────────────────────────────────────────────────────── + +type signer struct { + pub ed25519.PublicKey + priv ed25519.PrivateKey + kid string +} + +func newSigner(t *testing.T) signer { + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + return signer{pub, priv, grant.KeyID(pub)} +} + +const ( + epID = "cmtestendpoint000000000009" + rid = "555666777" + bizID = "cmtestbusiness000000000009" +) + +var t0 = time.Date(2026, 11, 20, 10, 0, 0, 0, time.UTC) + +func baseGrant(id string) grant.Grant { + return grant.Grant{V: 1, GrantID: id, EndpointID: epID, RustdeskID: rid, BusinessID: bizID, TechnicianID: "cmtesttechnician0000000009", + Mode: "view", Consent: "required", NotBefore: "2026-11-20T10:00:00Z", NotAfter: "2026-11-20T10:05:00Z", + MaxMinutes: 30, IdleMinutes: 10, Password: "ZZZZyyyyXXXXwwww00001111"} +} + +func (s signer) envelope(g grant.Grant) json.RawMessage { + body := grant.Canonical(&g) + sig := ed25519.Sign(s.priv, append([]byte(grant.Prefix), body...)) + env, _ := json.Marshal(map[string]string{"keyId": s.kid, "grant": base64.StdEncoding.EncodeToString(body), "sig": base64.StdEncoding.EncodeToString(sig)}) + return env +} + +// ── apply ─────────────────────────────────────────────────────────────────── + +func TestApplySetsReadsBackThenPassword(t *testing.T) { + f := newFake() + g := baseGrant("00112233445566778899aabbccddeeff") + out := newEnforcer(f).Apply(context.Background(), &g) + if !out.OK { + t.Fatalf("apply: %+v", out) + } + want := map[string]string{"verification-method": "use-permanent-password", "access-mode": "view", "enable-keyboard": "N", + "enable-clipboard": "N", "enable-file-transfer": "N", "enable-audio": "N", "enable-tunnel": "N", "enable-remote-restart": "N", + "approve-mode": "click", "allow-auto-disconnect": "Y", "auto-disconnect-timeout": "10"} + if !reflect.DeepEqual(f.opts, want) { + t.Fatalf("options %v", f.opts) + } + if f.password != g.Password { + t.Fatal("one-time password not set") + } + last := f.calls[len(f.calls)-1] + if last[0] != "--password" { + t.Fatalf("the password must be the last call, got %v", last) + } + if first := f.calls[0]; first[1] != "verification-method" { + t.Fatalf("the verification method must be first, got %v", first) + } +} + +func TestReadbackMismatchFailsClosed(t *testing.T) { + f := newFake() + f.ignore["access-mode"] = true // RustDesk keeps full access + g := baseGrant("00112233445566778899aabbccddeeff") + out := newEnforcer(f).Apply(context.Background(), &g) + if out.OK || out.Code != ReadbackMismatch || !reflect.DeepEqual(out.Keys, []string{"access-mode"}) { + t.Fatalf("outcome %+v", out) + } + if f.password == g.Password { + t.Fatal("the grant's password must never be set after a mismatch") + } + if f.password == "" || !reflect.DeepEqual(f.stopSeq, []string{"Y", "N"}) { + t.Fatalf("the session must be ended (random password, stop Y then N): pw=%v stop=%v", f.password != "", f.stopSeq) + } +} + +func TestPasswordWithoutDoneFails(t *testing.T) { + f := newFake() + f.noDone = true + g := baseGrant("00112233445566778899aabbccddeeff") + out := newEnforcer(f).Apply(context.Background(), &g) + if out.OK || out.Code != PasswordNotApplied || !reflect.DeepEqual(out.Keys, []string{"password"}) { + t.Fatalf("outcome %+v", out) + } +} + +func TestEmptyReadbackMeansDefault(t *testing.T) { + if !Matches("enable-keyboard", "", "Y") || Matches("enable-keyboard", "", "N") || Matches("access-mode", "", "view") || + !Matches("allow-auto-disconnect", "", "N") || Matches("allow-auto-disconnect", "", "Y") { + t.Fatal("empty readback table") + } +} + +func TestRandomPassword(t *testing.T) { + a, b := RandomPassword(), RandomPassword() + if PasswordArgs(a) == nil || a == b { + t.Fatalf("random passwords %q %q", a, b) + } +} + +// ── the poller ────────────────────────────────────────────────────────────── + +type fakePortal struct { + answers []PollAnswer + reports []Report + acks [][]string + stopAt int +} + +func (p *fakePortal) Poll(_ context.Context, ack []string, _ bool) (PollAnswer, error) { + p.acks = append(p.acks, ack) + if len(p.answers) == 0 { + return PollAnswer{}, ErrStop + } + a := p.answers[0] + p.answers = p.answers[1:] + return a, nil +} + +func (p *fakePortal) Report(_ context.Context, r Report) error { + for _, k := range r.Keys { + if k == "password" { + continue + } + } + p.reports = append(p.reports, r) + return nil +} + +func (p *fakePortal) events() []string { + var out []string + for _, r := range p.reports { + s := r.Event + if r.Outcome != "" { + s += ":" + r.Outcome + } + out = append(out, s) + } + return out +} + +type fakeHost struct { + keys map[string]ed25519.PublicKey + paused bool + sessions []int // successive answers; the last repeats + trustErr error +} + +func (h *fakeHost) RustdeskID(context.Context) (string, error) { return rid, nil } +func (h *fakeHost) Sessions() (int, error) { + if len(h.sessions) == 0 { + return 0, nil + } + n := h.sessions[0] + if len(h.sessions) > 1 { + h.sessions = h.sessions[1:] + } + return n, nil +} +func (h *fakeHost) Trust(context.Context) (map[string]ed25519.PublicKey, func(string, string) bool, error) { + if h.trustErr != nil { + return nil, nil, h.trustErr + } + return h.keys, func(string, string) bool { return h.paused }, nil +} + +type memStore struct { + state *State + saved *Saved + seen map[string]time.Time + saves int +} + +func (m *memStore) LoadState() (*State, error) { return m.state, nil } +func (m *memStore) SaveState(s *State) error { c := *s; m.state = &c; return nil } +func (m *memStore) LoadSaved() (*Saved, error) { return m.saved, nil } +func (m *memStore) SaveSaved(s *Saved) error { m.saved = s; m.saves++; return nil } +func (m *memStore) DeleteSaved() error { m.saved = nil; return nil } +func (m *memStore) LoadSeen() (map[string]time.Time, error) { return m.seen, nil } +func (m *memStore) SaveSeen(s map[string]time.Time) error { + m.seen = map[string]time.Time{} + for k, v := range s { + m.seen[k] = v + } + return nil +} + +type rig struct { + f *fakeRustdesk + portal *fakePortal + host *fakeHost + store *memStore + clock time.Time + p *Poller +} + +func newRig(t *testing.T, s signer) *rig { + r := &rig{f: newFake(), portal: &fakePortal{}, host: &fakeHost{keys: map[string]ed25519.PublicKey{s.kid: s.pub}}, store: &memStore{}, clock: t0.Add(time.Minute)} + r.p = &Poller{E: newEnforcer(r.f), P: r.portal, H: r.host, S: r.store, + Now: func() time.Time { return r.clock }, Wait: func(_ context.Context, d time.Duration) { r.clock = r.clock.Add(d) }} + return r +} + +func managed(state string, grants ...json.RawMessage) PollAnswer { + return PollAnswer{EndpointID: epID, Managed: &ManagedAnswer{State: state, Rollback: state == "rollback_pending"}, Grants: grants} +} + +func (r *rig) run(t *testing.T) { + t.Helper() + if err := r.p.Run(context.Background()); err != nil { + t.Fatalf("run: %v", err) + } +} + +func TestLegacyDoesNothing(t *testing.T) { + s := newSigner(t) + r := newRig(t, s) + r.portal.answers = []PollAnswer{{EndpointID: epID}} // managed: null + r.run(t) + if len(r.f.calls) != 0 || len(r.portal.reports) != 0 || r.store.saved != nil { + t.Fatalf("a Legacy computer must see no RustDesk call: %v %v", r.f.calls, r.portal.reports) + } + r = newRig(t, s) + r.run(t) // ErrStop at once (MSA off) + if len(r.f.calls) != 0 { + t.Fatal("MSA off: no RustDesk call") + } +} + +func TestTestSessionPendingFullCycle(t *testing.T) { + s := newSigner(t) + r := newRig(t, s) + before := map[string]string{} + for k, v := range r.f.opts { + before[k] = v + } + g := baseGrant("00112233445566778899aabbccddeeff") + r.host.sessions = []int{1, 1, 0} + r.portal.answers = []PollAnswer{managed("pending", s.envelope(g)), managed("pending"), managed("pending"), managed("pending"), {EndpointID: epID}} + r.run(t) + if got := r.portal.events(); !reflect.DeepEqual(got, []string{"applied", "connected", "ended:disconnected"}) { + t.Fatalf("events %v", got) + } + if r.store.saved == nil || r.store.saves != 1 || r.store.saved.Values["access-mode"] != "full" { + t.Fatalf("saved %+v", r.store.saved) + } + // Pending: the saved settings went back after the session. + if !reflect.DeepEqual(r.f.opts, before) { + t.Fatalf("pending computer not restored between test sessions: %v", r.f.opts) + } + if r.f.password == g.Password { + t.Fatal("after the session the one-time password must be gone") + } + if r.store.state.EndpointID != epID { + t.Fatal("endpoint id not pinned") + } + if !r.store.seen[g.GrantID].After(t0) { + t.Fatal("grant not in the replay set") + } + if len(r.portal.acks) < 2 || !reflect.DeepEqual(r.portal.acks[1], []string{g.GrantID}) { + t.Fatalf("acks %v", r.portal.acks) + } + for _, rep := range r.portal.reports { + b, _ := json.Marshal(rep) + if strings.Contains(string(b), g.Password) { + t.Fatal("a report carried the password") + } + } +} + +func TestReplayRefused(t *testing.T) { + s := newSigner(t) + r := newRig(t, s) + g := baseGrant("00112233445566778899aabbccddeeff") + r.store.seen = map[string]time.Time{g.GrantID: t0.Add(time.Hour)} + r.portal.answers = []PollAnswer{managed("pending", s.envelope(g)), {EndpointID: epID}} + r.run(t) + if got := r.portal.events(); !reflect.DeepEqual(got, []string{"failed:replayed"}) { + t.Fatalf("events %v", got) + } + if len(r.f.calls) != 0 { + t.Fatal("a replayed grant must change nothing") + } +} + +func TestBadKeyAndNoKeysRefused(t *testing.T) { + s, other := newSigner(t), newSigner(t) + r := newRig(t, s) + g := baseGrant("00112233445566778899aabbccddeeff") + r.portal.answers = []PollAnswer{managed("pending", other.envelope(g)), {EndpointID: epID}} + r.run(t) + if got := r.portal.events(); !reflect.DeepEqual(got, []string{"failed:unknown_key"}) || len(r.f.calls) != 0 { + t.Fatalf("events %v calls %v", got, r.f.calls) + } + r = newRig(t, s) + r.host.trustErr = errors.New("target not listed") + r.portal.answers = []PollAnswer{managed("pending", s.envelope(g)), {EndpointID: epID}} + r.run(t) + if got := r.portal.events(); !reflect.DeepEqual(got, []string{"failed:no_keys"}) || len(r.f.calls) != 0 { + t.Fatalf("events %v", got) + } +} + +func TestCeilingAndPauseRefused(t *testing.T) { + s := newSigner(t) + r := newRig(t, s) + g := baseGrant("00112233445566778899aabbccddeeff") + g.Mode = "control" + g2 := baseGrant("00112233445566778899aabbccddee00") + g2.Permissions.Files = true + r.portal.answers = []PollAnswer{managed("pending", s.envelope(g), s.envelope(g2)), {EndpointID: epID}} + r.run(t) + if got := r.portal.events(); !reflect.DeepEqual(got, []string{"failed:mode_not_allowed", "failed:permission_not_allowed"}) || len(r.f.calls) != 0 { + t.Fatalf("events %v", got) + } + r = newRig(t, s) + r.host.paused = true + r.portal.answers = []PollAnswer{managed("pending", s.envelope(baseGrant("00112233445566778899aabbccddeeff"))), {EndpointID: epID}} + r.run(t) + if got := r.portal.events(); !reflect.DeepEqual(got, []string{"failed:remote_paused"}) || len(r.f.calls) != 0 { + t.Fatalf("events %v", got) + } +} + +func TestWrongEndpointPinRefused(t *testing.T) { + s := newSigner(t) + r := newRig(t, s) + r.store.state = &State{Schema: StateSchema, EndpointID: "cmotherendpoint00000000009"} + r.portal.answers = []PollAnswer{managed("pending", s.envelope(baseGrant("00112233445566778899aabbccddeeff")))} + if err := r.p.Run(context.Background()); err == nil { + t.Fatal("a changed endpoint id must stop the poller") + } + if len(r.f.calls) != 0 { + t.Fatal("nothing applied under another endpoint id") + } +} + +func TestReadbackMismatchReported(t *testing.T) { + s := newSigner(t) + r := newRig(t, s) + r.f.ignore["enable-clipboard"] = true + r.f.opts["enable-clipboard"] = "Y" + r.portal.answers = []PollAnswer{managed("pending", s.envelope(baseGrant("00112233445566778899aabbccddeeff"))), {EndpointID: epID}} + r.run(t) + if len(r.portal.reports) != 1 || r.portal.reports[0].Outcome != ReadbackMismatch || !reflect.DeepEqual(r.portal.reports[0].Keys, []string{"enable-clipboard"}) { + t.Fatalf("reports %+v", r.portal.reports) + } +} + +func TestSaveFailsClosed(t *testing.T) { + s := newSigner(t) + r := newRig(t, s) + r.f.failRead["approve-mode"] = true + r.portal.answers = []PollAnswer{managed("pending", s.envelope(baseGrant("00112233445566778899aabbccddeeff"))), {EndpointID: epID}} + r.run(t) + if got := r.portal.events(); !reflect.DeepEqual(got, []string{"failed:save_failed"}) { + t.Fatalf("events %v", got) + } + for _, c := range r.f.calls { + if len(c) == 3 || c[0] == "--password" { + t.Fatalf("nothing may be set when the save failed: %v", c) + } + } +} + +func TestNoConnectionAndMaxMinutes(t *testing.T) { + s := newSigner(t) + r := newRig(t, s) + r.portal.answers = []PollAnswer{managed("verified", s.envelope(baseGrant("00112233445566778899aabbccddeeff")))} + for i := 0; i < 200; i++ { + r.portal.answers = append(r.portal.answers, managed("verified")) + } + r.portal.answers = append(r.portal.answers, PollAnswer{EndpointID: epID}) + r.run(t) + ev := r.portal.events() + if len(ev) < 3 || ev[0] != "secured" || ev[1] != "applied" || ev[2] != "ended:no_connection" { + t.Fatalf("events %v", ev) + } + r = newRig(t, s) + r.host.sessions = []int{1} + r.portal.answers = []PollAnswer{managed("verified", s.envelope(baseGrant("00112233445566778899aabbccddeeff")))} + for i := 0; i < 400; i++ { + r.portal.answers = append(r.portal.answers, managed("verified")) + } + r.portal.answers = append(r.portal.answers, PollAnswer{EndpointID: epID}) + r.run(t) + ev = r.portal.events() + if len(ev) < 4 || ev[2] != "connected" || ev[3] != "ended:max_minutes" { + t.Fatalf("events %v", ev) + } + // Verified: the managed settings stay after the session (no restore), with a password nobody is told. + if r.f.opts["access-mode"] != "view" || r.f.password == baseGrant("").Password { + t.Fatalf("verified computer after session: %v", r.f.opts) + } +} + +func TestRollbackRestores(t *testing.T) { + s := newSigner(t) + r := newRig(t, s) + before := map[string]string{} + for k, v := range r.f.opts { + before[k] = v + } + r.host.sessions = []int{1} + r.portal.answers = []PollAnswer{managed("verified", s.envelope(baseGrant("00112233445566778899aabbccddeeff"))), managed("rollback_pending"), {EndpointID: epID}} + r.run(t) + if got := r.portal.events(); !reflect.DeepEqual(got, []string{"secured", "applied", "connected", "ended:rollback", "restored"}) { + t.Fatalf("events %v", got) + } + if !reflect.DeepEqual(r.f.opts, before) || r.store.saved != nil { + t.Fatalf("not restored: %v saved=%v", r.f.opts, r.store.saved) + } +} + +func TestRollbackRestoreFailed(t *testing.T) { + s := newSigner(t) + r := newRig(t, s) + r.store.saved = &Saved{Schema: SavedSchema, Values: map[string]string{}} + for _, k := range Keys { + r.store.saved.Values[k] = "" + } + r.store.saved.Values["access-mode"] = "full" + r.f.ignore["access-mode"] = true + r.f.opts["access-mode"] = "view" + r.portal.answers = []PollAnswer{managed("rollback_pending"), {EndpointID: epID}} + r.run(t) + if len(r.portal.reports) != 1 || r.portal.reports[0].Event != "restore_failed" || !reflect.DeepEqual(r.portal.reports[0].Keys, []string{"access-mode"}) { + t.Fatalf("reports %+v", r.portal.reports) + } + if r.store.saved == nil { + t.Fatal("the saved settings must be kept after a failed restore") + } +} + +func TestRestCheckDrift(t *testing.T) { + s := newSigner(t) + r := newRig(t, s) + r.store.state = &State{Schema: StateSchema, EndpointID: epID, Secured: true, Applied: Desired(func() *grant.Grant { g := baseGrant(""); return &g }())} + if bad := newEnforcer(r.f).Set(context.Background(), r.store.state.Applied); len(bad) != 0 { + t.Fatal(bad) + } + r.f.calls = nil + r.portal.answers = []PollAnswer{managed("verified"), {EndpointID: epID}} + r.run(t) + if got := r.portal.events(); !reflect.DeepEqual(got, []string{"checked"}) { + t.Fatalf("events %v", got) + } + r.f.opts["access-mode"] = "full" + r.p.lastRB = time.Time{} + r.portal.answers = []PollAnswer{managed("verified"), {EndpointID: epID}} + r.portal.reports = nil + r.run(t) + if len(r.portal.reports) != 1 || r.portal.reports[0].Event != "drift" || !reflect.DeepEqual(r.portal.reports[0].Keys, []string{"access-mode"}) { + t.Fatalf("reports %+v", r.portal.reports) + } + if r.f.opts["access-mode"] != "view" { + t.Fatal("drift must be corrected") + } +} + +func TestGrantKeysFile(t *testing.T) { + s := newSigner(t) + doc := `{"schema":"rem0te-msa-grant-keys/1","keys":[{"keyId":"` + s.kid + `","publicKey":"` + base64.StdEncoding.EncodeToString(s.pub) + `"}]}` + keys, err := grant.ParseKeys([]byte(doc)) + if err != nil || len(keys) != 1 || !keys[s.kid].Equal(s.pub) { + t.Fatalf("parse: %v", err) + } + for _, bad := range []string{ + strings.Replace(doc, s.kid, "0000000000000000", 1), + strings.Replace(doc, "grant-keys/1", "grant-keys/2", 1), + strings.Replace(doc, `"keys"`, `"extra":1,"keys"`, 1), + doc + "x", + `{"schema":"rem0te-msa-grant-keys/1"}`, + } { + if _, err := grant.ParseKeys([]byte(bad)); err == nil { + t.Fatalf("accepted %s", bad) + } + } +} diff --git a/tools/windows-installer/internal/msa/enforce/poller.go b/tools/windows-installer/internal/msa/enforce/poller.go new file mode 100644 index 00000000..921c847a --- /dev/null +++ b/tools/windows-installer/internal/msa/enforce/poller.go @@ -0,0 +1,482 @@ +package enforce + +// The grant poller (0.72): `rem0te-agent.exe msa-poller`, started by the +// signed heartbeat only when the portal answers msaPoll: true (MSA_GRANTS on +// AND a Platform Admin moved this one computer into Managed Secure Access). +// Portable: the portal, the computer and the files are interfaces, so every +// decision runs under test with fakes. The Windows wiring is +// msa_poller_windows.go. +// +// What it does, in order, on each answer: +// +// - nothing at all unless the answer names a managed state (Legacy: it +// ends any session it holds and exits); +// - rollback: end any session, restore the saved settings, read them back, +// report restored (or restore_failed with the keys); +// - verified and not yet secured: replace the permanent password with one +// nobody is told, report secured; +// - each grant: verify it (internal/msa/grant) under the keys from the +// verified update chain only, this computer's own identity, the compiled +// Ceiling and the persisted replay set; refuse remote_paused under the +// signed pause; save the previous settings before the FIRST change; +// apply, read back, set the one-time password; report applied or why not; +// - between answers: watch for the RustDesk connection manager and end the +// session when it disconnects, when maxMinutes runs out, or when no one +// connected by notAfter; at rest, read the managed settings back hourly. +// +// Fail closed: no keys, an unreadable pause, a grant that does not verify, a +// readback that disagrees — each refuses and is reported; nothing weaker is +// ever applied in its place. + +import ( + "bytes" + "context" + "crypto/ed25519" + "encoding/base64" + "encoding/json" + "errors" + "regexp" + "time" + + "github.com/agit8or1/rem0te/windows-installer/internal/msa/grant" +) + +// ErrStop: the portal said this computer has no business polling (MSA +// switched off, not managed, not the signed agent). The poller exits. +var ErrStop = errors.New("msa: the portal does not want this computer to poll") + +// ManagedAnswer is the portal's managed state for this computer. +type ManagedAnswer struct { + State string `json:"state"` + Rollback bool `json:"rollback"` +} + +// PollAnswer is one poll's answer, as the agent reads it. +type PollAnswer struct { + Grants []json.RawMessage `json:"grants"` + Paused bool `json:"paused"` + EndpointID string `json:"endpointId"` + Managed *ManagedAnswer `json:"managed"` + RetryAfterMs int `json:"retryAfterMs"` +} + +// Report is one report to the portal. Never a password. +type Report struct { + Event string `json:"event"` + GrantID string `json:"grantId,omitempty"` + Outcome string `json:"outcome,omitempty"` + Keys []string `json:"keys,omitempty"` +} + +// Portal is the agent's side of POST /msa/agent/poll and /msa/agent/report +// (the device secret and RustDesk ID are the implementation's). +type Portal interface { + Poll(ctx context.Context, ack []string, wait bool) (PollAnswer, error) + Report(ctx context.Context, r Report) error +} + +// Host is the computer: its RustDesk ID, its open RustDesk sessions, the +// grant keys and signed pause from the verified update chain. +type Host interface { + RustdeskID(ctx context.Context) (string, error) + // Sessions counts `rustdesk.exe --cm`; an error is "cannot tell". + Sessions() (int, error) + // Trust returns the grant keys and whether the signed pause covers this + // business and RustDesk ID (an unreadable listed pause covers everything). + Trust(ctx context.Context) (keys map[string]ed25519.PublicKey, paused func(businessID, rustdeskID string) bool, err error) +} + +// State is the poller's own file (msa\enforce.json): the endpoint id it +// pinned, what it last applied (never a password), and whether the legacy +// password was replaced. +type State struct { + Schema string `json:"schema"` + EndpointID string `json:"endpointId,omitempty"` + Applied map[string]string `json:"applied,omitempty"` + Secured bool `json:"secured,omitempty"` +} + +// StateSchema names the state file. +const StateSchema = "rem0te-msa-enforce/1" + +// Store keeps the poller's files, SYSTEM-only. +type Store interface { + LoadState() (*State, error) + SaveState(*State) error + LoadSaved() (*Saved, error) // nil, nil when there is none + SaveSaved(*Saved) error + DeleteSaved() error + LoadSeen() (map[string]time.Time, error) + SaveSeen(map[string]time.Time) error +} + +// Poller bounds. +const ( + // Tick is how often an active session is checked. + Tick = 5 * time.Second + // RestCheck is how often a verified computer's settings are read back. + RestCheck = time.Hour + // IdleExit: with no session for this long the poller exits; the next + // heartbeat starts it again while the portal still wants it. + IdleExit = time.Hour + // MaxBackoff bounds the wait after a failed poll. + MaxBackoff = time.Minute +) + +type active struct { + g *grant.Grant + appliedAt time.Time + connected bool +} + +// Poller is one run. +type Poller struct { + E *Enforcer + P Portal + H Host + S Store + Now func() time.Time + Wait func(context.Context, time.Duration) + Logf func(string, ...any) + state *State + seen map[string]time.Time + act *active + mstate string + ack []string + lastRB time.Time + rolled bool +} + +func (p *Poller) now() time.Time { + if p.Now != nil { + return p.Now() + } + return time.Now() +} + +func (p *Poller) logf(f string, a ...any) { + if p.Logf != nil { + p.Logf(f, a...) + } +} + +func (p *Poller) wait(ctx context.Context, d time.Duration) { + if p.Wait != nil { + p.Wait(ctx, d) + return + } + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + case <-t.C: + } +} + +func (p *Poller) report(ctx context.Context, r Report) { + if err := p.P.Report(ctx, r); err != nil { + p.logf("msa-poller: report %s: %v", r.Event, err) + } +} + +// Run polls until the portal stops wanting it, the context ends, or IdleExit. +func (p *Poller) Run(ctx context.Context) error { + st, err := p.S.LoadState() + if err != nil || st == nil || st.Schema != StateSchema { + st = &State{Schema: StateSchema} + } + p.state = st + if p.seen, err = p.S.LoadSeen(); err != nil || p.seen == nil { + p.seen = map[string]time.Time{} + } + backoff := 5 * time.Second + lastActive := p.now() + for ctx.Err() == nil { + ans, err := p.P.Poll(ctx, p.ack, p.act == nil) + if errors.Is(err, ErrStop) { + p.endActive(ctx, NotEnabled) + return nil + } + if err != nil { + p.logf("msa-poller: poll: %v", err) + p.tick(ctx) + p.wait(ctx, backoff) + if backoff *= 2; backoff > MaxBackoff { + backoff = MaxBackoff + } + continue + } + backoff = 5 * time.Second + p.ack = nil + if !p.pin(ans.EndpointID) { + p.logf("msa-poller: the portal named another computer; stopping") + p.endActive(ctx, NotEnabled) + return errors.New("endpoint id changed") + } + if ans.Managed == nil { + p.endActive(ctx, NotEnabled) + return nil + } + p.mstate = ans.Managed.State + if ans.Managed.Rollback { + if !p.rolled { + p.rollback(ctx) + } + p.wait(ctx, Tick) + continue + } + p.rolled = false + if ans.Managed.State == "verified" && !p.state.Secured && p.act == nil { + if p.E.Secure(ctx) { + p.state.Secured = true + p.saveState() + p.report(ctx, Report{Event: "secured"}) + } + } + for _, env := range ans.Grants { + p.handle(ctx, env) + } + p.tick(ctx) + if p.act != nil { + lastActive = p.now() + p.wait(ctx, Tick) + continue + } + p.restCheck(ctx) + if p.now().Sub(lastActive) > IdleExit { + return nil + } + if ans.RetryAfterMs > 0 { + p.wait(ctx, time.Duration(ans.RetryAfterMs)*time.Millisecond) + } + } + p.endActive(context.Background(), NotEnabled) + return ctx.Err() +} + +// pin: the endpoint id the portal names is written once; a different one later is refused. +func (p *Poller) pin(id string) bool { + if id == "" { + return p.state.EndpointID != "" + } + if p.state.EndpointID == "" { + p.state.EndpointID = id + p.saveState() + return true + } + return p.state.EndpointID == id +} + +func (p *Poller) saveState() { + if err := p.S.SaveState(p.state); err != nil { + p.logf("msa-poller: state: %v", err) + } +} + +var grantIDRE = regexp.MustCompile(`^[0-9a-f]{32}$`) + +// grantIDOf reads the grant id out of an envelope without trusting it: only +// to name the grant in a refusal report (the portal checks it is this +// computer's own grant). +func grantIDOf(env []byte) string { + var e struct { + Grant string `json:"grant"` + } + if json.Unmarshal(env, &e) != nil { + return "" + } + b, err := base64.StdEncoding.DecodeString(e.Grant) + if err != nil || len(b) > grant.MaxGrantBytes { + return "" + } + var g struct { + GrantID string `json:"grantId"` + } + if json.Unmarshal(b, &g) != nil || !grantIDRE.MatchString(g.GrantID) { + return "" + } + return g.GrantID +} + +func (p *Poller) handle(ctx context.Context, env json.RawMessage) { + gid := grantIDOf(env) + if gid != "" { + p.ack = append(p.ack, gid) + } + refuse := func(code string, keys []string) { + p.logf("msa-poller: grant %s refused: %s", gid, code) + if gid != "" { + p.report(ctx, Report{Event: "failed", GrantID: gid, Outcome: code, Keys: keys}) + } + } + keys, paused, err := p.H.Trust(ctx) + if err != nil || len(keys) == 0 { + refuse(NoKeys, nil) + return + } + rid, err := p.H.RustdeskID(ctx) + if err != nil { + refuse(RustdeskNotReady, nil) + return + } + seen := map[string]bool{} + for id := range p.seen { + seen[id] = true + } + res := grant.Verify(bytes.TrimSpace(env), grant.Context{ + Keys: keys, EndpointID: p.state.EndpointID, RustdeskID: rid, Now: p.now(), Seen: seen, Ceiling: Ceiling, + }) + if !res.OK { + refuse(res.Reason, nil) + return + } + g := res.Grant + gid = g.GrantID + if paused == nil || paused(g.BusinessID, rid) { + refuse(grant.RemotePaused, nil) + return + } + // The replay set is written before anything changes: a crash after this + // can never let the same grant apply twice. + na, _ := time.Parse(time.RFC3339, g.NotAfter) + p.seen[g.GrantID] = na.Add(time.Duration(g.MaxMinutes)*time.Minute + grant.ClockSkew) + p.pruneSeen() + if err := p.S.SaveSeen(p.seen); err != nil { + refuse(SaveFailed, nil) + return + } + if p.act != nil { + p.endSession(ctx, Superseded) + } + // Save what RustDesk had before the FIRST change; never overwrite it. + if s, err := p.S.LoadSaved(); err != nil || s == nil { + vals, err := p.E.ReadAll(ctx) + if err != nil { + refuse(SaveFailed, nil) + return + } + if err := p.S.SaveSaved(&Saved{Schema: SavedSchema, SavedAt: p.now().UTC().Format(time.RFC3339), Values: vals}); err != nil { + refuse(SaveFailed, nil) + return + } + } + out := p.E.Apply(ctx, g) + if !out.OK { + refuse(out.Code, out.Keys) + return + } + p.state.Applied = Desired(g) + p.saveState() + p.act = &active{g: g, appliedAt: p.now()} + p.report(ctx, Report{Event: "applied", GrantID: g.GrantID}) +} + +func (p *Poller) pruneSeen() { + t := p.now() + for id, until := range p.seen { + if t.After(until) { + delete(p.seen, id) + } + } +} + +// tick watches an active session. +func (p *Poller) tick(ctx context.Context) { + a := p.act + if a == nil { + return + } + t := p.now() + if t.Sub(a.appliedAt) >= time.Duration(a.g.MaxMinutes)*time.Minute { + p.endSession(ctx, MaxMinutes) + return + } + n, err := p.H.Sessions() + if err != nil { + return // cannot tell: the time limits still end it + } + switch { + case n > 0 && !a.connected: + a.connected = true + p.report(ctx, Report{Event: "connected", GrantID: a.g.GrantID}) + case n == 0 && a.connected: + p.endSession(ctx, Disconnected) + case n == 0 && !a.connected: + if na, err := time.Parse(time.RFC3339, a.g.NotAfter); err != nil || t.After(na.Add(grant.ClockSkew)) { + p.endSession(ctx, NoConnection) + } + } +} + +func (p *Poller) endActive(ctx context.Context, code string) { + if p.act != nil { + p.endSession(ctx, code) + } +} + +// endSession: a password nobody is told, stop-service Y then N. On a +// computer still Managed (pending) the saved settings go back too, so +// Legacy works between test sessions as it did before; the portal then +// re-establishes a permanent password it knows through its rotation. +func (p *Poller) endSession(ctx context.Context, code string) { + a := p.act + p.act = nil + err := p.E.EndSession(ctx) + if err != nil { + p.logf("msa-poller: ending the session: %v", err) + code = StopFailed + } + if p.mstate == "pending" && code != Rollback { + if s, lerr := p.S.LoadSaved(); lerr == nil && s != nil { + if bad := p.E.Restore(ctx, s); len(bad) > 0 { + p.logf("msa-poller: restoring between test sessions: %v", bad) + } else { + p.state.Applied = nil + p.saveState() + } + } + } + if a != nil { + p.report(ctx, Report{Event: "ended", GrantID: a.g.GrantID, Outcome: code}) + } +} + +// rollback: end any session, then put back what RustDesk had before the first apply. +func (p *Poller) rollback(ctx context.Context) { + p.rolled = true + p.endActive(ctx, Rollback) + s, err := p.S.LoadSaved() + if err != nil { + p.report(ctx, Report{Event: "restore_failed", Keys: append([]string(nil), Keys...)}) + return + } + if s != nil { + if bad := p.E.Restore(ctx, s); len(bad) > 0 { + p.report(ctx, Report{Event: "restore_failed", Keys: bad}) + return + } + if err := p.S.DeleteSaved(); err != nil { + p.logf("msa-poller: removing the saved settings: %v", err) + } + } + p.state.Applied = nil + p.state.Secured = false + p.saveState() + p.report(ctx, Report{Event: "restored"}) +} + +// restCheck: on a verified computer with no session, read the managed +// settings back hourly. A change is drift: reported (the portal marks an +// enforcement failure) and the managed values set again. +func (p *Poller) restCheck(ctx context.Context) { + if p.mstate != "verified" || p.state.Applied == nil || p.now().Sub(p.lastRB) < RestCheck { + return + } + p.lastRB = p.now() + if bad := p.E.Check(ctx, p.state.Applied); len(bad) > 0 { + p.report(ctx, Report{Event: "drift", Keys: bad}) + _ = p.E.Set(ctx, p.state.Applied) + return + } + p.report(ctx, Report{Event: "checked"}) +} diff --git a/tools/windows-installer/internal/msa/grant/keys.go b/tools/windows-installer/internal/msa/grant/keys.go new file mode 100644 index 00000000..3fa0804b --- /dev/null +++ b/tools/windows-installer/internal/msa/grant/keys.go @@ -0,0 +1,81 @@ +package grant + +// The grant public keys, as the signed release metadata carries them (0.72): +// msa/grant-keys.json, a TUF target the release owner adds with +// `rem0te-signed-grant-key add` and `rem0te-signed-publish`. The agent reads +// it only through the verified update chain (internal/agent MsaTrust), so a +// substituted key needs a signed release. Pure: bytes in, keys out. + +import ( + "bytes" + "crypto/ed25519" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "io" +) + +// KeysTarget is the signed target name; KeysSchema its schema. The portal's +// grant-key-commands.ts and deploy/release use the same strings. +const ( + KeysTarget = "msa/grant-keys.json" + KeysSchema = "rem0te-msa-grant-keys/1" + // MaxKeys bounds the list; a portal has one active key, and a rotation two. + MaxKeys = 8 + // MaxKeysBytes bounds the file before it is parsed. + MaxKeysBytes = 16 << 10 +) + +// KeyID is the first 16 hex characters of the SHA-256 of the raw public key. +func KeyID(pub ed25519.PublicKey) string { + sum := sha256.Sum256(pub) + return hex.EncodeToString(sum[:])[:16] +} + +// ParseKeys is strict: an unknown field, a bad schema, a key id that is not +// the key's own, a duplicate, or more than MaxKeys refuses the whole file — +// the agent then trusts no grant key (every grant is unknown_key). +func ParseKeys(raw []byte) (map[string]ed25519.PublicKey, error) { + if len(raw) > MaxKeysBytes { + return nil, errors.New("grant keys: too large") + } + var doc struct { + Schema string `json:"schema"` + Keys []struct { + KeyID string `json:"keyId"` + PublicKey string `json:"publicKey"` + } `json:"keys"` + } + d := json.NewDecoder(bytes.NewReader(raw)) + d.DisallowUnknownFields() + if err := d.Decode(&doc); err != nil { + return nil, err + } + if _, err := d.Token(); err != io.EOF { + return nil, errors.New("grant keys: trailing data") + } + if doc.Schema != KeysSchema { + return nil, errors.New("grant keys: schema must be " + KeysSchema) + } + if doc.Keys == nil || len(doc.Keys) > MaxKeys { + return nil, errors.New("grant keys: missing or too many keys") + } + out := map[string]ed25519.PublicKey{} + for _, k := range doc.Keys { + b, err := base64.StdEncoding.Strict().DecodeString(k.PublicKey) + if err != nil || len(b) != ed25519.PublicKeySize || base64.StdEncoding.EncodeToString(b) != k.PublicKey { + return nil, errors.New("grant keys: a public key is not 32 bytes of standard base64") + } + pub := ed25519.PublicKey(b) + if !keyIDRE.MatchString(k.KeyID) || KeyID(pub) != k.KeyID { + return nil, errors.New("grant keys: a key id is not its key's") + } + if _, dup := out[k.KeyID]; dup { + return nil, errors.New("grant keys: duplicate key id") + } + out[k.KeyID] = pub + } + return out, nil +} diff --git a/tools/windows-installer/lab_enforce_windows_test.go b/tools/windows-installer/lab_enforce_windows_test.go new file mode 100644 index 00000000..32999583 --- /dev/null +++ b/tools/windows-installer/lab_enforce_windows_test.go @@ -0,0 +1,173 @@ +//go:build windows && labwindows + +package main + +// The Windows lab (0.72.0): Managed Secure Access enforcement against the +// RustDesk release the lab's RustDesk job installed, through the agent's own +// enforcement exec site (enforceRunner) and enforce.Enforcer — the code the +// msa-poller runs. One cycle, in order: +// +// save every setting → apply a view-only grant (every setting set and read +// back, then the one-time password, which must print "Done") → read back +// again → end the session (a random password nobody is told, stop-service +// Y, a pause, N, read back N) → restore the saved settings and read them +// back. +// +// Twice: as the runner's elevated administrator (this process), and as +// SYSTEM in session 0 — this same test binary started by a scheduled task +// with -lab-enforce-out, writing its result to a file this process reads. +// What it does not cover: the portal, the long-poll, grant verification +// (internal/msa/enforce's unit tests) and a real remote connection. + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "os" + "os/exec" + "path/filepath" + "testing" + "time" + + "github.com/agit8or1/rem0te/windows-installer/internal/labevidence" + "github.com/agit8or1/rem0te/windows-installer/internal/msa/enforce" + "github.com/agit8or1/rem0te/windows-installer/internal/msa/grant" +) + +var labEnforceOut = flag.String("lab-enforce-out", "", "lab only: run the enforcement cycle and write the result here") + +type enforceCycle struct { + OK bool `json:"ok"` + Steps []string `json:"steps"` + Err string `json:"err,omitempty"` +} + +func runEnforceCycle(ctx context.Context) enforceCycle { + var c enforceCycle + step := func(f string, a ...any) { c.Steps = append(c.Steps, fmt.Sprintf(f, a...)) } + fail := func(f string, a ...any) enforceCycle { c.Err = fmt.Sprintf(f, a...); return c } + e := &enforce.Enforcer{R: enforceRunner{exe: installedRustdeskExe()}} + + saved, err := e.ReadAll(ctx) + if err != nil { + return fail("save: %v", err) + } + step("saved %d settings", len(saved)) + + g := grant.Grant{V: 1, GrantID: "00112233445566778899aabbccddeeff", Mode: "view", Consent: "required", + MaxMinutes: 30, IdleMinutes: 10, Password: enforce.RandomPassword()} + if out := e.Apply(ctx, &g); !out.OK { + _ = e.Restore(ctx, &enforce.Saved{Schema: enforce.SavedSchema, Values: saved}) + return fail("apply: %s %v", out.Code, out.Keys) + } + step("applied a view-only grant: %d settings read back, one-time password set (Done)", len(enforce.Keys)) + if bad := e.Check(ctx, enforce.Desired(&g)); len(bad) > 0 { + return fail("second readback: %v", bad) + } + step("a second readback agreed") + + start := time.Now() + if err := e.EndSession(ctx); err != nil { + return fail("end session: %v", err) + } + step("ended the session in %s: random password, stop-service Y then N, read back N", time.Since(start).Round(time.Millisecond)) + + if bad := e.Restore(ctx, &enforce.Saved{Schema: enforce.SavedSchema, Values: saved}); len(bad) > 0 { + return fail("restore: %v", bad) + } + again, err := e.ReadAll(ctx) + if err != nil { + return fail("read after restore: %v", err) + } + for _, k := range enforce.Keys { + if !enforce.Matches(k, again[k], saved[k]) { + return fail("after restore %s reads %q, saved %q", k, again[k], saved[k]) + } + } + step("restored and read back every saved setting") + c.OK = true + return c +} + +// TestLabRustdeskEnforceChild is the SYSTEM half: it runs only when the +// scheduled task passes -lab-enforce-out. +func TestLabRustdeskEnforceChild(t *testing.T) { + if *labEnforceOut == "" { + t.Skip("started by TestLabRustdeskEnforce/system only") + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + b, _ := json.Marshal(runEnforceCycle(ctx)) + if err := os.WriteFile(*labEnforceOut+".new", b, 0o644); err != nil { + t.Fatal(err) + } + if err := os.Rename(*labEnforceOut+".new", *labEnforceOut); err != nil { + t.Fatal(err) + } +} + +func TestLabRustdeskEnforce(t *testing.T) { + labevidence.Require(t) + want := os.Getenv("REM0TE_LAB_RUSTDESK") + if want == "" { + t.Skip("REM0TE_LAB_RUSTDESK is not set: no RustDesk installed by the lab here") + } + report := func(t *testing.T, n *labevidence.Note, c enforceCycle) { + for _, s := range c.Steps { + n.Logf("%s", s) + } + if !c.OK { + t.Errorf("enforcement cycle failed: %s", c.Err) + } + } + + t.Run("admin", func(t *testing.T) { + n := labevidence.Track(t, "agent/msa-enforce/"+want+"/admin") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + report(t, n, runEnforceCycle(ctx)) + }) + + t.Run("system", func(t *testing.T) { + n := labevidence.Track(t, "agent/msa-enforce/"+want+"/system") + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + out := filepath.Join(os.Getenv("ProgramData"), "Rem0te", "lab-msa-enforce.json") + _ = os.MkdirAll(filepath.Dir(out), 0o755) + _ = os.Remove(out) + schtasks := filepath.Join(os.Getenv("SystemRoot"), "System32", "schtasks.exe") + task := "LabRem0teMsaEnforce" + run := func(args ...string) { + o, err := exec.Command(schtasks, args...).CombinedOutput() + if err != nil { + t.Fatalf("schtasks %v: %v %s", args, err, o) + } + } + _ = exec.Command(schtasks, "/Delete", "/TN", task, "/F").Run() + tr := fmt.Sprintf(`"%s" -test.run ^TestLabRustdeskEnforceChild$ -lab-enforce-out "%s"`, self, out) + run("/Create", "/TN", task, "/TR", tr, "/SC", "ONCE", "/ST", "00:00", "/RU", "SYSTEM", "/RL", "HIGHEST", "/F") + defer run("/Delete", "/TN", task, "/F") + run("/Run", "/TN", task) + deadline := time.Now().Add(6 * time.Minute) + var raw []byte + for time.Now().Before(deadline) { + if b, err := os.ReadFile(out); err == nil { + raw = b + break + } + time.Sleep(2 * time.Second) + } + if raw == nil { + t.Fatalf("no %s within 6 minutes", out) + } + var c enforceCycle + if err := json.Unmarshal(raw, &c); err != nil { + t.Fatalf("result: %v", err) + } + n.Logf("as SYSTEM (scheduled task, session 0), the agent's enforcement code through enforceRunner") + report(t, n, c) + }) +} diff --git a/tools/windows-installer/main.go b/tools/windows-installer/main.go index c065612b..e53b5120 100644 --- a/tools/windows-installer/main.go +++ b/tools/windows-installer/main.go @@ -25,6 +25,7 @@ // rem0te-agent.exe patch-scan read-only Windows Update posture (heartbeat, v0.27) // rem0te-agent.exe tray-host the tray host: starts rem0te-tray.exe in each session and speaks for it (heartbeat, v0.36) // rem0te-agent.exe rustdesk-preflight read-only RustDesk readiness preflight for Managed Secure Access (heartbeat, v0.69) +// rem0te-agent.exe msa-poller Managed Secure Access grant poller; only on a computer the portal says is managed (heartbeat msaPoll, v0.72) // // `chat` (the 0.34 chat host) is kept as another name for `tray-host`, for a // heartbeat written by an older portal. The 0.34 chat window (`chat-window`) @@ -216,6 +217,9 @@ func subcommand(args []string) int { if args[0] == "rustdesk-preflight" { return cmdRustdeskPreflight(args[1:]) } + if args[0] == "msa-poller" { + return cmdMsaPoller(args[1:]) + } if args[0] == "tray-host" || args[0] == "chat" { return cmdTrayHost(args[1:]) } diff --git a/tools/windows-installer/msa_poller_windows.go b/tools/windows-installer/msa_poller_windows.go new file mode 100644 index 00000000..1681dd9b --- /dev/null +++ b/tools/windows-installer/msa_poller_windows.go @@ -0,0 +1,325 @@ +//go:build windows + +package main + +// `rem0te-agent.exe msa-poller` (0.72.0): the Managed Secure Access grant +// poller, started detached by the signed heartbeat ONLY when the portal +// answered msaPoll: true — the server runs with MSA_GRANTS=on AND a Platform +// Admin moved this one computer into Managed Secure Access. On a Legacy +// computer the heartbeat never starts it, and if started anyway it asks the +// portal once, is told the computer is not managed (or 404), and exits +// without touching RustDesk. +// +// One instance (msa\poller.lock). The decisions are internal/msa/enforce's; +// this file is the wiring and the ENFORCEMENT exec site, enforceRunner.Run: +// the installed rustdesk.exe by its absolute path, an argument array that +// enforce.Valid accepts (a closed read, set, restore, password or +// stop-service toggle), no shell, no window, output capped. Its arguments +// are never logged: one of them can be a password. +// +// Files under StateDir\msa\enforce, whose DACL names SYSTEM only: the +// settings RustDesk had before the first apply (saved.json), the replay set +// (grants-seen.json) and the poller's state (enforce.json). + +import ( + "bytes" + "context" + "crypto/ed25519" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "syscall" + "time" + + "golang.org/x/sys/windows" + + "github.com/agit8or1/rem0te/windows-installer/internal/agent" + "github.com/agit8or1/rem0te/windows-installer/internal/flock" + "github.com/agit8or1/rem0te/windows-installer/internal/msa/enforce" + "github.com/agit8or1/rem0te/windows-installer/internal/trust" +) + +// enforceSDDL: SYSTEM only, inherited, nothing from the parent. Not even +// Administrators read the settings RustDesk had before (they include no +// secret, but they are what a rollback trusts). +const enforceSDDL = "D:P(A;OICI;FA;;;SY)" + +func enforceDir(p agent.Paths) string { return filepath.Join(msaDir(p), "enforce") } + +// enforceRunner is the enforcement's one exec site. +type enforceRunner struct{ exe string } + +func (r enforceRunner) Run(ctx context.Context, args []string) enforce.Result { + if !enforce.Valid(args) { + return enforce.Result{Err: errors.New("refused: not an enforcement command")} + } + if _, ok := regularFile(r.exe); !ok { + return enforce.Result{Err: errors.New("rustdesk.exe is not installed")} + } + if _, expected := rustdeskService(r.exe); !expected { + return enforce.Result{Err: errors.New("the RustDesk service does not run the installed rustdesk.exe")} + } + cmd := exec.CommandContext(ctx, r.exe, args...) + cmd.Dir = filepath.Dir(r.exe) + cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NO_WINDOW} + out := &capBuf{} + cmd.Stdout = out + cmd.WaitDelay = 5 * time.Second + err := cmd.Run() + res := enforce.Result{Stdout: out.Bytes()} + if ctx.Err() != nil { + res.TimedOut = true + } + if out.over { + res.Err = errors.New("output over the cap") + } + var ee *exec.ExitError + if errors.As(err, &ee) { + res.ExitCode = ee.ExitCode() + } else if err != nil { + res.Err = err + } + return res +} + +// ── the portal ────────────────────────────────────────────────────────────── + +type msaPortal struct { + base, rid, secret string + hc *http.Client +} + +func (m *msaPortal) post(ctx context.Context, path string, body map[string]any, hold time.Duration) ([]byte, int, error) { + body["rustdeskId"], body["agentSecret"] = m.rid, m.secret + b, _ := json.Marshal(body) + c, cancel := context.WithTimeout(ctx, hold+30*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(c, http.MethodPost, m.base+path, bytes.NewReader(b)) + if err != nil { + return nil, 0, err + } + req.Header.Set("Content-Type", "application/json") + resp, err := m.hc.Do(req) + if err != nil { + return nil, 0, err + } + defer resp.Body.Close() + raw, err := io.ReadAll(io.LimitReader(resp.Body, 256<<10)) + return raw, resp.StatusCode, err +} + +func (m *msaPortal) Poll(ctx context.Context, ack []string, wait bool) (enforce.PollAnswer, error) { + body := map[string]any{"wait": wait} + if len(ack) > 0 { + body["ack"] = ack + } + raw, code, err := m.post(ctx, "/msa/agent/poll", body, 25*time.Second) + if err != nil { + return enforce.PollAnswer{}, err + } + switch { + case code == http.StatusNotFound || code == http.StatusForbidden || code == http.StatusUnauthorized: + return enforce.PollAnswer{}, enforce.ErrStop + case code != http.StatusOK: + return enforce.PollAnswer{}, fmt.Errorf("poll: HTTP %d", code) + } + var env struct { + Data enforce.PollAnswer `json:"data"` + } + if err := json.Unmarshal(raw, &env); err != nil { + return enforce.PollAnswer{}, err + } + return env.Data, nil +} + +func (m *msaPortal) Report(ctx context.Context, r enforce.Report) error { + body := map[string]any{"event": r.Event} + if r.GrantID != "" { + body["grantId"] = r.GrantID + } + if r.Outcome != "" { + body["outcome"] = r.Outcome + } + if len(r.Keys) > 0 { + body["keys"] = r.Keys + } + _, code, err := m.post(ctx, "/msa/agent/report", body, 0) + if err == nil && code != http.StatusOK { + err = fmt.Errorf("report: HTTP %d", code) + } + return err +} + +// ── the computer ──────────────────────────────────────────────────────────── + +type msaHost struct { + paths agent.Paths + wp *winPlatform + wa *winActions + rid string +} + +func (h *msaHost) RustdeskID(context.Context) (string, error) { + // Read again: a RustDesk that changed its ID since the poller started + // must not receive a grant made for the old one. + rid, _, err := chatIdentity(h.paths) + if err != nil { + return "", err + } + return rid, nil +} + +func (h *msaHost) Sessions() (int, error) { return h.wa.RemoteSessions() } + +func (h *msaHost) Trust(context.Context) (map[string]ed25519.PublicKey, func(string, string) bool, error) { + keys, pz, err := agent.MsaTrust(agent.Options{PortalHost: pinnedPortal(), Root: embeddedRoot, Paths: h.paths}, h.wp) + if err != nil { + return nil, nil, err + } + // The signed pause has no `remote` scope; its actions scope (and an + // unreadable listed pause, which covers everything) stops grants too. + return keys, func(business, rid string) bool { return pz.ActionsPaused(business, rid) }, nil +} + +// ── the files ─────────────────────────────────────────────────────────────── + +type msaStore struct{ dir string } + +func (s msaStore) read(name string, v any) (bool, error) { + raw, err := os.ReadFile(filepath.Join(s.dir, name)) + if errors.Is(err, os.ErrNotExist) { + return false, nil + } + if err != nil { + return false, err + } + if len(raw) > 64<<10 { + return false, errors.New(name + ": too large") + } + return true, json.Unmarshal(raw, v) +} + +func (s msaStore) write(name string, v any) error { + b, err := json.Marshal(v) + if err != nil { + return err + } + return writeAtomic(filepath.Join(s.dir, name), b) +} + +func (s msaStore) LoadState() (*enforce.State, error) { + var st enforce.State + ok, err := s.read("enforce.json", &st) + if !ok || err != nil { + return nil, err + } + return &st, nil +} +func (s msaStore) SaveState(st *enforce.State) error { return s.write("enforce.json", st) } +func (s msaStore) LoadSaved() (*enforce.Saved, error) { + var sv enforce.Saved + ok, err := s.read("saved.json", &sv) + if !ok { + return nil, err + } + if err != nil || sv.Schema != enforce.SavedSchema { + return nil, errors.New("saved.json is not readable") + } + return &sv, nil +} +func (s msaStore) SaveSaved(sv *enforce.Saved) error { return s.write("saved.json", sv) } +func (s msaStore) DeleteSaved() error { + err := os.Remove(filepath.Join(s.dir, "saved.json")) + if errors.Is(err, os.ErrNotExist) { + return nil + } + return err +} +func (s msaStore) LoadSeen() (map[string]time.Time, error) { + m := map[string]time.Time{} + _, err := s.read("grants-seen.json", &m) + return m, err +} +func (s msaStore) SaveSeen(m map[string]time.Time) error { return s.write("grants-seen.json", m) } + +// secureEnforceDir: msa\enforce with the SYSTEM-only DACL, refusing a reparse point. +func secureEnforceDir(p agent.Paths, wp *winPlatform) (string, error) { + if err := wp.SecureDir(msaDir(p)); err != nil { + return "", err + } + dir := enforceDir(p) + if err := wp.SecureDir(dir); err != nil { // creates it, refuses a reparse point + return "", err + } + sd, err := windows.SecurityDescriptorFromString(enforceSDDL) + if err != nil { + return "", err + } + dacl, _, err := sd.DACL() + if err != nil { + return "", err + } + return dir, windows.SetNamedSecurityInfo(dir, windows.SE_FILE_OBJECT, + windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, dacl, nil) +} + +// cmdMsaPoller: the subcommand. It takes no arguments. +func cmdMsaPoller(args []string) int { + paths := defaultPaths() + logf := openLog(paths) + defer logf.Close() + if len(args) > 0 { + fmt.Fprintln(logf, " msa-poller: takes no arguments") + return 2 + } + if !trust.HasRoot(embeddedRoot) { + fmt.Fprintln(logf, " msa-poller: this build carries no update-signing root; it cannot verify grant keys") + return 3 + } + wp := &winPlatform{paths: paths, log: logf} + dir, err := secureEnforceDir(paths, wp) + if err != nil { + fmt.Fprintf(logf, " msa-poller: %v\n", err) + return 4 + } + l, err := flock.TryLock(filepath.Join(msaDir(paths), "poller.lock")) + if errors.Is(err, flock.ErrBusy) { + return 0 + } + if err != nil { + fmt.Fprintf(logf, " msa-poller: %v\n", err) + return 4 + } + defer l.Release() + + portal := pinnedPortal() + if !agent.ValidPortal(portal) { + fmt.Fprintln(logf, " msa-poller: no pinned portal") + return 4 + } + rid, secret, err := chatIdentity(paths) + if err != nil { + fmt.Fprintf(logf, " msa-poller: %v\n", err) + return 4 + } + o := agent.Options{PortalHost: portal, Root: embeddedRoot, Paths: paths} + p := &enforce.Poller{ + E: &enforce.Enforcer{R: enforceRunner{exe: installedRustdeskExe()}}, + P: &msaPortal{base: o.APIBase(), rid: rid, secret: secret, hc: &http.Client{}}, + H: &msaHost{paths: paths, wp: wp, wa: &winActions{paths: paths}, rid: rid}, + S: msaStore{dir: dir}, + Logf: func(f string, a ...any) { + fmt.Fprintf(logf, " "+f+"\n", a...) + }, + } + if err := p.Run(context.Background()); err != nil { + fmt.Fprintf(logf, " msa-poller: %v\n", err) + return 1 + } + return 0 +} diff --git a/version.json b/version.json index 3505971e..58b409ec 100644 --- a/version.json +++ b/version.json @@ -1,6 +1,6 @@ { - "version": "0.71.0", - "codename": "Tether", + "version": "0.72.0", + "codename": "Helm", "releaseDate": "2026-11-20", "channel": "stable" }