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
+83
View File
@@ -0,0 +1,83 @@
"""Administrative CLI: publish a built Agent package (scripts/build_agent_package.py
output) as an AgentRelease, ready to be downloaded/enrolled from the panel.
Like register_agent.py, this is a one-time, operator-run action against
DATABASE_URL directly — never a browser upload endpoint, so the release
binary never has to pass through an HTTP request body. The zip is copied
into the Hub's local release storage (AGENT_RELEASE_STORAGE_PATH), never
into PostgreSQL; only its metadata (version, sha256, size, path) is a row.
Usage:
python central/scripts/publish_agent_release.py --zip dist/GTIFiscalAgent-1.0.0.zip \\
--notes "First distributable build with secure enrollment"
Refuses to publish the same version+platform+architecture twice with a
different sha256 (an accidental respin must get a new version). Publishing
the exact same bytes again is a no-op (idempotent).
"""
import argparse
import hashlib
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "central"))
from sqlalchemy.orm import Session # noqa: E402
from app import release_storage # noqa: E402
from app.db import engine # noqa: E402
from app.models import AgentRelease # noqa: E402
def publish(session, zip_path: Path, *, platform="windows", architecture="x64", notes=None, created_by=None, version=None):
data = zip_path.read_bytes()
digest = hashlib.sha256(data).hexdigest()
version = version or _version_from_manifest(zip_path)
existing = session.query(AgentRelease).filter_by(version=version, platform=platform, architecture=architecture).one_or_none()
if existing:
if existing.sha256 == digest:
return existing, False # identical content already published: idempotent no-op
raise SystemExit(f"refused: {version}/{platform}/{architecture} is already published with a different sha256 "
f"({existing.sha256[:12]}... != {digest[:12]}...) — bump the version instead of overwriting it")
filename = release_storage.release_filename(version, platform, architecture)
dest = release_storage.storage_root() / filename
dest.write_bytes(data)
release = AgentRelease(version=version, platform=platform, architecture=architecture, filename=filename,
size_bytes=len(data), sha256=digest, storage_path=filename, status="PUBLISHED",
release_notes=notes, created_by=created_by)
session.add(release)
session.commit()
return release, True
def _version_from_manifest(zip_path: Path) -> str:
# The package name is `GTIFiscalAgent-<version>.zip`; avoids depending on
# zip internals just to learn the version this script itself is publishing.
stem = zip_path.stem
prefix = "GTIFiscalAgent-"
if not stem.startswith(prefix):
raise SystemExit(f"cannot infer version from filename {zip_path.name!r} — pass --version explicitly")
return stem[len(prefix):]
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--zip", required=True, type=Path, help="Path to the built package zip (scripts/build_agent_package.py output)")
parser.add_argument("--version", default=None, help="Override the version instead of inferring it from the filename")
parser.add_argument("--platform", default="windows")
parser.add_argument("--architecture", default="x64")
parser.add_argument("--notes", default=None, help="Release notes shown in the panel")
args = parser.parse_args()
if not args.zip.exists():
raise SystemExit(f"not found: {args.zip}")
with Session(engine) as session:
release, created = publish(session, args.zip, platform=args.platform, architecture=args.architecture, notes=args.notes, version=args.version)
print(f"{'published' if created else 'already published (idempotent)'}: version={release.version} "
f"platform={release.platform} architecture={release.architecture} sha256={release.sha256} size_bytes={release.size_bytes}")
if __name__ == "__main__":
main()