From bfffcef21fcd084fab5ad9c3621e1f4ddbdc5a8e Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Sat, 10 Oct 2026 12:40:37 +0000 Subject: [PATCH] Handle empty policy validation, domains without nameservers, and empty audit log values --- src/tailscale/cli/__init__.py | 2 +- src/tailscale/models.py | 18 ++++++ src/tailscale/tailscale.py | 22 ++++--- tests/cli/__snapshots__/test_cli.ambr | 12 ++++ tests/cli/test_cli.py | 17 ++++++ tests/test_tailscale.py | 82 +++++++++++++++++++++++++++ 6 files changed, 145 insertions(+), 8 deletions(-) diff --git a/src/tailscale/cli/__init__.py b/src/tailscale/cli/__init__.py index a489c0da..82e5545c 100644 --- a/src/tailscale/cli/__init__.py +++ b/src/tailscale/cli/__init__.py @@ -658,7 +658,7 @@ async def dns_split_command( table.add_column("Nameservers") for domain, nameservers in result.items(): - table.add_row(domain, ", ".join(nameservers)) + table.add_row(domain, ", ".join(nameservers or []) or "[dim]-[/dim]") console.print(table) diff --git a/src/tailscale/models.py b/src/tailscale/models.py index c1d28119..54e5584d 100644 --- a/src/tailscale/models.py +++ b/src/tailscale/models.py @@ -1020,6 +1020,24 @@ class AuditLog(_LenientModel): old: Any = None origin: str | None = None + @classmethod + def __pre_deserialize__(cls, d: dict[Any, Any]) -> dict[Any, Any]: + """Leave out empty values, but keep the old and new values as they are. + + An empty string there is what the property was set to, or from. + + Args: + ---- + d: The raw API response data. + + Returns: + ------- + The adjusted data ready for deserialization. + + """ + values = {key: d[key] for key in ("old", "new") if key in d} + return {**super().__pre_deserialize__(d), **values} + @dataclass class NetworkTraffic(_LenientModel): diff --git a/src/tailscale/tailscale.py b/src/tailscale/tailscale.py index 4761577a..bd7806c7 100644 --- a/src/tailscale/tailscale.py +++ b/src/tailscale/tailscale.py @@ -749,12 +749,13 @@ async def set_dns_search_paths(self, *, search_paths: list[str]) -> DNSSearchPat ) return DNSSearchPaths.from_json(data) - async def split_dns(self) -> dict[str, list[str]]: + async def split_dns(self) -> dict[str, list[str] | None]: """Get the split DNS configuration for the tailnet. Returns ------- - A dictionary mapping domain names to lists of nameserver addresses. + A dictionary mapping domain names to lists of nameserver addresses, + or None for a domain without nameservers. """ data = await self._request( @@ -763,8 +764,8 @@ async def split_dns(self) -> dict[str, list[str]]: return json.loads(data) async def set_split_dns( - self, *, split_dns: dict[str, list[str]] - ) -> dict[str, list[str]]: + self, *, split_dns: dict[str, list[str] | None] + ) -> dict[str, list[str] | None]: """Replace the split DNS configuration for the tailnet. Args: @@ -785,14 +786,15 @@ async def set_split_dns( return json.loads(data) async def update_split_dns( - self, *, split_dns: dict[str, list[str]] - ) -> dict[str, list[str]]: + self, *, split_dns: dict[str, list[str] | None] + ) -> dict[str, list[str] | None]: """Update part of the split DNS configuration for the tailnet. Args: ---- split_dns: A dictionary mapping domain names to lists of - nameserver addresses. Only provided domains are updated. + nameserver addresses. Only provided domains are updated; a + domain set to None is removed. Returns: ------- @@ -870,6 +872,9 @@ async def validate_policy_file(self, policy: str) -> PolicyFileValidation: content=policy, headers={"Content-Type": "application/hujson"}, ) + # The API answers with an empty body when everything passes. + if not data.strip(): + return PolicyFileValidation() return PolicyFileValidation.from_json(data) async def test_policy_file( @@ -893,6 +898,9 @@ async def test_policy_file( content=json.dumps(tests), headers={"Content-Type": "application/json"}, ) + # The API answers with an empty body when everything passes. + if not data.strip(): + return PolicyFileValidation() return PolicyFileValidation.from_json(data) async def preview_policy_rules( diff --git a/tests/cli/__snapshots__/test_cli.ambr b/tests/cli/__snapshots__/test_cli.ambr index fd10ae7b..28086267 100644 --- a/tests/cli/__snapshots__/test_cli.ambr +++ b/tests/cli/__snapshots__/test_cli.ambr @@ -661,6 +661,18 @@ ''' # --- +# name: test_dns_split_command_without_nameservers + ''' + Split DNS + ┏━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┓ + ┃ Domain ┃ Nameservers ┃ + ┡━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━┩ + │ corp.example.com │ 10.0.0.53 │ + │ old.example.com │ - │ + └──────────────────┴─────────────┘ + + ''' +# --- # name: test_expire_key_command ''' Key expired for device 12345. diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.py index 94c2b713..229bc811 100644 --- a/tests/cli/test_cli.py +++ b/tests/cli/test_cli.py @@ -756,6 +756,23 @@ def test_audit_logs_command( assert call.kwargs["end"] - call.kwargs["start"] == timedelta(hours=2) +def test_dns_split_command_without_nameservers( + runner: CliRunner, + snapshot: SnapshotAssertion, +) -> None: + """DNS split command shows a domain without nameservers.""" + mock_client = _mock_tailscale() + mock_client.split_dns.return_value = { + "corp.example.com": ["10.0.0.53"], + "old.example.com": None, + } + exit_code, output = _invoke( + runner, ["dns", "split", "--api-key", "tskey-api-test"], mock_client + ) + assert exit_code == 0 + assert output == snapshot + + # --- action commands --- diff --git a/tests/test_tailscale.py b/tests/test_tailscale.py index 505a5fc1..2dfa3755 100644 --- a/tests/test_tailscale.py +++ b/tests/test_tailscale.py @@ -3567,3 +3567,85 @@ async def test_malformed_oauth_token_response(body: str, reason: str) -> None: assert "tskey-secret" not in str(excinfo.value) assert tailscale.api_key is None await tailscale.close() + + +# --- Correctness tests --- + + +@pytest.mark.parametrize("method", ["validate_policy_file", "test_policy_file"]) +async def test_policy_validation_empty_body( + responses: aioresponses, + tailscale_client: Tailscale, + method: str, +) -> None: + """Test an empty body, which the API sends when all passes, is valid.""" + responses.post( + f"{URL}/tailnet/frenck/acl/validate", + status=200, + body="", + content_type="application/json", + ) + argument: Any = [] if method == "test_policy_file" else "{}" + validation = await getattr(tailscale_client, method)(argument) + + assert validation.valid is True + assert validation.data == [] + + +async def test_split_dns_domain_without_nameservers( + responses: aioresponses, + tailscale_client: Tailscale, +) -> None: + """Test a domain without nameservers comes back as None.""" + responses.get( + f"{URL}/tailnet/frenck/dns/split-dns", + status=200, + body='{"corp.example.com": ["10.0.0.53"], "old.example.com": null}', + content_type="application/json", + ) + assert await tailscale_client.split_dns() == { + "corp.example.com": ["10.0.0.53"], + "old.example.com": None, + } + + +async def test_update_split_dns_removes_domain( + responses: aioresponses, + tailscale_client: Tailscale, +) -> None: + """Test a domain set to None is sent as null, which removes it.""" + responses.patch( + f"{URL}/tailnet/frenck/dns/split-dns", + status=200, + body='{"corp.example.com": ["10.0.0.53"]}', + content_type="application/json", + ) + await tailscale_client.update_split_dns(split_dns={"old.example.com": None}) + + assert responses.requests + (request,) = next(iter(responses.requests.values())) + assert request.kwargs["json"] == {"old.example.com": None} + + +async def test_audit_log_keeps_empty_old_and_new( + responses: aioresponses, + tailscale_client: Tailscale, +) -> None: + """Test an empty old or new value is kept, as it is what it was set to.""" + responses.get( + f"{URL}/tailnet/frenck/logging/configuration" + "?start=2026-10-09T00:00:00%2B00:00&end=2026-10-10T00:00:00%2B00:00", + status=200, + body='{"logs": [{"action": "UPDATE", "actor": {"id": "u1"},' + '"eventTime": "2026-10-09T20:00:00Z", "eventGroupID": "",' + '"target": {"id": "n1", "property": "MACHINE_NAME"},' + '"old": "server", "new": ""}]}', + content_type="application/json", + ) + (log,) = await tailscale_client.configuration_audit_logs( + start=datetime(2026, 10, 9, tzinfo=UTC), + end=datetime(2026, 10, 10, tzinfo=UTC), + ) + + assert (log.old, log.new) == ("server", "") + assert log.event_group_id is None