Skip to content

🔥 feat: Host auth middleware #4199

Open
mutantkeyboard wants to merge 26 commits intogofiber:mainfrom
mutantkeyboard:host_auth_middleware
Open

🔥 feat: Host auth middleware #4199
mutantkeyboard wants to merge 26 commits intogofiber:mainfrom
mutantkeyboard:host_auth_middleware

Conversation

@mutantkeyboard
Copy link
Copy Markdown
Contributor

@mutantkeyboard mutantkeyboard commented Apr 8, 2026

Description

Add a new hostauthorization middleware that validates the incoming Host header against a configurable allowlist, rejecting unauthorized hosts with 403 Forbidden. This protects against DNS rebinding attacks
where an attacker-controlled domain resolves to the application's internal IP, causing browsers to send requests with a malicious Host header.

The middleware supports exact host matching, subdomain wildcards (.myapp.com), and CIDR ranges (10.0.0.0/8), with an optional dynamic validator function for runtime host resolution. It complements the Domain()
router (#4100) — Domain() handles host-based routing while hostauthorization acts as a security gate.

Fixes #4148

Changes introduced

  • Benchmarks: 3 benchmarks included (exact match, CIDR, mixed rules). All ~3,200 ns/op with 25 allocs on Apple M5.
  • Documentation Update: Added docs/middleware/hostauthorization.md with full usage guide, config reference, matching semantics, normalization rules, proxy support, and RFC compliance notes.
  • Changelog/What's New: New hostauthorization middleware — DNS rebinding protection via Host header validation with exact match, subdomain wildcard, and CIDR support.
  • Migration Guide: N/A — new middleware, no breaking changes.
  • API Alignment with Express: Modeled after host-validation (closest Express ecosystem equivalent). AllowedHosts/AllowedHostsFunc mirrors the AllowOrigins/AllowOriginsFunc pattern from the existing cors
    middleware. Next, ErrorHandler follow established Fiber conventions.
  • API Longevity: Minimal API surface (4 config fields). String-based allowlists and callback escape hatches — same patterns Rails has used since Rails 6 (2019) without breaking changes. No external
    dependencies, no state, no caching.
  • Examples: Usage examples covering basic protection, subdomain wildcards, CIDR ranges, health check exclusion, dynamic validation, custom error responses, and combined usage with Domain() router.

Type of change

Please delete options that are not relevant.

  • New feature (non-breaking change which adds functionality)
  • Enhancement (improvement to existing features and functionality)
  • Documentation update (changes to documentation)
  • Performance improvement (non-breaking change which improves efficiency)
  • Code consistency (non-breaking change which improves code reliability and robustness)

Checklist

Before you submit your pull request, please make sure you meet these requirements:

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

Commit formatting

Please use emojis in commit messages for an easy way to identify the purpose or intention of a commit. Check out the emoji cheatsheet here: CONTRIBUTING.md

@mutantkeyboard mutantkeyboard requested a review from a team as a code owner April 8, 2026 09:04
@welcome
Copy link
Copy Markdown

welcome Bot commented Apr 8, 2026

Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 8, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds a new hostauthorization middleware: implementation, configuration, documentation, README index entry, and comprehensive tests/benchmarks that enforce Host header allowlisting (exact, leading-dot wildcard, CIDR, dynamic validator) and rejection via a configurable error handler.

Changes

Cohort / File(s) Summary
Docs / README
/.github/README.md, docs/middleware/hostauthorization.md
Added README index row and a full middleware docs page describing func New(config ...Config) fiber.Handler, config fields, matching semantics (exact, leading-dot wildcard, CIDR), host normalization, proxy behavior, examples, and error handling.
Config
middleware/hostauthorization/config.go
New Config type (Next, AllowedHosts, AllowedHostsFunc, ErrorHandler), exported sentinel ErrForbiddenHost, ConfigDefault, and runtime validation/default injection (panics if neither AllowedHosts nor AllowedHostsFunc set).
Implementation
middleware/hostauthorization/hostauthorization.go
Added New(config ...Config) fiber.Handler that pre-parses AllowedHosts into exact names, leading-dot wildcard suffixes, and CIDR ranges (invalid CIDRs panic). Runtime: Next skip, hostname normalization (strip port/IPv6 brackets/trailing dot, lowercase), exact/wildcard/CIDR matching, fallback to AllowedHostsFunc, deny via ErrorHandler with ErrForbiddenHost.
Tests & Benchmarks
middleware/hostauthorization/hostauthorization_test.go
Extensive unit, integration, and benchmark tests covering config validation and panics, host normalization, exact/wildcard/CIDR/IP matches (v4/v6), dynamic allow-fn, Next bypass, TrustProxy + X-Forwarded-Host behavior, custom error handler, and performance microbenchmarks and end-to-end benchmarks.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client as Client
  participant App as Fiber App
  participant HA as HostAuthorization
  participant Store as AllowedHostsStore
  participant Func as AllowedHostsFunc
  participant Err as ErrorHandler

  Client->>App: HTTP request (Host header)
  App->>HA: invoke middleware
  HA->>HA: normalize Host (strip port/brackets/trailing dot, lowercase)
  HA->>Store: check exact / wildcard / CIDR matches
  alt matched
    Store-->>HA: allowed
    HA->>App: c.Next() -> downstream handler
  else not matched
    HA->>Func: if configured, call AllowedHostsFunc(host)
    alt func returns true
      Func-->>HA: allowed
      HA->>App: c.Next() -> downstream handler
    else
      HA->>Err: call ErrorHandler(c, ErrForbiddenHost)
      Err-->>Client: 403 Forbidden (or custom response)
    end
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • ReneWerner87
  • sixcolors
  • efectn

Poem

🐇 I hop through headers, trim brackets and dots,
I check wildcards, CIDRs, and exact little spots,
If hosts are true I let them pass on through,
If naughty hosts knock, I say “403, shoo!” 🥕

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.41% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title uses an emoji and vague phrasing that doesn't clearly convey the specific feature being added. Consider a more descriptive title like 'Add hostauthorization middleware for DNS rebinding protection' that conveys the feature without relying on emoji.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The pull request description comprehensively covers all required template sections including problem statement, changes introduced, type of change, and a complete checklist with detailed explanations.
Linked Issues check ✅ Passed The pull request fully addresses all requirements from issue #4148: DNS rebinding protection via Host header validation, exact/wildcard/CIDR matching, port stripping, X-Forwarded-Host support, 403 response codes, and stable minimal API.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing the hostauthorization middleware feature: configuration, implementation, documentation, tests, and README entry. No extraneous modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@ReneWerner87 ReneWerner87 added this to v3 Apr 8, 2026
@ReneWerner87 ReneWerner87 added this to the v3 milestone Apr 8, 2026
@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 8, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.28%. Comparing base (ce8d2a9) to head (32c78a6).
⚠️ Report is 11 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4199      +/-   ##
==========================================
+ Coverage   91.22%   91.28%   +0.05%     
==========================================
  Files         123      125       +2     
  Lines       11892    11971      +79     
==========================================
+ Hits        10849    10928      +79     
  Misses        655      655              
  Partials      388      388              
Flag Coverage Δ
unittests 91.28% <100.00%> (+0.05%) ⬆️

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.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a new hostauthorization middleware for Fiber v3, designed to protect against DNS rebinding attacks by validating the Host header against an allowlist of exact domains, subdomain wildcards, and CIDR ranges. The implementation includes comprehensive documentation and tests. Feedback focuses on making the configuration initialization more idiomatic for the Fiber framework and optimizing the performance of subdomain matching by pre-storing wildcard suffixes with their leading dots to avoid allocations during request processing.

Comment thread middleware/hostauthorization/config.go
Comment thread middleware/hostauthorization/hostauthorization.go Outdated
Comment thread middleware/hostauthorization/hostauthorization.go Outdated
Copy link
Copy Markdown
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: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/middleware/hostauthorization.md`:
- Around line 63-79: The CIDR Ranges doc misleadingly describes source-IP
filtering; update the wording to clarify that hostauthorization checks the
request Host header against AllowedHosts (not the client's IP). Edit the
examples and comments around hostauthorization.New and hostauthorization.Config
AllowedHosts entries to say things like "allowed Host header IP range" or "Host
header value" instead of "internal network" or "respond to requests from known
IP ranges" so readers understand this matches Host header strings/CIDR-like IPs
in the Host header only.

In `@middleware/hostauthorization/config.go`:
- Around line 13-41: Add the missing Exclude hook to the public Config by
declaring a field Exclude func(c fiber.Ctx) bool (optional, default nil) next to
Next and ErrorHandler in the Config struct; update the middleware code path that
currently checks Next to also call Exclude (both should be evaluated before any
host validation/AllowedHosts/AllowedHostsFunc logic) and treat a true return
from Exclude as a signal to skip host validation and not invoke ErrorHandler.
Ensure the field name is exactly Exclude and that callers can provide it the
same way as Next/ErrorHandler.

In `@middleware/hostauthorization/hostauthorization.go`:
- Around line 24-45: Normalize each configured host string using normalizeHost()
before any checks and storage: call normalizeHost(h) (after trimming) and skip
if it becomes empty; for CIDR parsing still use the normalized value for
net.ParseCIDR and append the result to parsed.cidrNets; for wildcard entries
(case strings.HasPrefix(h, ".")) store the suffix without the leading dot from
the normalized value into parsed.wildcardSuffixes; for exact matches insert the
normalized host into parsed.exact. Ensure all references use the normalized host
variable so comparisons match request hosts.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: abe37dce-637a-44c8-80d2-c96bfa96bba2

📥 Commits

Reviewing files that changed from the base of the PR and between 631e77d and 4b45ec9.

📒 Files selected for processing (5)
  • .github/README.md
  • docs/middleware/hostauthorization.md
  • middleware/hostauthorization/config.go
  • middleware/hostauthorization/hostauthorization.go
  • middleware/hostauthorization/hostauthorization_test.go

Comment thread docs/middleware/hostauthorization.md
Comment thread middleware/hostauthorization/config.go
Comment thread middleware/hostauthorization/hostauthorization.go
@ReneWerner87
Copy link
Copy Markdown
Member

Thanks for the contribution @mutantkeyboard , DNS rebinding protection is a valid concern and I appreciate the thorough work on docs and tests.

Before we move forward, I want to raise a design question: should this be a standalone middleware or an extension of the existing Domain() router?

Domain() already matches requests by host pattern at the routing level. Adding an allowlist/deny semantic there (e.g. app.SetAllowedHosts(...)) would:

  • Avoid the overhead of an extra handler in the middleware chain on every request
  • Make the relationship between host-based routing and host-based security explicit
  • Keep host logic in one place instead of two separate systems

If we do keep it as a standalone middleware, a few things need addressing:

Performance

  • ~3,200 ns/op with 25 allocations is too high for a middleware that runs on every request. The core of this is a map lookup + a few string comparisons, that should be near-zero alloc. The wildcard suffixes should be stored with the leading dot at init time (as already flagged in reviews), and normalizeHost() should be applied to config values at init, not just at request time.
    You can use the utils package or existing functions from the other middlewares

API / Consistency

  • Missing Exclude field , our other middlewares expose this hook, and this one should too for consistency.
  • normalizeHost() not applied to configured hosts during init - this can lead to subtle mismatches (e.g. MyApp.com in config vs myapp.com at runtime).

Documentation

  • The CIDR section reads like source-IP filtering ("respond to requests from known IP ranges"). This needs to clearly state it matches the Host header value, not the client IP. As written, someone could deploy this thinking they have IP-based access control, which
    would be a security misunderstanding.

Scope question

  • CIDR matching on the Host header is a fairly niche use case; in practice, Host headers rarely contain raw IPs outside of internal tooling. Is the complexity worth it, or would exact match + subdomain wildcards cover 99% of real-world usage?

I'd like to hear your thoughts on the Domain() integration angle before we iterate further on the middleware approach. Either way, the normalization logic and test coverage you've built here is solid and would carry over.

@mutantkeyboard
Copy link
Copy Markdown
Contributor Author

Hey @ReneWerner87, thank you for the review.

Regarding Domain() integration

I'm genuinely curious what did you have in mind there. My original inspiration for this was brannondorsey/host-validation, which is explicitly a standalone
middleware for DNS rebinding protection on Express. The pattern just felt like a natural fit here too — Domain() is opt-in per route and calls c.Next() on non-match, so it doesn't have global reject
semantics. CIDR and leading-dot wildcards would also need special-casing since parseDomainPattern doesn't support either today. That said, if you see a clean way to integrate it without blurring routing and
access control, I'm open to it.

Performance

The 3,200 ns/op and 25 allocations are from app.Test()

  • that overhead belongs to Fiber's request pipeline, not this middleware per se. The actual per-request cost is a map lookup, a couple of string ops, and one real alloc: the "."+suffix concat in the wildcard path. Fixing that (storing the leading dot at init) plus switching to utilsstrings.ToLower in normalizeHost gets the common path to near-zero alloc.
    I'm more than happy to add a lower-level benchmark that isolates just the matching logic so the numbers are less misleading.

normalizeHost at init

This one is actually a good catch - config entries with trailing dots won't match runtime-normalized hosts. Easy fix.

CIDR docs

This is actually a fair point. I can fix the wording to make clear it's matching the Host header value, not the client IP.

But regarding the overall architecture, I can integrate it into the existing Domain() or leave it as a separate middlware. It's really up to you and @gaby

WDYT?

@ReneWerner87
Copy link
Copy Markdown
Member

ok

Go ahead with the leading-dot fix at init + normalizeHost on config entries, that alone should clean up the hot path nicely. And yes, please add an isolated benchmark for just the matching logic so we have real numbers for the middleware cost without app.Test() noise.
Fix the CIDR docs wording as discussed.
On CIDR scope: keep it for now. It's not a lot of extra code and internal tooling with IP-based hosts is a real enough use case. We can always revisit if it causes maintenance headaches down the line.

pls also try the utils functions for the better performance

@mutantkeyboard
Copy link
Copy Markdown
Contributor Author

mutantkeyboard commented Apr 9, 2026

@ReneWerner87, am I crazy or it seems like fasthttp 1.7.0 has broken multiple packages with stuff like Host header in HTTP/1.1 , fs.FS handling and Cache-Control?

Copy link
Copy Markdown
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 (1)
middleware/hostauthorization/hostauthorization_test.go (1)

288-309: Add explicit Exclude integration coverage for parity.

This file validates Next bypass behavior, but there’s no explicit integration test for Exclude. Adding one would lock in the agreed middleware parity requirement and prevent regressions.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@middleware/hostauthorization/hostauthorization_test.go` around lines 288 -
309, Add a parallel integration test mirroring Test_HostAuthorization_Next to
exercise the Exclude hook: create Test_HostAuthorization_Exclude, spin up a
fiber app, register the middleware with AllowedHosts set to ["example.com"] and
Exclude set to a function that returns true for c.Path() == "/healthz", register
a GET /healthz handler that returns "OK", then send a request with req.Host =
"evil.com" to "/healthz" and assert the response status is 200; use the same
patterns (t.Parallel(), app.Use(New(Config{Exclude: ...})), and app.Test(...))
so it verifies Exclude bypass parity.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@middleware/hostauthorization/hostauthorization_test.go`:
- Around line 262-266: The test currently uses require.Error(t, err) which is
too generic; tighten the assertion to verify the failure is specifically the
Host-header rejection from app.Test by replacing require.Error(t, err) with a
targeted check such as require.ErrorContains(t, err, "host") or
require.ErrorContains(t, err, "missing Host") (or use require.ErrorIs with the
fasthttp specific error if available) so the test asserts the expected
Host-header rejection signal from app.Test rather than any error.

---

Nitpick comments:
In `@middleware/hostauthorization/hostauthorization_test.go`:
- Around line 288-309: Add a parallel integration test mirroring
Test_HostAuthorization_Next to exercise the Exclude hook: create
Test_HostAuthorization_Exclude, spin up a fiber app, register the middleware
with AllowedHosts set to ["example.com"] and Exclude set to a function that
returns true for c.Path() == "/healthz", register a GET /healthz handler that
returns "OK", then send a request with req.Host = "evil.com" to "/healthz" and
assert the response status is 200; use the same patterns (t.Parallel(),
app.Use(New(Config{Exclude: ...})), and app.Test(...)) so it verifies Exclude
bypass parity.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 32515b96-3acc-427e-a678-e2573add4fa0

📥 Commits

Reviewing files that changed from the base of the PR and between 698e01b and cf7f9ce.

📒 Files selected for processing (1)
  • middleware/hostauthorization/hostauthorization_test.go

Comment thread middleware/hostauthorization/hostauthorization_test.go Outdated
@gaby
Copy link
Copy Markdown
Member

gaby commented Apr 9, 2026

@ReneWerner87, am I crazy or it seems like fasthttp 1.7.0 has broken multiple packages with stuff like Host header in HTTP/1.1 , fs.FS handling and Cache-Control?

@ReneWerner87 @mutantkeyboard the PR for fasthttp was merged with failing tests. They added a bunch of security fixes that conflict with our security checks.

@gaby gaby changed the title 🔥 Feature: Host auth middleware 🔥 feat: Host auth middleware Apr 11, 2026
@gaby
Copy link
Copy Markdown
Member

gaby commented Apr 11, 2026

@mutantkeyboard Test failures are now related to the new middleware.

@mutantkeyboard
Copy link
Copy Markdown
Contributor Author

mutantkeyboard commented Apr 13, 2026

@gaby - I will fix that today

Copy link
Copy Markdown
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

♻️ Duplicate comments (1)
middleware/hostauthorization/hostauthorization_test.go (1)

275-279: ⚠️ Potential issue | 🟡 Minor

Tighten the empty-host error branch assertion.

On Lines 276-277, returning on any error can make this test pass for unrelated failures. Assert the expected Host-related failure before returning.

Suggested fix
 	resp, err := app.Test(req)
 	if err != nil {
+		require.ErrorContains(t, err, "Host")
 		return
 	}
 	require.Equal(t, fiber.StatusForbidden, resp.StatusCode)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@middleware/hostauthorization/hostauthorization_test.go` around lines 275 -
279, The test currently returns on any non-nil error from app.Test(req), which
can mask unrelated failures; modify the app.Test(req) error branch to assert the
error is the expected host-related failure (e.g., using require.ErrorContains(t,
err, "host" or "empty host") or an equivalent check against the Host validation
error) before returning, then keep the existing require.Equal(t,
fiber.StatusForbidden, resp.StatusCode) assertion for the response path;
reference the app.Test call and the err variable when adding the
failure-specific assertion.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@middleware/hostauthorization/hostauthorization_test.go`:
- Around line 455-457: The test currently calls require.ErrorIs inside the
ErrorHandler closure; move that assertion out of the callback by making
ErrorHandler side-effect-free (return the custom status/body only). Capture the
error returned by app.Test or assign the error to an outer variable inside the
closure (e.g., var handlerErr error; in ErrorHandler set handlerErr = err) and
then after calling app.Test perform require.ErrorIs(t, handlerErr,
ErrForbiddenHost) and any response assertions; reference ErrorHandler,
require.ErrorIs, ErrForbiddenHost, and app.Test when making the change.

---

Duplicate comments:
In `@middleware/hostauthorization/hostauthorization_test.go`:
- Around line 275-279: The test currently returns on any non-nil error from
app.Test(req), which can mask unrelated failures; modify the app.Test(req) error
branch to assert the error is the expected host-related failure (e.g., using
require.ErrorContains(t, err, "host" or "empty host") or an equivalent check
against the Host validation error) before returning, then keep the existing
require.Equal(t, fiber.StatusForbidden, resp.StatusCode) assertion for the
response path; reference the app.Test call and the err variable when adding the
failure-specific assertion.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 2b53a8e5-b6e4-4ba9-a4e6-fa3bc158bd36

📥 Commits

Reviewing files that changed from the base of the PR and between b542c02 and 5f7a435.

📒 Files selected for processing (2)
  • middleware/hostauthorization/hostauthorization.go
  • middleware/hostauthorization/hostauthorization_test.go

Comment thread middleware/hostauthorization/hostauthorization_test.go
@mutantkeyboard
Copy link
Copy Markdown
Contributor Author

@gaby - this is now fixed. 💪💪

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Given the current implementation and the distinct purposes, I recommend keeping hostauthorization as a separate middleware rather than integrating it directly into the Domain() router or Ctx helpers.

Here's why:

  • Separation of Concerns: The hostauthorization middleware serves a security function (DNS rebinding protection), while Domain() is primarily for routing. Keeping these concerns separate leads to a cleaner, more modular architecture. As the PR description states, hostauthorization acts as a "security gate" and Domain() as a "routing layer."
  • Flexibility: A standalone middleware can be applied globally, to specific groups, or conditionally, offering greater flexibility to users regardless of their routing strategy. Tying it to Domain() might limit its applicability.
  • Domain() Limitations: As @mutantkeyboard pointed out in comment [🐞] Found 3 gosec issues: CWE-78 and CWE-242 #5, Domain() is opt-in per route and lacks the global reject semantics needed for a security middleware. Additionally, parseDomainPattern in Domain() does not currently support CIDR ranges or leading-dot wildcards, which are core features of this host authorization middleware. Integrating these would add complexity to the router that might not align with its primary function.
  • Current Review Direction: The recent discussions (e.g., comment Add deprecated alerts, linting, nosec, typo's #6 from @ReneWerner87) have focused on optimizing the standalone middleware's performance and refining its documentation, implicitly affirming the current design choice.

Therefore, maintaining it as a dedicated middleware seems to be the most robust and flexible approach for this security feature.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Adds a new hostauthorization middleware to validate the incoming Host header against an allowlist to mitigate DNS rebinding / Host-header attacks, with support for exact hosts, subdomain wildcards, CIDR ranges, and an optional dynamic validator.

Changes:

  • Introduces middleware/hostauthorization with config, parsing/normalization, and request-time host matching.
  • Adds a comprehensive test suite plus benchmarks for matching and end-to-end middleware behavior.
  • Adds end-user documentation and lists the middleware in .github/README.md.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
middleware/hostauthorization/hostauthorization.go Implements allowlist parsing + host matching and the middleware handler.
middleware/hostauthorization/config.go Defines middleware configuration, defaults, and exported error.
middleware/hostauthorization/hostauthorization_test.go Adds unit/integration tests and benchmarks for matching behavior and proxy semantics.
docs/middleware/hostauthorization.md Documents usage, matching/normalization rules, and proxy/RFC notes.
.github/README.md Adds the new middleware to the project’s middleware list.

Comment thread middleware/hostauthorization/hostauthorization.go Outdated
Comment thread middleware/hostauthorization/hostauthorization.go Outdated
Comment thread middleware/hostauthorization/hostauthorization.go Outdated
@mutantkeyboard mutantkeyboard requested a review from gaby April 20, 2026 09:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

📝 [Proposal]: Host authorization middleware — DNS rebinding protection via Host header validation

4 participants