Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/tailscale/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
18 changes: 18 additions & 0 deletions src/tailscale/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
22 changes: 15 additions & 7 deletions src/tailscale/tailscale.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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:
Expand All @@ -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:
-------
Expand Down Expand Up @@ -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(
Expand All @@ -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(
Expand Down
12 changes: 12 additions & 0 deletions tests/cli/__snapshots__/test_cli.ambr
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
17 changes: 17 additions & 0 deletions tests/cli/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ---


Expand Down
82 changes: 82 additions & 0 deletions tests/test_tailscale.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading