Files
Tjark Rasche 9336f06eb4 feat(encryption): add recoverable owned etcd key rotation (#1376)
* feat(encryption): add recoverable owned etcd key rotation

Redistribute reviewed rotation lifecycle, storage-name identity, membership convergence, acknowledged rewrite recovery, loaded-config restart proof and version-gated Begin acceptance from c39e7326. Reuse the renewal foundation admission fences and deterministic notices without duplicating their implementation.

Adapt API descriptions and Kubernetes test dependency pins to current main; retain current-main VIP, nodepool replacement and machine-materialization admissions. Synchronize module manifests and regenerate protobuf, OpenAPI and notices artifacts through pinned Make targets.

Closes #1344

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* docs(encryption): drop database lock release for lost rotation hosts

The documented add_secondary lock release trusted the recorded rotation
phase, but RecordEtcdKeyRotationPhase is not monotonic, so a reset can move
the phase back while nodes already use the new key. Remove the database-edit
exception and keep the lock until the owning workflow completes; a lost host
is restored with the same identity or the cluster is restored from backup.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* fix(controller): finalize unnamed enablement key under the legacy name

Enablement may reuse a pending key staged before names were recorded and
admits node agents that predate the encryption identity RPC. Finalizing
that key queried every joined control-plane agent and failed on them.
Enablement distributes an unnamed pending key under the legacy name, so
record that name without discovery. Rotation, including rotation histories
recorded before ownership that finalize through the same activity after
EtcdEncrypted is set, keeps discovering the deployed pending name.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* fix(controller): reject reused workflow ID of a succeeded etcd key rotation

A new execution that reused the workflow ID of a succeeded rotation got
AlreadyCompleted from Begin and returned success without rotating. Begin
succeeds at most once per run, so a succeeded owner can only mean ID reuse;
return the non-retryable rotation precondition error instead. A retry of an
accepted Begin within the same run still finds a running owner and stays
idempotent. The workflow keeps its AlreadyCompleted branch, unchanged, so
recorded histories that carry it replay with their original commands.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* docs(agent): state the actual UpdateEncryptionConfig error codes

The contract said FailedPrecondition meant only a missing config and that
other codes left no partial state. The agent also returns Canceled,
Unavailable, and FailedPrecondition for a stale WAL entry, a config the
apiserver has not loaded, and config or ownership changes, and it retains
the WAL entry for a retry of the same operation. List the codes and drop
the no-partial-state guarantee. Comment-only; *.pb.go regenerated.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* docs(controller): note that a prepare failure releases the rotation lock

EtcdKeyRotationStatus said every failed rotation retains UpdateInProgress.
FailEtcdKeyRotation clears it for a prepare-phase failure; only failures
after prepare retain it.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* fix(controller): give a failed encrypted-object rewrite a fixed remedy

The rewrite activity clears ErrorMessage so agent errors that can echo
rejected Secret bodies never reach workflow history, which left the
workflow error as "encrypted-object rewrite failed: ". Return a fixed,
secret-free message pointing at the node rewrite state instead.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* fix(controller): refuse etcd key rotation until control-plane nodes run the cluster's Kubernetes version

PATCH records the desired Kubernetes version before the control-plane
upgrade marks ControlPlaneUpgrading, so Begin could accept a rotation
while every node still ran 1.33. add_secondary then failed for lack of the
encryption-config reload metric and the retained lock blocked the upgrade.

Begin now compares each control-plane node's pinned configuration version
with the cluster version and refuses, before taking the lock, when any node
differs or its version cannot be determined.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* fix(controller): complete legacy etcd key rotations on agents without key identity

A rotation started by the previous controller (no workflow owner) keeps
its node agents, because agent upgrades are refused while it holds the
mutation lock. After the controller upgrade, every rotation-phase node
call and its finalization required GetEtcdEncryptionKeyIdentity. Agents
without that RPC therefore failed the run, and the legacy failure path
released the lock while nodes could already write with the pending key.

Restore the original protocol for that case. A pending key with no
recorded name was staged by the earlier controller. Its node mutations
skip the identity RPC and send the request unnamed, as before: the agent
derives the name on add and matches the key by its bytes afterwards.
Legacy finalization makes the key active without recording or guessing a
name and drops the stale active name. The next init, join or rotation
discovers the name. Named pending keys, and every owned rotation, still
verify identity before each mutation. Enablement finalization still
records the legacy bootstrap name.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* fix(controller): require agent success status for etcd rotation membership gate

The node agent reports scripts it cannot start (for example EACCES) with
status "error" and exit code 0. Require the "success" status so the
membership gate never passes without a live check before old-key removal.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* docs(controller): pass the required --reason to the etcd rotation reset example

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* docs(controller): bound etcd rotation resets by Temporal history retention

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* fix(agent): match UpdateEncryptionConfig error codes to the documented list

A pre-write reload baseline that cannot read apiserver metrics now returns
Unavailable; nothing was written, so a retry is safe. A failed WAL removal
after confirmation returns Internal at once instead of being retried as a
metrics outage and reported as Unavailable.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* fix(controller): tell callers to start a new etcd rotation after a prepare failure

A prepare failure already released the rotation lock, so no reset of that
workflow can succeed. Begin now directs the caller to start a new rotation
with a new workflow ID instead of resetting the failed phase.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* fix(controller): retry retry-safe UpdateEncryptionConfig errors in key rotation

Every rotation UpdateEncryptionConfig error became FailedNotRestored, and
ApplyToNode returns outcomes rather than activity errors, so nothing
retried a node mutation. A transient Unavailable or DeadlineExceeded,
which the RPC contract calls safe to retry, failed the phase and kept the
lock until an operator reset the workflow.

Retry those two codes up to three times per node with a doubling backoff
from 5s, stopping when the context ends. Each attempt can wait about two
minutes for the reload, so the budget fits in the eight-minute
ApplyToNode activity timeout. Every other code still fails at once. The
guide now says what the automatic retry covers.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* docs(controller): correct etcd key rotation recovery, backup and agent boundary

Three guide corrections from review:

- A terminated or timed-out owner never runs its failure cleanup, so
  state stays running and the lock stays held in any phase, prepare
  included. Begin refuses a new workflow ID then; recovery is resetting
  that same workflow ID. The prepare row and the recovery intro now say
  so.
- Finalization replaces active and active-name and keeps no prior key, so
  operators must retain the current key Secret with their etcd backups
  before starting; the guide says to copy the Secret object into the
  backup store without printing its data.
- agent/v0.3.0-rc.2 also lacks GetEtcdEncryptionKeyIdentity, so it is
  now the named boundary.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* docs(agent): describe the current encryption rotation WAL protocol

The encRotationWALFile and commitConfigWrite comments still described a
reload-counter snapshot. The WAL now records only the operation id, and
the write first checks that the apiserver's loaded-config identity matches
the current on-disk config. Comments only.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* fix(controller): point a prepare-phase etcd rotation failure at a new workflow

After a prepare failure the rotation lock is already released and Begin
refuses a reset of that owner, yet updateFailed still told the operator to
recover the owning workflow. For prepare it now says to fix the
prerequisite and start a new rotation with a new workflow ID; later
phases keep the recover-the-owner message.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* test(controller): require bash and jq before the rotation membership probe test

The probe test ran host bash and jq with no precondition, and the probe
discards stderr, so without jq the converged case failed with a bare exit
status and the negative cases passed for the wrong reason. Skip when
either tool is missing, as the certificate-renewal runbook harness does.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* docs(controller): back up the old storage name when the key Secret lacks it

The guide told operators to copy the key Secret before a rotation because
its active and active-name fields hold the key and its storage name. A
Secret from before storage names were recorded, or one last rotated by
an earlier controller, has no active-name, so that copy cannot restore
a pre-rotation snapshot whose ciphertext carries the old name.

The workflow records the old key's storage name in active-name before
it enters add_secondary and keeps the old key in active until finalize.
Tell operators to copy the Secret again in that window when the first
copy has no active-name.

Also say that a node key update makes up to three attempts, which is
what the code does, instead of "retries up to three times".

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* docs(agent): say what defaultReloadPollInterval polls

The interval is used to poll the apiserver encryption metrics, both the
loaded-config identity during a key update and the reload counter during
enablement, not only the reload counter.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* fix(controller): record the active key name when rotation reuses a pending key

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* docs(api): point control-plane 409s at the etcd key rotation runbook

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* docs(controller): name the NVKE controller in the etcd key rotation runbook

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* fix(controller): tolerate an old key already removed from some nodes when reusing a pending key

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* docs(controller): say an old key removed from every node needs an earlier backup

When rotation reuses a pending key and no control-plane node still has
the old key, no node records its storage name either, so a node's
encryption config cannot replace the backup. Also drop an unreachable
error check: the pending-key lookup just above already returns those
errors.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* fix(agent): replace a stale encryption config when bootstrapping a reset node

kubeadm reset removes the static pod manifests, PKI, kubeconfigs and the
etcd data directory, but leaves /etc/kubernetes/kube-api-encryption behind.
Init or join after a reset, or on a reused host, then failed the storage
identity check with "renaming a storage key is unsafe" before kubeadm ran.

kubeadm init and join now replace an existing config whose key identity
conflicts when no local data can depend on it: /var/lib/etcd/member is
absent or empty and /etc/kubernetes/manifests/kube-apiserver.yaml is
absent. If either exists, the rename check still applies. The
enable-encryption RPC keeps the check unconditionally. A replacement is
logged with SHA-256 key digests only.

The agent does not receive the etcd dataDir. It checks kubeadm's default
/var/lib/etcd, which is also what the controller renders
(kubeadmconfig defaultEtcdDataDir).

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* fix(controller): preserve legacy pending-key staging on redelivery

Legacy rotation histories may persist an unnamed pending key before losing the staging activity acknowledgement. Redelivery under the legacy etcd_encryption lock now reuses that key without the identity RPC, while owned rotations still prove pending-key identity.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* docs(etcd-encryption): point PATCH conflicts at rotation recovery

A failed etcd key rotation keeps the etcd_key_rotation lock, so the
updateCluster description, its 409 response, the runtime 409 message and
the troubleshooting entry now point to phase-aware recovery. The rotation
guide names the Temporal namespace, task queue, address and TLS settings
the way the certificate-renewal guide does.

Addresses review threads r4335392969 and r4335393460.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* fix(etcd-encryption): guard host verifier test and document rotation lock retention

Review fixes for PR #1376:

- F3: skip TestEtcdKeyRotationVerifierRequiresExistingSecretRewriteAndConvergence
  when sha256sum is not on PATH, matching the runbook membership test, instead
  of failing with a misleading verifier error.
- F5a: the troubleshoot 409 cause and step-1 list, the create.md Updating row
  and the observe.md checklist now name a failed etcd key rotation that
  retained updateInProgress (type=etcd_key_rotation, etcdKeyRotation.state=failed)
  and link to phase-aware recovery.

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

* docs(etcd-encryption): cover closed running rotation owners and bound their reset

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>

---------

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>
2026-10-26 09:52:24 -07:00

134 lines
4.4 KiB
Go

// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package db
import (
"database/sql"
"errors"
"time"
"github.com/uptrace/bun/driver/pgdriver"
)
var ErrNotFound = errors.New("record not found")
const (
ConditionStatusTrue ConditionStatus = "True"
ConditionStatusFalse ConditionStatus = "False"
ConditionStatusUnknown ConditionStatus = "Unknown"
)
type ConditionStatus string
func ConditionStatusFromBool(status bool) ConditionStatus {
if status {
return ConditionStatusTrue
}
return ConditionStatusFalse
}
func BoolFromConditionStatus(status ConditionStatus) bool {
return status == ConditionStatusTrue
}
type Condition struct {
Status ConditionStatus `json:"status,omitempty"`
Message string `json:"message,omitempty"`
LastTransitionTime time.Time `json:"lastTransitionTime,omitempty"`
}
// Equal reports whether two conditions describe the same state. It compares
// LastTransitionTime with time.Time.Equal rather than ==, because == also
// compares the monotonic clock reading and the *Location pointer: the same
// instant read back from JSONB (UTC) and taken from an apimachinery
// metav1.Time (Local, see its UnmarshalJSON) is not == equal.
func (c Condition) Equal(other Condition) bool {
return c.Status == other.Status &&
c.Message == other.Message &&
c.LastTransitionTime.Equal(other.LastTransitionTime)
}
func NewCondition(status bool, message string) Condition {
return Condition{
Status: ConditionStatusFromBool(status),
Message: message,
LastTransitionTime: time.Now(),
}
}
// SetCondition updates existing to match condition. LastTransitionTime is set
// to now when the status changes, and is preserved otherwise. This follows the
// same transition-time behavior as apimachinery's meta.SetStatusCondition.
func SetCondition(existing *Condition, condition Condition) {
if existing.Status != condition.Status || existing.LastTransitionTime.IsZero() {
if condition.LastTransitionTime.IsZero() {
existing.LastTransitionTime = time.Now()
} else {
existing.LastTransitionTime = condition.LastTransitionTime
}
}
existing.Status = condition.Status
existing.Message = condition.Message
}
// OperationType identifies a long-running cluster mutation that is mutually
// exclusive with other CP-mutating operations. Persisted as the Type field of
// UpdateInProgress inside clusters.conditions JSONB; string values must stay
// stable because they are consumed by the UI and nvkectl.
type OperationType string
const (
OperationTypeEtcdEncryption OperationType = "etcd_encryption"
OperationTypeEtcdKeyRotation OperationType = "etcd_key_rotation"
OperationTypeK8sUpgrade OperationType = "k8s_upgrade"
OperationTypeCPNodesRecycling OperationType = "cp_nodes_recycling"
OperationTypeOIDCEnable OperationType = "oidc_enable"
OperationTypeSpireServerUpdate OperationType = "spire_server_update"
OperationTypeCertRenewal OperationType = "certificate_renewal"
)
// UpdateInProgress represents a mutually-exclusive cluster mutation in flight.
// Stored inside ClusterConditions JSONB; nil means no update in progress.
// A single UpdateInProgress entry replaces the proliferation of per-operation
// boolean flags (ControlPlaneUpgrading, CPNodesRecycling, etc.) so new
// operation types can be added without schema changes.
type UpdateInProgress struct {
Type OperationType `json:"type"`
// Message is a short, operator-facing string. It is echoed verbatim in the
// 409 response body on UpdateCluster conflicts, so writers MUST NOT put
// internal identifiers (workflow IDs, activity IDs, stack traces, or any
// other sensitive detail) here. Keep it to a human-readable summary.
Message string `json:"message,omitempty"`
StartedAt time.Time `json:"startedAt"`
}
func notFoundErrIfNoRowsAffected(res sql.Result) error {
rowsAffected, err := res.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
return ErrNotFound
}
return nil
}
func isViolationOfConstraint(err error, constraintName string) bool {
var pgErr pgdriver.Error
if errors.As(err, &pgErr) {
if pgErr.IntegrityViolation() {
// https://www.postgresql.org/docs/current/protocol-error-fields.html
// Field 'n' is the name of the constraint that was violated
if pgErr.Field('n') == constraintName {
return true
}
}
}
return false
}