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

Feat: Add mtls authentication for the API #87

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

nodauf
Copy link
Contributor

@nodauf nodauf commented Oct 2, 2024

Description

This PR add mTLS authentication for the API (#77). The op-service from the monorepo already implements the necessary requirements for this. I made a few adjustments since the default values are set for the TLS flags (default values). As a result, the checks (checks) always indicated that TLS was enabled, even when the user didn't provide the arguments.

Regarding your infrastructure, I'm not sure if using middleware might be a better option than what I implemented. The middleware could allow some endpoints (like the healthcheck) to bypass the mTLS. What are you though on this?

Tests

The feature was tested using the following command line:

go run main.go cli.go psp_executor --privatekey 0x2592897534a1873b0fdc91c6ac0ba938eeb19cd502b650072fe71fbc0105db92 --superchainconfig.address 0x0F24Af6B7147aAEf00b216Cd38667256DC56755a --safe.address 0x0F24Af6B7147aAEf00b216Cd38667256DC56755a --path /tmp/whatever --chainid 11155
111 --tls.ca certs/ca-cert.pem --tls.cert certs/server-cert.pem --tls.key certs/server-key.pem --rpc.url https://ethereum-sepolia.rpc.subquery.network/public --port.api 8443

And then it was confirmed that only client that are authenticated using a certificate can access the API:

> curl https://localhost:8443/api/healthcheck -k  --cert client-cert.pem --key client-key.pem
OK
> curl https://localhost:8443/api/healthcheck -k
curl: (56) OpenSSL SSL_read: OpenSSL/3.3.1: error:0A00045C:SSL routines::tlsv13 alert certificate required, errno 0

The files used in the previous command can be found below:
certs.zip

Metadata

@nodauf nodauf requested a review from a team as a code owner October 2, 2024 17:30
Copy link
Contributor

coderabbitai bot commented Oct 2, 2024

Walkthrough

The changes introduced in this pull request enhance the psp_executor package by adding support for mutual TLS (mTLS) in the HTTP API. This includes a new validation step in the configuration process, modifications to the CLI for TLS settings, and updates to the Defender struct to utilize these settings for secure communication. The integration of TLS enhances the security of both the service startup and API interactions, ensuring that only valid configurations are processed.

Changes

File Path Change Summary
op-defender/cmd/defender/cli.go Added a validation step in PSPExecutorMain to check configuration validity using cfg.Check().
op-defender/psp_executor/cli.go Added TLS configuration support: new import for optls, updated CLIConfig struct with TLSConfig, modified ReadCLIFlags, and added new TLS flags.
op-defender/psp_executor/defender.go Introduced mTLS support: added TLS-related imports, updated Defender struct with TLSConfig, modified Run method to use ListenAndServeTLS, and updated NewDefender function.
op-defender/psp_executor/README.md Updated documentation to include new TLS command-line options and modified curl command examples for API requests.

Assessment against linked issues

Objective Addressed Explanation
Implement mTLS support for the psp_executor HTTP API (Issue #77)
Ensure only authenticated users can make actions on the HTTP API (Issue #77)
Allow enabling/disabling mTLS via CLI flag (Issue #77) No CLI flag for enabling/disabling mTLS was added.

🐰 In the meadow, where the bunnies play,
New TLS features hop in today!
With mTLS, our paths are secure,
Only trusted friends, of that we're sure!
So let’s celebrate, with a joyful cheer,
For safe connections, we hold dear! 🌼✨


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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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.

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

🧹 Outside diff range and nitpick comments (3)
op-defender/psp_executor/cli.go (2)

102-119: Improve usage descriptions for TLS flags

The new TLS flags are added correctly. However, consider enhancing the Usage descriptions for clarity and consistency with existing flags.

Suggested changes:

 &cli.StringFlag{
     Name:    optls.TLSCaCertFlagName,
-    Usage:   "tls ca cert path",
+    Usage:   "TLS CA certificate file path",
     EnvVars: opservice.PrefixEnvVar(envPrefix, "TLS_CA"),
 },
 &cli.StringFlag{
     Name:    optls.TLSCertFlagName,
-    Usage:   "tls cert path",
+    Usage:   "TLS certificate file path",
     EnvVars: opservice.PrefixEnvVar(envPrefix, "TLS_CERT"),
 },
 &cli.StringFlag{
     Name:    optls.TLSKeyFlagName,
-    Usage:   "tls key",
+    Usage:   "TLS key file path",
     EnvVars: opservice.PrefixEnvVar(envPrefix, "TLS_KEY"),
 },

This improves readability and maintains consistency with the capitalization and descriptive style used in other flags.


102-119: Explicitly specify the Required field for TLS flags

Currently, the new TLS flags do not have the Required field specified. To enhance clarity, explicitly set Required: false since these flags are optional.

Example:

 &cli.StringFlag{
     Name:    optls.TLSCaCertFlagName,
     Usage:   "TLS CA certificate file path",
     EnvVars: opservice.PrefixEnvVar(envPrefix, "TLS_CA"),
+    Required: false,
 },

Apply the same addition to the TLSCertFlagName and TLSKeyFlagName flags.

op-defender/psp_executor/defender.go (1)

601-630: Consider allowing unauthenticated access to the health check endpoint

Currently, the server is configured to require mutual TLS authentication for all endpoints, including /api/healthcheck. This may prevent unauthenticated clients from accessing the health check endpoint, which is often needed for monitoring and health checks without authentication.

Consider configuring the server or implementing middleware to allow certain endpoints, like /api/healthcheck, to bypass mutual TLS authentication while keeping the rest of the API endpoints secured with mTLS.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 46b01e9 and fdb31a6.

📒 Files selected for processing (3)
  • op-defender/cmd/defender/cli.go (1 hunks)
  • op-defender/psp_executor/cli.go (4 hunks)
  • op-defender/psp_executor/defender.go (4 hunks)
🔇 Additional comments (7)
op-defender/cmd/defender/cli.go (2)

Line range hint 1-78: Verify mTLS implementation in related files

While this file now includes a validation step for the configuration, which is a positive change, the mTLS implementation mentioned in the PR objectives is not directly visible here.

To ensure that mTLS is properly implemented, let's examine related files:

#!/bin/bash
# Description: Search for mTLS-related code in the project

# Test 1: Search for mTLS configuration in Config struct
ast-grep --lang go --pattern 'type Config struct {
  $$$
  // Look for fields related to mTLS
  $_ $_
  $$$
}'

# Test 2: Search for mTLS setup in server initialization
rg --type go -A 10 'func New.*Server'

# Test 3: Search for mTLS-related flags
rg --type go 'cli\.StringFlag.*mTLS'

These checks will help verify that mTLS is properly configured and implemented across the project.


59-61: Approve: Good addition of configuration validation

The addition of the cfg.Check() call improves the robustness of the application by ensuring that only valid configurations are processed. This aligns well with the PR objectives of enhancing security and reliability.

Consider enhancing the error handling to provide more context:

 if err := cfg.Check(); err != nil {
-    return nil, err
+    return nil, fmt.Errorf("invalid configuration: %w", err)
 }

This will make debugging easier by providing more information about the nature of the configuration error.

To ensure that the cfg.Check() method includes all necessary validations, especially for mTLS, let's examine its implementation:

op-defender/psp_executor/cli.go (5)

5-5: Import statement for TLS configuration added correctly

The import of the optls package is necessary for TLS configuration and is appropriately included.


30-30: Addition of TLSConfig field to CLIConfig struct

The TLSConfig field is added to the CLIConfig struct to incorporate TLS settings, aligning with the objective of introducing mTLS authentication.


43-43: Initialize TLSConfig in ReadCLIFlags function

The TLSConfig field is properly initialized using optls.ReadCLIConfig(ctx), ensuring that TLS configurations are read from the CLI context.


50-50: Refactor CLIFlags function to use a local flags variable

Assigning the initial flags to a local variable flags allows for appending additional flags later, which is necessary for incorporating the new TLS flags.


123-128: Ensure TLSConfig.Check() handles optional TLS configuration

If mTLS is optional, verify that the Check() method of TLSConfig does not return an error when TLS settings are not provided.

Run the following script to confirm that the application initializes correctly without TLS configurations:

This ensures that the application remains functional when mTLS is not enabled, and TLSConfig.Check() handles the absence of TLS settings gracefully.

@Ethnical
Copy link
Collaborator

Ethnical commented Dec 4, 2024

Thanks a lot for the contribution @nodauf!
As discussed with you privately, it would be nice to have a documentation of the command in the current README -> https://github.com/ethereum-optimism/monitorism/blob/main/op-defender/psp_executor/README.md

I will try update the doc into the current branch if you can't?

@Ethnical
Copy link
Collaborator

Ethnical commented Jan 13, 2025

@nodauf are you able to push more about the documentation here, to make sure people can use and contrib easier would be perfect!
Let me know if not possible would be better to merge everything in the same time :)

@nodauf
Copy link
Contributor Author

nodauf commented Jan 13, 2025

Oh yeah, thanks for the reminder, I totally forgot.

@nodauf
Copy link
Contributor Author

nodauf commented Jan 13, 2025

@Ethnical @raffaele-oplabs I was finally able to finish the documentation :). Hope that's good. Feel free to tell if you need me to change anything.

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)
op-defender/psp_executor/README.md (3)

