-
Notifications
You must be signed in to change notification settings - Fork 1
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
Add sign method to handle signing requests in the API endpoint #13
Conversation
WalkthroughThe changes introduce a new case in the POST route handler of the Fastify server located in Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Server
participant Wallets
Client->>Server: POST /sign (keyId, digest)
Server->>Wallets: ecsign(keyId, buffer)
Wallets-->>Server: signature
Server-->>Client: response(signature)
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 (
|
875da99
to
d191b73
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: 1
🧹 Outside diff range and nitpick comments (2)
src/server.ts (2)
58-60
: Document the signing endpointAdd JSDoc comments to document the new signing functionality, including:
- Expected input format
- Response format
- Error scenarios
+ /** + * Signs a 32-byte digest using KMS + * @param params[0] - 32-byte hex string with 0x prefix + * @returns Object containing hex-encoded signature with 0x prefix + * @throws 400 if digest format is invalid + * @throws 500 if KMS signing fails + */ case 'sign':🧰 Tools
🪛 Biome (1.9.4)
[error] 59-59: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
58-60
: Consider adding rate limiting for signing operationsThe signing endpoint should be protected against potential abuse through rate limiting, especially since it involves KMS operations which may have associated costs.
Would you like me to provide an implementation using a rate limiting middleware?
🧰 Tools
🪛 Biome (1.9.4)
[error] 59-59: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (2)
.github/workflows/docker-publish.yml
(1 hunks)src/server.ts
(1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/server.ts
[error] 59-59: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
🔇 Additional comments (2)
.github/workflows/docker-publish.yml (1)
61-61
: Verify Trivy version compatibility and features
The Trivy scanner version update from 0.21.0 to 0.28.0 is significant. While keeping security tools updated is good practice, we should verify compatibility.
✅ Verification successful
Based on the release notes between v0.21.0 and v0.28.0, I can generate the final response:
Trivy version update is safe to proceed
The update from v0.21.0 to v0.28.0 brings several improvements and bug fixes:
- No breaking changes that affect the GitHub Action usage
- Added features: Kubernetes scanning, secret scanning, SPDX support
- Multiple bug fixes and security improvements
- Enhanced reporting capabilities
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check release notes and breaking changes between versions
gh api repos/aquasecurity/trivy/releases --paginate | \
jq -r '.[] | select(.tag_name >= "v0.21.0" and .tag_name <= "v0.28.0") | "\(.tag_name)\n\(.body)"'
Length of output: 19300
src/server.ts (1)
58-60
: Verify KMS permissions and key usage
Ensure that:
- The KMS key has appropriate signing permissions
- The key algorithm is suitable for the expected digest signing operation
✅ Verification successful
Based on the analysis of the codebase, I can now provide a comprehensive response regarding the KMS permissions and key usage verification:
KMS implementation confirms appropriate signing capabilities
The codebase shows a well-structured GCP KMS implementation that:
- Uses asymmetric signing with SHA-256 digest
- Implements integrity checks via CRC32C
- Properly handles key versioning and access paths
- Includes error handling for key permissions and signing operations
Key points verified:
- The KMS key is configured for asymmetric signing operations through GCP KMS
- The implementation includes proper digest signing with SHA-256 algorithm
- The code includes transit integrity verification for both request and response
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for KMS key configuration and permissions
rg -A 5 "KMSProviderGCP|keyId" --type typescript
Length of output: 85
Script:
#!/bin/bash
# Search for KMS related configuration and key usage patterns
rg -A 5 "KMS|keyId|signDigest" --type ts
Length of output: 31978
Script:
#!/bin/bash
# Find all TypeScript files that might contain KMS configuration
fd -e ts -e tsx -x cat {} | rg -A 5 "KMS|keyId|signDigest"
Length of output: 18170
Script:
#!/bin/bash
# Look for KMS provider implementation
ast-grep --pattern 'class $_ implements $_Provider {
$$$
signDigest($_, $_) {
$$$
}
$$$
}'
Length of output: 104
🧰 Tools
🪛 Biome (1.9.4)
[error] 59-59: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
src/server.ts
Outdated
case 'sign': | ||
const signature = await kmsProvider.signDigest(keyId, Buffer.from(params[0], 'hex')); | ||
return reply.code(200).send({result: signature.toString('hex')}); |
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.
Add input validation and error handling
The new signing endpoint needs additional safety measures:
- Missing input validation for the digest parameter
- No error handling for KMS operations
- Switch case declaration needs block scope
Apply this diff to improve the implementation:
case 'sign':
+ {
+ if (!params || !Array.isArray(params) || params.length === 0) {
+ reply.code(400).send({ error: 'Invalid parameters' });
+ return;
+ }
+ const digest = params[0];
+ if (typeof digest !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(digest)) {
+ reply.code(400).send({ error: 'Invalid digest format. Expected 32-byte hex string with 0x prefix' });
+ return;
+ }
+ try {
+ const digestBuffer = Buffer.from(digest.slice(2), 'hex');
+ const signature = await kmsProvider.signDigest(keyId, digestBuffer);
+ return reply.code(200).send({ result: '0x' + signature.toString('hex') });
+ } catch (error) {
+ console.error('KMS signing error:', error);
+ reply.code(500).send({ error: 'Failed to sign digest' });
+ return;
+ }
+ }
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
case 'sign': | |
const signature = await kmsProvider.signDigest(keyId, Buffer.from(params[0], 'hex')); | |
return reply.code(200).send({result: signature.toString('hex')}); | |
case 'sign': | |
{ | |
if (!params || !Array.isArray(params) || params.length === 0) { | |
reply.code(400).send({ error: 'Invalid parameters' }); | |
return; | |
} | |
const digest = params[0]; | |
if (typeof digest !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(digest)) { | |
reply.code(400).send({ error: 'Invalid digest format. Expected 32-byte hex string with 0x prefix' }); | |
return; | |
} | |
try { | |
const digestBuffer = Buffer.from(digest.slice(2), 'hex'); | |
const signature = await kmsProvider.signDigest(keyId, digestBuffer); | |
return reply.code(200).send({ result: '0x' + signature.toString('hex') }); | |
} catch (error) { | |
console.error('KMS signing error:', error); | |
reply.code(500).send({ error: 'Failed to sign digest' }); | |
return; | |
} | |
} |
🧰 Tools
🪛 Biome (1.9.4)
[error] 59-59: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
d191b73
to
951be62
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 and nitpick comments (1)
src/server.ts (1)
58-60
: Consider adding security middlewareFor a security-critical signing service, consider implementing:
- Rate limiting to prevent DoS attacks
- Authentication/authorization middleware to control access
- Request size limits to prevent memory exhaustion attacks
I can help implement these security measures if needed. Would you like me to provide example implementations?
🧰 Tools
🪛 Biome (1.9.4)
[error] 59-59: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
src/server.ts
(1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/server.ts
[error] 59-59: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
🔇 Additional comments (1)
src/server.ts (1)
58-60
:
Critical: Add security measures to the sign endpoint
The current implementation has several security concerns:
- No input validation for the digest parameter
- Missing error handling for KMS operations
- No audit logging for security-critical operations
- Switch case needs block scope (as flagged by static analysis)
Apply this enhanced diff that includes audit logging:
case 'sign':
+ {
+ if (!params || !Array.isArray(params) || params.length === 0) {
+ app.log.warn('Invalid parameters received for sign operation');
+ reply.code(400).send({ error: 'Invalid parameters' });
+ return;
+ }
+ const digest = params[0];
+ if (typeof digest !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(digest)) {
+ app.log.warn(`Invalid digest format received: ${digest}`);
+ reply.code(400).send({ error: 'Invalid digest format. Expected 32-byte hex string with 0x prefix' });
+ return;
+ }
+ try {
+ app.log.info(`Processing sign request for digest: ${digest}`);
+ const digestBuffer = Buffer.from(digest.slice(2), 'hex');
+ const signature = await kmsProvider.signDigest(keyId, digestBuffer);
+ const result = '0x' + signature.toString('hex');
+ app.log.info('Signature generated successfully');
+ return reply.code(200).send({ result });
+ } catch (error) {
+ app.log.error('KMS signing error:', error);
+ reply.code(500).send({ error: 'Failed to sign digest' });
+ return;
+ }
+ }
Let's verify the KMS provider's error handling capabilities:
#!/bin/bash
# Description: Check KMS provider's error handling implementation
ast-grep --pattern 'class KMSProviderGCP {
$$$
signDigest($_, $_) {
$$$
}
$$$
}'
🧰 Tools
🪛 Biome (1.9.4)
[error] 59-59: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
951be62
to
cc8ff64
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: 1
🧹 Outside diff range and nitpick comments (1)
src/server.ts (1)
58-60
: Consider additional security measuresThe new signing endpoint could benefit from additional security measures:
- Consider implementing a whitelist of allowed digest prefixes or patterns to prevent signing arbitrary data
- Add rate limiting to prevent potential abuse of the signing service
Example rate limiting implementation using
fastify-rate-limit
:import rateLimit from '@fastify/rate-limit' // Add at the top level of your application app.register(rateLimit, { max: 100, timeWindow: '1 minute' })Would you like me to provide a more detailed implementation of these security measures?
🧰 Tools
🪛 Biome (1.9.4)
[error] 59-59: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
src/server.ts
(1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/server.ts
[error] 59-59: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
🔇 Additional comments (1)
src/server.ts (1)
58-60
:
Add input validation, error handling, and documentation
The current implementation needs several improvements for security and reliability:
- Missing input validation for parameters
- No error handling for KMS operations
- Inconsistent response format (missing '0x' prefix)
- Switch case needs block scope
- Missing documentation
Apply this diff to improve the implementation:
case 'sign':
+ {
+ // Expects a 32-byte hex string with '0x' prefix as the digest parameter
+ if (!params || !Array.isArray(params) || params.length === 0) {
+ reply.code(400).send({ error: 'Invalid parameters' });
+ return;
+ }
+ const digest = params[0];
+ if (typeof digest !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(digest)) {
+ reply.code(400).send({ error: 'Invalid digest format. Expected 32-byte hex string with 0x prefix' });
+ return;
+ }
+ try {
+ const digestBuffer = Buffer.from(digest.slice(2), 'hex');
+ const signature = await kmsProvider.signDigest(keyId, digestBuffer);
+ return reply.code(200).send({ result: `0x${signature.toString('hex')}` });
+ } catch (error) {
+ console.error('KMS signing error:', error);
+ reply.code(500).send({ error: 'Failed to sign digest' });
+ return;
+ }
+ }
🧰 Tools
🪛 Biome (1.9.4)
[error] 59-59: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
src/server.ts
Outdated
case 'sign': | ||
const signature = await kmsProvider.signDigest(keyId, Buffer.from(params[0].slice(2), 'hex')); | ||
return reply.code(200).send({result: signature.toString('hex')}); |
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.
💡 Codebase verification
Input validation needed for the sign endpoint
The verification reveals that while other endpoints have proper input validation (e.g., eth_signTransaction
uses TransactionArgsSchema.safeParse
), the sign
endpoint lacks similar validation for params[0]
. The implementation should:
- Validate that
params[0]
is a valid hex string - Verify the digest length matches the expected size
- Include error handling for invalid inputs
Current security measures in the codebase:
- Request body validation for transaction signing
- Gas price limits and validation
- Error handling with appropriate HTTP status codes
🔗 Analysis chain
Verify the implementation patterns
Let's verify the consistency of the implementation with the rest of the codebase.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for similar signing implementations and usage patterns
# Look for similar signing implementations
echo "Checking for similar signing implementations..."
rg -A 5 "signDigest|sign.*digest"
# Look for potential usage patterns
echo "Checking for potential usage patterns..."
rg -A 5 "POST.*sign|sign.*endpoint"
# Check for security-related patterns
echo "Checking for security measures in other endpoints..."
rg -A 5 "rate.*limit|whitelist|validation"
Length of output: 7506
Script:
#!/bin/bash
# Let's verify the security measures and input validation in the server implementation
# Check the server implementation for request validation and security measures
echo "Checking server implementation..."
rg -A 10 "fastify.post|app.post" src/server.ts
# Check for input parameter validation
echo "Checking parameter validation..."
rg -A 10 "params\[0\]|keyId" src/server.ts
# Check for error handling patterns
echo "Checking error handling..."
rg -A 5 "catch|throw|error:" src/server.ts
Length of output: 3361
🧰 Tools
🪛 Biome (1.9.4)
[error] 59-59: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
cc8ff64
to
50ca469
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: 1
🧹 Outside diff range and nitpick comments (1)
src/server.ts (1)
63-66
: Consider adding rate limiting and audit loggingThe new signing endpoint should have similar security measures as the transaction signing endpoint:
- Rate limiting to prevent abuse
- Audit logging for security tracking
- Consider adding similar fee/gas checks if applicable to your use case
Consider implementing:
- A rate limiter middleware (similar to the transaction endpoint)
- Structured logging for audit trails
- Additional security measures based on your threat model
Would you like me to provide an example implementation of these security measures?
🧰 Tools
🪛 Biome (1.9.4)
[error] 64-64: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 65-65: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
src/server.ts
(2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/server.ts
[error] 64-64: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 65-65: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
🔇 Additional comments (1)
src/server.ts (1)
63-66
:
Critical: Add input validation and error handling for signing endpoint
The current implementation has several security concerns:
- No validation of the input digest
- Missing error handling for KMS operations
- No validation of signature components
- Switch case needs block scope
Apply this diff to improve security:
case 'sign':
+ {
+ if (!params || !Array.isArray(params) || params.length === 0) {
+ reply.code(400).send({ error: 'Invalid parameters' });
+ return;
+ }
+ const digest = params[0];
+ if (typeof digest !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(digest)) {
+ reply.code(400).send({ error: 'Invalid digest format. Expected 32-byte hex string with 0x prefix' });
+ return;
+ }
+ try {
+ const signature = await wallets.ecsign({ keyId }, Buffer.from(digest.slice(2), 'hex'), 1);
+
+ // Validate signature components
+ if (!signature.r || !signature.s || signature.v === undefined) {
+ throw new Error('Invalid signature components');
+ }
+
+ const res = Buffer.concat([
+ signature.r,
+ signature.s,
+ bigintToBuffer(signature.v)
+ ]).toString('hex');
+
+ return reply.code(200).send({ result: res });
+ } catch (error) {
+ console.error('Signing error:', error);
+ reply.code(500).send({ error: 'Failed to sign digest' });
+ return;
+ }
+ }
Let's verify the security measures in similar endpoints:
✅ Verification successful
Critical: Add input validation and error handling for signing endpoint
The codebase analysis confirms the security concerns. Other endpoints like eth_signTransaction
implement proper validation using Zod schemas and error handling, but the sign
endpoint lacks these security measures. The suggested changes in the review are valid and align with the established patterns in the codebase:
- The
eth_signTransaction
endpoint demonstrates proper validation usingTransactionArgsSchema.safeParse()
with error handling - Other endpoints use proper error codes (400 for invalid requests)
- The
sign
case lacks both validation and error handling, unlike other endpoints - The switch case indeed needs block scope to match the codebase style
The original review comment and its suggested fixes are accurate and should be implemented to maintain consistent security practices across the codebase.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for similar signing implementations and security patterns
# Look for input validation patterns
echo "Checking input validation patterns..."
rg -A 5 "safeParse|validate|check" src/
# Look for error handling patterns in signing operations
echo "Checking error handling in signing operations..."
rg -A 5 "catch.*sign|error.*sign" src/
Length of output: 3165
Script:
#!/bin/bash
# Let's analyze the codebase more thoroughly
# Check for signing implementations
echo "Checking signing implementations..."
ast-grep --pattern 'case $_ : $$$sign$$$'
# Look for switch case patterns
echo "Checking switch case patterns..."
rg -A 5 "switch.*case.*sign" src/
# Check for error handling in the server file
echo "Checking error handling patterns in server..."
rg -A 10 "try.*catch" src/server.ts
# Look for input validation schemas
echo "Looking for validation schemas..."
rg "Schema" src/
Length of output: 1319
Script:
#!/bin/bash
# Let's examine the types and validation patterns more closely
# Check the types file for validation schemas
echo "Checking types.ts content..."
cat src/types.ts
# Look for other switch cases in server.ts to compare patterns
echo "Checking server.ts switch patterns..."
rg -A 10 "switch.*\{" src/server.ts
# Look for existing error handling in server.ts
echo "Checking existing error handling..."
rg -B 5 -A 5 "reply\.code\(4[0-9]{2}\)" src/server.ts
Length of output: 2849
🧰 Tools
🪛 Biome (1.9.4)
[error] 64-64: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 65-65: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
Summary by CodeRabbit
New Features
Bug Fixes