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/__init__.py
ADDED
|
File without changes
|
brava_cli/__main__.py
ADDED
brava_cli/app.py
ADDED
|
@@ -0,0 +1,626 @@
|
|
|
1
|
+
"""Brava Security CLI — attack simulation and SIEM hygiene."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Annotated, Optional
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
import typer
|
|
10
|
+
from dotenv import load_dotenv
|
|
11
|
+
|
|
12
|
+
from brava_cli import auth, hygiene
|
|
13
|
+
from brava_cli.context import CliContext, resolve_context
|
|
14
|
+
from brava_cli.environments import resolve_account_id
|
|
15
|
+
from brava_cli.types import Snapshot
|
|
16
|
+
|
|
17
|
+
load_dotenv()
|
|
18
|
+
|
|
19
|
+
app = typer.Typer(
|
|
20
|
+
name="brava",
|
|
21
|
+
help="Brava Security CLI — attack simulation and SIEM hygiene",
|
|
22
|
+
no_args_is_help=True,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
auth_app = typer.Typer(help="Manage authentication credentials")
|
|
26
|
+
catalog_app = typer.Typer(help="Browse the simulation catalog")
|
|
27
|
+
accounts_app = typer.Typer(help="List connected environments (accounts)")
|
|
28
|
+
run_app = typer.Typer(help="Manage simulation, goal, sweep and test runs")
|
|
29
|
+
sim_app = typer.Typer(help="Simulation run commands")
|
|
30
|
+
goal_app = typer.Typer(help="Describe-goal run commands")
|
|
31
|
+
doctor_app = typer.Typer(help="Check CLI prerequisites")
|
|
32
|
+
|
|
33
|
+
app.add_typer(auth_app, name="auth")
|
|
34
|
+
app.add_typer(catalog_app, name="catalog")
|
|
35
|
+
app.add_typer(accounts_app, name="accounts")
|
|
36
|
+
app.add_typer(hygiene.siems_app, name="siems")
|
|
37
|
+
app.add_typer(run_app, name="run")
|
|
38
|
+
app.add_typer(doctor_app, name="doctor")
|
|
39
|
+
run_app.add_typer(sim_app, name="simulation")
|
|
40
|
+
run_app.add_typer(goal_app, name="goal")
|
|
41
|
+
run_app.add_typer(hygiene.sweep_app, name="sweep")
|
|
42
|
+
run_app.add_typer(hygiene.detection_test_app, name="test")
|
|
43
|
+
|
|
44
|
+
PRODUCT_PROBES: tuple[tuple[str, str], ...] = (
|
|
45
|
+
("Attack simulation", "/api/v1/attack-simulation/simulation?limit=1"),
|
|
46
|
+
("Hygiene", "/api/v1/public/hygiene/siems"),
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# ---------------------------------------------------------------------------
|
|
51
|
+
# auth commands
|
|
52
|
+
# ---------------------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@auth_app.command("login")
|
|
56
|
+
def auth_login(
|
|
57
|
+
token: Annotated[
|
|
58
|
+
str, typer.Option("--token", "-t", help="Personal access token (PAT)")
|
|
59
|
+
],
|
|
60
|
+
url: Annotated[
|
|
61
|
+
str, typer.Option("--url", help="Brava platform URL")
|
|
62
|
+
] = "https://console.brava.security",
|
|
63
|
+
) -> None:
|
|
64
|
+
"""Store credentials for the Brava platform."""
|
|
65
|
+
auth.store_credentials(token, url)
|
|
66
|
+
typer.echo(f"Credentials saved. Platform URL: {url}")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@auth_app.command("logout")
|
|
70
|
+
def auth_logout() -> None:
|
|
71
|
+
"""Remove stored credentials."""
|
|
72
|
+
auth.clear_credentials()
|
|
73
|
+
typer.echo("Credentials removed.")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@auth_app.command("status")
|
|
77
|
+
def auth_status() -> None:
|
|
78
|
+
"""Show current authentication status."""
|
|
79
|
+
env_token = os.environ.get("BRAVA_API_TOKEN")
|
|
80
|
+
stored = auth.load_credentials()
|
|
81
|
+
|
|
82
|
+
if env_token:
|
|
83
|
+
typer.echo(
|
|
84
|
+
f"Authenticated via BRAVA_API_TOKEN env var (prefix: {env_token[:12]}...)"
|
|
85
|
+
)
|
|
86
|
+
elif stored:
|
|
87
|
+
token, url = stored
|
|
88
|
+
typer.echo(f"Authenticated via stored credentials (prefix: {token[:12]}...)")
|
|
89
|
+
typer.echo(f" Platform URL: {url}")
|
|
90
|
+
else:
|
|
91
|
+
typer.echo(
|
|
92
|
+
"Not authenticated. Run `brava auth login --token <PAT>` or set BRAVA_API_TOKEN."
|
|
93
|
+
)
|
|
94
|
+
raise typer.Exit(1)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# ---------------------------------------------------------------------------
|
|
98
|
+
# catalog commands
|
|
99
|
+
# ---------------------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@catalog_app.command("list")
|
|
103
|
+
def catalog_list(
|
|
104
|
+
search: Annotated[
|
|
105
|
+
Optional[str], typer.Option(help="Filter by name/description")
|
|
106
|
+
] = None,
|
|
107
|
+
limit: Annotated[Optional[int], typer.Option(help="Max results")] = None,
|
|
108
|
+
offset: Annotated[Optional[int], typer.Option(help="Skip N results")] = None,
|
|
109
|
+
json: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
|
|
110
|
+
) -> None:
|
|
111
|
+
"""List available simulations from the catalog."""
|
|
112
|
+
ctx = resolve_context(json)
|
|
113
|
+
result = ctx.client.list_simulations(search=search, limit=limit, offset=offset)
|
|
114
|
+
ctx.print(result)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@catalog_app.command("get")
|
|
118
|
+
def catalog_get(
|
|
119
|
+
id: Annotated[str, typer.Argument(help="Simulation ID (e.g. SIM1)")],
|
|
120
|
+
json: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
|
|
121
|
+
) -> None:
|
|
122
|
+
"""Get simulation details by ID."""
|
|
123
|
+
ctx = resolve_context(json)
|
|
124
|
+
result = ctx.client.get_simulation(id)
|
|
125
|
+
ctx.print(result)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# ---------------------------------------------------------------------------
|
|
129
|
+
# accounts commands
|
|
130
|
+
# ---------------------------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@accounts_app.command("list")
|
|
134
|
+
def accounts_list(
|
|
135
|
+
active: Annotated[
|
|
136
|
+
Optional[bool],
|
|
137
|
+
typer.Option(
|
|
138
|
+
"--active/--inactive",
|
|
139
|
+
help="Filter by enabled/disabled state (default: show all)",
|
|
140
|
+
),
|
|
141
|
+
] = None,
|
|
142
|
+
json: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
|
|
143
|
+
) -> None:
|
|
144
|
+
"""List connected accounts with their environment UUID and cloud id.
|
|
145
|
+
|
|
146
|
+
Use the environment UUID, the cloud account id, or the name with
|
|
147
|
+
`--account-id` on `run simulation create` / `run goal create`.
|
|
148
|
+
"""
|
|
149
|
+
ctx = resolve_context(json)
|
|
150
|
+
result = ctx.client.list_environments(type="account", is_active=active)
|
|
151
|
+
ctx.print(result)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
# ---------------------------------------------------------------------------
|
|
155
|
+
# run simulation commands
|
|
156
|
+
# ---------------------------------------------------------------------------
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@sim_app.command("create")
|
|
160
|
+
def sim_create(
|
|
161
|
+
simulation_id: Annotated[
|
|
162
|
+
str, typer.Option("--simulation-id", help="Simulation ID (e.g. SIM1)")
|
|
163
|
+
],
|
|
164
|
+
account_id: Annotated[
|
|
165
|
+
str,
|
|
166
|
+
typer.Option(
|
|
167
|
+
"--account-id",
|
|
168
|
+
help="Target account: environment UUID, cloud account id, or name",
|
|
169
|
+
),
|
|
170
|
+
],
|
|
171
|
+
region: Annotated[str, typer.Option("--region", help="Target AWS region")],
|
|
172
|
+
params: Annotated[
|
|
173
|
+
Optional[str], typer.Option(help="Runtime params as JSON string")
|
|
174
|
+
] = None,
|
|
175
|
+
json: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
|
|
176
|
+
) -> None:
|
|
177
|
+
"""Create a new simulation run."""
|
|
178
|
+
import json as json_mod
|
|
179
|
+
|
|
180
|
+
parsed_params = None
|
|
181
|
+
if params:
|
|
182
|
+
try:
|
|
183
|
+
parsed_params = json_mod.loads(params)
|
|
184
|
+
except json_mod.JSONDecodeError as exc:
|
|
185
|
+
typer.echo(f"Error: Invalid --params JSON: {exc}", err=True)
|
|
186
|
+
raise typer.Exit(1)
|
|
187
|
+
|
|
188
|
+
ctx = resolve_context(json)
|
|
189
|
+
result = ctx.client.create_run(
|
|
190
|
+
simulation_id=simulation_id,
|
|
191
|
+
account_id=resolve_account_id(ctx.client, account_id),
|
|
192
|
+
region=region,
|
|
193
|
+
params=parsed_params,
|
|
194
|
+
)
|
|
195
|
+
ctx.print(result)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@sim_app.command("list")
|
|
199
|
+
def sim_list(
|
|
200
|
+
account_id: Annotated[
|
|
201
|
+
Optional[str],
|
|
202
|
+
typer.Option(
|
|
203
|
+
"--account-id",
|
|
204
|
+
help="Filter by target account: environment UUID, cloud id, or name",
|
|
205
|
+
),
|
|
206
|
+
] = None,
|
|
207
|
+
limit: Annotated[Optional[int], typer.Option(help="Max results")] = None,
|
|
208
|
+
offset: Annotated[Optional[int], typer.Option(help="Skip N results")] = None,
|
|
209
|
+
json: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
|
|
210
|
+
) -> None:
|
|
211
|
+
"""List simulation runs."""
|
|
212
|
+
ctx = resolve_context(json)
|
|
213
|
+
resolved = (
|
|
214
|
+
resolve_account_id(ctx.client, account_id) if account_id is not None else None
|
|
215
|
+
)
|
|
216
|
+
result = ctx.client.list_runs(account_id=resolved, limit=limit, offset=offset)
|
|
217
|
+
ctx.print(result)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
@sim_app.command("get")
|
|
221
|
+
def sim_get(
|
|
222
|
+
id: Annotated[str, typer.Argument(help="Simulation run UUID")],
|
|
223
|
+
json: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
|
|
224
|
+
) -> None:
|
|
225
|
+
"""Get simulation run details."""
|
|
226
|
+
ctx = resolve_context(json)
|
|
227
|
+
result = ctx.client.get_run(id)
|
|
228
|
+
ctx.print(result)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
@sim_app.command("watch")
|
|
232
|
+
def sim_watch(
|
|
233
|
+
id: Annotated[str, typer.Argument(help="Simulation run UUID")],
|
|
234
|
+
interval: Annotated[int, typer.Option(help="Poll interval in seconds")] = 5,
|
|
235
|
+
json: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
|
|
236
|
+
) -> None:
|
|
237
|
+
"""Watch a simulation run until completion."""
|
|
238
|
+
import time
|
|
239
|
+
from rich.live import Live
|
|
240
|
+
from rich.text import Text
|
|
241
|
+
|
|
242
|
+
ctx = resolve_context(json)
|
|
243
|
+
terminal_statuses = {
|
|
244
|
+
"COMPLETED",
|
|
245
|
+
"FAILED",
|
|
246
|
+
"TIMED_OUT",
|
|
247
|
+
"completed",
|
|
248
|
+
"failed",
|
|
249
|
+
"timed_out",
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if ctx.json_mode:
|
|
253
|
+
while True:
|
|
254
|
+
data = ctx.client.get_run(id)
|
|
255
|
+
status = data.get("status", "") if isinstance(data, dict) else ""
|
|
256
|
+
ctx.print(data)
|
|
257
|
+
if status in terminal_statuses:
|
|
258
|
+
raise typer.Exit(0 if status.lower() == "completed" else 1)
|
|
259
|
+
time.sleep(interval)
|
|
260
|
+
else:
|
|
261
|
+
with Live(Text("Polling..."), refresh_per_second=1) as live:
|
|
262
|
+
while True:
|
|
263
|
+
data = ctx.client.get_run(id)
|
|
264
|
+
status = data.get("status", "") if isinstance(data, dict) else ""
|
|
265
|
+
live.update(ctx.format(data))
|
|
266
|
+
if status in terminal_statuses:
|
|
267
|
+
ctx.print(data)
|
|
268
|
+
raise typer.Exit(0 if status.lower() == "completed" else 1)
|
|
269
|
+
time.sleep(interval)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
# ---------------------------------------------------------------------------
|
|
273
|
+
# run goal commands
|
|
274
|
+
# ---------------------------------------------------------------------------
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
@goal_app.command("create")
|
|
278
|
+
def goal_create(
|
|
279
|
+
goal: Annotated[str, typer.Option("--goal", help="Free-text research goal")],
|
|
280
|
+
account_id: Annotated[
|
|
281
|
+
str,
|
|
282
|
+
typer.Option(
|
|
283
|
+
"--account-id",
|
|
284
|
+
help="Target account: environment UUID, cloud account id, or name",
|
|
285
|
+
),
|
|
286
|
+
],
|
|
287
|
+
region: Annotated[str, typer.Option("--region", help="Target AWS region")],
|
|
288
|
+
interactive: Annotated[
|
|
289
|
+
bool,
|
|
290
|
+
typer.Option(
|
|
291
|
+
"--interactive/--no-interactive",
|
|
292
|
+
help="Pause after every strategist round for approval/feedback (required).",
|
|
293
|
+
),
|
|
294
|
+
],
|
|
295
|
+
profile_identifier: Annotated[
|
|
296
|
+
Optional[str], typer.Option("--profile", help="Profile identifier (role ARN)")
|
|
297
|
+
] = None,
|
|
298
|
+
json: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
|
|
299
|
+
) -> None:
|
|
300
|
+
"""Create a new describe-goal run."""
|
|
301
|
+
ctx = resolve_context(json)
|
|
302
|
+
result = ctx.client.create_goal_run(
|
|
303
|
+
goal=goal,
|
|
304
|
+
account_id=resolve_account_id(ctx.client, account_id),
|
|
305
|
+
region=region,
|
|
306
|
+
interactive=interactive,
|
|
307
|
+
profile_identifier=profile_identifier,
|
|
308
|
+
)
|
|
309
|
+
ctx.print(result)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
@goal_app.command("list")
|
|
313
|
+
def goal_list(
|
|
314
|
+
account_id: Annotated[
|
|
315
|
+
Optional[str],
|
|
316
|
+
typer.Option(
|
|
317
|
+
"--account-id",
|
|
318
|
+
help="Filter by target account: environment UUID, cloud id, or name",
|
|
319
|
+
),
|
|
320
|
+
] = None,
|
|
321
|
+
limit: Annotated[Optional[int], typer.Option(help="Max results")] = None,
|
|
322
|
+
offset: Annotated[Optional[int], typer.Option(help="Skip N results")] = None,
|
|
323
|
+
json: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
|
|
324
|
+
) -> None:
|
|
325
|
+
"""List describe-goal runs."""
|
|
326
|
+
ctx = resolve_context(json)
|
|
327
|
+
resolved = (
|
|
328
|
+
resolve_account_id(ctx.client, account_id) if account_id is not None else None
|
|
329
|
+
)
|
|
330
|
+
result = ctx.client.list_goal_runs(account_id=resolved, limit=limit, offset=offset)
|
|
331
|
+
ctx.print(result)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
@goal_app.command("get")
|
|
335
|
+
def goal_get(
|
|
336
|
+
id: Annotated[str, typer.Argument(help="Describe-goal run UUID")],
|
|
337
|
+
json: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
|
|
338
|
+
) -> None:
|
|
339
|
+
"""Get describe-goal run details."""
|
|
340
|
+
ctx = resolve_context(json)
|
|
341
|
+
result = ctx.client.get_goal_run(id)
|
|
342
|
+
ctx.print(result)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
@goal_app.command("approve")
|
|
346
|
+
def goal_approve(
|
|
347
|
+
id: Annotated[str, typer.Argument(help="Describe-goal run UUID")],
|
|
348
|
+
json: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
|
|
349
|
+
) -> None:
|
|
350
|
+
"""Approve the current pending review so the strategist continues."""
|
|
351
|
+
ctx = resolve_context(json)
|
|
352
|
+
ctx.client.approve_goal_run(id)
|
|
353
|
+
if not ctx.json_mode:
|
|
354
|
+
ctx.console.print(f"[green]Approved[/green] review for run {id}.")
|
|
355
|
+
ctx.print(ctx.client.get_goal_run(id))
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
@goal_app.command("feedback")
|
|
359
|
+
def goal_feedback(
|
|
360
|
+
id: Annotated[str, typer.Argument(help="Describe-goal run UUID")],
|
|
361
|
+
message: Annotated[
|
|
362
|
+
Optional[str],
|
|
363
|
+
typer.Option("--message", "-m", help="Feedback for the strategist"),
|
|
364
|
+
] = None,
|
|
365
|
+
message_file: Annotated[
|
|
366
|
+
Optional[str],
|
|
367
|
+
typer.Option(
|
|
368
|
+
"--message-file", help="Read feedback from a file ('-' for stdin)"
|
|
369
|
+
),
|
|
370
|
+
] = None,
|
|
371
|
+
json: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
|
|
372
|
+
) -> None:
|
|
373
|
+
"""Send free-text feedback; the strategist re-runs the current round."""
|
|
374
|
+
text = _resolve_feedback_message(message, message_file)
|
|
375
|
+
ctx = resolve_context(json)
|
|
376
|
+
ctx.client.submit_goal_feedback(id, text)
|
|
377
|
+
if not ctx.json_mode:
|
|
378
|
+
ctx.console.print(f"[green]Feedback sent[/green] for run {id}.")
|
|
379
|
+
ctx.print(ctx.client.get_goal_run(id))
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
@goal_app.command("interactivity")
|
|
383
|
+
def goal_interactivity(
|
|
384
|
+
id: Annotated[str, typer.Argument(help="Describe-goal run UUID")],
|
|
385
|
+
interactive: Annotated[
|
|
386
|
+
bool,
|
|
387
|
+
typer.Option(
|
|
388
|
+
"--interactive/--no-interactive",
|
|
389
|
+
help="Turn interactive review gates on or off (required).",
|
|
390
|
+
),
|
|
391
|
+
],
|
|
392
|
+
json: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
|
|
393
|
+
) -> None:
|
|
394
|
+
"""Toggle interactivity mid-run (applies at the next gate; does not approve a current pause)."""
|
|
395
|
+
ctx = resolve_context(json)
|
|
396
|
+
result = ctx.client.set_goal_interactivity(id, interactive)
|
|
397
|
+
ctx.print(result)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _resolve_feedback_message(message: str | None, message_file: str | None) -> str:
|
|
401
|
+
"""Resolve feedback text from --message, --message-file, or stdin ('-')."""
|
|
402
|
+
if message_file is not None:
|
|
403
|
+
text = (
|
|
404
|
+
sys.stdin.read() if message_file == "-" else Path(message_file).read_text()
|
|
405
|
+
)
|
|
406
|
+
elif message is not None:
|
|
407
|
+
text = message
|
|
408
|
+
else:
|
|
409
|
+
typer.echo("Error: provide --message or --message-file.", err=True)
|
|
410
|
+
raise typer.Exit(1)
|
|
411
|
+
text = text.strip()
|
|
412
|
+
if not text:
|
|
413
|
+
typer.echo("Error: feedback message is empty.", err=True)
|
|
414
|
+
raise typer.Exit(1)
|
|
415
|
+
return text
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
_GOAL_TERMINAL_STATUSES = {"complete", "failed", "cancelled"}
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
@goal_app.command("watch")
|
|
422
|
+
def goal_watch(
|
|
423
|
+
id: Annotated[str, typer.Argument(help="Describe-goal run UUID")],
|
|
424
|
+
interval: Annotated[int, typer.Option(help="Poll interval in seconds")] = 5,
|
|
425
|
+
interactive: Annotated[
|
|
426
|
+
bool,
|
|
427
|
+
typer.Option(
|
|
428
|
+
"--interactive/--no-interactive",
|
|
429
|
+
help="When the run pauses for review, prompt to approve / send feedback.",
|
|
430
|
+
),
|
|
431
|
+
] = False,
|
|
432
|
+
json: Annotated[bool, typer.Option("--json", help="Output raw JSON")] = False,
|
|
433
|
+
) -> None:
|
|
434
|
+
"""Watch a describe-goal run; with --interactive, act on review pauses."""
|
|
435
|
+
import time
|
|
436
|
+
from rich.live import Live
|
|
437
|
+
from rich.text import Text
|
|
438
|
+
|
|
439
|
+
ctx = resolve_context(json)
|
|
440
|
+
|
|
441
|
+
if interactive and not ctx.json_mode:
|
|
442
|
+
_interactive_follow(ctx, id, interval)
|
|
443
|
+
return
|
|
444
|
+
|
|
445
|
+
if ctx.json_mode:
|
|
446
|
+
while True:
|
|
447
|
+
data = ctx.client.get_goal_run(id)
|
|
448
|
+
status = data.get("status", "") if isinstance(data, dict) else ""
|
|
449
|
+
ctx.print(data)
|
|
450
|
+
if status.lower() in _GOAL_TERMINAL_STATUSES:
|
|
451
|
+
raise typer.Exit(0 if status.lower() == "complete" else 1)
|
|
452
|
+
time.sleep(interval)
|
|
453
|
+
else:
|
|
454
|
+
with Live(Text("Polling..."), refresh_per_second=1) as live:
|
|
455
|
+
while True:
|
|
456
|
+
data = ctx.client.get_goal_run(id)
|
|
457
|
+
status = data.get("status", "") if isinstance(data, dict) else ""
|
|
458
|
+
live.update(ctx.format(data))
|
|
459
|
+
if status.lower() in _GOAL_TERMINAL_STATUSES:
|
|
460
|
+
ctx.print(data)
|
|
461
|
+
raise typer.Exit(0 if status.lower() == "complete" else 1)
|
|
462
|
+
time.sleep(interval)
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _interactive_follow(ctx: CliContext, id: str, interval: int) -> None:
|
|
466
|
+
"""Poll a run and, on each review pause, prompt to approve or send feedback."""
|
|
467
|
+
import time
|
|
468
|
+
|
|
469
|
+
last_status = ""
|
|
470
|
+
while True:
|
|
471
|
+
data = ctx.client.get_goal_run(id)
|
|
472
|
+
status = data.get("status", "") if isinstance(data, dict) else ""
|
|
473
|
+
pending: Snapshot | None = (
|
|
474
|
+
data.get("pendingReview") if isinstance(data, dict) else None
|
|
475
|
+
)
|
|
476
|
+
|
|
477
|
+
if status != last_status:
|
|
478
|
+
ctx.console.print(ctx.format(data))
|
|
479
|
+
last_status = status
|
|
480
|
+
|
|
481
|
+
if status.lower() in _GOAL_TERMINAL_STATUSES:
|
|
482
|
+
raise typer.Exit(0 if status.lower() == "complete" else 1)
|
|
483
|
+
|
|
484
|
+
if status == "waiting_for_user_input" and isinstance(pending, dict):
|
|
485
|
+
summary = data.get("summary") if isinstance(data, dict) else None
|
|
486
|
+
if isinstance(summary, str) and summary:
|
|
487
|
+
ctx.console.print(summary)
|
|
488
|
+
ctx.console.print(
|
|
489
|
+
f"[yellow]Awaiting review — round "
|
|
490
|
+
f"{pending.get('roundNumber')} ({pending.get('kind')})[/yellow]"
|
|
491
|
+
)
|
|
492
|
+
choice = (
|
|
493
|
+
typer.prompt("[a]pprove / [f]eedback / [q]uit", default="a")
|
|
494
|
+
.strip()
|
|
495
|
+
.lower()
|
|
496
|
+
)
|
|
497
|
+
if choice in ("a", "approve"):
|
|
498
|
+
ctx.client.approve_goal_run(id)
|
|
499
|
+
ctx.console.print("[green]Approved.[/green]")
|
|
500
|
+
elif choice in ("f", "feedback"):
|
|
501
|
+
text = _read_interactive_feedback()
|
|
502
|
+
if text:
|
|
503
|
+
ctx.client.submit_goal_feedback(id, text)
|
|
504
|
+
ctx.console.print("[green]Feedback sent.[/green]")
|
|
505
|
+
elif choice in ("q", "quit"):
|
|
506
|
+
raise typer.Exit(0)
|
|
507
|
+
last_status = "" # re-print state after the action resolves
|
|
508
|
+
time.sleep(interval)
|
|
509
|
+
continue
|
|
510
|
+
|
|
511
|
+
time.sleep(interval)
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def _read_interactive_feedback() -> str:
|
|
515
|
+
"""Read multi-line feedback via $EDITOR, falling back to a single-line prompt."""
|
|
516
|
+
import click
|
|
517
|
+
|
|
518
|
+
edited = click.edit()
|
|
519
|
+
text = (edited or "").strip()
|
|
520
|
+
if not text:
|
|
521
|
+
text = typer.prompt("Feedback message").strip()
|
|
522
|
+
return text
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
# ---------------------------------------------------------------------------
|
|
526
|
+
# doctor
|
|
527
|
+
# ---------------------------------------------------------------------------
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
@doctor_app.callback(invoke_without_command=True)
|
|
531
|
+
def doctor() -> None:
|
|
532
|
+
"""Check CLI prerequisites and connectivity."""
|
|
533
|
+
from rich.console import Console
|
|
534
|
+
from rich.table import Table
|
|
535
|
+
|
|
536
|
+
console = Console()
|
|
537
|
+
checks: list[tuple[str, bool | None, str]] = []
|
|
538
|
+
|
|
539
|
+
py = sys.version_info
|
|
540
|
+
checks.append(
|
|
541
|
+
("Python >= 3.10", py >= (3, 10), f"{py.major}.{py.minor}.{py.micro}")
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
env_token = os.environ.get("BRAVA_API_TOKEN")
|
|
545
|
+
stored = auth.load_credentials()
|
|
546
|
+
auth_ok = bool(env_token or stored)
|
|
547
|
+
if env_token:
|
|
548
|
+
detail = "via BRAVA_API_TOKEN env var"
|
|
549
|
+
elif stored:
|
|
550
|
+
detail = f"stored credentials ({stored.url})"
|
|
551
|
+
else:
|
|
552
|
+
detail = "not authenticated"
|
|
553
|
+
checks.append(("Authentication", auth_ok, detail))
|
|
554
|
+
|
|
555
|
+
url = os.environ.get("BRAVA_URL") or (stored.url if stored else None)
|
|
556
|
+
token = env_token or (stored.token if stored else None)
|
|
557
|
+
if url:
|
|
558
|
+
try:
|
|
559
|
+
r = httpx.get(f"{url}/api/v1/health", timeout=5.0)
|
|
560
|
+
checks.append(
|
|
561
|
+
(
|
|
562
|
+
"Platform connectivity",
|
|
563
|
+
r.status_code == 200,
|
|
564
|
+
f"{url} -> HTTP {r.status_code}",
|
|
565
|
+
)
|
|
566
|
+
)
|
|
567
|
+
except Exception as exc:
|
|
568
|
+
checks.append(("Platform connectivity", False, str(exc)[:80]))
|
|
569
|
+
else:
|
|
570
|
+
checks.append(("Platform connectivity", False, "no URL configured"))
|
|
571
|
+
|
|
572
|
+
if url and token:
|
|
573
|
+
reachable = 0
|
|
574
|
+
for product, path in PRODUCT_PROBES:
|
|
575
|
+
try:
|
|
576
|
+
r = httpx.get(
|
|
577
|
+
f"{url}{path}",
|
|
578
|
+
headers={"Authorization": f"Bearer {token}"},
|
|
579
|
+
timeout=5.0,
|
|
580
|
+
)
|
|
581
|
+
except Exception as exc:
|
|
582
|
+
checks.append((product, False, str(exc)[:80]))
|
|
583
|
+
continue
|
|
584
|
+
if r.status_code == 200:
|
|
585
|
+
reachable += 1
|
|
586
|
+
checks.append((product, True, "accessible"))
|
|
587
|
+
elif r.status_code == 403:
|
|
588
|
+
checks.append((product, None, "API key lacks this product's scope"))
|
|
589
|
+
elif r.status_code == 401:
|
|
590
|
+
checks.append((product, False, "invalid or expired token"))
|
|
591
|
+
else:
|
|
592
|
+
checks.append((product, False, f"unexpected HTTP {r.status_code}"))
|
|
593
|
+
if reachable == 0:
|
|
594
|
+
checks.append(("Product access", False, "token cannot reach any product"))
|
|
595
|
+
elif auth_ok:
|
|
596
|
+
checks.append(("Product access", False, "skipped (no URL)"))
|
|
597
|
+
|
|
598
|
+
table = Table(title="brava doctor")
|
|
599
|
+
table.add_column("Check", style="bold")
|
|
600
|
+
table.add_column("Status")
|
|
601
|
+
table.add_column("Details")
|
|
602
|
+
|
|
603
|
+
all_ok = True
|
|
604
|
+
for name, ok, detail in checks:
|
|
605
|
+
if ok is None:
|
|
606
|
+
status = "[yellow]NO ACCESS[/yellow]"
|
|
607
|
+
elif ok:
|
|
608
|
+
status = "[green]OK[/green]"
|
|
609
|
+
else:
|
|
610
|
+
status = "[red]FAIL[/red]"
|
|
611
|
+
all_ok = False
|
|
612
|
+
table.add_row(name, status, detail)
|
|
613
|
+
|
|
614
|
+
console.print()
|
|
615
|
+
console.print(table)
|
|
616
|
+
console.print()
|
|
617
|
+
console.print(
|
|
618
|
+
"[green]All checks passed.[/green]"
|
|
619
|
+
if all_ok
|
|
620
|
+
else "[yellow]Some checks failed.[/yellow]"
|
|
621
|
+
)
|
|
622
|
+
raise typer.Exit(0 if all_ok else 1)
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
if __name__ == "__main__":
|
|
626
|
+
app()
|
brava_cli/auth.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Credential storage and retrieval for the Brava CLI."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import NamedTuple
|
|
6
|
+
|
|
7
|
+
CONFIG_DIR = Path.home() / ".config" / "brava-cli"
|
|
8
|
+
CREDENTIALS_FILE = CONFIG_DIR / "credentials.json"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class StoredCredentials(NamedTuple):
|
|
12
|
+
token: str
|
|
13
|
+
url: str
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def store_credentials(token: str, url: str) -> None:
|
|
17
|
+
"""Persist API token and URL to disk."""
|
|
18
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
19
|
+
CREDENTIALS_FILE.write_text(json.dumps({"token": token, "url": url}))
|
|
20
|
+
CREDENTIALS_FILE.chmod(0o600)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def load_credentials() -> StoredCredentials | None:
|
|
24
|
+
"""Load stored credentials, or ``None`` if not found."""
|
|
25
|
+
if not CREDENTIALS_FILE.exists():
|
|
26
|
+
return None
|
|
27
|
+
try:
|
|
28
|
+
data = json.loads(CREDENTIALS_FILE.read_text())
|
|
29
|
+
return StoredCredentials(token=data["token"], url=data["url"])
|
|
30
|
+
except (json.JSONDecodeError, KeyError):
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def clear_credentials() -> None:
|
|
35
|
+
"""Remove stored credentials."""
|
|
36
|
+
if CREDENTIALS_FILE.exists():
|
|
37
|
+
CREDENTIALS_FILE.unlink()
|