39-41: Add security context for TLS options.

Consider adding a note about the security implications and requirements for these certificates:

  • Explain that these are required for mTLS authentication
  • Mention that certificates should be properly secured
  • Add a reference to certificate generation instructions

81-81: Document certificate requirements for API requests.

The curl command shows client certificate usage but should include:

  1. Required certificate format (PEM, etc.)
  2. How to obtain valid client certificates
  3. Error responses for invalid certificates

130-132: Clarify TLS configuration requirements.

Please specify whether these TLS options are:

  1. Required or optional
  2. Their default values (if any)
  3. The behavior when partially configured
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fa9d06e and 6a5c7d2.

📒 Files selected for processing (1)
  • op-defender/psp_executor/README.md (4 hunks)

@@ -23,7 +23,7 @@ Settings of the HTTP API service:
To run the psp_executor service, you can use the following command:

```shell
go run ../cmd/defender psp_executor --privatekey 2a[..]c6 --safe.address 0x837DE453AD5F21E89771e3c06239d8236c0EFd5E --path /tmp/psps.json --chainid 11155111 --superchainconfig.address 0xC2Be75506d5724086DEB7245bd260Cc9753911Be --rpc.url http://localhost:8545 --port.api 8080
go run ../cmd/defender psp_executor --privatekey 2a[..]c6 --safe.address 0x837DE453AD5F21E89771e3c06239d8236c0EFd5E --path /tmp/psps.json --chainid 11155111 --superchainconfig.address 0xC2Be75506d5724086DEB7245bd260Cc9753911Be --rpc.url http://localhost:8545 --port.api 8080 --tls.ca certs/ca-cert.pem --tls.cert certs/server-cert.pem --tls.key certs/server-key.pem
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 security and readability of the example command.

  1. Replace the private key with a placeholder to prevent accidental exposure.
  2. Add line breaks for better readability.
-go run ../cmd/defender psp_executor --privatekey 2a[..]c6 --safe.address 0x837DE453AD5F21E89771e3c06239d8236c0EFd5E --path /tmp/psps.json --chainid 11155111 --superchainconfig.address 0xC2Be75506d5724086DEB7245bd260Cc9753911Be --rpc.url http://localhost:8545 --port.api 8080 --tls.ca certs/ca-cert.pem --tls.cert certs/server-cert.pem --tls.key certs/server-key.pem
+go run ../cmd/defender psp_executor \
+    --privatekey <your-private-key> \
+    --safe.address 0x837DE453AD5F21E89771e3c06239d8236c0EFd5E \
+    --path /tmp/psps.json \
+    --chainid 11155111 \
+    --superchainconfig.address 0xC2Be75506d5724086DEB7245bd260Cc9753911Be \
+    --rpc.url http://localhost:8545 \
+    --port.api 8080 \
+    --tls.ca certs/ca-cert.pem \
+    --tls.cert certs/server-cert.pem \
+    --tls.key certs/server-key.pem
📝 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
go run ../cmd/defender psp_executor --privatekey 2a[..]c6 --safe.address 0x837DE453AD5F21E89771e3c06239d8236c0EFd5E --path /tmp/psps.json --chainid 11155111 --superchainconfig.address 0xC2Be75506d5724086DEB7245bd260Cc9753911Be --rpc.url http://localhost:8545 --port.api 8080 --tls.ca certs/ca-cert.pem --tls.cert certs/server-cert.pem --tls.key certs/server-key.pem
go run ../cmd/defender psp_executor \
--privatekey <your-private-key> \
--safe.address 0x837DE453AD5F21E89771e3c06239d8236c0EFd5E \
--path /tmp/psps.json \
--chainid 11155111 \
--superchainconfig.address 0xC2Be75506d5724086DEB7245bd260Cc9753911Be \
--rpc.url http://localhost:8545 \
--port.api 8080 \
--tls.ca certs/ca-cert.pem \
--tls.cert certs/server-cert.pem \
--tls.key certs/server-key.pem

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.

Feature: mTLS support for the psp_executor HTTP API into op-defender
2 participants