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

Support parsing enrollment file in client #80

Merged
merged 4 commits into from
Feb 3, 2025
Merged

Conversation

jschlyter
Copy link
Member

@jschlyter jschlyter commented Feb 3, 2025

Summary by CodeRabbit

  • New Features
    • Added a file option that lets users provide enrollment data via a JSON file for a more flexible input method.
  • Bug Fixes
    • Improved error handling during file parsing to deliver clear feedback and ensure the enrollment process uses consistent server details.
  • Chores
    • Updated client files to include enrollment.json and modified the enrollment process in the test-client target for better data handling.

@jschlyter jschlyter requested a review from a team as a code owner February 3, 2025 12:38
Copy link
Contributor

coderabbitai bot commented Feb 3, 2025

Warning

Rate limit exceeded

@jschlyter has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 47 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 ee655ef and 04ed0d6.

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

Walkthrough

The changes modify the enrollment logic in nodeman/client.py by updating the command_enroll function and its command-line argument parser. A new --file argument is introduced to allow enrollment data to be read from a JSON file. The function now handles file-based input, including JSON parsing and error logging, and ensures the server URL is correctly assigned from either the command-line input or the parsed file data. In addition, when args.create is true, the function creates a new node and retrieves the necessary enrollment key. The Makefile is also updated to include enrollment.json and revise the test-client-enroll target to use a curl command for enrollment data retrieval.

Changes

File Change Summary
nodeman/client.py Updated command_enroll to handle a new --file argument. Added JSON file reading for enrollment data, enhanced error logging on file parse failures, and ensured consistent server URL assignment.
Makefile Modified CLIENT_FILES to include enrollment.json and changed the test-client-enroll target to use a curl command for enrollment data retrieval, followed by invoking nodeman_client.

Possibly related PRs

  • Implement support for renew in client #20: The changes in the main PR are related to the modifications in the command_enroll function in the retrieved PR, as both involve enhancements to the enrollment process within the nodeman/client.py file.
  • Improved client #23: The changes in the main PR, specifically the modifications to the command_enroll function in nodeman/client.py, are related to the enhancements made to the same function in the retrieved PR, which also includes updates to the command-line interface and error handling.
  • Send enrollment key as JWK #34: The changes in the main PR are related to the command_enroll function in nodeman/client.py, which has been modified to handle a new command-line argument and improve error handling, while the retrieved PR also modifies the same function to change how the enrollment key is managed, indicating a direct connection at the code level.

Poem

In a field of code I hop with glee,
A new --file flag set my data free.
JSON whispers secrets in the night,
As errors vanish with logging bright.
With every change my hops grow bold,
A rabbit’s tale in code retold.
🐇✨ Happy coding under the digital sky!


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 (3)
nodeman/client.py (3)

356-356: Add type hints and file validation.

Consider enhancing the file argument with type hints and validation:

-    enroll_parser.add_argument("--file", metavar="filename", help="Enrollment file")
+    enroll_parser.add_argument(
+        "--file",
+        metavar="filename",
+        help="JSON file containing enrollment data",
+        type=argparse.FileType('r'),
+    )

219-236: Standardize server URL assignment.

The server URL assignment is inconsistent across different enrollment paths. Consider standardizing the logic:

 def command_enroll(args: argparse.Namespace) -> NodeConfiguration:
+    server = args.server  # Default server from command line
+
     if args.create:
-        server = args.server
         node_bootstrap_information = command_create(args)
         name = node_bootstrap_information.name
         enrollment_key = JWK(**node_bootstrap_information.key.model_dump())
     elif args.file:
         with open(args.file) as fp:
             enrollment_data = json.load(fp)
         try:
             name = enrollment_data["name"]
-            server = enrollment_data["nodeman_url"]
+            # Override server only if specified in file
+            if "nodeman_url" in enrollment_data:
+                server = enrollment_data["nodeman_url"]
             enrollment_key = JWK(**enrollment_data["key"])
         except Exception as exc:
             logging.error("Error parsing enrollment file", exc_info=exc)
             raise SystemExit(2) from exc
     else:
-        server = args.server
         name = args.name
         enrollment_key = JWK(kty="oct", k=args.secret, alg="HS256")

232-233: Standardize error codes.

Consider using an enum for error codes to maintain consistency throughout the codebase.

+from enum import IntEnum
+
+class ErrorCode(IntEnum):
+    SUCCESS = 0
+    GENERAL_ERROR = 1
+    INVALID_INPUT = 2
+    NETWORK_ERROR = 3
+
 def command_enroll(args: argparse.Namespace) -> NodeConfiguration:
     ...
             logging.error("Error parsing enrollment file", exc_info=exc)
-            raise SystemExit(2) from exc
+            raise SystemExit(ErrorCode.INVALID_INPUT) from exc
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4b1b82d and 532988e.

📒 Files selected for processing (1)
  • nodeman/client.py (3 hunks)

node_bootstrap_information = command_create(args)
name = node_bootstrap_information.name
enrollment_key = JWK(**node_bootstrap_information.key.model_dump())
elif args.file:
with open(args.file) as fp:
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

Validate file path to prevent path traversal.

The file path should be validated before opening to prevent path traversal attacks.

