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

Implement support for renew in client #20

Merged
merged 3 commits into from
Dec 4, 2024
Merged

Implement support for renew in client #20

merged 3 commits into from
Dec 4, 2024

Conversation

jschlyter
Copy link
Member

@jschlyter jschlyter commented Dec 4, 2024

Summary by CodeRabbit

  • New Features

    • Introduced functionality for node enrollment and certificate renewal.
    • Enhanced command-line interface with new arguments for admin credentials and certificate renewal.
    • Support for multiple key types, including RSA and EdDSA.
  • Bug Fixes

    • Improved error handling for invalid signatures during node enrollment.
  • Documentation

    • Updated response behavior to exclude fields with None values in the enrollment response.

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

coderabbitai bot commented Dec 4, 2024

Walkthrough

The pull request introduces significant enhancements to the nodeman client and server functionalities. It adds two new functions, enroll and renew, to manage node enrollment and certificate renewal processes, respectively. The client now supports multiple key types and improved command-line interfaces for user authentication. Additionally, the enroll_node function in the server has been modified to exclude None values from its response model while maintaining existing logic for error handling and database interactions.

Changes

File Change Summary
nodeman/client.py Added enroll and renew functions for node management; enhanced command-line arguments for admin credentials; updated key handling to support RSA and EdDSA; improved logging and error handling.
nodeman/nodes.py Updated enroll_node function to exclude None values from response model while preserving existing logic.

Possibly related PRs

  • Update API #5: The changes in the NodeConfiguration class are relevant because the main PR introduces new functions (enroll and renew) that return NodeConfiguration objects, indicating a direct relationship in how node enrollment and configuration are handled.

Poem

In the land of nodes, where rabbits play,
New functions hop in, brightening the day.
Enroll and renew, with keys that gleam,
A secure little world, like a coder's dream.
With logs that sing and errors that flee,
Let's celebrate changes, oh so carefree! 🐇✨


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

🧹 Outside diff range and nitpick comments (3)
nodeman/client.py (3)

79-79: Fix typo in --password help text.

There is a typo in the help text for the --password argument. It should read "Admin password" instead of "Admin psername".

Apply this diff to correct the typo:

-parser.add_argument("--password", metavar="password", help="Admin psername")
+parser.add_argument("--password", metavar="password", help="Admin password")

96-96: Update the help text for the --server argument to reflect its purpose.

The help text "Aggregate receiver" for the --server argument is misleading. It should accurately describe that this argument specifies the Node Manager server URL.

Consider updating the help text as follows:

-parser.add_argument("--server", metavar="URL", help="Aggregate receiver", default="http://127.0.0.1:8080")
+parser.add_argument("--server", metavar="URL", help="Node Manager server URL", default="http://127.0.0.1:8080")

110-110: Simplify the open function by removing the unnecessary mode parameter 'r'.

In Python, the default mode for open() is 'r', so specifying it explicitly is redundant.

Apply this diff to simplify the code:

-with open(args.data_jwk_file, "r") as fp:
+with open(args.data_jwk_file) as fp:
🧰 Tools
🪛 Ruff (0.8.0)

110-110: Unnecessary open mode parameters

Remove open mode parameters

(UP015)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f7195bc and 4f41380.

📒 Files selected for processing (2)
  • nodeman/client.py (4 hunks)
  • nodeman/nodes.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.0)
nodeman/client.py

110-110: Unnecessary open mode parameters

Remove open mode parameters

(UP015)

🔇 Additional comments (1)
nodeman/nodes.py (1)

189-189: Ensure consistent response by excluding fields with None values.

The addition of response_model_exclude_none=True in the @router.post decorator for the enroll_node function ensures that fields with None values are excluded from the response. This improves the API response by not including unnecessary null fields.

from nodeman.x509 import generate_x509_csr

PrivateKey = ec.EllipticCurvePrivateKey | rsa.RSAPublicKey | Ed25519PrivateKey | Ed448PrivateKey
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Correct the use of RSAPublicKey to RSAPrivateKey in PrivateKey type alias.

The PrivateKey type alias includes rsa.RSAPublicKey, which is incorrect since we are dealing with private keys for generating CSRs. It should be rsa.RSAPrivateKey.

Apply this diff to fix the issue:

-PrivateKey = ec.EllipticCurvePrivateKey | rsa.RSAPublicKey | Ed25519PrivateKey | Ed448PrivateKey
+PrivateKey = ec.EllipticCurvePrivateKey | rsa.RSAPrivateKey | Ed25519PrivateKey | Ed448PrivateKey
📝 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.

