Skip to content

fix(encryption): flag an ignored per-RD key Secret, and say what LUKS under DRBD protects - #192

Merged
Andrei Kvapil (kvaps) merged 12 commits into
mainfrom
feat/byok-disk-encrypt
Nov 24, 2026
Merged

Andrei Kvapil (kvaps) merged 12 commits into
mainfrom
feat/byok-disk-encrypt

Conversation

@kvaps

@kvaps Andrei Kvapil (kvaps) commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

What

Main now has per-replica LUKS passwords wrapped under a master key (#258, docs/encryption-keys.md). That covers the key-hierarchy question this PR first raised and two of its fixes: rotation no longer strands volumes, so the rotation guard is dropped, and vd set-passphrase stays as main has it. Following D11 in encryption-keys.md, this PR keeps only what main still lacks.

Changes

  1. spec.encryption.passphraseSecretRef is declared and never read. An RD that sets it gets per-replica passwords wrapped under the cluster master key like every other RD, while the operator believes the referenced Secret holds the key. The CRD description now says NOT IMPLEMENTED, and a LUKS-layered RD that sets it gets an EncryptionKeyIgnored Condition on each of its Resources. This is a Condition and not a refusal: the field has always been inert, so a live cluster may carry RDs that set it and run fine, and failing their applies would move working volumes to broken ones. The Condition goes back to False when the field is cleared. The Condition message names the referenced Secret and follows it when the RD is repointed. Recorded as row 99 in docs/cli-parity-known-deltas.md.

  2. What LUKS in this stack protects. Several comments claimed DRBD ships ciphertext between peers in [DRBD,LUKS,STORAGE]. It does not: DRBD's lower disk is the dm-crypt mapper, so DRBD replicates plaintext and each node encrypts on the way to its own backing device. LUKS here is at-rest protection per node, not transport protection. The comments are corrected and docs/layer-stack.md gets a short section saying so. The ordering rule matches upstream LINSTOR and is unchanged.

Testing

  • make lint-config && make lint, go test ./... with envtest assets, integration LUKS|Encrypt.
  • The Condition tests drive buildDesiredFromCRD: set, cleared back to False, repointed at another Secret, absent on an ordinary LUKS RD, absent without LUKS, absent for an empty Secret name. With the call removed, the set and clear tests go red.

@coderabbitai

coderabbitai Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 6 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 37de53c1-f629-49ce-b1e2-3bf49675e6ec
Commits

Reviewing files that changed from the base of the PR and between 9ec5e81 and e635716.

Files selected for processing: 16

  • api/v1alpha1/drbd_options.go
  • api/v1alpha1/resource_types.go
  • config/crd/bases/blockstor.org_resourcedefinitions.yaml
  • docs/cli-parity-known-deltas.md
  • docs/layer-stack.md
  • pkg/dispatcher/dispatcher_test.go
  • pkg/rest/resource_groups_test.go
  • pkg/satellite/controllers/luks_passphrase.go
  • pkg/satellite/controllers/luks_passphrase_internal_test.go
  • pkg/satellite/controllers/luks_perrd_key_internal_test.go
  • pkg/satellite/controllers/resource.go
  • pkg/satellite/reconciler_drbd_test.go
  • pkg/validate/layers.go
  • tests/e2e/cli-matrix/lib.sh
  • tests/e2e/cli-matrix/rd-c-layer-list-rejected.sh
  • tests/e2e/drbd-luks-stack.sh

No actionable comments were generated in the recent review.

Walkthrough

The changes add safeguards for cluster passphrase rotation and per-volume passphrase writes. They report ignored per-ResourceDefinition Secret references through a condition and update documentation about encryption flow, key handling, and LINSTOR migration limits.

Changes: LUKS passphrase handling

Layer / File(s) Summary
Report ignored per-ResourceDefinition key references
api/v1alpha1/drbd_options.go, api/v1alpha1/resource_types.go, config/crd/bases/blockstor.cozystack.io_resourcedefinitions.yaml, pkg/satellite/controllers/luks_passphrase.go, pkg/satellite/controllers/resource.go, pkg/satellite/controllers/luks_passphrase_internal_test.go, pkg/satellite/controllers/luks_perrd_key_internal_test.go
The API descriptions define EncryptionKeyIgnored. Reconciliation sets the condition for LUKS resources with a nonempty per-ResourceDefinition Secret reference and continues using the cluster passphrase. Tests cover condition updates and cases that do not set the condition.
Guard REST passphrase rotation
pkg/rest/encryption.go, pkg/rest/encryption_rotation_guard.go, pkg/rest/encryption_rotation_guard_test.go
The PUT handler authenticates the old passphrase and checks for LUKS resource definitions that use the cluster key before changing it. Rotation returns HTTP 409 unless forced; lookup errors return HTTP 500. Tests cover inherited stacks, force options, unchanged values, and failures.
Refuse per-volume passphrase writes
pkg/rest/vd_passphrase_bug_233.go, pkg/rest/vd_passphrase_not_implemented_test.go
The volume-definition endpoint returns HTTP 501 for valid, nonempty passphrases without storing them. Tests check request formats, persistence, and existing error responses.
Document encryption behavior and migration limits
docs/byok-design.md, docs/cli-parity-known-deltas.md, docs/layer-stack.md, pkg/linstormigrate/convert.go, pkg/linstormigrate/testdata/golden/report.txt, pkg/validate/layers.go, pkg/dispatcher/dispatcher_test.go, pkg/rest/resource_groups_test.go, pkg/satellite/reconciler_drbd_test.go, tests/e2e/cli-matrix/*, tests/e2e/drbd-luks-stack.sh
Documentation and updated descriptions state that DRBD carries plaintext above the per-node LUKS mapper. They also describe passphrase behavior, ignored key references, and the limits on adopting encrypted LINSTOR volumes.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant ModifyHandler
  participant authenticateRotation
  participant luksRDNames
  participant ResourceDefinitionStore
  participant ResourceGroupStore
  participant PassphraseSecret
  Caller->>ModifyHandler: PUT passphrase and optional force
  ModifyHandler->>authenticateRotation: verify old passphrase
  authenticateRotation->>PassphraseSecret: read current passphrase
  ModifyHandler->>luksRDNames: check changed passphrase
  luksRDNames->>ResourceDefinitionStore: list resource definitions
  luksRDNames->>ResourceGroupStore: resolve inherited layer stacks
  luksRDNames-->>ModifyHandler: matching LUKS definitions or lookup error
  ModifyHandler->>PassphraseSecret: write new passphrase when allowed
  ModifyHandler-->>Caller: response
Loading

Suggested reviewers: ivanhunters

Merge Risk: Minimal · previous review 9ec5e

The change makes passphrase handling safer: rotation that could strand encrypted volumes is refused unless forced, per-volume passphrase writes are rejected rather than silently stored, and ignored per-resource keys are surfaced as a condition. Nothing in the supplied evidence blocks merging. The cluster behavior has not been exercised on a live stand.

Security architecture risk: Low · up to 9ec5e

The changes reduce silent encryption failures and stop new plaintext key writes through the per-volume endpoint. They do not implement safe re-keying or tenant-held keys. Cluster-wide key changes remain hazardous, and concurrent provisioning and replication-network protections are not fully covered.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — Authority over the configured cluster key can affect every encrypted volume that depends on it, across participating nodes. Existing explicit passphrase properties can select another key, but the ignored per-resource Secret-reference field provides no independent key-ownership boundary.

Security Findings and Attack Paths

  • inferred — A caller reaching the rotation endpoint and knowing the old passphrase can force a Secret change while existing headers retain the old key, causing later open or resize failures. This destructive capability predates the PR: the base performed the same mutation without requiring force. It is an unchanged architectural limitation, not an introduced finding.

Trust Boundaries and Controls

  • observed — Old-passphrase verification precedes the new safety gate, so force does not bypass that verification. The per-volume endpoint removes its previous persistence step and discards the validated supplied key rather than placing it in the ResourceDefinition.

Resilience and Maintainability Implications

  • inferred — The resource-list check, Secret update, and satellite key read are separate operations. Concurrent provisioning or stale resource visibility can therefore leave a header formatted with a key that is subsequently replaced. The new gate reduces exposure but does not establish an atomic key-lifecycle invariant; the underlying race was possible in the unguarded base.

Hardening Proposals

  • proposed — Future key-hierarchy work should coordinate formatting with key mutations across both REST and Kubernetes paths, persist suitable format-time key identity, and define recovery for interrupted transitions. A fingerprint can diagnose a mismatch but cannot itself re-key or reopen stranded headers.
Pre-merge checks: Passed 4

Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title names two changes: flagging an ignored per-ResourceDefinition key Secret, and clarifying what LUKS under DRBD protects. Both are in the changeset. The condition EncryptionKeyIgnored is added…
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title names two changes: flagging an ignored per-ResourceDefinition key Secret, and clarifying what LUKS under DRBD protects. Both are in the changeset. The condition EncryptionKeyIgnored is added, and DRBD-over-LUKS comments and docs are corrected to say DRBD carries plaintext and LUKS gives per-node at-rest protection. The title omits the other main changes (rotation guard with 409, vd set-passphrase returning 501), but it is related to the changeset and does not mislead. The title is 89 characters, which is slightly long.

Finishing Touches

🧪 Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

ℹ️ Recent review info

⚙️ Run configuration

  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 083b12d2-40e2-495d-9b7e-ceac401c00e7
📥 Commits

Reviewing files that changed from the base of the PR and between 5ff105a and 9ec5e81.

📒 Files selected for processing (24)

  • api/v1alpha1/drbd_options.go
  • api/v1alpha1/resource_types.go
  • config/crd/bases/blockstor.cozystack.io_resourcedefinitions.yaml
  • docs/byok-design.md
  • docs/cli-parity-known-deltas.md
  • docs/layer-stack.md
  • pkg/dispatcher/dispatcher_test.go
  • pkg/linstormigrate/convert.go
  • pkg/linstormigrate/testdata/golden/report.txt
  • pkg/rest/encryption.go
  • pkg/rest/encryption_rotation_guard.go
  • pkg/rest/encryption_rotation_guard_test.go
  • pkg/rest/resource_groups_test.go
  • pkg/rest/vd_passphrase_bug_233.go
  • pkg/rest/vd_passphrase_not_implemented_test.go
  • pkg/satellite/controllers/luks_passphrase.go
  • pkg/satellite/controllers/luks_passphrase_internal_test.go
  • pkg/satellite/controllers/luks_perrd_key_internal_test.go
  • pkg/satellite/controllers/resource.go
  • pkg/satellite/reconciler_drbd_test.go
  • pkg/validate/layers.go
  • tests/e2e/cli-matrix/lib.sh
  • tests/e2e/cli-matrix/rd-c-layer-list-rejected.sh
  • tests/e2e/drbd-luks-stack.sh

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

@IvanHunters IvanHunters left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict

NOT LGTM

The three refusals sit at real chokepoints and fail in the safe direction, so the shape is right. The blast radius is what is missing. The per-RD refusal wedges definitions that reconcile correctly today and leaves nothing on the object to say why; the rotation guard locks one door while an equally documented one reaches the same stranding; and the per-RD key mechanism the new docs advertise loses silently on the legacy configuration this repo still supports.

Reviewed at 66cce4b against merge-base 5ff105a. Build and vet are clean, go test ./pkg/rest/ ./pkg/satellite/controllers/ ./pkg/linstormigrate/ is green, and golangci-lint reports nothing from this branch.

Findings

  • [MAJOR] pkg/satellite/controllers/resource.go:1109, the per-RD-key refusal wedges resource definitions that work today, and the object carries no trace of why
  • [MAJOR] pkg/satellite/controllers/luks_passphrase.go:105, the CRD description still promises the field is read, so kubectl explain now walks operators into the refusal
  • [MAJOR] pkg/rest/encryption_rotation_guard.go:185, the guard closes PUT while ControllerConfig.spec.passphraseSecretRef reaches the same stranding unguarded
  • [MAJOR] docs/layer-stack.md:78, the per-RD override this PR documents loses silently to the legacy controller property
  • [MINOR] pkg/rest/encryption_rotation_guard.go:192, the fail-closed branch the comment argues hardest for has no test
  • [MINOR] pkg/rest/encryption_rotation_guard.go:91, the guard's RD set is both wider and narrower than the set a rotation can strand
  • [MINOR] pkg/rest/encryption_rotation_guard.go:168, the refusal's own remedy has no client that can send it
  • [MINOR] pkg/rest/vd_passphrase_bug_233.go:154, new writes stop but the keys already in etcd are left there
  • [MINOR] pkg/rest/encryption.go:77, the Force field silently relaxes the strict decode on POST and PATCH
  • [MINOR] pkg/rest/encryption.go:529, handlePassphraseModify lost its doc comment to authenticateRotation
  • [NIT] pkg/rest/vd_passphrase_bug_233.go:155, the comment points at a constant this same change deleted

Claim mismatches

[PARTIAL] "Every guard was mutation-checked: disabled or reverted, the named test goes red." Four do. Two branches of the rotation guard do not: the fail-closed store-error path and the name-list truncation both stay green when reverted.

[PARTIAL] "closes three surfaces that were quietly lying." Two of three are closed where named. The rotation surface is closed only on PUT. And the per-RD property surface, which this change newly documents as the working mechanism, still lies on legacy-property clusters.

[PARTIAL] §5, "an encrypted LINSTOR cluster cannot currently be adopted at all." The granularity argument does not bind for the one-volume-per-RD shape the converter's own fixtures use, since a per-RD property can express one key per RD. What binds for every shape is the blocker convert.go:1191 states first: LINSTOR's per-volume keys are wrapped with its master key and the converter implements no unwrap. Since §5 sequences BYOK behind the migration, it should lead with that.

What was and was not executed

Nothing here touched a cluster: the luksOpen failure after a rotation, the apply loop under a wedged RD and the real backoff cadence are reasoned from code, not run. bin/k8s is absent, so no envtest ran, and whether an admission rule for passphraseSecretRef would hit the ratcheting trap §6 worries about stays open.

One thing I looked at and am not filing: luksRDNames reads through the cached client while the sibling Get deliberately falls back to the uncached reader (pkg/store/k8s/k8s.go:71). A rotation issued right after an RD create could see zero LUKS RDs, but in that window the volume is not yet formatted, so it is harmless. A comment saying why the cached read is fine here would settle it, since the file next door explains why it is not.

This is a draft that names its own open edges, so nothing above re-litigates the unrun matrix cells or the hand-added parity rows.

Comment thread pkg/satellite/controllers/resource.go Outdated
// ErrPerRDKeyUnimplemented in luks_passphrase.go. Checked BEFORE
// the injection below so the refusal wins over the fallback it
// would otherwise silently take.
err = rejectUnimplementedPerRDKey(rd)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MAJOR] the per-RD-key refusal wedges resource definitions that work today, and the object carries no trace of why

rejectUnimplementedPerRDKey fires on layer stack plus the ref and nothing else. It never asks whether the volume is already formatted.

For a new RD that is right: nothing is formatted, the refusal keeps the wrong key off the header. For an RD already running in a customer cluster the volume is encrypted under the cluster key and opening fine. Refusing changes none of that. What it changes is that buildDesiredFromCRD returns an error, runApply returns it at resource.go:493 before recordPerResourceFailures and stampPostApply run, and controller-runtime requeues with exponential backoff forever. Resize, attach and peer adjust stop landing on that resource, permanently.

The failure is also invisible on the object. There is no event recorder anywhere in pkg/satellite/controllers and no SetStatusCondition on this path, so it exists only in the satellite pod log:

$ go test ./pkg/satellite/controllers/ -run TestProbeC -count=1 -v
    OBSERVED: refusal=resource definition pvc-luks-023 references Secret "tenant-owned-key": ...;
    Resource pvc-luks-023.node-a Status.Conditions=[]
--- PASS: TestProbeC_RefusalLeavesNoStatusCondition

The population is real: pkg/store/k8s/resource_definitions.go:149 and :272 carry code (Bug 209) to preserve Spec.Encryption across reconciler writes, and §6 says the field is reachable through kubectl apply / GitOps.

§6 names the shape trade-off but stops at the CRD-ratcheting objection without naming this consequence. Move rejection for new objects to a webhook or the RD create gate where it stops the object; for an RD already reconciling, keep applying under the key its headers were formatted with and stamp Ready=False plus a Warning Event. If the hard refusal stays, it must stamp a condition before returning: an unbounded requeue on a permanent misconfiguration with no surfaced status is what an operator finds three days later.

// The CRD description shipped in
// config/crd/bases/blockstor.cozystack.io_resourcedefinitions.yaml
// promises "The satellite reads it via the apiserver during reconcile;
// the passphrase never lands on Spec in plaintext." Nothing reads it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MAJOR] the CRD description still promises the field is read, so kubectl explain now walks operators into the refusal

This comment quotes the promise and leaves it standing. Neither api/v1alpha1/drbd_options.go nor config/crd/bases/blockstor.cozystack.io_resourcedefinitions.yaml is in the diff, so after merge kubectl explain resourcedefinition.spec.encryption.passphraseSecretRef still reads, verbatim at drbd_options.go:176-181 and CRD line 253:

passphraseSecretRef references the Secret carrying the LUKS
passphrase under the key `passphrase`. The satellite reads it
via the apiserver during reconcile; the passphrase never lands
on Spec in plaintext.

Before this PR that description was wrong but harmless, the field was ignored. Now it is an instruction that wedges the RD.

This is independent of the refusal's shape: even if rejection moves to admission, the description still has to say the field is not implemented and is rejected. Fix the godoc on EncryptionConfig.PassphraseSecretRef and regenerate the CRDs. ControllerConfig.Spec.PassphraseSecretRef is a different field and its description is accurate, leave it.

Comment thread pkg/rest/encryption_rotation_guard.go Outdated
// volumes exist" is not a licence to proceed. The caller sees 500 and
// retries, which is the cheap outcome; the alternative is a silent
// strand of every encrypted volume in the cluster.
func (s *Server) guardPassphraseRotation(ctx context.Context, w http.ResponseWriter, r *http.Request, body passphraseRequest) bool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MAJOR] the guard closes PUT while ControllerConfig.spec.passphraseSecretRef reaches the same stranding unguarded

passphrase.Read resolves the Secret's name through the ControllerConfig singleton on every call (pkg/passphrase/passphrase.go:74-89), and injectLUKSMasterPassphrase calls it on every reconcile of every LUKS-layered RD. Repointing that reference is a documented operator knob: api/v1alpha1/controllerconfig_types.go:51-58 says "Operators override via the ControllerConfig CRD". Doing so swaps the effective cryptsetup key with no refusal, no 409, no warning:

$ go test ./pkg/satellite/controllers/ -run TestProbeB -count=1 -v
    OBSERVED: LuksPassphrase before repoint="old-master", after repoint="new-master", refusal=<none>
--- PASS: TestProbeB_ControllerConfigRefRepointRotatesUnguarded

An operator migrating the passphrase into a differently-named or differently-managed Secret does exactly this, believes they moved custody of the same value, and strands every encrypted volume at the next attach, reboot or resize. Same failure, same silence, one CRD field from the door this guard locks.

handlePassphraseCreate is a narrower instance: on a cluster whose Secret has gone missing, POST writes a fresh value and returns 201 with the guard nowhere in the path. kubectl edit secret is genuinely out of scope, but the ControllerConfig reference is a supported configuration surface and belongs in the same guard, or the guard comment and parity row 86 need to stop claiming the rotation surface is covered.

Comment thread docs/layer-stack.md Outdated
create-passphrase`. One key per cluster, used verbatim as the
`cryptsetup` passphrase for every encrypted volume.
- A per-RD override exists via `DrbdOptions/Encryption/passphrase`
(the upstream `linstor rd set-property` key) and wins over the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MAJOR] the per-RD override this PR documents loses silently to the legacy controller property

The claim holds only when the cluster key lives in the Secret. pickLUKSPassphrase (pkg/dispatcher/dispatcher.go:373-379) prefers DrbdOptions/EncryptPassphrase, and injectLUKSMasterPassphrase skips injection when either key is set, so on a cluster still seeded through the legacy controller property the per-RD override is discarded:

$ go test ./pkg/satellite/controllers/ -run TestProbeD -count=1 -v
    OBSERVED: controller prop=cluster-legacy-prop + RD override=tenant-owned-key
    -> LuksPassphrase="cluster-legacy-prop"

Control, on a Secret-backed cluster the same override does win:

    OBSERVED: RD prop DrbdOptions/Encryption/passphrase=tenant-owned-key
    + cluster Secret=cluster-master -> LuksPassphrase="tenant-owned-key"

rd set-property returns 200 either way. The operator sets a per-RD key, gets no error, and the volume is encrypted with the cluster key: the silent-false-BYOK outcome §3.2 and §3.3 exist to eliminate, on the one per-RD mechanism this PR advertises as working. The precedence predates this branch; what is new is a document steering operators onto it without the caveat. Either state the exception here and reject the combination at rd set-property, or make the RD-scope key win over the controller-scope one and pin it.

What would change my mind: evidence the legacy DrbdOptions/EncryptPassphrase controller property is no longer a supported seed. refuseLUKSWithoutPassphrase at pkg/rest/resource_definitions.go:919 still accepts it as a valid prerequisite and passphrase.go:59-64 calls it kept for backward compatibility.

Comment thread pkg/rest/encryption_rotation_guard.go Outdated

names, err := s.luksRDNames(ctx)
if err != nil {
writeError(w, http.StatusInternalServerError,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MINOR] the fail-closed branch the comment argues hardest for has no test

The doc block above guardPassphraseRotation makes the case explicitly ("Fail-closed on a store error ... is not a licence to proceed"), and this is the only branch in the guard nothing holds:

M5 guard fail-open on store error                GAP: the suite stayed green without the fix
    test: go test ./pkg/rest/ -run 'Rotation' -count=1
    | ok  	github.com/cozystack/blockstor/pkg/rest	1.054s

Replacing the 500 with return true leaves the whole Rotation set green. That is the fail-open shape in the making: on an RBAC 403, an apiserver timeout or a cache error the guard would read "no encrypted volumes" and permit the state it exists to block. Seed a store whose List errors and assert 500 plus an intact Secret.

The rotationGuardMaxNamed truncation has the same gap (M6, also green) and matters less, but a six-RD case asserting the count and the ellipsis is two lines.

Comment thread pkg/rest/encryption_rotation_guard.go Outdated
b.WriteString(", …")
}

b.WriteString("). blockstor uses the cluster passphrase directly as the LUKS key, " +

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MINOR] the refusal's own remedy has no client that can send it

The message ends "repeat with force=true to rotate anyway and strand them". Neither supported CLI can do that.

python-linstor sends a fixed two-field body, confirmed by running it:

$ docker run --rm python:3.12-slim sh -c "pip install --quiet python-linstor; python -c \
    'import inspect,linstor; print(inspect.getsource(linstor.Linstor.crypt_modify_passphrase))'"

    def crypt_modify_passphrase(self, old_passphrase, new_passphrase):
        body = {
            "new_passphrase": new_passphrase,
            "old_passphrase": old_passphrase
        }
        return self._rest_request(
            apiconsts.API_MOD_CRYPT_PASS,
            "PUT", _pquote("/v1/encryption/passphrase"),
            body
        )

No force field, no query string. blockstor's own CLI registers only create-passphrase and enter-passphrase under the encryption noun (internal/cli/command/registry.go:265-271), so it cannot reach the verb at all. The operator hitting the 409 has to hand-roll HTTP. Either add the flag to the native CLI or reword the message to say what an operator can actually type.

Comment thread pkg/rest/vd_passphrase_bug_233.go Outdated
RetCode: maskInfo,
Message: "VD passphrase stored; cluster-side LUKS rotation pending Phase 12",
}})
// The value is deliberately NOT persisted. See the package-level

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MINOR] new writes stop but the keys already in etcd are left there

The handler no longer persists, and the new test walks every props bag to prove it. The keys the old handler already wrote stay exactly where §3.3 says they should not be: DrbdOptions/Encrypt/Passphrase on VolumeDefinition.Props, inline in ResourceDefinition.spec.volumeDefinitions, readable by anyone holding get resourcedefinitions.

Nothing in this branch removes them and the repository has no migration mechanism to hang a cleanup on. Since no code path ever read the value, deleting it is safe and lossless. A documented cleanup step (which property to delete on which volume definitions) in docs/layer-stack.md or the release notes would close the half that upgraded clusters actually live with. Framing the defect as an at-rest disclosure and then leaving the disclosed values in place is the gap.

Comment thread pkg/rest/encryption.go
NewPassphrase string `json:"new_passphrase,omitempty"`
OldPassphrase string `json:"old_passphrase,omitempty"`
Passphrase string `json:"passphrase,omitempty"`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MINOR] the Force field silently relaxes the strict decode on POST and PATCH

Force lands on passphraseRequest, the decode target for all three verbs through decodeJSON's DisallowUnknownFields. Before this change {"new_passphrase":"x","force":true} on POST or PATCH was a 400; now it is accepted and ignored.

The comment says "Ignored by POST/PATCH", which is accurate about the behaviour and is precisely the problem: a caller sending force to the create or enter verb gets a success and no indication the flag did nothing. Either give PUT its own body type, or reject force explicitly on the two verbs that do not honour it. Worth a line in the parity table either way, since row 86 documents the flag as belonging to one verb.

Comment thread pkg/rest/encryption.go Outdated
// The envelope shape (`[]ApiCallRc` with MASK_INFO + message)
// matches every other write-side endpoint in the apiserver so
// python-linstor's CLI loop renders the success line uniformly.
// authenticateRotation is the read-and-verify half of

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MINOR] handlePassphraseModify lost its doc comment to authenticateRotation

The extraction inserted authenticateRotation's comment directly onto the tail of the existing block with no blank line, so lines 501 to 563 are now one contiguous comment attached to authenticateRotation, and handlePassphraseModify at :565 has none.

godoc will render the whole status surface ("new == old and old verified, 200 OK plus MASK_INFO envelope, no Secret write", "happy rotation") against a function that performs none of it. A blank line at 528 and moving the original block back down fixes it.

Comment thread pkg/rest/vd_passphrase_bug_233.go Outdated
Message: "VD passphrase stored; cluster-side LUKS rotation pending Phase 12",
}})
// The value is deliberately NOT persisted. See the package-level
// note above `vdPassphrasePropKey`: storing it put the operator's

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NIT] the comment points at a constant this same change deleted

The comment reads "See the package-level note above vdPassphrasePropKey". That identifier is gone from the tree as of this diff:

$ grep -rn 'vdPassphrasePropKey' --include='*.go' .
pkg/rest/vd_passphrase_bug_233.go:155:	// note above `vdPassphrasePropKey`: storing it put the operator's

The only match is the comment itself, and the note it points at is now headed "Historical note — the per-VD passphrase property" with no such name in it. Someone grepping for the constant to find the rationale gets nothing.

Andrei Kvapil (kvaps) added a commit that referenced this pull request Sep 8, 2026
Review (IvanHunters, PR #192) caught the refusal added earlier: it
fails the apply for resource definitions that reconcile correctly
today. The field has always been inert, so a live cluster may carry
RDs that set it and run fine on the cluster key — refusing moves a
working volume to a broken one. And buildDesiredFromCRD's error goes
to controller-runtime's backoff, so the object carried no trace of
why it stopped.

The silence was the defect, not the provisioning. A LUKS-layered RD
that pins spec.encryption.passphraseSecretRef now keeps working on the
cluster key and gets an EncryptionKeyIgnored Condition naming the
ignored Secret and saying which key is actually in use. The Condition
tracks the live spec rather than latching, and is written only on a
state change so the steady state costs no apiserver traffic.

The CRD description promised the satellite reads the field, so
kubectl explain walked operators straight into the old refusal. It now
says NOT IMPLEMENTED and points at the Condition.

The test rig needed WithStatusSubresource: without it the fake client
answers a Status().Patch with "not found" while a plain Get succeeds,
which would have made any Condition assertion silently vacuous.

Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
blockstor uses the cluster master passphrase verbatim as the cryptsetup
key: no key-encryption-key, no per-volume data key. That single fact
decides the whole feature, so write it down before touching code.

Records three consequences confirmed in the tree — rotation strands
encrypted volumes, spec.encryption.passphraseSecretRef is declared and
never read, vd set-passphrase stores a key nothing consumes — and the
migration interlock: LINSTOR wraps its stored keys with its master key
and the converter implements no unwrap, so a live encrypted cluster
cannot be adopted today.

Proposes per-volume data keys wrapped by a KEK as the mechanism, with
per-tenant custody as the product surface and an external key manager
as one pluggable KEK provider. No decision taken.

Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
The cluster passphrase Secret is used verbatim as the cryptsetup key,
so rotating it leaves every LUKS header locked with the old value.
Nothing is destroyed — Format probes isLuks and no-ops — but dm-crypt
mappers already open outlive a satellite restart, so the cluster looks
healthy until a node reboot, a re-attach or a resize, and only then do
the volumes stop opening. The handler answered 200 through all of this.

PUT /v1/encryption/passphrase now returns 409 naming the blocking
resource definitions, with force=true (PUT body field or query
parameter) as the escape hatch. The linstor CLI has no flag for it, so
the message spells out the direct call.

The blocking set resolves the layer stack through the parent resource
group, so RDs that inherit LUKS rather than declaring it are seen, and
excludes RDs pinning their own passphrase, which a cluster rotation
cannot strand. The store-error path fails closed.

force lives on a PUT-only body type: sharing it would have made POST
and PATCH silently accept a key that was previously a 400 and means
nothing to them.

Deliberate divergence from upstream, where rotation is safe because the
master key only wraps per-volume keys. Recorded as parity delta 86.

Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
vd set-passphrase stamped the operator's key into the volume
definition's props under DrbdOptions/Encrypt/Passphrase and answered
200. The dispatcher lifts only DrbdOptions/EncryptPassphrase and
DrbdOptions/Encryption/passphrase, so the key was never consumed and
the volume kept the cluster key while the CLI reported success.

Volume definitions are inline in the ResourceDefinition spec, so the
key also sat in cleartext in etcd behind get resourcedefinitions — a
wider RBAC surface than Secret access. The REST read path redacts it,
so this was an at-rest disclosure through the Kubernetes door.

Storing a secret in cleartext for a feature that does not exist is all
cost: return a structured 501 and persist nothing. The 404 and 400
branches keep their precedence. The refusal does not remove keys
earlier releases already wrote; docs/layer-stack.md carries the purge
recipe and says to treat anything found that way as disclosed.
Recorded as parity delta 87.

Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
ResourceDefinition.spec.encryption.passphraseSecretRef is declared in
the API and its CRD description promised the satellite reads it during
reconcile. Nothing reads it. The only non-test code touching
Spec.Encryption preserves the field across updates so it survives a
reconciler write — defended against loss and never consumed.

An RD that set it therefore fell through to the cluster master
passphrase: object accepted on both doors, no error anywhere, volume
encrypted with the platform's key while the operator believed they held
the only one.

A LUKS-layered RD naming a passphrase Secret now keeps provisioning on
the cluster key and gets an EncryptionKeyIgnored Condition naming the
ignored Secret and stating which key is actually in use. Deliberately
not a refusal: the field has always been inert, so a live cluster may
carry RDs that set it and reconcile fine, and failing their applies
would move working volumes to broken ones. The Condition tracks the
live spec rather than latching, and is written only on a state change.

The CRD description now says NOT IMPLEMENTED so kubectl explain stops
promising otherwise. Implementing the field for real needs the
format-time key-identity pin described in docs/byok-design.md, since
honouring it on an already-formatted RD would itself make a working
volume unopenable. Recorded as parity delta 88.

Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
Five comments across pkg/validate, pkg/dispatcher, pkg/satellite,
pkg/rest and the e2e suite claimed DRBD ships ciphertext between peers
in the [DRBD,LUKS,STORAGE] stack. It does not, and the code says so:
maybeLUKS rewrites the volume->device map to the dm-crypt mapper paths
before applyDRBD, so DRBD's lower disk is the plaintext side.
drbd-luks-stack.sh already asserted exactly that two lines below its
own contradicting header.

So the pod writes plaintext into /dev/drbdN, DRBD replicates plaintext,
and each node encrypts on the way to its own backing device. LUKS here
is at-rest protection per node, not transport protection. Anyone
deriving the threat model from these comments would have concluded that
replication traffic is encrypted, and it is not.

Also corrects the documented passphrase precedence — the cluster-scope
property wins over the per-RD one, not the other way round — narrows
the rotation guard's documented scope to the REST verb it actually
covers, and rewrites the migration converter's LUKS warning, which told
operators to provision a field that does nothing and led them to an
unopenable volume.

Comment and documentation only; the layer ordering rule matches
upstream LINSTOR and is unchanged.

Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
@kvaps
Andrei Kvapil (kvaps) marked this pull request as ready for review October 5, 2026 13:55

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Andrei Kvapil (@kvaps) NOT LGTM. The rotation guard counts RDs as encrypted that the satellite never encrypts, and several new comments narrate the review history instead of the code.

The guard treats an RD that inherits LUKS from its resource group as encrypted, and the satellite does not. luksRDNames resolves the stack through apiv1.ResolveLayerStack, and the comment at encryption_rotation_guard.go:89-95 says those RDs "are encrypted and were being missed". But the satellite gets its stack from assembleDesired, which copies rd.Spec.LayerStack and nothing else (pkg/dispatcher/dispatcher.go:261-263). An empty stack becomes the satellite's DRBD+STORAGE default, with no LUKS. The only RG-aware resolver on that side, ResourceReconciler.resolveLayerStack, is called from export_test.go and nowhere in production. This PR's own Condition stamper agrees with the satellite: perRDKeySecretName checks rd.Spec.LayerStack only (luks_passphrase.go:115). So the same branch has two answers to "is this RD encrypted".

In practice the guard refuses a rotation over RDs a rotation cannot strand, and the 409 tells the operator they "were formatted with the current passphrase". TestRotationRefusedForRGInheritedLUKS pins that, and the mutation table counts it as evidence. Worse, the comment states as fact that putting LUKS on a resource group encrypts the RDs created in it through kubectl. As far as I can trace, those volumes are written to disk in plaintext. docs/layer-stack.md:30-33 says the same thing, but that text was there before this branch. Please make the guard, the comment and the test match what the satellite does. The silent plaintext for RG-inherited LUKS is its own bug and should not be fixed here. I'd file it separately.

Several comments added here tell the story of earlier revisions and the review instead of explaining the code: encryption_rotation_guard.go:86 ("Review found the first version's set..."), luks_passphrase.go:129-130 ("An earlier revision failed the apply here; review caught..."), encryption_rotation_guard_test.go:323 and :465, and luks_perrd_key_internal_test.go:26. The reasoning in them is worth keeping as a plain statement of the constraint. For example: a refusal would wedge RDs that reconcile today, and the error never reaches Status. Who found it and in which revision belongs in the PR thread.

The earlier changes-requested review from IvanHunters looks addressed at this head: the per-RD refusal became a Condition, the CRD description says NOT IMPLEMENTED (and make manifests produces no drift), the fail-closed path has a test, force is PUT-only, and the precedence and purge notes are in docs/layer-stack.md. On a trial merge with main 5c354a0, build, vet and the touched packages pass. In pkg/rest, the only failures are the harness shutdown timeouts the description already lists.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NOT LGTM, only because the branch no longer merges. The code and the upstream claims check out (key hierarchy and per-replica keys as in linstor-server EncryptionHelper and RscLuksLayerHelper), but main has moved under it and the merge conflicts in eight files, among them pkg/rest/encryption.go, pkg/satellite/controllers/luks_passphrase.go, pkg/satellite/controllers/resource.go and pkg/linstormigrate/convert.go. Those are logic conflicts, not mechanical ones, so please rebase onto main. One non-blocking note inline.

Comment thread docs/byok-design.md Outdated
replica**, and blockstor has exactly one for the whole cluster — but the per-RD
property (§2) can already express one key per resource definition, which is
enough for the one-volume-per-RD shape the converter's own fixtures use. So
granularity is not what blocks a single-volume RD; the unwrap is. Granularity

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking. Upstream generates a fresh random key per resource, so per replica, unless it copies one from a shared-storage or clone source (RscLuksLayerHelper.java:290-301 at 80bb295b). So even a one-volume RD with two replicas has two keys, and a per-RD prop cannot hold them. This sentence and the next paragraph disagree. The new warning in convert.go and the layer-stack.md bullet say "per volume" where upstream is per replica too.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. LINSTOR generates a password per replica and reuses one only when it copies it from a shared-storage peer or a clone source, or when the volume definition carries a user passphrase (RscLuksLayerHelper.java L255-318 at v1.33.1). So a per-RD prop cannot hold even a one-volume RD with two replicas. D11 in encryption-keys.md says to replace this note with that document, which states the per-replica scheme correctly, so 93f288f drops byok-design.md from the PR. The convert.go warning and the layer-stack.md bullet that said "per volume" are main's text after the merge and describe the imported per-replica keys. The same commit fixes the stack table, which still said "Per-volume cipher".

Main landed per-replica LUKS passwords wrapped under a master key
(#258), the hierarchy this branch only proposed. Its rotation guard
and the vd set-passphrase 501 are superseded there: a passphrase change
re-wraps the master key and touches no header. The merge takes main's
side for encryption.go, vd_passphrase_bug_233.go and convert.go, and
keeps the EncryptionKeyIgnored Condition, now worded for per-replica
keys, plus the plaintext-replication corrections.

Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
encryption-keys.md took the decision this note asked for (D11 says to
replace it), and after the merge the note described the single cluster
passphrase as current behaviour and claimed a per-RD key could hold a
one-volume RD. LINSTOR generates a password per replica, so even two
replicas of one volume have two keys. The layer-stack table said
per-volume for the same reason.

Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
The section this PR adds was hard-wrapped, which the repository's
prose rule refuses for new markdown. The sentence about earlier
comments is dropped too: the corrected comments are in the same diff,
and a doc should state what holds rather than its own history.

Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
@kvaps Andrei Kvapil (kvaps) changed the title fix(encryption): make the BYOK surfaces honest, and write down the key-hierarchy decision fix(encryption): flag an ignored per-RD key Secret, and say what LUKS under DRBD protects Nov 23, 2026
@kvaps

Copy link
Copy Markdown
Member Author

Merged main into the branch in dd9d0e4 (a merge, no force-push). Most conflicts came from #258, which landed the key hierarchy this PR only proposed: per-replica passwords wrapped under a master key, with LINSTOR's keys imported on migration. Following D11 in docs/encryption-keys.md, the merge takes main's side for encryption.go, vd_passphrase_bug_233.go and convert.go, so the rotation guard is gone (a passphrase change now re-wraps the master key and touches no header). What the PR still adds is the EncryptionKeyIgnored Condition for spec.encryption.passphraseSecretRef and the plaintext-replication corrections in comments and layer-stack.md. The Condition message, the CRD text and the test now say the volume's password is wrapped under the cluster master key, and point at docs/encryption-keys.md.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The merge with main resolves cleanly now, and taking main's key hierarchy leaves a small net diff: the EncryptionKeyIgnored Condition, the NOT IMPLEMENTED text on passphraseSecretRef with row 98, and the plaintext-replication corrections. The Condition owns only its own list entry and writes only on a change. Unit tests are red on this head from TestReconcileComesBackWhenAPlacementHoldRunsOut and TestManagerIndexesCachedReplicasByDefinitionKey, which this PR does not touch; both fail on main and #318 fixes them. One non-blocking note inline.

"Secret. See docs/encryption-keys.md"
}

if conditionAlreadyIs(target.Status.Conditions, blockstoriov1alpha1.ConditionEncryptionKeyIgnored, want) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking. This compares only the status, so if the RD switches passphraseSecretRef to another Secret, the Condition stays True with the old Secret name in its message. Comparing the message too would keep it current.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f557850. The write is now skipped only when the status and the message both match, so repointing the RD at another Secret rewrites the message. A message-only change keeps the time the status last changed, as meta.SetStatusCondition does. TestPerRDPassphraseConditionFollowsARenamedSecret repoints the RD and fails on the previous code with the first Secret's name still in the message.

Several open branches added accept-list rows at the next free id on
main, so the merged table carried
ids 95, 96, 97 and 100 twice. Each branch
now takes its own ids above main's 98, in PR order, so they stay
unique whatever order the branches merge in. This row moves from 98
to 99.

Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. I compared this head with the one I approved at e6c8821. The only difference is the known-delta row renumbered from 98 to 99 after the merge of main.

# Conflicts:
#	docs/cli-parity-known-deltas.md
The Condition was rewritten only when its status changed. An RD
repointed from one passphraseSecretRef to another kept the Condition
True with the first Secret's name, so the operator would look at an
object the RD no longer references. The write is now skipped only
when status and message both match, and a message-only change keeps
the time the status last changed.

Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Since the head I approved, the branch merged main and f557850 makes the EncryptionKeyIgnored write compare the message as well as the status, so a repointed RD now gets the new Secret name while the transition time stays put. The new test fails on the previous code, since that left the first Secret's name in place. The points in the earlier changes-requested review on 66cce4b are either answered here (the refusal is now a Condition, and the CRD text says NOT IMPLEMENTED) or about code that is no longer in the diff after the merge with main's key hierarchy. All checks are green.

Assisted-by: LLM
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
@kvaps
Andrei Kvapil (kvaps) merged commit 5f5e490 into main Nov 24, 2026
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants