feat: Agent distribution with secure enrollment from the control panel

One universal Windows Agent package per version (agent_releases: version/
platform/architecture/sha256/status DRAFT|PUBLISHED|REVOKED; the binary
lives on a local release-storage volume, never in PostgreSQL). An operator
creates a pending installation (agent_enrollments) from Agents / Servidores
-> + Nova instalação, then either downloads it directly or generates a
one-time HTTPS link (short TTL, single use). Either path streams the
package plus a freshly minted enrollment.json whose token is never written
to storage in plaintext, only its SHA-256 hash. On the client host,
gti-agent.ps1 install-auto verifies the bundle's SHA-256, refuses a non-
HTTPS Hub, enrolls via POST /v1/agents/enroll (deleting the enrollment
token immediately after, success or failure), writes an ACL-restricted
.env with the newly issued permanent Agent token, and registers the
Windows Service without starting it (Firebird stays unconfigured on
purpose). Idempotent, replay-proof, rate-limited per IP, fully audited,
never logs a secret.

Migration 0022_agent_releases_enrollment (verified fresh-DB ==
upgrade-from-0021 by pg_dump diff). GTI_FISCAL_VERSION/AGENT_VERSION
bumped to 1.1.0 as the single source of truth across code, packages, the
release manifest and every published AgentRelease row.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
gti
2026-09-23 13:19:31 -03:00
co-authored by Claude Sonnet 5
parent b1c496fc1b
commit 8d6122c096
36 changed files with 1515 additions and 47 deletions
+82 -5
View File
@@ -5,7 +5,7 @@ Agent installations. See `docs/OPERATIONS.md` for the day-to-day command
reference (creating jobs, checking status); this document is about getting a
new environment stood up and kept alive.
## RC1 (1.0.0-rc1) — supported path
## RC1 (1.1.0) — supported path
```
Hub central (Docker: Hub + PostgreSQL, deploy/hub)
@@ -27,8 +27,8 @@ Firebird. RC1 pilots run `FISCAL_MODE=DRY_RUN` + `FIREBIRD_WRITES=0`: the Agent
5. Health: `GET /health` (Postgres included), `GET /version` (release/engine/decision versions). `APP_ENV=production` refuses to start when `AGENT_DEV_TOKEN` is set.
6. Backup/restore: `sh backup.sh` (pg_dump -Fc into `BACKUP_DIR`, keeps 14) and `sh restore.sh <dump>` (asks for the word RESTORE, stops the Hub, restores, restarts; migrations rerun at start).
### Agent (client host, PowerShell as Administrator, inside the extracted `GTIFiscalAgent-1.0.0-rc1` folder)
Build the package on the release machine: `python scripts/build_agent_package.py` -> `dist/GTIFiscalAgent-1.0.0-rc1.zip` (+ `.sha256`; secret-scanned, no `.env`).
### Agent (client host, PowerShell as Administrator, inside the extracted `GTIFiscalAgent-<version>` folder)
Build the package on the release machine: `python scripts/build_agent_package.py` -> `dist/GTIFiscalAgent-<version>.zip` (the version is `release/VERSION`) (+ `.sha256`; secret-scanned, no `.env`).
| step | command |
|---|---|
@@ -132,8 +132,9 @@ Agents with `central/scripts/register_agent.py` (see below).
keep that frozen value — their real creation time is not recoverable).
- `0020` enforces NOT NULL on 20 timestamp columns that always had
`DEFAULT now()`. It aborts, changing nothing, if any NULL exists — clean
those rows explicitly first. `0021` adds the SSO federated identity (see "Human access"). Current head:
`0021_sso_federated_identity`
those rows explicitly first. `0021` adds the SSO federated identity (see "Human
access"); `0022` adds Agent releases + secure enrollment (see "Agent
distribution"). Current head: `0022_agent_releases_enrollment`
(also recorded in `release/RELEASE_MANIFEST.json`).
### HTTPS / reverse proxy
@@ -211,6 +212,82 @@ stored in Postgres (same `token_hash` mechanism `/v1/classify` already used
never authenticates another Agent's jobs (`agent_id` is checked on every
Job operation).
## Agent distribution: install from the panel (secure enrollment)
An alternative to `register_agent.py` for a real pilot: the panel drives the
whole installation, and the technician on the client's Windows host never
gets a permanent secret by hand.
**One-time: publish a release.** The Agent's universal package (one zip per
version — never one per client) is built and published by script, never
uploaded through a browser:
```bash
python scripts/build_agent_package.py # -> dist/GTIFiscalAgent-<version>.zip
docker exec <fiscal-hub-container> python central/scripts/publish_agent_release.py \
--zip dist/GTIFiscalAgent-<version>.zip --notes "..."
```
Publishing the same version again with different bytes is refused (bump the
version instead); publishing identical bytes again is a no-op. The zip lives
on the Hub's local `agent_releases` volume (`AGENT_RELEASE_STORAGE_PATH`,
default `/app/data/releases`), never in PostgreSQL — only its metadata
(`agent_releases`: version, sha256, size, status DRAFT/PUBLISHED/REVOKED) is
a row. `Agents / Servidores -> Releases` lists and can revoke a release.
**Per installation:** `Agents / Servidores -> + Nova instalação` — pick the
client, a display name, an optional expected hostname and the release,
"Criar instalação". That installation's page then offers:
- **Baixar Agent agora** — an authenticated, immediate download (the operator
is already logged in).
- **Gerar link temporário** — a one-time HTTPS URL
(`/dl/agent/<download-token>`), shown exactly once, TTL
`AGENT_DOWNLOAD_LINK_TTL_SECONDS` (default 30 min), single use
(`AGENT_DOWNLOAD_MAX_USES_DEFAULT`, default 1). Hand it to a technician or
open it directly on the client's server — no login required to use it.
Either path streams a bundle = the universal package + a freshly minted
`enrollment.json` (installation id, a one-time enrollment token, the Hub URL)
written at download time. Only that enrollment token's SHA-256 hash is ever
stored (`agent_enrollments.enrollment_token_hash`); its plaintext exists only
inside that one HTTP response — never on disk on the Hub, never logged.
**On the client Windows host**, elevated PowerShell, inside the extracted
package:
```powershell
.\gti-agent.ps1 install-auto
```
This checks every file in the bundle against `MANIFEST.json`'s SHA-256,
refuses a non-HTTPS Hub URL, calls `POST /v1/agents/enroll` with the
enrollment token (deleting `enrollment.json` immediately after, success or
failure), writes `.env` with the newly issued **permanent** `AGENT_TOKEN`
(ACL-restricted to Administrators/SYSTEM, same as `configure`), and
registers the Windows Service — **without starting it**: Firebird is still
unconfigured on purpose (this script never guesses a client's database path
or credentials, same rule as the manual path). Edit `FIREBIRD_DATABASE_PATH`
/ `FB_USER` / `FB_PASSWORD` / `COMPANY_CODE` in `.env`, then
`.\gti-agent.ps1 preflight ; .\gti-agent.ps1 start`. Running `install-auto`
again after a successful enrollment is a no-op (idempotent).
The Hub rejects: an expired or already-used download link, a revoked
installation or release, a wrong/tampered/replayed enrollment token, and a
second enrollment attempt for an already-enrolled installation. A hostname
that doesn't match what the operator expected is recorded
(`hostname_mismatch`) and audited, but does not block enrollment. Both
public routes (`GET /dl/agent/{token}`, `POST /v1/agents/enroll`) are
rate-limited per source IP. Audit actions: `INSTALLATION_CREATED`,
`DOWNLOAD_LINK_CREATED`, `DOWNLOAD_LINK_REJECTED`, `PACKAGE_DOWNLOADED`,
`ENROLLMENT_SUCCEEDED`, `ENROLLMENT_REJECTED`, `AGENT_CREDENTIAL_ISSUED`,
`INSTALLATION_REVOKED`, `AGENT_RELEASE_REVOKED` — the real IP, never a token.
Revoking a pending or enrolled installation (`Revogar` on its detail page)
invalidates any outstanding link/enrollment token immediately and, if an
Agent was already provisioned, disables it (`agents.enabled = false`) — its
existing sessions/jobs stop authenticating on the next request.
## Configuring an Agent installation
On the client machine, copy `agent/.env.example` to `agent/.env` and fill in