+import os.path
+
 def command_enroll(args: argparse.Namespace) -> NodeConfiguration:
     ...
     elif args.file:
+        file_path = os.path.abspath(args.file)
+        if not os.path.exists(file_path):
+            logging.error("Enrollment file does not exist: %s", args.file)
+            raise SystemExit(2)
+        if not os.path.isfile(file_path):
+            logging.error("Path is not a file: %s", args.file)
+            raise SystemExit(2)
+
-        with open(args.file) as fp:
+        with open(file_path) as fp:
📝 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
with open(args.file) as fp:
import os.path
def command_enroll(args: argparse.Namespace) -> NodeConfiguration:
...
elif args.file:
file_path = os.path.abspath(args.file)
if not os.path.exists(file_path):
logging.error("Enrollment file does not exist: %s", args.file)
raise SystemExit(2)
if not os.path.isfile(file_path):
logging.error("Path is not a file: %s", args.file)
raise SystemExit(2)
with open(file_path) as fp:
...

Comment on lines 225 to 233
with open(args.file) as fp:
enrollment_data = json.load(fp)
try:
name = enrollment_data["name"]
server = enrollment_data["nodeman_url"]
enrollment_key = JWK(**enrollment_data["key"])
except Exception as exc:
logging.error("Error parsing enrollment file", exc_info=exc)
raise SystemExit(2) from exc
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

Enhance file parsing error handling.

The current error handling is too broad. Consider:

  1. Validating the JSON schema
  2. Providing specific error messages for missing fields
  3. Using a Pydantic model for parsing
+from typing import TypedDict
+
+class EnrollmentData(TypedDict):
+    name: str
+    nodeman_url: str
+    key: dict
+
 def command_enroll(args: argparse.Namespace) -> NodeConfiguration:
     ...
     elif args.file:
         with open(args.file) as fp:
-            enrollment_data = json.load(fp)
-        try:
-            name = enrollment_data["name"]
-            server = enrollment_data["nodeman_url"]
-            enrollment_key = JWK(**enrollment_data["key"])
-        except Exception as exc:
-            logging.error("Error parsing enrollment file", exc_info=exc)
+            try:
+                enrollment_data = json.load(fp)
+            except json.JSONDecodeError as exc:
+                logging.error("Invalid JSON in enrollment file: %s", str(exc))
+                raise SystemExit(2) from exc
+
+        missing_fields = []
+        for field in ["name", "nodeman_url", "key"]:
+            if field not in enrollment_data:
+                missing_fields.append(field)
+
+        if missing_fields:
+            logging.error("Missing required fields in enrollment file: %s", ", ".join(missing_fields))
             raise SystemExit(2) from exc
+
+        try:
+            enrollment_data_typed = EnrollmentData(
+                name=enrollment_data["name"],
+                nodeman_url=enrollment_data["nodeman_url"],
+                key=enrollment_data["key"],
+            )
+            name = enrollment_data_typed["name"]
+            server = enrollment_data_typed["nodeman_url"]
+            enrollment_key = JWK(**enrollment_data_typed["key"])
+        except (KeyError, TypeError) as exc:
+            logging.error("Invalid field types in enrollment file: %s", str(exc))
+            raise SystemExit(2) from exc

Committable suggestion skipped: line range outside the PR's diff.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 532988e and 8aa70ed.

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

6-6: LGTM! Good choice using pathlib.Path.

Using pathlib.Path is the recommended way to handle file paths in modern Python.


225-241: Enhance JSON parsing error handling.

The current error handling is too broad and doesn't provide specific error messages for different failure cases.

Previous review comment suggested using a TypedDict for schema validation and providing specific error messages for different failure cases. This suggestion is still valid.

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

🧹 Nitpick comments (1)
Makefile (1)

41-42: Utilize File-Based Enrollment in test-client-enroll Target

The updated commands now use curl to fetch the enrollment JSON and then pass it to the client via --file enrollment.json. This is well aligned with the PR objective and client changes.

-	rm -f tls.crt tls-ca.crt tls.key data.json
-	[...]
-	poetry run nodeman_client --debug enroll
+	rm -f tls.crt tls-ca.crt tls.key data.json
+	curl -X POST --verbose --user username:password -o enrollment.json http://127.0.0.1:8080/api/v1/node
+	poetry run nodeman_client --debug enroll --file enrollment.json

Suggestion: Consider parameterizing the credentials (e.g., username:password) or endpoint URL via Makefile variables for improved flexibility and maintainability in different testing environments.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8aa70ed and ee655ef.

📒 Files selected for processing (1)
  • Makefile (2 hunks)
🔇 Additional comments (1)
Makefile (1)

16-16: Update CLIENT_FILES Variable to Include enrollment.json

Adding enrollment.json to the CLIENT_FILES list is consistent with the new enrollment file parsing feature in the client. This ensures that the enrollment file is also tracked for cleanup and packaging.

-CLIENT_FILES=		data.json tls.crt tls.key tls-ca.crt
+CLIENT_FILES=		data.json tls.crt tls.key tls-ca.crt enrollment.json

@jschlyter jschlyter merged commit 68aa7f8 into main Feb 3, 2025
5 checks passed
@jschlyter jschlyter deleted the client_enrollment_file branch February 3, 2025 15:24
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