#!/usr/bin/env python3 """Safely add one authorized Prenot@Mi account to the Italy Query pool. The tool is locked to ``ie.it.sentinel`` and defaults to a no-network preflight. A real upload requires ``--apply``. Username, password, and API token are never accepted as command-line arguments or printed. """ from __future__ import annotations import argparse import getpass import os import re import sys from pathlib import Path from typing import Any, Mapping import requests REPO_ROOT = Path(__file__).resolve().parents[1] if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) from utils.local_account import ( LocalAccountConfigurationError, read_local_account_config, ) ACCOUNT_POOL = "ie.it.sentinel" ACCOUNT_UPLOAD_URL = "https://api.text.skin/api/account/add" SERVICE_ID = 1321 DEFAULT_CONFIG_PATH = ( Path(__file__).resolve().parents[1] / "config" / "ita_query_account.local.json" ) _SAFE_ACCOUNT_ID = re.compile(r"^[A-Za-z0-9_-]{1,64}$") _LOCAL_CONFIG_KEYS = { "username": "ITA_QUERY_USERNAME", "password": "ITA_QUERY_PASSWORD", "account_upload_token": "VS_ACCOUNT_UPLOAD_TOKEN", } class AccountUploadConfigurationError(ValueError): """Raised before any request when required local input is invalid.""" def _local_config(path: Path) -> dict[str, str]: """Read the optional ignored JSON file without exposing secret values.""" if not path.exists(): return {} try: body = read_local_account_config(path, allowed_root=None) except LocalAccountConfigurationError as exc: raise AccountUploadConfigurationError( str(exc).replace("local account file", "local config") ) from exc return { env_name: body.get(config_key, "") for config_key, env_name in _LOCAL_CONFIG_KEYS.items() } def _credential_source( env: Mapping[str, str], *, config_path: Path | None, ) -> dict[str, str]: """Merge local config with explicit environment variables taking priority.""" source = _local_config(config_path) if config_path is not None else {} for env_name in _LOCAL_CONFIG_KEYS.values(): if env.get(env_name, "").strip(): source[env_name] = env[env_name] return source def _hidden_value( env: Mapping[str, str], name: str, prompt: str, *, non_interactive: bool, ) -> str: value = env.get(name, "").strip() if not value and not non_interactive: value = getpass.getpass(prompt).strip() if not value: raise AccountUploadConfigurationError(f"{name} is required") return value def _credentials( env: Mapping[str, str], *, non_interactive: bool, ) -> tuple[str, str, str]: username = _hidden_value( env, "ITA_QUERY_USERNAME", "Italy Query username (hidden): ", non_interactive=non_interactive, ) password = _hidden_value( env, "ITA_QUERY_PASSWORD", "Italy Query password: ", non_interactive=non_interactive, ) api_token = _hidden_value( env, "VS_ACCOUNT_UPLOAD_TOKEN", "Account API token: ", non_interactive=non_interactive, ) if any(character.isspace() for character in username) or "@" not in username: raise AccountUploadConfigurationError( "ITA_QUERY_USERNAME must be the account's email address" ) return username, password, api_token def _payload(username: str, password: str) -> dict[str, Any]: return { "pool_name": ACCOUNT_POOL, "username": username, "password": password, "extra_data": { "site": "prenotami.esteri.it", "country_code": "irl", "mission_code": "ita", "city": "Dublin", "service_id": SERVICE_ID, "role": "sentinel-query", }, } def _authorization_value(api_token: str) -> str: return api_token if api_token.startswith("Bearer ") else f"Bearer {api_token}" def _response_account_id(body: object) -> str: if not isinstance(body, dict): return "not-returned" data = body.get("data") if not isinstance(data, dict): return "not-returned" candidate = str(data.get("id") or data.get("account_id") or "") return candidate if _SAFE_ACCOUNT_ID.fullmatch(candidate) else "not-returned" def run_account_upload( env: Mapping[str, str], *, apply: bool, non_interactive: bool, config_path: Path | None = None, session: Any | None = None, ) -> int: if not apply: print( "ITA_ACCOUNT_UPLOAD_PREFLIGHT_OK " f"pool={ACCOUNT_POOL} service_id={SERVICE_ID} request_sent=false" ) return 0 try: source = _credential_source(env, config_path=config_path) username, password, api_token = _credentials( source, non_interactive=non_interactive, ) except AccountUploadConfigurationError as exc: print(f"ITA_ACCOUNT_UPLOAD_CONFIG_ERROR: {exc}", file=sys.stderr) return 2 http = session or requests.Session() if hasattr(http, "trust_env"): http.trust_env = False headers = { "Accept": "application/json", "Authorization": _authorization_value(api_token), "Content-Type": "application/json", } try: response = http.post( ACCOUNT_UPLOAD_URL, json=_payload(username, password), headers=headers, timeout=10, ) except requests.RequestException as exc: print( "ITA_ACCOUNT_UPLOAD_UNCERTAIN " f"pool={ACCOUNT_POOL} type={type(exc).__name__} " "action=verify-admin-before-retry", file=sys.stderr, ) return 5 if response.status_code != 200: print( "ITA_ACCOUNT_UPLOAD_REJECTED " f"pool={ACCOUNT_POOL} status={response.status_code} request_count=1", file=sys.stderr, ) return 4 try: body = response.json() except (TypeError, ValueError): print( "ITA_ACCOUNT_UPLOAD_UNCERTAIN " f"pool={ACCOUNT_POOL} type=InvalidJson " "action=verify-admin-before-retry", file=sys.stderr, ) return 5 if isinstance(body, dict) and body.get("code") not in (None, 0): print( "ITA_ACCOUNT_UPLOAD_REJECTED " f"pool={ACCOUNT_POOL} status=business-error request_count=1", file=sys.stderr, ) return 4 print( "ITA_ACCOUNT_UPLOAD_OK " f"pool={ACCOUNT_POOL} account_id={_response_account_id(body)} " "request_count=1" ) return 0 def parse_args(argv: list[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser( description=( "Add one authorized account to ie.it.sentinel. Without --apply, " "only a local preflight is performed." ) ) parser.add_argument( "--apply", action="store_true", help="Perform exactly one account upload request.", ) parser.add_argument( "--non-interactive", action="store_true", help="Fail instead of prompting when local config values are missing.", ) parser.add_argument( "--config", default=str(DEFAULT_CONFIG_PATH), help=( "Ignored local JSON config path. Environment variables override " "values from this file." ), ) return parser.parse_args(argv) def main(argv: list[str] | None = None) -> int: args = parse_args(argv) return run_account_upload( os.environ, apply=args.apply, non_interactive=args.non_interactive, config_path=Path(args.config).expanduser(), ) if __name__ == "__main__": raise SystemExit(main())