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.
Files changed (67) hide show
  1. ad_cli/__init__.py +6 -0
  2. ad_cli/__main__.py +6 -0
  3. ad_cli/auth.py +351 -0
  4. ad_cli/cli.py +278 -0
  5. ad_cli/discovery.py +243 -0
  6. ad_cli/dynamic.py +816 -0
  7. ad_cli/errors.py +45 -0
  8. ad_cli/http.py +424 -0
  9. ad_cli/invoke.py +652 -0
  10. ad_cli/main.py +703 -0
  11. cann_cli/__init__.py +6 -0
  12. cann_cli/__main__.py +6 -0
  13. cann_cli/auth.py +351 -0
  14. cann_cli/cli.py +278 -0
  15. cann_cli/discovery.py +243 -0
  16. cann_cli/dynamic.py +816 -0
  17. cann_cli/errors.py +45 -0
  18. cann_cli/http.py +424 -0
  19. cann_cli/invoke.py +652 -0
  20. cann_cli/main.py +703 -0
  21. ms_cli/__init__.py +6 -0
  22. ms_cli/__main__.py +6 -0
  23. ms_cli/auth.py +351 -0
  24. ms_cli/cli.py +278 -0
  25. ms_cli/discovery.py +243 -0
  26. ms_cli/dynamic.py +816 -0
  27. ms_cli/errors.py +45 -0
  28. ms_cli/http.py +424 -0
  29. ms_cli/invoke.py +652 -0
  30. ms_cli/main.py +703 -0
  31. ms_cli-0.2.0.dist-info/METADATA +444 -0
  32. ms_cli-0.2.0.dist-info/RECORD +67 -0
  33. ms_cli-0.2.0.dist-info/WHEEL +5 -0
  34. ms_cli-0.2.0.dist-info/entry_points.txt +2 -0
  35. ms_cli-0.2.0.dist-info/licenses/LICENSE +18 -0
  36. ms_cli-0.2.0.dist-info/top_level.txt +5 -0
  37. oed_cli/__init__.py +6 -0
  38. oed_cli/__main__.py +6 -0
  39. oed_cli/auth.py +1629 -0
  40. oed_cli/cli.py +297 -0
  41. oed_cli/defaults.toml +44 -0
  42. oed_cli/discovery.py +243 -0
  43. oed_cli/dynamic.py +816 -0
  44. oed_cli/errors.py +45 -0
  45. oed_cli/http.py +423 -0
  46. oed_cli/invoke.py +651 -0
  47. oed_cli/main.py +782 -0
  48. ogd_cli/__init__.py +6 -0
  49. ogd_cli/__main__.py +6 -0
  50. ogd_cli/auth.py +351 -0
  51. ogd_cli/cli.py +278 -0
  52. ogd_cli/discovery.py +243 -0
  53. ogd_cli/dynamic.py +816 -0
  54. ogd_cli/errors.py +45 -0
  55. ogd_cli/http.py +424 -0
  56. ogd_cli/invoke.py +652 -0
  57. ogd_cli/main.py +703 -0
  58. oud_cli/__init__.py +6 -0
  59. oud_cli/__main__.py +6 -0
  60. oud_cli/auth.py +351 -0
  61. oud_cli/cli.py +278 -0
  62. oud_cli/discovery.py +243 -0
  63. oud_cli/dynamic.py +816 -0
  64. oud_cli/errors.py +45 -0
  65. oud_cli/http.py +424 -0
  66. oud_cli/invoke.py +652 -0
  67. oud_cli/main.py +703 -0
