| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- """Load a locally stored account without exposing its secret values."""
- from __future__ import annotations
- import json
- import os
- import stat
- from pathlib import Path
- from vs_types import VSAccount
- PROJECT_ROOT = Path(__file__).resolve().parents[1]
- LOCAL_ACCOUNT_KEYS = frozenset(
- {"username", "password", "account_upload_token"}
- )
- class LocalAccountConfigurationError(ValueError):
- """Raised when a local account file cannot be used safely."""
- def _resolved_path(
- path: str | Path,
- *,
- allowed_root: Path | None,
- ) -> Path:
- candidate = Path(path).expanduser()
- if not candidate.is_absolute():
- candidate = (allowed_root or PROJECT_ROOT) / candidate
- resolved = candidate.resolve()
- if allowed_root is not None:
- resolved_root = allowed_root.resolve()
- if resolved != resolved_root and not resolved.is_relative_to(resolved_root):
- raise LocalAccountConfigurationError(
- "local account file must stay inside the configured project root"
- )
- return resolved
- def read_local_account_config(
- path: str | Path,
- *,
- allowed_root: Path | None = PROJECT_ROOT,
- ) -> dict[str, str]:
- """Read the shared local JSON schema used by runtime and onboarding tools."""
- if not str(path).strip():
- raise LocalAccountConfigurationError("local_account_file is required")
- resolved = _resolved_path(path, allowed_root=allowed_root)
- try:
- file_stat = resolved.stat()
- except FileNotFoundError as exc:
- raise LocalAccountConfigurationError(
- "local account file does not exist"
- ) from exc
- except OSError as exc:
- raise LocalAccountConfigurationError(
- f"cannot inspect local account file ({type(exc).__name__})"
- ) from exc
- if os.name == "posix" and file_stat.st_mode & (stat.S_IRWXG | stat.S_IRWXO):
- raise LocalAccountConfigurationError(
- "local account file permissions must deny group and other access"
- )
- try:
- raw_config = resolved.read_text(encoding="utf-8")
- except OSError as exc:
- raise LocalAccountConfigurationError(
- f"cannot read local account file ({type(exc).__name__})"
- ) from exc
- try:
- body = json.loads(raw_config)
- except json.JSONDecodeError as exc:
- raise LocalAccountConfigurationError(
- f"local account file is invalid JSON at line {exc.lineno}, "
- f"column {exc.colno}"
- ) from exc
- if not isinstance(body, dict):
- raise LocalAccountConfigurationError(
- "local account file must be a JSON object"
- )
- unexpected_keys = sorted(set(body) - LOCAL_ACCOUNT_KEYS)
- if unexpected_keys:
- raise LocalAccountConfigurationError(
- "local account file contains unsupported keys: "
- + ", ".join(unexpected_keys)
- )
- values: dict[str, str] = {}
- for key in LOCAL_ACCOUNT_KEYS:
- value = body.get(key, "")
- if not isinstance(value, str):
- raise LocalAccountConfigurationError(
- f"local account field {key} must be a string"
- )
- values[key] = value
- return values
- def load_local_account(
- path: str | Path,
- *,
- allowed_root: Path | None = PROJECT_ROOT,
- ) -> VSAccount:
- """Build the framework account object from a private local JSON file."""
- values = read_local_account_config(path, allowed_root=allowed_root)
- username = values["username"].strip()
- password = values["password"]
- if not username:
- raise LocalAccountConfigurationError(
- "local account username is required"
- )
- if not password:
- raise LocalAccountConfigurationError(
- "local account password is required"
- )
- return VSAccount(id=0, username=username, password=password)
|