Suggested change
PrivateKey = ec.EllipticCurvePrivateKey | rsa.RSAPublicKey | Ed25519PrivateKey | Ed448PrivateKey
PrivateKey = ec.EllipticCurvePrivateKey | rsa.RSAPrivateKey | Ed25519PrivateKey | Ed448PrivateKey

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

🧹 Outside diff range and nitpick comments (3)
nodeman/client.py (3)

47-67: Refactor common code into utility functions.

The renew function shares significant code with enroll. Consider extracting common functionality into utility functions to improve maintainability and reduce duplication.

+def _create_jws_payload(x509_key: PrivateKey, name: str, data_key: JWK) -> str:
+    """Create JWS payload with CSR and public key."""
+    x509_csr = generate_x509_csr(key=x509_key, name=name).public_bytes(serialization.Encoding.PEM).decode()
+    return json.dumps({"x509_csr": x509_csr, "public_key": data_key.export_public(as_dict=True)})
+
+def _send_request(url: str, payload: str, timeout: float = 30.0) -> dict:
+    """Send HTTP request with error handling."""
+    try:
+        response = httpx.post(url, json=payload, timeout=timeout)
+        response.raise_for_status()
+        return response.json()
+    except httpx.TimeoutException:
+        raise ConnectionError("Request timed out")
+    except httpx.HTTPStatusError as e:
+        if e.response.status_code == 401:
+            raise ValueError("Unauthorized: Invalid credentials")
+        elif e.response.status_code == 409:
+            raise ValueError("Resource conflict")
+        else:
+            raise ConnectionError(f"Request failed: {e}")

 def renew(name: str, server: str, data_key: JWK, x509_key: PrivateKey) -> NodeCertificate:
     """Renew existing node"""
+    if not name or not server:
+        raise ValueError("Name and server URL are required")
+
+    try:
+        httpx.URL(server)
+    except httpx.InvalidURL as e:
+        raise ValueError(f"Invalid server URL: {e}")

     data_alg = jwk_to_alg(data_key)
-    x509_csr = generate_x509_csr(key=x509_key, name=name).public_bytes(serialization.Encoding.PEM).decode()
-    jws_payload = json.dumps({"x509_csr": x509_csr, "public_key": data_key.export_public(as_dict=True)})
+    jws_payload = _create_jws_payload(x509_key, name, data_key)

     jws = JWS(payload=jws_payload)
     jws.add_signature(key=data_key, alg=data_alg, protected={"alg": data_alg})
     renewal_request = jws.serialize()

     url = urljoin(server, f"/api/v1/node/{name}/renew")
-    response = httpx.post(url, json=renewal_request)
-    response.raise_for_status()
-    renewal_response = response.json()
+    renewal_response = _send_request(url, renewal_request)

79-79: Fix typo in password argument help text.

The help text for the password argument contains a typo: "psername" should be "password".

-    parser.add_argument("--password", metavar="password", help="Admin psername")
+    parser.add_argument("--password", metavar="password", help="Admin password")

154-158: Add error handling for file operations.

The file writing operations should include proper error handling to catch and report IO errors.

     if args.tls_cert_file:
-        with open(args.tls_cert_file, "w") as fp:
-            fp.write(result.x509_certificate)
+        try:
+            with open(args.tls_cert_file, "w") as fp:
+                fp.write(result.x509_certificate)
+        except IOError as e:
+            logging.error("Failed to write certificate file: %s", str(e))
+            raise SystemExit(1)

     if args.tls_ca_file:
-        with open(args.tls_ca_file, "w") as fp:
-            fp.write(result.x509_ca_certificate)
+        try:
+            with open(args.tls_ca_file, "w") as fp:
+                fp.write(result.x509_ca_certificate)
+        except IOError as e:
+            logging.error("Failed to write CA certificate file: %s", str(e))
+            raise SystemExit(1)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4f41380 and 2e932c9.

📒 Files selected for processing (1)
  • nodeman/client.py (4 hunks)
🔇 Additional comments (1)
nodeman/client.py (1)

19-19: ⚠️ Potential issue

Fix incorrect key type in PrivateKey type alias.

The PrivateKey type alias incorrectly includes rsa.RSAPublicKey instead of rsa.RSAPrivateKey. This is a critical issue as the type is used for private key operations like CSR generation.

