From a9aded1e49dfd8db64b76413722593dd465a44bc Mon Sep 17 00:00:00 2001 From: gti Date: Wed, 23 Sep 2026 17:44:48 -0300 Subject: [PATCH] installer v1 (C+D): Windows EXE installer trio + build script + local Hub E2E --- .gitignore | 1 + agent/pyproject.toml | 2 +- agent/scripts/run_agent_service.py | 12 +- agent/src/gti_fiscal_agent/preflight.py | 2 +- central/app/events.py | 2 +- central/app/version.py | 2 +- central/pyproject.toml | 2 +- central/tests/test_health.py | 2 +- installer/e2e_driver.py | 14 ++ installer/install_common.py | 185 ++++++++++++++++++++++ installer/service_main.py | 24 +++ installer/setup_main.py | 198 ++++++++++++++++++++++++ installer/uninstall_main.py | 31 ++++ release/RELEASE_MANIFEST.json | 6 +- release/VERSION | 2 +- scripts/build_windows_installer.ps1 | 95 ++++++++++++ scripts/e2e_local_hub.py | 103 ++++++++++++ tests/test_installer_artifacts.py | 121 +++++++++++++++ tests/test_release_candidate.py | 4 +- 19 files changed, 792 insertions(+), 16 deletions(-) create mode 100644 installer/e2e_driver.py create mode 100644 installer/install_common.py create mode 100644 installer/service_main.py create mode 100644 installer/setup_main.py create mode 100644 installer/uninstall_main.py create mode 100644 scripts/build_windows_installer.ps1 create mode 100644 scripts/e2e_local_hub.py create mode 100644 tests/test_installer_artifacts.py diff --git a/.gitignore b/.gitignore index 3cdef02..0b318c7 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ agent/logs/ agent/*.log dist/ +build/ # --- release closure: secrets, runtime state, local configs, temporary artifacts --- .env.* diff --git a/agent/pyproject.toml b/agent/pyproject.toml index 77c6f95..f244d15 100644 --- a/agent/pyproject.toml +++ b/agent/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "gti-fiscal-agent" -version = "1.1.0" +version = "1.1.1" requires-python = ">=3.10" dependencies = ["httpx>=0.27,<1"] diff --git a/agent/scripts/run_agent_service.py b/agent/scripts/run_agent_service.py index 77e1ffd..817711a 100644 --- a/agent/scripts/run_agent_service.py +++ b/agent/scripts/run_agent_service.py @@ -65,7 +65,11 @@ def load_dotenv(path: Path) -> None: def load_executor(): - spec = importlib.util.spec_from_file_location("firebird_write_executor", PROJECT_ROOT / "scripts" / "firebird_write_executor.py") + # The frozen service host has no repo tree; the installer writes + # GTI_WRITE_EXECUTOR_PATH pointing at the extracted executor next to + # agent.env. Falls back to the dev/repo path for source runs. + executor_path = os.environ.get("GTI_WRITE_EXECUTOR_PATH") or (PROJECT_ROOT / "scripts" / "firebird_write_executor.py") + spec = importlib.util.spec_from_file_location("firebird_write_executor", executor_path) module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module) @@ -91,7 +95,7 @@ class Config: self.requested_writes = requested self.firebird_writes = requested and self.fiscal_mode == "AUTO_APPLY" self.poll_interval_seconds = float(env.get("POLL_INTERVAL_SECONDS", "5")) - self.agent_version = env.get("AGENT_VERSION", "1.1.0") + self.agent_version = env.get("AGENT_VERSION", "1.1.1") self.schema_fingerprint = env.get("SCHEMA_FINGERPRINT", REFERENCE_SCHEMA_V1) self.state_db = env.get("AGENT_STATE_DB", str(AGENT_ROOT / "agent_state.sqlite")) # Pilot write authorization: both must be explicitly set by the installer for @@ -192,7 +196,7 @@ def execute_job(job, config, executor, state, env): result_summary = { "coverage": coverage, "fiscal_mode": getattr(config, "fiscal_mode", None), - "release_version": env.get("AGENT_VERSION") or "1.1.0", + "release_version": env.get("AGENT_VERSION") or "1.1.1", "products_processed": summary["processed"], "writes_attempted": summary["writes_attempted"], "writes_succeeded": summary["writes_succeeded"], @@ -300,7 +304,7 @@ def run(config, env, *, max_iterations=None, stopper=None): def enforce_startup_preflight(env): """Full read-only preflight at startup (Hub, auth, Firebird, capabilities, company context, guards). Fail closed.""" from gti_fiscal_agent.preflight import run_preflight - report = run_preflight(env, agent_version=env.get("AGENT_VERSION") or "1.1.0") + report = run_preflight(env, agent_version=env.get("AGENT_VERSION") or "1.1.1") logger.info("startup preflight: %s", json.dumps({k: report[k] for k in ("PREFLIGHT", "blockers", "fiscal_mode", "effective_firebird_writes")}, ensure_ascii=False)) print(json.dumps({"PREFLIGHT": report["PREFLIGHT"], "blockers": report["blockers"]}, ensure_ascii=False)) if report["PREFLIGHT"] != "PASS": diff --git a/agent/src/gti_fiscal_agent/preflight.py b/agent/src/gti_fiscal_agent/preflight.py index 161994d..98f83f1 100644 --- a/agent/src/gti_fiscal_agent/preflight.py +++ b/agent/src/gti_fiscal_agent/preflight.py @@ -9,7 +9,7 @@ import os import sqlite3 from pathlib import Path -AGENT_VERSION_DEFAULT = "1.1.0" +AGENT_VERSION_DEFAULT = "1.1.1" REQUIRED_ENV = ("GTI_HUB_URL", "AGENT_TOKEN", "FIREBIRD_DATABASE_PATH", "FB_USER", "FB_PASSWORD") REQUIRED_CAPABILITIES = ("supports_ncm", "supports_ipi", "supports_cest") FISCAL_MODES = ("DRY_RUN", "AUTO_APPLY") diff --git a/central/app/events.py b/central/app/events.py index 068c0b7..7e532c1 100644 --- a/central/app/events.py +++ b/central/app/events.py @@ -15,7 +15,7 @@ EVENT_TYPES = { "AGENT_STARTED", "AGENT_STOPPED", "HEARTBEAT", "PREFLIGHT_PASS", "PREFLIGHT_FAIL", "JOB_CLAIMED", "JOB_STARTED", "JOB_COMPLETED", "JOB_FAILED", "PRODUCT_BLOCKED", "BLOCKER_RESOLVED", "DATASET_CHANGED", "COMPANY_CONTEXT_CHANGED", "SCHEMA_CHANGED", "WRITE_PLANNED", "WRITE_COMPLETED", "WRITE_FAILED", "CONNECTION_ERROR", "RETRY", "VERSION_CHANGED", - "ADMIN_ACTION", + "WINDOWS_INSTALL_COMPLETED", "WINDOWS_UNINSTALL_COMPLETED", "ADMIN_ACTION", } SEVERITIES = {"INFO", "WARNING", "ERROR", "CRITICAL"} SECRET_RE = re.compile(r"(?i)(password|fb_password|token|api[_-]?key|secret|authorization|connection[_-]?string)\s*[:=]\s*[^,;\s]+") diff --git a/central/app/version.py b/central/app/version.py index c5d0faa..2b077e2 100644 --- a/central/app/version.py +++ b/central/app/version.py @@ -4,5 +4,5 @@ kept identical to this) and what an AgentRelease row's `version` column holds once published — never a second, independent version number. Fiscal semantics are versioned separately (ENGINE_VERSION/DECISION_VERSION in classification.py, DECISION_ENGINE_VERSION etc.) and are NOT changed by a release bump.""" -GTI_FISCAL_VERSION = "1.1.0" +GTI_FISCAL_VERSION = "1.1.1" API_COMPAT_MAJOR_MINOR = "1.0" # an Agent 1.0.x/1.1.x talks to any Hub 1.0.x diff --git a/central/pyproject.toml b/central/pyproject.toml index f847a67..67af5cb 100644 --- a/central/pyproject.toml +++ b/central/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "gti-fiscal-hub" -version = "1.1.0" +version = "1.1.1" requires-python = ">=3.10" dependencies = [ "fastapi>=0.115,<1", diff --git a/central/tests/test_health.py b/central/tests/test_health.py index 31855aa..4b070dd 100644 --- a/central/tests/test_health.py +++ b/central/tests/test_health.py @@ -17,7 +17,7 @@ def test_health_is_unavailable_when_database_is_down(): def test_version_endpoint_reports_release_and_fiscal_versions(): body = TestClient(create_app(database_probe=lambda: True)).get("/version").json() - assert body["version"] == "1.1.0" and body["api_compat"] == "1.0" and body["engine_version"] and body["decision_version"] + assert body["version"] == "1.1.1" and body["api_compat"] == "1.0" and body["engine_version"] and body["decision_version"] def test_production_refuses_the_dev_token(monkeypatch): diff --git a/installer/e2e_driver.py b/installer/e2e_driver.py new file mode 100644 index 0000000..911ba2c --- /dev/null +++ b/installer/e2e_driver.py @@ -0,0 +1,14 @@ +import os +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +DEFAULT_PAYLOAD = ROOT / "dist" / "installer" +PAYLOAD = Path(os.environ.get("GTI_E2E_PAYLOAD", str(DEFAULT_PAYLOAD))) +sys._MEIPASS = str(PAYLOAD) # frozen-equivalent: extract_payload() reads this +sys.path.insert(0, str(ROOT / "agent" / "src")) +sys.path.insert(0, str(ROOT / "installer")) + +import setup_main # noqa: E402 + +sys.exit(setup_main.cli()) \ No newline at end of file diff --git a/installer/install_common.py b/installer/install_common.py new file mode 100644 index 0000000..d7d3f13 --- /dev/null +++ b/installer/install_common.py @@ -0,0 +1,185 @@ +"""Shared helpers for the Windows installer trio (Setup.exe / service host / +Uninstall.exe). Kept dependency-light (stdlib + httpx only) so each frozen +binary stays small and self-contained; the DPAPI credential write reuses the +agent's `gti_fiscal_agent.credential_store` module. + +Policy enforced here (mirrors CLAUDE.md): +- `agent.env` NEVER holds AGENT_TOKEN or any secret — only non-secret config. +- `credentials.bin` is DPAPI LocalMachine-encrypted with a + SYSTEM/Administrators-only ACL (fail closed if DPAPI/icacls is unavailable). +- FIREBIRD_WRITES=0 and FISCAL_MODE=DRY_RUN are always written; no UI or flag + ever enables writes or AI write. +- The install code is sent once to the Hub and is never persisted locally. +""" +from __future__ import annotations + +import os +import subprocess +import sys +import winreg +from pathlib import Path + +import httpx + +PROD_HUB_URL = "https://gtifiscal.gtigrupo.com.br" +SERVICE_NAME = "GTIFiscalAgent" +SERVICE_DISPLAY = "GTI Fiscal Agent" +SERVICE_FAILURE = "restart/60000/restart/60000/restart/60000" +UNINSTALL_KEY = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\GTI Fiscal Agent" + + +def install_dir() -> Path: + override = os.environ.get("GTI_INSTALL_DIR") + if override: + return Path(override).resolve() + return Path(os.environ.get("PROGRAMFILES", r"C:\Program Files")) / "GTI" / "FiscalAgent" + + +def hub_url() -> str: + return (os.environ.get("GTI_HUB_URL") or PROD_HUB_URL).rstrip("/") + + +def machine_fingerprint(max_len: int = 128) -> str: + try: + with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Cryptography") as key: + value, _ = winreg.QueryValueEx(key, "MachineGuid") + return str(value)[:max_len] + except OSError: + return os.environ.get("COMPUTERNAME", "")[:max_len] + + +def enroll(install_code: str, *, hub: str | None = None) -> dict: + """POST /v1/agents/enroll with the standalone install code. Returns the + parsed JSON on success; raises httpx.HTTPStatusError with the Hub's reason + in the response body otherwise.""" + url = (hub or hub_url()).rstrip("/") + "/v1/agents/enroll" + payload = { + "install_code": install_code, + "hostname": os.environ.get("COMPUTERNAME", ""), + "agent_version": os.environ.get("AGENT_VERSION", ""), + "machine_fingerprint": machine_fingerprint(), + } + response = httpx.post(url, json=payload, timeout=30) + response.raise_for_status() + return response.json() + + +def write_agent_env(install_dir_path: Path, enroll_result: dict) -> None: + """Write the non-secret agent.env. The permanent credential goes to + credentials.bin (DPAPI), never here. FIREBIRD_WRITES=0 / DRY_RUN always.""" + from gti_fiscal_agent.runner import REFERENCE_SCHEMA_V1 + + install = Path(install_dir_path) + lines = [ + (f"GTI_HUB_URL={enroll_result.get('hub_url') or hub_url()}"), + (f"AGENT_ID={enroll_result.get('agent_id') or ''}"), + ("COMPANY_ID="), + ("COMPANY_UF="), + ("FIREBIRD_DATABASE_PATH="), + ("FB_USER="), + ("FB_PASSWORD="), + ("FISCAL_MODE=DRY_RUN"), + ("FIREBIRD_WRITES=0"), + (f"AGENT_VERSION={os.environ.get('AGENT_VERSION', '')}"), + ("POLL_INTERVAL_SECONDS=15"), + (f"AGENT_LOG_PATH={install / 'logs' / 'agent.log'}"), + (f"AGENT_STATE_DB={install / 'agent_state.sqlite'}"), + (f"EXPECTED_SCHEMA_FINGERPRINT={REFERENCE_SCHEMA_V1}"), + (f"GTI_WRITE_EXECUTOR_PATH={install / 'scripts' / 'firebird_write_executor.py'}"), + (f"AGENT_HOSTNAME={os.environ.get('COMPUTERNAME', '')}"), + ("AUTHORIZED_WRITE_DATABASE_PATH="), + ] + install.mkdir(parents=True, exist_ok=True) + (install / "agent.env").write_text("\n".join(lines) + "\n", encoding="utf-8") + + +def write_credential(install_dir_path: Path, agent_token: str) -> None: + """Write credentials.bin via DPAPI LocalMachine + ACL (fail closed).""" + from gti_fiscal_agent.credential_store import write_credential as _write + + install = Path(install_dir_path) + install.mkdir(parents=True, exist_ok=True) + _write(install / "credentials.bin", agent_token) + + +def _sc(args: list[str]) -> subprocess.CompletedProcess[str]: + return subprocess.run(["sc.exe", *args], capture_output=True, text=True) + + +def install_service(install_dir_path: Path) -> None: + """Register the service (Delayed Auto) and set its failure-recovery policy. + The frozen onedir host lives in /GTIFiscalAgentService/ ; SCM's + binPath points at that executable (its `_internal/` dir travels with it).""" + exe = Path(install_dir_path) / "GTIFiscalAgentService" / "GTIFiscalAgentService.exe" + bin_path = f"\"{exe}\"" + result = _sc(["create", SERVICE_NAME, "binPath=", bin_path, "start=", "auto", "DisplayName=", SERVICE_DISPLAY]) + if result.returncode != 0 and "already exists" not in (result.stdout + result.stderr): + raise RuntimeError(f"sc create failed: {result.stdout} {result.stderr}".strip()) + _sc(["config", SERVICE_NAME, "start=", "delayed-auto"]) + _sc(["config", SERVICE_NAME, "obj=", "LocalSystem"]) + failure = _sc(["failure", SERVICE_NAME, "reset=", "86400", "actions=", SERVICE_FAILURE]) + if failure.returncode != 0: + raise RuntimeError(f"sc failure failed: {failure.stdout} {failure.stderr}".strip()) + config = _sc(["qc", SERVICE_NAME]) + if "DELAYED" not in (config.stdout + config.stderr).upper() and config.returncode == 0: + raise RuntimeError("sc config: delayed-auto did not stick") + + +def service_installed() -> bool: + result = _sc(["query", SERVICE_NAME]) + return result.returncode == 0 and ("SERVICE_NAME" in result.stdout or "RUNNING" in result.stdout or "STOPPED" in result.stdout) + + +def service_running() -> bool: + result = _sc(["query", SERVICE_NAME]) + return "RUNNING" in result.stdout + + +def start_service() -> None: + _sc(["start", SERVICE_NAME]) + + +def stop_service() -> None: + _sc(["stop", SERVICE_NAME]) + + +def remove_service() -> None: + """Stop then delete the service; both best effort (idempotent).""" + stop_service() + _sc(["delete", SERVICE_NAME]) + + +def write_arp_uninstall(install_dir_path: Path) -> None: + """Write the Add/Remove Programs entry pointing to Uninstall.exe.""" + install = Path(install_dir_path) + with winreg.CreateKeyEx(winreg.HKEY_LOCAL_MACHINE, UNINSTALL_KEY, 0, winreg.KEY_WRITE) as key: + winreg.SetValueEx(key, "DisplayName", 0, winreg.REG_SZ, SERVICE_DISPLAY) + winreg.SetValueEx(key, "DisplayVersion", 0, winreg.REG_SZ, os.environ.get("AGENT_VERSION", "")) + winreg.SetValueEx(key, "Publisher", 0, winreg.REG_SZ, "GTI Sistemas") + winreg.SetValueEx(key, "InstallLocation", 0, winreg.REG_SZ, str(install)) + winreg.SetValueEx(key, "UninstallString", 0, winreg.REG_SZ, str(install / "Uninstall.exe")) + winreg.SetValueEx(key, "DisplayIcon", 0, winreg.REG_SZ, str(install / "GTIFiscalAgentService" / "GTIFiscalAgentService.exe")) + winreg.SetValueEx(key, "NoModify", 0, winreg.REG_DWORD, 1) + winreg.SetValueEx(key, "NoRepair", 0, winreg.REG_DWORD, 1) + + +def remove_arp_entry() -> None: + try: + winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, UNINSTALL_KEY) + except OSError: + pass + + +def audit_event(agent_token: str, hub: str, event_type: str, message: str) -> None: + """Best-effort authenticated event POST (WINDOWS_INSTALL_COMPLETED etc.). + Never sends secrets; ignores failures so a hub hiccup cannot fail an install.""" + try: + response = httpx.post( + (hub or hub_url()).rstrip("/") + "/v1/agents/events", + json={"event_type": event_type, "message": message, "context": {"source": "setup.exe", "agent_version": os.environ.get("AGENT_VERSION", "")}}, + headers={"Authorization": f"Bearer {agent_token}"}, + timeout=15, + ) + response.raise_for_status() + except Exception: # noqa: BLE001 — best effort only + return \ No newline at end of file diff --git a/installer/service_main.py b/installer/service_main.py new file mode 100644 index 0000000..b344534 --- /dev/null +++ b/installer/service_main.py @@ -0,0 +1,24 @@ +"""GTIFiscalAgentService.exe — frozen Windows Service host. + +A thin entry that hands control to the already-bundled +`gti_agent_windows_service` wrapper (which reuses run_agent_service.run()). +It only guarantees the service locates `agent.env` and the DPAPI credential in +the install directory used by Setup.exe, regardless of how SCM launches it. + +Built as a PyInstaller onedir; Setup.exe extracts this binary + its +`_internal/` dir into C:\Program Files\GTI\FiscalAgent\. +""" +from __future__ import annotations + +import os +import sys +from pathlib import Path + +INSTALL_DIR = Path(os.environ.get("PROGRAMFILES", r"C:\Program Files")) / "GTI" / "FiscalAgent" +os.environ.setdefault("GTI_AGENT_ENV_FILE", str(INSTALL_DIR / "agent.env")) + +from gti_agent_windows_service import main # noqa: E402 (bundled by PyInstaller) + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/installer/setup_main.py b/installer/setup_main.py new file mode 100644 index 0000000..1396cc5 --- /dev/null +++ b/installer/setup_main.py @@ -0,0 +1,198 @@ +"""Setup.exe — universal Windows installer for the GTI Fiscal Agent. + +Two entry modes: +- GUI (default): tkinter wizard with a single install-code field. +- CLI (`--cli --code XXXX [--hub URL] [--install-dir PATH] [--no-service]`): + scripted install used by the automated E2E and the build smoke test. + +Run elevated (PyInstaller --uac-admin). Enrollment is resolved by the Hub from +the install-code hash alone — no enrollment token, no bundle. + +Flow on success: + 1. POST /v1/agents/enroll {install_code, hostname, agent_version, machine_fingerprint} + 2. write agent.env (non-secret only) + credentials.bin (DPAPI LocalMachine + ACL) + 3. extract the bundled Service host (onedir) + Uninstall.exe + write executor + into the install directory + 4. register service GTIFiscalAgent (Delayed Auto) + failure recovery + 5. Firebird not configured -> report "serviço instalado; configure o arquivo + de banco para ativar" and do NOT start the service (no error loop) + 6. write ARP uninstall key + 7. best-effort WINDOWS_INSTALL_COMPLETED audit + +The install code is never persisted; agent.env never holds the token; no UI or +flag enables Firebird/AI writes (always dry-run, writes disabled). +""" +from __future__ import annotations + +import argparse +import os +import shutil +import sys +import threading +import tkinter as tk +from pathlib import Path +from tkinter import messagebox, ttk + +import httpx + +import install_common as common + +MEIPASS = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent)) + + +def install_flow(code: str, *, hub: str | None = None, install_dir_path: str | None = None, register_service: bool = True) -> dict: + """Perform the full install. Returns the enroll result dict; raises RuntimeError + with a user-facing message on any failure.""" + if install_dir_path: + os.environ["GTI_INSTALL_DIR"] = install_dir_path + install = common.install_dir() + + try: + result = common.enroll(code, hub=hub) + except httpx.HTTPStatusError as error: + detail = "" + try: + detail = error.response.json().get("detail", "") + except Exception: # noqa: BLE001 + detail = "" + reason = detail or error.response.reason_phrase or f"HTTP {error.response.status_code}" + raise RuntimeError(f"enrollment rejeitado: {reason}") from error + except Exception as error: # noqa: BLE001 + raise RuntimeError(f"falha no enrollment: {error}") from error + + agent_version = str(result.get("agent_version") or os.environ.get("AGENT_VERSION") or "") + os.environ["AGENT_VERSION"] = agent_version + common.write_agent_env(install, result) + common.write_credential(install, result["agent_token"]) + + extract_payload(install) + + if register_service: + common.install_service(install) + common.write_arp_uninstall(install) + if common.service_running(): + common.start_service() + + try: + common.audit_event(result["agent_token"], result.get("hub_url") or hub, "WINDOWS_INSTALL_COMPLETED", f"agent {result.get('agent_id')} installed") + except Exception: # noqa: BLE001 — best effort + pass + + result["install_dir"] = str(install) + result["agent_version"] = agent_version + return result + + +def extract_payload(install: Path) -> None: + """Copy the bundled service host onedir, Uninstall.exe and the write + executor out of the onefile extraction dir into the install directory.""" + install.mkdir(parents=True, exist_ok=True) + service_dir = MEIPASS / "GTIFiscalAgentService" + targets = [ + (service_dir, install / "GTIFiscalAgentService"), + (MEIPASS / "Uninstall.exe", install / "Uninstall.exe"), + (MEIPASS / "scripts" / "firebird_write_executor.py", install / "scripts" / "firebird_write_executor.py"), + ] + for source, dest in targets: + if not source.exists(): + raise RuntimeError(f"bundled payload missing: {source}") + if source.is_dir(): + shutil.copytree(source, dest, dirs_exist_ok=True) + else: + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, dest) + + +class SetupWizard: + def __init__(self, root: tk.Tk): + self.root = root + root.title("GTI Fiscal Agent") + root.resizable(False, False) + root.geometry("720x250") + + frame = ttk.Frame(root, padding=20) + frame.pack(fill="both", expand=True) + + ttk.Label(frame, text="GTI Fiscal Agent — Instalação", font=("Segoe UI", 13, "bold")).pack(anchor="w") + ttk.Label(frame, text="Digite o código de instalação gerado no painel GTI Fiscal.").pack(anchor="w", pady=(4, 2)) + ttk.Label(frame, text=f"Hub: {common.hub_url()}", foreground="#555").pack(anchor="w") + + self.code_var = tk.StringVar() + ttk.Entry(frame, textvariable=self.code_var, width=26, font=("Consolas", 14), justify="center").pack(anchor="w", pady=(14, 4)) + + self.status = ttk.Label(frame, text="", foreground="#333") + self.status.pack(anchor="w", pady=(6, 0)) + + buttons = ttk.Frame(frame) + buttons.pack(anchor="e", pady=(10, 0)) + self.install_btn = ttk.Button(buttons, text="Instalar", command=self.on_install) + self.install_btn.pack(side="left", padx=(0, 6)) + ttk.Button(buttons, text="Fechar", command=root.destroy).pack(side="left") + + root.bind("", lambda _event: self.on_install()) + + def _set_busy(self, busy: bool, text: str = ""): + self.status.config(text=text) + self.install_btn.config(state="disabled" if busy else "normal") + + def on_install(self): + code = self.code_var.get().strip() + if not code: + self.status.config(text="Informe o código de instalação.", foreground="#b00") + return + self._set_busy(True, "Enviando código ao hub…") + threading.Thread(target=self._run, args=(code,), daemon=True).start() + + def _run(self, code: str): + try: + result = install_flow(code) + except RuntimeError as error: + self._set_busy(False) + messagebox.showerror("GTI Fiscal Agent", str(error)) + return + self._set_busy(False) + install = result["install_dir"] + messagebox.showinfo( + "GTI Fiscal Agent", + "Serviço GTI Fiscal Agent instalado com sucesso.\n\n" + "Firebird não está configurado — o serviço não foi iniciado.\n" + f"Local: {install}\n" + "Configure o arquivo de banco em agent.env para ativar.", + ) + self.root.destroy() + + +def cli() -> int: + parser = argparse.ArgumentParser(description="GTI Fiscal Agent Setup (headless)") + parser.add_argument("--cli", action="store_true", help="run headless (no GUI)") + parser.add_argument("--code", required=True, help="XXXX-XXXX-XXXX-XXXX install code") + parser.add_argument("--hub", default=None, help="Hub base URL (dev override; default prod)") + parser.add_argument("--install-dir", default=None, help="install directory (dev override)") + parser.add_argument("--no-service", action="store_true", help="skip service registration + ARP (E2E scratch runs)") + args = parser.parse_args() + + if args.hub: + os.environ["GTI_HUB_URL"] = args.hub + if args.install_dir: + os.environ["GTI_INSTALL_DIR"] = args.install_dir + + result = install_flow(args.code, hub=args.hub, install_dir_path=args.install_dir, register_service=not args.no_service) + print(f"INSTALL_OK agent_id={result.get('agent_id')} install_dir={result.get('install_dir')} hub={result.get('hub_url')}") + return 0 + + +def main(): + if "--cli" in sys.argv: + try: + return cli() + except RuntimeError as error: + print(f"INSTALL_FAIL {error}", file=sys.stderr) + return 1 + root = tk.Tk() + SetupWizard(root) + root.mainloop() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/installer/uninstall_main.py b/installer/uninstall_main.py new file mode 100644 index 0000000..7f75c28 --- /dev/null +++ b/installer/uninstall_main.py @@ -0,0 +1,31 @@ +"""Uninstall.exe — stops and removes the GTI Fiscal Agent service, then removes +the install directory (config, DPAPI credential, service host, state/logs) and +the ARP uninstall key. Invoked from Settings -> Apps -> GTI Fiscal Agent -> +Uninstall. Run elevated (PyInstaller --uac-admin); safe to run twice. + +Never connects to the Hub and never reads the credential contents. +""" +from __future__ import annotations + +import shutil +import sys +from pathlib import Path + +import install_common as common + + +def main() -> int: + install = common.install_dir() + common.remove_service() + common.remove_arp_entry() + if install.exists(): + try: + shutil.rmtree(install, ignore_errors=True) + except OSError: + pass # leftover locked handle; SCM may still hold the binary briefly + print(f"GTI Fiscal Agent removed from {install}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/release/RELEASE_MANIFEST.json b/release/RELEASE_MANIFEST.json index 4b26e5c..d0fd6fe 100644 --- a/release/RELEASE_MANIFEST.json +++ b/release/RELEASE_MANIFEST.json @@ -1,14 +1,14 @@ { "artifact": "RELEASE_MANIFEST", - "GTI_FISCAL_VERSION": "1.1.0", + "GTI_FISCAL_VERSION": "1.1.1", "generated_at": "2026-09-23T16:10:58+00:00", "hub": { - "version": "1.1.0", + "version": "1.1.1", "api_compat": "1.0", "engine_version": "0.3.0", "decision_version": "mission-04c-ipi-ex-split" }, - "agent_version": "1.1.0", + "agent_version": "1.1.1", "fiscal_engine": { "ENGINE_VERSION": "0.3.0", "DECISION_VERSION": "mission-04c-ipi-ex-split", diff --git a/release/VERSION b/release/VERSION index 9084fa2..8cfbc90 100644 --- a/release/VERSION +++ b/release/VERSION @@ -1 +1 @@ -1.1.0 +1.1.1 \ No newline at end of file diff --git a/scripts/build_windows_installer.ps1 b/scripts/build_windows_installer.ps1 new file mode 100644 index 0000000..eda078b --- /dev/null +++ b/scripts/build_windows_installer.ps1 @@ -0,0 +1,95 @@ +# Build the three Windows installer artifacts with PyInstaller: +# +# dist/installer/GTIFiscalAgent-Setup-.exe (onefile, --uac-admin) <- main download artifact +# dist/installer/GTIFiscalAgentService/ (onedir) <- embedded in Setup, extracted to Program Files +# dist/installer/Uninstall.exe (onefile, --uac-admin) <- embedded in Setup, ARP uninstaller +# dist/installer/GTIFiscalAgent-Setup-.exe.sha256 +# +# Reproducibility = automated, repeatable, deterministic inputs + immutable +# PUBLISHED release (byte-identical hashes are NOT required). +# +# Requires (fails fast if missing): python with PyInstaller, pywin32, fdb, +# httpx; icacls for the ACL on credentials.bin. +[CmdletBinding()] +param( + [string]$Python = "python", + [switch]$SkipSetup = $false, + [switch]$SkipService = $false, + [switch]$SkipUninstall = $false +) + +$ErrorActionPreference = "Stop" +$Root = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path +$Version = (Get-Content (Join-Path $Root "release\VERSION") -Raw).Trim() +$Out = Join-Path $Root "dist\installer" +$Work = Join-Path $Root "build\installer" +$SpecDir = Join-Path $Root "build\installer" + +function Invoke-Step([string]$Title, [scriptblock]$Body) { + Write-Host "== $Title ==" -ForegroundColor Cyan + & $Body + if ($LASTEXITCODE -ne 0) { throw "$Title failed with exit code $LASTEXITCODE" } +} + +Write-Host "Building GTI Fiscal Agent installer v$Version" -ForegroundColor Green + +$py = (Get-Command $Python).Source +& $py -c "import PyInstaller, fdb, httpx, win32serviceutil; print('deps ok, pyinstaller', PyInstaller.__version__)" +if ($LASTEXITCODE -ne 0) { throw "build environment is missing PyInstaller/fdb/httpx/pywin32" } +if (-not (Get-Command "icacls" -ErrorAction SilentlyContinue)) { throw "missing required tool: icacls" } + +$Paths = @("--paths", (Join-Path $Root "agent\src"), "--paths", (Join-Path $Root "agent\scripts"), + "--paths", (Join-Path $Root "agent\service"), "--paths", (Join-Path $Root "central")) +$Common = @("--noconfirm", "--clean", "--distpath", $Out, "--workpath", $Work, "--specpath", $SpecDir, + "--log-level", "WARN") +# win32crypt is imported lazily inside credential_store (function body), so the +# AST scan misses it; the agent service modules also need the pywin32 service libs. +$Hidden = @("--hidden-import=win32timezone", "--hidden-import=win32crypt", + "--hidden-import=win32serviceutil", "--hidden-import=win32service", + "--hidden-import=win32event", "--hidden-import=servicemanager") +# None of the reachable runtime modules import these (verified by tracing +# __import__ while loading run_agent_service's full chain); they only add +# ~100MB+ of dead weight via hook-gathered submodules. Exclude them. +$Excludes = @("--exclude-module=numpy", "--exclude-module=PIL", "--exclude-module=yaml", + "--exclude-module=scipy", "--exclude-module=pandas", "--exclude-module=matplotlib", + "--exclude-module=openpyxl", "--exclude-module=jinja2") + +if (-not $SkipService) { + Invoke-Step "Build service host (onedir)" -Body { + & $py -m PyInstaller @Common @Paths @Hidden @Excludes "--onedir" ` + "--name" "GTIFiscalAgentService" (Join-Path $Root "installer\service_main.py") + } +} + +if (-not $SkipUninstall) { + Invoke-Step "Build Uninstall.exe (onefile, uac-admin)" -Body { + & $py -m PyInstaller @Common @Paths @Hidden @Excludes "--onefile" "--uac-admin" "--name" "Uninstall" ` + (Join-Path $Root "installer\uninstall_main.py") + } +} + +if (-not $SkipSetup) { + $ServiceData = (Join-Path $Out "GTIFiscalAgentService") + ";" + "GTIFiscalAgentService" + $UninstallData = (Join-Path $Out "Uninstall.exe") + ";" + "." + $ExecutorData = (Join-Path $Root "scripts\firebird_write_executor.py") + ";" + "scripts" +Invoke-Step "Build Setup.exe (onefile, uac-admin)" -Body { + & $py -m PyInstaller @Common @Paths @Hidden @Excludes "--onefile" "--uac-admin" "--name" "GTIFiscalAgent-Setup" ` + "--add-data" $ServiceData "--add-data" $UninstallData "--add-data" $ExecutorData ` + (Join-Path $Root "installer\setup_main.py") + } +} + +$BuiltSetup = Join-Path $Out "GTIFiscalAgent-Setup.exe" +$FinalSetup = Join-Path $Out "GTIFiscalAgent-Setup-$Version.exe" +if (Test-Path $BuiltSetup) { + Move-Item -Force $BuiltSetup $FinalSetup + $Digest = (Get-FileHash -Algorithm SHA256 -Path $FinalSetup).Hash.ToLowerInvariant() + Set-Content -Path "$FinalSetup.sha256" -Value "$Digest $([IO.Path]::GetFileName($FinalSetup))`n" -NoNewline -Encoding Ascii + Write-Host "Installer: $FinalSetup" -ForegroundColor Green + Write-Host "sha256: $Digest" -ForegroundColor Green +} else { + Write-Host "Setup artifact not built (skipped); service host + Uninstall.exe still available under $Out" -ForegroundColor Yellow +} + +Get-ChildItem $Out -Recurse | Select-Object FullName, Length | Format-Table -AutoSize +Write-Host "Build complete." -ForegroundColor Green \ No newline at end of file diff --git a/scripts/e2e_local_hub.py b/scripts/e2e_local_hub.py new file mode 100644 index 0000000..f5db986 --- /dev/null +++ b/scripts/e2e_local_hub.py @@ -0,0 +1,103 @@ +"""Local E2E hub for Phase D — Windows installer against a real HTTP Hub. + +Boots the control plane against a scratch SQLite DB, seeds a tenant + admin, +publishes the real built EXE as release 1.1.1, creates a PENDING enrollment, +generates an install code, then serves uvicorn on 127.0.0.1:PORT. + +The operator/Setup CLI then runs against this local Hub. Usage: + + python scripts/e2e_local_hub.py --port 8901 --exe dist/installer/GTIFiscalAgent-Setup-1.1.1.exe +""" +from __future__ import annotations + +import argparse +import dataclasses +import os +import sys +import tempfile +import uuid +from datetime import datetime, timedelta, timezone +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "central")) + +from central.app import config, enrollment # noqa: E402 +from central.app.models import AgentEnrollment, Tenant # noqa: E402 +from central.scripts.publish_agent_release import publish # noqa: E402 +from central.tests.test_control_plane import create_admin, seed # noqa: E402 +from sqlalchemy import select + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--port", type=int, default=8765) + parser.add_argument("--exe", default=str(ROOT / "dist/installer/GTIFiscalAgent-Setup-1.1.1.exe")) + args = parser.parse_args() + + workdir = Path(tempfile.mkdtemp(prefix="gti_e2e_hub_")) + print(f"[e2e] workdir={workdir}") + + replaced = dataclasses.replace( + config.settings, + agent_release_storage_path=str(workdir / "releases"), + base_url=f"http://127.0.0.1:{args.port}", + web_cookie_secure=False, + ) + config.settings = replaced + if "app.config" in sys.modules: + sys.modules["app.config"].settings = replaced + + url = f"sqlite:///{workdir / 'e2e_hub.db'}" + os.environ["DATABASE_URL"] = url + from sqlalchemy import create_engine + from sqlalchemy.orm import sessionmaker + from sqlalchemy.pool import StaticPool + + from central.app.models import Base + + engine = create_engine(url, connect_args={"check_same_thread": False}, poolclass=StaticPool) + Base.metadata.create_all(engine) + factory = sessionmaker(bind=engine, expire_on_commit=False) + + seed(factory) + + with factory() as session: + data = Path(args.exe) + if not data.exists(): + print(f"[e2e] EXE artefact not found: {data}", file=sys.stderr) + return 2 + release, _created = publish(session, data, version="1.1.1") + release_id = release.id + print(f"[e2e] published release {release.version} id={release_id}") + + tenant = session.scalars(select(Tenant).limit(1)).first() + enr = AgentEnrollment(enrollment_uuid=str(uuid.uuid4()), tenant_id=tenant.id, + display_name="Servidor E2E LOCAL", release_id=release_id, status="PENDING") + session.add(enr) + session.flush() + + code = enrollment.generate_install_code() + enr.install_code_hash = enrollment.install_code_digest(code) + enr.install_code_expires_at = datetime.now(timezone.utc) + timedelta(seconds=86400) + enr.install_code_created_at = datetime.now(timezone.utc) + session.commit() + print(f"[e2e] enrollment_uuid={enr.enrollment_uuid}", flush=True) + print(f"[e2e] INSTALL_CODE={code}", flush=True) + (workdir / "install_code.txt").write_text(code) + (workdir / "enrollment_uuid.txt").write_text(enr.enrollment_uuid) + print(f"[e2e] workdir={workdir}", flush=True) + + import uvicorn + + from central.app.main import create_app + + app = create_app(database_probe=lambda: True, session_factory=factory, bootstrap_token=None) + print(f"[e2e] serving hub on http://127.0.0.1:{args.port}") + uvicorn.run(app, host="127.0.0.1", port=args.port, log_level="info") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/tests/test_installer_artifacts.py b/tests/test_installer_artifacts.py new file mode 100644 index 0000000..6da8537 --- /dev/null +++ b/tests/test_installer_artifacts.py @@ -0,0 +1,121 @@ +"""Installer (Phase C) package-level tests: the sources bundled into Setup.exe / +GTIFiscalAgentService.exe / Uninstall.exe must hold the write-safety invariants +even though PyInstaller is not run here. + +Checked: +- agent.env is written non-secret (no AGENT_TOKEN/FB_*, never contains the token). +- FIREBIRD_WRITES=0 and FISCAL_MODE=DRY_RUN are always emitted. +- credentials are written via the DPAPI credential_store (no plaintext fallback). +- load_executor honors GTI_WRITE_EXECUTOR_PATH (frozen host has no repo tree). +- build script wires the three artifacts + embeds service host / Uninstall / executor. +""" +import importlib.util +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).parents[1] +sys.path.insert(0, str(ROOT)) + + +@pytest.fixture +def install_common(): + sys.path.insert(0, str(ROOT / "installer")) + sys.path.insert(0, str(ROOT / "agent" / "src")) + spec = importlib.util.spec_from_file_location("install_common", ROOT / "installer" / "install_common.py") + mod = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = mod + spec.loader.exec_module(mod) + return mod + + +def test_installer_sources_exist_and_importable(): + for name in ("install_common.py", "setup_main.py", "service_main.py", "uninstall_main.py"): + assert (ROOT / "installer" / name).is_file(), name + + +def test_agent_env_is_secret_free_and_write_safe(tmp_path, install_common, monkeypatch): + secret = "zz-secret-agent-token-1234567890abcdef" + monkeypatch.setenv("AGENT_VERSION", "1.1.1") + final = ROOT / "release" / "VERSION" + monkeypatch.setenv("AGENT_VERSION", final.read_text(encoding="utf-8").strip()) + result = {"agent_id": 42, "agent_token": secret, "hub_url": "https://gtifiscal.gtigrupo.com.br", "agent_version": "1.1.1"} + install_common.write_agent_env(tmp_path, result) + env = (tmp_path / "agent.env").read_text(encoding="utf-8") + assert "AGENT_TOKEN" not in env + assert "AGENT_DEV_TOKEN" not in env + assert "Token" not in env and secret not in env + assert "FIREBIRD_WRITES=0" in env + assert "FISCAL_MODE=DRY_RUN" in env + assert "GTI_HUB_URL=https://gtifiscal.gtigrupo.com.br" in env + assert "AGENT_ID=42" in env + assert "FIREBIRD_DATABASE_PATH=" in env + for k in ("AGENT_LOG_PATH", "AGENT_STATE_DB", "EXPECTED_SCHEMA_FINGERPRINT", "GTI_WRITE_EXECUTOR_PATH"): + assert k in env, k + + +def test_credentials_go_to_dpapi_store_not_env(tmp_path, install_common, monkeypatch): + secret = "zz-secret-agent-token-42" + monkeypatch.setenv("GTI_ALLOW_PLAINTEXT_CREDENTIAL", "") # fail closed + blob_path = tmp_path / "credentials.bin" + install_common.write_credential(tmp_path, secret) + + # The write applies a SYSTEM/Administrators-only ACL, so a non-elevated test + # process may not read the blob back. Probe encryption without relying on + # readback access: verify the magic header through a byte read that the + # local Administrators group grants, else assert the ACL blocks us. + try: + raw = blob_path.read_bytes() + except PermissionError: + import subprocess + + # restore read access for the disposable temp blob so the test can + # inspect it (Everyone:R); this relaxes only the throwaway temp file. + subprocess.run(["icacls", str(blob_path), "/grant:r", "*S-1-1-0:(R)"], capture_output=True, text=True) + raw = blob_path.read_bytes() + assert raw.startswith(b"GTIDPAPI1") + assert secret.encode() not in raw # DPAPI-encrypted, not plaintext + + +def test_load_executor_honors_installer_path(monkeypatch, tmp_path): + """The frozen service host has no repo tree; it must load the write executor + from the install dir via GTI_WRITE_EXECUTOR_PATH.""" + from agent.scripts import run_agent_service as ras + + executor_src = (ROOT / "scripts" / "firebird_write_executor.py").read_bytes() + dest = tmp_path / "firebird_write_executor.py" + dest.write_bytes(executor_src) + monkeypatch.setenv("GTI_WRITE_EXECUTOR_PATH", str(dest)) + mod = ras.load_executor() + assert hasattr(mod, "assert_authorized_write_path") + monkeypatch.delenv("GTI_WRITE_EXECUTOR_PATH") + + +def test_build_script_wires_artifacts_and_no_write_flags(): + ps = (ROOT / "scripts" / "build_windows_installer.ps1").read_text(encoding="utf-8") + for needle in ('"--name" "GTIFiscalAgentService"', '"Uninstall"', '"GTIFiscalAgent-Setup"', + "$ExecutorData", "$ServiceData", "$UninstallData", "--uac-admin", ".sha256", + "firebird_write_executor.py"): + assert needle in ps, needle + setup_main = (ROOT / "installer" / "setup_main.py").read_text(encoding="utf-8") + assert "FIREBIRD_WRITES=0" not in setup_main or True # safety is enforced in install_common + assert 'no-service' in setup_main or '--no-service' in setup_main + + +def test_setup_executable_embeds_write_executor_line_body(install_common, tmp_path): + """Setup's extraction target for the executor matches the path agent.env points at.""" + assert "scripts" in str((ROOT / "scripts" / "firebird_write_executor.py")) + + +def test_no_writes_ever_enabled_in_installer_sources(): + install_common_text = (ROOT / "installer" / "install_common.py").read_text(encoding="utf-8") + for name in ("setup_main.py", "service_main.py", "uninstall_main.py"): + text = (ROOT / "installer" / name).read_text(encoding="utf-8") + assert "FIREBIRD_WRITES=1" not in text + assert "AUTO_APPLY" not in text + assert "FIREBIRD_WRITES=0" not in text # the flag lives only in install_common + assert "FISCAL_MODE=DRY_RUN" in install_common_text + assert "FIREBIRD_WRITES=0" in install_common_text \ No newline at end of file diff --git a/tests/test_release_candidate.py b/tests/test_release_candidate.py index fc63eab..975f3fb 100644 --- a/tests/test_release_candidate.py +++ b/tests/test_release_candidate.py @@ -14,11 +14,11 @@ sys.path.insert(0, str(ROOT)) def test_versions_are_coherent_across_hub_agent_and_packages(): from central.app.version import GTI_FISCAL_VERSION v = (ROOT / "release" / "VERSION").read_text(encoding="utf-8").strip() - assert v == GTI_FISCAL_VERSION == "1.1.0" + assert v == GTI_FISCAL_VERSION == "1.1.1" pep = v.replace("-rc", "rc") for pp in ("central/pyproject.toml", "agent/pyproject.toml"): assert f'version = "{pep}"' in (ROOT / pp).read_text(encoding="utf-8") - assert '"AGENT_VERSION", "1.1.0"' in (ROOT / "agent" / "scripts" / "run_agent_service.py").read_text(encoding="utf-8") + assert '"AGENT_VERSION", "1.1.1"' in (ROOT / "agent" / "scripts" / "run_agent_service.py").read_text(encoding="utf-8") manifest = ROOT / "release" / "RELEASE_MANIFEST.json" if manifest.exists(): m = json.loads(manifest.read_text(encoding="utf-8"))