Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(crypto): v2 volume encryption #3438

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

mantissahz
Copy link
Contributor

Which issue(s) this PR fixes:

Issue # longhorn/longhorn#7355

What this PR does / why we need it:

Special notes for your reviewer:

Additional documentation or context

@mantissahz mantissahz requested a review from a team January 8, 2025 09:55
@mantissahz mantissahz self-assigned this Jan 8, 2025
Copy link

coderabbitai bot commented Jan 8, 2025

Warning

Rate limit exceeded

@mantissahz has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 minutes and 21 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between b37ffa7 and 4be8397.

📒 Files selected for processing (2)
  • csi/crypto/crypto.go (5 hunks)
  • csi/node_server.go (6 hunks)

Walkthrough

The pull request introduces modifications across multiple files to enhance volume management, particularly for encrypted devices and data engine types. The changes focus on integrating Longhorn V2 engine support, updating crypto-related functions to handle different data engine types, and modifying validation logic for volume creation. The primary goal is to improve volume handling by adding more context-aware operations that can distinguish between different data engine versions.

Changes

File Change Summary
csi/crypto/crypto.go - Added Longhorn API import
- Updated VolumeMapper to accept dataEngine parameter
- Modified OpenVolume, CloseVolume, and ResizeEncryptoDevice to include dataEngine
- Introduced getEncryptVolumeName helper function
- Added logic to append -encrypted suffix for V2 engine volumes
csi/node_server.go - Enhanced logging to include dataEngine
- Updated method calls to crypto.VolumeMapper with dataEngine
- Improved handling of volume data engines in NodeStageVolume, NodeUnstageVolume, and NodeExpandVolume
webhook/resources/volume/validator.go - Removed error check for encrypted volumes with data engine v2

Sequence Diagram

sequenceDiagram
    participant NodeServer
    participant CryptoModule
    participant Volume

    NodeServer->>CryptoModule: NodeStageVolume(volume, dataEngine)
    CryptoModule->>CryptoModule: VolumeMapper(volume, dataEngine)
    alt DataEngine is V2
        CryptoModule-->>CryptoModule: Append '-encrypted' to volume name
    end
    CryptoModule->>Volume: Open/Stage Volume
    Volume-->>CryptoModule: Volume Staged
    CryptoModule-->>NodeServer: Return Status
Loading

The sequence diagram illustrates the enhanced volume staging process, showing how the data engine type influences volume mapping and staging operations.

Finishing Touches

  • 📝 Generate Docstrings

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@mantissahz mantissahz force-pushed the issue7355 branch 2 times, most recently from 76e1361 to cc5802d Compare January 8, 2025 10:02
@mantissahz mantissahz marked this pull request as ready for review January 9, 2025 02:48
Copy link

@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: 0

🧹 Nitpick comments (4)
csi/crypto/crypto.go (2)

Line range hint 103-120: Consider consolidating volume name handling

The volume name handling logic is duplicated between OpenVolume and CloseVolume. Consider extracting this to a helper function.

