simple-module-remote 0.0.50__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- simple_module_remote/__init__.py +12 -0
- simple_module_remote/commands/__init__.py +1 -0
- simple_module_remote/commands/api_cmd.py +157 -0
- simple_module_remote/commands/auth_cmd.py +166 -0
- simple_module_remote/commands/doctor_cmd.py +157 -0
- simple_module_remote/commands/env_cmd.py +198 -0
- simple_module_remote/commands/generated.py +50 -0
- simple_module_remote/commands/root.py +186 -0
- simple_module_remote/commands/runtime.py +263 -0
- simple_module_remote/commands/schema_cmd.py +155 -0
- simple_module_remote/commands/schema_fetch.py +129 -0
- simple_module_remote/commands/schema_source.py +181 -0
- simple_module_remote/config/__init__.py +1 -0
- simple_module_remote/config/_file_store.py +182 -0
- simple_module_remote/config/_private_dir.py +191 -0
- simple_module_remote/config/credentials.py +296 -0
- simple_module_remote/config/environments.py +186 -0
- simple_module_remote/config/paths.py +32 -0
- simple_module_remote/config/resolve.py +96 -0
- simple_module_remote/curated/__init__.py +1 -0
- simple_module_remote/generate/__init__.py +1 -0
- simple_module_remote/generate/body.py +198 -0
- simple_module_remote/generate/confirm.py +38 -0
- simple_module_remote/generate/context.py +38 -0
- simple_module_remote/generate/emit.py +278 -0
- simple_module_remote/generate/execute.py +220 -0
- simple_module_remote/generate/naming.py +69 -0
- simple_module_remote/generate/operations.py +181 -0
- simple_module_remote/generate/pagination.py +80 -0
- simple_module_remote/generate/pairs.py +22 -0
- simple_module_remote/generate/params.py +210 -0
- simple_module_remote/generate/prepare.py +134 -0
- simple_module_remote/generate/tree.py +59 -0
- simple_module_remote/generate/trust.py +42 -0
- simple_module_remote/generate/validate.py +136 -0
- simple_module_remote/http/__init__.py +1 -0
- simple_module_remote/http/client.py +292 -0
- simple_module_remote/http/errors.py +59 -0
- simple_module_remote/http/safety.py +124 -0
- simple_module_remote/output/__init__.py +1 -0
- simple_module_remote/output/reasons.py +17 -0
- simple_module_remote/output/render.py +149 -0
- simple_module_remote/output/sanitize.py +32 -0
- simple_module_remote/py.typed +0 -0
- simple_module_remote/schema/__init__.py +1 -0
- simple_module_remote/schema/cache.py +187 -0
- simple_module_remote/schema/loader.py +56 -0
- simple_module_remote-0.0.50.dist-info/METADATA +73 -0
- simple_module_remote-0.0.50.dist-info/RECORD +51 -0
- simple_module_remote-0.0.50.dist-info/WHEEL +4 -0
- simple_module_remote-0.0.50.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Fetch and vet a live schema before ``schema sync`` stores it."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
from typing import NamedTuple
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from simple_module_remote.commands.generated import operation_command
|
|
11
|
+
from simple_module_remote.commands.schema_source import MALFORMED
|
|
12
|
+
from simple_module_remote.generate.operations import invalid_cli_names
|
|
13
|
+
from simple_module_remote.generate.tree import TreeError, build_groups
|
|
14
|
+
from simple_module_remote.generate.validate import schema_problems
|
|
15
|
+
from simple_module_remote.http.client import ApiClient
|
|
16
|
+
from simple_module_remote.http.errors import ApiError
|
|
17
|
+
from simple_module_remote.output.sanitize import sanitize
|
|
18
|
+
from simple_module_remote.schema.cache import MAX_SCHEMA_BYTES, SchemaCacheError, parse_schema
|
|
19
|
+
|
|
20
|
+
__all__ = ["OPENAPI_PATH", "Fetched", "fetch_schema", "replayable_etag", "vet_schema"]
|
|
21
|
+
|
|
22
|
+
OPENAPI_PATH = "/api/_meta/openapi"
|
|
23
|
+
MAX_ETAG_CHARS = 256
|
|
24
|
+
CHUNK = 64 * 1024
|
|
25
|
+
IDENTITY = "identity"
|
|
26
|
+
HTTP_OK = 200
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Fetched(NamedTuple):
|
|
30
|
+
status: int
|
|
31
|
+
data: bytes
|
|
32
|
+
etag: str | None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _too_large() -> SchemaCacheError:
|
|
36
|
+
return SchemaCacheError(f"the schema is larger than {MAX_SCHEMA_BYTES} bytes")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def replayable_etag(value: str | None) -> str | None:
|
|
40
|
+
"""*value* when it can be stored and sent back as ``If-None-Match`` (printable ASCII)."""
|
|
41
|
+
if value is None or len(value) > MAX_ETAG_CHARS:
|
|
42
|
+
return None
|
|
43
|
+
return value if value.isascii() and value.isprintable() else None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _safe_etag(value: str | None, client: ApiClient) -> str | None:
|
|
47
|
+
tag = replayable_etag(value)
|
|
48
|
+
return tag if tag is not None and client.redact(tag) == tag else None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def fetch_schema(client: ApiClient, headers: dict[str, str]) -> Fetched:
|
|
52
|
+
"""``GET`` the schema without following redirects, reading at most the byte budget.
|
|
53
|
+
|
|
54
|
+
The body is requested uncompressed and a compressed answer is refused, so the budget
|
|
55
|
+
bounds what is held in memory. Transport failures while reading raise ``ApiError(0)``.
|
|
56
|
+
"""
|
|
57
|
+
wanted = {**headers, "Accept-Encoding": IDENTITY}
|
|
58
|
+
try:
|
|
59
|
+
with client.stream("GET", OPENAPI_PATH, headers=wanted, follow=False) as response:
|
|
60
|
+
if response.status_code != HTTP_OK:
|
|
61
|
+
return Fetched(response.status_code, b"", None)
|
|
62
|
+
encoding = response.headers.get("Content-Encoding", IDENTITY).strip().lower()
|
|
63
|
+
if encoding not in ("", IDENTITY):
|
|
64
|
+
raise SchemaCacheError("the server compressed the schema; refusing to inflate it")
|
|
65
|
+
declared = response.headers.get("Content-Length", "")
|
|
66
|
+
if declared.isascii() and declared.isdigit() and int(declared) > MAX_SCHEMA_BYTES:
|
|
67
|
+
raise _too_large()
|
|
68
|
+
chunks, size = [], 0
|
|
69
|
+
for chunk in response.iter_bytes(CHUNK): # no Content-Encoding: nothing decoded
|
|
70
|
+
size += len(chunk)
|
|
71
|
+
if size > MAX_SCHEMA_BYTES:
|
|
72
|
+
raise _too_large()
|
|
73
|
+
chunks.append(chunk)
|
|
74
|
+
etag = _safe_etag(response.headers.get("ETag"), client)
|
|
75
|
+
except (httpx.HTTPError, httpx.StreamError) as exc:
|
|
76
|
+
raise ApiError(0, message=f"reading the schema failed: {type(exc).__name__}") from None
|
|
77
|
+
return Fetched(HTTP_OK, b"".join(chunks), etag)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _strings(root: object) -> Iterator[str]:
|
|
81
|
+
"""Every key and string value in a JSON document, without recursion."""
|
|
82
|
+
stack = [root]
|
|
83
|
+
while stack:
|
|
84
|
+
node = stack.pop()
|
|
85
|
+
if isinstance(node, str):
|
|
86
|
+
yield node
|
|
87
|
+
elif isinstance(node, dict):
|
|
88
|
+
for key, value in node.items():
|
|
89
|
+
yield str(key)
|
|
90
|
+
stack.append(value)
|
|
91
|
+
elif isinstance(node, list):
|
|
92
|
+
stack.extend(node)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _forms(text: str) -> tuple[str, ...]:
|
|
96
|
+
return (text, sanitize(text), "".join(ch for ch in text if ch.isprintable()))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _carries_token(data: bytes, root: dict, client: ApiClient) -> bool:
|
|
100
|
+
texts = [data.decode("utf-8", errors="replace")]
|
|
101
|
+
texts.extend(_strings(root))
|
|
102
|
+
return any(client.redact(form) != form for text in texts for form in _forms(text))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def vet_schema(data: bytes, client: ApiClient) -> dict:
|
|
106
|
+
"""The parsed schema, or :class:`SchemaCacheError` when it must not be stored.
|
|
107
|
+
|
|
108
|
+
Refused: not OpenAPI, the credential anywhere in it (raw, decoded keys or values, or
|
|
109
|
+
after control characters are removed), an ``x-cli-name`` outside the command-name
|
|
110
|
+
alphabet, colliding command names, or a document the tree builder cannot handle.
|
|
111
|
+
"""
|
|
112
|
+
if len(data) > MAX_SCHEMA_BYTES:
|
|
113
|
+
raise _too_large()
|
|
114
|
+
root = parse_schema(data)
|
|
115
|
+
if _carries_token(data, root, client):
|
|
116
|
+
raise SchemaCacheError("the schema contains the credential; refusing to store it")
|
|
117
|
+
bad = invalid_cli_names(root)
|
|
118
|
+
if bad:
|
|
119
|
+
raise SchemaCacheError(f"invalid x-cli-name values: {', '.join(bad[:5])}")
|
|
120
|
+
problems = schema_problems(root)
|
|
121
|
+
if problems:
|
|
122
|
+
raise SchemaCacheError(sanitize(f"the schema is unusable: {'; '.join(problems)}"))
|
|
123
|
+
try:
|
|
124
|
+
build_groups(root, operation_command)
|
|
125
|
+
except TreeError as exc:
|
|
126
|
+
raise SchemaCacheError(sanitize(str(exc))) from None
|
|
127
|
+
except MALFORMED as exc:
|
|
128
|
+
raise SchemaCacheError(f"the schema is malformed ({type(exc).__name__})") from None
|
|
129
|
+
return root
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Pick the command schema for one invocation: the env's live cache or the bundled file.
|
|
2
|
+
|
|
3
|
+
The command tree is built from the schema before click parses the arguments, so the
|
|
4
|
+
root flags that choose it (``--env``, ``--schema``) are peeked from the raw arguments
|
|
5
|
+
first. The peek mirrors click's rules for the root options; click still parses and
|
|
6
|
+
validates them afterwards.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import click
|
|
16
|
+
|
|
17
|
+
from simple_module_remote.commands.runtime import SCHEMA_BUNDLED, SCHEMA_LIVE
|
|
18
|
+
from simple_module_remote.config.environments import (
|
|
19
|
+
ConfigError,
|
|
20
|
+
Environment,
|
|
21
|
+
load_config,
|
|
22
|
+
select_env,
|
|
23
|
+
)
|
|
24
|
+
from simple_module_remote.generate.operations import Operation
|
|
25
|
+
from simple_module_remote.generate.tree import TreeError, build_groups
|
|
26
|
+
from simple_module_remote.generate.trust import hint_index, trusted_hints
|
|
27
|
+
from simple_module_remote.generate.validate import schema_problems
|
|
28
|
+
from simple_module_remote.output.sanitize import sanitize
|
|
29
|
+
from simple_module_remote.schema.cache import CacheMeta, SchemaCacheError, load_cached
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"SCHEMA_SOURCES",
|
|
33
|
+
"RootFlags",
|
|
34
|
+
"SchemaChoice",
|
|
35
|
+
"choose_schema",
|
|
36
|
+
"peek_root_flags",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
SCHEMA_SOURCES = (SCHEMA_BUNDLED, SCHEMA_LIVE)
|
|
40
|
+
_ENV_OPTS = ("--env", "-e")
|
|
41
|
+
_SCHEMA_OPT = "--schema"
|
|
42
|
+
_VALUED_OPTS = (*_ENV_OPTS, "--tenant", _SCHEMA_OPT)
|
|
43
|
+
_END_OF_OPTIONS = "--"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class RootFlags:
|
|
48
|
+
env: str | None = None
|
|
49
|
+
schema: str | None = None
|
|
50
|
+
command: str | None = None # the first subcommand name, if any
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _split(token: str) -> tuple[str, str | None]:
|
|
54
|
+
"""``--opt=value`` / ``-evalue`` into ``(opt, value)``; ``(token, None)`` otherwise."""
|
|
55
|
+
if token.startswith("--") and "=" in token:
|
|
56
|
+
name, value = token.split("=", 1)
|
|
57
|
+
return name, value
|
|
58
|
+
if token.startswith("-e") and len(token) > len("-e"):
|
|
59
|
+
return "-e", token[len("-e") :]
|
|
60
|
+
return token, None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def peek_root_flags(args: Sequence[str]) -> RootFlags:
|
|
64
|
+
values: dict[str, str] = {}
|
|
65
|
+
rest = list(args)
|
|
66
|
+
while rest:
|
|
67
|
+
token = rest.pop(0)
|
|
68
|
+
if token == _END_OF_OPTIONS:
|
|
69
|
+
return RootFlags(values.get("env"), values.get("schema"), rest[0] if rest else None)
|
|
70
|
+
if not token.startswith("-") or token == "-":
|
|
71
|
+
return RootFlags(values.get("env"), values.get("schema"), token)
|
|
72
|
+
name, value = _split(token)
|
|
73
|
+
if name not in _VALUED_OPTS:
|
|
74
|
+
continue # a root flag (--version, --help) or an error click reports itself
|
|
75
|
+
if value is None:
|
|
76
|
+
if not rest:
|
|
77
|
+
break
|
|
78
|
+
value = rest.pop(0)
|
|
79
|
+
if name in _ENV_OPTS:
|
|
80
|
+
values["env"] = value
|
|
81
|
+
elif name == _SCHEMA_OPT:
|
|
82
|
+
values["schema"] = value
|
|
83
|
+
return RootFlags(values.get("env"), values.get("schema"), None)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass
|
|
87
|
+
class SchemaChoice:
|
|
88
|
+
source: str
|
|
89
|
+
path: Path
|
|
90
|
+
root: dict
|
|
91
|
+
groups: list[click.Group]
|
|
92
|
+
meta: CacheMeta | None = None
|
|
93
|
+
# Why the live schema is not in use (shown by `schema status`); empty when it is.
|
|
94
|
+
note: str = ""
|
|
95
|
+
# Set when `--schema live` was asked for but cannot be honoured.
|
|
96
|
+
error: str | None = None
|
|
97
|
+
# The environment resolved for this choice (requests reuse it); None when none is.
|
|
98
|
+
selected: tuple[Environment, bool] | None = None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
Factory = Callable[[Operation, dict], click.Command]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class MalformedSchemaError(Exception):
|
|
105
|
+
"""A cached document whose structures commands would trip over."""
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# What a malformed live document can raise while its tree is built.
|
|
109
|
+
MALFORMED = (RecursionError, TypeError, ValueError, KeyError, AttributeError, IndexError)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _trusting(factory: Factory, bundled_root: dict) -> Factory:
|
|
113
|
+
index = hint_index(bundled_root)
|
|
114
|
+
return lambda op, root: factory(trusted_hints(op, index), root)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def choose_schema(
|
|
118
|
+
*,
|
|
119
|
+
cli: str,
|
|
120
|
+
defaults_path: Path | None,
|
|
121
|
+
environ: Mapping[str, str],
|
|
122
|
+
flags: RootFlags,
|
|
123
|
+
bundled: SchemaChoice,
|
|
124
|
+
factory: Factory,
|
|
125
|
+
) -> SchemaChoice:
|
|
126
|
+
"""The live cache for the selected env when it is usable, else ``bundled``.
|
|
127
|
+
|
|
128
|
+
``--schema bundled`` always yields ``bundled``; ``--schema live`` yields the live
|
|
129
|
+
cache or ``bundled`` carrying an ``error`` the caller raises before running a
|
|
130
|
+
generated command. Live operations take their ``x-cli-safe`` from the bundled schema.
|
|
131
|
+
"""
|
|
132
|
+
try:
|
|
133
|
+
env, explicit = select_env(load_config(cli, defaults_path), flags.env, environ, cli)
|
|
134
|
+
except ConfigError:
|
|
135
|
+
return _fallback(bundled, "no environment selected", None, flags.schema, cli)
|
|
136
|
+
selected = (env, explicit)
|
|
137
|
+
if flags.schema == SCHEMA_BUNDLED:
|
|
138
|
+
return _fallback(bundled, "pinned with --schema bundled", selected, None)
|
|
139
|
+
sync = f"`{cli} --env {env.name} schema sync`"
|
|
140
|
+
try:
|
|
141
|
+
cached = load_cached(cli, env.name, env.url, env.origin)
|
|
142
|
+
if cached is None:
|
|
143
|
+
raise SchemaCacheError(f"no live schema cached for {env.name!r}")
|
|
144
|
+
problems = schema_problems(cached.root)
|
|
145
|
+
if problems:
|
|
146
|
+
raise MalformedSchemaError("; ".join(problems))
|
|
147
|
+
groups = build_groups(cached.root, _trusting(factory, bundled.root))
|
|
148
|
+
except (SchemaCacheError, TreeError) as exc:
|
|
149
|
+
return _fallback(bundled, f"{sanitize(str(exc))}: run {sync}", selected, flags.schema)
|
|
150
|
+
except (*MALFORMED, MalformedSchemaError) as exc:
|
|
151
|
+
why = str(exc) if isinstance(exc, MalformedSchemaError) else type(exc).__name__
|
|
152
|
+
note = sanitize(f"the cached schema for {env.name!r} is malformed ({why}): run {sync}")
|
|
153
|
+
note = " ".join(note.split()) # one line on stderr
|
|
154
|
+
click.echo(f"{cli}: using the bundled schema: {note}", err=True)
|
|
155
|
+
return _fallback(bundled, note, selected, flags.schema)
|
|
156
|
+
return SchemaChoice(
|
|
157
|
+
SCHEMA_LIVE, cached.path, cached.root, groups, cached.meta, selected=selected
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _fallback(
|
|
162
|
+
bundled: SchemaChoice,
|
|
163
|
+
note: str,
|
|
164
|
+
selected: tuple[Environment, bool] | None,
|
|
165
|
+
requested: str | None,
|
|
166
|
+
cli: str = "",
|
|
167
|
+
) -> SchemaChoice:
|
|
168
|
+
error = None
|
|
169
|
+
if requested == SCHEMA_LIVE:
|
|
170
|
+
error = f"--schema live: {note}"
|
|
171
|
+
if selected is None:
|
|
172
|
+
error += f" (pass --env, then run `{cli} --env <name> schema sync`)"
|
|
173
|
+
return SchemaChoice(
|
|
174
|
+
SCHEMA_BUNDLED,
|
|
175
|
+
bundled.path,
|
|
176
|
+
bundled.root,
|
|
177
|
+
bundled.groups,
|
|
178
|
+
note=note,
|
|
179
|
+
error=error,
|
|
180
|
+
selected=selected,
|
|
181
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""config area of the remote CLI engine."""
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""Fallback credential file: ``credentials.toml``, mode 0600 in a 0700 directory."""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import errno
|
|
5
|
+
import os
|
|
6
|
+
import secrets
|
|
7
|
+
import stat
|
|
8
|
+
import tomllib
|
|
9
|
+
from collections.abc import Generator
|
|
10
|
+
|
|
11
|
+
import tomli_w
|
|
12
|
+
|
|
13
|
+
from simple_module_remote.config.paths import config_dir
|
|
14
|
+
|
|
15
|
+
CREDENTIALS_FILENAME = "credentials.toml"
|
|
16
|
+
LOCK_SUFFIX = ".lock"
|
|
17
|
+
KEYRING_LOCK = "keyring.lock"
|
|
18
|
+
TOKEN_FIELD = "token"
|
|
19
|
+
ORIGIN_FIELD = "origin"
|
|
20
|
+
PIN_FIELDS = ("tenant_id", "tenant_slug") # optional: the tenant the token was pinned to
|
|
21
|
+
LOOSE_MODE_MASK = 0o077
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
_LOCK_FAILED = "cannot lock the credential store"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _lock_exclusive(fd: int) -> bool:
|
|
28
|
+
"""Block until ``fd`` holds an exclusive advisory lock; ``False`` when nothing can lock.
|
|
29
|
+
|
|
30
|
+
``fcntl`` is POSIX-only; where it is missing (Windows) updates are not serialized
|
|
31
|
+
across processes, which is the documented fallback.
|
|
32
|
+
"""
|
|
33
|
+
try:
|
|
34
|
+
import fcntl
|
|
35
|
+
except ImportError:
|
|
36
|
+
return False
|
|
37
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
38
|
+
return True
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def open_service_lock(service: str) -> int | None:
|
|
42
|
+
"""Open and exclusively lock the per-service keyring lock file.
|
|
43
|
+
|
|
44
|
+
``None`` where locking is unavailable (no ``fcntl``). Where it is available, failing to
|
|
45
|
+
take the lock raises :class:`FileStoreError`: the caller must not write unserialised.
|
|
46
|
+
"""
|
|
47
|
+
try:
|
|
48
|
+
import fcntl # noqa: F401 (only to know whether locking exists here)
|
|
49
|
+
except ImportError:
|
|
50
|
+
return None
|
|
51
|
+
directory = config_dir(service)
|
|
52
|
+
try:
|
|
53
|
+
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
54
|
+
fd = os.open(directory / KEYRING_LOCK, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
|
55
|
+
except OSError as exc:
|
|
56
|
+
raise FileStoreError(
|
|
57
|
+
f"cannot lock the credential store: {exc.__class__.__name__}"
|
|
58
|
+
) from None
|
|
59
|
+
try:
|
|
60
|
+
_lock_exclusive(fd)
|
|
61
|
+
except OSError as exc:
|
|
62
|
+
os.close(fd)
|
|
63
|
+
raise FileStoreError(
|
|
64
|
+
f"cannot lock the credential store: {exc.__class__.__name__}"
|
|
65
|
+
) from None
|
|
66
|
+
return fd
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class FileStoreError(Exception):
|
|
70
|
+
"""Unusable credentials file; the message never contains a token."""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class FileStore:
|
|
74
|
+
def __init__(self, cli: str) -> None:
|
|
75
|
+
if not (hasattr(os, "O_NOFOLLOW") and hasattr(os, "getuid")):
|
|
76
|
+
raise FileStoreError(
|
|
77
|
+
"no secure file credential store on this platform; install an OS keyring backend"
|
|
78
|
+
)
|
|
79
|
+
self._path = config_dir(cli) / CREDENTIALS_FILENAME
|
|
80
|
+
|
|
81
|
+
def _load(self) -> dict[str, dict[str, str]]:
|
|
82
|
+
try:
|
|
83
|
+
fd = os.open(self._path, os.O_RDONLY | os.O_NOFOLLOW)
|
|
84
|
+
except FileNotFoundError:
|
|
85
|
+
return {}
|
|
86
|
+
except OSError as exc:
|
|
87
|
+
if exc.errno == errno.ELOOP:
|
|
88
|
+
raise FileStoreError(f"refusing to read {self._path}: it is a symlink") from None
|
|
89
|
+
raise FileStoreError(f"cannot read {self._path}") from None
|
|
90
|
+
with os.fdopen(fd, "rb") as handle:
|
|
91
|
+
info = os.fstat(handle.fileno())
|
|
92
|
+
if not stat.S_ISREG(info.st_mode):
|
|
93
|
+
raise FileStoreError(f"refusing to read {self._path}: not a regular file")
|
|
94
|
+
if info.st_uid != os.getuid():
|
|
95
|
+
raise FileStoreError(f"refusing to read {self._path}: owned by another user")
|
|
96
|
+
if info.st_mode & LOOSE_MODE_MASK:
|
|
97
|
+
raise FileStoreError(
|
|
98
|
+
f"refusing to read {self._path}: it is accessible to other users "
|
|
99
|
+
f"(run `chmod 600 {self._path}`)"
|
|
100
|
+
)
|
|
101
|
+
try:
|
|
102
|
+
raw = tomllib.loads(handle.read().decode("utf-8"))
|
|
103
|
+
except (tomllib.TOMLDecodeError, OSError, UnicodeDecodeError):
|
|
104
|
+
raise FileStoreError(
|
|
105
|
+
f"cannot read {self._path}: file is corrupt; delete it and log in again"
|
|
106
|
+
) from None
|
|
107
|
+
out: dict[str, dict[str, str]] = {}
|
|
108
|
+
for key, table in raw.items():
|
|
109
|
+
if isinstance(table, dict) and all(
|
|
110
|
+
isinstance(table.get(f), str) for f in (TOKEN_FIELD, ORIGIN_FIELD)
|
|
111
|
+
):
|
|
112
|
+
out[key] = {
|
|
113
|
+
f: table[f]
|
|
114
|
+
for f in (TOKEN_FIELD, ORIGIN_FIELD, *PIN_FIELDS)
|
|
115
|
+
if isinstance(table.get(f), str)
|
|
116
|
+
}
|
|
117
|
+
return out
|
|
118
|
+
|
|
119
|
+
def _secure_dir(self) -> None:
|
|
120
|
+
directory = self._path.parent
|
|
121
|
+
try:
|
|
122
|
+
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
123
|
+
info = directory.stat()
|
|
124
|
+
if info.st_uid == os.getuid() and info.st_mode & LOOSE_MODE_MASK:
|
|
125
|
+
directory.chmod(0o700)
|
|
126
|
+
info = directory.stat()
|
|
127
|
+
except OSError as exc:
|
|
128
|
+
raise FileStoreError(f"cannot prepare {directory}: {exc.__class__.__name__}") from None
|
|
129
|
+
if info.st_mode & LOOSE_MODE_MASK:
|
|
130
|
+
raise FileStoreError(f"refusing to write in {directory}: it is not private")
|
|
131
|
+
|
|
132
|
+
def _write(self, data: dict[str, dict[str, str]]) -> None:
|
|
133
|
+
self._secure_dir()
|
|
134
|
+
tmp = self._path.with_name(f"{self._path.name}.{os.getpid()}.{secrets.token_hex(4)}.tmp")
|
|
135
|
+
try:
|
|
136
|
+
fd = os.open(tmp, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
137
|
+
with os.fdopen(fd, "wb") as handle:
|
|
138
|
+
handle.write(tomli_w.dumps(data).encode("utf-8"))
|
|
139
|
+
handle.flush()
|
|
140
|
+
os.fsync(handle.fileno())
|
|
141
|
+
tmp.replace(self._path)
|
|
142
|
+
except OSError as exc:
|
|
143
|
+
raise FileStoreError(f"cannot write {self._path}: {exc.__class__.__name__}") from None
|
|
144
|
+
finally:
|
|
145
|
+
with contextlib.suppress(OSError):
|
|
146
|
+
tmp.unlink(missing_ok=True)
|
|
147
|
+
|
|
148
|
+
def get(self, key: str) -> dict[str, str] | None:
|
|
149
|
+
return self._load().get(key)
|
|
150
|
+
|
|
151
|
+
@contextlib.contextmanager
|
|
152
|
+
def _locked(self) -> Generator[None]:
|
|
153
|
+
"""Serialize read-modify-write cycles across processes on a sibling lock file."""
|
|
154
|
+
self._secure_dir()
|
|
155
|
+
lock_path = self._path.with_name(self._path.name + LOCK_SUFFIX)
|
|
156
|
+
try:
|
|
157
|
+
fd = os.open(lock_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
|
158
|
+
_lock_exclusive(fd)
|
|
159
|
+
except OSError as exc:
|
|
160
|
+
raise FileStoreError(f"cannot lock {lock_path}: {exc.__class__.__name__}") from None
|
|
161
|
+
try:
|
|
162
|
+
yield
|
|
163
|
+
finally:
|
|
164
|
+
os.close(fd) # closing the descriptor releases the lock
|
|
165
|
+
|
|
166
|
+
def put(self, key: str, token: str, origin: str, pins: dict[str, str] | None = None) -> None:
|
|
167
|
+
with self._locked():
|
|
168
|
+
data = self._load()
|
|
169
|
+
data[key] = {TOKEN_FIELD: token, ORIGIN_FIELD: origin, **(pins or {})}
|
|
170
|
+
self._write(data)
|
|
171
|
+
|
|
172
|
+
def delete(self, key: str) -> bool:
|
|
173
|
+
with self._locked():
|
|
174
|
+
data = self._load()
|
|
175
|
+
if key not in data:
|
|
176
|
+
return False
|
|
177
|
+
del data[key]
|
|
178
|
+
self._write(data)
|
|
179
|
+
return True
|
|
180
|
+
|
|
181
|
+
def keys(self) -> list[str]:
|
|
182
|
+
return list(self._load())
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Owner-only directories handled by descriptor (the live schema cache).
|
|
2
|
+
|
|
3
|
+
Each directory is opened with ``O_DIRECTORY | O_NOFOLLOW`` and checked with ``fstat``
|
|
4
|
+
(owned by this user, mode 0700, tightened when we own a looser one). Every read, temp
|
|
5
|
+
file, rename and lock then goes through that descriptor (``dir_fd``), so swapping a
|
|
6
|
+
path component for a symlink after the check cannot redirect them. Where the platform
|
|
7
|
+
lacks ``dir_fd`` support (Windows), :class:`PrivateDirError` is raised and callers treat
|
|
8
|
+
the store as unavailable.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import contextlib
|
|
14
|
+
import errno
|
|
15
|
+
import os
|
|
16
|
+
import secrets
|
|
17
|
+
import stat
|
|
18
|
+
from collections.abc import Generator
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from types import TracebackType
|
|
21
|
+
|
|
22
|
+
from simple_module_remote.config._file_store import LOOSE_MODE_MASK, _lock_exclusive
|
|
23
|
+
|
|
24
|
+
__all__ = ["PrivateDir", "PrivateDirError", "private_dirs_supported"]
|
|
25
|
+
|
|
26
|
+
_DIR_FLAGS = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
|
|
27
|
+
# O_NONBLOCK: opening a FIFO must not wait for a writer; regular files ignore it.
|
|
28
|
+
_READ_FLAGS = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
|
|
29
|
+
_NEW_FLAGS = os.O_CREAT | os.O_EXCL | os.O_WRONLY | getattr(os, "O_NOFOLLOW", 0)
|
|
30
|
+
_LOCK_FLAGS = os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class PrivateDirError(Exception):
|
|
34
|
+
"""An unusable private directory or file; the message is safe to show."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def private_dirs_supported() -> bool:
|
|
38
|
+
needed = (os.open, os.mkdir, os.rename, os.unlink, os.stat)
|
|
39
|
+
return (
|
|
40
|
+
hasattr(os, "O_NOFOLLOW")
|
|
41
|
+
and hasattr(os, "O_DIRECTORY")
|
|
42
|
+
and hasattr(os, "getuid")
|
|
43
|
+
and all(fn in os.supports_dir_fd for fn in needed)
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _check_dir(fd: int, shown: Path) -> None:
|
|
48
|
+
info = os.fstat(fd)
|
|
49
|
+
if not stat.S_ISDIR(info.st_mode):
|
|
50
|
+
raise PrivateDirError(f"refusing to use {shown}: not a directory")
|
|
51
|
+
if info.st_uid != os.getuid():
|
|
52
|
+
raise PrivateDirError(f"refusing to use {shown}: owned by another user")
|
|
53
|
+
if info.st_mode & LOOSE_MODE_MASK:
|
|
54
|
+
os.fchmod(fd, 0o700)
|
|
55
|
+
if os.fstat(fd).st_mode & LOOSE_MODE_MASK:
|
|
56
|
+
raise PrivateDirError(f"refusing to use {shown}: it is not private")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _open_dir(name: str | Path, shown: Path, parent: int | None, create: bool) -> int | None:
|
|
60
|
+
"""Open (creating if asked) one directory level; ``None`` when absent and not created."""
|
|
61
|
+
if create:
|
|
62
|
+
with contextlib.suppress(FileExistsError):
|
|
63
|
+
os.mkdir(name, 0o700, dir_fd=parent)
|
|
64
|
+
try:
|
|
65
|
+
fd = os.open(name, _DIR_FLAGS, dir_fd=parent)
|
|
66
|
+
except FileNotFoundError:
|
|
67
|
+
return None
|
|
68
|
+
except OSError as exc:
|
|
69
|
+
if exc.errno in (errno.ELOOP, errno.ENOTDIR):
|
|
70
|
+
raise PrivateDirError(f"refusing to use {shown}: not a plain directory") from None
|
|
71
|
+
raise PrivateDirError(f"cannot open {shown}: {exc.__class__.__name__}") from None
|
|
72
|
+
try:
|
|
73
|
+
_check_dir(fd, shown)
|
|
74
|
+
except BaseException:
|
|
75
|
+
os.close(fd)
|
|
76
|
+
raise
|
|
77
|
+
return fd
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class PrivateDir:
|
|
81
|
+
"""``<base>/<name>`` opened by descriptor; use as a context manager."""
|
|
82
|
+
|
|
83
|
+
def __init__(self, base: Path, name: str, *, create: bool) -> None:
|
|
84
|
+
if not private_dirs_supported():
|
|
85
|
+
raise PrivateDirError("no secure file store on this platform")
|
|
86
|
+
self.path = base / name
|
|
87
|
+
self._fds: list[int] = []
|
|
88
|
+
try:
|
|
89
|
+
if create:
|
|
90
|
+
base.parent.mkdir(parents=True, exist_ok=True)
|
|
91
|
+
outer = _open_dir(base, base, None, create)
|
|
92
|
+
if outer is None:
|
|
93
|
+
self.fd = None
|
|
94
|
+
return
|
|
95
|
+
self._fds.append(outer)
|
|
96
|
+
inner = _open_dir(name, self.path, outer, create)
|
|
97
|
+
if inner is not None:
|
|
98
|
+
self._fds.append(inner)
|
|
99
|
+
self.fd = inner
|
|
100
|
+
except OSError as exc:
|
|
101
|
+
self.close()
|
|
102
|
+
raise PrivateDirError(f"cannot prepare {self.path}: {exc.__class__.__name__}") from None
|
|
103
|
+
except BaseException:
|
|
104
|
+
self.close()
|
|
105
|
+
raise
|
|
106
|
+
|
|
107
|
+
def __enter__(self) -> PrivateDir:
|
|
108
|
+
return self
|
|
109
|
+
|
|
110
|
+
def __exit__(
|
|
111
|
+
self,
|
|
112
|
+
exc_type: type[BaseException] | None,
|
|
113
|
+
exc: BaseException | None,
|
|
114
|
+
tb: TracebackType | None,
|
|
115
|
+
) -> None:
|
|
116
|
+
self.close()
|
|
117
|
+
|
|
118
|
+
def close(self) -> None:
|
|
119
|
+
while self._fds:
|
|
120
|
+
os.close(self._fds.pop())
|
|
121
|
+
|
|
122
|
+
def read(self, name: str, max_bytes: int) -> bytes | None:
|
|
123
|
+
"""An owner-only regular file's bytes (at most ``max_bytes``); ``None`` when absent."""
|
|
124
|
+
if self.fd is None:
|
|
125
|
+
return None
|
|
126
|
+
shown = self.path / name
|
|
127
|
+
try:
|
|
128
|
+
fd = os.open(name, _READ_FLAGS, dir_fd=self.fd)
|
|
129
|
+
except FileNotFoundError:
|
|
130
|
+
return None
|
|
131
|
+
except OSError as exc:
|
|
132
|
+
if exc.errno == errno.ELOOP:
|
|
133
|
+
raise PrivateDirError(f"refusing to read {shown}: it is a symlink") from None
|
|
134
|
+
raise PrivateDirError(f"cannot read {shown}") from None
|
|
135
|
+
with os.fdopen(fd, "rb") as handle:
|
|
136
|
+
info = os.fstat(handle.fileno())
|
|
137
|
+
if not stat.S_ISREG(info.st_mode):
|
|
138
|
+
raise PrivateDirError(f"refusing to read {shown}: not a regular file")
|
|
139
|
+
if info.st_uid != os.getuid():
|
|
140
|
+
raise PrivateDirError(f"refusing to read {shown}: owned by another user")
|
|
141
|
+
if info.st_mode & LOOSE_MODE_MASK:
|
|
142
|
+
raise PrivateDirError(f"refusing to read {shown}: it is accessible to other users")
|
|
143
|
+
if info.st_size > max_bytes:
|
|
144
|
+
raise PrivateDirError(f"refusing to read {shown}: larger than {max_bytes} bytes")
|
|
145
|
+
try:
|
|
146
|
+
data = handle.read(max_bytes + 1)
|
|
147
|
+
except OSError:
|
|
148
|
+
raise PrivateDirError(f"cannot read {shown}") from None
|
|
149
|
+
if len(data) > max_bytes:
|
|
150
|
+
raise PrivateDirError(f"refusing to read {shown}: larger than {max_bytes} bytes")
|
|
151
|
+
return data
|
|
152
|
+
|
|
153
|
+
def write(self, name: str, data: bytes) -> None:
|
|
154
|
+
"""Atomically replace ``name`` with ``data`` (mode 0600) inside this directory."""
|
|
155
|
+
if self.fd is None:
|
|
156
|
+
raise PrivateDirError(f"{self.path} is not open for writing")
|
|
157
|
+
tmp = f".{name}.{os.getpid()}.{secrets.token_hex(4)}.tmp"
|
|
158
|
+
try:
|
|
159
|
+
fd = os.open(tmp, _NEW_FLAGS, 0o600, dir_fd=self.fd)
|
|
160
|
+
with os.fdopen(fd, "wb") as handle:
|
|
161
|
+
handle.write(data)
|
|
162
|
+
handle.flush()
|
|
163
|
+
os.fsync(handle.fileno())
|
|
164
|
+
os.replace(tmp, name, src_dir_fd=self.fd, dst_dir_fd=self.fd)
|
|
165
|
+
except OSError as exc:
|
|
166
|
+
raise PrivateDirError(
|
|
167
|
+
f"cannot write {self.path / name}: {exc.__class__.__name__}"
|
|
168
|
+
) from None
|
|
169
|
+
finally:
|
|
170
|
+
with contextlib.suppress(OSError):
|
|
171
|
+
os.unlink(tmp, dir_fd=self.fd)
|
|
172
|
+
|
|
173
|
+
@contextlib.contextmanager
|
|
174
|
+
def locked(self, name: str) -> Generator[None]:
|
|
175
|
+
"""Hold an exclusive advisory lock on ``name`` in this directory."""
|
|
176
|
+
if self.fd is None:
|
|
177
|
+
raise PrivateDirError(f"{self.path} is not open for locking")
|
|
178
|
+
try:
|
|
179
|
+
fd = os.open(name, _LOCK_FLAGS, 0o600, dir_fd=self.fd)
|
|
180
|
+
except OSError as exc:
|
|
181
|
+
raise PrivateDirError(
|
|
182
|
+
f"cannot lock {self.path / name}: {exc.__class__.__name__}"
|
|
183
|
+
) from None
|
|
184
|
+
try:
|
|
185
|
+
try:
|
|
186
|
+
_lock_exclusive(fd)
|
|
187
|
+
except OSError as exc:
|
|
188
|
+
raise PrivateDirError(f"cannot lock {self.path / name}") from exc
|
|
189
|
+
yield
|
|
190
|
+
finally:
|
|
191
|
+
os.close(fd)
|