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(ext): added hsts middleware #29

Merged
merged 5 commits into from
Jan 23, 2025
Merged

feat(ext): added hsts middleware #29

merged 5 commits into from
Jan 23, 2025

Conversation

cnlangzi
Copy link
Member

@cnlangzi cnlangzi commented Jan 23, 2025

Changed

Fixed

Added

  • added hsts middleware

Tests

Tasks to complete before merging PR:

  • Ensure unit tests are passing. If not run make unit-test to check for any regressions 📋
  • Ensure lint tests are passing. if not run make lint to check for any issues
  • Ensure codecov/patch is passing for changes.

Summary by Sourcery

New Features:

  • Added HSTS middleware to enforce HTTPS connections.

Copy link

sourcery-ai bot commented Jan 23, 2025

Reviewer's Guide by Sourcery

This pull request introduces a new HSTS middleware that redirects HTTP requests to HTTPS and sets the Strict-Transport-Security header. The middleware is configurable with options for max-age, includeSubDomains, and preload.

Sequence diagram for HSTS middleware HTTP to HTTPS redirection

sequenceDiagram
    participant Client
    participant HSTS
    participant Server

    Client->>HSTS: HTTP Request
    alt is HTTP and GET/HEAD
        HSTS->>HSTS: Check X-Forwarded-Proto
        HSTS->>HSTS: Generate HTTPS URL
        HSTS->>HSTS: Set Strict-Transport-Security header
        HSTS-->>Client: 302 Redirect to HTTPS
    else is HTTPS
        HSTS->>Server: Forward Request
        Server-->>Client: Response
    end
Loading

Class diagram for HSTS middleware

classDiagram
    class HSTS {
        +Enable(maxAge time.Duration, includeSubdomains bool, preload bool) xun.Middleware
        -stripPort(hostPort string) string
    }
    note for HSTS "Middleware for enforcing HTTPS
and setting HSTS headers"

    class xun.Middleware {
        <<interface>>
        +HandleFunc(next xun.HandleFunc) xun.HandleFunc
    }

    HSTS ..> xun.Middleware : implements
Loading

Flow diagram for HSTS middleware decision process

flowchart TD
    A[Request] --> B{Check Protocol}
    B -->|HTTP| C{Check Method}
    B -->|HTTPS| D[Forward to Next Handler]
    C -->|GET/HEAD| E[Generate HTTPS URL]
    C -->|Other| D
    E --> F[Set HSTS Header]
    F --> G[Redirect to HTTPS]

    style A fill:#f9f,stroke:#333,stroke-width:2px
    style D fill:#9f9,stroke:#333,stroke-width:2px
    style G fill:#f99,stroke:#333,stroke-width:2px
Loading

File-Level Changes

Change Details Files
Added HSTS middleware to enforce HTTPS and set security headers.
  • Created a new hsts package with Enable middleware function.
  • Implemented logic to redirect HTTP requests to HTTPS.
  • Added functionality to set Strict-Transport-Security header with configurable max-age, includeSubDomains, and preload options.
  • Added unit tests for the middleware, covering various configurations and scenarios.
ext/hsts/hsts.go
ext/hsts/hsts_test.go
Removed the old middleware test and added a new one.
  • Removed the old middleware test from app_test.go.
  • Added a new middleware test to middleware_test.go.
app_test.go
middleware_test.go

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

deepsource-io bot commented Jan 23, 2025

Here's the code health analysis summary for commits 84b8b6b..b7dcc6c. View details on DeepSource ↗.

Analysis Summary

AnalyzerStatusSummaryLink
DeepSource Go LogoGo✅ SuccessView Check ↗

💡 If you’re a repository administrator, you can configure the quality gates from the settings.

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @cnlangzi - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟡 Security: 1 issue found
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

ext/hsts/hsts.go Outdated Show resolved Hide resolved
ext/hsts/hsts.go Outdated Show resolved Hide resolved
Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @cnlangzi - I've reviewed your changes and found some issues that need to be addressed.

Blocking issues:

  • The HTTPS redirection logic appears incorrect - it's redirecting when already on HTTPS, which could cause an infinite redirect loop. (link)
Here's what I looked at during the review
  • 🔴 General issues: 1 blocking issue
  • 🟡 Security: 1 issue found
  • 🟡 Testing: 1 issue found
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

ext/hsts/hsts.go Outdated Show resolved Hide resolved
ext/hsts/hsts.go Outdated

isHTTPS := false
// Check X-Forwarded-Proto header first
forwardedProto := r.Header.Get("X-Forwarded-Proto")
Copy link

Choose a reason for hiding this comment

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

🚨 issue (security): The X-Forwarded-Proto header should only be trusted from known proxy IPs to prevent spoofing.

Consider adding a configuration option to specify trusted proxy IPs and only accept the X-Forwarded-Proto header from these addresses.

"github.com/yaitoo/xun"
)

