local_account.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. """Load a locally stored account without exposing its secret values."""
  2. from __future__ import annotations
  3. import json
  4. import os
  5. import stat
  6. from pathlib import Path
  7. from vs_types import VSAccount
  8. PROJECT_ROOT = Path(__file__).resolve().parents[1]
  9. LOCAL_ACCOUNT_KEYS = frozenset(
  10. {"username", "password", "account_upload_token"}
  11. )
  12. class LocalAccountConfigurationError(ValueError):
  13. """Raised when a local account file cannot be used safely."""
  14. def _resolved_path(
  15. path: str | Path,
  16. *,
  17. allowed_root: Path | None,
  18. ) -> Path:
  19. candidate = Path(path).expanduser()
  20. if not candidate.is_absolute():
  21. candidate = (allowed_root or PROJECT_ROOT) / candidate
  22. resolved = candidate.resolve()
  23. if allowed_root is not None:
  24. resolved_root = allowed_root.resolve()
  25. if resolved != resolved_root and not resolved.is_relative_to(resolved_root):
  26. raise LocalAccountConfigurationError(
  27. "local account file must stay inside the configured project root"
  28. )
  29. return resolved
  30. def read_local_account_config(
  31. path: str | Path,
  32. *,
  33. allowed_root: Path | None = PROJECT_ROOT,
  34. ) -> dict[str, str]:
  35. """Read the shared local JSON schema used by runtime and onboarding tools."""
  36. if not str(path).strip():
  37. raise LocalAccountConfigurationError("local_account_file is required")
  38. resolved = _resolved_path(path, allowed_root=allowed_root)
  39. try:
  40. file_stat = resolved.stat()
  41. except FileNotFoundError as exc:
  42. raise LocalAccountConfigurationError(
  43. "local account file does not exist"
  44. ) from exc
  45. except OSError as exc:
  46. raise LocalAccountConfigurationError(
  47. f"cannot inspect local account file ({type(exc).__name__})"
  48. ) from exc
  49. if os.name == "posix" and file_stat.st_mode & (stat.S_IRWXG | stat.S_IRWXO):
  50. raise LocalAccountConfigurationError(
  51. "local account file permissions must deny group and other access"
  52. )
  53. try:
  54. raw_config = resolved.read_text(encoding="utf-8")
  55. except OSError as exc:
  56. raise LocalAccountConfigurationError(
  57. f"cannot read local account file ({type(exc).__name__})"
  58. ) from exc
  59. try:
  60. body = json.loads(raw_config)
  61. except json.JSONDecodeError as exc:
  62. raise LocalAccountConfigurationError(
  63. f"local account file is invalid JSON at line {exc.lineno}, "
  64. f"column {exc.colno}"
  65. ) from exc
  66. if not isinstance(body, dict):
  67. raise LocalAccountConfigurationError(
  68. "local account file must be a JSON object"
  69. )
  70. unexpected_keys = sorted(set(body) - LOCAL_ACCOUNT_KEYS)
  71. if unexpected_keys:
  72. raise LocalAccountConfigurationError(
  73. "local account file contains unsupported keys: "
  74. + ", ".join(unexpected_keys)
  75. )
  76. values: dict[str, str] = {}
  77. for key in LOCAL_ACCOUNT_KEYS:
  78. value = body.get(key, "")
  79. if not isinstance(value, str):
  80. raise LocalAccountConfigurationError(
  81. f"local account field {key} must be a string"
  82. )
  83. values[key] = value
  84. return values
  85. def load_local_account(
  86. path: str | Path,
  87. *,
  88. allowed_root: Path | None = PROJECT_ROOT,
  89. ) -> VSAccount:
  90. """Build the framework account object from a private local JSON file."""
  91. values = read_local_account_config(path, allowed_root=allowed_root)
  92. username = values["username"].strip()
  93. password = values["password"]
  94. if not username:
  95. raise LocalAccountConfigurationError(
  96. "local account username is required"
  97. )
  98. if not password:
  99. raise LocalAccountConfigurationError(
  100. "local account password is required"
  101. )
  102. return VSAccount(id=0, username=username, password=password)