On mk4, my old Hetzner cluster, every GitHub Actions workflow talked to the Kubernetes API over the internet. The API port was open to everyone, and a ServiceAccount token in each repository's secrets was all that stood between a stranger and my cluster. When I built the new cluster at Contabo, I closed port 6443 to everything except my own addresses. That also locked out GitHub's runners, which deploy everything I run.

This post is how my workflows get in now: an SSH user that can open one tunnel to the API and do nothing else, a ServiceAccount per repository, and one workflow that hands out the keys and tokens. You can copy the pattern to any cluster whose API you don't want on the internet.

This is part 4 of a six-part series on moving jithendar.com's k3s cluster from Hetzner to Contabo. Part 2 (opens in a new tab) built the cluster; Part 3 (opens in a new tab) rebuilt the images for amd64.

How it worked on mk4

I wrote the mk4 setup up in detail in How GitHub Actions Authenticates to My k3s Cluster (opens in a new tab). The short version: the cluster file I created mk4 with, hetzner-k3s.yaml in k8s-deployments, let anyone reach the API.

YAML
  allowed_networks:
    ssh:
      - 0.0.0.0/0   # tighten to your own IP, e.g. 203.0.113.4/32
    api:
      - 0.0.0.0/0   # tighten to your own IP

Each repository filled in a kubeconfig template at run time from two variables and a secret. From jithendar.com's .github/jithendar-ci-applier.yaml, as it was before the move:

YAML
clusters:
- name: mk4
  cluster:
    server: ${MK4_API_SERVER}
    certificate-authority-data: ${MK4_CA_DATA}
users:
- name: github-ci-applier
  user:
    token: ${MK4_CI_APPLY_TOKEN}

I set those values from my laptop with scripts/setup-ci-applier.sh. It worked, but I never liked two things: the API listening on the internet, and tokens I copied around by hand.

The rule on Contabo: port 6443 is for me only

On the new cluster, Ansible's prepare.yml turns on ufw and opens the API only to ADMIN_CIDRS, which comes from a secret because the repository is public:

YAML
    - name: Allow the Kubernetes API from the administrators
      community.general.ufw:
        rule: allow
        port: "6443"
        proto: tcp
        from_ip: "{{ item }}"
      loop: "{{ api_cidrs }}"

SSH stays open to the internet, keys only, and group_vars/all.yml says why: "GitHub's runners, which run the deploy workflow, connect from changing addresses." So a runner can reach port 22 but not 6443. The answer is a tunnel, and the trick is making sure the tunnel can't be used for anything else.

How a GitHub Actions job reaches the Kubernetes API, before and now. Before, on mk4: repository secrets MK4_API_SERVER, MK4_CA_DATA and MK4_CI_APPLY_TOKEN, set from a laptop, feed a job that calls the mk4 API on its public address on port 6443, which hetzner-k3s.yaml allowed from 0.0.0.0/0. Now, on contabo-k3s: repository secrets CONTABO_K3S_SSH_KEY, CONTABO_K3S_SSH_HOST, CONTABO_K3S_CA_DATA and one token feed a job running the action contabo-k3s-api. It opens SSH to master-1 as kube-tunnel, whose key may only forward to 127.0.0.1 and whose only command is nologin; the tunnel reaches the k3s API, where the token signs in as the repository's ServiceAccount with its own Role. The job's kubeconfig points at 127.0.0.1 and is checked with kubectl auth whoami. A direct connection to port 6443 is refused by ufw, which admits only ADMIN_CIDRS. Below, the workflow Contabo k3s CI access, run by hand in k8s-deployments: 1, a new ed25519 tunnel key that api-tunnel.yml makes the only authorized key; 2, the RBAC files from ci-access.yml applied as cluster-admin; 3, token Secrets created and tested with whoami through kube-tunnel; 4, the secrets written into each repository with a GitHub App token limited to those repositories.

A user that can only open one tunnel

The playbook contabo-k3s/ansible/api-tunnel.yml creates a system user, kube-tunnel, with /usr/sbin/nologin as its shell and a .ssh directory owned by root, so the user can't change its own keys. Its one authorized key carries its own limits:

YAML
        content: >
          restrict,port-forwarding,permitopen="127.0.0.1:6443",command="/usr/sbin/nologin"
          {{ (kube_tunnel_public_key | split(' '))[0:2] | join(' ') }} kube-tunnel

restrict turns everything off, port-forwarding turns local forwarding back on, permitopen limits it to the API on the node itself, and command replaces anything the client asks to run. The same rules go into sshd too, in /etc/ssh/sshd_config.d/50-kube-tunnel.conf:

