add_ita_query_account.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. #!/usr/bin/env python3
  2. """Safely add one authorized Prenot@Mi account to the Italy Query pool.
  3. The tool is locked to ``ie.it.sentinel`` and defaults to a no-network
  4. preflight. A real upload requires ``--apply``. Username, password, and API
  5. token are never accepted as command-line arguments or printed.
  6. """
  7. from __future__ import annotations
  8. import argparse
  9. import getpass
  10. import os
  11. import re
  12. import sys
  13. from pathlib import Path
  14. from typing import Any, Mapping
  15. import requests
  16. REPO_ROOT = Path(__file__).resolve().parents[1]
  17. if str(REPO_ROOT) not in sys.path:
  18. sys.path.insert(0, str(REPO_ROOT))
  19. from utils.local_account import (
  20. LocalAccountConfigurationError,
  21. read_local_account_config,
  22. )
  23. ACCOUNT_POOL = "ie.it.sentinel"
  24. ACCOUNT_UPLOAD_URL = "https://api.text.skin/api/account/add"
  25. SERVICE_ID = 1321
  26. DEFAULT_CONFIG_PATH = (
  27. Path(__file__).resolve().parents[1]
  28. / "config"
  29. / "ita_query_account.local.json"
  30. )
  31. _SAFE_ACCOUNT_ID = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
  32. _LOCAL_CONFIG_KEYS = {
  33. "username": "ITA_QUERY_USERNAME",
  34. "password": "ITA_QUERY_PASSWORD",
  35. "account_upload_token": "VS_ACCOUNT_UPLOAD_TOKEN",
  36. }
  37. class AccountUploadConfigurationError(ValueError):
  38. """Raised before any request when required local input is invalid."""
  39. def _local_config(path: Path) -> dict[str, str]:
  40. """Read the optional ignored JSON file without exposing secret values."""
  41. if not path.exists():
  42. return {}
  43. try:
  44. body = read_local_account_config(path, allowed_root=None)
  45. except LocalAccountConfigurationError as exc:
  46. raise AccountUploadConfigurationError(
  47. str(exc).replace("local account file", "local config")
  48. ) from exc
  49. return {
  50. env_name: body.get(config_key, "")
  51. for config_key, env_name in _LOCAL_CONFIG_KEYS.items()
  52. }
  53. def _credential_source(
  54. env: Mapping[str, str],
  55. *,
  56. config_path: Path | None,
  57. ) -> dict[str, str]:
  58. """Merge local config with explicit environment variables taking priority."""
  59. source = _local_config(config_path) if config_path is not None else {}
  60. for env_name in _LOCAL_CONFIG_KEYS.values():
  61. if env.get(env_name, "").strip():
  62. source[env_name] = env[env_name]
  63. return source
  64. def _hidden_value(
  65. env: Mapping[str, str],
  66. name: str,
  67. prompt: str,
  68. *,
  69. non_interactive: bool,
  70. ) -> str:
  71. value = env.get(name, "").strip()
  72. if not value and not non_interactive:
  73. value = getpass.getpass(prompt).strip()
  74. if not value:
  75. raise AccountUploadConfigurationError(f"{name} is required")
  76. return value
  77. def _credentials(
  78. env: Mapping[str, str],
  79. *,
  80. non_interactive: bool,
  81. ) -> tuple[str, str, str]:
  82. username = _hidden_value(
  83. env,
  84. "ITA_QUERY_USERNAME",
  85. "Italy Query username (hidden): ",
  86. non_interactive=non_interactive,
  87. )
  88. password = _hidden_value(
  89. env,
  90. "ITA_QUERY_PASSWORD",
  91. "Italy Query password: ",
  92. non_interactive=non_interactive,
  93. )
  94. api_token = _hidden_value(
  95. env,
  96. "VS_ACCOUNT_UPLOAD_TOKEN",
  97. "Account API token: ",
  98. non_interactive=non_interactive,
  99. )
  100. if any(character.isspace() for character in username) or "@" not in username:
  101. raise AccountUploadConfigurationError(
  102. "ITA_QUERY_USERNAME must be the account's email address"
  103. )
  104. return username, password, api_token
  105. def _payload(username: str, password: str) -> dict[str, Any]:
  106. return {
  107. "pool_name": ACCOUNT_POOL,
  108. "username": username,
  109. "password": password,
  110. "extra_data": {
  111. "site": "prenotami.esteri.it",
  112. "country_code": "irl",
  113. "mission_code": "ita",
  114. "city": "Dublin",
  115. "service_id": SERVICE_ID,
  116. "role": "sentinel-query",
  117. },
  118. }
  119. def _authorization_value(api_token: str) -> str:
  120. return api_token if api_token.startswith("Bearer ") else f"Bearer {api_token}"
  121. def _response_account_id(body: object) -> str:
  122. if not isinstance(body, dict):
  123. return "not-returned"
  124. data = body.get("data")
  125. if not isinstance(data, dict):
  126. return "not-returned"
  127. candidate = str(data.get("id") or data.get("account_id") or "")
  128. return candidate if _SAFE_ACCOUNT_ID.fullmatch(candidate) else "not-returned"
  129. def run_account_upload(
  130. env: Mapping[str, str],
  131. *,
  132. apply: bool,
  133. non_interactive: bool,
  134. config_path: Path | None = None,
  135. session: Any | None = None,
  136. ) -> int:
  137. if not apply:
  138. print(
  139. "ITA_ACCOUNT_UPLOAD_PREFLIGHT_OK "
  140. f"pool={ACCOUNT_POOL} service_id={SERVICE_ID} request_sent=false"
  141. )
  142. return 0
  143. try:
  144. source = _credential_source(env, config_path=config_path)
  145. username, password, api_token = _credentials(
  146. source,
  147. non_interactive=non_interactive,
  148. )
  149. except AccountUploadConfigurationError as exc:
  150. print(f"ITA_ACCOUNT_UPLOAD_CONFIG_ERROR: {exc}", file=sys.stderr)
  151. return 2
  152. http = session or requests.Session()
  153. if hasattr(http, "trust_env"):
  154. http.trust_env = False
  155. headers = {
  156. "Accept": "application/json",
  157. "Authorization": _authorization_value(api_token),
  158. "Content-Type": "application/json",
  159. }
  160. try:
  161. response = http.post(
  162. ACCOUNT_UPLOAD_URL,
  163. json=_payload(username, password),
  164. headers=headers,
  165. timeout=10,
  166. )
  167. except requests.RequestException as exc:
  168. print(
  169. "ITA_ACCOUNT_UPLOAD_UNCERTAIN "
  170. f"pool={ACCOUNT_POOL} type={type(exc).__name__} "
  171. "action=verify-admin-before-retry",
  172. file=sys.stderr,
  173. )
  174. return 5
  175. if response.status_code != 200:
  176. print(
  177. "ITA_ACCOUNT_UPLOAD_REJECTED "
  178. f"pool={ACCOUNT_POOL} status={response.status_code} request_count=1",
  179. file=sys.stderr,
  180. )
  181. return 4
  182. try:
  183. body = response.json()
  184. except (TypeError, ValueError):
  185. print(
  186. "ITA_ACCOUNT_UPLOAD_UNCERTAIN "
  187. f"pool={ACCOUNT_POOL} type=InvalidJson "
  188. "action=verify-admin-before-retry",
  189. file=sys.stderr,
  190. )
  191. return 5
  192. if isinstance(body, dict) and body.get("code") not in (None, 0):
  193. print(
  194. "ITA_ACCOUNT_UPLOAD_REJECTED "
  195. f"pool={ACCOUNT_POOL} status=business-error request_count=1",
  196. file=sys.stderr,
  197. )
  198. return 4
  199. print(
  200. "ITA_ACCOUNT_UPLOAD_OK "
  201. f"pool={ACCOUNT_POOL} account_id={_response_account_id(body)} "
  202. "request_count=1"
  203. )
  204. return 0
  205. def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
  206. parser = argparse.ArgumentParser(
  207. description=(
  208. "Add one authorized account to ie.it.sentinel. Without --apply, "
  209. "only a local preflight is performed."
  210. )
  211. )
  212. parser.add_argument(
  213. "--apply",
  214. action="store_true",
  215. help="Perform exactly one account upload request.",
  216. )
  217. parser.add_argument(
  218. "--non-interactive",
  219. action="store_true",
  220. help="Fail instead of prompting when local config values are missing.",
  221. )
  222. parser.add_argument(
  223. "--config",
  224. default=str(DEFAULT_CONFIG_PATH),
  225. help=(
  226. "Ignored local JSON config path. Environment variables override "
  227. "values from this file."
  228. ),
  229. )
  230. return parser.parse_args(argv)
  231. def main(argv: list[str] | None = None) -> int:
  232. args = parse_args(argv)
  233. return run_account_upload(
  234. os.environ,
  235. apply=args.apply,
  236. non_interactive=args.non_interactive,
  237. config_path=Path(args.config).expanduser(),
  238. )
  239. if __name__ == "__main__":
  240. raise SystemExit(main())