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
8 changes: 8 additions & 0 deletions changelog.d/1595.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
### Added

- Reach the Kubernetes API off the home network at `k8s.<domain>` through the Cloudflare Tunnel: `k8s/cloudflared/networkpolicy.yaml` lets cloudflared reach the API server on 6443, `cloudflared` is a `tools.lock` binary that `devops install-tools --tool cloudflared` installs, and `k8s/README.md` gives the TCP route, the `cloudflared access tcp` listener and the kubeconfig context ([#1595](https://github.com/dan-petty/devops-cli/issues/1595)).

### Fixed

- `devops cloudflare tunnel sync` places a new hostname before the first wildcard rule that would match it, since cloudflared takes the first matching rule; it appended new hostnames after every rule, so a host under an existing `*.<domain>` route was never reached ([#1595](https://github.com/dan-petty/devops-cli/issues/1595)).
- A `tools.lock` build may name its own `format`, for a tool packed differently per platform such as cloudflared's macOS `.tgz` ([#1595](https://github.com/dan-petty/devops-cli/issues/1595)).
23 changes: 23 additions & 0 deletions k8s/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,29 @@ Expose homelab Kubernetes services securely to the internet without public ports
devops k8s render k8s/ingress/ingress-routes.yaml
```

### 4. The Kubernetes API at `k8s.<domain>`

Off the home network, `kubectl` reaches the API server through the tunnel as a TCP route. An HTTP hostname cannot carry it: Cloudflare ends TLS at its edge, which drops kubectl's client certificate. `cloudflared access tcp` on the workstation carries the connection to the edge after an Access login, and TLS stays end to end between kubectl and the API server.

1. Route the hostname to the API server. `tunnel sync` merges into the tunnel's configuration and places a new hostname ahead of any wildcard rule that would take its traffic (cloudflared uses the first rule that matches). Use a hostname an Access application covers: `devops cloudflare access status` lists them, and `devops cloudflare access sync --domain k8s.<domain> -e <email>` adds one.
```bash
devops cloudflare tunnel sync --subdomains k8s --service tcp://kubernetes.default.svc.cluster.local:443 --dry-run
devops cloudflare tunnel sync --subdomains k8s --service tcp://kubernetes.default.svc.cluster.local:443
```
`k8s/cloudflared/networkpolicy.yaml` lets cloudflared reach the API server on 6443.
2. On the workstation, install `cloudflared` from `tools.lock` and open the local end of the route. The first connection prints an Access login URL to open.
```bash
devops install-tools --tool cloudflared
cloudflared access tcp --hostname k8s.<domain> --url 127.0.0.1:16443
```
3. Add a context that reaches the API server through it, with the credentials and CA of the cluster entry you use at home (`<cluster>` and `<user>` in `kubectl config view`):
```bash
kubectl config set-cluster <cluster>-tunnel --server=https://127.0.0.1:16443 --tls-server-name=kubernetes.default.svc
kubectl config set clusters.<cluster>-tunnel.certificate-authority-data "$(kubectl config view --raw -o jsonpath='{.clusters[?(@.name=="<cluster>")].cluster.certificate-authority-data}')"
kubectl config set-context <cluster>-tunnel --cluster=<cluster>-tunnel --user=<user>
kubectl --context <cluster>-tunnel get nodes
```

## Directory Structure

```
Expand Down
11 changes: 11 additions & 0 deletions k8s/cloudflared/networkpolicy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,17 @@ spec:
port: 7844
- protocol: TCP
port: 7844
# Allow the tunnel's k8s.<domain> TCP route to reach the API server. The `kubernetes`
# Service resolves to the node's address on 6443, which no namespace selector matches, so
# the peer is an ipBlock with the cloud metadata address excluded, as Argo CD's is.
- to:
- ipBlock:
cidr: 0.0.0.0/0
except:
- 169.254.169.254/32
ports:
- protocol: TCP
port: 6443
# Allow forwarding traffic exclusively to Traefik in kube-system.
# NOTE: no `ports:` restriction here — this cluster's kube-router NetworkPolicy
# engine fails to enforce (as "allow") egress rules that combine a peer
Expand Down
23 changes: 21 additions & 2 deletions src/devops_cli/cloudflare/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
CONST_CLOUDFLARE_DEFAULT_SESSION_DURATION,
CONST_CLOUDFLARE_DEFAULT_SUBDOMAINS,
CONST_CLOUDFLARE_RECORD_COMMENT,
CONST_CLOUDFLARE_WILDCARD_PREFIX,
CONST_URL_CLOUDFLARE_API_BASE,
)
from devops_cli.exceptions.cloudflare import CloudflareAPIError, CloudflareAuthError
Expand Down Expand Up @@ -133,19 +134,37 @@ def _merge_existing_and_target_rules(
return merged


def _wildcard_matches(pattern: str | None, hostname: str | None) -> bool:
"""Whether cloudflared matches `hostname` to the rule hostname `pattern`: a leading `*.`
matches any name ending in the rest (`matchHost` in cloudflared's ingress/rule.go)."""
if not pattern or not hostname or not pattern.startswith(CONST_CLOUDFLARE_WILDCARD_PREFIX):
return False
return hostname.lower().endswith(pattern[1:].lower())


def _insertion_index(rules: list[CloudflareTunnelIngressRule], hostname: str | None) -> int:
"""Where a new rule for `hostname` goes: before the first rule whose wildcard would match it,
since cloudflared takes the first match, else after every rule (#1595)."""
return next(
(i for i, rule in enumerate(rules) if _wildcard_matches(rule.hostname, hostname)),
len(rules),
)


def _merge_tunnel_ingress_rules(
current_rules: list[CloudflareTunnelIngressRule],
target_rules: list[CloudflareTunnelIngressRule],
) -> list[CloudflareTunnelIngressRule]:
"""Merge target ingress rules into current rules, preserving other routes and catch-all."""
"""Merge target ingress rules into current rules, preserving other routes and catch-all. A
new hostname goes before any wildcard rule that would otherwise take its traffic."""
target_by_key = {key: r for r in target_rules if (key := _rule_routing_key(r)) is not None}
seen_keys: set[tuple[str | None, str | None]] = set()
merged = _merge_existing_and_target_rules(current_rules, target_by_key, seen_keys)

for r in target_rules:
key = _rule_routing_key(r)
if key is not None and key not in seen_keys:
merged.append(r)
merged.insert(_insertion_index(merged, r.hostname), r)
seen_keys.add(key)

existing_catchall = next((r for r in current_rules if not r.hostname and not r.path), None)
Expand Down
2 changes: 1 addition & 1 deletion src/devops_cli/commands/install_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def install_binary(name: str, entry: BinaryTool, target_dir: Path) -> None:
with _staged(tool_install_dir(name, entry.version)) as stage:
data = _download(artifact.url)
_verify_sha256(name, data, artifact.sha256)
_UNPACKERS[entry.format](data, artifact, stage / entry.bin)
_UNPACKERS[entry.format_of(artifact)](data, artifact, stage / entry.bin)
_link_commands(name, entry, target_dir)


Expand Down
2 changes: 2 additions & 0 deletions src/devops_cli/config/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,8 @@
CONST_CLOUDFLARE_DEFAULT_SERVICE = "http://traefik.kube-system.svc.cluster.local:80"
CONST_CLOUDFLARE_CATCHALL_SERVICE = "http_status:404"
CONST_CLOUDFLARE_DEFAULT_SUBDOMAINS: tuple[str, ...] = ("*", "@")
# The only wildcard a tunnel ingress hostname takes: a leading `*.` (cloudflared ingress/rule.go).
CONST_CLOUDFLARE_WILDCARD_PREFIX = "*."
CONST_CLOUDFLARE_RECORD_COMMENT: Final[str] = "Managed by devops-cli"
CONST_CLOUDFLARE_BYPASS_POLICY_NAME: Final[str] = "homelab-public-ip-bypass"
CONST_CLOUDFLARE_ALLOW_POLICY_NAME: Final[str] = "Allow homelab authorized emails"
Expand Down
11 changes: 10 additions & 1 deletion src/devops_cli/tools_lock/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,18 @@ class _LockEntry(BaseModel):
model_config = ConfigDict(frozen=True, extra="forbid")


ArchiveFormat = Literal["binary", "gzip", "tar.gz"]


class Artifact(_LockEntry):
"""One platform's build of a binary tool: where it is fetched from and its SHA-256."""

url: str
sha256: str
# The archive member that is the tool, for a tar.gz build.
member: str | None = None
# A build packed unlike the tool's others, such as cloudflared's macOS tar.gz.
format: ArchiveFormat | None = None


class BinaryTool(_LockEntry):
Expand All @@ -45,10 +50,14 @@ class BinaryTool(_LockEntry):
description: str
source: str
bin: str
format: Literal["binary", "gzip", "tar.gz"]
format: ArchiveFormat
# Builds by `<os>-<arch>`, such as `linux-amd64`.
platforms: dict[str, Artifact]

def format_of(self, artifact: Artifact) -> ArchiveFormat:
"""How `artifact` is packed: its own format, else the tool's."""
return artifact.format or self.format

@property
def commands(self) -> tuple[str, ...]:
"""The commands the tool puts on PATH."""
Expand Down
29 changes: 29 additions & 0 deletions src/devops_cli/tools_lock/tools.lock
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
# alone gives it: popeye's `checksums.sha256`, get.helm.sh's `<archive>.sha256sum` and
# dl.k8s.io's `kubectl.sha256`. Trivy's version is also the `version` of every
# `aquasecurity/trivy-action` step in `.github/workflows/`.
# cloudflared's release notes give each macOS checksum for the binary inside the `.tgz`, not
# the archive: check the archive's digest by unpacking it and hashing `cloudflared`.
#
# To bump a Python tool, set its `version` here and in `<name>.in`, then, in this directory, run
# uv pip compile --universal --generate-hashes --python-version 3.14 <name>.in -o <name>.txt
Expand Down Expand Up @@ -145,6 +147,33 @@ sha256 = "2b414b2d1d4c224db3ca07bec343522270242acca8e8f8f55865a32a3ef49b9c"
url = "https://github.com/argoproj/argo-cd/releases/download/v3.5.4/argocd-darwin-arm64"
sha256 = "aac1cd7606c5960513edfc2a3ee7226c3860f0982f63b93b2f7e8b5c4d880873"

[binary.cloudflared]
version = "2026.9.3"
description = "Cloudflare Tunnel client, for kubectl over cloudflared access tcp"
source = "https://github.com/cloudflare/cloudflared"
bin = "cloudflared"
format = "binary"

[binary.cloudflared.platforms.linux-amd64]
url = "https://github.com/cloudflare/cloudflared/releases/download/2026.9.3/cloudflared-linux-amd64"
sha256 = "77e26d8d900e0b8469f416239d14b5f296525fdf79fee6f511ef55609e3fbac2"

[binary.cloudflared.platforms.linux-arm64]
url = "https://github.com/cloudflare/cloudflared/releases/download/2026.9.3/cloudflared-linux-arm64"
sha256 = "aaeb2d7d0da3614634c7e03ab13487a1522c2e79165ed2929cfe23d5e95b326d"

[binary.cloudflared.platforms.darwin-amd64]
url = "https://github.com/cloudflare/cloudflared/releases/download/2026.9.3/cloudflared-darwin-amd64.tgz"
sha256 = "d1155d0837487f261183b15c1eab6c4ebcad9dc49b94675f1524c3564cea3977"
format = "tar.gz"
member = "cloudflared"

[binary.cloudflared.platforms.darwin-arm64]
url = "https://github.com/cloudflare/cloudflared/releases/download/2026.9.3/cloudflared-darwin-arm64.tgz"
sha256 = "587c2cfb1c230fe36c7fa7727da78be459dae028cabe8c001291999350f07095"
format = "tar.gz"
member = "cloudflared"

[binary.kubectl-argo-rollouts]
version = "1.10.0"
description = "Argo Rollouts kubectl plugin"
Expand Down
53 changes: 53 additions & 0 deletions tests/test_cloudflare_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,59 @@ def fake_request(method: str, path: str, **kwargs: Any) -> Any:
assert (len(put_calls), put_body) == (1, expected_put)


@pytest.mark.parametrize(
("existing", "subdomain", "order"),
[
(
["*.example.com", "example.com"],
"k8s",
["k8s.example.com", "*.example.com", "example.com", None],
),
(
["*.lab.example.com", "*.example.com"],
"k8s.lab",
["k8s.lab.example.com", "*.lab.example.com", "*.example.com", None],
),
(["a.example.com"], "k8s", ["a.example.com", "k8s.example.com", None]),
],
ids=["under-a-wildcard", "under-the-nearest-wildcard", "no-wildcard"],
)
def test_a_new_hostname_goes_before_the_wildcard_cloudflared_would_match_it_to(
existing: list[str], subdomain: str, order: list[str | None]
) -> None:
"""cloudflared takes the first rule whose hostname matches, and `*.example.com` matches any
name ending in `.example.com`: a host added after it would never be reached (#1595)."""
client = CloudflareClient(token="test-token", account_id="acc-1")
current = {
"config": {
"ingress": [
*({"hostname": host, "service": "http://traefik:80"} for host in existing),
{"service": "http_status:404"},
]
}
}
sent: list[Any] = []

def fake_request(method: str, path: str, **kwargs: Any) -> Any:
if method == "GET":
return current
sent.append(kwargs["json_data"]["config"]["ingress"])
return {"config": kwargs["json_data"]["config"], "version": 2}

with (
patch.object(client, "resolve_tunnel_id", return_value="tunnel-1"),
patch.object(client, "_request", side_effect=fake_request),
):
client.sync_tunnel_routes(
tunnel_id="tunnel-1",
domain="example.com",
service="tcp://kubernetes.default.svc.cluster.local:443",
subdomains=[subdomain],
)

assert [rule.get("hostname") for rule in sent[0]] == order


def test_cloudflare_tunnel_sync_aborts_on_get_failure(mock_settings: Settings) -> None:
"""When GET of current tunnel config fails, sync raises an error and sends no PUT request."""
mock_client = MagicMock()
Expand Down
19 changes: 19 additions & 0 deletions tests/test_install_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ def _binary_entry(
name: str = "mytool",
archive_format: str = "binary",
member: str | None = None,
build_format: str | None = None,
) -> BinaryTool:
"""A lock entry for `name` 1.2.3 whose build for this platform is `artifact`, served at
`https://example.com/releases/<name>`."""
Expand All @@ -78,6 +79,7 @@ def _binary_entry(
"url": f"https://example.com/releases/{name}",
"sha256": hashlib.sha256(artifact).hexdigest(),
"member": member,
**({"format": build_format} if build_format else {}),
}
},
}
Expand Down Expand Up @@ -197,6 +199,23 @@ def test_each_archive_format_unpacks_to_the_tool(
assert (tmp_path / "bin" / "mytool").read_bytes() == EXECUTABLE


def test_a_build_packed_unlike_the_tools_others_unpacks_by_its_own_format(
stub_web: StubWeb, tmp_path: Path, isolate_user_data_root: Path
) -> None:
"""cloudflared publishes bare Linux binaries and macOS tar.gz archives: a build's own format
wins over the tool's."""
artifact = _tar_gz({"cloudflared": EXECUTABLE})
stub_web.content(ASSET_URL, artifact)

install_binary(
"mytool",
_binary_entry(artifact, member="cloudflared", build_format="tar.gz"),
tmp_path / "bin",
)

assert (tmp_path / "bin" / "mytool").read_bytes() == EXECUTABLE


def test_a_platform_the_lock_has_no_build_for_is_named(stub_web: StubWeb, tmp_path: Path) -> None:
"""A platform missing from the lock fails before any request, naming the tool and platform."""
entry = _binary_entry(EXECUTABLE).model_copy(update={"platforms": {}})
Expand Down
9 changes: 6 additions & 3 deletions tests/test_k8s_cloudflared.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,15 @@ def test_cloudflared_traefik_egress_rule_has_no_port_restriction() -> None:
to enforce (as "allow") egress rules that combine a peer selector (`to:`) with a
`ports:` restriction in the same rule, causing traffic matching such a rule to be
refused as if no rule existed. Re-adding a `ports:` restriction to this specific
rule would reintroduce the "connection refused" bug reaching Traefik.
rule would reintroduce the "connection refused" bug reaching Traefik. The API server rule
pairs an ipBlock peer with `ports:`, which kube-router enforces, as Argo CD's has since #1371.
"""
policy = yaml.safe_load((CLOUDFLARED_DIR / "networkpolicy.yaml").read_text(encoding="utf-8"))
egress_rules = policy["spec"]["egress"]
traefik_rules = [rule for rule in egress_rules if "to" in rule]
assert len(traefik_rules) == 1, "Expected exactly one egress rule with a `to:` peer selector"
traefik_rules = [
rule for rule in egress_rules if any("podSelector" in peer for peer in rule.get("to", []))
]
assert len(traefik_rules) == 1, "Expected exactly one egress rule with a pod selector peer"

traefik_rule = traefik_rules[0]
assert "ports" not in traefik_rule
Expand Down
10 changes: 6 additions & 4 deletions tests/test_k8s_network_policies.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,14 +245,16 @@ def test_ingress_admits_no_world_cidr(namespace: str) -> None:
assert cidrs == []


def test_argocd_api_server_egress_admits_6443_through_ipblock() -> None:
"""Verify Argo CD's API-server egress admits 6443 through an ipBlock peer (#1371).
@pytest.mark.parametrize("namespace", ["argocd", "cloudflared"])
def test_api_server_egress_admits_6443_through_ipblock(namespace: str) -> None:
"""Argo CD reconciles through the API server (#1371), and cloudflared carries the tunnel's
`k8s.<domain>` TCP route to it (#1595).

Namespace-only selectors (default, kube-system) never match the node IP the
`kubernetes` service resolves to. An ipBlock peer with metadata SSRF protection
allows Argo CD to reach the API server on 6443.
allows the pods to reach the API server on 6443.
"""
doc = yaml.safe_load((K8S_DIR / "argocd" / "networkpolicy.yaml").read_text("utf-8"))
doc = yaml.safe_load((K8S_DIR / namespace / "networkpolicy.yaml").read_text("utf-8"))
egress = doc["spec"]["egress"]
rule = next(r for r in egress if any(p.get("port") == 6443 for p in r.get("ports", [])))
ip_blocks = [to["ipBlock"] for to in rule.get("to", []) if "ipBlock" in to]
Expand Down
3 changes: 2 additions & 1 deletion tests/test_tools_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"helm",
"argo",
"argocd",
"cloudflared",
"kubectl-argo-rollouts",
"trivy",
"kube-linter",
Expand All @@ -50,7 +51,7 @@ def test_every_binary_build_is_an_https_url_with_a_sha256() -> None:
"""Each platform build is fetched over https and checked against a 32-byte SHA-256, and a
tar.gz build names the archive member that is the tool."""
builds = [
(name, tool.format, artifact)
(name, tool.format_of(artifact), artifact)
for name, tool in load_tools_lock().binary.items()
for artifact in tool.platforms.values()
]
Expand Down
Loading