Match User kube-tunnel
  AllowTcpForwarding local
  PermitOpen 127.0.0.1:6443
  AllowAgentForwarding no
  AllowStreamLocalForwarding no
  X11Forwarding no
  PermitTTY no
  PermitTunnel no
  ForceCommand /usr/sbin/nologin

A broken sshd file can lock you out of a remote server, so the playbook runs sshd -t and deletes the file if sshd refuses it. Then it asks sshd what it will really do, with sshd -T -C user=kube-tunnel,host=localhost,addr=127.0.0.1, and checks that kube-tunnel gets permitopen 127.0.0.1:6443 and root doesn't.

The action every repository uses

jithendar.com, practice-programming, moks-rag and monitoring each carry the same composite action, .github/actions/contabo-k3s-api/action.yml. It opens the tunnel:

Bash
ssh -i "$dir/key" -o IdentitiesOnly=yes -o BatchMode=yes -o ConnectTimeout=15 -o ServerAliveInterval=30 \
  -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="$dir/known_hosts" -o ExitOnForwardFailure=yes \
  -f -N -L "127.0.0.1:$PORT:127.0.0.1:6443" "kube-tunnel@$SSH_HOST"

PORT is 16443. The kubeconfig it writes points at https://127.0.0.1:16443 with the cluster's CA, which works because the API certificate names 127.0.0.1. Then it proves the token works before any deploy step runs:

Bash
who="$(KUBECONFIG="$kubeconfig" kubectl --request-timeout=20s auth whoami -o jsonpath='{.status.userInfo.username}')"

In a workflow it's one step. From jithendar.com's deploy-kubernetes.yml:

YAML
      - name: Contabo k3s API through SSH
        uses: ./.github/actions/contabo-k3s-api
        with:
          ssh-key: ${{ secrets.CONTABO_K3S_SSH_KEY }}
          ssh-host: ${{ secrets.CONTABO_K3S_SSH_HOST }}
          ca-data: ${{ secrets.CONTABO_K3S_CA_DATA }}
          token: ${{ secrets.CONTABO_K3S_CI_APPLY_TOKEN }}

The job's last step closes it: pkill -f 'L 127.0.0.1:16443:' || true.

One workflow hands out keys and tokens

I didn't want to go back to setting secrets by hand in four repositories, so k8s-deployments has a workflow, "Contabo k3s CI access", that I start by hand. What each repository gets is in contabo-k3s/ci-access.yml:

YAML
repositories:
  mrjithendar/jithendar.com:
    rbac:
      - kubernetes/80-ci-deployer.yaml
      - kubernetes/85-ci-applier.yaml
      - kubernetes/flow-runs-10-access.yaml
    tokens:
      CONTABO_K3S_CI_APPLY_TOKEN: jithendar/github-ci-applier
  mrjithendar/moks-rag:
    rbac:
      - deploy/argocd/ci-rbac.yaml
    tokens:
      CONTABO_K3S_ARGOCD_TOKEN: argocd/github-rag-argocd-deployer

Each run does four things:

  1. It makes a new key with ssh-keygen -q -t ed25519 -N '' -C kube-tunnel and runs api-tunnel.yml, so only that key is authorized from then on.
  2. Over root's own tunnel, as cluster-admin, it applies each repository's RBAC files, read from that repository's default branch, and creates any missing <sa>-token Secret. With rotate_tokens ticked it deletes them first, which kills every old copy.
  3. It opens a tunnel as kube-tunnel with the new key and signs in with every token. It also tries to run id and to forward to port 22, and fails if either works.
  4. It writes the secrets into each repository with a token from actions/create-github-app-token, limited to those repositories and to their secrets and environments. The CA is a secret too, because v3.3.0 of that action can't ask for the variables permission.

The run on 30 November took 2 minutes 18 seconds and ended like this (run 46428613839):

argocd/github-rag-argocd-deployer: OK
grafana-dashboards/github-dashboards-deployer: OK
jithendar/github-ci-applier: OK
jithendar/github-ci-deployer: OK
kube-tunnel: no command, no other port
mrjithendar/jithendar.com (repository secrets): CONTABO_K3S_SSH_KEY CONTABO_K3S_SSH_HOST CONTABO_K3S_CA_DATA CONTABO_K3S_CI_APPLY_TOKEN

What each ServiceAccount may do

The tunnel gives a workflow nothing its token doesn't, so the Roles matter. The site's applier (kubernetes/85-ci-applier.yaml) may create, patch and update its kinds in namespace jithendar. It can't delete, read Secrets or create pods. The file carries its own warning, which I keep there on purpose:

YAML
# WHAT THAT MEANS: with `escalate` and `bind` on Roles, a merged pull request that edits a Role in kubernetes/ can give
# this ServiceAccount (or any other in the namespace) any permission in namespace jithendar, including reading its
# Secrets. Review changes to kubernetes/*rbac*, 70-, 80- and 85- files as changes to cluster access.