func TestHstsMiddleware(t *testing.T) {
Copy link

Choose a reason for hiding this comment

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

suggestion (testing): Suggest adding tests for HTTPS requests.

It appears that the tests primarily focus on HTTP to HTTPS redirection. It's important to also verify the behavior when a request is already made over HTTPS. Specifically, ensure that the HSTS header is correctly set and that no redirection occurs in this scenario.

Suggested implementation:

func TestHstsMiddleware(t *testing.T) {
	tests := []struct {
		name           string
		scheme         string
		expectedStatus int
		checkRedirect bool
		checkHSTS     bool
	}{
		{
			name:           "HTTP request should redirect to HTTPS",
			scheme:         "http",
			expectedStatus: http.StatusMovedPermanently,
			checkRedirect: true,
			checkHSTS:     false,
		},
		{
			name:           "HTTPS request should include HSTS header",
			scheme:         "https",
			expectedStatus: http.StatusOK,
			checkRedirect: false,
			checkHSTS:     true,
		},
	}

	tr := http.DefaultTransport.(*http.Transport).Clone()
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			c := http.Client{
				Transport: tr,
				CheckRedirect: func(req *http.Request, via []*http.Request) error {
					return http.ErrUseLastResponse
				},
			}

			server := httptest.NewTLSServer(xun.HSTS(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				w.WriteHeader(http.StatusOK)
			})))
			defer server.Close()

			serverURL, _ := url.Parse(server.URL)
			req, _ := http.NewRequest("GET", fmt.Sprintf("%s://%s", tt.scheme, serverURL.Host), nil)

			resp, err := c.Do(req)
			require.NoError(t, err)
			defer resp.Body.Close()

			require.Equal(t, tt.expectedStatus, resp.StatusCode)

			if tt.checkRedirect {
				location := resp.Header.Get("Location")
				require.True(t, strings.HasPrefix(location, "https://"))
			}

			if tt.checkHSTS {
				hstsHeader := resp.Header.Get("Strict-Transport-Security")
				require.NotEmpty(t, hstsHeader)
				require.Contains(t, hstsHeader, "max-age=")
			}
		})
	}

You'll need to add these imports if they're not already present:

  • "fmt"
  • "net/http"
  • "crypto/tls"
  • "context"
  • "net"

The test now uses a table-driven approach to test both HTTP and HTTPS scenarios. For the HTTPS case, it verifies:

  1. The response status is 200 OK (no redirect)
  2. The HSTS header is present
  3. The HSTS header contains the required max-age directive

You may need to adjust the expected status codes and header values based on your specific HSTS middleware implementation.

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @cnlangzi - I've reviewed your changes and found some issues that need to be addressed.

Blocking issues:

  • The X-Forwarded-Proto header should only be trusted from known proxies (link)
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🔴 Security: 1 blocking issue
  • 🟡 Testing: 1 issue found
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

ext/hsts/hsts.go Outdated
Comment on lines 38 to 40
forwardedProto := r.Header.Get("X-Forwarded-Proto")
if forwardedProto != "" {
isHTTPS = forwardedProto == "https"
Copy link

Choose a reason for hiding this comment

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

🚨 issue (security): The X-Forwarded-Proto header should only be trusted from known proxies

Consider adding validation to ensure this header is only processed when coming from trusted proxy IPs. Otherwise, malicious clients could bypass HTTPS enforcement by spoofing this header.

"github.com/yaitoo/xun"
)

func TestHstsMiddleware(t *testing.T) {
Copy link

Choose a reason for hiding this comment

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

suggestion (testing): Suggest adding tests for different HTTP methods.

The current tests only cover GET requests. It would be beneficial to add tests for other HTTP methods like POST, PUT, DELETE, etc., to ensure the middleware behaves correctly in all scenarios. For non-GET/HEAD requests, the middleware should not redirect and HSTS header should not be set.

Suggested implementation:

func TestHstsMiddleware(t *testing.T) {
	testCases := []struct {
		name           string
		method         string
		expectedStatus int
		shouldRedirect bool
		shouldHaveHSTS bool
	}{
		{
			name:           "GET request",
			method:         http.MethodGet,
			expectedStatus: http.StatusOK,
			shouldRedirect: true,
			shouldHaveHSTS: true,
		},
		{
			name:           "HEAD request",
			method:         http.MethodHead,
			expectedStatus: http.StatusOK,
			shouldRedirect: true,
			shouldHaveHSTS: true,
		},
		{
			name:           "POST request",
			method:         http.MethodPost,
			expectedStatus: http.StatusOK,
			shouldRedirect: false,
			shouldHaveHSTS: false,
		},
		{
			name:           "PUT request",
			method:         http.MethodPut,
			expectedStatus: http.StatusOK,
			shouldRedirect: false,
			shouldHaveHSTS: false,
		},
		{
			name:           "DELETE request",
			method:         http.MethodDelete,
			expectedStatus: http.StatusOK,
			shouldRedirect: false,
			shouldHaveHSTS: false,
		},
	}

	tr := http.DefaultTransport.(*http.Transport).Clone()

You'll also need to:

  1. Modify the test implementation to iterate over the test cases
  2. Create requests using the specified method for each test case
  3. Add assertions to verify:
    • Redirect behavior based on shouldRedirect
    • HSTS header presence based on shouldHaveHSTS
    • Expected status code

The exact implementation will depend on how the rest of the test is structured, but the test cases provide a framework for comprehensive HTTP method testing.

Copy link

codecov bot commented Jan 23, 2025

Codecov Report

Attention: Patch coverage is 96.55172% with 1 line in your changes missing coverage. Please review.

Project coverage is 90.39%. Comparing base (84b8b6b) to head (b7dcc6c).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
ext/hsts/hsts.go 96.55% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #29      +/-   ##
==========================================
+ Coverage   90.25%   90.39%   +0.14%     
==========================================
  Files          35       36       +1     
  Lines        1231     1260      +29     
==========================================
+ Hits         1111     1139      +28     
- Misses         83       84       +1     
  Partials       37       37              
Flag Coverage Δ
Unit-Tests 90.39% <96.55%> (+0.14%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@cnlangzi cnlangzi merged commit 7a7fb40 into main Jan 23, 2025
7 checks passed
@cnlangzi cnlangzi deleted the feat/hsts branch January 23, 2025 14:00
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