ms-cli 0.2.0__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.
- ad_cli/__init__.py +6 -0
- ad_cli/__main__.py +6 -0
- ad_cli/auth.py +351 -0
- ad_cli/cli.py +278 -0
- ad_cli/discovery.py +243 -0
- ad_cli/dynamic.py +816 -0
- ad_cli/errors.py +45 -0
- ad_cli/http.py +424 -0
- ad_cli/invoke.py +652 -0
- ad_cli/main.py +703 -0
- cann_cli/__init__.py +6 -0
- cann_cli/__main__.py +6 -0
- cann_cli/auth.py +351 -0
- cann_cli/cli.py +278 -0
- cann_cli/discovery.py +243 -0
- cann_cli/dynamic.py +816 -0
- cann_cli/errors.py +45 -0
- cann_cli/http.py +424 -0
- cann_cli/invoke.py +652 -0
- cann_cli/main.py +703 -0
- ms_cli/__init__.py +6 -0
- ms_cli/__main__.py +6 -0
- ms_cli/auth.py +351 -0
- ms_cli/cli.py +278 -0
- ms_cli/discovery.py +243 -0
- ms_cli/dynamic.py +816 -0
- ms_cli/errors.py +45 -0
- ms_cli/http.py +424 -0
- ms_cli/invoke.py +652 -0
- ms_cli/main.py +703 -0
- ms_cli-0.2.0.dist-info/METADATA +444 -0
- ms_cli-0.2.0.dist-info/RECORD +67 -0
- ms_cli-0.2.0.dist-info/WHEEL +5 -0
- ms_cli-0.2.0.dist-info/entry_points.txt +2 -0
- ms_cli-0.2.0.dist-info/licenses/LICENSE +18 -0
- ms_cli-0.2.0.dist-info/top_level.txt +5 -0
- oed_cli/__init__.py +6 -0
- oed_cli/__main__.py +6 -0
- oed_cli/auth.py +1629 -0
- oed_cli/cli.py +297 -0
- oed_cli/defaults.toml +44 -0
- oed_cli/discovery.py +243 -0
- oed_cli/dynamic.py +816 -0
- oed_cli/errors.py +45 -0
- oed_cli/http.py +423 -0
- oed_cli/invoke.py +651 -0
- oed_cli/main.py +782 -0
- ogd_cli/__init__.py +6 -0
- ogd_cli/__main__.py +6 -0
- ogd_cli/auth.py +351 -0
- ogd_cli/cli.py +278 -0
- ogd_cli/discovery.py +243 -0
- ogd_cli/dynamic.py +816 -0
- ogd_cli/errors.py +45 -0
- ogd_cli/http.py +424 -0
- ogd_cli/invoke.py +652 -0
- ogd_cli/main.py +703 -0
- oud_cli/__init__.py +6 -0
- oud_cli/__main__.py +6 -0
- oud_cli/auth.py +351 -0
- oud_cli/cli.py +278 -0
- oud_cli/discovery.py +243 -0
- oud_cli/dynamic.py +816 -0
- oud_cli/errors.py +45 -0
- oud_cli/http.py +424 -0
- oud_cli/invoke.py +652 -0
- oud_cli/main.py +703 -0
oud_cli/discovery.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Discovery feed retrieval, parsing and local caching.
|
|
2
|
+
|
|
3
|
+
Reads ``https://api-gateway.osinfra.cn/discovery/apis`` (per ``context/discoverAPI.md``)
|
|
4
|
+
and caches the parsed feed under ``~/.cache/oud-cli/discovery.json``. A fresh
|
|
5
|
+
fetch happens only when the cache is older than :data:`CACHE_TTL_SECONDS`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import platform
|
|
14
|
+
import time
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from .errors import NotFoundError
|
|
20
|
+
from .http import apis_url, get_json
|
|
21
|
+
|
|
22
|
+
CACHE_TTL_SECONDS = 600 # 10 minutes
|
|
23
|
+
# Tolerance for clock skew when judging cache freshness. A cached
|
|
24
|
+
# ``__oud_fetched_at`` strictly newer than ``now + _CLOCK_SKEW_SECONDS`` is
|
|
25
|
+
# treated as a poisoned cache (issue #22): an attacker who can write the
|
|
26
|
+
# cache file can set a future timestamp so ``now - fetched_at`` is always
|
|
27
|
+
# negative and the TTL check never expires the entry. Rejecting future
|
|
28
|
+
# timestamps closes the "never-expires" bypass. 300s absorbs legitimate NTP
|
|
29
|
+
# drift between the writing process and a later reader. NOTE: kept in sync
|
|
30
|
+
# with ``dynamic._CLOCK_SKEW_SECONDS`` — both must use the same value.
|
|
31
|
+
_CLOCK_SKEW_SECONDS = 300
|
|
32
|
+
DEFAULT_COMMUNITY = "openubmc"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class ServiceMeta:
|
|
37
|
+
name: str
|
|
38
|
+
service_name: str
|
|
39
|
+
community: str
|
|
40
|
+
title: str
|
|
41
|
+
version: str
|
|
42
|
+
description: str
|
|
43
|
+
base_url: str
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def from_raw(cls, raw: dict[str, Any]) -> ServiceMeta:
|
|
47
|
+
return cls(
|
|
48
|
+
name=raw["name"],
|
|
49
|
+
service_name=raw["service_name"],
|
|
50
|
+
community=raw["community"],
|
|
51
|
+
title=raw.get("title", ""),
|
|
52
|
+
version=raw.get("version", ""),
|
|
53
|
+
description=raw.get("description", ""),
|
|
54
|
+
base_url=raw.get("base_url", ""),
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class DiscoveryFeed:
|
|
60
|
+
fetched_at: float
|
|
61
|
+
raw: dict[str, Any]
|
|
62
|
+
services: list[ServiceMeta] = field(default_factory=list)
|
|
63
|
+
|
|
64
|
+
def for_community(self, community: str) -> list[ServiceMeta]:
|
|
65
|
+
return [s for s in self.services if s.community == community]
|
|
66
|
+
|
|
67
|
+
def find_service(self, community: str, service_name: str) -> ServiceMeta:
|
|
68
|
+
for s in self.services:
|
|
69
|
+
if s.community == community and s.service_name == service_name:
|
|
70
|
+
return s
|
|
71
|
+
raise NotFoundError(
|
|
72
|
+
f"service '{service_name}' not found in community '{community}'",
|
|
73
|
+
kind="service_not_found",
|
|
74
|
+
hint="Run `oud services` to see the registered services.",
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _cache_dir() -> Path:
|
|
79
|
+
override = os.environ.get("OUD_CACHE_DIR")
|
|
80
|
+
if override:
|
|
81
|
+
return Path(override).expanduser()
|
|
82
|
+
if platform.system() == "Windows":
|
|
83
|
+
base = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local")
|
|
84
|
+
return base / "oud-cli" / "cache"
|
|
85
|
+
xdg = os.environ.get("XDG_CACHE_HOME")
|
|
86
|
+
base = Path(xdg) if xdg else Path.home() / ".cache"
|
|
87
|
+
return base / "oud-cli"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _cache_path() -> Path:
|
|
91
|
+
return _cache_dir() / "discovery.json"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def auth_token_path() -> Path:
|
|
95
|
+
"""Path to the auth.json file (sibling of ``discovery.json``).
|
|
96
|
+
|
|
97
|
+
Lives under the same XDG / Windows-LOCALAPPDATA cache directory as the
|
|
98
|
+
discovery feed, so a single ``OUD_CACHE_DIR`` override covers both.
|
|
99
|
+
"""
|
|
100
|
+
return _cache_dir() / "auth.json"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def ag_token_path(service: str = "ag") -> Path:
|
|
104
|
+
"""Path to an AtomGit (``ag``) PAT plaintext-fallback file.
|
|
105
|
+
|
|
106
|
+
Lives under a ``tokens/`` subdir of the cache dir so ``oud cache clear``
|
|
107
|
+
(which only unlinks ``discovery.json``) can never wipe credentials. The
|
|
108
|
+
real secret prefers the OS keystore via :class:`oud_cli.auth._SecureStore`;
|
|
109
|
+
this file is only the 0600 fallback when keyring is unreachable.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
return _cache_dir() / "tokens" / f"{service}.json"
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _read_cache(path: Path) -> DiscoveryFeed | None:
|
|
116
|
+
if not path.is_file():
|
|
117
|
+
return None
|
|
118
|
+
try:
|
|
119
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
120
|
+
except (OSError, json.JSONDecodeError):
|
|
121
|
+
return None
|
|
122
|
+
return _materialize(raw)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _materialize(raw: dict[str, Any]) -> DiscoveryFeed | None:
|
|
126
|
+
"""Build a :class:`DiscoveryFeed` from a raw cache dict.
|
|
127
|
+
|
|
128
|
+
Returns ``None`` (→ caller refetches) when the cache is poisoned: a
|
|
129
|
+
``__oud_fetched_at`` timestamp in the future beyond :data:`_CLOCK_SKEW_SECONDS`
|
|
130
|
+
would otherwise make the TTL check never expire the entry (issue #22).
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
fetched_at = float(raw.get("__oud_fetched_at", 0))
|
|
134
|
+
if fetched_at > time.time() + _CLOCK_SKEW_SECONDS:
|
|
135
|
+
return None
|
|
136
|
+
services = [ServiceMeta.from_raw(s) for s in raw.get("services", [])]
|
|
137
|
+
return DiscoveryFeed(fetched_at=fetched_at, raw=raw, services=services)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _atomic_write_json(path: Path, data: dict[str, Any], *, mode: int | None = None) -> None:
|
|
141
|
+
"""Write ``data`` as JSON to ``path`` atomically (tmp + replace).
|
|
142
|
+
|
|
143
|
+
Cache files are public data (discovery feed / OpenAPI specs), so by
|
|
144
|
+
default no restrictive perms are forced — only the torn-write race is
|
|
145
|
+
closed. Used by both the discovery feed cache and the per-service spec
|
|
146
|
+
cache (see :mod:`oud_cli.dynamic`) so a crash mid-write never leaves a
|
|
147
|
+
half-written file that a later read would parse as corrupt.
|
|
148
|
+
|
|
149
|
+
When ``mode`` is given (e.g. ``0o600``) the temp file is chmod'd before
|
|
150
|
+
the atomic replace, so the final file honors it. This is used for the
|
|
151
|
+
spec cache and the integrity ledger: a non-owner must NOT be able to
|
|
152
|
+
write a forged ``repr_digest`` (that would let a tampered spec pass local
|
|
153
|
+
verification). The brief pre-chmod window only exposes a public hash, so
|
|
154
|
+
read-leakage is harmless; what matters is blocking non-owner writes.
|
|
155
|
+
"""
|
|
156
|
+
|
|
157
|
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
|
158
|
+
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
159
|
+
if mode is not None:
|
|
160
|
+
with contextlib.suppress(OSError):
|
|
161
|
+
os.chmod(tmp, mode)
|
|
162
|
+
try:
|
|
163
|
+
tmp.replace(path)
|
|
164
|
+
except OSError:
|
|
165
|
+
# Best-effort: a failed replace (e.g. cross-device tmp) leaves the
|
|
166
|
+
# .tmp behind but never corrupts the existing cache. Callers treat
|
|
167
|
+
# cache write failures as non-fatal.
|
|
168
|
+
with contextlib.suppress(OSError):
|
|
169
|
+
tmp.unlink(missing_ok=True)
|
|
170
|
+
raise
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _write_cache(path: Path, feed: DiscoveryFeed) -> None:
|
|
174
|
+
payload = {
|
|
175
|
+
"__oud_fetched_at": feed.fetched_at,
|
|
176
|
+
"services": [s.__dict__ for s in feed.services],
|
|
177
|
+
}
|
|
178
|
+
try:
|
|
179
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
180
|
+
_atomic_write_json(path, payload)
|
|
181
|
+
except OSError:
|
|
182
|
+
# Cache is best-effort; failures here are not fatal.
|
|
183
|
+
pass
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _fetch_remote(community: str | None) -> DiscoveryFeed:
|
|
187
|
+
"""Hit the gateway. If ``community`` is provided, request that variant so the
|
|
188
|
+
payload layout matches the per-community view; otherwise request the global
|
|
189
|
+
payload which is keyed by community."""
|
|
190
|
+
|
|
191
|
+
if community:
|
|
192
|
+
data = get_json(apis_url(), params={"community": community})
|
|
193
|
+
services: list[ServiceMeta] = []
|
|
194
|
+
if isinstance(data, list):
|
|
195
|
+
services = [ServiceMeta.from_raw(s) for s in data]
|
|
196
|
+
else:
|
|
197
|
+
data = get_json(apis_url())
|
|
198
|
+
services = []
|
|
199
|
+
communities = data.get("communities", {}) if isinstance(data, dict) else {}
|
|
200
|
+
if isinstance(communities, dict):
|
|
201
|
+
for arr in communities.values():
|
|
202
|
+
if isinstance(arr, list):
|
|
203
|
+
services.extend(ServiceMeta.from_raw(s) for s in arr)
|
|
204
|
+
|
|
205
|
+
raw_payload = data if isinstance(data, dict) else {"services": data}
|
|
206
|
+
return DiscoveryFeed(
|
|
207
|
+
fetched_at=time.time(), raw=raw_payload, services=services
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def fetch_discovery(*, community: str | None = None, force_refresh: bool = False) -> DiscoveryFeed:
|
|
212
|
+
"""Return the discovery feed, using cache when fresh."""
|
|
213
|
+
|
|
214
|
+
cache_file = _cache_path()
|
|
215
|
+
cached = None if force_refresh else _read_cache(cache_file)
|
|
216
|
+
if cached is not None and (time.time() - cached.fetched_at) < CACHE_TTL_SECONDS:
|
|
217
|
+
return cached
|
|
218
|
+
|
|
219
|
+
feed = _fetch_remote(community)
|
|
220
|
+
_write_cache(cache_file, feed)
|
|
221
|
+
return feed
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def fetch_spec(service: ServiceMeta) -> dict[str, Any]:
|
|
225
|
+
"""Return the OpenAPI 3.x spec for one service, parsed JSON.
|
|
226
|
+
|
|
227
|
+
Delegates to :func:`oud_cli.dynamic.fetch_service_spec`, which adds a
|
|
228
|
+
per-service file cache, ``If-None-Match``/304 negotiation, and
|
|
229
|
+
``Repr-Digest`` verification (plus the local-cache integrity guards).
|
|
230
|
+
Previously this entry point fetched fresh on every call and discarded the
|
|
231
|
+
returned ETag, so 304 never fired and the spec body was re-downloaded each
|
|
232
|
+
time — the cached fetcher fixes that without changing this function's
|
|
233
|
+
contract (parsed JSON, or raises :class:`NotFoundError`). The import is
|
|
234
|
+
deferred to avoid a discovery ↔ dynamic import cycle.
|
|
235
|
+
"""
|
|
236
|
+
|
|
237
|
+
from .dynamic import fetch_service_spec # deferred: avoid import cycle
|
|
238
|
+
|
|
239
|
+
return fetch_service_spec(service)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def current_community() -> str:
|
|
243
|
+
return os.environ.get("OUD_COMMUNITY", DEFAULT_COMMUNITY)
|