Skip to content

<fix>[kvm]: create key when attach tpm#3776

Closed
zstack-robot-2 wants to merge 1 commit intozsv_5.0.0from
sync/zstackio/ref-attach-tpm@@2
Closed

<fix>[kvm]: create key when attach tpm#3776
zstack-robot-2 wants to merge 1 commit intozsv_5.0.0from
sync/zstackio/ref-attach-tpm@@2

Conversation

@zstack-robot-2
Copy link
Copy Markdown
Collaborator

For existing non-vTPM VMs, attach the key provider and
materialize the actual key before preInstantiateVmResource,
so libvirt secret cache lookup does not miss keyVersion.

Resolves: ZSV-11729

Change-Id: I6e6d6c6c647122226769756b75756c6f72654477

sync from gitlab !9646

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 16, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 90e23f2e-4f3c-4dff-98e6-b50c0f0957bb

📥 Commits

Reviewing files that changed from the base of the PR and between f30ef86 and 59d0b78.

📒 Files selected for processing (1)
  • plugin/kvm/src/main/java/org/zstack/kvm/tpm/KvmTpmManager.java

Walkthrough

addTpmToVm 流程中,context.keyProviderUuid 从可选变为必需,缺失时立即失败;当存在时,附加密钥提供器后新增调用 EncryptedResourceKeyManager.getOrCreateKey(...)(resourceUuid = 新建 TPM UUID、resourceType = TpmVO、keyProviderUuid = context.keyProviderUuid、purpose = "vtpm"),并根据其结果推进或终止流程。

Changes

Cohort / File(s) Summary
TPM 附加与密钥创建逻辑变更
plugin/kvm/src/main/java/org/zstack/kvm/tpm/KvmTpmManager.java
新增 @Autowired private EncryptedResourceKeyManager resourceKeyManager 字段;在 attach-key-provider-to-tpm 流程中将 context.keyProviderUuid 设为必需(为空时 trigger.fail(...) 并返回);在成功附加后调用 resourceKeyManager.getOrCreateKey(...)(resourceUuid = TPM UUID,resourceType = TpmVO,keyProviderUuid 来源于 context,purpose = "vtpm"),并根据异步结果调用 trigger.next()trigger.fail()

Sequence Diagram(s)

sequenceDiagram
  participant VMFlow as "VM Create Flow"
  participant Kvm as "KvmTpmManager"
  participant KeyMgr as "EncryptedResourceKeyManager"
  participant KeyProv as "KeyProvider DB"

  VMFlow->>Kvm: request addTpmToVm(context)
  Kvm->>Kvm: check context.keyProviderUuid
  alt keyProviderUuid == null
    Kvm-->>VMFlow: trigger.fail(operr(...))
  else keyProviderUuid != null
    Kvm->>KeyProv: attach key provider to TPM (async)
    KeyProv-->>Kvm: attach success
    Kvm->>KeyMgr: getOrCreateKey(resourceUuid=TPM UUID, resourceType=TpmVO, keyProviderUuid, purpose="vtpm")
    alt getOrCreateKey success
      KeyMgr-->>Kvm: success
      Kvm-->>VMFlow: trigger.next()
    else getOrCreateKey fail
      KeyMgr-->>Kvm: error
      Kvm-->>VMFlow: trigger.fail(error)
    end
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 我是小兔来报喜,
密钥若无路不通,
附加有序再创建,
vtpm 密钥握手中,
兔子为安全轻轻跳。

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed 标题准确地反映了主要变更:在附加TPM时创建加密密钥,与代码摘要中的核心变更相符。
Description check ✅ Passed 描述清晰地说明了变更目的:为非vTPM的现有虚拟机在preInstantiateVmResource之前附加密钥提供程序并创建实际密钥,与代码变更内容相关。

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch sync/zstackio/ref-attach-tpm@@2

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
plugin/kvm/src/main/java/org/zstack/kvm/tpm/KvmTpmManager.java (1)

287-292: ⚠️ Potential issue | 🟠 Major

缺少对创建的资源密钥的回滚处理。

当前的回滚逻辑(lines 287-292)仅分离了密钥提供器,但没有处理在 lines 268-284 中可能创建的加密资源密钥。根据检索到的学习记录,EncryptedResourceKeyManager.ResourceKeyResult 提供了 isCreatedNewKey() 方法来判断是否创建了新密钥。如果创建了新密钥,回滚时应删除已具体化的 key-tool secret 并移除 EncryptedResourceKeyRef 行。

建议在回滚逻辑中保存 ResourceKeyResult,并在回滚时检查 isCreatedNewKey() 以决定是否需要清理密钥。

