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
@@ -0,0 +1,33 @@
{% extends "base.html" %}
{% block title %}Nova instalação | GTI Fiscal{% endblock %}
{% block content %}
<div class="page-heading"><div><p class="eyebrow">DISTRIBUIÇÃO DO AGENT</p><h1>Nova instalação</h1><p class="muted">Cria uma instalação pendente; o pacote e o vínculo de enrollment só existem depois de gerados aqui.</p></div><div><a href="/agents" class="secondary">Voltar</a></div></div>
<section class="panel" style="max-width:560px">
{% if error %}<p class="error" role="alert">{{ error }}</p>{% endif %}
{% if not releases %}
<p class="muted">Nenhuma versão do Agent está publicada ainda. Publique uma release primeiro (<code>python central/scripts/publish_agent_release.py</code>) e ela aparecerá aqui.</p>
{% else %}
<form method="post" action="/agents/new">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<label>Cliente
<select name="tenant_id" required>
<option value="">Selecione</option>
{% for tenant in tenants %}<option value="{{ tenant.id }}">{{ tenant.name }}</option>{% endfor %}
</select>
</label>
<label>Nome da instalação
<input name="display_name" placeholder="ex. Servidor Principal" maxlength="160" required>
</label>
<label>Hostname esperado (opcional)
<input name="expected_hostname" placeholder="ex. SRV-CONSTRUCAO" maxlength="255">
</label>
<label>Versão do Agent
<select name="release_id" required>
{% for release in releases %}<option value="{{ release.id }}" {% if loop.first %}selected{% endif %}>{{ release.version }} ({{ release.platform }}/{{ release.architecture }})</option>{% endfor %}
</select>
</label>
<p><button type="submit">Criar instalação</button></p>
</form>
{% endif %}
</section>
{% endblock %}
@@ -0,0 +1,50 @@
{% extends "base.html" %}
{% block title %}{{ enr.display_name }} | Instalação | GTI Fiscal{% endblock %}
{% block content %}
<div class="detail-head"><div><p class="eyebrow">DISTRIBUIÇÃO DO AGENT</p><h1>{{ enr.display_name }}</h1><p class="muted">{{ tenant.name if tenant else "Cliente não encontrado" }} · release {{ release.version if release else "?" }}</p></div><div><span class="badge">{{ enr.status }}</span></div></div>
{% if download_link %}
<section class="panel">
<h2>Link temporário gerado</h2>
<p class="muted">Mostrado uma única vez, uso único, expira em pouco tempo. Copie agora — ele não pode ser recuperado depois.</p>
<p><code style="word-break:break-all">{{ download_link }}</code></p>
</section>
{% endif %}
<section class="panel">
<h2>Detalhes</h2>
<table>
<tr><th>Cliente</th><td>{{ tenant.name if tenant else "-" }}</td></tr>
<tr><th>Nome</th><td>{{ enr.display_name }}</td></tr>
<tr><th>Hostname esperado</th><td>{{ enr.expected_hostname or "não informado" }}</td></tr>
<tr><th>Versão do Agent</th><td>{{ release.version if release else "-" }} ({{ release.platform if release else "" }}/{{ release.architecture if release else "" }})</td></tr>
<tr><th>Status</th><td><span class="badge">{{ enr.status }}</span>{% if enr.hostname_mismatch %} <span class="badge critical">hostname divergente</span>{% endif %}</td></tr>
<tr><th>Criada em</th><td>{{ enr.created_at }}</td></tr>
<tr><th>Baixada em</th><td>{{ enr.downloaded_at or "ainda não" }}</td></tr>
<tr><th>Hostname visto</th><td>{{ enr.hostname_seen or "-" }}</td></tr>
{% if installed_agent %}
<tr><th>Agent</th><td><a href="/agents/{{ installed_agent.id }}">#{{ installed_agent.id }}</a> · {{ "ativo" if installed_agent.enabled else "desativado" }} · último heartbeat: {{ installed_agent.last_seen_at or "nenhum ainda" }}</td></tr>
{% endif %}
</table>
</section>
<section class="panel">
<h2>Ações</h2>
{% if enr.status not in ("ENROLLED", "REVOKED") %}
<form method="post" action="/agents/pending/{{ enr.enrollment_uuid }}/link" style="display:inline">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button type="submit">Gerar link temporário</button>
</form>
<a href="/agents/pending/{{ enr.enrollment_uuid }}/download" class="botao">Baixar Agent agora</a>
{% endif %}
{% if enr.status != "REVOKED" %}
<form method="post" action="/agents/pending/{{ enr.enrollment_uuid }}/revoke" style="display:inline" onsubmit="return confirm('Revogar esta instalação? Links e o Agent (se já ativo) deixam de funcionar.');">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button type="submit" class="secondary">Revogar</button>
</form>
{% endif %}
{% if enr.status == "ENROLLED" and installed_agent %}
<a href="/agents/{{ installed_agent.id }}" class="secondary">Ver Agent</a>
{% endif %}
</section>
{% endblock %}
+34
View File
@@ -0,0 +1,34 @@
{% extends "base.html" %}
{% block title %}Releases do Agent | GTI Fiscal{% endblock %}
{% block content %}
<div class="page-heading"><div><p class="eyebrow">DISTRIBUIÇÃO DO AGENT</p><h1>Versões do Agent</h1><p class="muted">O binário é universal por versão; publicação é feita por script (<code>central/scripts/publish_agent_release.py</code>), nunca por upload no navegador.</p></div><div><a href="/agents/new" class="botao">+ Nova instalação</a> <a href="/agents" class="secondary">Voltar</a></div></div>
<div class="panel table-wrap">
<table>
<caption>Releases catalogadas</caption>
<thead><tr><th>Versão</th><th>Plataforma</th><th>Status</th><th>SHA-256</th><th>Tamanho</th><th>Publicada em</th><th>Instalações</th><th></th></tr></thead>
<tbody>
{% for release in releases %}
<tr>
<td><b>{{ release.version }}</b></td>
<td>{{ release.platform }}/{{ release.architecture }}</td>
<td><span class="badge {{ 'critical' if release.status == 'REVOKED' else '' }}">{{ release.status }}</span></td>
<td><code>{{ release.sha256[:12] }}…</code></td>
<td>{{ "%.1f"|format(release.size_bytes / 1048576) }} MB</td>
<td>{{ release.published_at or "não publicada" }}</td>
<td>{{ installation_counts.get(release.id, 0) }}</td>
<td>
{% if release.status == "PUBLISHED" %}
<form method="post" action="/agents/releases/{{ release.id }}/revoke" onsubmit="return confirm('Revogar a release {{ release.version }}? Nenhum novo download poderá usá-la.');">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<button type="submit" class="secondary">Revogar</button>
</form>
{% endif %}
</td>
</tr>
{% else %}
<tr><td colspan="8" class="empty-state">Nenhuma release publicada ainda.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
+2 -1
View File
@@ -1,7 +1,8 @@
{% extends "base.html" %}
{% block title %}Agents | GTI Fiscal{% endblock %}
{% block content %}
<div class="page-heading"><div><p class="eyebrow">INVENTÁRIO OPERACIONAL</p><h1>Agents / Servidores</h1><p class="muted">Identidade do cliente primeiro; IDs técnicos ficam no detalhe.</p></div><form class="filters" method="get"><label>Cliente, instalação ou hostname<input name="search" value="{{ search }}"></label><label>Saúde técnica<select name="health"><option value="">Todos</option>{% for value in ["ONLINE","DEGRADED","OFFLINE","FAILED","UNKNOWN"] %}<option value="{{ value }}" {% if health_filter==value %}selected{% endif %}>{{ value|title }}</option>{% endfor %}</select></label><label>Ordenação<select name="sort"><option value="display_name" {% if sort=="display_name" %}selected{% endif %}>Nome de exibição</option><option value="worst_coverage" {% if sort=="worst_coverage" %}selected{% endif %}>Pior cobertura fiscal</option></select></label><button class="secondary" type="submit">Filtrar</button></form></div>
<div class="page-heading"><div><p class="eyebrow">INVENTÁRIO OPERACIONAL</p><h1>Agents / Servidores</h1><p class="muted">Identidade do cliente primeiro; IDs técnicos ficam no detalhe.</p></div><div><a href="/agents/new" class="botao">+ Nova instalação</a> <a href="/agents/releases" class="secondary">Releases</a></div></div>
<div class="page-heading"><form class="filters" method="get"><label>Cliente, instalação ou hostname<input name="search" value="{{ search }}"></label><label>Saúde técnica<select name="health"><option value="">Todos</option>{% for value in ["ONLINE","DEGRADED","OFFLINE","FAILED","UNKNOWN"] %}<option value="{{ value }}" {% if health_filter==value %}selected{% endif %}>{{ value|title }}</option>{% endfor %}</select></label><label>Ordenação<select name="sort"><option value="display_name" {% if sort=="display_name" %}selected{% endif %}>Nome de exibição</option><option value="worst_coverage" {% if sort=="worst_coverage" %}selected{% endif %}>Pior cobertura fiscal</option></select></label><button class="secondary" type="submit">Filtrar</button></form></div>
<div class="panel table-wrap"><table><caption>Instalações monitoradas</caption><thead><tr><th>Cliente</th><th>Nome de exibição</th><th>Hostname</th><th>Saúde técnica</th><th>Status fiscal</th><th>Cobertura fiscal</th><th>Produtos</th><th>Versão</th><th>Último heartbeat</th></tr></thead><tbody>{% for item in result["items"] %}<tr><td><a href="/agents/{{ item.agent_id }}"><b>{{ item.client or "Cliente não identificado" }}</b></a></td><td>{{ item.display_name or "Não informado" }}</td><td>{{ item.hostname or "Não informado" }}</td><td><span class="badge {{ item.technical_health|lower }}">Saúde técnica: {{ item.technical_health_label }}</span></td><td><span class="badge fiscal-{{ item.fiscal_status|lower }}">Status fiscal: {{ item.fiscal_status_label }}</span><small>{{ item.fiscally_complete }} completos · {{ item.safe_blocked }} bloqueados com segurança · {{ item.failed_products }} falhas · {{ item.unclassified_products }} não classificados</small>{% if not item.coverage_invariant_pass %}<small class="error">Inconsistência: {{ item.coverage_overcount_products }} acima do total{% if item.coverage_invalid_counts %}; contagens negativas{% endif %}</small>{% endif %}</td><td><strong>{{ "%.1f"|format(item.fiscal_completion_percent)|replace(".", ",") }}%</strong><small>{{ item.fiscally_complete }} / {{ item.total_products }} completos</small></td><td>{{ item.total_products }}<small>{{ item.failed_products }} falhas técnicas</small></td><td>{{ item.agent_version_display }}</td><td title="{{ item.last_seen_at }}">{{ item.last_seen_display }}<small>{{ item.last_seen_age }}</small></td></tr>{% else %}<tr><td colspan="9" class="empty-state">Nenhuma instalação encontrada.</td></tr>{% endfor %}</tbody></table></div>
<nav class="pagination" aria-label="Paginação de agents">{% if result.page > 1 %}<a href="/agents?page={{ result.page - 1 }}{% if query_base %}&{{ query_base }}{% endif %}">Anterior</a>{% endif %}<span>Página {{ result.page }} · {{ result.total }} instalações</span>{% if result.page * result.page_size < result.total %}<a href="/agents?page={{ result.page + 1 }}{% if query_base %}&{{ query_base }}{% endif %}">Próxima</a>{% endif %}</nav>
{% endblock %}