proxy-platform 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.

Potentially problematic release.


This version of proxy-platform might be problematic. Click here for more details.

@@ -0,0 +1,894 @@
1
+ """Firewall management commands."""
2
+
3
+ import json
4
+ import logging
5
+ from typing import Any
6
+
7
+ import typer
8
+ from requests import Response
9
+ from rich.console import Console
10
+ from rich.table import Table
11
+
12
+ from ..client import APIClient
13
+ from ..config import get_default_api_type
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ app = typer.Typer()
18
+ console = Console()
19
+
20
+
21
+ def _print_error(response: Response) -> None:
22
+ """Print error message from API response."""
23
+ console.print(f"[red]Error: {response.status_code}[/red]")
24
+ try:
25
+ error_data: Any = response.json()
26
+ if isinstance(error_data, dict):
27
+ console.print(error_data.get("detail", "Unknown error"))
28
+ else:
29
+ console.print(str(error_data))
30
+ except Exception:
31
+ console.print(response.text if response.text else "Unknown error")
32
+
33
+
34
+ def _unwrap_response(data: Any) -> Any:
35
+ """Unwrap API response if it contains a 'data' key.
36
+
37
+ Handles both wrapped responses ({'data': ...}) and direct responses.
38
+ """
39
+ if data is None:
40
+ return None
41
+ if isinstance(data, dict) and "data" in data:
42
+ return data["data"]
43
+ return data
44
+
45
+
46
+ @app.command("list")
47
+ def list_firewalls(
48
+ api: str | None = typer.Option(
49
+ None, "--api", "-a", help="API type (admin or user). Uses default if not specified."
50
+ ),
51
+ ) -> None:
52
+ """List all firewalls.
53
+
54
+ Display all firewalls accessible to the authenticated user.
55
+ """
56
+ if api is None:
57
+ api = get_default_api_type()
58
+
59
+ try:
60
+ client = APIClient(api_type=api)
61
+ response = client.get("/api/v1/firewalls")
62
+
63
+ # Debug: Show what we got
64
+ logger.debug(f"Response status: {response.status_code}")
65
+ logger.debug(f"Response headers: {response.headers}")
66
+ try:
67
+ logger.debug(f"Response text length: {len(response.text) if response.text else 0}")
68
+ except (TypeError, AttributeError):
69
+ logger.debug("Response text length: N/A (mock or unavailable)")
70
+
71
+ if response.status_code == 200:
72
+ try:
73
+ data = response.json()
74
+ logger.debug(f"Parsed JSON type: {type(data)}")
75
+ logger.debug(f"JSON keys: {list(data.keys()) if isinstance(data, dict) else 'not a dict'}")
76
+ except Exception as e:
77
+ console.print(f"[red]Error: Failed to parse response as JSON: {e}[/red]")
78
+ console.print(f"[dim]Response text: {response.text[:200]}[/dim]")
79
+ raise typer.Exit(1) from None
80
+
81
+ firewalls = _unwrap_response(data)
82
+ logger.debug(f"After unwrap, type: {type(firewalls)}")
83
+
84
+ if firewalls is None:
85
+ console.print("[red]Error: Response data is None[/red]")
86
+ console.print(f"[dim]Full response: {data}[/dim]")
87
+ raise typer.Exit(1)
88
+
89
+ if not isinstance(firewalls, list):
90
+ console.print("[red]Error: Unexpected response format[/red]")
91
+ console.print(f"[dim]Expected list, got: {type(firewalls).__name__}[/dim]")
92
+ console.print(f"[dim]Data: {firewalls}[/dim]")
93
+ raise typer.Exit(1)
94
+
95
+ if not firewalls:
96
+ console.print("[yellow]No firewalls found[/yellow]")
97
+ return
98
+
99
+ table = Table(title="Firewalls")
100
+ table.add_column("ID", style="cyan")
101
+ table.add_column("Name", style="green")
102
+ table.add_column("Description", style="white")
103
+ table.add_column("Rules", justify="right", style="magenta")
104
+ table.add_column("Created", style="dim")
105
+
106
+ for firewall in firewalls:
107
+ # Handle None description values
108
+ desc = firewall.get("description") or ""
109
+ desc_display = desc[:50] + ("..." if len(desc) > 50 else "")
110
+
111
+ table.add_row(
112
+ str(firewall.get("id", "N/A")),
113
+ firewall.get("name", "N/A"),
114
+ desc_display,
115
+ str(firewall.get("rule_count", len(firewall.get("rules", [])))),
116
+ firewall.get("created_at", "N/A"),
117
+ )
118
+
119
+ console.print(table)
120
+ console.print(f"\n[dim]Total: {len(firewalls)} firewall(s)[/dim]")
121
+
122
+ else:
123
+ _print_error(response)
124
+ raise typer.Exit(1)
125
+
126
+ except Exception as e:
127
+ console.print(f"[red]Error: {str(e)}[/red]")
128
+ import traceback
129
+
130
+ console.print(f"[dim]{traceback.format_exc()}[/dim]")
131
+ raise typer.Exit(1) from None
132
+
133
+
134
+ @app.command("get")
135
+ def get_firewall(
136
+ firewall_id: str = typer.Argument(..., help="Firewall ID"),
137
+ api: str | None = typer.Option(
138
+ None, "--api", "-a", help="API type (admin or user). Uses default if not specified."
139
+ ),
140
+ ) -> None:
141
+ """Get firewall details.
142
+
143
+ Display detailed information about a specific firewall.
144
+ """
145
+ if api is None:
146
+ api = get_default_api_type()
147
+
148
+ try:
149
+ client = APIClient(api_type=api)
150
+ response = client.get(f"/api/v1/firewalls/{firewall_id}")
151
+
152
+ if response.status_code == 200:
153
+ data = response.json()
154
+ firewall = _unwrap_response(data)
155
+
156
+ console.print("\n[bold]Firewall Details[/bold]")
157
+ console.print("─" * 80)
158
+ console.print(f"ID: [cyan]{firewall.get('id', 'N/A')}[/cyan]")
159
+ console.print(f"Name: [green]{firewall.get('name', 'N/A')}[/green]")
160
+ console.print(f"Description: {firewall.get('description', 'N/A')}")
161
+ console.print(f"Created: [dim]{firewall.get('created_at', 'N/A')}[/dim]")
162
+ console.print(f"Updated: [dim]{firewall.get('updated_at', 'N/A')}[/dim]")
163
+
164
+ rules = firewall.get("rules", [])
165
+ if rules:
166
+ console.print(f"\n[bold]Firewall Rules ({len(rules)})[/bold]")
167
+ console.print("─" * 80)
168
+
169
+ table = Table(show_header=True)
170
+ table.add_column("ID", style="cyan")
171
+ table.add_column("Direction", style="yellow")
172
+ table.add_column("Protocol", style="magenta")
173
+ table.add_column("Ports", style="green")
174
+ table.add_column("Source IPs", style="white")
175
+ table.add_column("Action", style="blue")
176
+
177
+ for rule in rules:
178
+ direction = rule.get("direction", "inbound")
179
+ ports = rule.get("destination_ports") if direction == "inbound" else rule.get("source_ports")
180
+ if ports:
181
+ port_str = ", ".join(str(p) for p in ports)
182
+ else:
183
+ port_str = "any"
184
+
185
+ source_ips = rule.get("source_ips") or []
186
+ ip_str = ", ".join(source_ips) if source_ips else "any"
187
+
188
+ table.add_row(
189
+ str(rule.get("id", "N/A")),
190
+ direction,
191
+ rule.get("protocol", "N/A"),
192
+ port_str,
193
+ ip_str,
194
+ rule.get("action", "allow"),
195
+ )
196
+
197
+ console.print(table)
198
+ else:
199
+ console.print("\n[yellow]No rules configured[/yellow]")
200
+
201
+ console.print()
202
+
203
+ else:
204
+ _print_error(response)
205
+ raise typer.Exit(1)
206
+
207
+ except Exception as e:
208
+ console.print(f"[red]Error: {str(e)}[/red]")
209
+ raise typer.Exit(1) from None
210
+
211
+
212
+ @app.command("create")
213
+ def create_firewall(
214
+ name: str = typer.Option(..., "--name", "-n", help="Firewall name"),
215
+ description: str | None = typer.Option(None, "--description", "-d", help="Firewall description"),
216
+ api: str | None = typer.Option(
217
+ None, "--api", "-a", help="API type (admin or user). Uses default if not specified."
218
+ ),
219
+ ) -> None:
220
+ """Create a new firewall.
221
+
222
+ Create a new firewall with the specified name and optional description.
223
+ """
224
+ if api is None:
225
+ api = get_default_api_type()
226
+
227
+ try:
228
+ client = APIClient(api_type=api)
229
+
230
+ payload = {"name": name}
231
+ if description:
232
+ payload["description"] = description
233
+
234
+ response = client.post("/api/v1/firewalls", data=payload)
235
+
236
+ if response.status_code in [200, 201]:
237
+ data_response = response.json()
238
+ firewall = _unwrap_response(data_response)
239
+ console.print("\n[green]✓[/green] Firewall created successfully!")
240
+ console.print(f"ID: [cyan]{firewall.get('id')}[/cyan]")
241
+ console.print(f"Name: [green]{firewall.get('name')}[/green]")
242
+ if firewall.get("description"):
243
+ console.print(f"Description: {firewall.get('description')}")
244
+ console.print()
245
+
246
+ else:
247
+ _print_error(response)
248
+ raise typer.Exit(1)
249
+
250
+ except Exception as e:
251
+ console.print(f"[red]Error: {str(e)}[/red]")
252
+ raise typer.Exit(1) from None
253
+
254
+
255
+ @app.command("update")
256
+ def update_firewall(
257
+ firewall_id: str = typer.Argument(..., help="Firewall ID"),
258
+ name: str | None = typer.Option(None, "--name", "-n", help="New firewall name"),
259
+ description: str | None = typer.Option(None, "--description", "-d", help="New firewall description"),
260
+ api: str | None = typer.Option(
261
+ None, "--api", "-a", help="API type (admin or user). Uses default if not specified."
262
+ ),
263
+ ) -> None:
264
+ """Update a firewall.
265
+
266
+ Update the name and/or description of an existing firewall.
267
+ """
268
+ if api is None:
269
+ api = get_default_api_type()
270
+
271
+ if not name and not description:
272
+ console.print("[red]Error: At least one of --name or --description must be provided[/red]")
273
+ raise typer.Exit(1)
274
+
275
+ try:
276
+ client = APIClient(api_type=api)
277
+
278
+ payload = {}
279
+ if name:
280
+ payload["name"] = name
281
+ if description:
282
+ payload["description"] = description
283
+
284
+ response = client.patch(f"/api/v1/firewalls/{firewall_id}", data=payload)
285
+
286
+ if response.status_code == 200:
287
+ data_response = response.json()
288
+ firewall = _unwrap_response(data_response)
289
+ console.print("\n[green]✓[/green] Firewall updated successfully!")
290
+ console.print(f"ID: [cyan]{firewall.get('id')}[/cyan]")
291
+ console.print(f"Name: [green]{firewall.get('name')}[/green]")
292
+ if firewall.get("description"):
293
+ console.print(f"Description: {firewall.get('description')}")
294
+ console.print()
295
+
296
+ else:
297
+ _print_error(response)
298
+ raise typer.Exit(1)
299
+
300
+ except Exception as e:
301
+ console.print(f"[red]Error: {str(e)}[/red]")
302
+ raise typer.Exit(1) from None
303
+
304
+
305
+ @app.command("delete")
306
+ def delete_firewall(
307
+ firewall_id: str = typer.Argument(..., help="Firewall ID"),
308
+ force: bool = typer.Option(False, "--force", "-f", help="Skip confirmation prompt"),
309
+ api: str | None = typer.Option(
310
+ None, "--api", "-a", help="API type (admin or user). Uses default if not specified."
311
+ ),
312
+ ) -> None:
313
+ """Delete a firewall.
314
+
315
+ Delete a firewall by its ID. This will also delete all associated rules.
316
+ """
317
+ if api is None:
318
+ api = get_default_api_type()
319
+
320
+ if not force:
321
+ confirm = typer.confirm(f"Are you sure you want to delete firewall {firewall_id}?")
322
+ if not confirm:
323
+ console.print("[yellow]Deletion cancelled[/yellow]")
324
+ raise typer.Abort()
325
+
326
+ try:
327
+ client = APIClient(api_type=api)
328
+ response = client.delete(f"/api/v1/firewalls/{firewall_id}")
329
+
330
+ if response.status_code in [200, 204]:
331
+ console.print(f"[green]✓[/green] Firewall {firewall_id} deleted successfully")
332
+
333
+ else:
334
+ _print_error(response)
335
+ raise typer.Exit(1)
336
+
337
+ except Exception as e:
338
+ console.print(f"[red]Error: {str(e)}[/red]")
339
+ raise typer.Exit(1) from None
340
+
341
+
342
+ # Firewall Rules Commands
343
+ rules_app = typer.Typer()
344
+ app.add_typer(rules_app, name="rules", help="Manage firewall rules")
345
+
346
+
347
+ @rules_app.command("list")
348
+ def list_rules(
349
+ firewall_id: str = typer.Argument(..., help="Firewall ID"),
350
+ api: str | None = typer.Option(
351
+ None, "--api", "-a", help="API type (admin or user). Uses default if not specified."
352
+ ),
353
+ ) -> None:
354
+ """List all rules for a firewall.
355
+
356
+ Display all rules configured for the specified firewall.
357
+ """
358
+ if api is None:
359
+ api = get_default_api_type()
360
+
361
+ try:
362
+ client = APIClient(api_type=api)
363
+ response = client.get(f"/api/v1/firewalls/{firewall_id}/rules")
364
+
365
+ if response.status_code == 200:
366
+ data = response.json()
367
+ rules = _unwrap_response(data)
368
+
369
+ if not isinstance(rules, list):
370
+ console.print("[red]Error: Unexpected response format[/red]")
371
+ console.print(f"[dim]Expected list, got: {type(rules).__name__}[/dim]")
372
+ raise typer.Exit(1)
373
+
374
+ if not rules:
375
+ console.print(f"[yellow]No rules found for firewall {firewall_id}[/yellow]")
376
+ return
377
+
378
+ table = Table(title=f"Firewall Rules (Firewall ID: {firewall_id})")
379
+ table.add_column("ID", style="cyan")
380
+ table.add_column("Direction", style="yellow")
381
+ table.add_column("Protocol", style="magenta")
382
+ table.add_column("Port Range", style="green")
383
+ table.add_column("Source/Dest", style="white")
384
+ table.add_column("Action", style="blue")
385
+ table.add_column("Priority", justify="right", style="dim")
386
+
387
+ for rule in rules:
388
+ # Handle port range display
389
+ # API returns destination_ports for inbound, source_ports for outbound
390
+ # OR port_range_min/port_range_max for backwards compatibility
391
+ direction = rule.get("direction", "")
392
+
393
+ # Try new format first (arrays)
394
+ if direction == "inbound" or direction == "ingress":
395
+ ports = rule.get("destination_ports")
396
+ else:
397
+ ports = rule.get("source_ports")
398
+
399
+ # Fall back to old format (min/max)
400
+ if ports is None:
401
+ port_min = rule.get("port_range_min")
402
+ port_max = rule.get("port_range_max")
403
+ if port_min is not None and port_max is not None:
404
+ if port_min == port_max:
405
+ ports = [port_min]
406
+ else:
407
+ ports = [port_min, port_max]
408
+
409
+ if ports is None or len(ports) == 0:
410
+ port_range = "any"
411
+ elif len(ports) == 1:
412
+ port_range = str(ports[0])
413
+ elif len(ports) == 2:
414
+ port_range = f"{ports[0]}-{ports[1]}"
415
+ else:
416
+ # Multiple ports (not a range)
417
+ port_range = ",".join(str(p) for p in ports)
418
+
419
+ # Handle remote IP display
420
+ # API returns source_ips for inbound, destination_ips for outbound
421
+ # OR remote_ip_prefix for backwards compatibility
422
+ if direction == "inbound" or direction == "ingress":
423
+ ips = rule.get("source_ips")
424
+ else:
425
+ ips = rule.get("destination_ips")
426
+
427
+ # Fall back to old format (remote_ip_prefix)
428
+ if ips is None:
429
+ remote_ip = rule.get("remote_ip_prefix")
430
+ if remote_ip:
431
+ ips = [remote_ip]
432
+
433
+ if ips is None or len(ips) == 0:
434
+ ip_display = "any"
435
+ elif len(ips) == 1:
436
+ ip_display = ips[0]
437
+ else:
438
+ ip_display = ", ".join(ips[:2]) + ("..." if len(ips) > 2 else "")
439
+
440
+ table.add_row(
441
+ str(rule.get("id", "N/A")),
442
+ rule.get("direction", "N/A"),
443
+ rule.get("protocol", "N/A"),
444
+ port_range,
445
+ ip_display,
446
+ rule.get("action", "N/A"),
447
+ str(rule.get("priority", "N/A")),
448
+ )
449
+
450
+ console.print(table)
451
+ console.print(f"\n[dim]Total: {len(rules)} rule(s)[/dim]")
452
+
453
+ else:
454
+ _print_error(response)
455
+ raise typer.Exit(1)
456
+
457
+ except Exception as e:
458
+ console.print(f"[red]Error: {str(e)}[/red]")
459
+ raise typer.Exit(1) from None
460
+
461
+
462
+ @rules_app.command("create")
463
+ def create_rule(
464
+ firewall_id: str = typer.Argument(..., help="Firewall ID"),
465
+ direction: str = typer.Option(..., "--direction", help="Direction (ingress/inbound or egress/outbound)"),
466
+ protocol: str = typer.Option(..., "--protocol", help="Protocol (tcp, udp, icmp, or any)"),
467
+ name: str | None = typer.Option(None, "--name", "-n", help="Rule name (auto-generated if not provided)"),
468
+ action: str = typer.Option("allow", "--action", help="Action (allow or deny)"),
469
+ port_min: int | None = typer.Option(None, "--port-min", help="Minimum port number"),
470
+ port_max: int | None = typer.Option(None, "--port-max", help="Maximum port number"),
471
+ remote_ip: str | None = typer.Option(None, "--remote-ip", help="Remote IP prefix (CIDR notation)"),
472
+ priority: int | None = typer.Option(None, "--priority", help="Rule priority (lower = higher priority)"),
473
+ description: str | None = typer.Option(None, "--description", "-d", help="Rule description"),
474
+ api: str | None = typer.Option(
475
+ None, "--api", "-a", help="API type (admin or user). Uses default if not specified."
476
+ ),
477
+ ) -> None:
478
+ """Create a new firewall rule.
479
+
480
+ Add a new rule to the specified firewall.
481
+ """
482
+ if api is None:
483
+ api = get_default_api_type()
484
+
485
+ # Normalize direction: accept both ingress/inbound and egress/outbound
486
+ direction_map = {
487
+ "ingress": "inbound",
488
+ "inbound": "inbound",
489
+ "egress": "outbound",
490
+ "outbound": "outbound",
491
+ }
492
+
493
+ if direction.lower() not in direction_map:
494
+ console.print("[red]Error: Direction must be 'ingress', 'egress', 'inbound', or 'outbound'[/red]")
495
+ raise typer.Exit(1)
496
+
497
+ direction = direction_map[direction.lower()]
498
+
499
+ if protocol not in ["tcp", "udp", "icmp", "any"]:
500
+ console.print("[red]Error: Protocol must be 'tcp', 'udp', 'icmp', or 'any'[/red]")
501
+ raise typer.Exit(1)
502
+
503
+ if action not in ["allow", "deny"]:
504
+ console.print("[red]Error: Action must be 'allow' or 'deny'[/red]")
505
+ raise typer.Exit(1)
506
+
507
+ try:
508
+ client = APIClient(api_type=api)
509
+
510
+ # Auto-generate name if not provided
511
+ if name is None:
512
+ name = f"{action.capitalize()} {protocol.upper()} {direction}"
513
+ if port_min is not None:
514
+ if port_max is not None and port_max != port_min:
515
+ name += f" ports {port_min}-{port_max}"
516
+ else:
517
+ name += f" port {port_min}"
518
+
519
+ payload: dict[str, Any] = {
520
+ "name": name,
521
+ "direction": direction,
522
+ "protocol": protocol,
523
+ "action": action,
524
+ }
525
+
526
+ # Handle ports - API uses destination_ports for ingress, source_ports for egress
527
+ if port_min is not None or port_max is not None:
528
+ # Build port list: single port or range
529
+ ports: list[int] = []
530
+ if port_min is not None and port_max is not None:
531
+ if port_min == port_max:
532
+ ports = [port_min]
533
+ else:
534
+ ports = [port_min, port_max]
535
+ elif port_min is not None:
536
+ ports = [port_min]
537
+ elif port_max is not None:
538
+ ports = [port_max]
539
+
540
+ # Set the appropriate field based on direction
541
+ if direction == "inbound":
542
+ payload["destination_ports"] = ports
543
+ else:
544
+ payload["source_ports"] = ports
545
+
546
+ # Handle remote IP - API uses source_ips for inbound, destination_ips for outbound
547
+ if remote_ip:
548
+ if direction == "inbound":
549
+ payload["source_ips"] = [remote_ip]
550
+ else:
551
+ payload["destination_ips"] = [remote_ip]
552
+
553
+ if priority is not None:
554
+ payload["priority"] = priority
555
+ if description:
556
+ payload["description"] = description
557
+
558
+ response = client.post(f"/api/v1/firewalls/{firewall_id}/rules", data=payload)
559
+
560
+ if response.status_code in [200, 201]:
561
+ data_response = response.json()
562
+ rule = _unwrap_response(data_response)
563
+
564
+ # Format ports for display
565
+ direction = rule.get("direction", "")
566
+ if direction in ["inbound"]:
567
+ ports = rule.get("destination_ports")
568
+ else:
569
+ ports = rule.get("source_ports")
570
+
571
+ if ports is None or len(ports) == 0:
572
+ port_display = "any"
573
+ elif len(ports) == 1:
574
+ port_display = str(ports[0])
575
+ elif len(ports) == 2:
576
+ port_display = f"{ports[0]}-{ports[1]}"
577
+ else:
578
+ port_display = ",".join(str(p) for p in ports)
579
+
580
+ # Format IPs for display
581
+ if direction in ["inbound"]:
582
+ ips = rule.get("source_ips")
583
+ else:
584
+ ips = rule.get("destination_ips")
585
+
586
+ if ips is None or len(ips) == 0:
587
+ ip_display = "any"
588
+ elif len(ips) == 1:
589
+ ip_display = ips[0]
590
+ else:
591
+ ip_display = ", ".join(ips)
592
+
593
+ console.print("\n[green]✓[/green] Firewall rule created successfully!")
594
+ console.print(f"Rule ID: [cyan]{rule.get('id')}[/cyan]")
595
+ console.print(f"Name: [white]{rule.get('name')}[/white]")
596
+ console.print(f"Direction: [yellow]{rule.get('direction')}[/yellow]")
597
+ console.print(f"Protocol: [magenta]{rule.get('protocol')}[/magenta]")
598
+ console.print(f"Action: [blue]{rule.get('action')}[/blue]")
599
+ console.print(f"Port(s): [green]{port_display}[/green]")
600
+ console.print(f"Source/Dest: [white]{ip_display}[/white]")
601
+ console.print(f"Priority: [dim]{rule.get('priority', 100)}[/dim]")
602
+ if rule.get("description"):
603
+ console.print(f"Description: [dim]{rule.get('description')}[/dim]")
604
+ console.print()
605
+
606
+ else:
607
+ _print_error(response)
608
+ raise typer.Exit(1)
609
+
610
+ except Exception as e:
611
+ console.print(f"[red]Error: {str(e)}[/red]")
612
+ raise typer.Exit(1) from None
613
+
614
+
615
+ @rules_app.command("update")
616
+ def update_rule(
617
+ firewall_id: str = typer.Argument(..., help="Firewall ID"),
618
+ rule_id: str = typer.Argument(..., help="Rule ID"),
619
+ direction: str | None = typer.Option(None, "--direction", help="Direction (inbound or outbound)"),
620
+ protocol: str | None = typer.Option(None, "--protocol", help="Protocol (tcp, udp, icmp, or any)"),
621
+ action: str | None = typer.Option(None, "--action", help="Action (allow or deny)"),
622
+ port_min: int | None = typer.Option(None, "--port-min", help="Minimum port number"),
623
+ port_max: int | None = typer.Option(None, "--port-max", help="Maximum port number"),
624
+ remote_ip: str | None = typer.Option(None, "--remote-ip", help="Remote IP prefix (CIDR notation)"),
625
+ priority: int | None = typer.Option(None, "--priority", help="Rule priority (lower = higher priority)"),
626
+ description: str | None = typer.Option(None, "--description", "-d", help="Rule description"),
627
+ api: str | None = typer.Option(
628
+ None, "--api", "-a", help="API type (admin or user). Uses default if not specified."
629
+ ),
630
+ ) -> None:
631
+ """Update a firewall rule.
632
+
633
+ Modify an existing firewall rule.
634
+ """
635
+ if api is None:
636
+ api = get_default_api_type()
637
+
638
+ if direction and direction not in ["ingress", "egress"]:
639
+ console.print("[red]Error: Direction must be 'ingress' or 'egress'[/red]")
640
+ raise typer.Exit(1)
641
+
642
+ if protocol and protocol not in ["tcp", "udp", "icmp", "any"]:
643
+ console.print("[red]Error: Protocol must be 'tcp', 'udp', 'icmp', or 'any'[/red]")
644
+ raise typer.Exit(1)
645
+
646
+ if action and action not in ["allow", "deny"]:
647
+ console.print("[red]Error: Action must be 'allow' or 'deny'[/red]")
648
+ raise typer.Exit(1)
649
+
650
+ if not any([direction, protocol, action, port_min, port_max, remote_ip, priority, description]):
651
+ console.print("[red]Error: At least one field must be provided for update[/red]")
652
+ raise typer.Exit(1)
653
+
654
+ try:
655
+ client = APIClient(api_type=api)
656
+
657
+ payload: dict[str, Any] = {}
658
+ if direction:
659
+ payload["direction"] = direction
660
+ if protocol:
661
+ payload["protocol"] = protocol
662
+ if action:
663
+ payload["action"] = action
664
+ if port_min is not None:
665
+ payload["port_range_min"] = port_min
666
+ if port_max is not None:
667
+ payload["port_range_max"] = port_max
668
+ if remote_ip:
669
+ payload["remote_ip_prefix"] = remote_ip
670
+ if priority is not None:
671
+ payload["priority"] = priority
672
+ if description:
673
+ payload["description"] = description
674
+
675
+ response = client.patch(f"/api/v1/firewalls/{firewall_id}/rules/{rule_id}", data=payload)
676
+
677
+ if response.status_code == 200:
678
+ data_response = response.json()
679
+ rule = _unwrap_response(data_response)
680
+ console.print("\n[green]✓[/green] Firewall rule updated successfully!")
681
+ console.print(f"Rule ID: [cyan]{rule.get('id')}[/cyan]")
682
+ console.print(f"Direction: [yellow]{rule.get('direction')}[/yellow]")
683
+ console.print(f"Protocol: [magenta]{rule.get('protocol')}[/magenta]")
684
+ console.print(f"Action: [blue]{rule.get('action')}[/blue]")
685
+ console.print()
686
+
687
+ else:
688
+ _print_error(response)
689
+ raise typer.Exit(1)
690
+
691
+ except Exception as e:
692
+ console.print(f"[red]Error: {str(e)}[/red]")
693
+ raise typer.Exit(1) from None
694
+
695
+
696
+ @rules_app.command("delete")
697
+ def delete_rule(
698
+ firewall_id: str = typer.Argument(..., help="Firewall ID"),
699
+ rule_id: str = typer.Argument(..., help="Rule ID"),
700
+ force: bool = typer.Option(False, "--force", "-f", help="Skip confirmation prompt"),
701
+ api: str | None = typer.Option(
702
+ None, "--api", "-a", help="API type (admin or user). Uses default if not specified."
703
+ ),
704
+ ) -> None:
705
+ """Delete a firewall rule.
706
+
707
+ Remove a rule from the specified firewall.
708
+ """
709
+ if api is None:
710
+ api = get_default_api_type()
711
+
712
+ if not force:
713
+ confirm = typer.confirm(f"Are you sure you want to delete rule {rule_id} from firewall {firewall_id}?")
714
+ if not confirm:
715
+ console.print("[yellow]Deletion cancelled[/yellow]")
716
+ raise typer.Abort()
717
+
718
+ try:
719
+ client = APIClient(api_type=api)
720
+ response = client.delete(f"/api/v1/firewalls/{firewall_id}/rules/{rule_id}")
721
+
722
+ if response.status_code in [200, 204]:
723
+ console.print(f"[green]✓[/green] Rule {rule_id} deleted successfully from firewall {firewall_id}")
724
+
725
+ else:
726
+ _print_error(response)
727
+ raise typer.Exit(1)
728
+
729
+ except Exception as e:
730
+ console.print(f"[red]Error: {str(e)}[/red]")
731
+ raise typer.Exit(1) from None
732
+
733
+
734
+ # Additional utility commands
735
+
736
+
737
+ @app.command("by-name")
738
+ def get_firewall_by_name(
739
+ name: str = typer.Argument(..., help="Firewall name"),
740
+ api: str | None = typer.Option(
741
+ None, "--api", "-a", help="API type (admin or user). Uses default if not specified."
742
+ ),
743
+ ) -> None:
744
+ """Get firewall by name.
745
+
746
+ Find and display a firewall by its name.
747
+ """
748
+ if api is None:
749
+ api = get_default_api_type()
750
+
751
+ try:
752
+ client = APIClient(api_type=api)
753
+ response = client.get(f"/api/v1/firewalls/by-name?name={name}")
754
+
755
+ if response.status_code == 200:
756
+ data = response.json()
757
+ firewall = _unwrap_response(data)
758
+
759
+ console.print("\n[bold]Firewall Details[/bold]")
760
+ console.print("─" * 80)
761
+ console.print(f"ID: [cyan]{firewall.get('id', 'N/A')}[/cyan]")
762
+ console.print(f"Name: [green]{firewall.get('name', 'N/A')}[/green]")
763
+ console.print(f"Description: {firewall.get('description', 'N/A')}")
764
+ console.print(f"Created: [dim]{firewall.get('created_at', 'N/A')}[/dim]")
765
+ console.print()
766
+
767
+ else:
768
+ _print_error(response)
769
+ raise typer.Exit(1)
770
+
771
+ except Exception as e:
772
+ console.print(f"[red]Error: {str(e)}[/red]")
773
+ raise typer.Exit(1) from None
774
+
775
+
776
+ @app.command("clusters")
777
+ def get_firewall_clusters(
778
+ firewall_id: str = typer.Argument(..., help="Firewall ID"),
779
+ api: str | None = typer.Option(
780
+ None, "--api", "-a", help="API type (admin or user). Uses default if not specified."
781
+ ),
782
+ ) -> None:
783
+ """List clusters using a firewall.
784
+
785
+ Display all clusters that are using the specified firewall.
786
+ """
787
+ if api is None:
788
+ api = get_default_api_type()
789
+
790
+ try:
791
+ client = APIClient(api_type=api)
792
+ response = client.get(f"/api/v1/firewalls/{firewall_id}/clusters")
793
+
794
+ if response.status_code == 200:
795
+ data = response.json()
796
+ clusters = _unwrap_response(data)
797
+
798
+ # Handle case where clusters might still be wrapped or be a dict
799
+ if isinstance(clusters, dict):
800
+ # If it's still a dict, it might have a 'clusters' key or similar
801
+ if "clusters" in clusters:
802
+ clusters = clusters["clusters"]
803
+ else:
804
+ # Unexpected format, show what we got
805
+ console.print("[red]Error: Unexpected response format[/red]")
806
+ console.print(f"[dim]Response keys: {list(clusters.keys())}[/dim]")
807
+ raise typer.Exit(1)
808
+
809
+ if not isinstance(clusters, list):
810
+ console.print(f"[red]Error: Expected list, got {type(clusters).__name__}[/red]")
811
+ raise typer.Exit(1)
812
+
813
+ if not clusters:
814
+ console.print(f"[yellow]No clusters using firewall {firewall_id}[/yellow]")
815
+ return
816
+
817
+ # Log raw cluster data for debugging
818
+ logger.debug(f"Raw cluster data: {json.dumps(clusters, indent=2)}")
819
+
820
+ table = Table(title=f"Clusters Using Firewall {firewall_id}")
821
+ table.add_column("Cluster ID", style="cyan")
822
+ table.add_column("Name", style="green")
823
+ table.add_column("Status", style="yellow")
824
+ table.add_column("Provider", style="blue")
825
+
826
+ for cluster in clusters:
827
+ # Support both cluster_id and id, cluster_name and name
828
+ cluster_id_val = cluster.get("cluster_id") or cluster.get("id", "N/A")
829
+ cluster_name_val = cluster.get("cluster_name") or cluster.get("name", "N/A")
830
+
831
+ table.add_row(
832
+ str(cluster_id_val),
833
+ cluster_name_val,
834
+ cluster.get("status", "N/A"),
835
+ cluster.get("provider", "N/A"),
836
+ )
837
+
838
+ console.print(table)
839
+ console.print(f"\n[dim]Total: {len(clusters)} cluster(s)[/dim]")
840
+
841
+ else:
842
+ _print_error(response)
843
+ raise typer.Exit(1)
844
+
845
+ except Exception as e:
846
+ console.print(f"[red]Error: {str(e)}[/red]")
847
+ raise typer.Exit(1) from None
848
+
849
+
850
+ @app.command("validate-deletion")
851
+ def validate_firewall_deletion(
852
+ firewall_id: str = typer.Argument(..., help="Firewall ID"),
853
+ api: str | None = typer.Option(
854
+ None, "--api", "-a", help="API type (admin or user). Uses default if not specified."
855
+ ),
856
+ ) -> None:
857
+ """Validate if a firewall can be deleted.
858
+
859
+ Check if a firewall can be safely deleted without affecting active clusters.
860
+ """
861
+ if api is None:
862
+ api = get_default_api_type()
863
+
864
+ try:
865
+ client = APIClient(api_type=api)
866
+ response = client.get(f"/api/v1/firewalls/{firewall_id}/validate-deletion")
867
+
868
+ if response.status_code == 200:
869
+ data = response.json()
870
+ result = _unwrap_response(data)
871
+
872
+ can_delete = result.get("can_delete", False)
873
+ reasons = result.get("reasons", [])
874
+
875
+ console.print(f"\n[bold]Deletion Validation for Firewall {firewall_id}[/bold]")
876
+ console.print("─" * 80)
877
+
878
+ if can_delete:
879
+ console.print("[green]✓ Firewall can be safely deleted[/green]")
880
+ else:
881
+ console.print("[red]✗ Firewall cannot be deleted[/red]")
882
+ console.print("\n[yellow]Reasons:[/yellow]")
883
+ for reason in reasons:
884
+ console.print(f" • {reason}")
885
+
886
+ console.print()
887
+
888
+ else:
889
+ _print_error(response)
890
+ raise typer.Exit(1)
891
+
892
+ except Exception as e:
893
+ console.print(f"[red]Error: {str(e)}[/red]")
894
+ raise typer.Exit(1) from None