From 57cde9a5e5c005c8460ef61aadf2016ef4d807fa Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Sat, 10 Oct 2026 11:36:26 +0000 Subject: [PATCH] Add dump commands for the whole API, and say when the API refuses a request --- README.md | 19 +- src/tailscale/cli/__init__.py | 530 ++++++++++++++++++++++---- tests/cli/__snapshots__/test_cli.ambr | 118 ++++++ tests/cli/test_cli.py | 112 ++++++ 4 files changed, 701 insertions(+), 78 deletions(-) diff --git a/README.md b/README.md index 188e02e1..8be5ccfc 100644 --- a/README.md +++ b/README.md @@ -115,15 +115,32 @@ tailscale-api delete-key k1234567890abcdef tailscale-api dump devices tailscale-api dump device nSRVBN3CNTRL tailscale-api dump routes nSRVBN3CNTRL +tailscale-api dump device-posture-attributes nSRVBN3CNTRL +tailscale-api dump device-invites nSRVBN3CNTRL +tailscale-api dump dns-configuration tailscale-api dump dns-nameservers tailscale-api dump dns-preferences tailscale-api dump dns-search-paths tailscale-api dump dns-split tailscale-api dump users tailscale-api dump user u12345 -tailscale-api dump settings +tailscale-api dump user-invites tailscale-api dump keys tailscale-api dump key k1234567890abcdef +tailscale-api dump settings +tailscale-api dump policy +tailscale-api dump webhooks +tailscale-api dump services +tailscale-api dump service svc:example +tailscale-api dump service-hosts svc:example +tailscale-api dump posture-integrations +tailscale-api dump oauth-apps +tailscale-api dump contacts +tailscale-api dump organization-tailnets +tailscale-api dump audit-logs --hours 24 +tailscale-api dump network-logs --hours 1 +tailscale-api dump log-stream network +tailscale-api dump log-stream-status configuration ``` OAuth authentication is also supported via `--oauth-client-id` and diff --git a/src/tailscale/cli/__init__.py b/src/tailscale/cli/__init__.py index 882d87b4..86bf8e2d 100644 --- a/src/tailscale/cli/__init__.py +++ b/src/tailscale/cli/__init__.py @@ -4,6 +4,7 @@ import json import sys +from datetime import UTC, datetime, timedelta from typing import Annotated import typer @@ -15,6 +16,7 @@ TailscaleAuthenticationError, TailscaleConnectionError, TailscaleError, + TailscalePermissionError, ) from tailscale.tailscale import Tailscale @@ -61,6 +63,21 @@ ] +# Registered before the authentication error handler, as the first handler that +# matches is used, and a permission error is an authentication error too. +@cli.error_handler(TailscalePermissionError) +def permission_error_handler(err: TailscalePermissionError) -> None: + """Handle the API refusing a request the credentials are not allowed.""" + panel = Panel( + f"The Tailscale API refused the request: {err.reason}", + expand=False, + title="Permission denied", + border_style="red bold", + ) + console.print(panel) + sys.exit(1) + + @cli.error_handler(TailscaleAuthenticationError) def authentication_error_handler(_: TailscaleAuthenticationError) -> None: """Handle authentication errors.""" @@ -1058,6 +1075,32 @@ async def settings_posture_identity_command( ) 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, + api_key: str | None, + oauth_client_id: str | None, + oauth_client_secret: str | None, + uri: str, + *, + params: dict[str, str] | None = None, +) -> None: + """Print the raw JSON response of the Tailscale API for a URI. + + A "{tailnet}" in the URI is replaced by the tailnet in use. + """ + client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) + async with client: + data = await client._request( # noqa: SLF001 + uri.replace("{tailnet}", client.tailnet), params=params + ) + typer.echo(json.dumps(json.loads(data), indent=2, default=str)) + @dump.command("devices") async def dump_devices_command( @@ -1067,12 +1110,13 @@ async def dump_devices_command( oauth_client_secret: OAuthClientSecret = None, ) -> None: """Dump all devices as raw JSON.""" - client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) - async with client: - data = await client._request( # noqa: SLF001 - f"tailnet/{client.tailnet}/devices?fields=all" - ) - typer.echo(json.dumps(json.loads(data), indent=2, default=str)) + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/devices?fields=all", + ) @dump.command("device") @@ -1087,12 +1131,93 @@ async def dump_device_command( oauth_client_secret: OAuthClientSecret = None, ) -> None: """Dump a single device as raw JSON.""" - client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) - async with client: - data = await client._request( # noqa: SLF001 - f"device/{device_id}?fields=all" - ) - typer.echo(json.dumps(json.loads(data), indent=2, default=str)) + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + f"device/{device_id}?fields=all", + ) + + +@dump.command("routes") +async def dump_routes_command( + device_id: Annotated[ + str, + typer.Argument(help="Device ID or node ID"), + ], + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump device routes as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + f"device/{device_id}/routes", + ) + + +@dump.command("device-posture-attributes") +async def dump_device_posture_attributes_command( + device_id: Annotated[ + str, + typer.Argument(help="Device ID or node ID"), + ], + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump the posture attributes of a device as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + f"device/{device_id}/attributes", + ) + + +@dump.command("device-invites") +async def dump_device_invites_command( + device_id: Annotated[ + str, + typer.Argument(help="Device ID or node ID"), + ], + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump the invites to share a device as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + f"device/{device_id}/device-invites", + ) + + +@dump.command("dns-configuration") +async def dump_dns_configuration_command( + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump the full DNS configuration as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/dns/configuration", + ) @dump.command("dns-nameservers") @@ -1103,12 +1228,13 @@ async def dump_dns_nameservers_command( oauth_client_secret: OAuthClientSecret = None, ) -> None: """Dump DNS nameservers as raw JSON.""" - client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) - async with client: - data = await client._request( # noqa: SLF001 - f"tailnet/{client.tailnet}/dns/nameservers" - ) - typer.echo(json.dumps(json.loads(data), indent=2, default=str)) + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/dns/nameservers", + ) @dump.command("dns-preferences") @@ -1119,12 +1245,13 @@ async def dump_dns_preferences_command( oauth_client_secret: OAuthClientSecret = None, ) -> None: """Dump DNS preferences as raw JSON.""" - client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) - async with client: - data = await client._request( # noqa: SLF001 - f"tailnet/{client.tailnet}/dns/preferences" - ) - typer.echo(json.dumps(json.loads(data), indent=2, default=str)) + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/dns/preferences", + ) @dump.command("dns-search-paths") @@ -1135,12 +1262,13 @@ async def dump_dns_search_paths_command( oauth_client_secret: OAuthClientSecret = None, ) -> None: """Dump DNS search paths as raw JSON.""" - client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) - async with client: - data = await client._request( # noqa: SLF001 - f"tailnet/{client.tailnet}/dns/searchpaths" - ) - typer.echo(json.dumps(json.loads(data), indent=2, default=str)) + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/dns/searchpaths", + ) @dump.command("dns-split") @@ -1151,12 +1279,13 @@ async def dump_dns_split_command( oauth_client_secret: OAuthClientSecret = None, ) -> None: """Dump split DNS configuration as raw JSON.""" - client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) - async with client: - data = await client._request( # noqa: SLF001 - f"tailnet/{client.tailnet}/dns/split-dns" - ) - typer.echo(json.dumps(json.loads(data), indent=2, default=str)) + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/dns/split-dns", + ) @dump.command("users") @@ -1167,12 +1296,13 @@ async def dump_users_command( oauth_client_secret: OAuthClientSecret = None, ) -> None: """Dump all users as raw JSON.""" - client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) - async with client: - data = await client._request( # noqa: SLF001 - f"tailnet/{client.tailnet}/users" - ) - typer.echo(json.dumps(json.loads(data), indent=2, default=str)) + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/users?type=all", + ) @dump.command("user") @@ -1187,12 +1317,30 @@ async def dump_user_command( oauth_client_secret: OAuthClientSecret = None, ) -> None: """Dump a single user as raw JSON.""" - client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) - async with client: - data = await client._request( # noqa: SLF001 - f"users/{user_id}" - ) - typer.echo(json.dumps(json.loads(data), indent=2, default=str)) + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + f"users/{user_id}", + ) + + +@dump.command("user-invites") +async def dump_user_invites_command( + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump the open invites for users as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/user-invites", + ) @dump.command("keys") @@ -1203,12 +1351,13 @@ async def dump_keys_command( oauth_client_secret: OAuthClientSecret = None, ) -> None: """Dump all keys as raw JSON.""" - client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) - async with client: - data = await client._request( # noqa: SLF001 - f"tailnet/{client.tailnet}/keys?all=true" - ) - typer.echo(json.dumps(json.loads(data), indent=2, default=str)) + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/keys?all=true", + ) @dump.command("key") @@ -1223,12 +1372,13 @@ async def dump_key_command( oauth_client_secret: OAuthClientSecret = None, ) -> None: """Dump a single key as raw JSON.""" - client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) - async with client: - data = await client._request( # noqa: SLF001 - f"tailnet/{client.tailnet}/keys/{key_id}" - ) - typer.echo(json.dumps(json.loads(data), indent=2, default=str)) + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + f"tailnet/{{tailnet}}/keys/{key_id}", + ) @dump.command("settings") @@ -1239,29 +1389,255 @@ async def dump_settings_command( oauth_client_secret: OAuthClientSecret = None, ) -> None: """Dump tailnet settings as raw JSON.""" - client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) - async with client: - data = await client._request( # noqa: SLF001 - f"tailnet/{client.tailnet}/settings" - ) - typer.echo(json.dumps(json.loads(data), indent=2, default=str)) + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/settings", + ) -@dump.command("routes") -async def dump_routes_command( - device_id: Annotated[ +@dump.command("policy") +async def dump_policy_command( + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump the policy file as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/acl", + ) + + +@dump.command("webhooks") +async def dump_webhooks_command( + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump all webhooks as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/webhooks", + ) + + +@dump.command("services") +async def dump_services_command( + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump all Services as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/services", + ) + + +@dump.command("service") +async def dump_service_command( + name: Annotated[ str, - typer.Argument(help="Device ID or node ID"), + typer.Argument(help="Service name, like svc:example"), ], tailnet: Tailnet = "-", api_key: ApiKey = None, oauth_client_id: OAuthClientId = None, oauth_client_secret: OAuthClientSecret = None, ) -> None: - """Dump device routes as raw JSON.""" - client = _build_client(tailnet, api_key, oauth_client_id, oauth_client_secret) - async with client: - data = await client._request( # noqa: SLF001 - f"device/{device_id}/routes" - ) - typer.echo(json.dumps(json.loads(data), indent=2, default=str)) + """Dump a single Service as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + f"tailnet/{{tailnet}}/services/{name}", + ) + + +@dump.command("service-hosts") +async def dump_service_hosts_command( + name: Annotated[ + str, + typer.Argument(help="Service name, like svc:example"), + ], + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump the devices hosting a Service as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + f"tailnet/{{tailnet}}/services/{name}/devices", + ) + + +@dump.command("posture-integrations") +async def dump_posture_integrations_command( + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump the posture integrations as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/posture/integrations", + ) + + +@dump.command("oauth-apps") +async def dump_oauth_apps_command( + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump the OAuth apps as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/oauth-apps", + ) + + +@dump.command("contacts") +async def dump_contacts_command( + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump the contacts of the tailnet as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/contacts", + ) + + +@dump.command("organization-tailnets") +async def dump_organization_tailnets_command( + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump the tailnets of the organization as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "organizations/-/tailnets", + ) + + +@dump.command("log-stream") +async def dump_log_stream_command( + log_type: Annotated[ + str, + typer.Argument(help="Log type (configuration/network)"), + ], + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump the log streaming configuration as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + f"tailnet/{{tailnet}}/logging/{log_type}/stream", + ) + + +@dump.command("log-stream-status") +async def dump_log_stream_status_command( + log_type: Annotated[ + str, + typer.Argument(help="Log type (configuration/network)"), + ], + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump the log streaming status as raw JSON.""" + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + f"tailnet/{{tailnet}}/logging/{log_type}/stream/status", + ) + + +@dump.command("audit-logs") +async def dump_audit_logs_command( + hours: LogHours = 24, + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump the configuration audit logs as raw JSON.""" + end = datetime.now(UTC) + start = end - timedelta(hours=hours) + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/logging/configuration", + params={"start": start.isoformat(), "end": end.isoformat()}, + ) + + +@dump.command("network-logs") +async def dump_network_logs_command( + hours: LogHours = 24, + tailnet: Tailnet = "-", + api_key: ApiKey = None, + oauth_client_id: OAuthClientId = None, + oauth_client_secret: OAuthClientSecret = None, +) -> None: + """Dump the network flow logs as raw JSON.""" + end = datetime.now(UTC) + start = end - timedelta(hours=hours) + await _dump( + tailnet, + api_key, + oauth_client_id, + oauth_client_secret, + "tailnet/{tailnet}/logging/network", + params={"start": start.isoformat(), "end": end.isoformat()}, + ) diff --git a/tests/cli/__snapshots__/test_cli.ambr b/tests/cli/__snapshots__/test_cli.ambr index 9085c2e8..e98d0db6 100644 --- a/tests/cli/__snapshots__/test_cli.ambr +++ b/tests/cli/__snapshots__/test_cli.ambr @@ -107,6 +107,19 @@ ]), }), 'dump': dict({ + 'audit-logs': list([ + 'api_key', + 'hours', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), + 'contacts': list([ + 'api_key', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), 'device': list([ 'api_key', 'device_id', @@ -114,12 +127,32 @@ 'oauth_client_secret', 'tailnet', ]), + 'device-invites': list([ + 'api_key', + 'device_id', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), + 'device-posture-attributes': list([ + 'api_key', + 'device_id', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), 'devices': list([ 'api_key', 'oauth_client_id', 'oauth_client_secret', 'tailnet', ]), + 'dns-configuration': list([ + 'api_key', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), 'dns-nameservers': list([ 'api_key', 'oauth_client_id', @@ -157,6 +190,51 @@ 'oauth_client_secret', 'tailnet', ]), + 'log-stream': list([ + 'api_key', + 'log_type', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), + 'log-stream-status': list([ + 'api_key', + 'log_type', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), + 'network-logs': list([ + 'api_key', + 'hours', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), + 'oauth-apps': list([ + 'api_key', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), + 'organization-tailnets': list([ + 'api_key', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), + 'policy': list([ + 'api_key', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), + 'posture-integrations': list([ + 'api_key', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), 'routes': list([ 'api_key', 'device_id', @@ -164,6 +242,26 @@ 'oauth_client_secret', 'tailnet', ]), + 'service': list([ + 'api_key', + 'name', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), + 'service-hosts': list([ + 'api_key', + 'name', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), + 'services': list([ + 'api_key', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), 'settings': list([ 'api_key', 'oauth_client_id', @@ -177,12 +275,24 @@ 'tailnet', 'user_id', ]), + 'user-invites': list([ + 'api_key', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), 'users': list([ 'api_key', 'oauth_client_id', 'oauth_client_secret', 'tailnet', ]), + 'webhooks': list([ + 'api_key', + 'oauth_client_id', + 'oauth_client_secret', + 'tailnet', + ]), }), 'expire-key': list([ 'api_key', @@ -538,6 +648,14 @@ ''' # --- +# name: test_permission_error_handler + ''' + ╭───────────────────────────────── Permission denied ──────────────────────────────────╮ + │ The Tailscale API refused the request: feature not available on current billing plan │ + ╰──────────────────────────────────────────────────────────────────────────────────────╯ + + ''' +# --- # name: test_rename_command ''' Device 12345 renamed to new-hostname. diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.py index 4894d874..ae4c4de9 100644 --- a/tests/cli/test_cli.py +++ b/tests/cli/test_cli.py @@ -4,6 +4,7 @@ from __future__ import annotations import json +from datetime import datetime, timedelta from importlib.metadata import entry_points from typing import TYPE_CHECKING from unittest.mock import AsyncMock, MagicMock, patch @@ -18,6 +19,7 @@ TailscaleAuthenticationError, TailscaleConnectionError, TailscaleError, + TailscalePermissionError, ) from tailscale.models import ( Device, @@ -960,6 +962,30 @@ def test_authentication_error_handler( assert capsys.readouterr().out == snapshot +def test_permission_error_handler( + capsys: pytest.CaptureFixture[str], + snapshot: SnapshotAssertion, +) -> None: + """Permission error handler prints the reason of the API and exits with 1.""" + handler = cli.error_handlers[TailscalePermissionError] + with pytest.raises(SystemExit) as exc_info: + handler( + TailscalePermissionError( + 403, "feature not available on current billing plan" + ) + ) + assert exc_info.value.code == 1 + assert capsys.readouterr().out == snapshot + + +def test_permission_error_handler_is_used_first() -> None: + """A permission error does not get the authentication error handler.""" + handlers = list(cli.error_handlers) + assert handlers.index(TailscalePermissionError) < handlers.index( + TailscaleAuthenticationError + ) + + def test_connection_error_handler( capsys: pytest.CaptureFixture[str], snapshot: SnapshotAssertion, @@ -992,3 +1018,89 @@ def test_console_script() -> None: if entry_point.value.startswith("tailscale.") } assert scripts == {"tailscale-api": "tailscale._cli:main"} + + +@pytest.mark.parametrize( + ("args", "uri"), + [ + (["devices"], "tailnet/-/devices?fields=all"), + (["device", "n1"], "device/n1?fields=all"), + (["routes", "n1"], "device/n1/routes"), + (["device-posture-attributes", "n1"], "device/n1/attributes"), + (["device-invites", "n1"], "device/n1/device-invites"), + (["dns-configuration"], "tailnet/-/dns/configuration"), + (["dns-nameservers"], "tailnet/-/dns/nameservers"), + (["dns-preferences"], "tailnet/-/dns/preferences"), + (["dns-search-paths"], "tailnet/-/dns/searchpaths"), + (["dns-split"], "tailnet/-/dns/split-dns"), + (["users"], "tailnet/-/users?type=all"), + (["user", "u1"], "users/u1"), + (["user-invites"], "tailnet/-/user-invites"), + (["keys"], "tailnet/-/keys?all=true"), + (["key", "k1"], "tailnet/-/keys/k1"), + (["settings"], "tailnet/-/settings"), + (["policy"], "tailnet/-/acl"), + (["webhooks"], "tailnet/-/webhooks"), + (["services"], "tailnet/-/services"), + (["service", "svc:web"], "tailnet/-/services/svc:web"), + (["service-hosts", "svc:web"], "tailnet/-/services/svc:web/devices"), + (["posture-integrations"], "tailnet/-/posture/integrations"), + (["oauth-apps"], "tailnet/-/oauth-apps"), + (["contacts"], "tailnet/-/contacts"), + (["organization-tailnets"], "organizations/-/tailnets"), + (["log-stream", "network"], "tailnet/-/logging/network/stream"), + ( + ["log-stream-status", "configuration"], + "tailnet/-/logging/configuration/stream/status", + ), + ], +) +def test_dump_commands( + runner: CliRunner, + args: list[str], + uri: str, +) -> None: + """Dump commands request their endpoint and print its raw JSON.""" + mock_client = _mock_tailscale(raw_response='{"answer": [42]}') + exit_code, output = _invoke( + runner, + ["dump", *args, "--api-key", "tskey-api-test"], + mock_client, + ) + assert exit_code == 0 + assert json.loads(output) == {"answer": [42]} + mock_client._request.assert_called_once_with( # pylint: disable=protected-access + uri, params=None + ) + + +@pytest.mark.parametrize( + ("command", "uri"), + [ + ("audit-logs", "tailnet/-/logging/configuration"), + ("network-logs", "tailnet/-/logging/network"), + ], +) +def test_dump_log_commands( + runner: CliRunner, + command: str, + uri: str, +) -> None: + """Dump log commands request the given hours of logs.""" + mock_client = _mock_tailscale(raw_response='{"logs": null}') + exit_code, output = _invoke( + runner, + ["dump", command, "--hours", "2", "--api-key", "tskey-api-test"], + mock_client, + ) + assert exit_code == 0 + assert json.loads(output) == {"logs": None} + + mock_client._request.assert_called_once() # pylint: disable=protected-access + call = mock_client._request.call_args # pylint: disable=protected-access + assert call.args == (uri,) + params = call.kwargs["params"] + start = datetime.fromisoformat(params["start"]) + end = datetime.fromisoformat(params["end"]) + assert end - start == timedelta(hours=2) + assert end.tzinfo is not None