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

Generic enrollment keys #36

Merged
merged 3 commits into from
Dec 18, 2024
Merged

Generic enrollment keys #36

merged 3 commits into from
Dec 18, 2024

Conversation

jschlyter
Copy link
Member

@jschlyter jschlyter commented Dec 18, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new configuration section for internal Certificate Authority (CA) settings.
    • Added a new class for managing node enrollment in the database.
    • Enhanced JSON Web Key (JWK) representation with new private key classes.
  • Bug Fixes

    • Updated node enrollment handling to utilize the new enrollment model.
  • Tests

    • Refined test cases for node enrollment and certificate renewal processes, improving security and clarity.

Copy link
Contributor

coderabbitai bot commented Dec 18, 2024

Warning

Rate limit exceeded

@jschlyter has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 25 minutes and 34 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 2bc78ab and b91b075.

📒 Files selected for processing (1)
  • tests/test_api.py (6 hunks)

Walkthrough

This pull request introduces significant changes to the node management system, focusing on enhancing the configuration and key management for node enrollment. The modifications span multiple files, including nodeman.toml, database models, JOSE (JSON Object Signing and Encryption) implementation, and node enrollment logic. The changes primarily revolve around introducing a new internal Certificate Authority configuration, expanding key management capabilities, and updating the enrollment process to use more flexible key types.

Changes

File Change Summary
nodeman.toml Added [internal_ca] section with new parameters for issuer CA certificate, private key, and validity days
nodeman/db_models.py Introduced TapirNodeEnrollment class with name and key fields
nodeman/jose.py Added private key classes for RSA, EC, and OKP with new alg field and PrivateJwk type
nodeman/models.py Updated NodeBootstrapInformation to support PrivateJwk alongside PrivateSymmetric
nodeman/nodes.py Transitioned from TapirNodeSecret to TapirNodeEnrollment for node enrollment management

Sequence Diagram

sequenceDiagram
    participant Client
    participant NodeManager
    participant InternalCA
    participant Database

    Client->>NodeManager: Enroll Node
    NodeManager->>InternalCA: Generate Enrollment Key
    InternalCA-->>NodeManager: Return Enrollment Key
    NodeManager->>Database: Save TapirNodeEnrollment
    Database-->>NodeManager: Confirm Save
    NodeManager->>Client: Return Enrollment Response
Loading

Possibly Related PRs

Suggested Reviewers

  • morkrost

Poem

🐰 Nodes dance with keys so bright,
Enrollment's path now clear and light
CA secrets tucked away with care
New models bloom without despair
A rabbit's code, both strong and fair! 🔑


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.

@jschlyter jschlyter marked this pull request as ready for review December 18, 2024 09:09
@jschlyter jschlyter requested a review from a team as a code owner December 18, 2024 09:09
@jschlyter jschlyter requested a review from eest December 18, 2024 09:09
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 (5)
nodeman/nodes.py (3)

77-80: Potential concurrency race when creating TapirNodeEnrollment.

When generating the enrollment key and immediately storing it, consider wrapping the creation of both TapirNode and TapirNodeEnrollment in a transaction (if your DB and ODM support it) to ensure consistency in high-concurrency scenarios.


222-224: Potentially handle multiple node enrollments.

Currently, only one enrollment entry is expected per node. If in the future multiple enrollment processes are introduced (or re-enrollment entries are needed), consider whether this logic should handle multiple matches instead of just the first.


236-236: Clear inline comment on signature verification.

Minor note: good to see a clarifying comment reminding future maintainers of the purpose of signature verification by the enrollment key.

nodeman.toml (1)

15-16: Commented-out [step] lines.

Retaining them is helpful for historical context or fallback. However, if the old approach is truly deprecated, consider fully removing or referencing them in a readme to avoid confusion.

tests/test_api.py (1)

325-328: Consider extracting key generation parameters

The key generation parameters (kty, crv, alg) are duplicated across test cases. Consider extracting these into constants or test parameters.

+# At the top of the file
+TEST_KEY_PARAMS = {
+    "ed25519": {"kty": "OKP", "crv": "Ed25519", "alg": "EdDSA"},
+    "p256": {"kty": "EC", "crv": "P-256"},
+    # ... other key types
+}

-    data_key = JWK.generate(kty=kty, crv=crv, alg="EdDSA")
-    bad_data_key = JWK.generate(kty=kty, crv=crv, alg="EdDSA")
+    params = TEST_KEY_PARAMS["ed25519"]
+    data_key = JWK.generate(**params)
+    bad_data_key = JWK.generate(**params)

Also applies to: 340-341

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3ecb950 and 2bc78ab.

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