-PrivateKey = ec.EllipticCurvePrivateKey | rsa.RSAPublicKey | Ed25519PrivateKey | Ed448PrivateKey
+PrivateKey = ec.EllipticCurvePrivateKey | rsa.RSAPrivateKey | Ed25519PrivateKey | Ed448PrivateKey

Comment on lines +118 to +131
if not (args.username and args.password):
logging.error("Admin username & password required")
sys.exit(-1)
try:
auth = (args.username, args.password)
response = httpx.post(urljoin(args.server, "/api/v1/node"), auth=auth)
response.raise_for_status()
except httpx.HTTPError as exc:
logging.error("Failed to create node: %s", str(exc))
raise SystemExit(1) from exc
create_response = response.json()
name = create_response["name"]
secret = create_response["secret"]
logging.info("Got name=%s secret=%s", name, secret)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improve security and error handling for admin authentication.

The current implementation has several issues:

  1. Password is exposed in command line arguments
  2. Inconsistent error handling (mixing sys.exit and SystemExit)
  3. No validation of admin credentials before use

Consider:

  1. Using environment variables or a config file for admin credentials
  2. Consistent error handling approach
  3. Validating credentials format
+def get_admin_credentials() -> tuple[str, str]:
+    """Get admin credentials from environment variables."""
+    username = os.getenv("NODEMAN_ADMIN_USERNAME")
+    password = os.getenv("NODEMAN_ADMIN_PASSWORD")
+    if not username or not password:
+        raise ValueError("Admin credentials must be set in NODEMAN_ADMIN_USERNAME and NODEMAN_ADMIN_PASSWORD")
+    return username, password

-            if not (args.username and args.password):
-                logging.error("Admin username & password required")
-                sys.exit(-1)
+            try:
+                username, password = get_admin_credentials()
+            except ValueError as e:
+                logging.error(str(e))
+                raise SystemExit(1)
             try:
-                auth = (args.username, args.password)
+                auth = (username, password)
                 response = httpx.post(urljoin(args.server, "/api/v1/node"), auth=auth)
                 response.raise_for_status()
📝 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.

Suggested change
if not (args.username and args.password):
logging.error("Admin username & password required")
sys.exit(-1)
try:
auth = (args.username, args.password)
response = httpx.post(urljoin(args.server, "/api/v1/node"), auth=auth)
response.raise_for_status()
except httpx.HTTPError as exc:
logging.error("Failed to create node: %s", str(exc))
raise SystemExit(1) from exc
create_response = response.json()
name = create_response["name"]
secret = create_response["secret"]
logging.info("Got name=%s secret=%s", name, secret)
try:
username, password = get_admin_credentials()
except ValueError as e:
logging.error(str(e))
raise SystemExit(1)
try:
auth = (username, password)
response = httpx.post(urljoin(args.server, "/api/v1/node"), auth=auth)
response.raise_for_status()
except httpx.HTTPError as exc:
logging.error("Failed to create node: %s", str(exc))
raise SystemExit(1) from exc
create_response = response.json()
name = create_response["name"]
secret = create_response["secret"]
logging.info("Got name=%s secret=%s", name, secret)

Comment on lines +22 to +45
def enroll(name: str, server: str, hmac_key: JWK, data_key: JWK, x509_key: PrivateKey) -> NodeConfiguration:
"""Enroll new node"""

hmac_alg = "HS256"
data_alg = jwk_to_alg(data_key)
x509_csr = generate_x509_csr(key=x509_key, name=name).public_bytes(serialization.Encoding.PEM).decode()

jws_payload = json.dumps({"x509_csr": x509_csr, "public_key": data_key.export_public(as_dict=True)})

jws = JWS(payload=jws_payload)
jws.add_signature(key=hmac_key, alg=hmac_alg, protected={"alg": hmac_alg})
jws.add_signature(key=data_key, alg=data_alg, protected={"alg": data_alg})
enrollment_request = jws.serialize()

url = urljoin(server, f"/api/v1/node/{name}/enroll")
response = httpx.post(url, json=enrollment_request)
response.raise_for_status()

enrollment_response = response.json()

logging.debug("Response: %s", json.dumps(enrollment_response, indent=4))

return NodeConfiguration(**enrollment_response)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add input validation and improve error handling.

The enroll function should validate input parameters and include better error handling:

  1. Validate server URL format
  2. Add request timeout
  3. Add more specific error handling for different HTTP status codes
 def enroll(name: str, server: str, hmac_key: JWK, data_key: JWK, x509_key: PrivateKey) -> NodeConfiguration:
     """Enroll new node"""
