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
ogd_cli/errors.py ADDED
@@ -0,0 +1,45 @@
1
+ """Exit codes and exception hierarchy for ``ogd``."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class ExitCode:
7
+ OK = 0
8
+ USER_ERROR = 1
9
+ NETWORK_ERROR = 2
10
+ UPSTREAM_ERROR = 3
11
+ NOT_FOUND = 4
12
+
13
+
14
+ class OgdError(Exception):
15
+ """Base for all ``ogd`` runtime errors."""
16
+
17
+ code: int = ExitCode.USER_ERROR
18
+
19
+ def __init__(self, message: str, *, kind: str | None = None, hint: str | None = None) -> None:
20
+ super().__init__(message)
21
+ self.message = message
22
+ self.kind = kind or self.__class__.__name__
23
+ self.hint = hint
24
+
25
+ def to_dict(self) -> dict:
26
+ d: dict = {"ok": False, "code": self.code, "error": self.kind, "message": self.message}
27
+ if self.hint:
28
+ d["hint"] = self.hint
29
+ return d
30
+
31
+
32
+ class UserError(OgdError):
33
+ code = ExitCode.USER_ERROR
34
+
35
+
36
+ class NetworkError(OgdError):
37
+ code = ExitCode.NETWORK_ERROR
38
+
39
+
40
+ class UpstreamError(OgdError):
41
+ code = ExitCode.UPSTREAM_ERROR
42
+
43
+
44
+ class NotFoundError(OgdError):
45
+ code = ExitCode.NOT_FOUND
ogd_cli/http.py ADDED
@@ -0,0 +1,424 @@
1
+ """WAF-safe HTTP client for the openEuler Infra gateway.
2
+
3
+ The gateway sits behind a CloudWAF that returns a Chinese-language HTML block
4
+ page when the request lacks browser-style headers (see ``context/discoverAPI.md``
5
+ section "注意事项 & 已知限制"). This module bakes those headers in so every call
6
+ made by ``ogd`` succeeds without users tweaking curl flags.
7
+
8
+ Note on ``Referer``: openEuler APIG rejects requests that carry a
9
+ ``Referer: https://api-gateway.osinfra.cn/`` header with HTTP 401 on at
10
+ least one production path (``easysearch`` / ``sigsearch/docs``). The
11
+ ``/discovery/apis`` feed does not need Referer to pass the CloudWAF
12
+ either — empirically verified 2026-07-28. So ``_headers()`` does NOT
13
+ emit a default Referer. Callers can still pass one explicitly via the
14
+ ``headers=`` argument to :func:`get_request` if a future endpoint
15
+ demands it.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import base64
21
+ import hashlib
22
+ import hmac
23
+ import os
24
+ from typing import Any
25
+
26
+ import httpx
27
+
28
+ from . import __version__
29
+ from .errors import NetworkError, NotFoundError, UpstreamError, UserError
30
+
31
+ DEFAULT_GATEWAY = "https://api-gateway.osinfra.cn"
32
+ # Path prefix under the gateway that serves the discovery API. Production routes
33
+ # the feed through a reverse proxy at ``/discovery/apis``; a discovery service
34
+ # reached directly (e.g. a test deployment) serves ``/apis``. Override the
35
+ # gateway host and/or this prefix via env to point the CLI at a non-production
36
+ # deployment without code changes:
37
+ # OGD_GATEWAY=https://apig-discovery.test.osinfra.cn
38
+ # OGD_DISCOVERY_PREFIX=/apis
39
+ DEFAULT_DISCOVERY_PREFIX = "/discovery/apis"
40
+ _TIMEOUT_SECONDS = 30.0
41
+ DEFAULT_USER_AGENT = f"ogd/{__version__} (+https://gitcode.com/openeuler/oed-cli)"
42
+
43
+
44
+ def resolve_gateway() -> str:
45
+ """Return the gateway host: ``OGD_GATEWAY`` env > :data:`DEFAULT_GATEWAY`.
46
+
47
+ Strip a trailing ``/`` so concatenation with an absolute path never yields
48
+ ``//``. Used at request-build time (not import time) so flipping the env
49
+ takes effect without reloading the module.
50
+ """
51
+ gw = os.environ.get("OGD_GATEWAY") or DEFAULT_GATEWAY
52
+ return gw.rstrip("/")
53
+
54
+
55
+ def resolve_discovery_prefix() -> str:
56
+ """Return the discovery API path prefix: env > default.
57
+
58
+ ``OGD_DISCOVERY_PREFIX=/apis`` points at a directly-reached discovery
59
+ service; the default ``/discovery/apis`` goes through the gateway reverse
60
+ proxy. Leading slash enforced, trailing slash stripped.
61
+ """
62
+ p = os.environ.get("OGD_DISCOVERY_PREFIX") or DEFAULT_DISCOVERY_PREFIX
63
+ if not p.startswith("/"):
64
+ p = "/" + p
65
+ return p.rstrip("/") or "/"
66
+
67
+
68
+ def apis_url() -> str:
69
+ """Full URL of the discovery feed list endpoint."""
70
+ return f"{resolve_gateway()}{resolve_discovery_prefix()}"
71
+
72
+
73
+ def spec_url(community: str, service_name: str) -> str:
74
+ """Full URL of one service's OpenAPI document endpoint."""
75
+ return f"{resolve_gateway()}{resolve_discovery_prefix()}/{community}/{service_name}"
76
+
77
+
78
+ def _resolve_user_agent(user_agent: str | None) -> str:
79
+ """Resolve the User-Agent: explicit arg > ``OGD_USER_AGENT`` env > default.
80
+
81
+ An empty string falls through to the next source — passing ``--user-agent ""``
82
+ is treated the same as not passing it.
83
+ """
84
+
85
+ if user_agent:
86
+ return user_agent
87
+ env = os.environ.get("OGD_USER_AGENT")
88
+ if env:
89
+ return env
90
+ return DEFAULT_USER_AGENT
91
+
92
+
93
+ def _headers(
94
+ extra: dict[str, str] | None = None,
95
+ *,
96
+ user_agent: str | None = None,
97
+ token: str | None = None,
98
+ cookie: str | None = None,
99
+ service_name: str = "",
100
+ ) -> dict[str, str]:
101
+ h = {
102
+ "User-Agent": _resolve_user_agent(user_agent),
103
+ "Accept": "application/json, text/plain, */*",
104
+ "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
105
+ }
106
+ if token:
107
+ h["Authorization"] = f"Bearer {token}"
108
+ # Plaintext identity/routing headers for the APIG frontend custom-auth
109
+ # function (see ``context/custom-auth.py``). These are NOT a secret —
110
+ # they only declare the calling client (``source``), the target
111
+ # service (``target``) and the active community (``community``, which
112
+ # selects per-community backend credentials such as the etherpad api
113
+ # key map) so APIG can apply per-service header forwarding. Names are
114
+ # community-agnostic so all community CLIs (ogd / oed / ad / cann / oud)
115
+ # share the same contract. Emitted for ALL service calls (token present
116
+ # or not): anonymous services like etherpad rely on ``x-community`` for
117
+ # the gateway to pick the pre-configured per-community api key — without
118
+ # it the gateway returns 401. Real authorization (when a token is sent)
119
+ # comes from the Bearer token + the server-side role lookup; a
120
+ # signed/HMAC header was removed because a secret baked into a
121
+ # distributed CLI cannot be kept secret. ``service_name`` empty =
122
+ # discovery / spec fetch — public.
123
+ # NOTE: read the env directly — importing discovery here would cycle
124
+ # (discovery → http).
125
+ if service_name:
126
+ h["x-source"] = "ogd-cli"
127
+ h["x-target"] = service_name
128
+ h["x-community"] = os.environ.get("OGD_COMMUNITY", "opengauss")
129
+ if cookie:
130
+ h["Cookie"] = cookie
131
+ if extra:
132
+ h.update(extra)
133
+ return h
134
+
135
+
136
+ def _is_waf_block(html: str) -> bool:
137
+ lowered = html[:512].lower()
138
+ return (
139
+ "<!doctype html" in lowered
140
+ and ("cloudwaf" in lowered or "访问被拦截" in html or "requestid" in lowered)
141
+ )
142
+
143
+
144
+ def get_json(url: str, *, params: dict | None = None, headers: dict | None = None) -> Any:
145
+ """GET ``url`` and return parsed JSON.
146
+
147
+ Raises:
148
+
149
+ - :class:`NetworkError` (exit 2) for connectivity / WAF failures
150
+ - :class:`UpstreamError` (exit 3) for genuine 5xx / unexpected payloads
151
+ - :class:`NotFoundError` (exit 4) when the upstream reports an empty spec
152
+ """
153
+
154
+ return _decode(get_request("GET", url, params=params, headers=headers), spec_endpoint=True)
155
+
156
+
157
+ def get_request(
158
+ method: str,
159
+ url: str,
160
+ *,
161
+ params: dict | None = None,
162
+ body: Any = None,
163
+ headers: dict | None = None,
164
+ timeout: float = _TIMEOUT_SECONDS,
165
+ user_agent: str | None = None,
166
+ token: str | None = None,
167
+ cookie: str | None = None,
168
+ service_name: str = "",
169
+ ) -> httpx.Response:
170
+ """Run an arbitrary HTTP request and return the raw :class:`httpx.Response`.
171
+
172
+ Adds the WAF-safe browser headers; auto-declares ``Content-Type: application/json``
173
+ when ``body`` is set and the caller has not overridden it. Surfaces
174
+ connectivity failures as :class:`NetworkError`; WAF blocks as
175
+ :class:`NetworkError` (kind ``waf_block``); 5xx as :class:`UpstreamError`.
176
+
177
+ ``user_agent`` overrides the default User-Agent header — useful when a
178
+ specific APIG backend's WAF rejects the default ``ogd/x.y.z`` UA with a
179
+ misleading 401 (e.g. ``easysearch``). Falls back to ``OGD_USER_AGENT`` env,
180
+ then the bundled default.
181
+
182
+ ``token`` adds an ``Authorization: Bearer <token>`` header (only when set).
183
+ ``cookie`` adds a ``Cookie: <cookie>`` header (only when set). Both are
184
+ added by :func:`_headers` before the caller's ``headers=`` extras merge,
185
+ so caller-supplied ``Authorization`` / ``Cookie`` override the kwargs.
186
+
187
+ ``service_name`` (when set — token or not) emits plaintext
188
+ ``x-source: ogd-cli``, ``x-target: <service>`` and
189
+ ``x-community: <OGD_COMMUNITY|opengauss>`` headers — the APIG frontend
190
+ custom-auth function reads them to pick per-service / per-community header
191
+ forwarding rules. They carry no secret; authorization is done by the Bearer
192
+ token plus a server-side role lookup.
193
+ """
194
+
195
+ method = method.upper()
196
+ extra = dict(headers or {})
197
+ if body is not None and not any(h.lower() == "content-type" for h in extra):
198
+ extra["Content-Type"] = "application/json"
199
+
200
+ try:
201
+ try:
202
+ client_cm = httpx.Client(timeout=timeout, follow_redirects=True)
203
+ except ImportError as exc:
204
+ # httpx reads *_PROXY env vars (trust_env defaults True). A
205
+ # ``socks5://`` proxy makes it lazily import ``socksio``; without
206
+ # the extra installed the Client() constructor raises ImportError
207
+ # rather than an httpx.HTTPError. Surface a readable message.
208
+ if "socksio" in str(exc).lower():
209
+ raise UserError(
210
+ "A SOCKS proxy is set (via *_PROXY env vars) but the "
211
+ "'socksio' package is not installed.",
212
+ kind="socks_dependency_missing",
213
+ hint="Install the SOCKS transport: pip install 'httpx[socks]'.",
214
+ ) from exc
215
+ raise
216
+ with client_cm as client:
217
+ return client.request(
218
+ method,
219
+ url,
220
+ params=params if params else None,
221
+ json=body if body is not None else None,
222
+ headers=_headers(
223
+ extra,
224
+ user_agent=user_agent,
225
+ token=token,
226
+ cookie=cookie,
227
+ service_name=service_name,
228
+ ),
229
+ )
230
+ except httpx.HTTPError as exc:
231
+ raise NetworkError(f"{method} {url} failed: {exc}", kind="network_error") from exc
232
+
233
+
234
+ def _decode(
235
+ resp: httpx.Response,
236
+ *,
237
+ spec_endpoint: bool = False,
238
+ ) -> Any:
239
+ """Validate ``resp`` and return parsed JSON.
240
+
241
+ ``spec_endpoint=True`` treats an empty body as :class:`NotFoundError`
242
+ (used for spec discovery). For runtime service calls an empty body is
243
+ considered a successful empty payload (``null``).
244
+ """
245
+
246
+ if resp.status_code >= 500:
247
+ raise UpstreamError(
248
+ f"{resp.request.method} {resp.url} returned {resp.status_code}",
249
+ kind="upstream_error",
250
+ hint="Check gateway status; retry shortly.",
251
+ )
252
+
253
+ if _is_waf_block(resp.text):
254
+ raise NetworkError(
255
+ f"Gateway WAF blocked the request to {resp.url}",
256
+ kind="waf_block",
257
+ hint=(
258
+ "Some APIG backends reject the bundled ogd/x.y.z User-Agent. "
259
+ "Retry with `--user-agent 'Mozilla/5.0 ...'` or set "
260
+ "OGD_USER_AGENT in the environment."
261
+ ),
262
+ )
263
+
264
+ if not resp.content:
265
+ if spec_endpoint:
266
+ raise NotFoundError(
267
+ f"{resp.request.method} {resp.url} "
268
+ f"returned an empty body (HTTP {resp.status_code})",
269
+ kind="spec_missing",
270
+ hint=(
271
+ "The discovery feed lists this service but its OpenAPI "
272
+ "spec has not been published yet."
273
+ ),
274
+ )
275
+ return None
276
+
277
+ try:
278
+ return resp.json()
279
+ except Exception as exc:
280
+ raise UpstreamError(
281
+ f"{resp.request.method} {resp.url} returned non-JSON body (HTTP {resp.status_code})",
282
+ kind="upstream_error",
283
+ ) from exc
284
+
285
+
286
+ def request_json(
287
+ method: str,
288
+ url: str,
289
+ *,
290
+ params: dict | None = None,
291
+ body: Any = None,
292
+ headers: dict | None = None,
293
+ timeout: float = _TIMEOUT_SECONDS,
294
+ ) -> Any:
295
+ """Run a request and return parsed JSON (empty body → ``None``)."""
296
+
297
+ resp = get_request(method, url, params=params, body=body, headers=headers, timeout=timeout)
298
+ return _decode(resp)
299
+
300
+
301
+ def _normalize_etag(etag: str | None) -> str | None:
302
+ """Strip the ``W/`` weak prefix and surrounding quotes from an ETag value.
303
+
304
+ The discovery service emits the raw SHA256 hex as both ``ETag`` and
305
+ ``X-Content-SHA256`` (no quotes, no weak prefix), but a generic gateway
306
+ may re-quote or weaken it. Return the bare hex for comparison, or
307
+ ``None`` for an empty / malformed value.
308
+ """
309
+ if not etag:
310
+ return None
311
+ e = etag.strip()
312
+ if e.startswith("W/"):
313
+ e = e[2:]
314
+ if len(e) >= 2 and e.startswith('"') and e.endswith('"'):
315
+ e = e[1:-1]
316
+ return e or None
317
+
318
+
319
+ def parse_repr_digest(header: str | None) -> str | None:
320
+ """Parse an RFC 9530 ``Repr-Digest`` header, return the sha-256 base64 value.
321
+
322
+ Header form ``sha-256=<base64>``; may carry multiple algorithms comma-
323
+ separated. Returns the sha-256 value or ``None`` when absent / not found.
324
+ Algorithm name is case-insensitive, spaces around ``=`` tolerated.
325
+ """
326
+ if not header:
327
+ return None
328
+ for item in header.split(","):
329
+ item = item.strip()
330
+ if "=" not in item:
331
+ continue
332
+ algo, _, value = item.partition("=")
333
+ if algo.strip().lower() != "sha-256":
334
+ continue
335
+ value = value.strip()
336
+ if not value:
337
+ return None
338
+ return value
339
+ return None
340
+
341
+
342
+ def _verify_content_integrity(content: bytes, headers: httpx.Headers) -> str | None:
343
+ """Verify the response body against its ``Repr-Digest`` header, when present.
344
+
345
+ The discovery service stamps the response with an RFC 9530 ``Repr-Digest``
346
+ header carrying ``sha-256=<base64(sha256(body))>``. When present we
347
+ recompute the SHA256 locally (base64-encoded) and compare constant-time; a
348
+ mismatch means the body was altered in transit (tampering / a transparent
349
+ proxy rewriting content) and is raised as :class:`UpstreamError`.
350
+
351
+ When no ``Repr-Digest`` header is present (the gateway strips it, or the
352
+ deployment predates this feature) we **skip** verification and return
353
+ ``None`` — verify-when-present, never fail-when-absent.
354
+
355
+ Returns the base64 digest value (for local-cache integrity checks) when the
356
+ check passes or was skipped-with-a-header; ``None`` otherwise.
357
+ """
358
+ raw = headers.get("Repr-Digest")
359
+ if not raw:
360
+ return None
361
+ expected = parse_repr_digest(raw)
362
+ if not expected:
363
+ return None
364
+ actual = base64.b64encode(hashlib.sha256(content).digest()).decode("ascii")
365
+ if not hmac.compare_digest(actual, expected):
366
+ raise UpstreamError(
367
+ "OpenAPI spec integrity check failed: body SHA256 does not match "
368
+ "the Repr-Digest header",
369
+ kind="integrity_mismatch",
370
+ hint=(
371
+ "The spec body was altered between the discovery service and "
372
+ "this client (transparent proxy rewrite or tampering). Refusing "
373
+ "to load the spec; retry, and report if persistent."
374
+ ),
375
+ )
376
+ return expected
377
+
378
+
379
+ def fetch_json_with_integrity(
380
+ url: str,
381
+ *,
382
+ if_none_match: str | None = None,
383
+ params: dict | None = None,
384
+ headers: dict | None = None,
385
+ timeout: float = _TIMEOUT_SECONDS,
386
+ ) -> tuple[Any | None, str | None, str | None]:
387
+ """GET ``url`` with WAF-safe headers and return ``(data, etag, repr_digest)``.
388
+
389
+ Combines :func:`get_request`, :func:`_decode`, and content-checksum
390
+ verification for the OpenAPI spec endpoints:
391
+
392
+ - Sends ``If-None-Match`` when the caller has a cached ETag, so an unchanged
393
+ spec comes back as ``304`` (no body) and the caller can reuse its cache.
394
+ - On ``304`` returns ``(None, etag, repr_digest)`` — ``data`` is ``None``;
395
+ the response's ``ETag`` (hex, for 304 negotiation) and ``Repr-Digest``
396
+ (base64, for local-cache integrity) are returned for the caller to store.
397
+ - Otherwise decodes + checksum-verifies the body and returns
398
+ ``(parsed_json, etag, repr_digest)``. ``repr_digest`` is ``None`` when the
399
+ endpoint did not emit a ``Repr-Digest`` header (verification skipped).
400
+ """
401
+ req_headers = dict(headers or {})
402
+ if if_none_match:
403
+ req_headers["If-None-Match"] = if_none_match
404
+
405
+ # Force an uncompressed body. The discovery service stamps ``ETag`` and
406
+ # ``Repr-Digest`` over the *uncompressed* bytes; the front-line WAF/CDN
407
+ # transparently gzips large responses and then strips the (now-mismatched)
408
+ # ``ETag`` header on the compressed path — leaving only ``Repr-Digest``
409
+ # (a non-standard header the WAF does not rewrite). For an uncompressed
410
+ # body both headers survive, so ``If-None-Match`` / 304 negotiation works.
411
+ # ``Repr-Digest`` verification is unaffected either way: httpx always
412
+ # decompresses before exposing ``resp.content``. Specs are small (~tens of
413
+ # KB) and fetched at most every cache TTL, so the bandwidth cost is moot.
414
+ req_headers.setdefault("Accept-Encoding", "identity")
415
+
416
+ resp = get_request("GET", url, params=params, headers=req_headers, timeout=timeout)
417
+ if resp.status_code == 304:
418
+ repr_digest = parse_repr_digest(resp.headers.get("Repr-Digest"))
419
+ return None, resp.headers.get("ETag"), repr_digest
420
+
421
+ data = _decode(resp, spec_endpoint=True)
422
+ etag = resp.headers.get("ETag")
423
+ repr_digest = _verify_content_integrity(resp.content, resp.headers)
424
+ return data, etag, repr_digest