14-14: Good move changing to TapirNodeEnrollment.

You switched from TapirNodeSecret to TapirNodeEnrollment. Ensure that all references to TapirNodeSecret across the codebase are removed or updated to prevent confusion.


191-192: Ensure consistency and maintain auditing logic for node enrollment deletion.

On node deletion, you also remove its enrollment record. This is good for ensuring no stale secrets remain; however, some systems prefer to keep a historical record for auditing or forensic analysis.


227-227: Empty line note.

No direct issue, but be mindful if you intend to insert logic or comments here.


228-228: JWK import is correct.

The usage of JWK(**node_enrollment.key) aligns with the changes to store the key as a DictField. Ensure error handling is robust if the stored data is malformed.


238-238: Signature verification is correct.

The logic for verifying JWS by enrollment key is appropriate.


241-242: Fine-grained error response.

Raising 401 Unauthorized for invalid enrollment signature is an appropriate usage of HTTP status codes.


267-267: Final enrollment deletion could omit re-enrollment.

After successful enrollment, the record is deleted. If this node needs to re-enroll, it might need a new record. Validate that it is the desired flow for your business logic.

nodeman.toml (1)

4-8: Good introduction of [internal_ca] section.

This new section clarifies where the internal CA details reside. The inline comments referencing the prior [step] section are helpful but ensure that future maintainers understand which config is active.

nodeman/db_models.py (1)

46-50: New TapirNodeEnrollment model looks good.

By storing both name and key in a dedicated collection, you now have a more granular enrollment record for each node. Be sure to add any indexes you might need for lookup or expiry.

nodeman/jose.py (4)

14-14: Optional alg field is beneficial.

Allowing an optional algorithm field in BaseJWK is a good enhancement for flexibility across different cryptographic operations.


40-42: EC private key representation is correct.

The addition of a private scalar (d) for curves P-256/P-384 aligns with typical Elliptic Curve standard usage.


52-54: OKP private key representation is correct.

Similar to RSA/EC changes, properly storing the private field for Ed/X curves. Same caution applies about logging.


64-64: PrivateJwk union ensures flexible usage.

Defining PrivateJwk as a union of RSA, EC, and OKP private keys is a clear approach to handle multiple key types.

nodeman/models.py (2)

10-10: LGTM: Import changes align with new key type support

The addition of PrivateJwk import supports the enhanced key type flexibility for node enrollment.


68-68: Verify backward compatibility with existing nodes

The field type change from PrivateSymmetric to PrivateSymmetric | PrivateJwk enhances flexibility but requires verification of existing node compatibility.

✅ Verification successful

Let me gather more information about the key usage and type handling in the codebase.


Based on the gathered information, I can now provide the final response:

The type change to PrivateSymmetric | PrivateJwk is backward compatible

The code analysis shows that:

  • The key handling in enroll_node uses JWK operations (JWK(**node_enrollment.key)) which works with both types
  • The client code in command_enroll already handles JWK format for enrollment
  • No direct dependencies on PrivateSymmetric type are found in the codebase
  • The key is only used during the enrollment process and not stored long-term
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for existing nodes that might be affected by the key type change

# Search for node creation/enrollment patterns
rg -A 5 "NodeBootstrapInformation|create_node|enroll_node"

# Look for any existing key type references
ast-grep --pattern 'key: PrivateSymmetric = $_'

Length of output: 2670


Script:

#!/bin/bash
# Check how the key is used in node enrollment and validation
rg -A 5 "key.*PrivateSymmetric|key.*PrivateJwk"

# Look for key validation or processing logic
ast-grep --pattern 'def $_($$$) -> NodeConfiguration:
  $$$
'

# Check for any key-related migrations or database schemas
fd -e sql -e py -e json "migration|schema" --exec rg -l "key|PrivateSymmetric|PrivateJwk" {}

Length of output: 8515

tests/test_api.py (2)

103-103: LGTM: Improved algorithm detection logic

The new algorithm detection with fallback mechanism is more robust:

  1. First tries to get the algorithm directly from the key
  2. Falls back to jwk_to_alg if not present

Also applies to: 283-283


Line range hint 101-114: Verify JWS signature order requirements

The code adds signatures in a specific order (enrollment key first, data key second). Verify if this order is required by the API implementation.

nodeman/jose.py Show resolved Hide resolved
tests/test_api.py Outdated Show resolved Hide resolved
@jschlyter jschlyter merged commit 069de6a into main Dec 18, 2024
5 checks passed
@jschlyter jschlyter deleted the generic_enrollment_keys branch December 18, 2024 09:17
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