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

Send enrollment key as JWK #34

Merged
merged 1 commit into from
Dec 17, 2024
Merged

Send enrollment key as JWK #34

merged 1 commit into from
Dec 17, 2024

Conversation

jschlyter
Copy link
Member

@jschlyter jschlyter commented Dec 17, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new PrivateSymmetric class for handling JSON Web Keys.
    • Enhanced the create_node endpoint to return a structured NodeBootstrapInformation object with a key attribute.
  • Bug Fixes

    • Updated tests to reflect changes in the response structure for node creation and key handling.
    • Refined handling of HMAC keys in tests to ensure consistency and correctness.
  • Chores

    • Minor adjustments to logging and error handling during the enrollment process.

@jschlyter jschlyter marked this pull request as ready for review December 17, 2024 15:16
@jschlyter jschlyter requested a review from a team as a code owner December 17, 2024 15:16
Copy link
Contributor

coderabbitai bot commented Dec 17, 2024

Walkthrough

The pull request introduces significant changes to the node enrollment process across multiple files in the nodeman project. The primary focus is on refactoring how node enrollment secrets are handled, moving from a raw secret to a more structured JSON Web Key (JWK) approach. The changes involve modifying the client.py, jose.py, models.py, and nodes.py files to support a new PrivateSymmetric key type and update the node bootstrap information structure. The modifications ensure a more secure and standardized method of generating and managing node enrollment keys.

Changes

File Changes
nodeman/client.py - Updated command_create to log response in debug mode
- Modified return to use key instead of secret in NodeBootstrapInformation
nodeman/jose.py - Added new PrivateSymmetric class for private symmetric keys
- Defined with kty, k, and optional alg attributes
nodeman/models.py - Replaced secret with key: PrivateSymmetric in NodeBootstrapInformation
- Imported PrivateSymmetric from .jose
nodeman/nodes.py - Generate node enrollment key using JWK.generate with "HS256" algorithm
- Updated create_node to return NodeBootstrapInformation with key
- Added response_model_exclude_none=True to endpoint decorator
tests/test_api.py - Updated secret retrieval from create_response["secret"] to create_response["key"]["k"]
- Modified HMAC key creation to use full key object

Possibly related issues

  • dnstapir/nodeman#33: This issue directly aligns with the PR's objective to send enrollment secret as a JWK, making it highly likely to be resolved by these changes.

Sequence Diagram

sequenceDiagram
    participant Client
    participant NodeManager
    participant Database

    Client->>NodeManager: Request Node Creation
    NodeManager->>NodeManager: Generate HS256 Enrollment Key
    NodeManager->>Database: Store Node Information
    NodeManager-->>Client: Return NodeBootstrapInformation with Key
    Client->>NodeManager: Enroll Node using Key
Loading

Poem

🐰 A Rabbit's Ode to Key Evolution 🔑

From secrets raw to JWK so bright,
Our enrollment dance takes graceful flight
HS256 now leads the way
With symmetric keys in grand display
Security hops with playful might!


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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

Copy link
Contributor

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

🧹 Nitpick comments (2)
nodeman/nodes.py (1)

77-77: Consider storing the complete JWK

Currently only storing the key component (k) might bypass algorithm enforcement during verification. Consider storing the complete JWK:

-    TapirNodeSecret(name=node.name, secret=node_enrollment_key.k).save()
+    TapirNodeSecret(name=node.name, secret=node_enrollment_key.export(private_key=True)).save()

Then update the verification code to reconstruct the complete JWK with the correct algorithm:

-    hmac_key = JWK(kty="oct", k=node_secret.secret)
+    hmac_key = JWK.from_json(node_secret.secret)
tests/test_api.py (1)

Line range hint 278-330: Consider adding test for malformed JWK handling

While the current tests cover valid JWK and incorrect signatures, consider adding a test case for malformed JWK responses to ensure robust error handling.

Example test case:

