Files
Tjark Rasche 6e6152857e feat(controller): record credential operation audit evidence (#1378)
* feat(controller): record credential operation audit evidence

Redistribute the reviewed credential audit ledger and manual evidence tool onto the native monitoring stack. Keep writes bounded and best-effort, preserve operation results and retained ownership, classify explicit V1 no-op markers, and record failed legacy attempts and confirmed terminal outcomes.

Sources: 73d9368b, 1e44e29b (d2039631), f96c9150, and 33d7e1aa; final source 66bfce3a. Adapt fence-store recording to the inherited neutral credential mutation tests and verify PostgreSQL evidence retention after cluster deletion.

Closes #1346

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

* feat(controller): retire lost control-plane nodes from failed etcd key rotations

A failed rotation from add_secondary on keeps the etcd_key_rotation lock, and
every phase and reset needs all snapshot nodes, so a permanently lost host
left the cluster unable to finish the rotation or replace the node.

Add the operator-started RetireLostEtcdRotationNode workflow. Under the
cluster row lock it requires the failed owning rotation, a node-mutation
phase, a joined control-plane node that is unready and does not answer a live
agent probe, no other removal in flight, and a ready etcd quorum. It records
the node in the rotation status, marks it deleting, writes a credential audit
event with the new node_retired reason, and tears only that node down. The
retained lock admits removal of a retired node alone; joins, scale-up,
upgrades and other nodes stay fenced until the reset rotation completes on
the survivors, so the replacement joins with the finalized key.

Document the recovery procedure and the audit reason.

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

* fix(controller): bound CSR-derived credential audit rows per managed node

A workload customer holds the nvke:breakglass cluster-admin kubeconfig, so
it can impersonate system:node:<managed node> and create CSRs with fresh
keys. The CSR controller wrote a ledger row per CSR UID for the skip path
and three for a valid one, and the table has no bound or retention, so a
tenant could grow the shared management database without limit. The
code comment and the audit guide claimed otherwise.

Route every CSR-derived write through Recorder.RecordCSR, which stores
the event only while that cluster and node have fewer than 12 CSR-derived
events in the last hour (four check/approve/verify triples). The count is
taken from credential_audit_events under a per-target advisory lock in the
insert transaction, so a controller restart does not reset the bound and
concurrent reconciles cannot both pass it. Background inspections of the
same credential do not consume the budget. Dropped events are counted
under the new, pre-initialized rate_limited result of
nvke_controller_credential_audit_writes_total, which the guide describes
as expected under CSR churn rather than a sink failure.

A controller test floods one managed node with distinct-UID CSRs and
checks rows stop at the bound while a second node is unaffected; a
Postgres test covers the SQL count, the window, the per-node scope and
idempotent repeats.

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

* fix(controller): audit a rolled-back lost-node retirement as a failure

RetireLostEtcdRotationNode set the audit outcome inside the transaction
closure and recorded it even when RunInTx returned an error, including a
commit failure. A rolled-back retirement was then audited as
rotate/success/node_retired, and the Temporal retry recorded a second
success. Any RunInTx error now records failure/operation_failed. A test
runs the closure successfully and then fails the commit.

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

* fix(controller): require a quorum of the current membership to retire a lost node

The retirement quorum check counted members without the lost node, so it
checked quorum after removal. The etcd member removal itself must commit
under the current membership, which still includes the lost node, so for
even sizes the check was one vote short: on a four-node control plane
with two ready survivors it committed RetiredNodes and Deleting=true, and
RemoveEtcdMember could then not reach quorum.

Require ready >= (members+1)/2+1. Tests refuse two- and four-node
control planes without a ready majority, refuse five nodes with two ready
survivors, and still admit three of three, four of four and three of
five. The rotation guide states the rule.

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

* fix(controller): start the retired node's teardown after any closed run

The retire workflow started its teardown-node-<id> child with
ALLOW_DUPLICATE_FAILED_ONLY. Label-driven remediation starts that ID with
AllowCPNode=false and, for a control-plane node, returns success without
tearing it down. Retirement has already committed Deleting=true, so every
rerun of the retire workflow then failed until Temporal retention purged
the completed run.

Use ALLOW_DUPLICATE so the child starts after any closed run of that ID.
A run that is still open keeps failing the start with an already-started
error, which the workflow returns as before. A workflow test completes a
remediation-style run of the same ID first and requires the retire
workflow's teardown to run.

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

* fix(controller): skip audit rows for unchanged certificate inspections

The inspection audit's operation hash includes AttemptedAt, so every
inspection got a new event_id and ON CONFLICT never deduplicated an
unchanged observation. With monitoring on by default every hour, each node
added one or two rows per hour indefinitely, and the guide only said to
monitor growth.

Do not record a successful inspection event when it repeats the previous
inspection's outcome and fingerprints for that node and credential; the
controller already has the previous CertificateInspection. Changes and
failures are still recorded. A test covers two unchanged inspections
leaving one row, a changed fingerprint adding one, and repeated failures.
The audit guide describes the dedupe.

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

* docs(controller): list CSR audit outcomes, link the T1 runbook, split the tool build

Three corrections to the credential audit guide:

- List the CSR controller's actual action/outcome/reason pairs. A
  managed node's rejected CSR is check/no_op/identity_not_approved, so
  filtering on outcome='failure' missed rejected identities.
- "The manual runbook" and "the runbook's health and CA checks" named no
  document. Link docs/site-operations/certificate-renewal.md and its
  health-check and verification sections.
- The only example chained the one-time build with a check/success/
  verified observation, so following it recorded a check nobody had
  performed. Show the build and the first observation as separate steps.

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

* docs(controller): set the retire workflow inputs and order its checks

The retire procedure used $rotation_workflow_id and $lost_node_id without
setting them, and the only rotation_workflow_id assignment in the guide
mints a new ID, while this workflow needs the retained owner's. Show where
to read both: conditions.etcdKeyRotation.workflowID of the cluster and the
lost node's id from the node list.

The guide also placed the live agent probe and the audit event inside the
one locked transaction. The probe runs before the locked checks and the
audit event is written after the transaction returns, best effort; the
guide now says so.

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

* docs(controller): list cmd/credential-audit in the contributor layout

The controller AGENTS.md layout still listed cmd/worker as the only
entrypoint, so the new credential-audit tool was missing from contributor
guidance.

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

* fix(controller): record rejected CSRs once per node and hour

Rejected CSRs drew from the same per-node audit bound as approvals and
issued certificates, and each used its own CSR UID as the operation
identity. A tenant holding the break-glass kubeconfig could create a
dozen mismatching CSRs naming a node, use up the hour's budget, and then
get a valid CSR approved with no check, approve or verify row. Only
rate_limited went up, and the guide called that benign.

A rejection now uses the operation identity node/rejected/<UTC hour>.
The event timestamp is excluded from the event ID, so every rejection for
one node in one hour has the same ID. The existing duplicate check stores
it once, and it uses one slot of the bound. Verified, approve and verify
events keep the per-UID identity, and the SQL is unchanged.

The guide now says rejections are recorded at most once per node per
hour, that a non-zero rate_limited means CSR evidence, including
approvals, may be missing, and how to find the affected node. The
suggested alert includes rate_limited.

The flood test now requires one rejection row after many rejected CSRs,
then the check, approval and issued-certificate events of a following
valid CSR. With the old identity it stores 12 rejection rows and fails.

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

* fix(controller): skip repeated identical certificate inspection failures

Unchanged successful inspections were already skipped, but every failed
inspection was recorded with a fresh event ID. A node whose agent lacks
the inspection RPC is reported as unsupported and re-inspected every
interval, so each such node kept adding one or two ledger rows an hour.
The same happened for a credential that stays missing.

Skip any inspection observation whose outcome, reason and fingerprints
match the previous inspection's for the same credential. All failed
probes map to the same audit reason, so compare the inspection's own
reason too: a change from unsupported to unavailable is still recorded.
Recording a long-running failure again later, for example once a day,
is left out to keep this simple.

The test now requires that two identical unsupported inspections leave
one row and that a changed failure reason adds one. Both fail with the
change reverted.

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

* test(controller): group the inspection audit test helper parameters

gofumpt's extra rules require grouped parameters of the same type, and
lint flagged the helper added by the previous commit.

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

* fix(controller): record a repeated inspection until the ledger holds it

The certificate inspection controller skipped an observation that repeated
the previous inspection, but that inspection is committed to the node row
before its best-effort ledger write. When the write failed, every later
identical inspection was skipped, so the ledger held no row for that
credential state until it changed.

Recorder.Record now reports whether the ledger holds the event. The node's
inspection carries AuditRecorded, set by a second small update under
GetNodeForUpdate once all of its events are stored, and a repeat is
skipped only when the previous inspection has it. The update is best
effort: if it fails, the next identical inspection is recorded again, and
the deterministic event ID keeps that idempotent.

This was chosen over querying the ledger for the previous observation's
event IDs because it needs no new query method on the store and no
migration: the field is appended to the existing JSONB inspection.

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

* docs(controller): count the retried approval in the CSR audit bound

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

* docs(controller): link the credential audit guide from the documents it supports

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

* test(controller): keep renewal retry fixtures compatible with audit

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

* fix(controller): require a live probe before retiring a lost node

A failed preliminary node lookup or missing agent address previously looked like an agent that did not answer. Lost-node retirement now refuses new retirement unless the live probe actually runs, while already-retired repeats can still resume teardown.

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

* docs(credential-audit): prepare T1 evidence before the renewal window

The site certificate-renewal runbook now lists the NVKE checkout and Go
toolchain on the operator machine, and asks for the credential-audit build
and per-step recording in Section 1, before the first node's checks. The
rotation guide's fence overview names retired-node teardown alongside
cluster deletion.

Addresses review threads r4335326733 and r4335327189.

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

* fix(controller): tighten credential audit certificate evidence

Reject a certificate PEM bundle whose first block is malformed instead of
fingerprinting the valid certificate pem.Decode skips to. Record
verify/success/observed only for a CSR that NVKE approved, has no Failed
condition, and whose leaf carries the request's public key; a key mismatch
records verify/failure/observation_unavailable. Document that the row does
not authenticate the issuer.

Fixes PR #1378 review findings: F1, F4.

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

* fix(controller): record only the key-checked leaf fingerprint for issued CSR certificates

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

* fix(controller): mark inspection audit state column-only

markInspectionAuditRecorded wrote the whole node through the wrapped UpdateNode, which enqueues every node controller, for a change to the certificate inspection column only. Use the column-only UpdateNodeCertificateInspection, as the inspection write itself does.

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

---------

Signed-off-by: Tjark Gunnar Rasche <trasche@nvidia.com>
2026-10-26 18:56:19 +01:00

245 lines
9.2 KiB
Go

// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// Package certificates reconciles persisted, read-only certificate observations.
package certificates
import (
"context"
"encoding/hex"
"errors"
"fmt"
"log/slog"
"time"
"github.com/google/uuid"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
pb "github.com/dsx-ai-factory/nvke/agent/pkg/agent/proto"
catalog "github.com/dsx-ai-factory/nvke/agent/pkg/certificates"
"github.com/dsx-ai-factory/nvke/controller/internal/config"
"github.com/dsx-ai-factory/nvke/controller/internal/controllers/dbreconcile"
"github.com/dsx-ai-factory/nvke/controller/internal/controllers/dbreconcile/dbwrapper"
dbfilters "github.com/dsx-ai-factory/nvke/controller/internal/controllers/dbreconcile/filters"
"github.com/dsx-ai-factory/nvke/controller/internal/credentialaudit"
"github.com/dsx-ai-factory/nvke/controller/internal/db"
"github.com/dsx-ai-factory/nvke/controller/internal/metrics"
)
const (
inspectionInvalidResponse = "invalid_response"
inspectionUnsupported = "unsupported"
// A failed or incomplete inspection is repeated after inspectionRetryBase,
// doubling until the retry count reaches maxInspectionRetries and never
// beyond the inspection interval.
inspectionRetryBase = time.Minute
maxInspectionRetries = 6
// inspectionWorkers bounds concurrent inspections, as the agent-readiness
// controller's default does for the same probe pattern, so an unreachable
// agent holding its 30s probe does not delay other due nodes.
inspectionWorkers = 8
)
type inspector interface {
InspectKubernetesCertificates(ctx context.Context, node db.Node) (*pb.InspectKubernetesCertificatesResponse, error)
}
// Controller keeps network inspection outside Prometheus scrapes.
type Controller struct {
cfg config.Config
database *dbwrapper.DB
agent inspector
audit *credentialaudit.Recorder
// name registers the controller; controller-runtime rejects a name already
// registered in the process, so tests that set up a manager repeatedly vary it.
name string
}
// NewController constructs the certificate observation controller.
func NewController(cfg config.Config, database *dbwrapper.DB, agent inspector) *Controller {
return &Controller{
cfg: cfg, database: database, agent: agent,
audit: credentialaudit.NewRecorder(database, nil, metrics.RecordCredentialAuditWrite),
name: "certificate-inspection",
}
}
// SetupWithManager watches only non-deleting nodes.
func (c *Controller) SetupWithManager(mgr manager.Manager) error {
return dbreconcile.AddController(mgr, dbreconcile.Controller{
Name: c.name,
Reconciler: c,
Workers: inspectionWorkers,
Sources: []dbreconcile.Source{dbwrapper.NewNodeSource(c.database, dbfilters.Node{Deleting: ptr.To(false)})},
})
}
// Reconcile persists the latest inspection without modifying credentials.
func (c *Controller) Reconcile(ctx context.Context, key dbreconcile.Key) (reconcile.Result, error) {
node, err := c.database.GetNode(ctx, key.ID)
if errors.Is(err, db.ErrNotFound) {
return reconcile.Result{}, nil
}
if err != nil {
return reconcile.Result{}, fmt.Errorf("get inspection node: %w", err)
}
if node.Conditions.Deleting.Status == db.ConditionStatusTrue || node.Conditions.Joined.Status != db.ConditionStatusTrue {
return reconcile.Result{}, nil
}
now := time.Now().UTC()
if previous := node.CertificateInspection; previous != nil {
if due := previous.AttemptedAt.Add(c.nextDelay(previous)); now.Before(due) {
return reconcile.Result{RequeueAfter: due.Sub(now)}, nil
}
}
probeCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
response, probeErr := c.agent.InspectKubernetesCertificates(probeCtx, node)
cancel()
observation := inspectionObservation(node.CertificateInspection, response, probeErr, node.ControlPlane, time.Now().UTC())
if needsEarlyRetry(observation) {
observation.Retries = 1
if previous := node.CertificateInspection; previous != nil {
observation.Retries = min(previous.Retries+1, maxInspectionRetries)
}
}
persisted := false
err = c.database.RunInTx(ctx, func(ctx context.Context, tx db.Tx) error {
locked, err := tx.GetNodeForUpdate(ctx, node.ID)
if err != nil {
return err
}
if locked.Conditions.Deleting.Status == db.ConditionStatusTrue {
return nil
}
locked.CertificateInspection = observation
// A column-only write: the wrapped UpdateNode would enqueue every node controller.
err = tx.UpdateNodeCertificateInspection(ctx, &locked)
persisted = err == nil
return err
})
if errors.Is(err, db.ErrNotFound) {
return reconcile.Result{}, nil
}
if err != nil {
return reconcile.Result{}, fmt.Errorf("persist certificate inspection: %w", err)
}
if persisted && c.recordInspectionAudit(ctx, node, node.CertificateInspection, observation) {
c.markInspectionAuditRecorded(ctx, node.ID, observation.AttemptedAt)
}
return reconcile.Result{RequeueAfter: c.nextDelay(observation)}, nil
}
// markInspectionAuditRecorded is best effort: if it fails, the next identical
// inspection is recorded again rather than skipped.
func (c *Controller) markInspectionAuditRecorded(ctx context.Context, nodeID uuid.UUID, attemptedAt time.Time) {
err := c.database.RunInTx(ctx, func(ctx context.Context, tx db.Tx) error {
locked, err := tx.GetNodeForUpdate(ctx, nodeID)
if err != nil {
return err
}
// Only the inspection whose observations were written is marked.
if locked.CertificateInspection == nil || !locked.CertificateInspection.AttemptedAt.Equal(attemptedAt) {
return nil
}
locked.CertificateInspection.AuditRecorded = true
return tx.UpdateNodeCertificateInspection(ctx, &locked)
})
if err != nil && !errors.Is(err, db.ErrNotFound) {
slog.WarnContext(ctx, "Certificate inspection audit state could not be persisted", "node_id", nodeID, "err", err)
}
}
// nextDelay is how long after an attempt the node is inspected again: the full
// interval after a complete or unsupported result, otherwise a short backoff, so
// a transient failure does not leave the node unavailable for a whole interval.
func (c *Controller) nextDelay(observation *db.CertificateInspection) time.Duration {
if observation.Retries <= 0 {
return c.cfg.CertificateInspectionInterval
}
return min(inspectionRetryBase<<(observation.Retries-1), c.cfg.CertificateInspectionInterval)
}
// needsEarlyRetry reports a failed probe, or a successful one that found a
// required credential missing or invalid, which a kubelet still bootstrapping
// TLS can produce. An agent without the inspection RPC is not retried early.
func needsEarlyRetry(observation *db.CertificateInspection) bool {
if !observation.Available {
return observation.Reason != inspectionUnsupported
}
for _, item := range observation.Certificates {
if item.State != "available" && catalog.Required(item.Credential) {
return true
}
}
return false
}
func inspectionObservation(previous *db.CertificateInspection, response *pb.InspectKubernetesCertificatesResponse, probeErr error, controlPlane bool, now time.Time) *db.CertificateInspection {
observation := &db.CertificateInspection{AttemptedAt: now, Reason: "unavailable"}
if previous != nil {
observation.ObservedAt = previous.ObservedAt
observation.Certificates = previous.Certificates
}
if status.Code(probeErr) == codes.Unimplemented {
observation.Reason = inspectionUnsupported
return observation
}
if probeErr != nil || response == nil {
return observation
}
parsed := make([]db.CertificateObservation, 0, len(catalog.Names(controlPlane)))
seen := map[string]bool{}
for _, item := range response.GetCertificates() {
if !catalog.Supports(item.GetCredential(), controlPlane) || seen[item.GetCredential()] {
observation.Reason = inspectionInvalidResponse
return observation
}
seen[item.GetCredential()] = true
entry := db.CertificateObservation{Credential: item.GetCredential()}
switch item.GetState() {
case pb.KubernetesCertificateObservation_STATE_AVAILABLE:
if item.GetNotAfterUnixSeconds() <= 0 {
observation.Reason = inspectionInvalidResponse
return observation
}
if fingerprint := item.GetCertificateSha256(); fingerprint != "" {
decoded, err := hex.DecodeString(fingerprint)
if err != nil || len(decoded) != 32 {
observation.Reason = inspectionInvalidResponse
return observation
}
entry.CertificateSHA256 = fingerprint
}
entry.State = inspectionCertificateAvailable
entry.NotAfter = time.Unix(item.GetNotAfterUnixSeconds(), 0).UTC()
case pb.KubernetesCertificateObservation_STATE_MISSING:
entry.State = "missing"
case pb.KubernetesCertificateObservation_STATE_INVALID:
entry.State = "invalid"
case pb.KubernetesCertificateObservation_STATE_UNSPECIFIED:
observation.Reason = inspectionInvalidResponse
return observation
default:
observation.Reason = inspectionInvalidResponse
return observation
}
parsed = append(parsed, entry)
}
if len(parsed) != len(catalog.Names(controlPlane)) {
observation.Reason = inspectionInvalidResponse
return observation
}
observation.Available = true
observation.Reason = ""
observation.ObservedAt = &now
observation.Certificates = parsed
return observation
}