-
Notifications
You must be signed in to change notification settings - Fork 13
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
feature(keys): support der and sec1 as input formats separately #187
Conversation
WalkthroughThis pull request enhances cryptographic key handling in the Changes
Sequence DiagramsequenceDiagram
participant Key as Verifying/Signing Key
participant DER as DER Serialization
participant Algo as CryptoAlgorithm
Key->>DER: to_der()
DER-->>Key: Serialized Bytes
DER->>Algo: from_algorithm_and_der()
Algo-->>Key: Reconstructed Key
Possibly related PRs
Suggested reviewers
Poem
Finishing Touches
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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
🔭 Outside diff range comments (1)
crates/keys/src/lib.rs (1)
Add test coverage for DER and SEC1 format handling
The codebase has implemented DER and SEC1 format support but lacks test coverage:
VerifyingKey::from_algorithm_and_bytes_der()
supports DER format for Secp256r1 keysSignature::from_algorithm_and_bytes_der()
supports DER format for both Secp256k1 and Secp256r1 signaturesVerifyingKey
supports SEC1 format for Secp256r1 keysTest cases needed:
- Parsing valid DER-formatted Secp256r1 verifying keys
- Parsing valid DER-formatted Secp256k1 and Secp256r1 signatures
- Parsing valid SEC1-formatted Secp256r1 verifying keys
- Error handling for unsupported DER formats (Ed25519 keys/signatures)
- Error handling for invalid DER/SEC1 inputs
🔗 Analysis chain
Line range hint
11-128
: Add test coverage for DER and SEC1 format handling.While the existing tests thoroughly cover the base functionality, they don't verify the new DER and SEC1 format support mentioned in the PR objectives. Consider adding:
- Tests for parsing DER-formatted keys
- Tests for parsing SEC1-formatted keys
- Tests for invalid DER/SEC1 inputs
Let's check if there are any existing DER/SEC1 format tests elsewhere:
Would you like me to help draft the additional test cases?
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for DER/SEC1 related tests in the codebase rg -l "test.*der|test.*sec1|from_.*der|from_.*sec1" --type rustLength of output: 154
Script:
#!/bin/bash # Let's check the content of these files to see if they contain DER/SEC1 format tests echo "=== verifying_keys.rs ===" rg -A 5 "test.*der|test.*sec1|from_.*der|from_.*sec1" crates/keys/src/verifying_keys.rs echo -e "\n=== signatures.rs ===" rg -A 5 "test.*der|test.*sec1|from_.*der|from_.*sec1" crates/keys/src/signatures.rsLength of output: 1608
🧹 Nitpick comments (1)
crates/keys/src/signatures.rs (1)
32-44
: Enhanced from_algorithm_and_bytes with CryptoAlgorithm
By replacing string checking with a match over the CryptoAlgorithm variants, the code becomes more robust. Just verify that all call sites have been updated and always pass the correct format (DER vs. SEC1).
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
crates/keys/src/algorithm.rs
(1 hunks)crates/keys/src/lib.rs
(1 hunks)crates/keys/src/signatures.rs
(3 hunks)crates/keys/src/signing_keys.rs
(4 hunks)crates/keys/src/verifying_keys.rs
(5 hunks)
🔇 Additional comments (24)
crates/keys/src/signatures.rs (5)
10-11
: Use of CryptoAlgorithm import is consistent with the PR’s goals
Importing and using CryptoAlgorithm instead of strings improves type safety and avoids stray string comparisons.
26-27
: Switched from DER to compact and raw byte serialization
Switching Secp256k1 to compact serialization via “serialize_compact()” and using “to_vec()” for Secp256r1 indicates the code now clearly differentiates serialization formats.
46-52
: New from_algorithm_and_bytes_der method
Great separation of concerns between the standard from_algorithm_and_bytes method and this new DER-specific approach. This avoids confusion about which input format is expected.
58-63
: Returning CryptoAlgorithm instead of &str
Replacing string-based returns with the enum formalizes the algorithm identification. The fallback to Ed25519 in the Placeholder variant may need a separate strategy if it’s truly a “placeholder” or an error case.
72-73
: Parsing algorithm from CryptoPayload
Ensures CryptoPayload is parsed into the strongly typed CryptoAlgorithm. Confirm that errors from parse() are properly handled or surfaced upstream.
crates/keys/src/verifying_keys.rs (8)
3-8
: Imports for p256 ECDSA usage
Adding and restructuring these imports signals the shift to more robust handling for p256 ECDSA.
22-22
: Introduction of CryptoAlgorithm import
Aligns with the PR’s approach to unify algorithm handling across keys, signatures, and verifying keys.
69-77
: from_algorithm_and_bytes with CryptoAlgorithm
Accepting the enum and matching on algorithm variants significantly reduces the risk of invalid string inputs.
83-91
: New from_algorithm_and_bytes_der method
This method clarifies how DER-encoded keys are handled, but it explicitly bails for Ed25519 and Secp256k1, indicating partial coverage. If needed in the future, you can add those as well.
93-97
: algorithm method returning CryptoAlgorithm
Further unifies the approach of using a single typed enum to identify each key type.
128-128
: Verifying Secp256r1 signatures
Uses the updated verify_digest flow. Good approach for verifying ECDSA messages with the p256 crate.
139-139
: Parsing from CryptoPayload
Successfully converts from the algorithm string to the new enum. This is consistent with the approach taken in Signatures and SigningKey.
144-147
: Algorithm and bytes in CryptoPayload
Returning the algorithm via “to_string()” is consistent with the Display implementation from CryptoAlgorithm, ensuring a lowercase output.
crates/keys/src/algorithm.rs (4)
1-2
: Imports for Display and FromStr
Confirmed that these traits allow for a safe, typed approach to parse and represent the chosen algorithm.
3-9
: Definition of the new enum CryptoAlgorithm
Excellent improvement for typed cryptographic algorithms. This code lumps Ed25519, Secp256k1, and Secp256r1 under a single, strongly typed umbrella.
10-21
: Implementing FromStr
Lowercase matching ensures broad user input compatibility. Provide mild caution on potential input changes (like uppercase, etc.). The error message is descriptive for invalid inputs.
23-31
: Implementing Display
A straightforward mapping for the enum variants. This is consistent with the new “algorithm().to_string()” usage.
crates/keys/src/signing_keys.rs (5)
1-1
: Importing anyhow::Result
Ensures consistent error handling, matching the approach used in other crypto modules.
11-11
: Importing CryptoAlgorithm
Required to support the strongly typed approach for algorithm selection.
46-54
: from_algorithm_and_bytes using CryptoAlgorithm
Replacing string references with an enum match removes ambiguity and the possibility of typos. This shift is a central goal of the PR.
60-64
: algorithm method returning CryptoAlgorithm
Refining the method’s return type to align with other modules, ensuring consistent usage of the enum.
102-102
: Parsing from CryptoPayload
Confirms the usage is analogous to the approach in signatures and verifying keys. This standardization is beneficial.
crates/keys/src/lib.rs (2)
1-9
: LGTM! Module organization follows best practices.
The addition of the algorithm
module and its public export is well-structured and follows Rust module organization best practices.
Line range hint 1-128
: Verify backward compatibility and security considerations.
Please ensure:
- The new format support maintains backward compatibility with existing key formats
- The cryptographic implementations follow security best practices, particularly for DER/SEC1 parsing
Let's check for potential security considerations:
✅ Verification successful
Let me gather more specific information about the cryptographic implementations and format handling.
Based on the comprehensive analysis of the implementation, I can now provide a final response:
Verification confirms robust key format handling and security practices.
The implementation demonstrates:
- Proper format handling with explicit algorithm checks and byte validation for all supported key types (Ed25519, Secp256k1, Secp256r1)
- Comprehensive error handling using Result types for all parsing operations
- Proper serialization methods using standard formats (SEC1 for secp256r1, compressed format for secp256k1)
- Extensive test coverage validating format compatibility and key reconstruction
- Safe cryptographic implementations using well-established libraries (ed25519-consensus, secp256k1, p256)
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Look for existing security-related comments or known issues
rg -i "security|vulnerability|cve|unsafe" --type rust
# Check for any TODOs or FIXMEs related to security
rg -i "todo.*secur|fixme.*secur" --type rust
# Look for existing DER/SEC1 parsing implementations
ast-grep --pattern 'fn $_(der|sec1)$$$'
Length of output: 383
Script:
#!/bin/bash
# Check the algorithm implementations and key format handling
rg -A 10 "impl.*SigningKey|impl.*VerifyingKey|impl.*Signature" --type rust
# Look for any error handling related to key parsing
rg -A 5 "Error|unwrap|expect" crates/keys/src/
# Check for any format conversion or parsing functions
ast-grep --pattern 'fn from_$_($$$) {
$$$
}'
Length of output: 21181
c13b186
to
a594f50
Compare
a594f50
to
0fc3837
Compare
There was a problem hiding this 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 (2)
crates/keys/src/signatures.rs (2)
Line range hint
45-51
: Improve Error Handling and Messages for Unsupported FormatsThe new method
from_algorithm_and_bytes_der
usesbail!
with a simple error message forEd25519
. Providing more informative error messages can improve usability.Consider enhancing the error message for
Ed25519
to guide users:- CryptoAlgorithm::Ed25519 => bail!("Ed25519 sig from DER format is not implemented"), + CryptoAlgorithm::Ed25519 => bail!("Ed25519 signatures do not support DER format. Please use the raw signature format."),
Line range hint
45-51
: Reduce Code Duplication in Signature Parsing MethodsBoth
from_algorithm_and_bytes
andfrom_algorithm_and_bytes_der
have similar match arms with slight variations. This duplication can be refactored to improve code maintainability.Consider refactoring by introducing a helper function or parameterizing the deserialization method:
fn deserialize_signature<F>( algorithm: CryptoAlgorithm, bytes: &[u8], deserializer: F, ) -> Result<Self> where F: Fn(&[u8]) -> Result<Self>, { match algorithm { CryptoAlgorithm::Ed25519 => deserializer(bytes), CryptoAlgorithm::Secp256k1 => deserializer(bytes), CryptoAlgorithm::Secp256r1 => deserializer(bytes), } }Then,
from_algorithm_and_bytes
andfrom_algorithm_and_bytes_der
can calldeserialize_signature
with appropriate deserializers.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
crates/keys/src/signatures.rs
(3 hunks)crates/keys/src/verifying_keys.rs
(3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- crates/keys/src/verifying_keys.rs
⏰ Context from checks skipped due to timeout of 90000ms (3)
- GitHub Check: integration-test
- GitHub Check: unused dependencies
- GitHub Check: unit-test
🔇 Additional comments (2)
crates/keys/src/signatures.rs (2)
25-26
:⚠️ Potential issuePotential Breaking Change in Signature Serialization
The serialization method for
Secp256k1Signature
andSecp256r1Signature
into_bytes
has been changed to use compact serialization (serialize_compact()
) and direct vector conversion (to_vec()
), respectively. This alters the byte representation of signatures, which may affect interoperability with external systems or backward compatibility.Please verify if this change in serialization format is intentional and ensure that all dependent systems or interfaces handle the new formats correctly.
36-43
: 🛠️ Refactor suggestionEnsure Consistency Between Serialization and Deserialization
In
from_algorithm_and_bytes
, signatures are deserialized usingfrom_compact
forSecp256k1Signature
andfrom_slice
forSecp256r1Signature
. Ensure these methods are consistent with the serialization methods used into_bytes
to prevent deserialization errors.Consider adding tests to confirm that a signature serialized with
to_bytes
can be successfully deserialized withfrom_algorithm_and_bytes
.
0fc3837
to
9ff3eb4
Compare
There was a problem hiding this 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 (1)
crates/keys/src/signatures.rs (1)
Line range hint
55-63
: Add documentation for the DER format method.Consider adding documentation to explain:
- The purpose of DER format support
- Which algorithms support DER format
- Expected input format for each supported algorithm
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
crates/keys/src/lib.rs
(2 hunks)crates/keys/src/signatures.rs
(2 hunks)crates/keys/src/verifying_keys.rs
(4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
- GitHub Check: unused dependencies
- GitHub Check: unit-test
- GitHub Check: integration-test
🔇 Additional comments (9)
crates/keys/src/signatures.rs (3)
31-38
: LGTM! Clean DER format implementation.The DER format serialization is well-implemented with proper error handling for unsupported Ed25519 format.
46-53
: LGTM! Consistent with serialization changes.The deserialization changes align well with the corresponding serialization changes in
to_bytes
.
1-1
: LGTM! Verify backward compatibility.The serialization changes for Secp256k1 (using compact format) and Secp256r1 look good. However, let's verify that existing consumers can handle these formats.
Also applies to: 25-29
✅ Verification successful
Serialization changes are safe and backward compatible
The changes are well-tested with roundtrip verification in the test suite, and all consumers properly handle the serialization formats through appropriate abstractions.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for direct usage of to_bytes() to ensure consumers can handle the new formats rg -A 3 "to_bytes\(\)" --type rustLength of output: 13195
crates/keys/src/verifying_keys.rs (4)
3-9
: LGTM! Appropriate imports for DER support.The addition of PKCS8 traits is appropriate for DER encoding/decoding support.
66-73
: LGTM! Well-structured DER implementation.The DER format serialization is properly implemented for Secp256r1 with appropriate error handling for unsupported algorithms.
89-97
: Add documentation for the DER format method.Consider adding documentation to explain:
- The purpose of DER format support
- Which algorithms support DER format
- Expected input format
134-134
: LGTM! Good optimization.Removing the unnecessary DER conversion for Secp256r1 signature verification is a good optimization.
crates/keys/src/lib.rs (2)
47-58
: LGTM! Good test coverage for DER format.The test properly verifies DER encoding/decoding for Secp256r1 verifying keys with appropriate documentation about unsupported algorithms.
116-135
: LGTM! Comprehensive test coverage.The test thoroughly verifies DER encoding/decoding for both Secp256k1 and Secp256r1 signatures.
9ff3eb4
to
c382972
Compare
There was a problem hiding this 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
🔭 Outside diff range comments (1)
crates/keys/src/signatures.rs (1)
Additional error case tests needed for DER parsing
While the happy path is well tested, there's insufficient coverage for error cases:
- No tests for invalid/malformed DER data
- No boundary tests for DER parsing
- No explicit tests verifying Ed25519 DER rejection
🔗 Analysis chain
Line range hint
54-62
: Verify test coverage for error cases.Ensure there are tests covering:
- Attempting to parse invalid DER data
- Error cases for Ed25519
- Edge cases for both Secp256k1 and Secp256r1
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check test coverage for DER parsing error cases rg -A 5 "test.*der.*error|test.*der.*invalid" crates/keys/src/tests.rsLength of output: 72
Script:
#!/bin/bash # Find all test files in crates/keys echo "=== Test files ===" fd "test.*\.rs$" crates/keys/ # Search for signature-related tests echo -e "\n=== Signature tests ===" rg -B2 -A5 "fn test.*sign|#\[test\].*\n.*sign" crates/keys/ # Search for from_algorithm tests echo -e "\n=== Algorithm conversion tests ===" rg -B2 -A5 "fn test.*algorithm|#\[test\].*\n.*algorithm" crates/keys/Length of output: 769
Script:
#!/bin/bash # Display test file contents echo "=== Test file contents ===" cat crates/keys/src/tests.rs # Search for signature tests with simpler patterns echo -e "\n=== Signature and DER tests ===" rg "test.*signature|test.*der|from_algorithm" crates/keys/src/tests.rsLength of output: 7857
🧹 Nitpick comments (5)
crates/keys/src/verifying_keys.rs (2)
66-73
: Add documentation explaining algorithm support.While the implementation is correct, consider adding documentation that explains:
- Why DER format is only supported for Secp256r1
- Whether Ed25519 and Secp256k1 support will be added in the future
- Any relevant specifications or standards that influenced this decision
89-97
: Enhance error messages for better debugging.Consider making the error messages more informative by explaining why the format is not implemented or suggesting alternative formats. For example:
- CryptoAlgorithm::Ed25519 => bail!("Ed25519 vk from DER format is not implemented"), + CryptoAlgorithm::Ed25519 => bail!("Ed25519 keys do not support DER format. Use from_algorithm_and_bytes instead."),crates/keys/src/signatures.rs (1)
24-28
: Document the serialization formats.Consider adding documentation comments explaining:
- What format is used for each algorithm (compact, DER, etc.)
- Any size or format constraints that callers should be aware of
crates/keys/src/tests.rs (2)
37-48
: Add negative test cases for DER parsing.Consider adding test cases for:
- Attempting to parse Ed25519 keys in DER format (should fail)
- Attempting to parse Secp256k1 keys in DER format (should fail)
- Attempting to parse invalid DER data
106-125
: Add error case tests for DER signatures.The happy path is well tested, but consider adding test cases for:
- Attempting to parse Ed25519 signatures in DER format (should fail)
- Attempting to parse malformed DER data
- Attempting to parse DER data with incorrect algorithm
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
crates/keys/src/signatures.rs
(2 hunks)crates/keys/src/tests.rs
(2 hunks)crates/keys/src/verifying_keys.rs
(4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
- GitHub Check: unused dependencies
- GitHub Check: integration-test
- GitHub Check: unit-test
- GitHub Check: build-and-push-image
🔇 Additional comments (3)
crates/keys/src/verifying_keys.rs (2)
3-9
: LGTM! Clean import organization.The addition of
pkcs8
traits and reorganization of imports improves code readability while providing the necessary functionality for DER encoding/decoding.
134-134
: LGTM! Simplified signature verification.Good optimization by removing the unnecessary DER conversion and using verify_digest directly.
crates/keys/src/signatures.rs (1)
30-37
: Review DER format support consistency.There's an inconsistency in DER format support between
VerifyingKey
andSignature
:
VerifyingKey
only supports DER for Secp256r1Signature
supports DER for both Secp256k1 and Secp256r1This inconsistency should either be documented or aligned.
Summary by CodeRabbit
New Features
Tests
Bug Fixes