+    if not name or not server:
+        raise ValueError("Name and server URL are required")
+    
+    try:
+        # Validate server URL
+        httpx.URL(server)
+    except httpx.InvalidURL as e:
+        raise ValueError(f"Invalid server URL: {e}")

     hmac_alg = "HS256"
     data_alg = jwk_to_alg(data_key)
     x509_csr = generate_x509_csr(key=x509_key, name=name).public_bytes(serialization.Encoding.PEM).decode()

     jws_payload = json.dumps({"x509_csr": x509_csr, "public_key": data_key.export_public(as_dict=True)})

     jws = JWS(payload=jws_payload)
     jws.add_signature(key=hmac_key, alg=hmac_alg, protected={"alg": hmac_alg})
     jws.add_signature(key=data_key, alg=data_alg, protected={"alg": data_alg})
     enrollment_request = jws.serialize()

     url = urljoin(server, f"/api/v1/node/{name}/enroll")
-    response = httpx.post(url, json=enrollment_request)
-    response.raise_for_status()
+    try:
+        response = httpx.post(url, json=enrollment_request, timeout=30.0)
+        response.raise_for_status()
+    except httpx.TimeoutException:
+        raise ConnectionError("Enrollment request timed out")
+    except httpx.HTTPStatusError as e:
+        if e.response.status_code == 401:
+            raise ValueError("Unauthorized: Invalid credentials")
+        elif e.response.status_code == 409:
+            raise ValueError("Node already exists")
+        else:
+            raise ConnectionError(f"Enrollment failed: {e}")
📝 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.

Suggested change
def enroll(name: str, server: str, hmac_key: JWK, data_key: JWK, x509_key: PrivateKey) -> NodeConfiguration:
"""Enroll new node"""
hmac_alg = "HS256"
data_alg = jwk_to_alg(data_key)
x509_csr = generate_x509_csr(key=x509_key, name=name).public_bytes(serialization.Encoding.PEM).decode()
jws_payload = json.dumps({"x509_csr": x509_csr, "public_key": data_key.export_public(as_dict=True)})
jws = JWS(payload=jws_payload)
jws.add_signature(key=hmac_key, alg=hmac_alg, protected={"alg": hmac_alg})
jws.add_signature(key=data_key, alg=data_alg, protected={"alg": data_alg})
enrollment_request = jws.serialize()
url = urljoin(server, f"/api/v1/node/{name}/enroll")
response = httpx.post(url, json=enrollment_request)
response.raise_for_status()
enrollment_response = response.json()
logging.debug("Response: %s", json.dumps(enrollment_response, indent=4))
return NodeConfiguration(**enrollment_response)
def enroll(name: str, server: str, hmac_key: JWK, data_key: JWK, x509_key: PrivateKey) -> NodeConfiguration:
"""Enroll new node"""
if not name or not server:
raise ValueError("Name and server URL are required")
try:
# Validate server URL
httpx.URL(server)
except httpx.InvalidURL as e:
raise ValueError(f"Invalid server URL: {e}")
hmac_alg = "HS256"
data_alg = jwk_to_alg(data_key)
x509_csr = generate_x509_csr(key=x509_key, name=name).public_bytes(serialization.Encoding.PEM).decode()
jws_payload = json.dumps({"x509_csr": x509_csr, "public_key": data_key.export_public(as_dict=True)})
jws = JWS(payload=jws_payload)
jws.add_signature(key=hmac_key, alg=hmac_alg, protected={"alg": hmac_alg})
jws.add_signature(key=data_key, alg=data_alg, protected={"alg": data_alg})
enrollment_request = jws.serialize()
url = urljoin(server, f"/api/v1/node/{name}/enroll")
try:
response = httpx.post(url, json=enrollment_request, timeout=30.0)
response.raise_for_status()
except httpx.TimeoutException:
raise ConnectionError("Enrollment request timed out")
except httpx.HTTPStatusError as e:
if e.response.status_code == 401:
raise ValueError("Unauthorized: Invalid credentials")
elif e.response.status_code == 409:
raise ValueError("Node already exists")
else:
raise ConnectionError(f"Enrollment failed: {e}")
enrollment_response = response.json()
logging.debug("Response: %s", json.dumps(enrollment_response, indent=4))
return NodeConfiguration(**enrollment_response)

@jschlyter jschlyter merged commit cff5e7e into main Dec 4, 2024
5 checks passed
@jschlyter jschlyter deleted the renew_fixes branch December 4, 2024 12:56
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