brava-cli 0.3.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.
- brava_cli/__init__.py +0 -0
- brava_cli/__main__.py +6 -0
- brava_cli/app.py +626 -0
- brava_cli/auth.py +37 -0
- brava_cli/client.py +281 -0
- brava_cli/context.py +173 -0
- brava_cli/duration.py +23 -0
- brava_cli/environments.py +113 -0
- brava_cli/hygiene.py +342 -0
- brava_cli/hygiene_results.py +84 -0
- brava_cli/siems.py +29 -0
- brava_cli/types.py +26 -0
- brava_cli-0.3.0.dist-info/METADATA +36 -0
- brava_cli-0.3.0.dist-info/RECORD +16 -0
- brava_cli-0.3.0.dist-info/WHEEL +4 -0
- brava_cli-0.3.0.dist-info/entry_points.txt +2 -0
brava_cli/client.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""HTTP client for the Brava platform API (via BFF)."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from typing import Any, Literal, overload
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
|
|
8
|
+
from brava_cli.types import Snapshot, as_dicts
|
|
9
|
+
|
|
10
|
+
# Friendly messages for attack-simulation error codes returned as
|
|
11
|
+
# ``{errorCode, message}``. Keep in sync with the API's error codes.
|
|
12
|
+
GOAL_RUN_ERROR_MESSAGES: dict[int, str] = {
|
|
13
|
+
1008: "Run not found.",
|
|
14
|
+
1017: "Runner immediate queue is not configured; live control is unavailable.",
|
|
15
|
+
1023: "Cannot change interactivity for a completed run.",
|
|
16
|
+
1024: "Run is no longer waiting for review (it may have been approved or moved on).",
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _format_http_error(exc: httpx.HTTPStatusError) -> str:
|
|
21
|
+
response = exc.response
|
|
22
|
+
try:
|
|
23
|
+
parsed: Snapshot = response.json()
|
|
24
|
+
except ValueError:
|
|
25
|
+
return f"HTTP {response.status_code}: {response.text}"
|
|
26
|
+
if isinstance(parsed, dict):
|
|
27
|
+
code = parsed.get("errorCode")
|
|
28
|
+
mapped = GOAL_RUN_ERROR_MESSAGES.get(code) if isinstance(code, int) else None
|
|
29
|
+
message = mapped or parsed.get("message")
|
|
30
|
+
if isinstance(message, str) and message:
|
|
31
|
+
return f"Error (HTTP {response.status_code}): {message}"
|
|
32
|
+
return f"HTTP {response.status_code}: {response.text}"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _object(value: Snapshot) -> dict[str, object]:
|
|
36
|
+
if isinstance(value, dict):
|
|
37
|
+
return value
|
|
38
|
+
sys.exit(f"Unexpected response: {value!r}")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class BravaClient:
|
|
42
|
+
"""Authenticated HTTP client for the Brava BFF."""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self, url: str, token: str, transport: httpx.BaseTransport | None = None
|
|
46
|
+
) -> None:
|
|
47
|
+
self._http = httpx.Client(
|
|
48
|
+
base_url=url.rstrip("/"),
|
|
49
|
+
headers={
|
|
50
|
+
"Authorization": f"Bearer {token}",
|
|
51
|
+
"Content-Type": "application/json",
|
|
52
|
+
},
|
|
53
|
+
timeout=30.0,
|
|
54
|
+
transport=transport,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
def _request(
|
|
58
|
+
self, method: str, path: str, passthrough: tuple[int, ...] = (), **kwargs: Any
|
|
59
|
+
) -> Snapshot:
|
|
60
|
+
try:
|
|
61
|
+
response = self._http.request(method, path, **kwargs)
|
|
62
|
+
response.raise_for_status()
|
|
63
|
+
except httpx.HTTPStatusError as exc:
|
|
64
|
+
if exc.response.status_code in passthrough:
|
|
65
|
+
raise
|
|
66
|
+
sys.exit(_format_http_error(exc))
|
|
67
|
+
except httpx.RequestError as exc:
|
|
68
|
+
sys.exit(f"Request failed: {exc}")
|
|
69
|
+
# Accepted (202) control actions return an empty body.
|
|
70
|
+
if not response.content:
|
|
71
|
+
return {}
|
|
72
|
+
return response.json()
|
|
73
|
+
|
|
74
|
+
def _get(self, path: str, params: dict[str, Any] | None = None) -> Snapshot:
|
|
75
|
+
return self._request("GET", path, params=params)
|
|
76
|
+
|
|
77
|
+
def _post(self, path: str, body: dict[str, Any]) -> Snapshot:
|
|
78
|
+
return self._request("POST", path, json=body)
|
|
79
|
+
|
|
80
|
+
# --- simulation catalog (via BFF) ---
|
|
81
|
+
|
|
82
|
+
def list_simulations(
|
|
83
|
+
self,
|
|
84
|
+
search: str | None = None,
|
|
85
|
+
offset: int | None = None,
|
|
86
|
+
limit: int | None = None,
|
|
87
|
+
) -> Snapshot:
|
|
88
|
+
params: dict[str, Any] = {}
|
|
89
|
+
if search is not None:
|
|
90
|
+
params["search"] = search
|
|
91
|
+
if offset is not None:
|
|
92
|
+
params["offset"] = offset
|
|
93
|
+
if limit is not None:
|
|
94
|
+
params["limit"] = limit
|
|
95
|
+
return self._get("/api/v1/attack-simulation/simulation", params or None)
|
|
96
|
+
|
|
97
|
+
def get_simulation(self, id: str) -> Snapshot:
|
|
98
|
+
return self._get(f"/api/v1/attack-simulation/simulation/{id}")
|
|
99
|
+
|
|
100
|
+
# --- simulation runs (via BFF) ---
|
|
101
|
+
|
|
102
|
+
def create_run(
|
|
103
|
+
self,
|
|
104
|
+
simulation_id: str,
|
|
105
|
+
account_id: str,
|
|
106
|
+
region: str,
|
|
107
|
+
params: dict[str, Any] | None = None,
|
|
108
|
+
) -> Snapshot:
|
|
109
|
+
body: dict[str, Any] = {
|
|
110
|
+
"simulationMetadataId": simulation_id,
|
|
111
|
+
"targetAccountId": account_id,
|
|
112
|
+
"targetRegion": region,
|
|
113
|
+
}
|
|
114
|
+
if params is not None:
|
|
115
|
+
body["params"] = params
|
|
116
|
+
return self._post("/api/v1/attack-simulation/simulation-run", body)
|
|
117
|
+
|
|
118
|
+
def list_runs(
|
|
119
|
+
self,
|
|
120
|
+
account_id: str | None = None,
|
|
121
|
+
offset: int | None = None,
|
|
122
|
+
limit: int | None = None,
|
|
123
|
+
) -> Snapshot:
|
|
124
|
+
params: dict[str, Any] = {}
|
|
125
|
+
if account_id is not None:
|
|
126
|
+
params["accountId"] = account_id
|
|
127
|
+
if offset is not None:
|
|
128
|
+
params["offset"] = offset
|
|
129
|
+
if limit is not None:
|
|
130
|
+
params["limit"] = limit
|
|
131
|
+
return self._get("/api/v1/attack-simulation/simulation-run", params or None)
|
|
132
|
+
|
|
133
|
+
def get_run(self, id: str) -> Snapshot:
|
|
134
|
+
return self._get(f"/api/v1/attack-simulation/simulation-run/{id}")
|
|
135
|
+
|
|
136
|
+
# --- describe-goal runs (via BFF) ---
|
|
137
|
+
|
|
138
|
+
def create_goal_run(
|
|
139
|
+
self,
|
|
140
|
+
goal: str,
|
|
141
|
+
account_id: str,
|
|
142
|
+
region: str,
|
|
143
|
+
interactive: bool,
|
|
144
|
+
profile_identifier: str | None = None,
|
|
145
|
+
) -> Snapshot:
|
|
146
|
+
body: dict[str, Any] = {
|
|
147
|
+
"goal": goal,
|
|
148
|
+
"targetAccountId": account_id,
|
|
149
|
+
"targetRegion": region,
|
|
150
|
+
"interactive": interactive,
|
|
151
|
+
}
|
|
152
|
+
if profile_identifier is not None:
|
|
153
|
+
body["profileIdentifier"] = profile_identifier
|
|
154
|
+
return self._post("/api/v1/attack-simulation/describe-goal-run", body)
|
|
155
|
+
|
|
156
|
+
def approve_goal_run(self, id: str) -> Snapshot:
|
|
157
|
+
return self._post(
|
|
158
|
+
f"/api/v1/attack-simulation/describe-goal-run/{id}/approve", {}
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
def submit_goal_feedback(self, id: str, message: str) -> Snapshot:
|
|
162
|
+
return self._post(
|
|
163
|
+
f"/api/v1/attack-simulation/describe-goal-run/{id}/feedback",
|
|
164
|
+
{"message": message},
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
def set_goal_interactivity(self, id: str, interactive: bool) -> Snapshot:
|
|
168
|
+
return self._post(
|
|
169
|
+
f"/api/v1/attack-simulation/describe-goal-run/{id}/interactivity",
|
|
170
|
+
{"interactive": interactive},
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
def list_goal_runs(
|
|
174
|
+
self,
|
|
175
|
+
account_id: str | None = None,
|
|
176
|
+
offset: int | None = None,
|
|
177
|
+
limit: int | None = None,
|
|
178
|
+
) -> Snapshot:
|
|
179
|
+
params: dict[str, Any] = {}
|
|
180
|
+
if account_id is not None:
|
|
181
|
+
params["accountId"] = account_id
|
|
182
|
+
if offset is not None:
|
|
183
|
+
params["offset"] = offset
|
|
184
|
+
if limit is not None:
|
|
185
|
+
params["limit"] = limit
|
|
186
|
+
return self._get("/api/v1/attack-simulation/describe-goal-run", params or None)
|
|
187
|
+
|
|
188
|
+
def get_goal_run(self, id: str) -> Snapshot:
|
|
189
|
+
return self._get(f"/api/v1/attack-simulation/describe-goal-run/{id}")
|
|
190
|
+
|
|
191
|
+
# --- environments (via BFF) ---
|
|
192
|
+
|
|
193
|
+
@overload
|
|
194
|
+
def list_environments(
|
|
195
|
+
self,
|
|
196
|
+
type: str | None = None,
|
|
197
|
+
is_active: bool | None = None,
|
|
198
|
+
*,
|
|
199
|
+
forbidden_ok: Literal[False] = False,
|
|
200
|
+
) -> Snapshot: ...
|
|
201
|
+
@overload
|
|
202
|
+
def list_environments(
|
|
203
|
+
self,
|
|
204
|
+
type: str | None = None,
|
|
205
|
+
is_active: bool | None = None,
|
|
206
|
+
*,
|
|
207
|
+
forbidden_ok: bool,
|
|
208
|
+
) -> Snapshot | None: ...
|
|
209
|
+
def list_environments(
|
|
210
|
+
self,
|
|
211
|
+
type: str | None = None,
|
|
212
|
+
is_active: bool | None = None,
|
|
213
|
+
*,
|
|
214
|
+
forbidden_ok: bool = False,
|
|
215
|
+
) -> Snapshot | None:
|
|
216
|
+
"""List cloud environments for the tenant.
|
|
217
|
+
|
|
218
|
+
Returns every environment row (orgs and accounts, top-level and nested);
|
|
219
|
+
the caller filters locally. Used to resolve a friendly account
|
|
220
|
+
identifier (cloud account id / name) to its Brava environment UUID.
|
|
221
|
+
With ``forbidden_ok``, an HTTP 403 returns ``None`` instead of exiting.
|
|
222
|
+
"""
|
|
223
|
+
params: dict[str, Any] = {}
|
|
224
|
+
if type is not None:
|
|
225
|
+
params["type"] = type
|
|
226
|
+
if is_active is not None:
|
|
227
|
+
params["isActive"] = is_active
|
|
228
|
+
try:
|
|
229
|
+
return self._request(
|
|
230
|
+
"GET",
|
|
231
|
+
"/api/v1/environment",
|
|
232
|
+
passthrough=(403,) if forbidden_ok else (),
|
|
233
|
+
params=params or None,
|
|
234
|
+
)
|
|
235
|
+
except httpx.HTTPStatusError:
|
|
236
|
+
return None
|
|
237
|
+
|
|
238
|
+
# --- hygiene (via BFF) ---
|
|
239
|
+
|
|
240
|
+
def list_siems(self) -> list[dict[str, object]]:
|
|
241
|
+
result = self._get("/api/v1/public/hygiene/siems")
|
|
242
|
+
return as_dicts(result.get("data")) if isinstance(result, dict) else []
|
|
243
|
+
|
|
244
|
+
def start_detection_test(
|
|
245
|
+
self, integration_id: str, rule: str, inject: bool
|
|
246
|
+
) -> dict[str, object]:
|
|
247
|
+
"""Raises ``httpx.HTTPStatusError`` on 409 so callers can retry."""
|
|
248
|
+
return _object(
|
|
249
|
+
self._request(
|
|
250
|
+
"POST",
|
|
251
|
+
"/api/v1/hygiene/detection-test/telemetry",
|
|
252
|
+
passthrough=(httpx.codes.CONFLICT,),
|
|
253
|
+
json={
|
|
254
|
+
"ruleId": rule,
|
|
255
|
+
"integrationId": integration_id,
|
|
256
|
+
"inject": inject,
|
|
257
|
+
},
|
|
258
|
+
)
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
def get_detection_test(self, test_id: str) -> dict[str, object]:
|
|
262
|
+
return _object(self._get(f"/api/v1/hygiene/detection-test/{test_id}"))
|
|
263
|
+
|
|
264
|
+
def start_rule_sweep(self, integration_id: str, rule: str) -> dict[str, object]:
|
|
265
|
+
"""Raises ``httpx.HTTPStatusError`` on 409 so callers can retry."""
|
|
266
|
+
return _object(
|
|
267
|
+
self._request(
|
|
268
|
+
"POST",
|
|
269
|
+
"/api/v1/hygiene/rule-sweep",
|
|
270
|
+
passthrough=(httpx.codes.CONFLICT,),
|
|
271
|
+
json={"integrationId": integration_id, "ruleId": rule},
|
|
272
|
+
)
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
def get_rule_sweep(self, run_id: str) -> dict[str, object]:
|
|
276
|
+
return _object(self._get(f"/api/v1/hygiene/rule-sweep/{run_id}"))
|
|
277
|
+
|
|
278
|
+
# --- health ---
|
|
279
|
+
|
|
280
|
+
def health(self) -> Snapshot:
|
|
281
|
+
return self._get("/api/v1/health")
|
brava_cli/context.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""CLI context with dual-mode output (Rich for TTY, JSON for CI)."""
|
|
2
|
+
|
|
3
|
+
# pyright: reportUnknownArgumentType=false, reportUnknownVariableType=false, reportUnknownMemberType=false
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
|
|
11
|
+
from rich.console import Console, RenderableType
|
|
12
|
+
from rich.panel import Panel
|
|
13
|
+
from rich.table import Table
|
|
14
|
+
from rich.text import Text
|
|
15
|
+
|
|
16
|
+
from brava_cli import auth
|
|
17
|
+
from brava_cli.client import BravaClient
|
|
18
|
+
from brava_cli.types import Snapshot
|
|
19
|
+
|
|
20
|
+
STATUS_COLORS: dict[str, str] = {
|
|
21
|
+
"planning": "yellow",
|
|
22
|
+
"executing": "blue",
|
|
23
|
+
"waiting_for_user_input": "yellow",
|
|
24
|
+
"collecting": "cyan",
|
|
25
|
+
"complete": "green",
|
|
26
|
+
"completed": "green",
|
|
27
|
+
"failed": "red",
|
|
28
|
+
"timed_out": "red",
|
|
29
|
+
"PLANNING": "yellow",
|
|
30
|
+
"EXECUTING": "blue",
|
|
31
|
+
"WAITING_FOR_USER_INPUT": "yellow",
|
|
32
|
+
"COLLECTING": "cyan",
|
|
33
|
+
"COMPLETED": "green",
|
|
34
|
+
"FAILED": "red",
|
|
35
|
+
"TIMED_OUT": "red",
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
PREFERRED_COLUMNS: list[str] = [
|
|
39
|
+
"id",
|
|
40
|
+
"cid",
|
|
41
|
+
"name",
|
|
42
|
+
"providerExternalIdentifier",
|
|
43
|
+
"isActive",
|
|
44
|
+
"status",
|
|
45
|
+
"goal",
|
|
46
|
+
"simulationMetadataId",
|
|
47
|
+
"targetAccountId",
|
|
48
|
+
"targetRegion",
|
|
49
|
+
"provider",
|
|
50
|
+
"vendorName",
|
|
51
|
+
"createdAt",
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class CliContext:
|
|
56
|
+
"""Holds the authenticated client and output mode."""
|
|
57
|
+
|
|
58
|
+
def __init__(self, client: BravaClient, json_mode: bool = False) -> None:
|
|
59
|
+
self.client = client
|
|
60
|
+
self.json_mode = json_mode or not sys.stdout.isatty()
|
|
61
|
+
self.console = Console()
|
|
62
|
+
|
|
63
|
+
def print(self, data: Snapshot) -> None:
|
|
64
|
+
if self.json_mode:
|
|
65
|
+
print(json.dumps(data, indent=2, default=str))
|
|
66
|
+
else:
|
|
67
|
+
self.console.print(self.format(data))
|
|
68
|
+
|
|
69
|
+
def format(self, data: Snapshot) -> RenderableType:
|
|
70
|
+
if isinstance(data, list):
|
|
71
|
+
return _format_list(data)
|
|
72
|
+
if "data" in data and isinstance(data["data"], list):
|
|
73
|
+
return _format_paginated(data)
|
|
74
|
+
return _format_dict(data)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def resolve_context(json_mode: bool = False) -> CliContext:
|
|
78
|
+
"""Resolve URL and token from env or stored credentials."""
|
|
79
|
+
url = os.environ.get("BRAVA_URL")
|
|
80
|
+
token = os.environ.get("BRAVA_API_TOKEN")
|
|
81
|
+
|
|
82
|
+
if not url or not token:
|
|
83
|
+
stored = auth.load_credentials()
|
|
84
|
+
if stored:
|
|
85
|
+
token = token or stored.token
|
|
86
|
+
url = url or stored.url
|
|
87
|
+
|
|
88
|
+
if not url:
|
|
89
|
+
typer.echo(
|
|
90
|
+
"Error: No Brava URL configured. Run `brava auth login` or set BRAVA_URL.",
|
|
91
|
+
err=True,
|
|
92
|
+
)
|
|
93
|
+
raise typer.Exit(1)
|
|
94
|
+
|
|
95
|
+
if not token:
|
|
96
|
+
typer.echo(
|
|
97
|
+
"Error: Not authenticated. Run `brava auth login --token <PAT>` or set BRAVA_API_TOKEN.",
|
|
98
|
+
err=True,
|
|
99
|
+
)
|
|
100
|
+
raise typer.Exit(1)
|
|
101
|
+
|
|
102
|
+
client = BravaClient(url=url, token=token)
|
|
103
|
+
return CliContext(client=client, json_mode=json_mode)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _format_list(items: list[dict[str, object] | object]) -> Table:
|
|
107
|
+
if not items:
|
|
108
|
+
return Table(title="No results")
|
|
109
|
+
|
|
110
|
+
first = items[0]
|
|
111
|
+
if not isinstance(first, dict):
|
|
112
|
+
table = Table(show_lines=False)
|
|
113
|
+
table.add_column("value")
|
|
114
|
+
for item in items:
|
|
115
|
+
table.add_row(Text(str(item)))
|
|
116
|
+
return table
|
|
117
|
+
|
|
118
|
+
all_keys: list[str] = list(first.keys())
|
|
119
|
+
keys = [k for k in PREFERRED_COLUMNS if k in all_keys]
|
|
120
|
+
if not keys:
|
|
121
|
+
keys = [k for k in all_keys if not isinstance(first.get(k), (dict, list))][:8]
|
|
122
|
+
|
|
123
|
+
table = Table(show_lines=False)
|
|
124
|
+
for key in keys:
|
|
125
|
+
table.add_column(key, style="bold" if key in ("id", "cid", "name") else "")
|
|
126
|
+
|
|
127
|
+
for item in items:
|
|
128
|
+
if not isinstance(item, dict):
|
|
129
|
+
continue
|
|
130
|
+
row: list[Text] = []
|
|
131
|
+
for key in keys:
|
|
132
|
+
val = item.get(key, "")
|
|
133
|
+
if key == "status":
|
|
134
|
+
color = STATUS_COLORS.get(str(val), "white")
|
|
135
|
+
row.append(Text(str(val), style=color))
|
|
136
|
+
elif key == "createdAt" and isinstance(val, str) and len(val) > 10:
|
|
137
|
+
row.append(Text(val[:10]))
|
|
138
|
+
else:
|
|
139
|
+
s = str(val) if val is not None else ""
|
|
140
|
+
row.append(Text(s[:60] + "..." if len(s) > 60 else s))
|
|
141
|
+
table.add_row(*row)
|
|
142
|
+
return table
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _format_paginated(data: dict[str, object]) -> Table:
|
|
146
|
+
items = data["data"]
|
|
147
|
+
assert isinstance(items, list)
|
|
148
|
+
total = data.get("total", len(items))
|
|
149
|
+
table = _format_list(items)
|
|
150
|
+
table.caption = f"Showing {len(items)} of {total}"
|
|
151
|
+
return table
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _format_dict(data: dict[str, object]) -> Panel:
|
|
155
|
+
lines: list[str] = []
|
|
156
|
+
for key, val in data.items():
|
|
157
|
+
if key == "status":
|
|
158
|
+
color = STATUS_COLORS.get(str(val), "white")
|
|
159
|
+
lines.append(f"[bold]{key}:[/bold] [{color}]{val}[/{color}]")
|
|
160
|
+
elif key == "pendingReview" and isinstance(val, dict):
|
|
161
|
+
lines.append(
|
|
162
|
+
f"[bold]{key}:[/bold] [yellow]round "
|
|
163
|
+
f"{val.get('roundNumber')} ({val.get('kind')})[/yellow]"
|
|
164
|
+
)
|
|
165
|
+
elif isinstance(val, list) and len(val) > 3:
|
|
166
|
+
lines.append(f"[bold]{key}:[/bold] ({len(val)} items)")
|
|
167
|
+
elif isinstance(val, dict):
|
|
168
|
+
lines.append(f"[bold]{key}:[/bold] {{...}}")
|
|
169
|
+
else:
|
|
170
|
+
lines.append(f"[bold]{key}:[/bold] {val}")
|
|
171
|
+
|
|
172
|
+
title = str(data.get("id", data.get("name", "Result")))
|
|
173
|
+
return Panel("\n".join(lines), title=title, expand=False)
|
brava_cli/duration.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Parse a short duration string like '60s'/'30m'/'2h' into seconds."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
_PATTERN = re.compile(r"(\d+)([smh])")
|
|
6
|
+
_MULTIPLIERS = {"s": 1, "m": 60, "h": 3600}
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def parse_duration(value: str) -> float:
|
|
10
|
+
"""Parse a duration string into a positive float number of seconds.
|
|
11
|
+
|
|
12
|
+
Accepts integer-prefix + single suffix from {s, m, h}. Rejects empty,
|
|
13
|
+
missing suffix, decimals, negatives, zero, and whitespace.
|
|
14
|
+
"""
|
|
15
|
+
match = _PATTERN.fullmatch(value)
|
|
16
|
+
if match is None:
|
|
17
|
+
raise ValueError(
|
|
18
|
+
f"Invalid duration {value!r}: expected '<int><s|m|h>' (e.g. '60s', '30m', '2h')"
|
|
19
|
+
)
|
|
20
|
+
quantity = int(match.group(1))
|
|
21
|
+
if quantity == 0:
|
|
22
|
+
raise ValueError(f"Invalid duration {value!r}: must be > 0")
|
|
23
|
+
return float(quantity * _MULTIPLIERS[match.group(2)])
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Resolve a user-supplied account identifier to a Brava environment UUID.
|
|
2
|
+
|
|
3
|
+
The simulation/goal APIs key the target on the Brava environment UUID
|
|
4
|
+
(``targetAccountId``). Users, however, know their cloud-native identifiers
|
|
5
|
+
(AWS account number, Azure subscription id, GCP project id) or the display
|
|
6
|
+
name they gave the environment — those are what the console surfaces. This
|
|
7
|
+
module bridges the two so ``--account-id`` accepts either form.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import uuid
|
|
11
|
+
|
|
12
|
+
import typer
|
|
13
|
+
|
|
14
|
+
from brava_cli.client import BravaClient
|
|
15
|
+
from brava_cli.types import Snapshot
|
|
16
|
+
|
|
17
|
+
_ACCOUNT_TYPE = "account"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def is_uuid(value: str) -> bool:
|
|
21
|
+
try:
|
|
22
|
+
uuid.UUID(value)
|
|
23
|
+
return True
|
|
24
|
+
except ValueError:
|
|
25
|
+
return False
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _accounts(client: BravaClient) -> list[dict[str, object]] | None:
|
|
29
|
+
"""Fetch account-type environments; ``None`` if the key may not list them."""
|
|
30
|
+
result: Snapshot | None = client.list_environments(
|
|
31
|
+
type=_ACCOUNT_TYPE, forbidden_ok=True
|
|
32
|
+
)
|
|
33
|
+
if result is None:
|
|
34
|
+
return None
|
|
35
|
+
if not isinstance(result, list):
|
|
36
|
+
return []
|
|
37
|
+
return [item for item in result if isinstance(item, dict)]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _describe(account: dict[str, object]) -> str:
|
|
41
|
+
"""One-line candidate description for error messages."""
|
|
42
|
+
name = account.get("name", "?")
|
|
43
|
+
external = account.get("providerExternalIdentifier", "?")
|
|
44
|
+
provider = account.get("provider", "?")
|
|
45
|
+
env_id = account.get("id", "?")
|
|
46
|
+
return f" {name} ({provider} {external}) -> {env_id}"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _fail_ambiguous(value: str, matches: list[dict[str, object]]) -> None:
|
|
50
|
+
lines = "\n".join(_describe(m) for m in matches)
|
|
51
|
+
typer.echo(
|
|
52
|
+
f"Error: '{value}' matches multiple environments. "
|
|
53
|
+
f"Pass the exact environment UUID instead:\n{lines}",
|
|
54
|
+
err=True,
|
|
55
|
+
)
|
|
56
|
+
raise typer.Exit(1)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def resolve_account_id(client: BravaClient, value: str) -> str:
|
|
60
|
+
"""Resolve ``value`` to a Brava environment UUID.
|
|
61
|
+
|
|
62
|
+
Matching precedence against the tenant's account-type environments:
|
|
63
|
+
1. exact environment UUID (``id``)
|
|
64
|
+
2. exact cloud-native id (``providerExternalIdentifier``)
|
|
65
|
+
3. exact, case-insensitive display name (``name``)
|
|
66
|
+
|
|
67
|
+
A valid-looking UUID that matches nothing is passed through unchanged so
|
|
68
|
+
existing pinned UUIDs keep working even if the listing is unavailable.
|
|
69
|
+
Ambiguous or unknown non-UUID identifiers exit with a clear message.
|
|
70
|
+
If the API key may not list environments, only a UUID is accepted.
|
|
71
|
+
"""
|
|
72
|
+
accounts = _accounts(client)
|
|
73
|
+
if accounts is None:
|
|
74
|
+
if is_uuid(value):
|
|
75
|
+
return value
|
|
76
|
+
typer.echo(
|
|
77
|
+
"Error: this API key cannot list environments; "
|
|
78
|
+
"pass --account-id as the Brava environment UUID.",
|
|
79
|
+
err=True,
|
|
80
|
+
)
|
|
81
|
+
raise typer.Exit(1)
|
|
82
|
+
|
|
83
|
+
by_id = [a for a in accounts if a.get("id") == value]
|
|
84
|
+
if by_id:
|
|
85
|
+
return value
|
|
86
|
+
|
|
87
|
+
by_external = [a for a in accounts if a.get("providerExternalIdentifier") == value]
|
|
88
|
+
if len(by_external) == 1:
|
|
89
|
+
return str(by_external[0]["id"])
|
|
90
|
+
if len(by_external) > 1:
|
|
91
|
+
_fail_ambiguous(value, by_external)
|
|
92
|
+
|
|
93
|
+
lowered = value.lower()
|
|
94
|
+
by_name = [
|
|
95
|
+
a
|
|
96
|
+
for a in accounts
|
|
97
|
+
if isinstance(a.get("name"), str) and str(a["name"]).lower() == lowered
|
|
98
|
+
]
|
|
99
|
+
if len(by_name) == 1:
|
|
100
|
+
return str(by_name[0]["id"])
|
|
101
|
+
if len(by_name) > 1:
|
|
102
|
+
_fail_ambiguous(value, by_name)
|
|
103
|
+
|
|
104
|
+
if is_uuid(value):
|
|
105
|
+
return value
|
|
106
|
+
|
|
107
|
+
typer.echo(
|
|
108
|
+
f"Error: no environment matched '{value}'. "
|
|
109
|
+
f"Pass a Brava environment UUID, a cloud account id, or an "
|
|
110
|
+
f"environment name. Run `brava accounts list` to see them.",
|
|
111
|
+
err=True,
|
|
112
|
+
)
|
|
113
|
+
raise typer.Exit(1)
|