probegate-cli 0.1.0__tar.gz
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.
- probegate_cli-0.1.0/PKG-INFO +123 -0
- probegate_cli-0.1.0/README.md +106 -0
- probegate_cli-0.1.0/pyproject.toml +20 -0
- probegate_cli-0.1.0/setup.cfg +4 -0
- probegate_cli-0.1.0/src/probegate_cli/__init__.py +1 -0
- probegate_cli-0.1.0/src/probegate_cli/api.py +75 -0
- probegate_cli-0.1.0/src/probegate_cli/config.py +116 -0
- probegate_cli-0.1.0/src/probegate_cli/credentials.py +63 -0
- probegate_cli-0.1.0/src/probegate_cli/main.py +395 -0
- probegate_cli-0.1.0/src/probegate_cli/models.py +83 -0
- probegate_cli-0.1.0/src/probegate_cli.egg-info/PKG-INFO +123 -0
- probegate_cli-0.1.0/src/probegate_cli.egg-info/SOURCES.txt +15 -0
- probegate_cli-0.1.0/src/probegate_cli.egg-info/dependency_links.txt +1 -0
- probegate_cli-0.1.0/src/probegate_cli.egg-info/entry_points.txt +2 -0
- probegate_cli-0.1.0/src/probegate_cli.egg-info/requires.txt +11 -0
- probegate_cli-0.1.0/src/probegate_cli.egg-info/top_level.txt +1 -0
- probegate_cli-0.1.0/tests/test_cli.py +522 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: probegate-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Internal cloud assessment platform CLI
|
|
5
|
+
Requires-Python: >=3.12
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: typer==0.27.2
|
|
8
|
+
Requires-Dist: rich==15.0.0
|
|
9
|
+
Requires-Dist: httpx==0.28.1
|
|
10
|
+
Requires-Dist: pydantic==2.14.3
|
|
11
|
+
Requires-Dist: keyring==25.7.0
|
|
12
|
+
Requires-Dist: platformdirs==4.5.1
|
|
13
|
+
Provides-Extra: test
|
|
14
|
+
Requires-Dist: pytest<10,>=8; extra == "test"
|
|
15
|
+
Requires-Dist: ruff<1,>=0.11; extra == "test"
|
|
16
|
+
Requires-Dist: build<2,>=1; extra == "test"
|
|
17
|
+
|
|
18
|
+
# ProbeGate CLI (internal 0.1.0)
|
|
19
|
+
|
|
20
|
+
Cloud-only client: assessments execute on existing platform workers. Prepare Project,
|
|
21
|
+
authorized Target and published Suite on the platform first. No backend, DB, Redis,
|
|
22
|
+
MinIO or LLM key is required on the client. No registry release is authorized.
|
|
23
|
+
|
|
24
|
+
Build/install with Python 3.12 (from repository root):
|
|
25
|
+
|
|
26
|
+
```text
|
|
27
|
+
python -m pip install build
|
|
28
|
+
python -m build --wheel cli
|
|
29
|
+
python -m pip install cli/dist/probegate_cli-0.1.0-py3-none-any.whl
|
|
30
|
+
probegate --help
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Development/checks: `python -m pip install -e "cli[test]"`, then `make lint` and
|
|
34
|
+
`make test`. Existing root tests remain enabled. `PYTHON` selects the interpreter;
|
|
35
|
+
`PYTEST_ARGS` supplies optional pytest arguments. GNU Make is needed for make commands.
|
|
36
|
+
|
|
37
|
+
```text
|
|
38
|
+
probegate login --platform https://assessment.example --email qa@example.org
|
|
39
|
+
probegate init --project <uuid> --target <uuid> --suite <uuid> --suite-version 1.0 --category QUALITY --overwrite
|
|
40
|
+
probegate run --mode pipeline --max-requests 20 --timeout-s 120 --yes --json
|
|
41
|
+
probegate run --mode agent --max-requests 10 --timeout-s 120 --max-steps 10 --max-tokens 2000 --yes --json
|
|
42
|
+
probegate watch --run <uuid>
|
|
43
|
+
probegate watch --run <uuid> --once --json
|
|
44
|
+
probegate findings --run <uuid> --json
|
|
45
|
+
probegate stop --run <uuid> --yes --json
|
|
46
|
+
probegate report --run <uuid> --format json --output report.json --json
|
|
47
|
+
probegate report --run <uuid> --format html --output report.html
|
|
48
|
+
probegate logout
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
`--platform` is an origin, without `/api/v1`; the client adds that existing prefix.
|
|
52
|
+
Remote origins require HTTPS. HTTP is accepted only for explicit localhost/127.0.0.1/::1
|
|
53
|
+
origins. TLS verification stays enabled. Redirects and ambient HTTP proxy configuration
|
|
54
|
+
are disabled, so bearer credentials cannot be forwarded to a redirected origin.
|
|
55
|
+
|
|
56
|
+
Passwords are prompted with hidden input, never accepted as arguments. Native Windows
|
|
57
|
+
Credential Manager and Linux Secret Service are supported secure stores. A missing,
|
|
58
|
+
locked or unsupported backend fails loudly. There is no plaintext fallback. An explicit
|
|
59
|
+
`PROBEGATE_TOKEN` overrides the saved token; logout cannot unset it in the parent shell
|
|
60
|
+
or revoke the JWT server-side. A saved token is scoped to platform origin and account.
|
|
61
|
+
Use `PROBEGATE_ACCOUNT` or `init --account` to select an account for data commands.
|
|
62
|
+
|
|
63
|
+
Config contains non-secret defaults only. Paths default to platformdirs user config/state
|
|
64
|
+
locations. Override them with `PROBEGATE_CONFIG` (file) and `PROBEGATE_STATE_DIR` (directory).
|
|
65
|
+
Configuration precedence is flags > `PROBEGATE_PLATFORM`/`PROBEGATE_ACCOUNT` > config.
|
|
66
|
+
Resource IDs, category, version and polling interval come from flags/config; resource-ID
|
|
67
|
+
environment variables are not supported. Poll interval defaults to 2 seconds and may be
|
|
68
|
+
changed by `init --polling-interval` or `watch --interval` (0.2–60 seconds).
|
|
69
|
+
Malformed config fails; repair it or select a new config file. `init` replaces existing
|
|
70
|
+
config only after interactive confirmation or `--overwrite`.
|
|
71
|
+
|
|
72
|
+
Run budgets are mandatory. Each invocation creates one PIPELINE or independent AGENT
|
|
73
|
+
run. Project defaults are explicitly disabled (`use_project_defaults:false`), so they
|
|
74
|
+
cannot silently add strategies/rubric/profile. Agent uses the server's documented
|
|
75
|
+
strategy defaults; this CLI does not expose custom strategies or pipeline_first.
|
|
76
|
+
Confirmation displays the exact request plus Project ID. Noninteractive submission
|
|
77
|
+
and stop require `--yes`. Target authorization, suite publication, tenant/RBAC and
|
|
78
|
+
execution limits continue to be enforced by the backend and worker.
|
|
79
|
+
|
|
80
|
+
Before creating a run, the client writes an atomic non-secret intent containing UUID,
|
|
81
|
+
origin, Project, idempotency key, exact body, timestamp and nullable run ID. If POST loses
|
|
82
|
+
its response, keep that intent and resume explicitly:
|
|
83
|
+
|
|
84
|
+
```text
|
|
85
|
+
probegate run --resume-intent <intent-uuid> --yes --json
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Select the original origin through config or `PROBEGATE_PLATFORM`; resume forbids
|
|
89
|
+
all origin/payload flags. It reuses the saved Project/body/key. If the run ID was
|
|
90
|
+
already saved, it returns that ID without POST. If response persistence failed after
|
|
91
|
+
creation, resubmitting the same intent still recovers the server run. Never edit a
|
|
92
|
+
journal to create a new payload or remove it while recovering. Same key/different body
|
|
93
|
+
is a backend 409. POSTs never automatically retry. Auth failures require explicit login
|
|
94
|
+
and explicit retry; the client never replays writes after login automatically.
|
|
95
|
+
|
|
96
|
+
GET retries transport errors, 5xx and 429 at most three times after the initial attempt.
|
|
97
|
+
Delays are 1/2/4 seconds; Retry-After seconds/date is capped at 30 seconds per retry.
|
|
98
|
+
Other HTTP errors do not retry. Each HTTP request has a 15 second timeout, separate
|
|
99
|
+
from the run's worker execution timeout. Watch exits after exhausted retries without
|
|
100
|
+
changing server state. Ctrl+C detaches (130) and prints attach/stop instructions.
|
|
101
|
+
|
|
102
|
+
Agent progress means reserved steps, and remaining means unused capacity. COMPLETED
|
|
103
|
+
does not imply PASS. Finding states remain server-owned; pending findings are not
|
|
104
|
+
confirmed bugs. Status does not depend on findings/report permissions. Stop verifies
|
|
105
|
+
the current server status; an unverified stop request fails with guidance to watch.
|
|
106
|
+
|
|
107
|
+
All terminal output is plain, without animation or markup interpretation. Data commands
|
|
108
|
+
accept `--json`: one complete document on stdout, diagnostics on stderr. Watch JSON
|
|
109
|
+
waits for terminal status unless `--once` is selected. Report JSON stdout retains the
|
|
110
|
+
original report schema; files always retain exact server response bytes.
|
|
111
|
+
Downloads validate media type/JSON schema_version 1.0 before atomic publication.
|
|
112
|
+
Existing files require `--overwrite`; failed downloads keep any previous destination.
|
|
113
|
+
Files are not opened automatically. Reports may contain sensitive redacted evidence;
|
|
114
|
+
protect and share downloaded files under your organization's rules.
|
|
115
|
+
|
|
116
|
+
Exit codes: 0 successful operation/COMPLETED (even with FAIL findings); 1 API/auth/network,
|
|
117
|
+
local I/O, invalid server report or FAILED; 2 invalid parameters/config; 3 STOPPED;
|
|
118
|
+
130 interrupted watch. Stop returning STOPPED also exits 3. No quality gate exit policy.
|
|
119
|
+
|
|
120
|
+
Evidence and limitations: [verification](../docs/qa/cli-platform/verification.md),
|
|
121
|
+
[contract review](../docs/specs/cli-platform/review.md). Windows and Ubuntu WSL wheel
|
|
122
|
+
checks do not certify staging, a native Linux desktop credential store or all Linux
|
|
123
|
+
systems. Local runner, extension and CI gate remain outside scope.
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# ProbeGate CLI (internal 0.1.0)
|
|
2
|
+
|
|
3
|
+
Cloud-only client: assessments execute on existing platform workers. Prepare Project,
|
|
4
|
+
authorized Target and published Suite on the platform first. No backend, DB, Redis,
|
|
5
|
+
MinIO or LLM key is required on the client. No registry release is authorized.
|
|
6
|
+
|
|
7
|
+
Build/install with Python 3.12 (from repository root):
|
|
8
|
+
|
|
9
|
+
```text
|
|
10
|
+
python -m pip install build
|
|
11
|
+
python -m build --wheel cli
|
|
12
|
+
python -m pip install cli/dist/probegate_cli-0.1.0-py3-none-any.whl
|
|
13
|
+
probegate --help
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Development/checks: `python -m pip install -e "cli[test]"`, then `make lint` and
|
|
17
|
+
`make test`. Existing root tests remain enabled. `PYTHON` selects the interpreter;
|
|
18
|
+
`PYTEST_ARGS` supplies optional pytest arguments. GNU Make is needed for make commands.
|
|
19
|
+
|
|
20
|
+
```text
|
|
21
|
+
probegate login --platform https://assessment.example --email qa@example.org
|
|
22
|
+
probegate init --project <uuid> --target <uuid> --suite <uuid> --suite-version 1.0 --category QUALITY --overwrite
|
|
23
|
+
probegate run --mode pipeline --max-requests 20 --timeout-s 120 --yes --json
|
|
24
|
+
probegate run --mode agent --max-requests 10 --timeout-s 120 --max-steps 10 --max-tokens 2000 --yes --json
|
|
25
|
+
probegate watch --run <uuid>
|
|
26
|
+
probegate watch --run <uuid> --once --json
|
|
27
|
+
probegate findings --run <uuid> --json
|
|
28
|
+
probegate stop --run <uuid> --yes --json
|
|
29
|
+
probegate report --run <uuid> --format json --output report.json --json
|
|
30
|
+
probegate report --run <uuid> --format html --output report.html
|
|
31
|
+
probegate logout
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`--platform` is an origin, without `/api/v1`; the client adds that existing prefix.
|
|
35
|
+
Remote origins require HTTPS. HTTP is accepted only for explicit localhost/127.0.0.1/::1
|
|
36
|
+
origins. TLS verification stays enabled. Redirects and ambient HTTP proxy configuration
|
|
37
|
+
are disabled, so bearer credentials cannot be forwarded to a redirected origin.
|
|
38
|
+
|
|
39
|
+
Passwords are prompted with hidden input, never accepted as arguments. Native Windows
|
|
40
|
+
Credential Manager and Linux Secret Service are supported secure stores. A missing,
|
|
41
|
+
locked or unsupported backend fails loudly. There is no plaintext fallback. An explicit
|
|
42
|
+
`PROBEGATE_TOKEN` overrides the saved token; logout cannot unset it in the parent shell
|
|
43
|
+
or revoke the JWT server-side. A saved token is scoped to platform origin and account.
|
|
44
|
+
Use `PROBEGATE_ACCOUNT` or `init --account` to select an account for data commands.
|
|
45
|
+
|
|
46
|
+
Config contains non-secret defaults only. Paths default to platformdirs user config/state
|
|
47
|
+
locations. Override them with `PROBEGATE_CONFIG` (file) and `PROBEGATE_STATE_DIR` (directory).
|
|
48
|
+
Configuration precedence is flags > `PROBEGATE_PLATFORM`/`PROBEGATE_ACCOUNT` > config.
|
|
49
|
+
Resource IDs, category, version and polling interval come from flags/config; resource-ID
|
|
50
|
+
environment variables are not supported. Poll interval defaults to 2 seconds and may be
|
|
51
|
+
changed by `init --polling-interval` or `watch --interval` (0.2–60 seconds).
|
|
52
|
+
Malformed config fails; repair it or select a new config file. `init` replaces existing
|
|
53
|
+
config only after interactive confirmation or `--overwrite`.
|
|
54
|
+
|
|
55
|
+
Run budgets are mandatory. Each invocation creates one PIPELINE or independent AGENT
|
|
56
|
+
run. Project defaults are explicitly disabled (`use_project_defaults:false`), so they
|
|
57
|
+
cannot silently add strategies/rubric/profile. Agent uses the server's documented
|
|
58
|
+
strategy defaults; this CLI does not expose custom strategies or pipeline_first.
|
|
59
|
+
Confirmation displays the exact request plus Project ID. Noninteractive submission
|
|
60
|
+
and stop require `--yes`. Target authorization, suite publication, tenant/RBAC and
|
|
61
|
+
execution limits continue to be enforced by the backend and worker.
|
|
62
|
+
|
|
63
|
+
Before creating a run, the client writes an atomic non-secret intent containing UUID,
|
|
64
|
+
origin, Project, idempotency key, exact body, timestamp and nullable run ID. If POST loses
|
|
65
|
+
its response, keep that intent and resume explicitly:
|
|
66
|
+
|
|
67
|
+
```text
|
|
68
|
+
probegate run --resume-intent <intent-uuid> --yes --json
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Select the original origin through config or `PROBEGATE_PLATFORM`; resume forbids
|
|
72
|
+
all origin/payload flags. It reuses the saved Project/body/key. If the run ID was
|
|
73
|
+
already saved, it returns that ID without POST. If response persistence failed after
|
|
74
|
+
creation, resubmitting the same intent still recovers the server run. Never edit a
|
|
75
|
+
journal to create a new payload or remove it while recovering. Same key/different body
|
|
76
|
+
is a backend 409. POSTs never automatically retry. Auth failures require explicit login
|
|
77
|
+
and explicit retry; the client never replays writes after login automatically.
|
|
78
|
+
|
|
79
|
+
GET retries transport errors, 5xx and 429 at most three times after the initial attempt.
|
|
80
|
+
Delays are 1/2/4 seconds; Retry-After seconds/date is capped at 30 seconds per retry.
|
|
81
|
+
Other HTTP errors do not retry. Each HTTP request has a 15 second timeout, separate
|
|
82
|
+
from the run's worker execution timeout. Watch exits after exhausted retries without
|
|
83
|
+
changing server state. Ctrl+C detaches (130) and prints attach/stop instructions.
|
|
84
|
+
|
|
85
|
+
Agent progress means reserved steps, and remaining means unused capacity. COMPLETED
|
|
86
|
+
does not imply PASS. Finding states remain server-owned; pending findings are not
|
|
87
|
+
confirmed bugs. Status does not depend on findings/report permissions. Stop verifies
|
|
88
|
+
the current server status; an unverified stop request fails with guidance to watch.
|
|
89
|
+
|
|
90
|
+
All terminal output is plain, without animation or markup interpretation. Data commands
|
|
91
|
+
accept `--json`: one complete document on stdout, diagnostics on stderr. Watch JSON
|
|
92
|
+
waits for terminal status unless `--once` is selected. Report JSON stdout retains the
|
|
93
|
+
original report schema; files always retain exact server response bytes.
|
|
94
|
+
Downloads validate media type/JSON schema_version 1.0 before atomic publication.
|
|
95
|
+
Existing files require `--overwrite`; failed downloads keep any previous destination.
|
|
96
|
+
Files are not opened automatically. Reports may contain sensitive redacted evidence;
|
|
97
|
+
protect and share downloaded files under your organization's rules.
|
|
98
|
+
|
|
99
|
+
Exit codes: 0 successful operation/COMPLETED (even with FAIL findings); 1 API/auth/network,
|
|
100
|
+
local I/O, invalid server report or FAILED; 2 invalid parameters/config; 3 STOPPED;
|
|
101
|
+
130 interrupted watch. Stop returning STOPPED also exits 3. No quality gate exit policy.
|
|
102
|
+
|
|
103
|
+
Evidence and limitations: [verification](../docs/qa/cli-platform/verification.md),
|
|
104
|
+
[contract review](../docs/specs/cli-platform/review.md). Windows and Ubuntu WSL wheel
|
|
105
|
+
checks do not certify staging, a native Linux desktop credential store or all Linux
|
|
106
|
+
systems. Local runner, extension and CI gate remain outside scope.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=75"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "probegate-cli"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Internal cloud assessment platform CLI"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.12"
|
|
11
|
+
dependencies = ["typer==0.27.2", "rich==15.0.0", "httpx==0.28.1", "pydantic==2.14.3", "keyring==25.7.0", "platformdirs==4.5.1"]
|
|
12
|
+
|
|
13
|
+
[project.optional-dependencies]
|
|
14
|
+
test = ["pytest>=8,<10", "ruff>=0.11,<1", "build>=1,<2"]
|
|
15
|
+
|
|
16
|
+
[project.scripts]
|
|
17
|
+
probegate = "probegate_cli.main:app"
|
|
18
|
+
|
|
19
|
+
[tool.setuptools.packages.find]
|
|
20
|
+
where = ["src"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Internal client for the assessment platform; execution stays on workers."""
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Bounded platform HTTP client; POSTs are never automatically replayed."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import time
|
|
5
|
+
from datetime import UTC, datetime
|
|
6
|
+
from email.utils import parsedate_to_datetime
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from probegate_cli.config import CliError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Api:
|
|
14
|
+
"""Call only the selected origin's existing /api/v1 endpoints."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, platform: str, token: str | None = None):
|
|
17
|
+
"""Use TLS verification, finite timeouts and no redirects or ambient proxy credentials."""
|
|
18
|
+
self.client = httpx.Client(
|
|
19
|
+
base_url=platform + "/api/v1/",
|
|
20
|
+
timeout=15,
|
|
21
|
+
follow_redirects=False,
|
|
22
|
+
trust_env=False,
|
|
23
|
+
headers={"Authorization": f"Bearer {token}"} if token else {},
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
def __enter__(self):
|
|
27
|
+
"""Manage the connection pool for one command."""
|
|
28
|
+
return self
|
|
29
|
+
|
|
30
|
+
def __exit__(self, *args):
|
|
31
|
+
"""Close all pooled connections even when a command fails."""
|
|
32
|
+
self.client.close()
|
|
33
|
+
|
|
34
|
+
def request(self, method: str, path: str, **kwargs) -> httpx.Response:
|
|
35
|
+
"""Retry GET transport/5xx/429 failures at most three times; sanitize all errors."""
|
|
36
|
+
for attempt in range(4):
|
|
37
|
+
try:
|
|
38
|
+
response = self.client.request(method, path, **kwargs)
|
|
39
|
+
except httpx.HTTPError:
|
|
40
|
+
if method == "GET" and attempt < 3:
|
|
41
|
+
time.sleep(2**attempt)
|
|
42
|
+
continue
|
|
43
|
+
raise CliError("Network error; server state is unknown.") from None
|
|
44
|
+
if method == "GET" and (response.status_code >= 500 or response.status_code == 429) and attempt < 3:
|
|
45
|
+
delay = 2**attempt
|
|
46
|
+
if response.status_code == 429:
|
|
47
|
+
raw = response.headers.get("Retry-After", "")
|
|
48
|
+
if raw.isdigit():
|
|
49
|
+
delay = min(30, int(raw)) if len(raw) < 10 else 30
|
|
50
|
+
else:
|
|
51
|
+
try:
|
|
52
|
+
delay = max(0, min(30, (parsedate_to_datetime(raw) - datetime.now(UTC)).total_seconds()))
|
|
53
|
+
except (ValueError, TypeError, OverflowError):
|
|
54
|
+
delay = 30
|
|
55
|
+
time.sleep(delay)
|
|
56
|
+
continue
|
|
57
|
+
if not 200 <= response.status_code < 300:
|
|
58
|
+
# Never echo arbitrary server messages, request bodies, URLs or auth headers.
|
|
59
|
+
code = "api_error"
|
|
60
|
+
try:
|
|
61
|
+
candidate = response.json().get("error", "")
|
|
62
|
+
if isinstance(candidate, str) and re.fullmatch(r"[a-z_]{1,64}", candidate):
|
|
63
|
+
code = candidate
|
|
64
|
+
except (ValueError, AttributeError):
|
|
65
|
+
pass
|
|
66
|
+
raise CliError(f"HTTP {response.status_code} ({code}); check platform permissions/configuration.")
|
|
67
|
+
return response
|
|
68
|
+
raise CliError("Retry limit reached.")
|
|
69
|
+
|
|
70
|
+
def json(self, method: str, path: str, **kwargs):
|
|
71
|
+
"""Require valid JSON without printing the response on decoding failure."""
|
|
72
|
+
try:
|
|
73
|
+
return self.request(method, path, **kwargs).json()
|
|
74
|
+
except ValueError:
|
|
75
|
+
raise CliError("Platform returned invalid JSON.") from None
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Atomic local persistence and strict platform origin validation."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import tempfile
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from urllib.parse import urlsplit
|
|
8
|
+
|
|
9
|
+
from platformdirs import user_config_path, user_state_path
|
|
10
|
+
|
|
11
|
+
from probegate_cli.models import Config, Intent
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CliError(Exception):
|
|
15
|
+
"""Safe diagnostic with a documented process exit code."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, message: str, code: int = 1):
|
|
18
|
+
"""Store only a user-safe message, never a raw HTTP exception."""
|
|
19
|
+
super().__init__(message)
|
|
20
|
+
self.code = code
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def origin(value: str) -> str:
|
|
24
|
+
"""Accept HTTPS origins and explicit loopback HTTP, without URL credentials."""
|
|
25
|
+
try:
|
|
26
|
+
if any(char.isspace() or not char.isprintable() for char in value):
|
|
27
|
+
raise ValueError
|
|
28
|
+
parsed = urlsplit(value)
|
|
29
|
+
port = parsed.port
|
|
30
|
+
if (
|
|
31
|
+
parsed.scheme not in {"http", "https"}
|
|
32
|
+
or not parsed.hostname
|
|
33
|
+
or parsed.username is not None
|
|
34
|
+
or parsed.password is not None
|
|
35
|
+
or parsed.query
|
|
36
|
+
or parsed.fragment
|
|
37
|
+
or parsed.path not in {"", "/"}
|
|
38
|
+
):
|
|
39
|
+
raise ValueError
|
|
40
|
+
if parsed.scheme == "http" and parsed.hostname not in {"localhost", "127.0.0.1", "::1"}:
|
|
41
|
+
raise ValueError
|
|
42
|
+
host = parsed.hostname.lower()
|
|
43
|
+
host = f"[{host}]" if ":" in host else host
|
|
44
|
+
suffix = f":{port}" if port and port != (443 if parsed.scheme == "https" else 80) else ""
|
|
45
|
+
return f"{parsed.scheme}://{host}{suffix}"
|
|
46
|
+
except ValueError:
|
|
47
|
+
raise CliError("Platform must be an HTTPS origin (HTTP allowed only on loopback).", 2) from None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def config_path() -> Path:
|
|
51
|
+
"""Locate non-secret config, allowing an explicit isolated config file."""
|
|
52
|
+
return Path(os.environ.get("PROBEGATE_CONFIG", user_config_path("probegate") / "config.json"))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def state_path() -> Path:
|
|
56
|
+
"""Locate intent journals separately from credentials."""
|
|
57
|
+
return Path(os.environ.get("PROBEGATE_STATE_DIR", user_state_path("probegate") / "intents"))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def atomic_write(path: Path, data: bytes, overwrite: bool = True) -> None:
|
|
61
|
+
"""Publish complete bytes atomically; preserve any previous file on failure."""
|
|
62
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
63
|
+
fd, temporary = tempfile.mkstemp(prefix=".probegate-", dir=path.parent)
|
|
64
|
+
try:
|
|
65
|
+
with os.fdopen(fd, "wb") as stream:
|
|
66
|
+
stream.write(data)
|
|
67
|
+
stream.flush()
|
|
68
|
+
os.fsync(stream.fileno())
|
|
69
|
+
if overwrite:
|
|
70
|
+
os.replace(temporary, path)
|
|
71
|
+
else:
|
|
72
|
+
# Hard-link publication is atomic and refuses races with existing destinations.
|
|
73
|
+
os.link(temporary, path)
|
|
74
|
+
finally:
|
|
75
|
+
Path(temporary).unlink(missing_ok=True)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def load_config() -> Config | None:
|
|
79
|
+
"""Read config strictly and reject corrupt data without exposing its contents."""
|
|
80
|
+
path = config_path()
|
|
81
|
+
if not path.exists():
|
|
82
|
+
return None
|
|
83
|
+
try:
|
|
84
|
+
config = Config.model_validate_json(path.read_bytes())
|
|
85
|
+
config.platform_url = origin(config.platform_url)
|
|
86
|
+
return config
|
|
87
|
+
except (ValueError, OSError):
|
|
88
|
+
raise CliError("Invalid or unreadable config; repair it or select PROBEGATE_CONFIG.", 2) from None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def save_config(config: Config) -> None:
|
|
92
|
+
"""Persist only validated non-secret defaults."""
|
|
93
|
+
atomic_write(config_path(), config.model_dump_json(indent=2).encode())
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def save_intent(intent: Intent, overwrite: bool = True) -> None:
|
|
97
|
+
"""Persist a validated request before any network mutation."""
|
|
98
|
+
atomic_write(state_path() / f"{intent.id}.json", intent.model_dump_json(indent=2).encode(), overwrite)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def load_intent(identifier) -> Intent:
|
|
102
|
+
"""Load an exact intent by UUID, refusing arbitrary filesystem paths."""
|
|
103
|
+
try:
|
|
104
|
+
from uuid import UUID
|
|
105
|
+
|
|
106
|
+
intent = Intent.model_validate_json((state_path() / f"{UUID(str(identifier))}.json").read_bytes())
|
|
107
|
+
if str(intent.id) != str(identifier) or origin(intent.platform_url) != intent.platform_url:
|
|
108
|
+
raise ValueError
|
|
109
|
+
return intent
|
|
110
|
+
except (ValueError, OSError):
|
|
111
|
+
raise CliError("Invalid or unreadable intent.", 2) from None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def json_bytes(value) -> bytes:
|
|
115
|
+
"""Encode deterministic JSON without terminal formatting."""
|
|
116
|
+
return json.dumps(value, ensure_ascii=True, sort_keys=True).encode()
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Credential store access without plaintext or insecure backend fallback."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
import keyring
|
|
6
|
+
from keyring.errors import KeyringError, PasswordDeleteError
|
|
7
|
+
|
|
8
|
+
from probegate_cli.config import CliError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def service(platform: str) -> str:
|
|
12
|
+
"""Bind credentials to a normalized origin and this CLI."""
|
|
13
|
+
return f"probegate:{platform}"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def secure_backend():
|
|
17
|
+
"""Allow only native OS stores or the Linux Secret Service implementation."""
|
|
18
|
+
try:
|
|
19
|
+
backend = keyring.get_keyring()
|
|
20
|
+
except (KeyringError, RuntimeError):
|
|
21
|
+
raise CliError("OS credential store unavailable.") from None
|
|
22
|
+
module = type(backend).__module__
|
|
23
|
+
if module not in {"keyring.backends.Windows", "keyring.backends.macOS", "keyring.backends.SecretService"}:
|
|
24
|
+
raise CliError("No supported secure keyring; configure an OS store or explicitly set PROBEGATE_TOKEN.")
|
|
25
|
+
return backend
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def token(platform: str, account: str | None) -> str:
|
|
29
|
+
"""Prefer an explicit environment token; otherwise read the selected OS account."""
|
|
30
|
+
value = os.environ.get("PROBEGATE_TOKEN")
|
|
31
|
+
if value is not None:
|
|
32
|
+
if not value.strip() or any(char.isspace() for char in value):
|
|
33
|
+
raise CliError("Invalid PROBEGATE_TOKEN.", 2)
|
|
34
|
+
return value
|
|
35
|
+
if not account:
|
|
36
|
+
raise CliError("Login first or explicitly set PROBEGATE_TOKEN.")
|
|
37
|
+
try:
|
|
38
|
+
value = secure_backend().get_password(service(platform), account)
|
|
39
|
+
except (KeyringError, RuntimeError):
|
|
40
|
+
raise CliError("OS credential store unavailable; unlock it or explicitly set PROBEGATE_TOKEN.") from None
|
|
41
|
+
if not value:
|
|
42
|
+
raise CliError("No saved credential; login again.")
|
|
43
|
+
return value
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def store(platform: str, account: str, value: str) -> None:
|
|
47
|
+
"""Save only the token in a native credential store."""
|
|
48
|
+
try:
|
|
49
|
+
secure_backend().set_password(service(platform), account, value)
|
|
50
|
+
except (KeyringError, RuntimeError):
|
|
51
|
+
raise CliError("Could not save token securely; no plaintext fallback is available.") from None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def remove(platform: str, account: str) -> None:
|
|
55
|
+
"""Remove the selected stored credential without claiming JWT revocation."""
|
|
56
|
+
try:
|
|
57
|
+
backend = secure_backend()
|
|
58
|
+
if backend.get_password(service(platform), account) is not None:
|
|
59
|
+
backend.delete_password(service(platform), account)
|
|
60
|
+
except PasswordDeleteError:
|
|
61
|
+
raise CliError("Credential deletion failed; check the OS store.") from None
|
|
62
|
+
except (KeyringError, RuntimeError):
|
|
63
|
+
raise CliError("OS credential store unavailable; credential deletion was not verified.") from None
|