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

Save issued certificates to database #44

Merged
merged 3 commits into from
Dec 19, 2024
Merged

Conversation

jschlyter
Copy link
Member

@jschlyter jschlyter commented Dec 19, 2024

Summary by CodeRabbit

  • New Features

    • Introduced TapirCertificate class for storing certificate data.
    • Added x509_certificate_not_valid_after field to NodeCertificate for expiration dates.
    • Enhanced enroll_node function to include certificate expiration date in responses.
  • Bug Fixes

    • Improved error handling in renew_node to prevent renewal of inactive nodes.
  • Documentation

    • Updated method signatures to reflect new return values and added fields.

@jschlyter jschlyter requested a review from a team as a code owner December 19, 2024 12:40
Copy link
Contributor

coderabbitai bot commented Dec 19, 2024

Walkthrough

This pull request introduces enhancements to the node certificate management system across multiple files in the nodeman package. It adds a new database model, TapirCertificate, for storing detailed certificate information, including expiration dates. The NodeCertificate model is updated to include an expiration date for X.509 certificates. Additionally, the certificate processing logic is refined to integrate the new model and improve validation and error handling during node enrollment and renewal processes.

Changes

File Changes
nodeman/db_models.py Added TapirCertificate class with fields for certificate details including name, issuer, subject, serial number, validity dates, and certificate data.
nodeman/models.py Added x509_certificate_not_valid_after: datetime field to NodeCertificate class.
nodeman/nodes.py Updated enroll_node and renew_node methods to include certificate expiration date and add activation status verification.
nodeman/x509.py Imported TapirCertificate, modified process_csr_request to save certificate details to the database and include expiration date in the response.

Possibly related PRs

Poem

🐰 A Rabbit's Ode to Certificates 🔐
In databases of nodes and trust,
Certificates bloom with details just!
Expiration dates now clearly shown,
Our digital realm has freshly grown
With security's most playful crown! 🎉


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 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: 1

🧹 Nitpick comments (3)
nodeman/db_models.py (1)

55-64: Consider adding validation and helper methods

A few suggestions to enhance the model:

  1. Add validation for the certificate field to ensure it's a valid PEM format
  2. Consider storing serial as an integer field for consistent handling with X.509 operations
  3. Add a classmethod to create instance from an X.509 certificate object

Example implementation:

-    serial = StringField()
+    serial = IntField()
+
+    @classmethod
+    def from_x509_cert(cls, name: str, cert: 'x509.Certificate') -> 'TapirCertificate':
+        return cls(
+            name=name,
+            issuer=cert.issuer.rfc4514_string(),
+            subject=cert.subject.rfc4514_string(),
+            serial=cert.serial_number,
+            not_valid_before=cert.not_valid_before_utc,
+            not_valid_after=cert.not_valid_after_utc,
+            certificate=cert.public_bytes(serialization.Encoding.PEM).decode(),
+        )
+
+    def clean(self):
+        """Validate certificate field format"""
+        if self.certificate:
+            try:
+                load_pem_x509_certificate(self.certificate.encode())
+            except ValueError as e:
+                raise ValidationError("Invalid certificate PEM format") from e
nodeman/models.py (1)

75-75: Consider adding validation for certificate expiration

The new field x509_certificate_not_valid_after should have validation to ensure it's:

  1. Not in the past when creating new certificates
  2. After not_valid_before if that field is present

Example implementation:

-    x509_certificate_not_valid_after: datetime
+    x509_certificate_not_valid_after: datetime = Field(
+        title="Certificate expiration date",
+        description="When the X.509 certificate expires",
+    )
+
+    @field_validator("x509_certificate_not_valid_after")
+    @classmethod
+    def validate_expiration(cls, v: datetime):
+        if v < datetime.now(timezone.utc):
+            raise ValueError("Certificate expiration date cannot be in the past")
+        return v
nodeman/nodes.py (1)

Line range hint 332-333: Consider adding debug logging for activation check

The validation check for node activation is a good security measure. Consider adding debug logging to help with troubleshooting activation-related issues.

Add logging before raising the exception:

     if not node.activated:
+        logging.debug("Renewal attempt for non-activated node %s", name, extra={"nodename": name})
         raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="Node not activated")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bd6c969 and 519210a.

📒 Files selected for processing (4)
  • nodeman/db_models.py (1 hunks)
  • nodeman/models.py (1 hunks)
  • nodeman/nodes.py (1 hunks)
  • nodeman/x509.py (3 hunks)
🔇 Additional comments (4)
nodeman/db_models.py (1)

46-53: LGTM on model structure and indexes

The model structure with indexes on name and composite [issuer, serial] is well-designed for efficient querying. The unique constraint on [issuer, serial] correctly enforces certificate uniqueness.

nodeman/x509.py (2)

175-175: LGTM on certificate expiration field

The addition of x509_certificate_not_valid_after to the return value is correct and consistent with the model changes.


149-157: Verify certificate uniqueness constraints

Let's verify the effectiveness of the unique constraint on [issuer, serial] and check for potential race conditions.

✅ Verification successful

Certificate uniqueness is properly enforced

The model definition shows that a unique compound index is set on ["issuer", "serial"] fields, which will prevent duplicate certificates at the database level. While there's no explicit transaction handling, MongoDB's atomic operations on single documents provide sufficient protection against race conditions in this case.

  • ✓ Unique constraint on ["issuer", "serial"] is properly defined in nodeman/db_models.py
  • ✓ Document-level atomicity in MongoDB handles concurrent save operations safely
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any existing duplicate certificates
ast-grep --pattern 'TapirCertificate.objects($$$)' | grep -i 'find\|get'

