okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-022-refusals: environmental refusals repair or warn instead of blocking (audit items 1-4, 6, 8-10, 12-15)bcf88b738

main
12.7 KiB303 linesraw
1"""Owner-local monitor connections; store references, never credential values.
2
3This module is standard-library only so the portable monitor bundle and source
4CLI resolve the same saved connection without importing server or installer code.
5"""
6
7from __future__ import annotations
8
9import os
10try:
11    from strata_control.private_files import private_mkdir as _private_mkdir
12except ImportError:                                     # a thin bundle (monitor only) ships without strata_control
13    def _private_mkdir(path, *, parents=False, exist_ok=True):
14        path.mkdir(mode=0o700, parents=parents, exist_ok=exist_ok)
15        return path
16try:
17    from strata_control import posix_owner
18except ImportError:                                     # the same thin bundle: the old plain check
19    import stat as _stat
20
21    class posix_owner:                                  # noqa: N801
22        owner_only_wrong = staticmethod(lambda path, details: os.name == "posix" and (details.st_uid != os.getuid() or _stat.S_IMODE(details.st_mode) & 0o077))
23        owner_only_text = staticmethod(lambda text, path: text)
24try:
25    from strata_control import atomic as _atomic_mod
26except ImportError:                                     # the same thin bundle: a plain replace
27    class _atomic_mod:                                  # noqa: N801
28        replace = staticmethod(os.replace)
29import hashlib
30import json
31import os
32import re
33import stat
34import tempfile
35from contextlib import contextmanager
36from pathlib import Path
37
38from strata_cli.client import server_url, url_prefix
39
40
41NAME = re.compile(r"[a-z][a-z0-9_-]{0,63}\Z")
42ENV_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,127}\Z")
43MAX_BYTES = 4096
44DEFAULT_URL = "http://127.0.0.1:8095"
45
46
47class ConnectionError(ValueError):
48    def __init__(self, message: str, exit_code: int = 2):
49        super().__init__(message)
50        self.exit_code = exit_code
51
52
53def _name(value: str) -> str:
54    if not isinstance(value, str) or not NAME.fullmatch(value):
55        raise ConnectionError("connection name must use lowercase a-z, 0-9, _ or - and start with a letter")
56    return value
57
58
59def prefix_path(value: str) -> str:
60    try:
61        return url_prefix(value)
62    except ValueError as exc:
63        raise ConnectionError(str(exc)) from None
64
65
66def credential_name(value: str) -> str:
67    if not isinstance(value, str) or not ENV_NAME.fullmatch(value):
68        raise ConnectionError("credential reference must be an ASCII environment variable name")
69    return value
70
71
72def connection_dir(*, create: bool = False) -> Path:
73    explicit = os.environ.get("STRATA_CONNECTION_DIR")
74    if explicit:
75        directory = Path(explicit).expanduser()
76        if not directory.is_absolute():
77            raise ConnectionError("STRATA_CONNECTION_DIR must be absolute")
78    elif os.name == "nt":
79        base = os.environ.get("APPDATA")
80        directory = (Path(base) if base else Path.home() / "AppData" / "Roaming") / "Strata" / "connections"
81    else:
82        directory = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "strata" / "connections"
83    if create:
84        _private_mkdir(directory, parents=True, exist_ok=True)
85    if directory.exists() or directory.is_symlink():
86        details = directory.lstat()
87        if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and
88                (posix_owner.owner_only_wrong(directory, details))):
89            raise ConnectionError(posix_owner.owner_only_text("connection directory must be owner-only", directory), 5)
90    return directory
91
92
93def _path(name: str, *, create_dir: bool = False) -> Path:
94    return connection_dir(create=create_dir) / f"{_name(name)}.json"
95
96
97def _validate(value: object, *, expected_name: str | None = None) -> dict:
98    if not isinstance(value, dict) or set(value) != {"schema_version", "id", "url", "prefix", "credential_env"}:
99        raise ConnectionError("connection has an unsupported schema", 5)
100    if type(value["schema_version"]) is not int or value["schema_version"] != 1:
101        raise ConnectionError("connection has an unsupported schema version", 5)
102    name = _name(value["id"])
103    if expected_name is not None and name != expected_name:
104        raise ConnectionError("connection ID does not match its filename", 5)
105    try:
106        url = server_url(value["url"])
107    except (ValueError, TypeError):
108        raise ConnectionError("connection URL must be a safe server root", 5) from None
109    prefix = prefix_path(value["prefix"])
110    credential = credential_name(value["credential_env"])
111    if url != value["url"] or prefix != value["prefix"]:
112        raise ConnectionError("connection URL or prefix is not canonical", 5)
113    return {"schema_version": 1, "id": name, "url": url, "prefix": prefix,
114            "credential_env": credential}
115
116
117def _bytes(value: dict) -> bytes:
118    data = (json.dumps(value, sort_keys=True, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
119    if len(data) > MAX_BYTES:
120        raise ConnectionError("connection record exceeds 4 KiB", 5)
121    return data
122
123
124def _revision(data: bytes) -> str:
125    return hashlib.sha256(data).hexdigest()[:16]
126
127
128def load(name: str) -> tuple[dict, str]:
129    path = _path(name)
130    try:
131        details = path.lstat()
132        if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_BYTES or \
133                (os.name == "posix" and (posix_owner.owner_only_wrong(path, details))):
134            raise ConnectionError(posix_owner.owner_only_text("connection file must be a private regular file under 4 KiB", path), 5)
135        data = path.read_bytes()
136        value = json.loads(data.decode("utf-8"))
137    except FileNotFoundError:
138        raise ConnectionError(f"connection {name!r} is not saved; use strata connection create", 5) from None
139    except (OSError, UnicodeError, ValueError) as exc:
140        if isinstance(exc, ConnectionError):
141            raise
142        raise ConnectionError("connection file is unreadable", 5) from None
143    try:
144        return _validate(value, expected_name=name), _revision(data)
145    except (ConnectionError, ValueError, TypeError) as exc:
146        raise ConnectionError(f"connection file has invalid values ({type(exc).__name__})", 5) from None
147
148
149def list_connections() -> list[dict]:
150    directory = connection_dir()
151    if not directory.exists():
152        return []
153    paths = [path for path in sorted(directory.glob("*.json")) if NAME.fullmatch(path.stem)]
154    if len(paths) > 100:
155        raise ConnectionError("more than 100 connection records need inspection", 5)
156    result = []
157    for path in paths:
158        try:
159            value, revision = load(path.stem)
160            result.append({"id": value["id"], "url": value["url"], "prefix": value["prefix"],
161                           "credential_env": value["credential_env"], "revision": revision})
162        except ConnectionError as exc:
163            result.append({"id": path.stem, "error": str(exc)})
164    return result
165
166
167def _replace(path: Path, data: bytes) -> None:
168    descriptor, name = tempfile.mkstemp(prefix=f".{path.stem}-", suffix=".tmp", dir=path.parent)
169    try:
170        with os.fdopen(descriptor, "wb") as stream:
171            stream.write(data)
172            stream.flush()
173            os.fsync(stream.fileno())
174        _atomic_mod.replace(name, path)
175        if os.name == "posix":
176            try:
177                parent = os.open(path.parent, os.O_RDONLY)
178                try:
179                    os.fsync(parent)
180                finally:
181                    os.close(parent)
182            except OSError:
183                # The replacement succeeded; do not report a failed save afterward.
184                pass
185    finally:
186        if os.path.exists(name):
187            os.unlink(name)
188
189
190@contextmanager
191def _lock(name: str):
192    path = connection_dir(create=True) / f".{_name(name)}.lock"
193    descriptor = os.open(path, os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600)
194    with os.fdopen(descriptor, "r+b") as stream:
195        details = os.fstat(stream.fileno())
196        if not stat.S_ISREG(details.st_mode) or (os.name == "posix" and
197                (posix_owner.owner_only_wrong(path, details))):
198            raise ConnectionError(posix_owner.owner_only_text("connection lock must be owner-only", path), 5)
199        if os.name == "nt":
200            import msvcrt
201            stream.seek(0)
202            if not stream.read(1):
203                stream.write(b"0")
204                stream.flush()
205            stream.seek(0)
206            msvcrt.locking(stream.fileno(), msvcrt.LK_LOCK, 1)
207            try:
208                yield
209            finally:
210                stream.seek(0)
211                msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
212        else:
213            import fcntl
214            fcntl.flock(stream.fileno(), fcntl.LOCK_EX)
215            try:
216                yield
217            finally:
218                fcntl.flock(stream.fileno(), fcntl.LOCK_UN)
219
220
221def create(name: str, url: str, *, prefix: str = "",
222           credential_env: str = "STRATA_TELEMETRY_KEY") -> tuple[dict, str]:
223    name = _name(name)
224    value = _validate({"schema_version": 1, "id": name, "url": server_url(url),
225                       "prefix": prefix_path(prefix), "credential_env": credential_name(credential_env)},
226                      expected_name=name)
227    data = _bytes(value)
228    path = _path(name, create_dir=True)
229    flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
230    try:
231        descriptor = os.open(path, flags, 0o600)
232    except FileExistsError:
233        raise ConnectionError(f"connection {name!r} already exists") from None
234    try:
235        with os.fdopen(descriptor, "wb") as stream:
236            stream.write(data)
237            stream.flush()
238            os.fsync(stream.fileno())
239    except BaseException:
240        path.unlink(missing_ok=True)
241        raise
242    return value, _revision(data)
243
244
245def propose(name: str, assignment: str) -> tuple[dict, str]:
246    current, revision = load(name)
247    key, sep, raw = assignment.partition("=")
248    if not sep or key not in ("url", "prefix", "credential_env"):
249        raise ConnectionError("expected url=ROOT, prefix=/PATH or credential_env=ENV_NAME")
250    candidate = dict(current)
251    candidate[key] = (server_url(raw) if key == "url" else
252                      prefix_path(raw) if key == "prefix" else credential_name(raw))
253    return _validate(candidate, expected_name=name), revision
254
255
256def save(name: str, value: dict, *, expected_revision: str) -> tuple[dict, str]:
257    name = _name(name)
258    value = _validate(value, expected_name=name)
259    if not isinstance(expected_revision, str) or not re.fullmatch(r"[0-9a-f]{16}", expected_revision):
260        raise ConnectionError("connection revision must be 16 lowercase hex characters")
261    path = _path(name)
262    with _lock(name):
263        current, revision = load(name)
264        if revision != expected_revision:
265            raise ConnectionError("connection changed since preview; inspect it again", 6)
266        data = _bytes(value)
267        if value == current:
268            return current, revision
269        _replace(path, data)
270        return value, _revision(data)
271
272
273def resolve(*, url: str | None = None, connection: str | None = None,
274            credential_env: str | None = None, timeout: float | None = None,
275            environment: dict | None = None) -> dict:
276    env = os.environ if environment is None else environment
277    selected = connection or (None if url is not None else env.get("STRATA_CONNECTION"))
278    if url is not None and connection is not None:
279        raise ConnectionError("choose --url or --connection, not both")
280    if selected:
281        saved, revision = load(selected)
282        root, prefix = saved["url"], saved["prefix"]
283        key_ref = saved["credential_env"]
284        origins = {"url": "connection", "prefix": "connection", "credential_env": "connection"}
285    else:
286        revision = None
287        root = url if url is not None else env.get("STRATA_URL", DEFAULT_URL)
288        prefix = ""
289        key_ref = "STRATA_API_KEY"
290        origins = {"url": "flag" if url is not None else "environment" if "STRATA_URL" in env else "default",
291                   "prefix": "default", "credential_env": "default"}
292    if credential_env is not None:
293        key_ref = credential_env
294        origins["credential_env"] = "flag"
295    if timeout is not None and (type(timeout) not in (int, float) or not 0 < timeout <= 30):
296        raise ConnectionError("timeout must be greater than zero and at most 30 seconds")
297    origins["timeout_s"] = "flag" if timeout is not None else "default"
298    normalized_url, normalized_prefix = server_url(root), prefix_path(prefix)
299    return {"url": normalized_url, "prefix": normalized_prefix,
300            "base_url": normalized_url + normalized_prefix,
301            "credential_env": credential_name(key_ref), "credential_present": bool(env.get(key_ref)),
302            "timeout_s": timeout if timeout is not None else 3.0,
303            "connection": selected, "connection_revision": revision, "origins": origins}