oed_cli/dynamic.py ADDED
@@ -0,0 +1,816 @@
1
+ """Dynamic OpenAPI → operation-table mapping.
2
+
3
+ Each operation in an openEuler-gateway OpenAPI doc lives under
4
+ ``spec.paths[path][verb]`` with an optional
5
+ ``x-apigateway-backend.httpEndpoints`` block describing the upstream
6
+ backend (scheme/address/path/method). :func:`collect_operations` walks
7
+ the spec and exposes each (path, verb) pair as a :class:`Operation` so
8
+ the dispatcher can build URLs without hand-written client code.
9
+
10
+ URL construction:
11
+
12
+ The ``x-apigateway-backend.httpEndpoints.address`` field often points to
13
+ a staging / test backend (e.g. ``cvesa.test.osinfra.cn``) that the
14
+ gateway's CloudWAF blocks — even with browser-style headers. Each
15
+ service's runtime gateway is whatever its discovery feed entry says
16
+ (``ServiceMeta.base_url``); :func:`resolve_runtime_gateway` reads that
17
+ value, strips whitespace and a trailing ``/``, and returns it verbatim.
18
+ The runtime URL is therefore ``resolve_runtime_gateway(service) +
19
+ spec.paths[key]``; the backend block is parsed for diagnostics
20
+ (method, scheme) only and never trusted for the host. There is **no
21
+ fallback** — if the gateway hands back an empty string or the legacy
22
+ ``$APIG_GROUP_ENTRY_URL`` placeholder, the resulting URL will fail at
23
+ HTTP time and surface a clear error.
24
+
25
+ CLI surface:
26
+
27
+ Each declared ``query`` / ``path`` parameter on an operation is exposed
28
+ as its own ``--<kebab-case>`` flag by :func:`to_flag` / :func:`param_flag_index`,
29
+ so users can run ``oed <service> <op> --cve-id CVE-2024-1234`` instead
30
+ of stuffing JSON into ``--params``. The legacy ``--params '{...}'``
31
+ form is preserved as an escape hatch and is overridden by per-param
32
+ flags when both are present.
33
+
34
+ The most common backend block we still see in specs:
35
+
36
+ "x-apigateway-backend": {
37
+ "type": "HTTP",
38
+ "httpEndpoints": {
39
+ "address": "software-pkg.openeuler.org",
40
+ "scheme": "https",
41
+ "method": "GET",
42
+ "path": "/api/v1/cla",
43
+ }
44
+ }
45
+
46
+ Specs that omit this block still work — the operation is registered
47
+ with an empty ``address`` and its method/scheme taken from the OpenAPI
48
+ ``(path, verb)`` pair. Several openEuler services (``cve``,
49
+ ``pkgcontrib``, …) publish specs without it.
50
+ """
51
+
52
+ from __future__ import annotations
53
+
54
+ import hashlib
55
+ import hmac
56
+ import json
57
+ import os
58
+ import re
59
+ import time
60
+ from dataclasses import dataclass, field
61
+ from pathlib import Path
62
+ from typing import Any
63
+
64
+ from .discovery import (
65
+ ServiceMeta,
66
+ _atomic_write_json,
67
+ _cache_dir,
68
+ current_community,
69
+ fetch_discovery,
70
+ )
71
+ from .errors import NotFoundError, UserError
72
+ from .http import fetch_json_with_integrity, spec_url
73
+
74
+ SPEC_CACHE_TTL_SECONDS = 600 # 10 min, mirrors the discovery feed TTL
75
+ # Mirror of ``discovery._CLOCK_SKEW_SECONDS`` — a cached spec whose
76
+ # ``__oed_fetched_at`` is newer than ``now + _CLOCK_SKEW_SECONDS`` is treated
77
+ # as poisoned (future-timestamp TTL bypass, issue #22) and refetched. Keep in
78
+ # sync with the discovery-side constant.
79
+ _CLOCK_SKEW_SECONDS = 300
80
+ # Spec URLs are built at request time via http.spec_url, which honors the
81
+ # OED_GATEWAY / OED_DISCOVERY_PREFIX env vars so the CLI can target a test
82
+ # deployment without code changes.
83
+
84
+ # Runtime base URL for every dynamic call. Each service's gateway host
85
+ # is read straight from the discovery feed (``ServiceMeta.base_url``) —
86
+ # no fallback constant, no environment override, no derivation from
87
+ # the OpenAPI spec. The gateway is the source of truth.
88
+ _HTTP_VERBS = {"get", "post", "put", "patch", "delete", "head", "options"}
89
+
90
+
91
+ def resolve_runtime_gateway(service: ServiceMeta) -> str:
92
+ """Return the runtime base URL for ``service``.
93
+
94
+ Reads ``service.base_url`` from the discovery feed, stripping
95
+ whitespace and a trailing ``/`` so concatenation with an OpenAPI
96
+ path (``/v1/...``) never produces ``//``. Returns the feed value
97
+ verbatim — if the gateway hands back an empty string or the legacy
98
+ ``$APIG_GROUP_ENTRY_URL`` placeholder, that string flows through
99
+ and the HTTP call fails loudly rather than being silently rewritten.
100
+ """
101
+
102
+ candidate = (service.base_url or "").strip()
103
+ return candidate.rstrip("/")
104
+
105
+ # Flag-name derivation -------------------------------------------------- #
106
+
107
+
108
+ def to_flag(name: str) -> str:
109
+ """Convert a spec parameter name to a kebab-case CLI flag stem.
110
+
111
+ Examples:
112
+ ``cveId`` → ``cve-id``
113
+ ``pageNum`` → ``page-num``
114
+ ``count_per_page`` → ``count-per-page``
115
+ ``id`` → ``id``
116
+ """
117
+
118
+ s = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "-", name)
119
+ s = s.replace("_", "-")
120
+ return s.lower()
121
+
122
+
123
+ def param_flag_index(op: Operation) -> dict[str, dict[str, Any]]:
124
+ """Map CLI flag stems to declared query / path parameter defs.
125
+
126
+ Each declared parameter is registered twice — once under its
127
+ kebab-case stem (``--cve-id``) and once under the raw spec name
128
+ (``--cveId``) — so users can pick whichever form reads better.
129
+ """
130
+
131
+ out: dict[str, dict[str, Any]] = {}
132
+ for p in op.parameters:
133
+ if p.get("in") not in {"query", "path"}:
134
+ continue
135
+ out[to_flag(p["name"])] = p
136
+ out[p["name"]] = p
137
+ return out
138
+
139
+
140
+ @dataclass(frozen=True)
141
+ class Backend:
142
+ """The real upstream service backing one OpenAPI operation."""
143
+
144
+ scheme: str
145
+ address: str
146
+ path: str
147
+ method: str
148
+
149
+
150
+ @dataclass(frozen=True)
151
+ class Operation:
152
+ """One callable API operation, derived from a (path, verb) OpenAPI pair."""
153
+
154
+ service_name: str
155
+ path: str
156
+ http_method: str
157
+ backend: Backend
158
+ summary: str = ""
159
+ description: str = ""
160
+ parameters: tuple[dict[str, Any], ...] = field(default_factory=tuple)
161
+ body_required: bool = False
162
+ # Raw ``requestBody`` block (so we don't lose the OpenAPI-level metadata)
163
+ # plus the inlined ``body_schema`` resolved against ``components/schemas``
164
+ # for the ``application/json`` content type — the latter is what agents
165
+ # consume to learn how to build a ``--json`` body. ``None`` when the op
166
+ # has no JSON body.
167
+ request_body: dict[str, Any] | None = None
168
+ body_schema: dict[str, Any] | None = None
169
+ operation_id: str = ""
170
+ # Resolved runtime base URL — read from ``ServiceMeta.base_url`` via
171
+ # :func:`resolve_runtime_gateway`. Empty by default so callers that
172
+ # build Operations without a service still work; ``invoke.py`` reads
173
+ # this field to build every request URL.
174
+ base_url: str = ""
175
+
176
+ @classmethod
177
+ def from_openapi(
178
+ cls,
179
+ *,
180
+ service_name: str,
181
+ path: str,
182
+ verb: str,
183
+ op: dict[str, Any],
184
+ backend: Backend,
185
+ base_url: str = "",
186
+ spec: dict[str, Any] | None = None,
187
+ ) -> Operation:
188
+ request_body = op.get("requestBody") if isinstance(op.get("requestBody"), dict) else None
189
+ body_schema: dict[str, Any] | None = None
190
+ if request_body is not None and spec is not None:
191
+ body_schema = _resolve_json_body_schema(request_body, spec)
192
+ return cls(
193
+ service_name=service_name,
194
+ path=path,
195
+ http_method=verb.upper(),
196
+ backend=backend,
197
+ summary=op.get("summary", ""),
198
+ description=op.get("description", ""),
199
+ parameters=tuple(op.get("parameters", []) or ()),
200
+ body_required=bool(op.get("requestBody", {}).get("required")),
201
+ request_body=request_body,
202
+ body_schema=body_schema,
203
+ operation_id=op.get("operationId") or f"{verb.upper()} {path}",
204
+ base_url=base_url,
205
+ )
206
+
207
+ @property
208
+ def path_params(self) -> list[dict[str, Any]]:
209
+ return [p for p in self.parameters if p.get("in") == "path"]
210
+
211
+ @property
212
+ def query_params(self) -> list[dict[str, Any]]:
213
+ return [p for p in self.parameters if p.get("in") == "query"]
214
+
215
+ @property
216
+ def display_name(self) -> str:
217
+ """User-facing operation name. Strips the ``API_`` prefix that
218
+ Huawei APIG auto-appends to every operationId on services like
219
+ ``software-package-server`` — see ``operations_table`` for the
220
+ lookup alias that keeps the raw form working too."""
221
+
222
+ if self.operation_id.startswith("API_") and len(self.operation_id) > 4:
223
+ return self.operation_id[4:]
224
+ return self.operation_id
225
+
226
+
227
+ def _parse_backend(op: dict[str, Any], *, path: str, verb: str) -> Backend:
228
+ """Return the :class:`Backend` for an operation.
229
+
230
+ When the spec omits ``x-apigateway-backend`` (or types it as something
231
+ other than ``HTTP``) we synthesize one from the OpenAPI ``(path, verb)``
232
+ pair with an empty ``address``. The block is diagnostics-only — the
233
+ runtime host always comes from :func:`resolve_runtime_gateway` — so a
234
+ missing block must not make the operation disappear from the command
235
+ table. Several openEuler services (``cve``, ``pkgcontrib``, …) ship
236
+ specs without it.
237
+ """
238
+
239
+ raw = op.get("x-apigateway-backend")
240
+ if not isinstance(raw, dict) or raw.get("type") != "HTTP":
241
+ return Backend(scheme="https", address="", path=path, method=verb.upper())
242
+ eps = raw.get("httpEndpoints") or {}
243
+ return Backend(
244
+ scheme=eps.get("scheme", "https"),
245
+ address=eps.get("address", ""),
246
+ path=eps.get("path", "/"),
247
+ method=(eps.get("method") or verb).upper(),
248
+ )
249
+
250
+
251
+ # --------------------------------------------------------------------------- #
252
+ # $ref resolver for request-body schemas
253
+ # --------------------------------------------------------------------------- #
254
+
255
+
256
+ def _inline_refs(node: Any, *, spec: dict[str, Any], _seen: frozenset[str] = frozenset()) -> Any:
257
+ """Recursively inline ``$ref: #/components/schemas/X`` in ``node``.
258
+
259
+ Only resolves refs the openEuler gateway actually emits (a single schema
260
+ bag under ``components.schemas``); external ``$ref``s and non-JSON-Reference
261
+ forms are left alone so the original spec stays recoverable for
262
+ diagnostics. Recursion depth is bounded by the ref-graph so a cyclic
263
+ schema can't blow the stack.
264
+ """
265
+
266
+ if isinstance(node, dict):
267
+ if "$ref" in node and isinstance(node["$ref"], str):
268
+ ref = node["$ref"]
269
+ if ref.startswith("#/components/schemas/") and ref not in _seen:
270
+ key = ref.rsplit("/", 1)[-1]
271
+ schemas = (spec.get("components") or {}).get("schemas") or {}
272
+ target = schemas.get(key)
273
+ if isinstance(target, dict):
274
+ return _inline_refs(
275
+ target, spec=spec, _seen=_seen | {ref}
276
+ )
277
+ return node
278
+ return {k: _inline_refs(v, spec=spec, _seen=_seen) for k, v in node.items()}
279
+ if isinstance(node, list):
280
+ return [_inline_refs(v, spec=spec, _seen=_seen) for v in node]
281
+ return node
282
+
283
+
284
+ def _resolve_json_body_schema(
285
+ request_body: dict[str, Any], spec: dict[str, Any]
286
+ ) -> dict[str, Any] | None:
287
+ """Return the inlined JSON-body schema for a requestBody block.
288
+
289
+ Prefers the ``application/json`` content type; falls back to the first
290
+ declared content type when JSON isn't there. Returns ``None`` if the
291
+ block has no schema to resolve.
292
+ """
293
+
294
+ content = request_body.get("content") or {}
295
+ media = content.get("application/json") or next(iter(content.values()), None)
296
+ if not isinstance(media, dict):
297
+ return None
298
+ schema = media.get("schema")
299
+ if not isinstance(schema, dict):
300
+ return None
301
+ resolved = _inline_refs(schema, spec=spec)
302
+ return resolved if isinstance(resolved, dict) else None
303
+
304
+
305
+ def collect_operations(
306
+ spec: dict[str, Any], service_name: str, *, base_url: str = ""
307
+ ) -> list[Operation]:
308
+ """Walk ``spec.paths`` and return every operation.
309
+
310
+ ``base_url`` is the resolved runtime URL (output of
311
+ :func:`resolve_runtime_gateway`); it is baked into every returned
312
+ :class:`Operation` so :mod:`oed_cli.invoke` does not need to know
313
+ which service produced the operation. The ``spec`` is also passed
314
+ through so each operation's ``requestBody`` can be resolved against
315
+ ``components/schemas``.
316
+ """
317
+
318
+ out: list[Operation] = []
319
+ paths = spec.get("paths") or {}
320
+ for path, item in paths.items():
321
+ if not isinstance(item, dict):
322
+ continue
323
+ for verb, op in item.items():
324
+ if verb.lower() not in _HTTP_VERBS or not isinstance(op, dict):
325
+ continue
326
+ out.append(
327
+ Operation.from_openapi(
328
+ service_name=service_name,
329
+ path=path,
330
+ verb=verb,
331
+ op=op,
332
+ backend=_parse_backend(op, path=path, verb=verb),
333
+ base_url=base_url,
334
+ spec=spec,
335
+ )
336
+ )
337
+ return out
338
+
339
+
340
+ def operations_table(
341
+ spec: dict[str, Any], service_name: str, *, base_url: str = ""
342
+ ) -> dict[str, Operation]:
343
+ """Build a name → :class:`Operation` lookup. Each operationId is the primary
344
+ key; secondary aliases are ``"<VERB> <path>"`` (e.g. ``"GET /v1/cla"``)
345
+ and — for specs whose operationIds carry an APIG-generated ``API_``
346
+ prefix — the prefix-stripped form (``API_listFoo`` → ``listFoo``)."""
347
+
348
+ table: dict[str, Operation] = {}
349
+ for op in collect_operations(spec, service_name, base_url=base_url):
350
+ primary = op.operation_id
351
+ table[primary] = op
352
+ table[f"{op.http_method} {op.path}"] = op
353
+ stripped = op.display_name
354
+ if stripped != primary and stripped not in table:
355
+ table[stripped] = op
356
+ return table
357
+
358
+
359
+ def resolve_operation(table: dict[str, Operation], name: str) -> Operation:
360
+ """Look up an operation by ``name`` (case-insensitive), with helpful errors."""
361
+
362
+ if name in table:
363
+ return table[name]
364
+ lowered = name.lower()
365
+ for key, op in table.items():
366
+ if key.lower() == lowered:
367
+ return op
368
+ raise NotFoundError(
369
+ f"no operation matches '{name}'",
370
+ kind="method_not_found",
371
+ hint="Run `oed <service>` to list every operationId for this service.",
372
+ )
373
+
374
+
375
+ def parse_json_arg(blob: str | None, *, flag: str) -> dict[str, Any] | None:
376
+ """Parse a JSON flag with a precise error pointing at the flag name."""
377
+
378
+ if blob is None or blob == "":
379
+ return None
380
+ try:
381
+ obj = json.loads(blob)
382
+ except json.JSONDecodeError as exc:
383
+ raise UserError(
384
+ f"--{flag} is not valid JSON: {exc.msg} (line {exc.lineno}, col {exc.colno})",
385
+ kind="invalid_json",
386
+ ) from exc
387
+ if not isinstance(obj, dict):
388
+ raise UserError(
389
+ f"--{flag} must decode to a JSON object, got {type(obj).__name__}",
390
+ kind="invalid_json",
391
+ )
392
+ return obj
393
+
394
+
395
+ def coerce_param_types(op: Operation, params: dict[str, Any]) -> dict[str, Any]:
396
+ """Cast well-known string params to int/float based on the OpenAPI schema.
397
+
398
+ openEuler specs declare ``schema.type: integer`` for fields like
399
+ ``page_num``/``count_per_page``; many callers pass them as strings.
400
+ Without coercion the backend rejects them. We only convert ints the
401
+ spec actually declares, so we never mis-cast user data.
402
+ """
403
+
404
+ out: dict[str, Any] = {}
405
+ declared_ints = {
406
+ p["name"]
407
+ for p in op.parameters
408
+ if p.get("schema", {}).get("type") == "integer" and p.get("name") in params
409
+ }
410
+ declared_numbers = {
411
+ p["name"]
412
+ for p in op.parameters
413
+ if p.get("schema", {}).get("type") == "number" and p.get("name") in params
414
+ }
415
+ for k, v in params.items():
416
+ if k in declared_ints and isinstance(v, str) and v.lstrip("-").isdigit():
417
+ out[k] = int(v)
418
+ elif k in declared_numbers and isinstance(v, str):
419
+ try:
420
+ out[k] = float(v)
421
+ except ValueError:
422
+ out[k] = v
423
+ else:
424
+ out[k] = v
425
+ return out
426
+
427
+
428
+ def coerce_flag_value(param_def: dict[str, Any], value: str) -> Any:
429
+ """Coerce one CLI string flag to the spec-declared type.
430
+
431
+ CLI flags arrive as strings (``--page-num 3`` → ``"3"``), but the
432
+ OpenAPI schema often declares ``integer``. Callers can also pass
433
+ already-typed values via ``--params '{...}'``; those bypass this
434
+ helper and go through :func:`coerce_param_types` instead.
435
+ """
436
+
437
+ schema_type = (param_def.get("schema") or {}).get("type", "string")
438
+ if schema_type == "integer":
439
+ stripped = value.lstrip("-")
440
+ if stripped.isdigit():
441
+ return int(value)
442
+ return value
443
+ if schema_type == "number":
444
+ try:
445
+ return float(value)
446
+ except ValueError:
447
+ return value
448
+ if schema_type == "boolean":
449
+ lowered = value.lower()
450
+ if lowered in {"true", "1", "yes", "on"}:
451
+ return True
452
+ if lowered in {"false", "0", "no", "off"}:
453
+ return False
454
+ return value
455
+
456
+
457
+ # --------------------------------------------------------------------------- #
458
+ # Local spec cache (per-service file, mirrors discovery.py layout)
459
+ # --------------------------------------------------------------------------- #
460
+
461
+
462
+ def _spec_cache_path(community: str, service_name: str) -> Path:
463
+ # ``_cache_dir`` is imported at module scope so tests can monkeypatch it on
464
+ # this module (``setattr(dyn, "_cache_dir", ...)``) and actually redirect
465
+ # the spec cache. A deferred ``from .discovery import _cache_dir`` here
466
+ # would bypass that patch and silently write to the real cache dir.
467
+ return _cache_dir() / "specs" / community / f"{service_name}.json"
468
+
469
+
470
+ def _integrity_index_path() -> Path:
471
+ """Path to the integrity ledger holding per-spec ``repr_digest`` values.
472
+
473
+ The digest is stored SEPARATELY from the spec cache file (and at 0600) so
474
+ that editing the visible ``spec`` field cannot, on its own, make a
475
+ tampered spec pass local verification — the attacker must also write this
476
+ protected ledger. Verification reads the digest ONLY from here, with a
477
+ one-time fallback to the legacy inline field for pre-hardening caches.
478
+ (Plan A: local-cache anti-tamper hardening.)
479
+ """
480
+ return _cache_dir() / ".integrity.json"
481
+
482
+
483
+ def _cache_key_for_path(path: Path) -> str:
484
+ """Derive ``"community/service"`` from a spec cache path.
485
+
486
+ The spec cache path is ``<cache_dir>/specs/<community>/<service>.json``,
487
+ so ``parent.name`` is the community and the stem is the service name.
488
+ This lets the read helpers keep their ``path``-only signatures while
489
+ looking the digest up in the ledger.
490
+ """
491
+ return f"{path.parent.name}/{path.stem}"
492
+
493
+
494
+ def _read_integrity_index() -> dict[str, str]:
495
+ """Load the integrity ledger, or ``{}`` when absent / unreadable."""
496
+ path = _integrity_index_path()
497
+ if not path.is_file():
498
+ return {}
499
+ try:
500
+ raw = json.loads(path.read_text(encoding="utf-8"))
501
+ except (OSError, json.JSONDecodeError):
502
+ return {}
503
+ if not isinstance(raw, dict):
504
+ return {}
505
+ return {k: v for k, v in raw.items() if isinstance(k, str) and isinstance(v, str)}
506
+
507
+
508
+ def _write_integrity_index(index: dict[str, str]) -> None:
509
+ path = _integrity_index_path()
510
+ try:
511
+ path.parent.mkdir(parents=True, exist_ok=True)
512
+ _atomic_write_json(path, index, mode=0o600)
513
+ except OSError:
514
+ return # best-effort
515
+
516
+
517
+ def _lookup_digest(path: Path) -> str | None:
518
+ """Return the stored ``repr_digest`` for the spec at ``path``, or None."""
519
+ val = _read_integrity_index().get(_cache_key_for_path(path))
520
+ return val if isinstance(val, str) and val else None
521
+
522
+
523
+ def _store_digest(path: Path, digest: str) -> None:
524
+ """Record ``digest`` for the spec at ``path`` in the protected ledger."""
525
+ index = _read_integrity_index()
526
+ index[_cache_key_for_path(path)] = digest
527
+ _write_integrity_index(index)
528
+
529
+
530
+ def _spec_repr_digest(spec: dict[str, Any]) -> str:
531
+ """Compute the RFC 9530 base64 sha-256 digest of a spec dict.
532
+
533
+ Serializes with the same parameters as the discovery service's
534
+ ``_send_integrity_response`` (``ensure_ascii=False, indent=2``), so the
535
+ digest matches the server's ``Repr-Digest`` of the spec body. Used to
536
+ verify a locally-cached spec against its stored ``repr_digest`` — detects
537
+ local-cache tampering (a spec edited on disk without updating the digest).
538
+ """
539
+ import base64
540
+ payload = json.dumps(spec, ensure_ascii=False, indent=2).encode("utf-8")
541
+ return base64.b64encode(hashlib.sha256(payload).digest()).decode("ascii")
542
+
543
+
544
+ def _read_spec_cache(path: Path) -> dict[str, Any] | None:
545
+ if not path.is_file():
546
+ return None
547
+ try:
548
+ raw = json.loads(path.read_text(encoding="utf-8"))
549
+ except (OSError, json.JSONDecodeError):
550
+ return None
551
+ fetched_at = float(raw.get("__oed_fetched_at", 0))
552
+ # Poisoned cache (issue #22): a future timestamp makes the TTL check
553
+ # below never expire the entry. Reject and refetch.
554
+ if fetched_at > time.time() + _CLOCK_SKEW_SECONDS:
555
+ return None
556
+ age = time.time() - fetched_at
557
+ if age >= SPEC_CACHE_TTL_SECONDS:
558
+ return None
559
+ spec = raw.get("spec")
560
+ if not isinstance(spec, dict):
561
+ return None
562
+ # Local-integrity check: verify the on-disk spec still hashes to its
563
+ # stored repr_digest. The digest lives in the protected integrity ledger
564
+ # (separate 0600 file) so editing the spec file alone can't make a
565
+ # tampered spec pass — the attacker must also forge the ledger. Legacy
566
+ # caches (pre-hardening) still carry the digest inline; read it from there
567
+ # as a one-time fallback so existing caches migrate on next write.
568
+ cached_digest = _lookup_digest(path) or raw.get("repr_digest")
569
+ if isinstance(cached_digest, str) and cached_digest and not hmac.compare_digest(
570
+ _spec_repr_digest(spec), cached_digest
571
+ ):
572
+ return None
573
+ return spec
574
+
575
+
576
+ def _read_cached_etag(path: Path) -> str | None:
577
+ """Return the ETag stored alongside a (possibly stale) cached spec.
578
+
579
+ Used to drive a conditional ``If-None-Match`` request when the cache has
580
+ expired: the spec on disk may be stale but its ETag is still valid for
581
+ revalidation, letting the server answer ``304`` and save a full re-download.
582
+ """
583
+ if not path.is_file():
584
+ return None
585
+ try:
586
+ raw = json.loads(path.read_text(encoding="utf-8"))
587
+ except (OSError, json.JSONDecodeError):
588
+ return None
589
+ etag = raw.get("etag")
590
+ return etag if isinstance(etag, str) and etag else None
591
+
592
+
593
+ def _cached_repr_digest(path: Path) -> str | None:
594
+ """Return the stored ``repr_digest`` for the spec at ``path``.
595
+
596
+ Read from the protected integrity ledger; fall back to the legacy inline
597
+ field for caches written before the ledger existed (one-time migration).
598
+ """
599
+ digest = _lookup_digest(path)
600
+ if digest:
601
+ return digest
602
+ if not path.is_file():
603
+ return None
604
+ try:
605
+ raw = json.loads(path.read_text(encoding="utf-8"))
606
+ except (OSError, json.JSONDecodeError):
607
+ return None
608
+ legacy = raw.get("repr_digest")
609
+ return legacy if isinstance(legacy, str) and legacy else None
610
+
611
+
612
+ def _read_cached_spec_raw(path: Path) -> dict[str, Any] | None:
613
+ """Return the cached spec dict regardless of TTL, IF it passes the local
614
+ integrity check (its sha-256 matches the stored ``repr_digest``).
615
+
616
+ Used to reuse a spec on a ``304 Not Modified``. The integrity guard closes
617
+ the "304 reuses a tampered local cache" blind spot: if the on-disk spec was
618
+ edited without updating its digest, the caller must NOT reuse it — return
619
+ ``None`` so ``fetch_service_spec`` falls through to a full re-download.
620
+ """
621
+
622
+ if not path.is_file():
623
+ return None
624
+ try:
625
+ raw = json.loads(path.read_text(encoding="utf-8"))
626
+ except (OSError, json.JSONDecodeError):
627
+ return None
628
+ spec = raw.get("spec")
629
+ if not isinstance(spec, dict):
630
+ return None
631
+ cached_digest = _lookup_digest(path) or raw.get("repr_digest")
632
+ if isinstance(cached_digest, str) and cached_digest and not hmac.compare_digest(
633
+ _spec_repr_digest(spec), cached_digest
634
+ ):
635
+ return None # tampered — refuse to reuse, force re-download
636
+ return spec
637
+
638
+
639
+ def _write_spec_cache(
640
+ path: Path,
641
+ spec: dict[str, Any],
642
+ etag: str | None = None,
643
+ repr_digest: str | None = None,
644
+ ) -> None:
645
+ """Write the spec cache file at 0600; store ``repr_digest`` in the
646
+ SEPARATE protected ledger rather than in this file.
647
+
648
+ ``etag`` and ``fetched_at`` stay here: the ETag is a cache token, not
649
+ security-sensitive (forging it only causes a safe 304-miss → refetch).
650
+ The ``repr_digest`` is what gates local-cache trust, so it must NOT live
651
+ next to the spec it guards — otherwise a single file edit can re-stamp
652
+ both. The spec file is 0600 so non-owners can't write it at all.
653
+ """
654
+ payload: dict[str, Any] = {
655
+ "__oed_fetched_at": time.time(),
656
+ "spec": spec,
657
+ }
658
+ if etag:
659
+ payload["etag"] = etag
660
+ # repr_digest intentionally NOT written here — see _integrity_index_path.
661
+ try:
662
+ path.parent.mkdir(parents=True, exist_ok=True)
663
+ _atomic_write_json(path, payload, mode=0o600)
664
+ except OSError:
665
+ return # best-effort
666
+ if repr_digest:
667
+ _store_digest(path, repr_digest)
668
+
669
+
670
+ def fetch_service_spec(
671
+ service: ServiceMeta, *, force_refresh: bool = False
672
+ ) -> dict[str, Any]:
673
+ """Load one service's OpenAPI, using a file cache when fresh.
674
+
675
+ Beyond the TTL cache, this drives content-checksum verification and
676
+ conditional requests against the discovery service's integrity headers
677
+ (issue #15 F-03 + checksum hardening): a cached ETag is sent as
678
+ ``If-None-Match`` so an unchanged spec returns ``304`` (no body) and the
679
+ cache is merely re-stamped instead of re-downloaded. The response body's
680
+ SHA256 is checked against the ``Repr-Digest`` header (RFC 9530) when present;
681
+ a mismatch raises :class:`UpstreamError` (``integrity_mismatch``).
682
+
683
+ Local-cache integrity is also enforced on read: a cached spec whose SHA256
684
+ no longer matches its stored ``repr_digest`` (edited on disk) is treated as
685
+ invalid and refetched — both on TTL-hit reads and on ``304`` reuse.
686
+ """
687
+
688
+ cache_path = _spec_cache_path(service.community, service.service_name)
689
+
690
+ # Fresh cache → return immediately, no network. (Integrity-checked inside.)
691
+ if not force_refresh:
692
+ cached = _read_spec_cache(cache_path)
693
+ if cached is not None:
694
+ return cached
695
+
696
+ url = spec_url(service.community, service.service_name)
697
+ stale_etag = _read_cached_etag(cache_path)
698
+
699
+ # Conditional request when we hold an ETag; the server may answer 304.
700
+ data, etag, repr_digest = fetch_json_with_integrity(url, if_none_match=stale_etag)
701
+
702
+ if data is None:
703
+ # 304 Not Modified — the cached spec is still current. Reuse it rather
704
+ # than re-downloading, but only if it passes the local integrity check
705
+ # (``_read_cached_spec_raw`` verifies the on-disk spec against its
706
+ # stored ``repr_digest``; a tampered cache returns None here).
707
+ stale_spec = _read_cached_spec_raw(cache_path)
708
+ if stale_spec is not None:
709
+ _write_spec_cache(
710
+ cache_path, stale_spec,
711
+ etag=etag or stale_etag,
712
+ repr_digest=repr_digest or _cached_repr_digest(cache_path),
713
+ )
714
+ return stale_spec
715
+ # Stale spec missing or tampered — refetch unconditionally.
716
+ data, etag, repr_digest = fetch_json_with_integrity(url)
717
+
718
+ if not isinstance(data, dict) or "openapi" not in data:
719
+ raise NotFoundError(
720
+ f"GET {url} did not return an OpenAPI document",
721
+ kind="spec_missing",
722
+ hint="The discovery feed lists this service but its OpenAPI spec is not available.",
723
+ )
724
+ _write_spec_cache(cache_path, data, etag=etag, repr_digest=repr_digest)
725
+ return data
726
+
727
+
728
+ def resolve_service(community: str | None = None, force_refresh: bool = False) -> ServiceMeta:
729
+ """Find the service named by the ``OED_SERVICE`` env var (used in tests).
730
+
731
+ Real CLI dispatch uses :func:`resolve_service_by_name`. This helper exists
732
+ so that scripts / tests can still drive ``invoke.call_operation`` without
733
+ going through the full dispatch table.
734
+ """
735
+
736
+ name = os.environ.get("OED_SERVICE")
737
+ if not name:
738
+ raise UserError(
739
+ "OED_SERVICE env var is not set; pass service_name explicitly.",
740
+ kind="missing_service",
741
+ )
742
+ return resolve_service_by_name(name, community=community, force_refresh=force_refresh)
743
+
744
+
745
+ def resolve_service_by_name(
746
+ service_name: str,
747
+ *,
748
+ community: str | None = None,
749
+ force_refresh: bool = False,
750
+ ) -> ServiceMeta:
751
+ """Locate a :class:`ServiceMeta` by ``service_name`` in the given/active community."""
752
+
753
+ feed = fetch_discovery(force_refresh=force_refresh)
754
+ target_community = community or current_community()
755
+ matches = [s for s in feed.services if s.service_name == service_name]
756
+ if not matches:
757
+ other = sorted({s.community for s in feed.services})
758
+ raise NotFoundError(
759
+ f"service '{service_name}' is not registered",
760
+ kind="service_not_found",
761
+ hint=(
762
+ f"Available communities: {other}. "
763
+ "Run `oed services` to list registered services."
764
+ ),
765
+ )
766
+ if len(matches) == 1:
767
+ return matches[0]
768
+ for s in matches:
769
+ if s.community == target_community:
770
+ return s
771
+ other_communities = sorted({s.community for s in matches})
772
+ raise UserError(
773
+ f"service '{service_name}' is registered in multiple communities {other_communities}; "
774
+ f"set OED_COMMUNITY to pick one (current: {target_community}).",
775
+ kind="ambiguous_service",
776
+ )
777
+
778
+
779
+ def operations_for(
780
+ service_name: str,
781
+ *,
782
+ community: str | None = None,
783
+ force_refresh: bool = False,
784
+ ) -> tuple[ServiceMeta, dict[str, Operation], dict[str, Any]]:
785
+ """One-shot helper: resolve a service, fetch its spec, build the table.
786
+
787
+ Returns ``(service_meta, operations_table, raw_spec)`` so callers can
788
+ inspect both the structured view and the raw OpenAPI doc. Each
789
+ operation in the returned table has ``base_url`` set to
790
+ :func:`resolve_runtime_gateway` of the resolved service.
791
+ """
792
+
793
+ service = resolve_service_by_name(
794
+ service_name, community=community, force_refresh=force_refresh
795
+ )
796
+ spec = fetch_service_spec(service, force_refresh=force_refresh)
797
+ base_url = resolve_runtime_gateway(service)
798
+ return service, operations_table(spec, service.service_name, base_url=base_url), spec
799
+
800
+
801
+ __all__ = [
802
+ "Backend",
803
+ "Operation",
804
+ "collect_operations",
805
+ "coerce_flag_value",
806
+ "coerce_param_types",
807
+ "fetch_service_spec",
808
+ "operations_for",
809
+ "operations_table",
810
+ "param_flag_index",
811
+ "parse_json_arg",
812
+ "resolve_operation",
813
+ "resolve_runtime_gateway",
814
+ "resolve_service_by_name",
815
+ "to_flag",
816
+ ]