# Check for any concurrent certificate operations
rg -A 5 'save_certificate|TapirCertificate.*save'

Length of output: 126


Script:

#!/bin/bash
# Check model definition for uniqueness constraints
rg -A 10 "class TapirCertificate"

# Check for any existing certificate operations
rg -l "TapirCertificate"

# Check for any transaction or locking mechanisms
rg -A 5 "@transaction.atomic|select_for_update"

Length of output: 624

nodeman/nodes.py (1)

279-279: Verify NodeConfiguration model includes the new field

The addition of x509_certificate_not_valid_after aligns with the PR objective of tracking certificate data. The field is correctly propagated from the certificate processing.

Let's verify the field is properly defined in the NodeConfiguration model:

✅ Verification successful

Field is properly defined in the model hierarchy

The x509_certificate_not_valid_after field is correctly defined in the NodeCertificate base class, which NodeConfiguration inherits from. The field is properly typed as datetime and is a required field (no default value), which aligns with the usage in the code under review.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for NodeConfiguration model definition
ast-grep --pattern 'class NodeConfiguration' -A 20

Length of output: 52


Script:

#!/bin/bash
# Let's try searching for NodeConfiguration using ripgrep for better coverage
rg "class NodeConfiguration" -A 20

Length of output: 673


Script:

#!/bin/bash
# Let's check the NodeCertificate class since NodeConfiguration inherits from it
rg "class NodeCertificate" -A 20

Length of output: 1335

nodeman/x509.py Outdated Show resolved Hide resolved
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: 0

🔭 Outside diff range comments (1)
nodeman/x509.py (1)

Line range hint 149-167: Consider using database transaction

The certificate issuance process involves multiple database operations (saving certificate and potentially updating node status). Consider wrapping these operations in a transaction to ensure data consistency.

+from mongoengine import get_db
+
 def process_csr_request(request: Request, csr: x509.CertificateSigningRequest, name: str) -> NodeCertificate:
     """Verify CSR and issue certificate"""
+    session = get_db().client.start_session()
+    with session.start_transaction():
+        try:
             # ... existing code ...
-            TapirCertificate.from_x509_certificate(name=name, x509_certificate=x509_certificate).save()
+            TapirCertificate.from_x509_certificate(
+                name=name, 
+                x509_certificate=x509_certificate
+            ).save(session=session)
             # ... rest of the code ...
+        except Exception as exc:
+            session.abort_transaction()
+            raise
🧹 Nitpick comments (3)
nodeman/db_models.py (2)

48-55: Consider index ordering optimization

The composite index on ["issuer", "serial"] might benefit from reverse order ["serial", "issuer"] if queries frequently filter by serial number first. This could improve query performance for certificate lookups by serial number.


80-85: Enhance certificate validation

The current validation only checks if the certificate can be parsed. Consider adding additional validations:

  1. Certificate chain validation
  2. Expiration date validation
  3. Key usage validation
 def clean(self):
     """Validate certificate format"""
     try:
-        x509.load_pem_x509_certificate(self.certificate.encode())
+        cert = x509.load_pem_x509_certificate(self.certificate.encode())
+        # Validate certificate dates
+        now = datetime.now(timezone.utc)
+        if now < cert.not_valid_before_utc or now > cert.not_valid_after_utc:
+            raise ValidationError("Certificate is not valid at the current time")
+        # Validate key usage
+        if cert.extensions.get_extension_for_oid(ExtensionOID.KEY_USAGE).value.key_cert_sign:
+            raise ValidationError("Certificate must not have key_cert_sign usage")
     except ValueError as exc:
         raise ValidationError("Invalid certificate PEM format") from exc
nodeman/nodes.py (1)

300-301: Improve error handling for non-activated nodes

Consider providing a more descriptive error message and moving the activation check earlier in the function to fail fast.

-    if not node.activated:
-        logging.debug("Renewal attempt for non-activated node %s", name, extra={"nodename": name})
-        raise HTTPException(status.HTTP_400_BAD_REQUEST, detail="Node not activated")
+    if not node.activated:
+        msg = f"Cannot renew certificate for node '{name}' as it has not completed the enrollment process"
+        logging.warning(msg, extra={"nodename": name})
+        raise HTTPException(
+            status_code=status.HTTP_400_BAD_REQUEST,
+            detail=msg
+        )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 519210a and 3c41069.

📒 Files selected for processing (3)
  • nodeman/db_models.py (2 hunks)
  • nodeman/nodes.py (2 hunks)
  • nodeman/x509.py (3 hunks)
🔇 Additional comments (2)
nodeman/x509.py (1)

149-150: Add error handling for database operations

The certificate saving operation could fail silently. Consider adding error handling for database operations.

nodeman/nodes.py (1)

279-279: LGTM: Certificate expiration tracking added

The addition of x509_certificate_not_valid_after to the NodeConfiguration response is a good improvement for certificate lifecycle management.

@jschlyter jschlyter merged commit 2e8b85d into main Dec 19, 2024
5 checks passed
@jschlyter jschlyter deleted the save_issued_certificates branch December 19, 2024 13:16
@jschlyter jschlyter restored the save_issued_certificates branch January 7, 2025 07:37
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