+func getEncryptVolumeName(volume, dataEngine string) string {
+    if dataEngine == string(longhorn.DataEngineTypeV2) {
+        return volume + mapperV2VolumeSuffix
+    }
+    return volume
+}

 func OpenVolume(volume, dataEngine, devicePath, passphrase string) error {
-    encryptVolumeName := volume
-    if dataEngine == string(longhorn.DataEngineTypeV2) {
-        encryptVolumeName = volume + mapperV2VolumeSuffix
-    }
+    encryptVolumeName := getEncryptVolumeName(volume, dataEngine)
     logrus.Infof("Opening device %s with LUKS on %s", devicePath, encryptVolumeName)

128-140: Use consistent error handling

The error handling in CloseVolume could be improved to match the pattern in OpenVolume where errors are logged with context.

 func CloseVolume(volume, dataEngine string) error {
     namespaces := []lhtypes.Namespace{lhtypes.NamespaceMnt, lhtypes.NamespaceIpc}
     nsexec, err := lhns.NewNamespaceExecutor(lhtypes.ProcessNone, lhtypes.HostProcDirectory, namespaces)
     if err != nil {
         return err
     }

-    encryptVolumeName := volume
-    if dataEngine == string(longhorn.DataEngineTypeV2) {
-        encryptVolumeName = volume + mapperV2VolumeSuffix
-    }
+    encryptVolumeName := getEncryptVolumeName(volume, dataEngine)
     logrus.Infof("Closing LUKS device %s", encryptVolumeName)
     _, err = nsexec.LuksClose(encryptVolumeName, lhtypes.LuksTimeout)
+    if err != nil {
+        logrus.WithError(err).Warnf("Failed to close LUKS device %s", encryptVolumeName)
+    }
     return err
 }
webhook/resources/volume/validator.go (1)

170-171: LGTM: Clear validation for V2 volume limitations

The validation correctly prevents the use of backing images with V2 volumes. The error message is clear and descriptive.

However, consider adding a comment explaining why backing images are not supported for V2 volumes to help future maintainers.

 if types.IsDataEngineV2(volume.Spec.DataEngine) {
+    // Backing images are not supported for V2 volumes due to architectural limitations
+    // in the current implementation of the V2 data engine.
     if volume.Spec.BackingImage != "" {
         return werror.NewInvalidError("backing image is not supported for data engine v2", "")
     }
csi/node_server.go (1)

519-519: Consider adding error recovery for crypto operations

The crypto device operations could benefit from additional error recovery mechanisms. If OpenVolume fails, we might want to attempt cleanup.

+func (ns *NodeServer) cleanupCryptoDevice(volumeID, dataEngine string) {
+    if err := crypto.CloseVolume(volumeID, dataEngine); err != nil {
+        ns.log.WithError(err).Warnf("Failed to cleanup crypto device for volume %s", volumeID)
+    }
+}

 if err := crypto.OpenVolume(volumeID, dataEngine, devicePath, passphrase); err != nil {
+    ns.cleanupCryptoDevice(volumeID, dataEngine)
     return nil, status.Error(codes.Internal, err.Error())
 }

Also applies to: 529-529, 534-534

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e11c082 and 6827312.

📒 Files selected for processing (3)
  • csi/crypto/crypto.go (4 hunks)
  • csi/node_server.go (6 hunks)
  • webhook/resources/volume/validator.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build binaries
  • GitHub Check: Summary
🔇 Additional comments (6)
csi/crypto/crypto.go (3)

13-13: LGTM: Clean addition of V2 support

The import of the Longhorn API package and the addition of the V2 volume suffix constant are well-placed and follow the existing pattern.

Also applies to: 18-18


74-77: LGTM: Clear data engine type handling

The VolumeMapper function now correctly handles different data engine types by appending the -encrypted suffix for V2 volumes. The implementation is clean and straightforward.


144-145: Verify error handling in ResizeEncryptoDevice

The function checks if the device is open but doesn't verify if it's a V2 volume before proceeding. Consider adding validation for V2 volume support.

csi/node_server.go (3)

491-492: LGTM: Enhanced logging with data engine info

Good addition of data engine information in the log message for better debugging.


632-644: LGTM: Improved crypto device cleanup logic

The changes properly handle crypto device cleanup based on data engine type and shared access requirements.


Line range hint 825-853: Verify volume expansion support for V2 volumes

The code handles encrypted volume expansion, but we should verify if V2 volumes support this operation.

✅ Verification successful

V2 volumes support encrypted volume expansion

The implementation in csi/node_server.go is engine-agnostic and works for both V1 and V2 volumes. The code only checks if the volume is encrypted and handles the crypto operations accordingly, using the dataEngine parameter only for constructing the appropriate mapper path.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if volume expansion is supported for V2 volumes
# by looking for any restrictions or validations in the codebase.

rg "DataEngineTypeV2.*expansion" 

Length of output: 34


Script:

#!/bin/bash
# Search for V2 volume handling and expansion-related code
rg "DataEngineTypeV2" -A 5 -B 5

# Search for volume expansion validations
rg "NodeExpandVolume|ControllerExpandVolume" -A 10

# Search for data engine type checks during expansion
rg "dataEngine.*expand|expand.*dataEngine" -A 5 -B 5

Length of output: 116265

ref: longhorn/longhorn 7355

Signed-off-by: James Lu <james.lu@suse.com>
Copy link

@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

🧹 Nitpick comments (1)
csi/crypto/crypto.go (1)

Line range hint 103-117: Enhance error message clarity

While the implementation is correct, the error message could be more informative for debugging purposes.

Consider including the data engine type in the error message:

-		logrus.WithError(err).Warnf("Failed to open LUKS device %s", devicePath)
+		logrus.WithError(err).Warnf("Failed to open LUKS device %s (engine: %s)", devicePath, dataEngine)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6827312 and b37ffa7.

📒 Files selected for processing (3)
  • csi/crypto/crypto.go (4 hunks)
  • csi/node_server.go (6 hunks)
  • webhook/resources/volume/validator.go (0 hunks)
💤 Files with no reviewable changes (1)
  • webhook/resources/volume/validator.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • csi/node_server.go
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build binaries
  • GitHub Check: Summary
🔇 Additional comments (5)
csi/crypto/crypto.go (5)

13-13: LGTM! Clean addition of imports and constants

The new import and constant are well-structured and necessary for V2 engine support.

Also applies to: 18-18


124-129: LGTM! Well-structured helper function

Clean implementation that properly encapsulates the volume name logic for different engine types.


132-132: LGTM! Clean adaptation for V2 engine support

The changes maintain consistency with the rest of the implementation while properly supporting V2 volumes.

Also applies to: 139-141


Line range hint 74-156: Verify path handling security

While the implementation looks secure, let's ensure proper path handling throughout the crypto operations.

Let's check for potential path traversal vulnerabilities:

✅ Verification successful

Path handling implementation is secure

The crypto operations use proper path handling throughout:

  • All paths are constructed using path.Join
  • Fixed /dev/mapper prefix with proper validation
  • Standard library path cleaning prevents directory traversal
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for path validation and sanitization
rg -A 5 "path\.(Clean|Join|Base)" csi/
# Check for direct path concatenation
rg -A 5 "\/.*\+" csi/

Length of output: 2744


Script:

#!/bin/bash
# Check for path-related constants in crypto package
rg -A 2 "const.*[Pp]ath|var.*[Pp]ath" csi/crypto/
# Check for mapper-related constants
rg -A 2 "const.*mapper|var.*mapper" csi/crypto/

Length of output: 101


Script:

#!/bin/bash
# Get the complete crypto.go file content
cat csi/crypto/crypto.go

# Search for variable declarations and imports
rg -p "^(var|import|const)" csi/crypto/

Length of output: 7298


74-77: LGTM! Verify volume name validation

The V2 engine path construction logic is clean and consistent. The -encrypted suffix addition is properly handled.

Let's verify that volume names are properly validated upstream to prevent path traversal:

✅ Verification successful

Volume name validation is secure against path traversal

The implementation is safe because:

  • Volume names are validated using strict regex ^[a-z0-9][a-z0-9_.-]+$
  • Path construction uses path.Join with fixed prefix/suffix
  • Validation occurs in webhook before reaching the mapper
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for volume name validation in the codebase
rg -A 5 "func.*[Vv]alidate.*[Vv]olume[Nn]ame" 

Length of output: 47


Script:

#!/bin/bash
# Search for volume name patterns in CRD definitions and validation contexts
rg -g '*.yaml' -g '*.go' -A 5 'volume.*name.*pattern|volume.*name.*validation'

# Search for volume name usage in crypto context
rg -g '*.go' -A 5 'volume.*name.*=|volume.*:=|volume\s+string'

# Search for general name validation patterns
ast-grep --pattern 'func $_(volume string) $$ { $$$ }'

Length of output: 68340


Script:

#!/bin/bash
# Search for ValidateName implementation
rg -g '*.go' -A 10 'func ValidateName'

# Search for volume name validation usage in crypto context
rg -g '*.go' -B 5 -A 5 'util\.ValidateName.*volume'

Length of output: 11211

csi/crypto/crypto.go Show resolved Hide resolved
when opening and closing a luks2 format device.

ref: longhorn/longhorn 7355

Signed-off-by: James Lu <james.lu@suse.com>
Comment on lines +75 to +77
if dataEngine == string(longhorn.DataEngineTypeV2) {
return path.Join(mapperFilePathPrefix, volume+mapperV2VolumeSuffix)
}
Copy link
Member

Choose a reason for hiding this comment

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

Use if types.IsDataEngineV2(...)

func VolumeMapper(volume string) string {
func VolumeMapper(volume, dataEngine string) string {
if dataEngine == string(longhorn.DataEngineTypeV2) {
return path.Join(mapperFilePathPrefix, volume+mapperV2VolumeSuffix)
Copy link
Member

Choose a reason for hiding this comment

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

Add a comment for explaining the purpose of the suffix.

if err != nil {
logrus.WithError(err).Warnf("Failed to open LUKS device %s", devicePath)
}
return err
}

func getEncryptVolumeName(volume, dataEngine string) string {
if dataEngine == string(longhorn.DataEngineTypeV2) {
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
if dataEngine == string(longhorn.DataEngineTypeV2) {
if types.IsDataEngineV2(...)

func VolumeMapper(volume string) string {
func VolumeMapper(volume, dataEngine string) string {
if dataEngine == string(longhorn.DataEngineTypeV2) {
return path.Join(mapperFilePathPrefix, volume+mapperV2VolumeSuffix)
Copy link
Member

Choose a reason for hiding this comment

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

Reuse getEncryptVolumeName()

Suggested change
return path.Join(mapperFilePathPrefix, volume+mapperV2VolumeSuffix)
return path.Join(mapperFilePathPrefix, getEncryptVolumeName(volume))

Comment on lines +632 to +644
dataEngine := string(longhorn.DataEngineTypeV1)
if volume != nil {
dataEngine = volume.DataEngine
}
sharedAccess := requiresSharedAccess(volume, nil)
cleanupCryptoDevice := !sharedAccess || (sharedAccess && volume.Migratable)
if cleanupCryptoDevice {
cryptoDevice := crypto.VolumeMapper(volumeID, dataEngine)
if isOpen, err := crypto.IsDeviceOpen(cryptoDevice); err != nil {
return nil, status.Error(codes.Internal, err.Error())
} else if isOpen {
log.Infof("Volume %s closing active crypto device %s", volumeID, cryptoDevice)
if err := crypto.CloseVolume(volumeID, volume.DataEngine); err != nil {
Copy link
Member

Choose a reason for hiding this comment

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

It doesn't handle volume == nil case

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