My favourite rule is newer. When I split moks-rag's Argo CD Application into one per component, its deploy workflow had to delete the old Application, once. It got exactly that (deploy/argocd/ci-rbac.yaml in moks-rag):

YAML
  - apiGroups: ["argoproj.io"]
    resources: ["applications"]
    resourceNames: ["moks-rag-stack"]
    verbs: ["delete"]

Problems I hit

ServiceAccounts nobody had written down. The first Contabo deploy of jithendar.com stopped in its preflight (run 46412537056):

##[error]ServiceAccount jithendar/flow-runner does not exist: a person creates it first (kubernetes/README.md)
##[error]ServiceAccount jithendar/seo-agent-manager does not exist: a person creates it first (kubernetes/README.md)

On mk4 I had applied kubernetes/flow-runs-10-access.yaml by hand, and CI never applies files that grant identity. The fix was to add the file to jithendar.com's rbac list in ci-access.yml (k8s-deployments #77 (opens in a new tab)) and run CI access again.

practice-programming had the same gap. Its deploy timed out (run 46425131305):

Waiting for deployment "practice-dispatcher" rollout to finish: 0 out of 2 new replicas have been updated...
error: timed out waiting for the condition
##[error]Rollout of practice-dispatcher did not finish within 5m

The ServiceAccounts practice-api and practice-dispatcher were missing, so the Deployments couldn't create a single pod. They come from the executor's sandbox files, also applied by hand on mk4. #79 (opens in a new tab) added the four files to practice-programming's rbac list. My rule now: anything I ever applied by hand on the old cluster goes into ci-access.yml.

A hint that pointed the wrong way. One deploy failed its server-side dry run (run 46414458290):

no matches for kind "ScaledObject" in version "keda.sh/v1alpha1"
ensure CRDs are installed first
##[error]Server dry run of group site failed. If the message says "forbidden", the cluster still has an older github-ci-applier Role: ...

Auth was fine: a few lines earlier the log said signed in as system:serviceaccount:jithendar:github-ci-applier. KEDA wasn't installed yet, because I had started the deploy before the platform apply finished, and my own hint blamed RBAC. Read the first error line, not the hint.

What is better, and what is still weak

Better: the API is off the internet. A stolen tunnel key opens no shell and reaches nothing but the API. Each repository signs in as itself, and one run rotates the key, and optionally the tokens, everywhere.

Still weak:

  • Port 22 is open to the internet, keys only. Turning on Contabo's firewall is next on my list.
  • The action trusts the host key on first sight (accept-new). The API's CA in CONTABO_K3S_CA_DATA is what proves the far end.
  • The tokens are long-lived ServiceAccount token Secrets with no expiry, as on mk4. [ASK JITHENDAR: Do you plan short-lived tokens or OIDC to the API server, or is that out of scope?]
  • The root SSH key that CI access uses lives in the contabo-k3s environment of k8s-deployments.

Verify it works

Every deploy prints who it signed in as. From jithendar.com's run 46429843245 on 30 November:

Contabo k3s API through SSH: signed in as system:serviceaccount:jithendar:github-ci-applier
deployment "jithendar-com" successfully rolled out
deployment "jithendar-com-worker" successfully rolled out
deployment "seo-agent" successfully rolled out
all smoke checks passed

practice-programming's run 46429770667 opened one tunnel and signed in twice, once per token:

Contabo k3s API through SSH: signed in as system:serviceaccount:jithendar:github-ci-applier
Contabo k3s API through SSH: signed in as system:serviceaccount:jithendar:github-ci-deployer

To check a token's rights through the tunnel, with the kubeconfig the action wrote (expected output, from the Role above):

Bash
kubectl auth can-i patch deployments -n jithendar   # yes
kubectl auth can-i delete deployments -n jithendar  # no
kubectl auth can-i get secrets -n jithendar         # no

And to confirm the key opens no shell (expected output: no terminal, then nologin's message):

Bash
ssh -i ~/.ssh/<key> kube-tunnel@<control-plane address>
PTY allocation request failed on channel 0
This account is currently not available.

Key takeaways

  • If your CI can reach SSH but not the API, an SSH user limited to one permitopen target gives you a tunnel without a shell.
  • Put the limits in both places: the key's options and an sshd Match block, and check them with sshd -T.
  • Keep one identity per repository. The tunnel should give nothing the token doesn't.
  • Let one workflow mint the key, apply the RBAC, test every token and write the secrets. Then rotating is a button.

Previous: Part 3: Rebuilding the images for arm64 and amd64 (opens in a new tab) · Next: Part 5: The database migration pipeline and the cutover (opens in a new tab)