Skip to content

CKS: give each cluster its own API key pair, limited to the APIs it calls, with rotateKubernetesClusterKeys - #14910

Open
bhouse-nexthop wants to merge 1 commit into
apache:mainfrom
bhouse-nexthop:cks-scoped-keys
Open

bhouse-nexthop wants to merge 1 commit into
apache:mainfrom
bhouse-nexthop:cks-scoped-keys

Conversation

@bhouse-nexthop

@bhouse-nexthop bhouse-nexthop commented Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Every CKS cluster of an account or project used the same API key pair: the latest key pair of a shared service user (<account>-kubeadmin inside the owner's account, or kubeadmin-<project> for a project). A key read from kube-system/cloudstack-secret of one cluster could not be revoked without breaking every other cluster of that owner, and with an account-owned cluster it carried all the owner's rights. The keys went to the control node on the SSH command line, and the secret was created only if missing, so it could not be replaced.

Building on the key pairs of #9504, each cluster now has its own key pair.

Before After
Key pair Latest key pair of the shared service user, shared by every cluster of the owner cks-<cluster uuid> on the same service user, one per cluster; its id is the cluster detail apiKeyPairId
Allowed APIs Everything the service user's role allows Only the APIs below, and only those the role also grants (a WARN lists any the role lacks)
Delivery deploy-cloudstack-secret -k <api key> -s <secret key> on the SSH command line, then /tmp/cloud-config The cloud-config is copied as a 0600 file with a name of its own, opened as stdin and deleted before deploy-cloudstack-secret runs. Create, scale and upgrade still store it only if the secret is missing; a rotation replaces the secret with kubectl apply --server-side
Rotation Not possible New API rotateKubernetesClusterKeys, and a "Rotate API keys" action in the UI
Cluster delete Key pair stays The cluster's key pairs (cks-<cluster uuid>) deleted

Allowed APIs, taken from the calls in the code of each component:

Component APIs
CloudStack Kubernetes provider (apache/cloudstack-kubernetes-provider main: cloudstack.go, cloudstack_instances.go, cloudstack_loadbalancer.go) listVirtualMachines, listNetworks, listCapabilities, listPublicIpAddresses, associateIpAddress, disassociateIpAddress, listLoadBalancerRules, createLoadBalancerRule, updateLoadBalancerRule, deleteLoadBalancerRule, assignToLoadBalancerRule, removeFromLoadBalancerRule, listLoadBalancerRuleInstances, listLBStickinessPolicies, createLBStickinessPolicy, deleteLBStickinessPolicy, listFirewallRules, createFirewallRule, deleteFirewallRule, listNetworkACLLists, listNetworkACLs, createNetworkACL, updateNetworkACLItem, deleteNetworkACL
Cluster autoscaler (kubernetes/autoscaler cluster-autoscaler/cloudprovider/cloudstack/service/cks.go) listKubernetesClusters, scaleKubernetesCluster
Both, for async jobs queryAsyncJobResult
CloudStack CSI driver v3.0.0 (pkg/cloud), only when the cluster has CSI enabled listZones, listVolumes, createVolume, deleteVolume, attachVolume, detachVolume, resizeVolume, listSnapshots, createSnapshot, deleteSnapshot

The autoscaler APIs are always allowed, as autoscaling can be turned on after the cluster is created. The "Project Kubernetes Service Role" is now built from the same two lists. Compared with before, it gains listCapabilities, the three LB stickiness APIs, listNetworkACLLists, updateNetworkACLItem and listZones, which these components call, and drops updateFirewallRule, which none of them calls. Roles created before keep what they have.

rotateKubernetesClusterKeys (cluster must be Running):

  1. creates a new key pair for the cluster;
  2. copies the current deploy-cloudstack-secret to the control node and replaces the api-key and secret-key lines of the secret's cloud-config with the new keys (adding them under [Global] if missing); every other line is kept, so a setting an operator added, such as ssl-no-verify = true, survives, and so do api-url and project-id. The merge is done on the node in bash builtins, so the keys never appear in a process's arguments. If the secret cannot be read, it is left as it is and the rotation fails;
  3. restarts the components that read the secret: cloud-controller-manager, cluster-autoscaler, cloudstack-csi-controller and cloudstack-csi-node, whichever exist, and waits for their rollouts (3 minutes per deployment, 15 for the daemonset), so the old key pair is deleted only once they use the new one;
  4. records the new key pair and deletes the cluster's other key pairs, found by name.

If the secret is not stored, the cluster keeps its keys and the job fails. The new key pair is not deleted then, as the script may have stored it before the SSH session failed; it is deleted by the next rotation that completes, or with the cluster. If the secret is stored but the script does not report every component restarted, the new key pair is recorded, the previous ones stay for the pods still running with them, and the job fails with the script output; rotating again once the component runs completes it. The job is serialised per cluster. If the cluster turns out to be being deleted once the new key pair is created, the rotation deletes that key pair and fails, as the deletion may already have deleted the cluster's key pairs.

The rotation needs the cluster Running with every node up: it reaches the first control node over SSH and waits for the CSI node daemonset to restart on each node.

UI: the Kubernetes cluster view has a "Rotate API keys" action, shown while a CloudManaged cluster is Running and only to callers allowed rotateKubernetesClusterKeys. Its confirmation says what happens: a new key pair is stored in the cluster, the provider, autoscaler and CSI driver (whichever run in it) are restarted, the old key pair is deleted while a shared one from before 24.0.0 is kept, a failed step keeps the old key pair so the rotation can be run again, and every node must be up. The API returns only success, so nothing new is shown in the cluster details and no key is shown anywhere.

The key pairs belong to the service user <account>-kubeadmin of the owner account, or for a project to the user of the project's service account, and only to a user of that account: an account whose name starts with kubeadmin- is no longer taken for a project service account, and a user of that name in another account is refused.

Clusters created before this change keep using the shared key pair, and scale and upgrade leave their secret as it is. rotateKubernetesClusterKeys moves such a cluster onto its own key pair; it does not delete the shared key pair, as other clusters may still use it. Moving every existing cluster, and then deleting the shared key pair, is not part of this PR.

Decisions:

  • No end date and no automatic rotation: a key pair that expires on its own would stop the cluster's load balancers and autoscaling. Rotation is the explicit API, which an operator can schedule.
  • The rules are per API name, as API key pair restructure #9504 defines them. A cluster's key can still call deleteLoadBalancerRule on another cluster of the same owner. Separating two clusters fully needs separate accounts or projects.
  • No schema change: the key pairs are in the API key pair restructure #9504 tables and the id in kubernetes_cluster_details.

Fixes #14909

Types of changes

  • Breaking change (fix or feature that would cause existing functionality to change)
  • New feature (non-breaking change which adds functionality)
  • Bug fix (non-breaking change which fixes an issue)
  • Enhancement (improves an existing feature and functionality)
  • Cleanup (Code refactoring and cleanup, that may add test cases)
  • Build/CI
  • Test (unit or integration test code)

Feature/Enhancement Scale or Bug Severity

Feature/Enhancement Scale

  • Major
  • Minor

Screenshots (if appropriate):

How Has This Been Tested?

Unit tests: 161 in the kubernetes-service module pass, 33 of them new:

  • KubernetesClusterManagerImplKeyPairTest (16): allowed APIs with and without CSI, APIs the role lacks left out, a role allowing none refused (a key pair without rules would have every permission of its account), the key pair name and rules, a second start reusing the key pair of a failed first one, rotate (new pair recorded and the others deleted; secret not stored keeps every pair; components not all restarted records the new pair but keeps the others; refused when Stopped), deleting by name all pairs of the cluster but the one kept, a rotation that finds the cluster being deleted deleting its new key pair, and the service user lookup (an account named like a project service account, a project, a user of another account refused).
  • KubernetesClusterActionWorkerSecretTest (10): the keys go only in the copied 0600 file, under a name of its own, and never in the SSH command; an existing secret is accepted without --restart but not with it; --restart only for a rotation; the secret counts as stored only when the script reports it, so an older script that is still in place counts as failed; the keys file is removed by a second command only when the script did not run; a cluster without its own key pair keeps its secret; project-id only for a project-owned cluster.
  • DeployCloudStackSecretScriptTest (7): runs deploy-cloudstack-secret against a stub kubectl: with --restart, an existing secret with extra lines (ssl-no-verify, a value holding = and spaces, a comment) keeps them and gets only the new keys; missing keys are added under [Global]; key names in any case are replaced; a missing secret gets the new cloud-config; a secret that cannot be read is left as it is and nothing is reported stored; no key appears in a kubectl argument; without --restart, an existing secret is left and a missing one stored.

UI: npm run lint finds no errors; the ActionButton and AutogenView unit tests pass (137 of 137).

The script was also run against a stub kubectl: secret present and absent without --restart, the secret lookup failing (exits without storing), --restart with every component restarting, kubectl apply failing, a workload lookup failing, and a daemonset rollout timing out.

Tested on a KVM lab with an account-owned and a project cluster, rotation included: see the test report in the comments.

How did you try to break this feature and the system with this change?

  • A role that lacks some of the APIs (a project role created by an older version): the key pair gets the rest and a WARN names the missing ones, instead of the create failing.
  • A rotate whose secret update fails, or whose SSH session drops: the old key pair stays in use; a rotate where a component does not restart, or the session drops while the script waits for one: the old key pair stays for its pods.
  • A first start that fails after creating the key pair: the next start reuses it instead of leaving it behind.
  • An API server error while checking for the secret during scale or upgrade: the script stops instead of replacing the secret; every kubectl call but the rollout waits has a 60 second request timeout, so the SSH session cannot hang.
  • The SSH command: SshHelper logs a failing command at ERROR, and the command holds no key.

@codecov

codecov Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 58.49057% with 88 lines in your changes missing coverage. Please review.
✅ Project coverage is 20.94%. Comparing base (58fda71) to head (01ab543).

Files with missing lines Patch % Lines
...bernetes/cluster/KubernetesClusterManagerImpl.java 71.77% 24 Missing and 11 partials ⚠️
...rnetes/cluster/RotateKubernetesClusterKeysCmd.java 0.00% 34 Missing ⚠️
...r/actionworkers/KubernetesClusterActionWorker.java 81.39% 6 Missing and 2 partials ⚠️
...g/apache/cloudstack/acl/dao/ApiKeyPairDaoImpl.java 0.00% 6 Missing ⚠️
.../actionworkers/KubernetesClusterDestroyWorker.java 0.00% 5 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##              main   #14910       +/-   ##
============================================
+ Coverage     3.86%   20.94%   +17.08%     
- Complexity       0    21184    +21184     
============================================
  Files          494     6058     +5564     
  Lines        42888   549730   +506842     
  Branches      8141    78946    +70805     
============================================
+ Hits          1657   115163   +113506     
- Misses       40999   421104   +380105     
- Partials       232    13463    +13231     
Flag Coverage Δ
uitests 3.86% <ø> (-0.01%) ⬇️
unittests 22.39% <58.49%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@bhouse-nexthop

Copy link
Copy Markdown
Collaborator Author

Tested on a KVM lab running a main (24.0) build that includes this change, at the current head of this PR. Primary storage is Ceph RBD. Each CKS cluster is Kubernetes 1.34.7, 1 control and 1 worker node, without CSI. It was run twice: once with the cluster owned by an account, and once with the cluster in a project (service account kubeadmin-<project>, "Project Kubernetes Service Role").

Result: 31 of 31 checks passed for the account-owned cluster, and 32 of 32 for the project cluster.

Step Checks
Create exactly one live key pair named cks-<cluster uuid>, and the cluster detail apiKeyPairId names it; its rules are exactly the 27 CCM and autoscaler APIs, all ALLOW, with no volume API; the api-key in kube-system/cloudstack-secret is that pair's; no cloud-config file is left on the control node
CCM on the cluster key a LoadBalancer Service gets an external IP, and CloudStack has the LB rule on it
Scope signed with the cluster key, listKubernetesClusters succeeds and listUsers is refused (432)
Rotate before rotating, ssl-no-verify = false was added to the secret's cloud-config. The job succeeds; the detail names a new live pair and the old pair is removed; the secret holds the new api-key and still has the ssl-no-verify line; the CCM pod was replaced; the old key is refused (401) and the new key works (200); a second LoadBalancer Service gets an IP, and deleting the first removes its LB rule
Logs neither secret key (old or new) is in management-server.log or apilog.log
Delete no live cks-<cluster uuid> pair is left

The merge of the cloud-config on rotation is also covered by DeployCloudStackSecretScriptTest, which runs the script against a stub kubectl: values holding = and spaces, key names in another case, missing key lines, and a secret that cannot be read.

Not tested: a cluster with CSI enabled (the extra volume and snapshot rules), the cluster autoscaler on the new key, and a rotation with a node down.

Every CKS cluster of an account or project used the same API key pair, the
latest one of a shared service user, and it was never rotated. A key read
from kube-system/cloudstack-secret of one cluster could not be revoked
without breaking every other cluster of that owner, and with an
account-owned cluster it carried all the owner's rights. The keys also went
to the control node on the SSH command line, and the secret was only
created if missing, so it could not be updated.

A new cluster now gets its own key pair, named cks-<cluster uuid>, on the
service user. Its rules allow only the APIs that the CloudStack Kubernetes
provider and the cluster autoscaler call, plus those of the CloudStack CSI
driver when the cluster has CSI enabled, and only those the service
account's role grants. The rules are per API, not per resource, so the key
can still act on the owner's other clusters. The key pair id is kept in the
cluster details. The cloud-config is copied to the control node as a 0600
file and read on stdin. Creating, scaling and upgrading a cluster store it
only if the secret is missing, as before.

rotateKubernetesClusterKeys creates a new key pair, replaces the api-key
and secret-key lines of the secret with kubectl apply --server-side,
keeping its other lines such as ssl-no-verify, restarts the components that
read the secret and waits for them, then deletes the cluster's other key
pairs. If the secret is not stored, or a component does not restart, the
key pairs that may still be in use stay until a rotation completes or the
cluster is deleted. A cluster created before this change keeps the shared
key pair until it is rotated; the shared key pair stays, as other clusters
may still use it. Deleting a cluster deletes its key pairs, and a rotation
that finds the cluster being deleted deletes the key pair it created.

The Kubernetes cluster view gets a Rotate API keys action, shown while the
cluster is Running, with a confirmation that says what the rotation does.

The key pairs belong to the user <account>-kubeadmin of the owner account,
or for a project to the user of the project's service account, and only to
a user of that account.

Signed-off-by: Brad House <bhouse@nexthop.ai>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CKS: all clusters of an account or project share one API key pair, with every permission of its user, that cannot be rotated

1 participant