Skip to content

Conversation

cnlangzi
Copy link
Member

@cnlangzi cnlangzi commented Jan 23, 2025

Changed

  • used Optional pattern in hsts.Enable

Fixed

Added

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

Enhancements:

  • Change the Enable function signature to accept a variadic number of options.

Copy link

sourcery-ai bot commented Jan 23, 2025

Reviewer's Guide by Sourcery

This pull request refactors the hsts.Enable function to use the functional options pattern, providing a more flexible and readable way to configure the HSTS middleware.

Sequence diagram for HSTS middleware configuration

sequenceDiagram
    participant C as Client
    participant M as HSTS Middleware
    participant H as HTTP Handler

    C->>M: HTTP Request
    activate M
    alt TLS not enabled & (GET or HEAD)
        M->>M: Configure HSTS headers
        Note over M: Apply MaxAge
        Note over M: Apply IncludeSubDomains
        Note over M: Apply Preload
        M->>C: Redirect to HTTPS
    else
        M->>H: Forward Request
        H->>C: Response
    end
    deactivate M
Loading

Class diagram for HSTS configuration changes

classDiagram
    class Config {
        +int64 MaxAge
        +bool IncludeSubDomains
        +bool Preload
    }

    class Option {
        <<interface>>
        +func(c *Config)
    }

    Option ..> Config : modifies

    note for Config "New configuration struct"
    note for Option "New functional options pattern"
Loading

File-Level Changes

Change Details Files
Refactor hsts.Enable to use functional options pattern.
  • The Enable function now accepts a variadic list of Option functions.
  • A new Config struct was introduced to hold the HSTS configuration.
  • Default values for MaxAge, IncludeSubDomains, and Preload are set in the Enable function.
  • The Option functions (WithMaxAge, WithDomains, WithPreload) are used to modify the Config struct.
  • The test cases were updated to use the new functional options pattern.
ext/hsts/hsts.go
ext/hsts/hsts_test.go
ext/hsts/option.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

@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 - here's some feedback:

Overall Comments:

  • The PR changes default values for includeSubDomains and preload to true, which is a breaking change. Consider either keeping the old defaults or documenting this change prominently in the changelog.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟡 Security: 2 issues found
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 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 21 to 25
cfg := &Config{
MaxAge: defaultMaxAge,
IncludeSubDomains: true,
Preload: true,
}
Copy link

Choose a reason for hiding this comment

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

🚨 suggestion (security): Consider making IncludeSubDomains and Preload false by default

These are strong security settings that can have significant implications. Preloading in particular is difficult to undo and should be an explicit opt-in choice.

Suggested change
cfg := &Config{
MaxAge: defaultMaxAge,
IncludeSubDomains: true,
Preload: true,
}
cfg := &Config{
MaxAge: defaultMaxAge,
IncludeSubDomains: false,
Preload: false,
}

//
// The maximum age specifies the duration for which the HSTS policy is in effect.
// Note that the maximum age is specified in seconds, so "1h" would be equivalent to 3600.
func WithMaxAge(t time.Duration) Option {
Copy link

Choose a reason for hiding this comment

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

🚨 suggestion (security): Add validation for MaxAge to ensure it's within browser-accepted limits

Most browsers have maximum limits for the HSTS max-age (e.g., Chrome limits it to 2 years). Consider adding validation to prevent compatibility issues.

Suggested implementation:

}

// maxHSTSAge is the maximum allowed duration for HSTS (2 years, matching browser limits)
const maxHSTSAge = 2 * 365 * 24 * time.Hour

// Option is a function that modifies a Config instance.
// WithMaxAge sets the maximum age for the HSTS policy.
//
// The maximum age specifies the duration for which the HSTS policy is in effect.
// Note that the maximum age is specified in seconds, so "1h" would be equivalent to 3600.
// The maximum allowed duration is 2 years (63072000 seconds) to ensure browser compatibility.
func WithMaxAge(t time.Duration) Option {
	return func(c *Config) {
		if t <= 0 {
			return
		}
		if t > maxHSTSAge {
			t = maxHSTSAge
		}
		c.MaxAge = int64(t / time.Second)


import "time"

// Config represents the configuration options for HSTS (HTTP Strict Transport Security).
Copy link

Choose a reason for hiding this comment

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

issue (complexity): Consider using a constructor function instead of the functional options pattern to simplify the configuration logic and reduce code size.

The functional options pattern adds unnecessary complexity for this simple configuration. Consider using a constructor function instead:

// NewConfig creates a new HSTS configuration with the specified parameters.
// Pass 0 for maxAge to use the default duration.
func NewConfig(maxAge time.Duration, includeSubDomains bool, preload bool) Config {
    c := Config{
        IncludeSubDomains: includeSubDomains,
        Preload:           preload,
    }
    if maxAge > 0 {
        c.MaxAge = int64(maxAge / time.Second)
    }
    return c
}

This approach:

  • Reduces code size by ~80% while maintaining all functionality
  • Keeps the validation logic for maxAge
  • Makes the API just as clear at the call site
  • Is easier to understand and maintain

Usage remains simple: cfg := NewConfig(time.Hour, true, false)

Copy link

codecov bot commented Jan 23, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 90.53%. Comparing base (7a7fb40) to head (4facee3).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #30      +/-   ##
==========================================
+ Coverage   90.39%   90.53%   +0.14%     
==========================================
  Files          36       37       +1     
  Lines        1260     1279      +19     
==========================================
+ Hits         1139     1158      +19     
  Misses         84       84              
  Partials       37       37              
Flag Coverage Δ
Unit-Tests 90.53% <100.00%> (+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.

Copy link

deepsource-io bot commented Jan 23, 2025

Here's the code health analysis summary for commits 7a7fb40..4facee3. 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.

@cnlangzi cnlangzi merged commit 87e3e56 into main Jan 23, 2025
7 checks passed
@cnlangzi cnlangzi deleted the fix/hsts branch January 23, 2025 15:22
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