ita_local_profile.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """Provision a private, account-scoped browser profile for local Italy Query tools."""
  2. from __future__ import annotations
  3. import hashlib
  4. import os
  5. import stat
  6. from pathlib import Path
  7. PROJECT_ROOT = Path(__file__).resolve().parents[1]
  8. ITA_QUERY_ACCOUNT_FILE = PROJECT_ROOT / "config" / "ita_query_account.local.json"
  9. ITA_QUERY_PROFILE_ROOT = PROJECT_ROOT / "data" / "ita_query_profiles"
  10. class ItaLocalProfileError(ValueError):
  11. """Raised when a local Italy Query browser profile is unsafe to use."""
  12. def _ensure_private_directory(path: Path) -> Path:
  13. if path.is_symlink():
  14. raise ItaLocalProfileError("browser profile directory must not be a symlink")
  15. try:
  16. path.mkdir(mode=0o700, parents=True, exist_ok=True)
  17. except OSError as exc:
  18. raise ItaLocalProfileError(
  19. f"cannot create browser profile directory ({type(exc).__name__})"
  20. ) from exc
  21. if path.is_symlink() or not path.is_dir():
  22. raise ItaLocalProfileError(
  23. "browser profile path must be a private directory"
  24. )
  25. if os.name == "posix":
  26. try:
  27. path.chmod(0o700)
  28. mode = stat.S_IMODE(path.stat().st_mode)
  29. except OSError as exc:
  30. raise ItaLocalProfileError(
  31. f"cannot secure browser profile directory ({type(exc).__name__})"
  32. ) from exc
  33. if mode != 0o700:
  34. raise ItaLocalProfileError(
  35. "browser profile directory permissions must be 700"
  36. )
  37. return path.resolve()
  38. def prepare_ita_query_profile(
  39. username: str,
  40. *,
  41. profile_root: str | Path | None = None,
  42. ) -> Path:
  43. """Create a deterministic private profile without putting the username in its path."""
  44. normalized_username = str(username or "").strip().casefold()
  45. if not normalized_username:
  46. raise ItaLocalProfileError("Italy Query username is required for its profile")
  47. root = Path(profile_root or ITA_QUERY_PROFILE_ROOT).expanduser()
  48. private_root = _ensure_private_directory(root)
  49. profile_id = hashlib.sha256(normalized_username.encode("utf-8")).hexdigest()[:24]
  50. return _ensure_private_directory(private_root / profile_id)