diff --git a/README.md b/README.md index d1942a90..6b3464bd 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,18 @@ tailscale-api settings external-tailnets admin tailscale-api settings https --enable tailscale-api settings route-selection regional-routing +# Edit the policy file (HuJSON, comments included). The ETag makes sure it is +# not set when someone else changed it in the meantime. +ETAG="$(tailscale-api policy show --etag)" +tailscale-api policy show > policy.hujson +tailscale-api policy validate policy.hujson +tailscale-api policy set policy.hujson --etag "$ETAG" + +# List webhooks and Services, and the configuration changes of the last day +tailscale-api webhooks +tailscale-api services +tailscale-api audit-logs --hours 24 + # List and manage auth keys tailscale-api keys tailscale-api delete-key k1234567890abcdef diff --git a/src/tailscale/cli/__init__.py b/src/tailscale/cli/__init__.py index 86bf8e2d..f95fe477 100644 --- a/src/tailscale/cli/__init__.py +++ b/src/tailscale/cli/__init__.py @@ -5,6 +5,7 @@ import json import sys from datetime import UTC, datetime, timedelta +from pathlib import Path from typing import Annotated import typer @@ -1069,17 +1070,202 @@ async def settings_posture_identity_command( console.print(f"[green]Posture identity collection {state}.[/green]") +LogHours = Annotated[ + int, + typer.Option("--hours", help="How many hours of logs to show", min=1), +] + +policy = AsyncTyper( + help="Show, validate, and set the policy file of the tailnet.", + no_args_is_help=True, +) +cli.add_typer(policy, name="policy") + +PolicyPath = Annotated[ + Path, + typer.Argument( + help="Path to a policy file, as HuJSON or JSON", + exists=True, + dir_okay=False, + readable=True, + ), +] + + +@policy.command("show") +async def policy_show_command( + etag: Annotated[ + bool, + typer.Option("--etag", help="Show the ETag instead of the policy file"), + ] = False, + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Show the policy file, with its comments, as HuJSON.""" + client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) + async with client: + policy_file = await client.policy_file() + typer.echo(policy_file.etag if etag else policy_file.policy) + + +@policy.command("validate") +async def policy_validate_command( + path: PolicyPath, + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Validate a policy file, and run its tests, without setting it.""" + client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) + async with client: + validation = await client.validate_policy_file(path.read_text(encoding="utf-8")) + + if validation.valid: + console.print("[green]The policy file is valid.[/green]") + return + + console.print(f"[red]The policy file is not valid: {validation.message}[/red]") + for result in validation.data: + for error in result.errors: + console.print(f" [bold]{result.user}[/bold]: {error}") + sys.exit(1) + + +@policy.command("set") +async def policy_set_command( + path: PolicyPath, + etag: Annotated[ + str | None, + typer.Option( + "--etag", + help=( + "Only set it when the policy file is still at this ETag, " + "from policy show --etag" + ), + ), + ] = None, + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Set the policy file of the tailnet.""" + client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) + async with client: + policy_file = await client.set_policy_file( + path.read_text(encoding="utf-8"), etag=etag + ) + console.print(f"[green]Policy file set (ETag {policy_file.etag}).[/green]") + + +@cli.command("webhooks") +async def webhooks_command( + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """List all webhooks in the tailnet.""" + client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) + async with client: + webhooks = await client.webhooks() + + table = Table(title="Webhooks", show_header=True, border_style="dim") + table.add_column("Endpoint ID", style="cyan") + table.add_column("URL", style="bold") + table.add_column("Provider") + table.add_column("Events") + + for webhook in webhooks: + table.add_row( + webhook.endpoint_id, + webhook.endpoint_url, + webhook.provider_type or "[dim]-[/dim]", + ", ".join(webhook.subscriptions), + ) + + console.print(table) + + +@cli.command("services") +async def services_command( + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """List all Services in the tailnet.""" + client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) + async with client: + services = await client.services() + + table = Table(title="Services", show_header=True, border_style="dim") + table.add_column("Name", style="cyan") + table.add_column("Addresses") + table.add_column("Ports") + table.add_column("Tags") + table.add_column("Comment") + + for service in services: + table.add_row( + service.name, + ", ".join(service.addrs) or "[dim]-[/dim]", + ", ".join(service.ports) or "[dim]-[/dim]", + ", ".join(service.tags) or "[dim]-[/dim]", + service.comment or "", + ) + + console.print(table) + + +@cli.command("audit-logs") +async def audit_logs_command( + hours: LogHours = 24, + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """List the configuration changes of the last hours.""" + end = datetime.now(UTC) + client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) + async with client: + logs = await client.configuration_audit_logs( + start=end - timedelta(hours=hours), end=end + ) + + table = Table(title="Audit logs", show_header=True, border_style="dim") + table.add_column("Time", style="cyan") + table.add_column("Actor", style="bold") + table.add_column("Action") + table.add_column("Target") + table.add_column("Property") + + for log in logs: + actor = log.actor.login_name or log.actor.display_name or log.actor.actor_id + target = " ".join( + part for part in (log.target.target_type, log.target.name) if part + ) + table.add_row( + log.event_time.isoformat(timespec="seconds"), + actor, + log.action or "", + target, + log.target.property or "", + ) + + console.print(table) + + dump = AsyncTyper( help="Dump raw API responses as JSON (useful for debugging/fixtures).", no_args_is_help=True, ) cli.add_typer(dump, name="dump") -LogHours = Annotated[ - int, - typer.Option("--hours", help="How many hours of logs to dump", min=1), -] - async def _dump( # pylint: disable=too-many-arguments tailnet: str, diff --git a/tests/cli/__snapshots__/test_cli.ambr b/tests/cli/__snapshots__/test_cli.ambr index e98d0db6..fd10ae7b 100644 --- a/tests/cli/__snapshots__/test_cli.ambr +++ b/tests/cli/__snapshots__/test_cli.ambr @@ -1,4 +1,16 @@ # serializer version: 1 +# name: test_audit_logs_command + ''' + Audit logs + ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┓ + ┃ Time ┃ Actor ┃ Action ┃ Target ┃ Property ┃ + ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━┩ + │ 2026-10-09T18:39:35+00:00 │ alice@example.com │ UPDATE │ NODE server │ MACHINE_NAME │ + │ 2026-10-09T19:00:00+00:00 │ nDEVICE123 │ │ ADMIN_CONSOLE │ │ + └───────────────────────────┴───────────────────┴────────┴───────────────┴──────────────┘ + + ''' +# --- # name: test_authentication_error_handler ''' ╭───────────────── Authentication error ──────────────────╮ @@ -18,6 +30,13 @@ # --- # name: test_cli_structure dict({ + 'audit-logs': list([ + 'api_key', + 'hours', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), 'authorize': list([ 'api_key', 'device_id', @@ -307,6 +326,30 @@ 'oauth_client_secret', 'tailnet', ]), + 'policy': dict({ + 'set': list([ + 'api_key', + 'etag', + 'oauth_client_id', + 'oauth_client_secret', + 'path', + 'tailnet', + ]), + 'show': list([ + 'api_key', + 'etag', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), + 'validate': list([ + 'api_key', + 'oauth_client_id', + 'oauth_client_secret', + 'path', + 'tailnet', + ]), + }), 'rename': list([ 'api_key', 'device_id', @@ -322,6 +365,12 @@ 'oauth_client_secret', 'tailnet', ]), + 'services': list([ + 'api_key', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), 'set-ip': list([ 'api_key', 'device_id', @@ -445,6 +494,12 @@ 'oauth_client_secret', 'tailnet', ]), + 'webhooks': list([ + 'api_key', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), }) # --- # name: test_connection_error_handler @@ -656,6 +711,25 @@ ''' # --- +# name: test_policy_set_command + ''' + Policy file set (ETag "e5678"). + + ''' +# --- +# name: test_policy_validate_command + ''' + The policy file is valid. + + ''' +# --- +# name: test_policy_validate_command_invalid + ''' + The policy file is not valid: test(s) failed + alice@example.com: address "100.64.0.1:22": want: Drop, got: Accept + + ''' +# --- # name: test_rename_command ''' Device 12345 renamed to new-hostname. @@ -675,6 +749,18 @@ ''' # --- +# name: test_services_command + ''' + Services + ┏━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━┓ + ┃ Name ┃ Addresses ┃ Ports ┃ Tags ┃ Comment ┃ + ┡━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━┩ + │ svc:web │ 100.100.100.100 │ tcp:443 │ tag:web │ The website │ + │ svc:bare │ - │ - │ - │ │ + └──────────┴─────────────────┴─────────┴─────────┴─────────────┘ + + ''' +# --- # name: test_set_ip_command ''' IPv4 address for device 12345 set to 100.64.0.1. @@ -808,3 +894,15 @@ ''' # --- +# name: test_webhooks_command + ''' + Webhooks + ┏━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━┓ + ┃ Endpoint ID ┃ URL ┃ Provider ┃ Events ┃ + ┡━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━┩ + │ e1234CNTRL │ https://example.com/tailscale │ - │ nodeCreated, nodeDeleted │ + │ e5678CNTRL │ https://hooks.slack.com/services/T000 │ slack │ userNeedsApproval │ + └─────────────┴───────────────────────────────────────┴──────────┴──────────────────────────┘ + + ''' +# --- diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.py index ae4c4de9..43e0b3a2 100644 --- a/tests/cli/test_cli.py +++ b/tests/cli/test_cli.py @@ -4,7 +4,7 @@ from __future__ import annotations import json -from datetime import datetime, timedelta +from datetime import UTC, datetime, timedelta from importlib.metadata import entry_points from typing import TYPE_CHECKING from unittest.mock import AsyncMock, MagicMock, patch @@ -22,19 +22,29 @@ TailscalePermissionError, ) from tailscale.models import ( + AuditLog, + AuditLogActor, + AuditLogTarget, Device, DeviceRoutes, Devices, DNSNameservers, DNSPreferences, DNSSearchPaths, + PolicyFile, + PolicyFileValidation, + PolicyTestResult, TailnetSettings, TailscaleKey, + TailscaleService, TailscaleUser, + TailscaleWebhook, ) from tests.conftest import FIXTURES_DIR if TYPE_CHECKING: + from pathlib import Path + from syrupy.assertion import SnapshotAssertion @@ -558,6 +568,194 @@ def test_settings_route_selection_command( ) +# --- policy, webhook, Service, and audit log commands --- + + +def test_policy_show_command(runner: CliRunner) -> None: + """Policy show command prints the policy file as HuJSON.""" + mock_client = _mock_tailscale() + mock_client.policy_file.return_value = PolicyFile( + policy='// Comment\n{"acls": []}\n', etag='"e1234"' + ) + exit_code, output = _invoke( + runner, ["policy", "show", "--api-key", "tskey-api-test"], mock_client + ) + assert exit_code == 0 + assert output == '// Comment\n{"acls": []}\n\n' + + +def test_policy_show_etag_command(runner: CliRunner) -> None: + """Policy show command prints the ETag with --etag.""" + mock_client = _mock_tailscale() + mock_client.policy_file.return_value = PolicyFile(policy="{}", etag='"e1234"') + exit_code, output = _invoke( + runner, + ["policy", "show", "--etag", "--api-key", "tskey-api-test"], + mock_client, + ) + assert exit_code == 0 + assert output == '"e1234"\n' + + +def test_policy_validate_command( + runner: CliRunner, + tmp_path: Path, + snapshot: SnapshotAssertion, +) -> None: + """Policy validate command says when the policy file is valid.""" + policy_path = tmp_path / "policy.hujson" + policy_path.write_text('{"acls": []}') + mock_client = _mock_tailscale() + mock_client.validate_policy_file.return_value = PolicyFileValidation() + exit_code, output = _invoke( + runner, + ["policy", "validate", str(policy_path), "--api-key", "tskey-api-test"], + mock_client, + ) + assert exit_code == 0 + assert output == snapshot + mock_client.validate_policy_file.assert_called_once_with('{"acls": []}') + + +def test_policy_validate_command_invalid( + runner: CliRunner, + tmp_path: Path, + snapshot: SnapshotAssertion, +) -> None: + """Policy validate command shows why the policy file is not valid.""" + policy_path = tmp_path / "policy.hujson" + policy_path.write_text('{"acls": []}') + mock_client = _mock_tailscale() + mock_client.validate_policy_file.return_value = PolicyFileValidation( + message="test(s) failed", + data=[ + PolicyTestResult( + user="alice@example.com", + errors=['address "100.64.0.1:22": want: Drop, got: Accept'], + ) + ], + ) + exit_code, output = _invoke( + runner, + ["policy", "validate", str(policy_path), "--api-key", "tskey-api-test"], + mock_client, + ) + assert exit_code == 1 + assert output == snapshot + + +def test_policy_set_command( + runner: CliRunner, + tmp_path: Path, + snapshot: SnapshotAssertion, +) -> None: + """Policy set command sets the policy file, guarded by the ETag.""" + policy_path = tmp_path / "policy.hujson" + policy_path.write_text('{"acls": []}') + mock_client = _mock_tailscale() + mock_client.set_policy_file.return_value = PolicyFile( + policy='{"acls": []}', etag='"e5678"' + ) + exit_code, output = _invoke( + runner, + [ + "policy", + "set", + str(policy_path), + "--etag", + '"e1234"', + "--api-key", + "tskey-api-test", + ], + mock_client, + ) + assert exit_code == 0 + assert output == snapshot + mock_client.set_policy_file.assert_called_once_with('{"acls": []}', etag='"e1234"') + + +def test_webhooks_command( + runner: CliRunner, + snapshot: SnapshotAssertion, +) -> None: + """Webhooks command renders a table of all webhooks.""" + mock_client = _mock_tailscale() + mock_client.webhooks.return_value = [ + TailscaleWebhook( + endpoint_id="e1234CNTRL", + endpoint_url="https://example.com/tailscale", + subscriptions=["nodeCreated", "nodeDeleted"], + ), + TailscaleWebhook( + endpoint_id="e5678CNTRL", + endpoint_url="https://hooks.slack.com/services/T000", + provider_type="slack", + subscriptions=["userNeedsApproval"], + ), + ] + exit_code, output = _invoke( + runner, ["webhooks", "--api-key", "tskey-api-test"], mock_client + ) + assert exit_code == 0 + assert output == snapshot + + +def test_services_command( + runner: CliRunner, + snapshot: SnapshotAssertion, +) -> None: + """Services command renders a table of all Services.""" + mock_client = _mock_tailscale() + mock_client.services.return_value = [ + TailscaleService( + name="svc:web", + addrs=["100.100.100.100"], + ports=["tcp:443"], + tags=["tag:web"], + comment="The website", + ), + TailscaleService(name="svc:bare"), + ] + exit_code, output = _invoke( + runner, ["services", "--api-key", "tskey-api-test"], mock_client + ) + assert exit_code == 0 + assert output == snapshot + + +def test_audit_logs_command( + runner: CliRunner, + snapshot: SnapshotAssertion, +) -> None: + """Audit logs command renders a table of the configuration changes.""" + mock_client = _mock_tailscale() + mock_client.configuration_audit_logs.return_value = [ + AuditLog( + actor=AuditLogActor(actor_id="u1", login_name="alice@example.com"), + event_time=datetime(2026, 10, 9, 18, 39, 35, tzinfo=UTC), + target=AuditLogTarget( + target_type="NODE", name="server", property="MACHINE_NAME" + ), + action="UPDATE", + ), + AuditLog( + actor=AuditLogActor(actor_id="nDEVICE123"), + event_time=datetime(2026, 10, 9, 19, 0, tzinfo=UTC), + target=AuditLogTarget(target_type="ADMIN_CONSOLE"), + ), + ] + exit_code, output = _invoke( + runner, + ["audit-logs", "--hours", "2", "--api-key", "tskey-api-test"], + mock_client, + ) + assert exit_code == 0 + assert output == snapshot + + call = mock_client.configuration_audit_logs.call_args + assert call.kwargs["end"] - call.kwargs["start"] == timedelta(hours=2) + + # --- action commands ---