Commit Graph

686 Commits (v2)

Author SHA1 Message Date
Aaron Zingerle 8c84b0fd8a
🩹 fix: Middleware/CORS Remove Scheme Restriction (#3168)
🩹 Fix: Middleware/CORS Remove Scheme Restriction (gofiber#3160)

Co-authored-by: Aaron Zingerle <aaron.zingerle@vipaso.io>
2024-10-14 15:04:25 +02:00
Juan Calderon-Perez 1c526892e7
🐛 bug: Use Content-Length for bytesReceived and bytesSent tags in Logger Middleware in v2 (#3067)
Use Content-Length for bytesSent and bytesReceived in Logger
2024-07-18 13:41:39 +02:00
Jason McNeil 66a881441b
fix(middleware/session): mutex for thread safety (#3050)
* chore: Remove extra release and acquire ctx calls in session_test.go

* feat: Remove unnecessary session mutex lock in decodeSessionData function

* chore: Refactor session benchmark tests

* fix(middleware/session): mutex for thread safety

* feat: Add session mutex lock for thread safety

* chore: Refactor releaseSession mutex
2024-06-30 21:16:23 +02:00
Jason McNeil c7bfb31bf9
test(middleware/session): Remove extra release and aquire ctx calls in session_test.go (#3043) 2024-06-26 15:46:28 +02:00
René abf8f324d6 prepare version v2.52.5 2024-06-26 11:05:26 +02:00
Jason McNeil 7926e5bf4d
Merge pull request from GHSA-98j2-3j3p-fw2v
* fix: token injection vulnerability GHSA-98j2-3j3p-fw2v

- Ensure session IDs are securely generated server-side.
- Add validation to prevent user-supplied session IDs.
- Update tests to verify correct session token use.

This update addresses the critical session middleware vulnerability identified in versions 2 and above of GoFiber.

* test(middleware/csrf): Save session after generating new session ID

This commit saves the session after generating a new session ID to ensure that the updated session ID is persisted. This change is necessary to address a critical session middleware vulnerability identified in versions 2 and above of GoFiber.

* chore: Save session ID in context for middleware chain

The code changes add functionality to save the newly generated session ID in the context, allowing it to be accessible to subsequent middlewares in the chain. This improvement ensures that the session ID is available for use throughout the middleware stack.

* test: Fix session freshness check in session_test

The code changes in `session_test.go` fix the session freshness check by updating the assertions for `sess.Fresh()` and `sess.ID()`. The previous assertions were incorrect and have been corrected to ensure the session ID remains the same and the session is not fresh.

* refactor(session.go): general clean-up

* chore: Revert session freshness behavior

The code changes in `session_test.go` fix the session freshness check by updating the assertions for `sess.Fresh()` and `sess.ID()`. The previous assertions were incorrect and have been corrected to ensure the session ID remains the same and the session is not fresh.
2024-06-26 09:17:41 +02:00
Feng 4262f5b591
fix: monitor middleware reporting of CPU usage (#2984)
monitPIDCPU should be transient, not persistent.

Co-authored-by: Juan Calderon-Perez <835733+gaby@users.noreply.github.com>
2024-06-24 16:32:04 +02:00
Jason McNeil a6f4c133bc
fix(middleware/cors): Vary header handling non-cors OPTIONS requests (#2939)
* fix(middleware/cors): Vary header handling non-cors OPTIONS requests

* chore(middleware/cors): Add Vary header for non-CORS OPTIONS requests comment
2024-03-26 22:22:42 +01:00
Jason McNeil e574c0db52
fix(middleware/cors): CORS handling (#2937)
* fix(middleware/cors): CORS handling

* fix(middleware/cors): Vary header handling

* test(middleware/cors): Ensure Vary Headers checked
2024-03-26 21:57:42 +01:00
Jason McNeil ba10e68d01
test(middleware/csrf): Fix Benchmark Tests (#2932)
* test(middleware/csrf): fix Benchmark_Middleware_CSRF_*

* fix(middleware/csrf): update refererMatchesHost()
2024-03-25 15:30:20 +01:00
Jason McNeil 1607d872d9
fix(middleware/cors): Categorize requests correctly (#2921)
* fix(middleware/cors): categorise requests correctly

* test(middleware/cors): improve test coverage for request types

* test(middleware/cors): Add subdomain matching tests

* test(middleware/cors): parallel tests for CORS headers based on request type

* test(middleware/cors): Add benchmark for CORS subdomain matching

* test(middleware/cors): cover additiona test cases

* refactor(middleware/cors): origin validation and normalization
2024-03-20 14:57:29 +01:00
Jason McNeil 1aac6f618b
fix(middleware/cors): Handling and wildcard subdomain matching (#2915)
* fix: allow origins check

Refactor CORS origin validation and normalization to trim leading or trailing whitespace in the cfg.AllowOrigins string [list]. URLs with whitespace inside the URL are invalid, so the normalizeOrigin will return false because url.Parse will fail, and the middleware will panic.

fixes #2882

* test: AllowOrigins with whitespace

* test(middleware/cors): add benchmarks

* chore: fix linter errors

* test(middleware/cors): use h() instead of app.Test()

* test(middleware/cors): add miltiple origins in Test_CORS_AllowOriginScheme

* chore: refactor validate and normalize

* test(cors/middleware): add more benchmarks

* fix(middleware/cors): handling and wildcard subdomain matching

docs(middleware/cors): add How it works and Security Considerations

* chore: grammar

* Apply suggestions from code review

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* chore: fix misspelling

* test(middleware/cors): combine Invalid_Origins tests

* refactor(middleware/cors): headers handling

* docs(middleware/cors): Update AllowOrigins description

* chore: merge

* perf(middleware/cors): optimize handler

* perf(middleware/cors): optimize handler

* chore(middleware/cors): ipdate origin handling logic

* chore(middleware/cors): fix header capitalization

* docs(middleware/cors): improve sercuity notes

* docs(middleware/cors): Improve security notes

* docs(middleware/cors): improve CORS overview

* docs(middleware/cors): fix ordering of how it works

* docs(middleware/cors): add additional info to How to works

* docs(middleware/cors): rm space

* docs(middleware/cors): add validation for AllowOrigins origins to overview

* docs(middleware/cors): update ExposeHeaders and MaxAge descriptions

* docs(middleware/cors): Add dynamic origin validation example

* docs(middleware/cors): Improve security notes and fix header capitalization

* docs(middleware/cors): configuration examples

* docs(middleware/cors): `"*"`

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2024-03-17 13:43:16 +01:00
Jason McNeil d456e7d82e
fix(middleware/cors): Validation of multiple Origins (#2883)
* fix: allow origins check

Refactor CORS origin validation and normalization to trim leading or trailing whitespace in the cfg.AllowOrigins string [list]. URLs with whitespace inside the URL are invalid, so the normalizeOrigin will return false because url.Parse will fail, and the middleware will panic.

fixes #2882

* test: AllowOrigins with whitespace

* test(middleware/cors): add benchmarks

* chore: fix linter errors

* test(middleware/cors): use h() instead of app.Test()

* test(middleware/cors): add miltiple origins in Test_CORS_AllowOriginScheme

* chore: refactor validate and normalize

* test(cors/middleware): add more benchmarks
2024-03-01 10:31:11 +01:00
René Werner 70f21d5f7e fix cors domain normalize 2024-02-21 21:18:56 +01:00
Juan Calderon-Perez f0cd3b44b0
Merge pull request from GHSA-fmg4-x8pw-hjhg
* Enforce Wildcard Origins with AllowCredentials check

* Expand unit-tests, fix issues with subdomains logic, update docs

* Update cors.md

* Added test using localhost, ipv4, and ipv6 address

* improve documentation markdown

---------

Co-authored-by: René Werner <rene@gofiber.io>
2024-02-21 14:47:33 +01:00
Lucas Lemos 5e30112d08
fix: healthcheck middleware not working with route group (#2863)
* fix: healthcheck middleware not working with route group

* perf: change verification method to improve perf

* Update healthcheck_test.go

* test: add not matching route test for strict routing

* add more test cases

* correct tests

* correct test helpers

* correct tests

* correct tests

---------

Co-authored-by: Juan Calderon-Perez <835733+gaby@users.noreply.github.com>
Co-authored-by: René Werner <rene@gofiber.io>
2024-02-19 14:28:58 +01:00
Lucas Lemos 6249bc48bc
feat: add liveness and readiness checks (#2509)
*  feat: add liveness and readiness checkers

* 📝 docs: add docs for liveness and readiness

*  feat: add options method for probe checkers

*  tests: add tests for liveness and readiness

* ♻️ refactor: change default endpoint values

* ♻️ refactor: change default value for liveness endpoint

* 📝 docs: add return status for liveness and readiness probes

* ♻️ refactor: change probechecker to middleware

* 📝 docs: move docs to middleware session

* ♻️ refactor: apply gofumpt formatting

* ♻️ refactor: remove unused parameter

* split config and apply a review

* apply reviews and add testcases

* add benchmark

* cleanup

* rename middleware

* fix linter

* Update docs and config values

* Revert change to IsReady

* Updates based on code review

* Update docs to match other middlewares

---------

Co-authored-by: Muhammed Efe Cetin <efectn@protonmail.com>
Co-authored-by: Juan Calderon-Perez <835733+gaby@users.noreply.github.com>
Co-authored-by: Juan Calderon-Perez <jgcalderonperez@protonmail.com>
2024-01-03 18:13:58 +01:00
RW 38eb4bd238
♻️ logger/middleware colorize logger error message #2593 (#2773) 2023-12-23 08:31:58 +01:00
gilwo d6c88764eb
🩹🚨 - fix for redirect with query params (#2748)
* redirect with query params did not work, fix it and add test for it

* redirect middleware - fix test typo
2023-12-22 16:18:04 +01:00
RW c49faf9a8a
🐛 [Bug]: Adaptator + otelfiber issue #2641 (#2772) 2023-12-22 14:49:58 +01:00
Muhammad Kholid B 1fac52a42a
🩹 Fix: CORS middleware should use the defined AllowedOriginsFunc config when AllowedOrigins is empty (#2771) 2023-12-22 14:48:37 +01:00
Bruno dc2d2ef524
Changing default log output (#2730)
changing default log output

Closes #2729
2023-12-18 15:20:18 +01:00
Benjamin Grosse b1850834a3
fix: don't constrain middlewares' context-keys to strings 🐛 (#2751)
* Revert "Revert "🐛 requestid.Config.ContextKey is interface{} (#2369)" (#2742)"

This reverts commit 28be17f929.

* fix: request ContextKey default value condition

Should check for `nil` since it is `any`.

* fix: don't constrain middlewares' context-keys to strings

`context` recommends using "unexported type" as context keys to avoid
collisions https://pkg.go.dev/github.com/gofiber/fiber/v2#Ctx.Locals.

The official go blog also recommends this https://go.dev/blog/context.

`fiber.Ctx.Locals(key any, value any)` correctly allows consumers to
use unexported types or e.g. strings.

But some fiber middlewares constrain their context-keys to `string` in
their "default config structs", making it impossible to use unexported
types.

This PR removes the `string` _constraint_ from all middlewares, allowing
to now use unexported types as per the official guidelines. However
the default value is still a string, so it's not a breaking change, and
anyone still using strings as context keys is not affected.
2023-12-12 14:55:29 +01:00
iRedMail c441bdf2d0
🩹 middleware/logger/: log client IP address by default (#2755)
* middleware/logger: Log client IP address by default.

* Update doc.
2023-12-08 10:36:43 +01:00
Jason McNeil e4d7e84335
chore(encryptcookie)!: update default config (#2753)
* chore(encryptcookie)!: update default config

docs(encryptcookie): enhance documentation and examples

BREAKING CHANGE: removed the hardcoded "csrf_" from the Except.

* docs(encryptcookie): reads or modifies cookies

* chore(encryptcookie): csrf config example

* docs(encryptcookie): md table spacing
2023-12-07 08:39:41 +01:00
nickajacks1 8d5248bee6
🚨 Test: race in session middleware tests (#2740)
A Session must not be accessed after Save() is called, but a unit test
calls Session.ID() after Session.Save(), sometimes causing the test to
fail when -race is enabled. The assertions that ID() was being used in
were redundant with the previous two assertions (checking that the
session name header is empty), so we can just remove the offending code.
2023-11-27 14:38:31 +01:00
RW 28be17f929
Revert "🐛 requestid.Config.ContextKey is interface{} (#2369)" (#2742)
This reverts commit d7b36cde
2023-11-27 14:35:49 +01:00
nickajacks1 eeced206ed
test: Fix failing CSRF tests (#2720)
 test: fix failing csrf test

A test validating that expired tokens fail was hitting a race condition
with garbage collection. Sometimes, an assertion that expects memory
storage GC to have triggered happens too quickly, causing the assertion
to fail. Give the GC a little bit more time to process before asserting.
2023-11-22 19:21:30 +01:00
Jason McNeil 2374cad3cd
📄 docs: improve csrf docs (#2726)
* docs: improve csrf docs

- fix issues with `X-Csrf-Token` capitalization inconsistency.
- reduce redundancy and repetition.
- improve grammar.

* docs: update middleware description

* docs: within vs in

* docs: deleting tokens

* docs: MUST

* docs: add colon

* docs: all modern browsers

* docs: patterns

* docs: improve phrasing of pattern options
2023-11-16 12:34:31 +01:00
nickajacks1 1e55045a30
test(limiter): fix intermittent failures (#2716)
The limiter middleware unit tests are failing due to a race between the
storage garbage collector and the unit test itself. The sliding window
limiter tracks requests using memory storage. In several of the unit
tests, this storage expiry ends up being 4 seconds. The test waits for 4
seconds, then sends a request, expecting it to succeed. However, the
unit test occasionally wakes up before the storage GC kicks in. As an
effect of the very coarse timer (using seconds as units), the middleware
correctly rejects the request, causing the test to fail.

Update the sleep to 4.5 seconds. This will not slow down the execution
of the test suite, as these tests run in parallel with a separate 9
second long test.

I'm not 100% sure this solves the issue, and ideally we'd be able to
run tests without time.Sleep.
2023-11-10 11:33:10 +01:00
database64128 b99712f13e
middleware/pprof: improve performance (#2709)
*  middleware/pprof: improve performance

Concatenate the custom and fixed prefixes beforehand, so the trimmed path can be switched on against constant strings.

goos: linux
goarch: amd64
pkg: github.com/gofiber/fiber/v2/middleware/pprof
cpu: 13th Gen Intel(R) Core(TM) i9-13900K
BenchmarkPprof/Slow-32         	 4912642	       246.3 ns/op	     480 B/op	      10 allocs/op
BenchmarkPprof/Fast-32         	411908472	         2.913 ns/op	       0 B/op	       0 allocs/op
PASS

* 🌂 middleware/pprof: disable nonamedreturns linter on cutPrefix
2023-11-09 08:05:54 +01:00
Jason McNeil 8c3916dbf4
Merge pull request from GHSA-94w9-97p3-p368
* feat: improved csrf with session support

* fix: double submit cookie

* feat: add warning cookie extractor without session

* feat: add warning CsrfFromCookie SameSite

* fix: use byes.Equal instead

* fix: Overriden CookieName KeyLookup cookie:<name>

* feat: Create helpers.go

* feat: use compareTokens (constant time compare)

* feat: validate cookie to prevent token injection

* refactor: clean up csrf.go

* docs: update comment about Double Submit Cookie

* docs: update docs for CSRF changes

* feat: add DeleteToken

* refactor: no else

* test: add more tests

* refactor: re-order tests

* docs: update safe methods RCF add note

* test: add CSRF_Cookie_Injection_Exploit

* feat: add SingleUseToken config

* test: check for new token

* docs: use warning

* fix: always register type Token

* feat: use UUIDv4

* test: swap in UUIDv4 here too

* fix: raw token injection

* fix: merege error

* feat: Sentinel errors

* chore: rename test

* fix: url parse

* test: add path to referer

* test: add expiration tests

* docs: add cookie prefix note

* docs: fix typo

* docs: add warning for refer checks

* test: add referer edge cases

And call ctx.Request.Reset() and
ctx.Response.Reset() before re-using ctx.
2023-10-16 09:06:30 +02:00
René Werner bb90fc1187 fix lint errors 2023-10-11 15:16:35 +02:00
Jason McNeil b50d91d58e
Merge pull request from GHSA-94w9-97p3-p368
* feat: improved csrf with session support

* fix: double submit cookie

* feat: add warning cookie extractor without session

* feat: add warning CsrfFromCookie SameSite

* fix: use byes.Equal instead

* fix: Overriden CookieName KeyLookup cookie:<name>

* feat: Create helpers.go

* feat: use compareTokens (constant time compare)

* feat: validate cookie to prevent token injection

* refactor: clean up csrf.go

* docs: update comment about Double Submit Cookie

* docs: update docs for CSRF changes

* feat: add DeleteToken

* refactor: no else

* test: add more tests

* refactor: re-order tests

* docs: update safe methods RCF add note

* test: add CSRF_Cookie_Injection_Exploit

* feat: add SingleUseToken config

* test: check for new token

* docs: use warning

* fix: always register type Token

* feat: use UUIDv4

* test: swap in UUIDv4 here too
2023-10-11 14:41:42 +02:00
M. Efe Çetin 9292a36e28
🐛 bug: fix nil pointer dereference issue on idempotency middleware (#2668) 2023-10-10 08:23:23 +02:00
Michael Bell 8228da91fc
[filesystem middleware] improve status for SendFile (#2664)
SendFile response code for success
2023-10-06 13:10:20 +02:00
René Werner 59409f3841 improve sendFile documentation 2023-10-06 11:43:10 +02:00
Tiago Peczenyj 0d3354675b
Fix loop variable captured by func literal (#2660)
* fix loop variable xxx captured by func literal

* fix middleware/pprof tests
2023-10-05 13:49:57 +02:00
Tiago Peczenyj ab4e731607
Run gofumpt and goimports (#2662)
* run goimports -w -local github.com/gofiber/fiber .

* run gofumpt -w -extra .
2023-10-05 13:14:30 +02:00
KaptinLin d00f0b8348
feat: add Reset method to Session struct in session middleware (#2654) 2023-10-02 15:19:35 +02:00
KaptinLin d86c257c89
feat: add Delete method to Store struct in session middleware (#2655)
*  feat: add Delete method to Store struct in session middleware

* ♻ refactor: enhance Delete method and test cases in session middleware
2023-10-02 15:19:18 +02:00
M. Efe Çetin 6e443f6026
refactor: use utils.AssertEqual instead of t.Fatal on some tests (#2653) 2023-09-28 14:40:42 +02:00
M. Efe Çetin a9447a5b49
ctx: change signatures of GetReqHeaders and GetRespHeaders (#2650)
* ctx: change signatures of GetReqHeaders and GetRespHeaders

* fix middlewares
2023-09-28 08:31:31 +02:00
M. Efe Çetin e6d6fbe5a8
middleware: cors: allow disabling caching in preflight requests (#2649) 2023-09-27 15:06:24 +02:00
Juan Calderon-Perez 5d6552e42d
🐛 fix(middleware/adaptor): Reduce memory usage by replacing io.ReadAll() with io.Copy() (#2637)
* Replace io.ReadAll with io.Copy for Adaptor Middleware

* Add nolint to Close() during benchmark
2023-09-19 08:08:51 +02:00
CuiPeiyu d0d5e9ee99
[middleware/filesystem]: Set response code (#2632)
Specified response code
2023-09-14 14:46:34 +02:00
Akarshit Joshi 6d34e23815
[Bug]: Logger Middleware: Enabling color changes padding for some fields #2604 (#2616)
🐛 Removes extra padding for response code, method
2023-09-11 08:45:00 +02:00
Eng Zer Jun 242ff94505
♻️ Refactor: Remove redundant nil check (#2584)
From the Go docs:

  "If the map is nil, the number of iterations is 0." [1]

Therefore, an additional nil check for before the loop is unnecessary.

[1]: https://go.dev/ref/spec#For_range

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
2023-08-17 20:49:53 +02:00
Jacob 892b23bd46
Add custom data property to favicon middleware config (#2579)
* Add custom data property to favicon middleware

* Update favicon middleware docs

* Fix formatting
2023-08-17 15:04:53 +02:00
Jason McNeil c3ae06608b
🐛 fix(middleware/logger): default latency output format (#2580)
* fix: default logger formater latency

* test: add Test_Logger_WithLatency_DefaultFormat

* test: rm t.Parallel() from Latency tests

Trying to make windows CI pass....

* test: fix windows sleep issue
2023-08-17 14:33:59 +02:00