def test_enroll_malformed_jwk() -> None:
    client = get_test_client()
    admin_client = get_test_client()
    admin_client.auth = BACKEND_CREDENTIALS
    
    # Mock response to return malformed JWK
    response = admin_client.post("/api/v1/node")
    create_response = response.json()
    create_response["key"]["kty"] = "invalid"
    
    with pytest.raises(ValueError):
        hmac_key = JWK(**create_response["key"])
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dabf57b and 30898ef.

📒 Files selected for processing (5)
  • nodeman/client.py (2 hunks)
  • nodeman/jose.py (1 hunks)
  • nodeman/models.py (2 hunks)
  • nodeman/nodes.py (2 hunks)
  • tests/test_api.py (4 hunks)
🔇 Additional comments (7)
nodeman/models.py (1)

68-68: Verify API compatibility for existing clients

The change from secret: str to key: PrivateSymmetric is a breaking change in the API response structure. Ensure that:

  1. All clients are updated to handle JWK format
  2. API version is bumped if backward compatibility isn't maintained
✅ Verification successful

API change is safe and properly handled

The codebase analysis shows that the NodeBootstrapInformation model is only used internally within the application:

  1. In nodes.py, the API endpoint creates the key using JWK.generate() and exports it as a dictionary before returning
  2. In client.py, the client code already expects and handles the key in the new format
  3. No external clients or other usages of the old secret field were found
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find potential client implementations that might break
rg -A 3 "NodeBootstrapInformation.*secret" --type py

Length of output: 54


Script:

#!/bin/bash
# Let's try a broader search to find usages of NodeBootstrapInformation
rg -A 5 "NodeBootstrapInformation" --type py

# Also search for any API endpoints or handlers that might use this model
rg -A 5 "def.*bootstrap" --type py

# Look for test files that might show usage patterns
fd "test.*\.py$" --exec rg -l "NodeBootstrapInformation"

Length of output: 2352

nodeman/nodes.py (1)

82-83: LGTM: Response handling is correct

The response correctly includes the complete JWK with algorithm metadata.

nodeman/client.py (2)

156-159: LGTM! Improved security by moving sensitive data to debug level.

The change appropriately moves the full response logging to debug level, reducing the risk of accidentally exposing sensitive data in production logs.


213-213: Verify key format validation

While accessing the JWK's 'k' parameter is correct for symmetric keys, we should ensure that the key format is validated before access.

✅ Verification successful

Based on the search results, I can now provide a final response as there's sufficient evidence to verify the key validation concern:

Key validation is properly implemented in the codebase

The key validation is handled through multiple layers:

  • The PrivateSymmetric model in jose.py enforces JWK structure validation with strict type constraints for kty and k fields
  • The key is validated during JWS verification in nodes.py where jws.verify(key=hmac_key) is called
  • The jwcrypto library's JWK implementation provides additional validation when constructing the key object
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for key format validation before accessing 'k' parameter
# Look for validation code in the codebase

# Search for key validation patterns
rg -A 5 "def.*validate.*key" 

# Search for JWK validation patterns
ast-grep --pattern 'if $key["kty"] != "oct": $_'

Length of output: 81


Script:

#!/bin/bash
# Let's try a broader search for key validation patterns and JWK handling

# Search for JWK-related code and validation
rg -B 2 -A 5 "jwk|JWK" 

# Search for key validation or verification patterns
rg -B 2 -A 5 "(verify|validate|check).*key" -g "*.py"

# Look at the context around where the key is used
rg -B 10 -A 5 "node_bootstrap_information.key" -g "*.py"

Length of output: 28822

tests/test_api.py (3)

83-83: LGTM! Improved key handling by using complete JWK object.

The change properly uses the complete JWK object from the response instead of reconstructing it, which is more secure and maintains all key metadata.

Also applies to: 102-103


279-282: LGTM! Added explicit algorithm verification.

The addition of the algorithm assertion ensures the test uses the correct HMAC algorithm (HS256) and helps catch any unintended algorithm changes.


327-330: LGTM! Consistent algorithm verification in error test case.

The changes maintain consistency with the successful enrollment test cases and properly verify the HMAC algorithm in the error test scenario.

nodeman/jose.py Show resolved Hide resolved
nodeman/nodes.py Show resolved Hide resolved
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.

1 participant