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

Summary by CodeRabbit

  • New Features

    • Introduced TLS configuration support in the CLI, enhancing security and flexibility.
    • Added mutual TLS (mTLS) capabilities for secure client-server communication in the API server.
  • Bug Fixes

    • Implemented validation checks for configuration settings to ensure only valid configurations are processed.

@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 modifications to the CLI configuration for TLS settings, validation of configurations, and updates to the Defender struct to utilize these settings for secure communication. A new validation step ensures that configurations are checked before execution, improving the robustness of the application.

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

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:

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

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