Based on learnings: "In ZStack's KvmTpmExtensions.preReleaseVmResource, as of PR #3716, the ResourceKeyResult.refExistedBeforeCreate field has been removed from EncryptedResourceKeyManager.ResourceKeyResult. Rollback behavior is now determined solely by ResourceKeyResult.isCreatedNewKey(): when true, the implementation deletes the materialized key-tool secret and removes the EncryptedResourceKeyRef row; when false, rollback is a no-op."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@plugin/kvm/src/main/java/org/zstack/kvm/tpm/KvmTpmManager.java` around lines
287 - 292, The rollback currently only detaches the key provider
(tpmKeyBackend.detachKeyProviderFromTpm using context.createdTpmUuid) but misses
cleanup for any newly created encrypted resource key; capture and store the
EncryptedResourceKeyManager.ResourceKeyResult from the create path (e.g., in the
KvmTpmManager context as context.resourceKeyResult) and in the rollback lambda
check resourceKeyResult.isCreatedNewKey(), and if true delete the materialized
key-tool secret and remove the EncryptedResourceKeyRef row (use your existing
key-secret deletion and DB removal helpers or add methods like
deleteKeyToolSecret(...) and removeEncryptedResourceKeyRef(...)); leave behavior
as no-op when isCreatedNewKey() is false.
🧹 Nitpick comments (1)
plugin/kvm/src/main/java/org/zstack/kvm/tpm/KvmTpmManager.java (1)

268-273: 建议使用完整的变量名以提高可读性。

变量名 keyCtx 使用了缩写。根据编码规范,应避免不必要的缩写,建议使用完整的变量名 keyContext 以提升代码可读性。

As per coding guidelines: "不允许使用不必要的缩写,如:AbsSchedulerJobcondiFu 等。应使用完整单词提升可读性。"

♻️ 重命名建议
-                    EncryptedResourceKeyManager.GetOrCreateResourceKeyContext keyCtx =
+                    EncryptedResourceKeyManager.GetOrCreateResourceKeyContext keyContext =
                             new EncryptedResourceKeyManager.GetOrCreateResourceKeyContext();
-                    keyCtx.setResourceUuid(context.createdTpmUuid);
-                    keyCtx.setResourceType(TpmVO.class.getSimpleName());
-                    keyCtx.setKeyProviderUuid(context.keyProviderUuid);
-                    keyCtx.setPurpose("vtpm");
-                    resourceKeyManager.getOrCreateKey(keyCtx, new ReturnValueCompletion<EncryptedResourceKeyManager.ResourceKeyResult>(trigger) {
+                    keyContext.setResourceUuid(context.createdTpmUuid);
+                    keyContext.setResourceType(TpmVO.class.getSimpleName());
+                    keyContext.setKeyProviderUuid(context.keyProviderUuid);
+                    keyContext.setPurpose("vtpm");
+                    resourceKeyManager.getOrCreateKey(keyContext, new ReturnValueCompletion<EncryptedResourceKeyManager.ResourceKeyResult>(trigger) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@plugin/kvm/src/main/java/org/zstack/kvm/tpm/KvmTpmManager.java` around lines
268 - 273, Rename the local variable keyCtx to a full-word name (e.g.,
keyContext) where the EncryptedResourceKeyManager.GetOrCreateResourceKeyContext
is instantiated and used in the KvmTpmManager class; update all subsequent
references (setResourceUuid, setResourceType, setKeyProviderUuid, setPurpose) to
use the new variable name to follow the coding guideline against unnecessary
abbreviations.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@plugin/kvm/src/main/java/org/zstack/kvm/tpm/KvmTpmManager.java`:
- Around line 259-286: The code calls resourceKeyManager.getOrCreateKey(...)
with a ReturnValueCompletion that calls trigger.next() on success, but then
immediately calls trigger.next() again right after starting the async call,
causing duplicate continuation; remove the extraneous trigger.next() that
follows resourceKeyManager.getOrCreateKey(...) so only the completion's
success() advances the flow (leave tpmKeyBackend.attachKeyProviderToTpm(...) and
context.keyProviderAttached = true as-is and rely on
EncryptedResourceKeyManager.GetOrCreateResourceKeyContext + the
ReturnValueCompletion to drive the next trigger).

---

Outside diff comments:
In `@plugin/kvm/src/main/java/org/zstack/kvm/tpm/KvmTpmManager.java`:
- Around line 287-292: The rollback currently only detaches the key provider
(tpmKeyBackend.detachKeyProviderFromTpm using context.createdTpmUuid) but misses
cleanup for any newly created encrypted resource key; capture and store the
EncryptedResourceKeyManager.ResourceKeyResult from the create path (e.g., in the
KvmTpmManager context as context.resourceKeyResult) and in the rollback lambda
check resourceKeyResult.isCreatedNewKey(), and if true delete the materialized
key-tool secret and remove the EncryptedResourceKeyRef row (use your existing
key-secret deletion and DB removal helpers or add methods like
deleteKeyToolSecret(...) and removeEncryptedResourceKeyRef(...)); leave behavior
as no-op when isCreatedNewKey() is false.

---

Nitpick comments:
In `@plugin/kvm/src/main/java/org/zstack/kvm/tpm/KvmTpmManager.java`:
- Around line 268-273: Rename the local variable keyCtx to a full-word name
(e.g., keyContext) where the
EncryptedResourceKeyManager.GetOrCreateResourceKeyContext is instantiated and
used in the KvmTpmManager class; update all subsequent references
(setResourceUuid, setResourceType, setKeyProviderUuid, setPurpose) to use the
new variable name to follow the coding guideline against unnecessary
abbreviations.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: cd178880-46e3-4845-a27f-ac41d0d17d29

📥 Commits

Reviewing files that changed from the base of the PR and between 1ddd492 and f30ef86.

📒 Files selected for processing (1)
  • plugin/kvm/src/main/java/org/zstack/kvm/tpm/KvmTpmManager.java

Comment thread plugin/kvm/src/main/java/org/zstack/kvm/tpm/KvmTpmManager.java
For existing non-vTPM VMs, attach the key provider and
materialize the actual key before preInstantiateVmResource,
so libvirt secret cache lookup does not miss keyVersion.

Resolves: ZSV-11729

Change-Id: I6e6d6c6c647122226769756b75756c6f72654477
@MatheMatrix MatheMatrix force-pushed the sync/zstackio/ref-attach-tpm@@2 branch from f30ef86 to 59d0b78 Compare April 16, 2026 13:03
@zstack-robot-2 zstack-robot-2 deleted the sync/zstackio/ref-attach-tpm@@2 branch April 17, 2026 01:55
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.

2 participants