previty-cli 0.1.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.
previty_cli/config.py ADDED
@@ -0,0 +1,200 @@
1
+ """Credentials file, API URL and key resolution, host allowlist."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import os
8
+ import stat
9
+ import sys
10
+ import tempfile
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Any
14
+ from urllib.parse import urlsplit
15
+
16
+ from previty_cli.errors import UsageError
17
+ from previty_cli.redact import register_secret
18
+
19
+ DEFAULT_API_URL = "https://api.previty.de/public/v1"
20
+ ALLOWED_HOSTS = frozenset({"api.previty.de", "api.dev.previty.de"})
21
+ LOCAL_HOSTS = frozenset({"localhost", "127.0.0.1"})
22
+ KEY_PREFIX = "prv_"
23
+
24
+ ENV_API_KEY = "PREVITY_API_KEY"
25
+ ENV_API_URL = "PREVITY_API_URL"
26
+ ENV_CONFIG_DIR = "PREVITY_CONFIG_DIR"
27
+ ENV_ALLOW_LOCALHOST = "PREVITY_ALLOW_INSECURE_LOCALHOST"
28
+
29
+ IS_WINDOWS = sys.platform == "win32"
30
+
31
+
32
+ def config_dir() -> Path:
33
+ """Per-user config directory (D7). Built by hand, not with platformdirs."""
34
+ override = os.environ.get(ENV_CONFIG_DIR)
35
+ if override:
36
+ return Path(override).expanduser()
37
+ if IS_WINDOWS:
38
+ appdata = os.environ.get("APPDATA")
39
+ base = Path(appdata) if appdata else Path.home() / "AppData" / "Roaming"
40
+ return base / "previty"
41
+ xdg = os.environ.get("XDG_CONFIG_HOME")
42
+ base = Path(xdg) if xdg and Path(xdg).is_absolute() else Path.home() / ".config"
43
+ return base / "previty"
44
+
45
+
46
+ def credentials_path() -> Path:
47
+ return config_dir() / "credentials.json"
48
+
49
+
50
+ def validate_key_format(key: str) -> str:
51
+ key = key.strip()
52
+ if not key:
53
+ raise UsageError("The API key is empty.")
54
+ if not key.startswith(KEY_PREFIX) or any(c.isspace() for c in key):
55
+ raise UsageError(
56
+ f"That does not look like a Previty API key (expected {KEY_PREFIX}...)."
57
+ )
58
+ return key
59
+
60
+
61
+ def validate_api_url(url: str) -> str:
62
+ """Return the normalised URL or raise a usage error (exit 2) before any request."""
63
+ try:
64
+ parts = urlsplit(url.strip())
65
+ host = parts.hostname
66
+ port = parts.port
67
+ except ValueError as exc:
68
+ raise UsageError(f"Invalid API URL: {exc}") from None
69
+ if parts.username is not None or parts.password is not None:
70
+ raise UsageError("The API URL must not contain credentials.")
71
+ if parts.query or parts.fragment:
72
+ raise UsageError("The API URL must not contain a query or fragment.")
73
+ allow_local = os.environ.get(ENV_ALLOW_LOCALHOST) == "1"
74
+ remote_ok = (
75
+ host in ALLOWED_HOSTS and parts.scheme == "https" and port in (None, 443)
76
+ )
77
+ local_ok = host in LOCAL_HOSTS and allow_local and parts.scheme in ("http", "https")
78
+ if not (remote_ok or local_ok):
79
+ hint = None
80
+ if host in LOCAL_HOSTS:
81
+ hint = f"Set {ENV_ALLOW_LOCALHOST}=1 to allow localhost for development."
82
+ raise UsageError(
83
+ f"API host not allowed: {host or url!r}. "
84
+ f"Allowed: {', '.join(sorted(ALLOWED_HOSTS))} over https.",
85
+ hint=hint,
86
+ )
87
+ return url.strip().rstrip("/")
88
+
89
+
90
+ @dataclass
91
+ class StoredCredentials:
92
+ api_url: str | None = None
93
+ api_key: str | None = None
94
+
95
+
96
+ def _warn(message: str) -> None:
97
+ print(f"Warning: {message}", file=sys.stderr)
98
+
99
+
100
+ def read_credentials(*, warn: bool = True) -> StoredCredentials:
101
+ path = credentials_path()
102
+ try:
103
+ st = path.stat()
104
+ raw = path.read_text(encoding="utf-8")
105
+ except FileNotFoundError:
106
+ return StoredCredentials()
107
+ except OSError as exc:
108
+ raise UsageError(f"Cannot read {path}: {exc.strerror or exc}") from None
109
+ if warn and not IS_WINDOWS and st.st_mode & (stat.S_IRWXG | stat.S_IRWXO):
110
+ _warn(
111
+ f"{path} is readable by other users (mode {stat.S_IMODE(st.st_mode):04o}). "
112
+ f"Run: chmod 600 {path}"
113
+ )
114
+ try:
115
+ data: Any = json.loads(raw)
116
+ except json.JSONDecodeError:
117
+ raise UsageError(
118
+ f"{path} is not valid JSON.", hint="Run `previty login` again."
119
+ ) from None
120
+ if not isinstance(data, dict):
121
+ raise UsageError(f"{path} has an unexpected format.")
122
+ key = data.get("apiKey")
123
+ url = data.get("apiUrl")
124
+ return StoredCredentials(
125
+ api_url=url if isinstance(url, str) else None,
126
+ api_key=key if isinstance(key, str) else None,
127
+ )
128
+
129
+
130
+ def write_credentials(api_url: str, api_key: str) -> Path:
131
+ """Write ``{apiUrl, apiKey}`` atomically: private temp file, then os.replace."""
132
+ directory = config_dir()
133
+ created = not directory.exists()
134
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
135
+ if created and not IS_WINDOWS:
136
+ os.chmod(directory, 0o700)
137
+ path = credentials_path()
138
+ # mkstemp creates the file with mode 0600, so the key is never written
139
+ # into a file other users could read.
140
+ fd, tmp_name = tempfile.mkstemp(dir=directory, prefix=".credentials-")
141
+ try:
142
+ if not IS_WINDOWS:
143
+ os.chmod(tmp_name, 0o600)
144
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
145
+ json.dump({"apiUrl": api_url, "apiKey": api_key}, fh, indent=2)
146
+ fh.write("\n")
147
+ fh.flush()
148
+ os.fsync(fh.fileno())
149
+ os.replace(tmp_name, path)
150
+ except BaseException:
151
+ with contextlib.suppress(OSError):
152
+ os.unlink(tmp_name)
153
+ raise
154
+ return path
155
+
156
+
157
+ def delete_credentials() -> bool:
158
+ try:
159
+ credentials_path().unlink()
160
+ except FileNotFoundError:
161
+ return False
162
+ return True
163
+
164
+
165
+ @dataclass
166
+ class Settings:
167
+ api_url: str
168
+ api_key: str | None
169
+ key_source: str # "env", "file" or "none"
170
+
171
+
172
+ def resolve_api_url(flag: str | None, stored: StoredCredentials | None = None) -> str:
173
+ """URL: flag > PREVITY_API_URL > file > default; always allowlisted."""
174
+ url = (
175
+ flag
176
+ or os.environ.get(ENV_API_URL)
177
+ or (stored.api_url if stored else None)
178
+ or DEFAULT_API_URL
179
+ )
180
+ return validate_api_url(url)
181
+
182
+
183
+ def resolve_settings(api_url_flag: str | None = None) -> Settings:
184
+ """Key: PREVITY_API_KEY > file. URL: flag > PREVITY_API_URL > file > default."""
185
+ stored = read_credentials()
186
+ env_key = os.environ.get(ENV_API_KEY)
187
+ if env_key:
188
+ key: str | None = validate_key_format(env_key)
189
+ source = "env"
190
+ elif stored.api_key:
191
+ key = stored.api_key
192
+ source = "file"
193
+ else:
194
+ key = None
195
+ source = "none"
196
+ if key:
197
+ register_secret(key)
198
+ return Settings(
199
+ api_url=resolve_api_url(api_url_flag, stored), api_key=key, key_source=source
200
+ )
previty_cli/errors.py ADDED
@@ -0,0 +1,126 @@
1
+ """Error classes and the mapping from API error codes to exit codes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from previty_cli import exit_codes
8
+ from previty_cli.redact import scrub
9
+
10
+ _CODE_EXIT: dict[str, int] = {
11
+ # 400 / 422
12
+ "IDEMPOTENCY_KEY_REQUIRED": exit_codes.USAGE,
13
+ "VALIDATION_ERROR": exit_codes.USAGE,
14
+ "IDEMPOTENCY_KEY_REUSED": exit_codes.USAGE,
15
+ # generic fallbacks of the public API
16
+ "BAD_REQUEST": exit_codes.USAGE,
17
+ "METHOD_NOT_ALLOWED": exit_codes.USAGE,
18
+ "PAYLOAD_TOO_LARGE": exit_codes.USAGE,
19
+ "CONFLICT": exit_codes.CONFLICT,
20
+ # 401 / 403 authentication
21
+ "API_KEY_REQUIRED": exit_codes.AUTH,
22
+ "INVALID_API_KEY": exit_codes.AUTH,
23
+ "API_KEY_EXPIRED": exit_codes.AUTH,
24
+ "API_ACCESS_DISABLED": exit_codes.AUTH,
25
+ "MEMBERSHIP_REMOVED": exit_codes.AUTH,
26
+ "ORGANIZATION_DELETION_PENDING": exit_codes.AUTH,
27
+ # 403 permission
28
+ "KEY_PERMISSION_MISSING": exit_codes.PERMISSION,
29
+ "NOT_APPLICATION_OWNER": exit_codes.PERMISSION,
30
+ "PERMISSION_DENIED": exit_codes.PERMISSION,
31
+ # 404
32
+ "NOT_FOUND": exit_codes.NOT_FOUND,
33
+ # 403 billing
34
+ "SUBSCRIPTION_REQUIRED": exit_codes.QUOTA,
35
+ "CHECK_LIMIT_REACHED": exit_codes.QUOTA,
36
+ # 409
37
+ "DATA_SOURCE_SYNC_FAILED": exit_codes.CONFLICT,
38
+ "NO_CODE_CHANGES": exit_codes.CONFLICT,
39
+ "CHECK_RUNNING": exit_codes.CONFLICT,
40
+ "DATA_SOURCE_SYNC_IN_PROGRESS": exit_codes.CONFLICT,
41
+ "DATA_SOURCE_NOT_OWNED": exit_codes.CONFLICT,
42
+ "DATA_SOURCE_BRANCH_UNSUPPORTED": exit_codes.CONFLICT,
43
+ "BRANCH_NOT_FOUND": exit_codes.CONFLICT,
44
+ "GITHUB_NOT_CONNECTED": exit_codes.CONFLICT,
45
+ "GITHUB_TOKEN_INVALID": exit_codes.CONFLICT,
46
+ "NO_ACTIVE_RULE_SET": exit_codes.CONFLICT,
47
+ "NO_DATA_SOURCE": exit_codes.CONFLICT,
48
+ "REQUEST_IN_PROGRESS": exit_codes.CONFLICT,
49
+ # 429 and the edge
50
+ "RATE_LIMITED": exit_codes.RATE_LIMITED,
51
+ "BLOCKED_BY_EDGE": exit_codes.RATE_LIMITED,
52
+ # 5xx
53
+ "INTERNAL_ERROR": exit_codes.GENERAL,
54
+ "SERVICE_UNAVAILABLE": exit_codes.GENERAL,
55
+ }
56
+
57
+ _STATUS_EXIT: dict[int, int] = {
58
+ 400: exit_codes.USAGE,
59
+ 401: exit_codes.AUTH,
60
+ 403: exit_codes.PERMISSION,
61
+ 404: exit_codes.NOT_FOUND,
62
+ 409: exit_codes.CONFLICT,
63
+ 422: exit_codes.USAGE,
64
+ 429: exit_codes.RATE_LIMITED,
65
+ }
66
+
67
+
68
+ def exit_code_for(code: str, status: int | None = None) -> int:
69
+ """Exit code for an API error code; unknown codes fall back to the HTTP status."""
70
+ if code in _CODE_EXIT:
71
+ return _CODE_EXIT[code]
72
+ if status is not None:
73
+ return _STATUS_EXIT.get(status, exit_codes.GENERAL)
74
+ return exit_codes.GENERAL
75
+
76
+
77
+ class PrevityError(Exception):
78
+ """Any error the CLI reports to the user. Carries a stable code and exit code."""
79
+
80
+ def __init__(
81
+ self,
82
+ code: str,
83
+ message: str,
84
+ *,
85
+ exit_code: int | None = None,
86
+ status: int | None = None,
87
+ details: Any = None,
88
+ request_id: str | None = None,
89
+ hint: str | None = None,
90
+ ) -> None:
91
+ message = scrub(message)
92
+ super().__init__(message)
93
+ self.code = code
94
+ self.message = message
95
+ self.status = status
96
+ self.details = details or None
97
+ self.request_id = request_id
98
+ self.hint = scrub(hint) if hint else hint
99
+ self.exit_code = (
100
+ exit_code if exit_code is not None else exit_code_for(code, status)
101
+ )
102
+
103
+ def to_dict(self) -> dict[str, Any]:
104
+ body: dict[str, Any] = {"code": self.code, "message": self.message}
105
+ if self.details is not None:
106
+ body["details"] = self.details
107
+ if self.request_id:
108
+ body["requestId"] = self.request_id
109
+ if self.hint:
110
+ body["hint"] = self.hint
111
+ return {"error": body}
112
+
113
+
114
+ class UsageError(PrevityError):
115
+ def __init__(self, message: str, *, hint: str | None = None) -> None:
116
+ super().__init__("USAGE_ERROR", message, exit_code=exit_codes.USAGE, hint=hint)
117
+
118
+
119
+ class NotLoggedInError(PrevityError):
120
+ def __init__(self) -> None:
121
+ super().__init__(
122
+ "API_KEY_REQUIRED",
123
+ "No API key found.",
124
+ exit_code=exit_codes.AUTH,
125
+ hint="Run `previty login` or set PREVITY_API_KEY.",
126
+ )
@@ -0,0 +1,31 @@
1
+ """Exit codes of the CLI. Fixed for v1 (implementation plan, section 6.3)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ SUCCESS = 0
6
+ GENERAL = 1 # unexpected or server error, network failure after retries
7
+ USAGE = 2 # bad flags, would need a prompt in non-TTY, host not allowed
8
+ AUTH = 3 # no key, invalid, expired, org API access off, membership removed
9
+ PERMISSION = 4 # key scope missing, not application owner
10
+ NOT_FOUND = 5
11
+ QUOTA = 6 # CHECK_LIMIT_REACHED, SUBSCRIPTION_REQUIRED
12
+ CONFLICT = 7 # precondition or conflict, also "not ready"
13
+ WAIT_TIMEOUT = 8 # --timeout reached; the check keeps running
14
+ CHECK_FAILED = 9 # the check ended as failed
15
+ FAIL_ON = 10 # --fail-on matched findings
16
+ RATE_LIMITED = 11 # rate limited or blocked at the edge
17
+
18
+ DESCRIPTIONS: dict[int, str] = {
19
+ SUCCESS: "Success",
20
+ GENERAL: "Unexpected or server error, network failure after retries",
21
+ USAGE: "Usage error (bad flags, prompt needed without a terminal, host not allowed)",
22
+ AUTH: "Authentication (no key, invalid, expired, API access off, membership removed)",
23
+ PERMISSION: "Permission (key scope missing, not application owner)",
24
+ NOT_FOUND: "Not found",
25
+ QUOTA: "Quota or billing (CHECK_LIMIT_REACHED, SUBSCRIPTION_REQUIRED)",
26
+ CONFLICT: "Precondition or conflict (sync failed, no changes, check running, branch errors, not ready)",
27
+ WAIT_TIMEOUT: "Wait timeout (--timeout); the check keeps running",
28
+ CHECK_FAILED: "The check ended as failed",
29
+ FAIL_ON: "--fail-on matched findings",
30
+ RATE_LIMITED: "Rate limited or blocked at the edge",
31
+ }
@@ -0,0 +1,44 @@
1
+ """Output helpers shared by all commands.
2
+
3
+ Rich is imported lazily (only for terminal output); JSON never goes through it.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ import sys
10
+ from typing import TYPE_CHECKING
11
+
12
+ if TYPE_CHECKING:
13
+ from rich.console import Console
14
+
15
+ _CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]")
16
+
17
+
18
+ def is_stdout_tty() -> bool:
19
+ return sys.stdout.isatty()
20
+
21
+
22
+ def is_stdin_tty() -> bool:
23
+ return sys.stdin.isatty()
24
+
25
+
26
+ def is_stderr_tty() -> bool:
27
+ return sys.stderr.isatty()
28
+
29
+
30
+ def clean(value: object) -> str:
31
+ """Strip terminal control characters (e.g. ANSI escapes) from server text."""
32
+ return _CONTROL.sub("", str(value))
33
+
34
+
35
+ def make_console(*, no_color: bool = False, stderr: bool = False) -> Console:
36
+ from rich.console import Console
37
+
38
+ return Console(
39
+ stderr=stderr,
40
+ no_color=no_color or None,
41
+ highlight=False,
42
+ markup=False,
43
+ emoji=False,
44
+ )
@@ -0,0 +1,24 @@
1
+ """JSON output: ``json.dumps`` straight to stdout, never through Rich."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+ from typing import Any
8
+
9
+
10
+ def dumps(data: Any) -> str:
11
+ return json.dumps({"data": data}, indent=2, ensure_ascii=False)
12
+
13
+
14
+ def emit(data: Any) -> None:
15
+ sys.stdout.write(dumps(data) + "\n")
16
+ sys.stdout.flush()
17
+
18
+
19
+ def emit_error(error: dict[str, Any]) -> None:
20
+ """Error object on stderr so stdout stays parseable."""
21
+ from previty_cli.redact import scrub
22
+
23
+ sys.stderr.write(scrub(json.dumps(error, ensure_ascii=False)) + "\n")
24
+ sys.stderr.flush()
@@ -0,0 +1,70 @@
1
+ """Markdown rendering of findings (``previty results --format markdown``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from previty_cli.api import models as m
6
+ from previty_cli.output import clean
7
+
8
+ _LABEL = {
9
+ "fail_critical": "FAIL (critical)",
10
+ "fail": "FAIL",
11
+ "unclear": "UNCLEAR",
12
+ "out_of_scope": "OUT OF SCOPE",
13
+ "pass": "PASS",
14
+ }
15
+
16
+
17
+ def _quote(text: str) -> str:
18
+ return "\n".join(f"> {line}" for line in clean(text).splitlines() or [""])
19
+
20
+
21
+ def render_results(data: m.PublicFindingList) -> str:
22
+ out = [
23
+ f"# Results: {clean(data.check_name)}",
24
+ "",
25
+ f"Application: {clean(data.application_name)} ({data.application_id}) ",
26
+ f"Check: {clean(data.check_name)} ({data.check_id}) ",
27
+ f"Findings: {len(data.items)} of {data.total}",
28
+ "",
29
+ f"_{clean(data.content_notice)}_",
30
+ "",
31
+ ]
32
+ for f in data.items:
33
+ req = f.requirement
34
+ out.append(
35
+ f"## {_LABEL.get(f.status.value, f.status.value.upper())}: "
36
+ f"{clean((f.model_output.title if f.model_output else None) or (req.title if req else None) or f.id)}"
37
+ )
38
+ out.append("")
39
+ if req:
40
+ where = " / ".join(
41
+ clean(p) for p in (req.policy_set_name, req.section, req.title) if p
42
+ )
43
+ sev = f" (severity: {clean(req.severity)})" if req.severity else ""
44
+ out.append(f"- Requirement: {where}{sev}")
45
+ if req.text:
46
+ out.append("")
47
+ out.append(_quote(req.text))
48
+ out.append(f"- Finding ID: {f.id}")
49
+ mo = f.model_output
50
+ if mo and mo.explanation:
51
+ out += [
52
+ "",
53
+ "**Explanation (untrusted model output)**",
54
+ "",
55
+ _quote(mo.explanation),
56
+ ]
57
+ if mo and mo.suggested_fix:
58
+ out += [
59
+ "",
60
+ "**Suggested fix (untrusted model output)**",
61
+ "",
62
+ _quote(mo.suggested_fix),
63
+ ]
64
+ if f.check_error:
65
+ out += [
66
+ "",
67
+ f"Check error: {clean(f.check_error.code)} {clean(f.check_error.message or '')}",
68
+ ]
69
+ out.append("")
70
+ return "\n".join(out).rstrip() + "\n"