repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/body_dump_test.go
middleware/body_dump_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "errors" "io" "net/http" "net/http/httptest" "strings" "testing" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func TestBodyDump(t *testing.T) { e := echo.New() hw := "Hello, World!" req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(hw)) rec := httptest.NewRecorder() c := e.NewContext(req, rec) h := func(c echo.Context) error { body, err := io.ReadAll(c.Request().Body) if err != nil { return err } return c.String(http.StatusOK, string(body)) } requestBody := "" responseBody := "" mw := BodyDump(func(c echo.Context, reqBody, resBody []byte) { requestBody = string(reqBody) responseBody = string(resBody) }) if assert.NoError(t, mw(h)(c)) { assert.Equal(t, requestBody, hw) assert.Equal(t, responseBody, hw) assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, hw, rec.Body.String()) } // Must set default skipper BodyDumpWithConfig(BodyDumpConfig{ Skipper: nil, Handler: func(c echo.Context, reqBody, resBody []byte) { requestBody = string(reqBody) responseBody = string(resBody) }, }) } func TestBodyDumpFails(t *testing.T) { e := echo.New() hw := "Hello, World!" req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(hw)) rec := httptest.NewRecorder() c := e.NewContext(req, rec) h := func(c echo.Context) error { return errors.New("some error") } mw := BodyDump(func(c echo.Context, reqBody, resBody []byte) {}) if !assert.Error(t, mw(h)(c)) { t.FailNow() } assert.Panics(t, func() { mw = BodyDumpWithConfig(BodyDumpConfig{ Skipper: nil, Handler: nil, }) }) assert.NotPanics(t, func() { mw = BodyDumpWithConfig(BodyDumpConfig{ Skipper: func(c echo.Context) bool { return true }, Handler: func(c echo.Context, reqBody, resBody []byte) { }, }) if !assert.Error(t, mw(h)(c)) { t.FailNow() } }) } func TestBodyDumpResponseWriter_CanNotFlush(t *testing.T) { bdrw := bodyDumpResponseWriter{ ResponseWriter: new(testResponseWriterNoFlushHijack), // this RW does not support flush } assert.PanicsWithError(t, "response writer flushing is not supported", func() { bdrw.Flush() }) } func TestBodyDumpResponseWriter_CanFlush(t *testing.T) { trwu := testResponseWriterUnwrapperHijack{testResponseWriterUnwrapper: testResponseWriterUnwrapper{rw: httptest.NewRecorder()}} bdrw := bodyDumpResponseWriter{ ResponseWriter: &trwu, } bdrw.Flush() assert.Equal(t, 1, trwu.unwrapCalled) } func TestBodyDumpResponseWriter_CanUnwrap(t *testing.T) { trwu := &testResponseWriterUnwrapper{rw: httptest.NewRecorder()} bdrw := bodyDumpResponseWriter{ ResponseWriter: trwu, } result := bdrw.Unwrap() assert.Equal(t, trwu, result) } func TestBodyDumpResponseWriter_CanHijack(t *testing.T) { trwu := testResponseWriterUnwrapperHijack{testResponseWriterUnwrapper: testResponseWriterUnwrapper{rw: httptest.NewRecorder()}} bdrw := bodyDumpResponseWriter{ ResponseWriter: &trwu, // this RW supports hijacking through unwrapping } _, _, err := bdrw.Hijack() assert.EqualError(t, err, "can hijack") } func TestBodyDumpResponseWriter_CanNotHijack(t *testing.T) { trwu := testResponseWriterUnwrapper{rw: httptest.NewRecorder()} bdrw := bodyDumpResponseWriter{ ResponseWriter: &trwu, // this RW supports hijacking through unwrapping } _, _, err := bdrw.Hijack() assert.EqualError(t, err, "feature not supported") } func TestBodyDump_ReadError(t *testing.T) { e := echo.New() // Create a reader that fails during read failingReader := &failingReadCloser{ data: []byte("partial data"), failAt: 7, // Fail after 7 bytes failWith: errors.New("connection reset"), } req := httptest.NewRequest(http.MethodPost, "/", failingReader) rec := httptest.NewRecorder() c := e.NewContext(req, rec) h := func(c echo.Context) error { // This handler should not be reached if body read fails body, _ := io.ReadAll(c.Request().Body) return c.String(http.StatusOK, string(body)) } requestBodyReceived := "" mw := BodyDump(func(c echo.Context, reqBody, resBody []byte) { requestBodyReceived = string(reqBody) }) err := mw(h)(c) // Verify error is propagated assert.Error(t, err) assert.Contains(t, err.Error(), "connection reset") // Verify handler was not executed (callback wouldn't have received data) assert.Empty(t, requestBodyReceived) } // failingReadCloser is a helper type for testing read errors type failingReadCloser struct { data []byte pos int failAt int failWith error } func (f *failingReadCloser) Read(p []byte) (n int, err error) { if f.pos >= f.failAt { return 0, f.failWith } n = copy(p, f.data[f.pos:]) f.pos += n if f.pos >= f.failAt { return n, f.failWith } return n, nil } func (f *failingReadCloser) Close() error { return nil }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/middleware_test.go
middleware/middleware_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "bufio" "errors" "github.com/stretchr/testify/assert" "net" "net/http" "net/http/httptest" "regexp" "testing" ) func TestRewriteURL(t *testing.T) { var testCases = []struct { whenURL string expectPath string expectRawPath string expectQuery string expectErr string }{ { whenURL: "http://localhost:8080/old", expectPath: "/new", expectRawPath: "", }, { // encoded `ol%64` (decoded `old`) should not be rewritten to `/new` whenURL: "/ol%64", // `%64` is decoded `d` expectPath: "/old", expectRawPath: "/ol%64", }, { whenURL: "http://localhost:8080/users/+_+/orders/___++++?test=1", expectPath: "/user/+_+/order/___++++", expectRawPath: "", expectQuery: "test=1", }, { whenURL: "http://localhost:8080/users/%20a/orders/%20aa", expectPath: "/user/ a/order/ aa", expectRawPath: "", }, { whenURL: "http://localhost:8080/%47%6f%2f?test=1", expectPath: "/Go/", expectRawPath: "/%47%6f%2f", expectQuery: "test=1", }, { whenURL: "/users/jill/orders/T%2FcO4lW%2Ft%2FVp%2F", expectPath: "/user/jill/order/T/cO4lW/t/Vp/", expectRawPath: "/user/jill/order/T%2FcO4lW%2Ft%2FVp%2F", }, { // do nothing, replace nothing whenURL: "http://localhost:8080/user/jill/order/T%2FcO4lW%2Ft%2FVp%2F", expectPath: "/user/jill/order/T/cO4lW/t/Vp/", expectRawPath: "/user/jill/order/T%2FcO4lW%2Ft%2FVp%2F", }, { whenURL: "http://localhost:8080/static", expectPath: "/static/path", expectRawPath: "", expectQuery: "role=AUTHOR&limit=1000", }, { whenURL: "/static", expectPath: "/static/path", expectRawPath: "", expectQuery: "role=AUTHOR&limit=1000", }, } rules := map[*regexp.Regexp]string{ regexp.MustCompile("^/old$"): "/new", regexp.MustCompile("^/users/(.*?)/orders/(.*?)$"): "/user/$1/order/$2", regexp.MustCompile("^/static$"): "/static/path?role=AUTHOR&limit=1000", } for _, tc := range testCases { t.Run(tc.whenURL, func(t *testing.T) { req := httptest.NewRequest(http.MethodGet, tc.whenURL, nil) err := rewriteURL(rules, req) if tc.expectErr != "" { assert.EqualError(t, err, tc.expectErr) } else { assert.NoError(t, err) } assert.Equal(t, tc.expectPath, req.URL.Path) // Path field is stored in decoded form: /%47%6f%2f becomes /Go/. assert.Equal(t, tc.expectRawPath, req.URL.RawPath) // RawPath, an optional field which only gets set if the default encoding is different from Path. assert.Equal(t, tc.expectQuery, req.URL.RawQuery) }) } } type testResponseWriterNoFlushHijack struct { } func (w *testResponseWriterNoFlushHijack) WriteHeader(statusCode int) { } func (w *testResponseWriterNoFlushHijack) Write([]byte) (int, error) { return 0, nil } func (w *testResponseWriterNoFlushHijack) Header() http.Header { return nil } type testResponseWriterUnwrapper struct { unwrapCalled int rw http.ResponseWriter } func (w *testResponseWriterUnwrapper) WriteHeader(statusCode int) { } func (w *testResponseWriterUnwrapper) Write([]byte) (int, error) { return 0, nil } func (w *testResponseWriterUnwrapper) Header() http.Header { return nil } func (w *testResponseWriterUnwrapper) Unwrap() http.ResponseWriter { w.unwrapCalled++ return w.rw } type testResponseWriterUnwrapperHijack struct { testResponseWriterUnwrapper } func (w *testResponseWriterUnwrapperHijack) Hijack() (net.Conn, *bufio.ReadWriter, error) { return nil, nil, errors.New("can hijack") }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/method_override_test.go
middleware/method_override_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "bytes" "net/http" "net/http/httptest" "testing" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func TestMethodOverride(t *testing.T) { e := echo.New() m := MethodOverride() h := func(c echo.Context) error { return c.String(http.StatusOK, "test") } // Override with http header req := httptest.NewRequest(http.MethodPost, "/", nil) rec := httptest.NewRecorder() req.Header.Set(echo.HeaderXHTTPMethodOverride, http.MethodDelete) c := e.NewContext(req, rec) m(h)(c) assert.Equal(t, http.MethodDelete, req.Method) // Override with form parameter m = MethodOverrideWithConfig(MethodOverrideConfig{Getter: MethodFromForm("_method")}) req = httptest.NewRequest(http.MethodPost, "/", bytes.NewReader([]byte("_method="+http.MethodDelete))) rec = httptest.NewRecorder() req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationForm) c = e.NewContext(req, rec) m(h)(c) assert.Equal(t, http.MethodDelete, req.Method) // Override with query parameter m = MethodOverrideWithConfig(MethodOverrideConfig{Getter: MethodFromQuery("_method")}) req = httptest.NewRequest(http.MethodPost, "/?_method="+http.MethodDelete, nil) rec = httptest.NewRecorder() c = e.NewContext(req, rec) m(h)(c) assert.Equal(t, http.MethodDelete, req.Method) // Ignore `GET` req = httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderXHTTPMethodOverride, http.MethodDelete) assert.Equal(t, http.MethodGet, req.Method) }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/rewrite_test.go
middleware/rewrite_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "io" "net/http" "net/http/httptest" "net/url" "regexp" "testing" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func TestRewriteAfterRouting(t *testing.T) { e := echo.New() // middlewares added with `Use()` are executed after routing is done and do not affect which route handler is matched e.Use(RewriteWithConfig(RewriteConfig{ Rules: map[string]string{ "/old": "/new", "/api/*": "/$1", "/js/*": "/public/javascripts/$1", "/users/*/orders/*": "/user/$1/order/$2", }, })) e.GET("/public/*", func(c echo.Context) error { return c.String(http.StatusOK, c.Param("*")) }) e.GET("/*", func(c echo.Context) error { return c.String(http.StatusOK, c.Param("*")) }) var testCases = []struct { whenPath string expectRoutePath string expectRequestPath string expectRequestRawPath string }{ { whenPath: "/api/users", expectRoutePath: "api/users", expectRequestPath: "/users", expectRequestRawPath: "", }, { whenPath: "/js/main.js", expectRoutePath: "js/main.js", expectRequestPath: "/public/javascripts/main.js", expectRequestRawPath: "", }, { whenPath: "/users/jack/orders/1", expectRoutePath: "users/jack/orders/1", expectRequestPath: "/user/jack/order/1", expectRequestRawPath: "", }, { // no rewrite rule matched. already encoded URL should not be double encoded or changed in any way whenPath: "/user/jill/order/T%2FcO4lW%2Ft%2FVp%2F", expectRoutePath: "user/jill/order/T%2FcO4lW%2Ft%2FVp%2F", expectRequestPath: "/user/jill/order/T/cO4lW/t/Vp/", // this is equal to `url.Parse(tc.whenPath)` result expectRequestRawPath: "/user/jill/order/T%2FcO4lW%2Ft%2FVp%2F", }, { // just rewrite but do not touch encoding. already encoded URL should not be double encoded whenPath: "/users/jill/orders/T%2FcO4lW%2Ft%2FVp%2F", expectRoutePath: "users/jill/orders/T%2FcO4lW%2Ft%2FVp%2F", expectRequestPath: "/user/jill/order/T/cO4lW/t/Vp/", // this is equal to `url.Parse(tc.whenPath)` result expectRequestRawPath: "/user/jill/order/T%2FcO4lW%2Ft%2FVp%2F", }, { // ` ` (space) is encoded by httpClient to `%20` when doing request to Echo. `%20` should not be double escaped or changed in any way when rewriting request whenPath: "/api/new users", expectRoutePath: "api/new users", expectRequestPath: "/new users", expectRequestRawPath: "", }, } for _, tc := range testCases { t.Run(tc.whenPath, func(t *testing.T) { target, _ := url.Parse(tc.whenPath) req := httptest.NewRequest(http.MethodGet, target.String(), nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, tc.expectRoutePath, rec.Body.String()) assert.Equal(t, tc.expectRequestPath, req.URL.Path) assert.Equal(t, tc.expectRequestRawPath, req.URL.RawPath) }) } } // Issue #1086 func TestEchoRewritePreMiddleware(t *testing.T) { e := echo.New() r := e.Router() // Rewrite old url to new one // middlewares added with `Pre()` are executed before routing is done and therefore change which handler matches e.Pre(Rewrite(map[string]string{ "/old": "/new", }, )) // Route r.Add(http.MethodGet, "/new", func(c echo.Context) error { return c.NoContent(http.StatusOK) }) req := httptest.NewRequest(http.MethodGet, "/old", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, "/new", req.URL.EscapedPath()) assert.Equal(t, http.StatusOK, rec.Code) } // Issue #1143 func TestRewriteWithConfigPreMiddleware_Issue1143(t *testing.T) { e := echo.New() r := e.Router() // middlewares added with `Pre()` are executed before routing is done and therefore change which handler matches e.Pre(RewriteWithConfig(RewriteConfig{ Rules: map[string]string{ "/api/*/mgmt/proj/*/agt": "/api/$1/hosts/$2", "/api/*/mgmt/proj": "/api/$1/eng", }, })) r.Add(http.MethodGet, "/api/:version/hosts/:name", func(c echo.Context) error { return c.String(http.StatusOK, "hosts") }) r.Add(http.MethodGet, "/api/:version/eng", func(c echo.Context) error { return c.String(http.StatusOK, "eng") }) for i := 0; i < 100; i++ { req := httptest.NewRequest(http.MethodGet, "/api/v1/mgmt/proj/test/agt", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, "/api/v1/hosts/test", req.URL.EscapedPath()) assert.Equal(t, http.StatusOK, rec.Code) defer rec.Result().Body.Close() bodyBytes, _ := io.ReadAll(rec.Result().Body) assert.Equal(t, "hosts", string(bodyBytes)) } } // Issue #1573 func TestEchoRewriteWithCaret(t *testing.T) { e := echo.New() e.Pre(RewriteWithConfig(RewriteConfig{ Rules: map[string]string{ "^/abc/*": "/v1/abc/$1", }, })) rec := httptest.NewRecorder() var req *http.Request req = httptest.NewRequest(http.MethodGet, "/abc/test", nil) e.ServeHTTP(rec, req) assert.Equal(t, "/v1/abc/test", req.URL.Path) req = httptest.NewRequest(http.MethodGet, "/v1/abc/test", nil) e.ServeHTTP(rec, req) assert.Equal(t, "/v1/abc/test", req.URL.Path) req = httptest.NewRequest(http.MethodGet, "/v2/abc/test", nil) e.ServeHTTP(rec, req) assert.Equal(t, "/v2/abc/test", req.URL.Path) } // Verify regex used with rewrite func TestEchoRewriteWithRegexRules(t *testing.T) { e := echo.New() e.Pre(RewriteWithConfig(RewriteConfig{ Rules: map[string]string{ "^/a/*": "/v1/$1", "^/b/*/c/*": "/v2/$2/$1", "^/c/*/*": "/v3/$2", }, RegexRules: map[*regexp.Regexp]string{ regexp.MustCompile("^/x/.+?/(.*)"): "/v4/$1", regexp.MustCompile("^/y/(.+?)/(.*)"): "/v5/$2/$1", }, })) var rec *httptest.ResponseRecorder var req *http.Request testCases := []struct { requestPath string expectPath string }{ {"/unmatched", "/unmatched"}, {"/a/test", "/v1/test"}, {"/b/foo/c/bar/baz", "/v2/bar/baz/foo"}, {"/c/ignore/test", "/v3/test"}, {"/c/ignore1/test/this", "/v3/test/this"}, {"/x/ignore/test", "/v4/test"}, {"/y/foo/bar", "/v5/bar/foo"}, } for _, tc := range testCases { t.Run(tc.requestPath, func(t *testing.T) { req = httptest.NewRequest(http.MethodGet, tc.requestPath, nil) rec = httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, tc.expectPath, req.URL.EscapedPath()) }) } } // Ensure correct escaping as defined in replacement (issue #1798) func TestEchoRewriteReplacementEscaping(t *testing.T) { e := echo.New() // NOTE: these are incorrect regexps as they do not factor in that URI we are replacing could contain ? (query) and # (fragment) parts // so in reality they append query and fragment part as `$1` matches everything after that prefix e.Pre(RewriteWithConfig(RewriteConfig{ Rules: map[string]string{ "^/a/*": "/$1?query=param", "^/b/*": "/$1;part#one", }, RegexRules: map[*regexp.Regexp]string{ regexp.MustCompile("^/x/(.*)"): "/$1?query=param", regexp.MustCompile("^/y/(.*)"): "/$1;part#one", regexp.MustCompile("^/z/(.*)"): "/$1?test=1#escaped%20test", }, })) var rec *httptest.ResponseRecorder var req *http.Request testCases := []struct { requestPath string expect string }{ {"/unmatched", "/unmatched"}, {"/a/test", "/test?query=param"}, {"/b/foo/bar", "/foo/bar;part#one"}, {"/x/test", "/test?query=param"}, {"/y/foo/bar", "/foo/bar;part#one"}, {"/z/foo/b%20ar", "/foo/b%20ar?test=1#escaped%20test"}, {"/z/foo/b%20ar?nope=1#yes", "/foo/b%20ar?nope=1#yes?test=1%23escaped%20test"}, // example of appending } for _, tc := range testCases { t.Run(tc.requestPath, func(t *testing.T) { req = httptest.NewRequest(http.MethodGet, tc.requestPath, nil) rec = httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, tc.expect, req.URL.String()) }) } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/rate_limiter_test.go
middleware/rate_limiter_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "errors" "math/rand" "net/http" "net/http/httptest" "sync" "sync/atomic" "testing" "time" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" "golang.org/x/time/rate" ) func TestRateLimiter(t *testing.T) { e := echo.New() handler := func(c echo.Context) error { return c.String(http.StatusOK, "test") } var inMemoryStore = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 1, Burst: 3}) mw := RateLimiter(inMemoryStore) testCases := []struct { id string code int }{ {"127.0.0.1", http.StatusOK}, {"127.0.0.1", http.StatusOK}, {"127.0.0.1", http.StatusOK}, {"127.0.0.1", http.StatusTooManyRequests}, {"127.0.0.1", http.StatusTooManyRequests}, {"127.0.0.1", http.StatusTooManyRequests}, {"127.0.0.1", http.StatusTooManyRequests}, } for _, tc := range testCases { req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Add(echo.HeaderXRealIP, tc.id) rec := httptest.NewRecorder() c := e.NewContext(req, rec) _ = mw(handler)(c) assert.Equal(t, tc.code, rec.Code) } } func TestRateLimiter_panicBehaviour(t *testing.T) { var inMemoryStore = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 1, Burst: 3}) assert.Panics(t, func() { RateLimiter(nil) }) assert.NotPanics(t, func() { RateLimiter(inMemoryStore) }) } func TestRateLimiterWithConfig(t *testing.T) { var inMemoryStore = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 1, Burst: 3}) e := echo.New() handler := func(c echo.Context) error { return c.String(http.StatusOK, "test") } mw := RateLimiterWithConfig(RateLimiterConfig{ IdentifierExtractor: func(c echo.Context) (string, error) { id := c.Request().Header.Get(echo.HeaderXRealIP) if id == "" { return "", errors.New("invalid identifier") } return id, nil }, DenyHandler: func(ctx echo.Context, identifier string, err error) error { return ctx.JSON(http.StatusForbidden, nil) }, ErrorHandler: func(ctx echo.Context, err error) error { return ctx.JSON(http.StatusBadRequest, nil) }, Store: inMemoryStore, }) testCases := []struct { id string code int }{ {"127.0.0.1", http.StatusOK}, {"127.0.0.1", http.StatusOK}, {"127.0.0.1", http.StatusOK}, {"127.0.0.1", http.StatusForbidden}, {"", http.StatusBadRequest}, {"127.0.0.1", http.StatusForbidden}, {"127.0.0.1", http.StatusForbidden}, } for _, tc := range testCases { req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Add(echo.HeaderXRealIP, tc.id) rec := httptest.NewRecorder() c := e.NewContext(req, rec) _ = mw(handler)(c) assert.Equal(t, tc.code, rec.Code) } } func TestRateLimiterWithConfig_defaultDenyHandler(t *testing.T) { var inMemoryStore = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 1, Burst: 3}) e := echo.New() handler := func(c echo.Context) error { return c.String(http.StatusOK, "test") } mw := RateLimiterWithConfig(RateLimiterConfig{ IdentifierExtractor: func(c echo.Context) (string, error) { id := c.Request().Header.Get(echo.HeaderXRealIP) if id == "" { return "", errors.New("invalid identifier") } return id, nil }, Store: inMemoryStore, }) testCases := []struct { id string code int }{ {"127.0.0.1", http.StatusOK}, {"127.0.0.1", http.StatusOK}, {"127.0.0.1", http.StatusOK}, {"127.0.0.1", http.StatusTooManyRequests}, {"", http.StatusForbidden}, {"127.0.0.1", http.StatusTooManyRequests}, {"127.0.0.1", http.StatusTooManyRequests}, } for _, tc := range testCases { req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Add(echo.HeaderXRealIP, tc.id) rec := httptest.NewRecorder() c := e.NewContext(req, rec) _ = mw(handler)(c) assert.Equal(t, tc.code, rec.Code) } } func TestRateLimiterWithConfig_defaultConfig(t *testing.T) { { var inMemoryStore = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 1, Burst: 3}) e := echo.New() handler := func(c echo.Context) error { return c.String(http.StatusOK, "test") } mw := RateLimiterWithConfig(RateLimiterConfig{ Store: inMemoryStore, }) testCases := []struct { id string code int }{ {"127.0.0.1", http.StatusOK}, {"127.0.0.1", http.StatusOK}, {"127.0.0.1", http.StatusOK}, {"127.0.0.1", http.StatusTooManyRequests}, {"127.0.0.1", http.StatusTooManyRequests}, {"127.0.0.1", http.StatusTooManyRequests}, {"127.0.0.1", http.StatusTooManyRequests}, } for _, tc := range testCases { req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Add(echo.HeaderXRealIP, tc.id) rec := httptest.NewRecorder() c := e.NewContext(req, rec) _ = mw(handler)(c) assert.Equal(t, tc.code, rec.Code) } } } func TestRateLimiterWithConfig_skipper(t *testing.T) { e := echo.New() var beforeFuncRan bool handler := func(c echo.Context) error { return c.String(http.StatusOK, "test") } var inMemoryStore = NewRateLimiterMemoryStore(5) req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Add(echo.HeaderXRealIP, "127.0.0.1") rec := httptest.NewRecorder() c := e.NewContext(req, rec) mw := RateLimiterWithConfig(RateLimiterConfig{ Skipper: func(c echo.Context) bool { return true }, BeforeFunc: func(c echo.Context) { beforeFuncRan = true }, Store: inMemoryStore, IdentifierExtractor: func(ctx echo.Context) (string, error) { return "127.0.0.1", nil }, }) _ = mw(handler)(c) assert.Equal(t, false, beforeFuncRan) } func TestRateLimiterWithConfig_skipperNoSkip(t *testing.T) { e := echo.New() var beforeFuncRan bool handler := func(c echo.Context) error { return c.String(http.StatusOK, "test") } var inMemoryStore = NewRateLimiterMemoryStore(5) req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Add(echo.HeaderXRealIP, "127.0.0.1") rec := httptest.NewRecorder() c := e.NewContext(req, rec) mw := RateLimiterWithConfig(RateLimiterConfig{ Skipper: func(c echo.Context) bool { return false }, BeforeFunc: func(c echo.Context) { beforeFuncRan = true }, Store: inMemoryStore, IdentifierExtractor: func(ctx echo.Context) (string, error) { return "127.0.0.1", nil }, }) _ = mw(handler)(c) assert.Equal(t, true, beforeFuncRan) } func TestRateLimiterWithConfig_beforeFunc(t *testing.T) { e := echo.New() handler := func(c echo.Context) error { return c.String(http.StatusOK, "test") } var beforeRan bool var inMemoryStore = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 1, Burst: 3}) req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Add(echo.HeaderXRealIP, "127.0.0.1") rec := httptest.NewRecorder() c := e.NewContext(req, rec) mw := RateLimiterWithConfig(RateLimiterConfig{ BeforeFunc: func(c echo.Context) { beforeRan = true }, Store: inMemoryStore, IdentifierExtractor: func(ctx echo.Context) (string, error) { return "127.0.0.1", nil }, }) _ = mw(handler)(c) assert.Equal(t, true, beforeRan) } func TestRateLimiterMemoryStore_Allow(t *testing.T) { var inMemoryStore = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 1, Burst: 3, ExpiresIn: 2 * time.Second}) testCases := []struct { id string allowed bool }{ {"127.0.0.1", true}, // 0 ms {"127.0.0.1", true}, // 220 ms burst #2 {"127.0.0.1", true}, // 440 ms burst #3 {"127.0.0.1", false}, // 660 ms block {"127.0.0.1", false}, // 880 ms block {"127.0.0.1", true}, // 1100 ms next second #1 {"127.0.0.2", true}, // 1320 ms allow other ip {"127.0.0.1", false}, // 1540 ms no burst {"127.0.0.1", false}, // 1760 ms no burst {"127.0.0.1", false}, // 1980 ms no burst {"127.0.0.1", true}, // 2200 ms no burst {"127.0.0.1", false}, // 2420 ms no burst {"127.0.0.1", false}, // 2640 ms no burst {"127.0.0.1", false}, // 2860 ms no burst {"127.0.0.1", true}, // 3080 ms no burst {"127.0.0.1", false}, // 3300 ms no burst {"127.0.0.1", false}, // 3520 ms no burst {"127.0.0.1", false}, // 3740 ms no burst {"127.0.0.1", false}, // 3960 ms no burst {"127.0.0.1", true}, // 4180 ms no burst {"127.0.0.1", false}, // 4400 ms no burst {"127.0.0.1", false}, // 4620 ms no burst {"127.0.0.1", false}, // 4840 ms no burst {"127.0.0.1", true}, // 5060 ms no burst } for i, tc := range testCases { t.Logf("Running testcase #%d => %v", i, time.Duration(i)*220*time.Millisecond) inMemoryStore.timeNow = func() time.Time { return time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC).Add(time.Duration(i) * 220 * time.Millisecond) } allowed, _ := inMemoryStore.Allow(tc.id) assert.Equal(t, tc.allowed, allowed) } } func TestRateLimiterMemoryStore_cleanupStaleVisitors(t *testing.T) { var inMemoryStore = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 1, Burst: 3}) inMemoryStore.visitors = map[string]*Visitor{ "A": { Limiter: rate.NewLimiter(1, 3), lastSeen: time.Now(), }, "B": { Limiter: rate.NewLimiter(1, 3), lastSeen: time.Now().Add(-1 * time.Minute), }, "C": { Limiter: rate.NewLimiter(1, 3), lastSeen: time.Now().Add(-5 * time.Minute), }, "D": { Limiter: rate.NewLimiter(1, 3), lastSeen: time.Now().Add(-10 * time.Minute), }, } inMemoryStore.Allow("D") inMemoryStore.cleanupStaleVisitors() var exists bool _, exists = inMemoryStore.visitors["A"] assert.Equal(t, true, exists) _, exists = inMemoryStore.visitors["B"] assert.Equal(t, true, exists) _, exists = inMemoryStore.visitors["C"] assert.Equal(t, false, exists) _, exists = inMemoryStore.visitors["D"] assert.Equal(t, true, exists) } func TestNewRateLimiterMemoryStore(t *testing.T) { testCases := []struct { rate rate.Limit burst int expiresIn time.Duration expectedExpiresIn time.Duration }{ {1, 3, 5 * time.Second, 5 * time.Second}, {2, 4, 0, 3 * time.Minute}, {1, 5, 10 * time.Minute, 10 * time.Minute}, {3, 7, 0, 3 * time.Minute}, } for _, tc := range testCases { store := NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: tc.rate, Burst: tc.burst, ExpiresIn: tc.expiresIn}) assert.Equal(t, tc.rate, store.rate) assert.Equal(t, tc.burst, store.burst) assert.Equal(t, tc.expectedExpiresIn, store.expiresIn) } } func TestRateLimiterMemoryStore_FractionalRateDefaultBurst(t *testing.T) { store := NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{ Rate: 0.5, // fractional rate should get a burst of at least 1 }) base := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) store.timeNow = func() time.Time { return base } allowed, err := store.Allow("user") assert.NoError(t, err) assert.True(t, allowed, "first request should not be blocked") allowed, err = store.Allow("user") assert.NoError(t, err) assert.False(t, allowed, "burst token should be consumed immediately") store.timeNow = func() time.Time { return base.Add(2 * time.Second) } allowed, err = store.Allow("user") assert.NoError(t, err) assert.True(t, allowed, "token should refill for fractional rate after time passes") } func generateAddressList(count int) []string { addrs := make([]string, count) for i := 0; i < count; i++ { addrs[i] = randomString(15) } return addrs } func run(wg *sync.WaitGroup, store RateLimiterStore, addrs []string, max int, b *testing.B) { for i := 0; i < b.N; i++ { store.Allow(addrs[rand.Intn(max)]) } wg.Done() } func benchmarkStore(store RateLimiterStore, parallel int, max int, b *testing.B) { addrs := generateAddressList(max) wg := &sync.WaitGroup{} for i := 0; i < parallel; i++ { wg.Add(1) go run(wg, store, addrs, max, b) } wg.Wait() } const ( testExpiresIn = 1000 * time.Millisecond ) func BenchmarkRateLimiterMemoryStore_1000(b *testing.B) { var store = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 100, Burst: 200, ExpiresIn: testExpiresIn}) benchmarkStore(store, 10, 1000, b) } func BenchmarkRateLimiterMemoryStore_10000(b *testing.B) { var store = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 100, Burst: 200, ExpiresIn: testExpiresIn}) benchmarkStore(store, 10, 10000, b) } func BenchmarkRateLimiterMemoryStore_100000(b *testing.B) { var store = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 100, Burst: 200, ExpiresIn: testExpiresIn}) benchmarkStore(store, 10, 100000, b) } func BenchmarkRateLimiterMemoryStore_conc100_10000(b *testing.B) { var store = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 100, Burst: 200, ExpiresIn: testExpiresIn}) benchmarkStore(store, 100, 10000, b) } // TestRateLimiterMemoryStore_TOCTOUFix verifies that the TOCTOU race condition is fixed // by ensuring timeNow() is only called once per Allow() call func TestRateLimiterMemoryStore_TOCTOUFix(t *testing.T) { t.Parallel() store := NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{ Rate: 1, Burst: 1, ExpiresIn: 2 * time.Second, }) // Track time calls to verify we use the same time value timeCallCount := 0 baseTime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) store.timeNow = func() time.Time { timeCallCount++ return baseTime } // First request - should succeed allowed, err := store.Allow("127.0.0.1") assert.NoError(t, err) assert.True(t, allowed, "First request should be allowed") // Verify timeNow() was only called once assert.Equal(t, 1, timeCallCount, "timeNow() should only be called once per Allow()") } // TestRateLimiterMemoryStore_ConcurrentAccess verifies rate limiting correctness under concurrent load func TestRateLimiterMemoryStore_ConcurrentAccess(t *testing.T) { t.Parallel() store := NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{ Rate: 10, Burst: 5, ExpiresIn: 5 * time.Second, }) const goroutines = 50 const requestsPerGoroutine = 20 var wg sync.WaitGroup var allowedCount, deniedCount int32 for i := 0; i < goroutines; i++ { wg.Add(1) go func() { defer wg.Done() for j := 0; j < requestsPerGoroutine; j++ { allowed, err := store.Allow("test-user") assert.NoError(t, err) if allowed { atomic.AddInt32(&allowedCount, 1) } else { atomic.AddInt32(&deniedCount, 1) } time.Sleep(time.Millisecond) } }() } wg.Wait() totalRequests := goroutines * requestsPerGoroutine allowed := int(allowedCount) denied := int(deniedCount) assert.Equal(t, totalRequests, allowed+denied, "All requests should be processed") assert.Greater(t, denied, 0, "Some requests should be denied due to rate limiting") assert.Greater(t, allowed, 0, "Some requests should be allowed") } // TestRateLimiterMemoryStore_RaceDetection verifies no data races with high concurrency // Run with: go test -race ./middleware -run TestRateLimiterMemoryStore_RaceDetection func TestRateLimiterMemoryStore_RaceDetection(t *testing.T) { t.Parallel() store := NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{ Rate: 100, Burst: 200, ExpiresIn: 1 * time.Second, }) const goroutines = 100 const requestsPerGoroutine = 100 var wg sync.WaitGroup identifiers := []string{"user1", "user2", "user3", "user4", "user5"} for i := 0; i < goroutines; i++ { wg.Add(1) go func(routineID int) { defer wg.Done() for j := 0; j < requestsPerGoroutine; j++ { identifier := identifiers[routineID%len(identifiers)] _, err := store.Allow(identifier) assert.NoError(t, err) } }(i) } wg.Wait() } // TestRateLimiterMemoryStore_TimeOrdering verifies time ordering consistency in rate limiting decisions func TestRateLimiterMemoryStore_TimeOrdering(t *testing.T) { t.Parallel() store := NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{ Rate: 1, Burst: 2, ExpiresIn: 5 * time.Second, }) currentTime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) store.timeNow = func() time.Time { return currentTime } // First two requests should succeed (burst=2) allowed1, _ := store.Allow("user1") assert.True(t, allowed1, "Request 1 should be allowed (burst)") allowed2, _ := store.Allow("user1") assert.True(t, allowed2, "Request 2 should be allowed (burst)") // Third request should be denied allowed3, _ := store.Allow("user1") assert.False(t, allowed3, "Request 3 should be denied (burst exhausted)") // Advance time by 1 second currentTime = currentTime.Add(1 * time.Second) // Fourth request should succeed allowed4, _ := store.Allow("user1") assert.True(t, allowed4, "Request 4 should be allowed (1 token available)") }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/method_override.go
middleware/method_override.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "net/http" "github.com/labstack/echo/v4" ) // MethodOverrideConfig defines the config for MethodOverride middleware. type MethodOverrideConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // Getter is a function that gets overridden method from the request. // Optional. Default values MethodFromHeader(echo.HeaderXHTTPMethodOverride). Getter MethodOverrideGetter } // MethodOverrideGetter is a function that gets overridden method from the request type MethodOverrideGetter func(echo.Context) string // DefaultMethodOverrideConfig is the default MethodOverride middleware config. var DefaultMethodOverrideConfig = MethodOverrideConfig{ Skipper: DefaultSkipper, Getter: MethodFromHeader(echo.HeaderXHTTPMethodOverride), } // MethodOverride returns a MethodOverride middleware. // MethodOverride middleware checks for the overridden method from the request and // uses it instead of the original method. // // For security reasons, only `POST` method can be overridden. func MethodOverride() echo.MiddlewareFunc { return MethodOverrideWithConfig(DefaultMethodOverrideConfig) } // MethodOverrideWithConfig returns a MethodOverride middleware with config. // See: `MethodOverride()`. func MethodOverrideWithConfig(config MethodOverrideConfig) echo.MiddlewareFunc { // Defaults if config.Skipper == nil { config.Skipper = DefaultMethodOverrideConfig.Skipper } if config.Getter == nil { config.Getter = DefaultMethodOverrideConfig.Getter } return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { if config.Skipper(c) { return next(c) } req := c.Request() if req.Method == http.MethodPost { m := config.Getter(c) if m != "" { req.Method = m } } return next(c) } } } // MethodFromHeader is a `MethodOverrideGetter` that gets overridden method from // the request header. func MethodFromHeader(header string) MethodOverrideGetter { return func(c echo.Context) string { return c.Request().Header.Get(header) } } // MethodFromForm is a `MethodOverrideGetter` that gets overridden method from the // form parameter. func MethodFromForm(param string) MethodOverrideGetter { return func(c echo.Context) string { return c.FormValue(param) } } // MethodFromQuery is a `MethodOverrideGetter` that gets overridden method from // the query parameter. func MethodFromQuery(param string) MethodOverrideGetter { return func(c echo.Context) string { return c.QueryParam(param) } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/key_auth_test.go
middleware/key_auth_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "errors" "net/http" "net/http/httptest" "strings" "testing" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func testKeyValidator(key string, c echo.Context) (bool, error) { switch key { case "valid-key": return true, nil case "error-key": return false, errors.New("some user defined error") default: return false, nil } } func TestKeyAuth(t *testing.T) { handlerCalled := false handler := func(c echo.Context) error { handlerCalled = true return c.String(http.StatusOK, "test") } middlewareChain := KeyAuth(testKeyValidator)(handler) e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderAuthorization, "Bearer valid-key") rec := httptest.NewRecorder() c := e.NewContext(req, rec) err := middlewareChain(c) assert.NoError(t, err) assert.True(t, handlerCalled) } func TestKeyAuthWithConfig(t *testing.T) { var testCases = []struct { name string givenRequestFunc func() *http.Request givenRequest func(req *http.Request) whenConfig func(conf *KeyAuthConfig) expectHandlerCalled bool expectError string }{ { name: "ok, defaults, key from header", givenRequest: func(req *http.Request) { req.Header.Set(echo.HeaderAuthorization, "Bearer valid-key") }, expectHandlerCalled: true, }, { name: "ok, custom skipper", givenRequest: func(req *http.Request) { req.Header.Set(echo.HeaderAuthorization, "Bearer error-key") }, whenConfig: func(conf *KeyAuthConfig) { conf.Skipper = func(context echo.Context) bool { return true } }, expectHandlerCalled: true, }, { name: "nok, defaults, invalid key from header, Authorization: Bearer", givenRequest: func(req *http.Request) { req.Header.Set(echo.HeaderAuthorization, "Bearer invalid-key") }, expectHandlerCalled: false, expectError: "code=401, message=Unauthorized, internal=invalid key", }, { name: "nok, defaults, invalid scheme in header", givenRequest: func(req *http.Request) { req.Header.Set(echo.HeaderAuthorization, "Bear valid-key") }, expectHandlerCalled: false, expectError: "code=400, message=invalid key in the request header", }, { name: "nok, defaults, missing header", givenRequest: func(req *http.Request) {}, expectHandlerCalled: false, expectError: "code=400, message=missing key in request header", }, { name: "ok, custom key lookup from multiple places, query and header", givenRequest: func(req *http.Request) { req.URL.RawQuery = "key=invalid-key" req.Header.Set("API-Key", "valid-key") }, whenConfig: func(conf *KeyAuthConfig) { conf.KeyLookup = "query:key,header:API-Key" }, expectHandlerCalled: true, }, { name: "ok, custom key lookup, header", givenRequest: func(req *http.Request) { req.Header.Set("API-Key", "valid-key") }, whenConfig: func(conf *KeyAuthConfig) { conf.KeyLookup = "header:API-Key" }, expectHandlerCalled: true, }, { name: "nok, custom key lookup, missing header", givenRequest: func(req *http.Request) { }, whenConfig: func(conf *KeyAuthConfig) { conf.KeyLookup = "header:API-Key" }, expectHandlerCalled: false, expectError: "code=400, message=missing key in request header", }, { name: "ok, custom key lookup, query", givenRequest: func(req *http.Request) { q := req.URL.Query() q.Add("key", "valid-key") req.URL.RawQuery = q.Encode() }, whenConfig: func(conf *KeyAuthConfig) { conf.KeyLookup = "query:key" }, expectHandlerCalled: true, }, { name: "nok, custom key lookup, missing query param", whenConfig: func(conf *KeyAuthConfig) { conf.KeyLookup = "query:key" }, expectHandlerCalled: false, expectError: "code=400, message=missing key in the query string", }, { name: "ok, custom key lookup, form", givenRequestFunc: func() *http.Request { req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("key=valid-key")) req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationForm) return req }, whenConfig: func(conf *KeyAuthConfig) { conf.KeyLookup = "form:key" }, expectHandlerCalled: true, }, { name: "nok, custom key lookup, missing key in form", givenRequestFunc: func() *http.Request { req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader("xxx=valid-key")) req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationForm) return req }, whenConfig: func(conf *KeyAuthConfig) { conf.KeyLookup = "form:key" }, expectHandlerCalled: false, expectError: "code=400, message=missing key in the form", }, { name: "ok, custom key lookup, cookie", givenRequest: func(req *http.Request) { req.AddCookie(&http.Cookie{ Name: "key", Value: "valid-key", }) q := req.URL.Query() q.Add("key", "valid-key") req.URL.RawQuery = q.Encode() }, whenConfig: func(conf *KeyAuthConfig) { conf.KeyLookup = "cookie:key" }, expectHandlerCalled: true, }, { name: "nok, custom key lookup, missing cookie param", whenConfig: func(conf *KeyAuthConfig) { conf.KeyLookup = "cookie:key" }, expectHandlerCalled: false, expectError: "code=400, message=missing key in cookies", }, { name: "nok, custom errorHandler, error from extractor", whenConfig: func(conf *KeyAuthConfig) { conf.KeyLookup = "header:token" conf.ErrorHandler = func(err error, context echo.Context) error { httpError := echo.NewHTTPError(http.StatusTeapot, "custom") httpError.Internal = err return httpError } }, expectHandlerCalled: false, expectError: "code=418, message=custom, internal=missing key in request header", }, { name: "nok, custom errorHandler, error from validator", givenRequest: func(req *http.Request) { req.Header.Set(echo.HeaderAuthorization, "Bearer error-key") }, whenConfig: func(conf *KeyAuthConfig) { conf.ErrorHandler = func(err error, context echo.Context) error { httpError := echo.NewHTTPError(http.StatusTeapot, "custom") httpError.Internal = err return httpError } }, expectHandlerCalled: false, expectError: "code=418, message=custom, internal=some user defined error", }, { name: "nok, defaults, error from validator", givenRequest: func(req *http.Request) { req.Header.Set(echo.HeaderAuthorization, "Bearer error-key") }, whenConfig: func(conf *KeyAuthConfig) {}, expectHandlerCalled: false, expectError: "code=401, message=Unauthorized, internal=some user defined error", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { handlerCalled := false handler := func(c echo.Context) error { handlerCalled = true return c.String(http.StatusOK, "test") } config := KeyAuthConfig{ Validator: testKeyValidator, } if tc.whenConfig != nil { tc.whenConfig(&config) } middlewareChain := KeyAuthWithConfig(config)(handler) e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) if tc.givenRequestFunc != nil { req = tc.givenRequestFunc() } if tc.givenRequest != nil { tc.givenRequest(req) } rec := httptest.NewRecorder() c := e.NewContext(req, rec) err := middlewareChain(c) assert.Equal(t, tc.expectHandlerCalled, handlerCalled) if tc.expectError != "" { assert.EqualError(t, err, tc.expectError) } else { assert.NoError(t, err) } }) } } func TestKeyAuthWithConfig_panicsOnInvalidLookup(t *testing.T) { assert.PanicsWithError( t, "extractor source for lookup could not be split into needed parts: a", func() { handler := func(c echo.Context) error { return c.String(http.StatusOK, "test") } KeyAuthWithConfig(KeyAuthConfig{ Validator: testKeyValidator, KeyLookup: "a", })(handler) }, ) } func TestKeyAuthWithConfig_panicsOnEmptyValidator(t *testing.T) { assert.PanicsWithValue( t, "echo: key-auth middleware requires a validator function", func() { handler := func(c echo.Context) error { return c.String(http.StatusOK, "test") } KeyAuthWithConfig(KeyAuthConfig{ Validator: nil, })(handler) }, ) } func TestKeyAuthWithConfig_ContinueOnIgnoredError(t *testing.T) { var testCases = []struct { name string whenContinueOnIgnoredError bool givenKey string expectStatus int expectBody string }{ { name: "no error handler is called", whenContinueOnIgnoredError: true, givenKey: "valid-key", expectStatus: http.StatusTeapot, expectBody: "", }, { name: "ContinueOnIgnoredError is false and error handler is called for missing token", whenContinueOnIgnoredError: false, givenKey: "", // empty response with 200. This emulates previous behaviour when error handler swallowed the error expectStatus: http.StatusOK, expectBody: "", }, { name: "error handler is called for missing token", whenContinueOnIgnoredError: true, givenKey: "", expectStatus: http.StatusTeapot, expectBody: "public-auth", }, { name: "error handler is called for invalid token", whenContinueOnIgnoredError: true, givenKey: "x.x.x", expectStatus: http.StatusUnauthorized, expectBody: "{\"message\":\"Unauthorized\"}\n", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() e.GET("/", func(c echo.Context) error { testValue, _ := c.Get("test").(string) return c.String(http.StatusTeapot, testValue) }) e.Use(KeyAuthWithConfig(KeyAuthConfig{ Validator: testKeyValidator, ErrorHandler: func(err error, c echo.Context) error { if _, ok := err.(*ErrKeyAuthMissing); ok { c.Set("test", "public-auth") return nil } return echo.ErrUnauthorized }, KeyLookup: "header:X-API-Key", ContinueOnIgnoredError: tc.whenContinueOnIgnoredError, })) req := httptest.NewRequest(http.MethodGet, "/", nil) if tc.givenKey != "" { req.Header.Set("X-API-Key", tc.givenKey) } res := httptest.NewRecorder() e.ServeHTTP(res, req) assert.Equal(t, tc.expectStatus, res.Code) assert.Equal(t, tc.expectBody, res.Body.String()) }) } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/redirect_test.go
middleware/redirect_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "net/http" "net/http/httptest" "testing" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) type middlewareGenerator func() echo.MiddlewareFunc func TestRedirectHTTPSRedirect(t *testing.T) { var testCases = []struct { whenHost string whenHeader http.Header expectLocation string expectStatusCode int }{ { whenHost: "labstack.com", expectLocation: "https://labstack.com/", expectStatusCode: http.StatusMovedPermanently, }, { whenHost: "labstack.com", whenHeader: map[string][]string{echo.HeaderXForwardedProto: {"https"}}, expectLocation: "", expectStatusCode: http.StatusOK, }, } for _, tc := range testCases { t.Run(tc.whenHost, func(t *testing.T) { res := redirectTest(HTTPSRedirect, tc.whenHost, tc.whenHeader) assert.Equal(t, tc.expectStatusCode, res.Code) assert.Equal(t, tc.expectLocation, res.Header().Get(echo.HeaderLocation)) }) } } func TestRedirectHTTPSWWWRedirect(t *testing.T) { var testCases = []struct { whenHost string whenHeader http.Header expectLocation string expectStatusCode int }{ { whenHost: "labstack.com", expectLocation: "https://www.labstack.com/", expectStatusCode: http.StatusMovedPermanently, }, { whenHost: "www.labstack.com", expectLocation: "", expectStatusCode: http.StatusOK, }, { whenHost: "a.com", expectLocation: "https://www.a.com/", expectStatusCode: http.StatusMovedPermanently, }, { whenHost: "ip", expectLocation: "https://www.ip/", expectStatusCode: http.StatusMovedPermanently, }, { whenHost: "labstack.com", whenHeader: map[string][]string{echo.HeaderXForwardedProto: {"https"}}, expectLocation: "", expectStatusCode: http.StatusOK, }, } for _, tc := range testCases { t.Run(tc.whenHost, func(t *testing.T) { res := redirectTest(HTTPSWWWRedirect, tc.whenHost, tc.whenHeader) assert.Equal(t, tc.expectStatusCode, res.Code) assert.Equal(t, tc.expectLocation, res.Header().Get(echo.HeaderLocation)) }) } } func TestRedirectHTTPSNonWWWRedirect(t *testing.T) { var testCases = []struct { whenHost string whenHeader http.Header expectLocation string expectStatusCode int }{ { whenHost: "www.labstack.com", expectLocation: "https://labstack.com/", expectStatusCode: http.StatusMovedPermanently, }, { whenHost: "a.com", expectLocation: "https://a.com/", expectStatusCode: http.StatusMovedPermanently, }, { whenHost: "ip", expectLocation: "https://ip/", expectStatusCode: http.StatusMovedPermanently, }, { whenHost: "www.labstack.com", whenHeader: map[string][]string{echo.HeaderXForwardedProto: {"https"}}, expectLocation: "", expectStatusCode: http.StatusOK, }, } for _, tc := range testCases { t.Run(tc.whenHost, func(t *testing.T) { res := redirectTest(HTTPSNonWWWRedirect, tc.whenHost, tc.whenHeader) assert.Equal(t, tc.expectStatusCode, res.Code) assert.Equal(t, tc.expectLocation, res.Header().Get(echo.HeaderLocation)) }) } } func TestRedirectWWWRedirect(t *testing.T) { var testCases = []struct { whenHost string whenHeader http.Header expectLocation string expectStatusCode int }{ { whenHost: "labstack.com", expectLocation: "http://www.labstack.com/", expectStatusCode: http.StatusMovedPermanently, }, { whenHost: "a.com", expectLocation: "http://www.a.com/", expectStatusCode: http.StatusMovedPermanently, }, { whenHost: "ip", expectLocation: "http://www.ip/", expectStatusCode: http.StatusMovedPermanently, }, { whenHost: "a.com", whenHeader: map[string][]string{echo.HeaderXForwardedProto: {"https"}}, expectLocation: "https://www.a.com/", expectStatusCode: http.StatusMovedPermanently, }, { whenHost: "www.ip", expectLocation: "", expectStatusCode: http.StatusOK, }, } for _, tc := range testCases { t.Run(tc.whenHost, func(t *testing.T) { res := redirectTest(WWWRedirect, tc.whenHost, tc.whenHeader) assert.Equal(t, tc.expectStatusCode, res.Code) assert.Equal(t, tc.expectLocation, res.Header().Get(echo.HeaderLocation)) }) } } func TestRedirectNonWWWRedirect(t *testing.T) { var testCases = []struct { whenHost string whenHeader http.Header expectLocation string expectStatusCode int }{ { whenHost: "www.labstack.com", expectLocation: "http://labstack.com/", expectStatusCode: http.StatusMovedPermanently, }, { whenHost: "www.a.com", expectLocation: "http://a.com/", expectStatusCode: http.StatusMovedPermanently, }, { whenHost: "www.a.com", whenHeader: map[string][]string{echo.HeaderXForwardedProto: {"https"}}, expectLocation: "https://a.com/", expectStatusCode: http.StatusMovedPermanently, }, { whenHost: "ip", expectLocation: "", expectStatusCode: http.StatusOK, }, } for _, tc := range testCases { t.Run(tc.whenHost, func(t *testing.T) { res := redirectTest(NonWWWRedirect, tc.whenHost, tc.whenHeader) assert.Equal(t, tc.expectStatusCode, res.Code) assert.Equal(t, tc.expectLocation, res.Header().Get(echo.HeaderLocation)) }) } } func TestNonWWWRedirectWithConfig(t *testing.T) { var testCases = []struct { name string givenCode int givenSkipFunc func(c echo.Context) bool whenHost string whenHeader http.Header expectLocation string expectStatusCode int }{ { name: "usual redirect", whenHost: "www.labstack.com", expectLocation: "http://labstack.com/", expectStatusCode: http.StatusMovedPermanently, }, { name: "redirect is skipped", givenSkipFunc: func(c echo.Context) bool { return true // skip always }, whenHost: "www.labstack.com", expectLocation: "", expectStatusCode: http.StatusOK, }, { name: "redirect with custom status code", givenCode: http.StatusSeeOther, whenHost: "www.labstack.com", expectLocation: "http://labstack.com/", expectStatusCode: http.StatusSeeOther, }, } for _, tc := range testCases { t.Run(tc.whenHost, func(t *testing.T) { middleware := func() echo.MiddlewareFunc { return NonWWWRedirectWithConfig(RedirectConfig{ Skipper: tc.givenSkipFunc, Code: tc.givenCode, }) } res := redirectTest(middleware, tc.whenHost, tc.whenHeader) assert.Equal(t, tc.expectStatusCode, res.Code) assert.Equal(t, tc.expectLocation, res.Header().Get(echo.HeaderLocation)) }) } } func redirectTest(fn middlewareGenerator, host string, header http.Header) *httptest.ResponseRecorder { e := echo.New() next := func(c echo.Context) (err error) { return c.NoContent(http.StatusOK) } req := httptest.NewRequest(http.MethodGet, "/", nil) req.Host = host if header != nil { req.Header = header } res := httptest.NewRecorder() c := e.NewContext(req, res) fn()(next)(c) return res }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/timeout_test.go
middleware/timeout_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "bytes" "context" "errors" "fmt" "io" "log" "net" "net/http" "net/http/httptest" "net/url" "reflect" "strings" "sync" "testing" "time" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func TestTimeoutSkipper(t *testing.T) { t.Parallel() m := TimeoutWithConfig(TimeoutConfig{ Skipper: func(context echo.Context) bool { return true }, Timeout: 1 * time.Nanosecond, }) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e := echo.New() c := e.NewContext(req, rec) err := m(func(c echo.Context) error { time.Sleep(25 * time.Microsecond) return errors.New("response from handler") })(c) // if not skipped we would have not returned error due context timeout logic assert.EqualError(t, err, "response from handler") } func TestTimeoutWithTimeout0(t *testing.T) { t.Parallel() m := Timeout() req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e := echo.New() c := e.NewContext(req, rec) err := m(func(c echo.Context) error { assert.NotEqual(t, "*context.timerCtx", reflect.TypeOf(c.Request().Context()).String()) return nil })(c) assert.NoError(t, err) } func TestTimeoutErrorOutInHandler(t *testing.T) { t.Parallel() m := TimeoutWithConfig(TimeoutConfig{ // Timeout has to be defined or the whole flow for timeout middleware will be skipped Timeout: 50 * time.Millisecond, }) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e := echo.New() c := e.NewContext(req, rec) rec.Code = 1 // we want to be sure that even 200 will not be sent err := m(func(c echo.Context) error { // this error must not be written to the client response. Middlewares upstream of timeout middleware must be able // to handle returned error and this can be done only then handler has not yet committed (written status code) // the response. return echo.NewHTTPError(http.StatusTeapot, "err") })(c) assert.Error(t, err) assert.EqualError(t, err, "code=418, message=err") assert.Equal(t, 1, rec.Code) assert.Equal(t, "", rec.Body.String()) } func TestTimeoutSuccessfulRequest(t *testing.T) { t.Parallel() m := TimeoutWithConfig(TimeoutConfig{ // Timeout has to be defined or the whole flow for timeout middleware will be skipped Timeout: 50 * time.Millisecond, }) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e := echo.New() c := e.NewContext(req, rec) err := m(func(c echo.Context) error { return c.JSON(http.StatusCreated, map[string]string{"data": "ok"}) })(c) assert.NoError(t, err) assert.Equal(t, http.StatusCreated, rec.Code) assert.Equal(t, "{\"data\":\"ok\"}\n", rec.Body.String()) } func TestTimeoutOnTimeoutRouteErrorHandler(t *testing.T) { t.Parallel() actualErrChan := make(chan error, 1) m := TimeoutWithConfig(TimeoutConfig{ Timeout: 1 * time.Millisecond, OnTimeoutRouteErrorHandler: func(err error, c echo.Context) { actualErrChan <- err }, }) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e := echo.New() c := e.NewContext(req, rec) stopChan := make(chan struct{}) err := m(func(c echo.Context) error { <-stopChan return errors.New("error in route after timeout") })(c) stopChan <- struct{}{} assert.NoError(t, err) actualErr := <-actualErrChan assert.EqualError(t, actualErr, "error in route after timeout") } func TestTimeoutTestRequestClone(t *testing.T) { t.Parallel() req := httptest.NewRequest(http.MethodPost, "/uri?query=value", strings.NewReader(url.Values{"form": {"value"}}.Encode())) req.AddCookie(&http.Cookie{Name: "cookie", Value: "value"}) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") rec := httptest.NewRecorder() m := TimeoutWithConfig(TimeoutConfig{ // Timeout has to be defined or the whole flow for timeout middleware will be skipped Timeout: 1 * time.Second, }) e := echo.New() c := e.NewContext(req, rec) err := m(func(c echo.Context) error { // Cookie test cookie, err := c.Request().Cookie("cookie") if assert.NoError(t, err) { assert.EqualValues(t, "cookie", cookie.Name) assert.EqualValues(t, "value", cookie.Value) } // Form values if assert.NoError(t, c.Request().ParseForm()) { assert.EqualValues(t, "value", c.Request().FormValue("form")) } // Query string assert.EqualValues(t, "value", c.Request().URL.Query()["query"][0]) return nil })(c) assert.NoError(t, err) } //func TestTimeoutRecoversPanic(t *testing.T) { // t.Parallel() // e := echo.New() // e.Use(Recover()) // recover middleware will handler our panic // e.Use(TimeoutWithConfig(TimeoutConfig{ // Timeout: 50 * time.Millisecond, // })) // // e.GET("/", func(c echo.Context) error { // panic("panic!!!") // }) // // req := httptest.NewRequest(http.MethodGet, "/", nil) // rec := httptest.NewRecorder() // // assert.NotPanics(t, func() { // e.ServeHTTP(rec, req) // }) //} func TestTimeoutDataRace(t *testing.T) { t.Parallel() timeout := 1 * time.Millisecond m := TimeoutWithConfig(TimeoutConfig{ Timeout: timeout, ErrorMessage: "Timeout! change me", }) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e := echo.New() c := e.NewContext(req, rec) err := m(func(c echo.Context) error { // NOTE: when difference between timeout duration and handler execution time is almost the same (in range of 100microseconds) // the result of timeout does not seem to be reliable - could respond timeout, could respond handler output // difference over 500microseconds (0.5millisecond) response seems to be reliable time.Sleep(timeout) // timeout and handler execution time difference is close to zero return c.String(http.StatusOK, "Hello, World!") })(c) assert.NoError(t, err) if rec.Code == http.StatusServiceUnavailable { assert.Equal(t, "Timeout! change me", rec.Body.String()) } else { assert.Equal(t, "Hello, World!", rec.Body.String()) } } func TestTimeoutWithErrorMessage(t *testing.T) { t.Parallel() timeout := 1 * time.Millisecond m := TimeoutWithConfig(TimeoutConfig{ Timeout: timeout, ErrorMessage: "Timeout! change me", }) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e := echo.New() c := e.NewContext(req, rec) stopChan := make(chan struct{}) err := m(func(c echo.Context) error { // NOTE: when difference between timeout duration and handler execution time is almost the same (in range of 100microseconds) // the result of timeout does not seem to be reliable - could respond timeout, could respond handler output // difference over 500microseconds (0.5millisecond) response seems to be reliable <-stopChan return c.String(http.StatusOK, "Hello, World!") })(c) stopChan <- struct{}{} assert.NoError(t, err) assert.Equal(t, http.StatusServiceUnavailable, rec.Code) assert.Equal(t, "Timeout! change me", rec.Body.String()) } func TestTimeoutWithDefaultErrorMessage(t *testing.T) { t.Parallel() timeout := 1 * time.Millisecond m := TimeoutWithConfig(TimeoutConfig{ Timeout: timeout, ErrorMessage: "", }) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e := echo.New() c := e.NewContext(req, rec) stopChan := make(chan struct{}) err := m(func(c echo.Context) error { <-stopChan return c.String(http.StatusOK, "Hello, World!") })(c) stopChan <- struct{}{} assert.NoError(t, err) assert.Equal(t, http.StatusServiceUnavailable, rec.Code) assert.Equal(t, `<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>`, rec.Body.String()) } func TestTimeoutCanHandleContextDeadlineOnNextHandler(t *testing.T) { t.Parallel() timeout := 1 * time.Millisecond m := TimeoutWithConfig(TimeoutConfig{ Timeout: timeout, ErrorMessage: "Timeout! change me", }) handlerFinishedExecution := make(chan bool) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e := echo.New() c := e.NewContext(req, rec) stopChan := make(chan struct{}) err := m(func(c echo.Context) error { // NOTE: when difference between timeout duration and handler execution time is almost the same (in range of 100microseconds) // the result of timeout does not seem to be reliable - could respond timeout, could respond handler output // difference over 500microseconds (0.5millisecond) response seems to be reliable <-stopChan // The Request Context should have a Deadline set by http.TimeoutHandler if _, ok := c.Request().Context().Deadline(); !ok { assert.Fail(t, "No timeout set on Request Context") } handlerFinishedExecution <- c.Request().Context().Err() == nil return c.String(http.StatusOK, "Hello, World!") })(c) stopChan <- struct{}{} assert.NoError(t, err) assert.Equal(t, http.StatusServiceUnavailable, rec.Code) assert.Equal(t, "Timeout! change me", rec.Body.String()) assert.False(t, <-handlerFinishedExecution) } func TestTimeoutWithFullEchoStack(t *testing.T) { // test timeout with full http server stack running, do see what http.Server.ErrorLog contains var testCases = []struct { name string whenPath string whenForceHandlerTimeout bool expectStatusCode int expectResponse string expectLogContains []string expectLogNotContains []string }{ { name: "404 - write response in global error handler", whenPath: "/404", expectResponse: "{\"message\":\"Not Found\"}\n", expectStatusCode: http.StatusNotFound, expectLogNotContains: []string{"echo:http: superfluous response.WriteHeader call from"}, expectLogContains: []string{`"status":404,"error":"code=404, message=Not Found"`}, }, { name: "418 - write response in handler", whenPath: "/", expectResponse: "{\"message\":\"OK\"}\n", expectStatusCode: http.StatusTeapot, expectLogNotContains: []string{"echo:http: superfluous response.WriteHeader call from"}, expectLogContains: []string{`"status":418,"error":"",`}, }, { name: "503 - handler timeouts, write response in timeout middleware", whenForceHandlerTimeout: true, whenPath: "/", expectResponse: "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>", expectStatusCode: http.StatusServiceUnavailable, expectLogNotContains: []string{ "echo:http: superfluous response.WriteHeader call from", }, expectLogContains: []string{"http: Handler timeout"}, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() buf := new(coroutineSafeBuffer) e.Logger.SetOutput(buf) // NOTE: timeout middleware is first as it changes Response.Writer and causes data race for logger middleware if it is not first e.Use(TimeoutWithConfig(TimeoutConfig{ Timeout: 100 * time.Millisecond, })) e.Use(Logger()) e.Use(Recover()) wg := sync.WaitGroup{} if tc.whenForceHandlerTimeout { wg.Add(1) // make `wg.Wait()` block until we release it with `wg.Done()` } e.GET("/", func(c echo.Context) error { wg.Wait() return c.JSON(http.StatusTeapot, map[string]string{"message": "OK"}) }) server, addr, err := startServer(e) if err != nil { assert.NoError(t, err) return } defer server.Close() res, err := http.Get(fmt.Sprintf("http://%v%v", addr, tc.whenPath)) if err != nil { assert.NoError(t, err) return } if tc.whenForceHandlerTimeout { wg.Done() // extremely short periods are not reliable for tests when it comes to goroutines. We can not guarantee in which // order scheduler decides do execute: 1) request goroutine, 2) timeout timer goroutine. // most of the time we get result we expect but Mac OS seems to be quite flaky time.Sleep(50 * time.Millisecond) // shutdown waits for server to shutdown. this way we wait logger mw to be executed ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() server.Shutdown(ctx) } assert.Equal(t, tc.expectStatusCode, res.StatusCode) if body, err := io.ReadAll(res.Body); err == nil { assert.Equal(t, tc.expectResponse, string(body)) } else { assert.Fail(t, err.Error()) } logged := buf.String() for _, subStr := range tc.expectLogContains { assert.True(t, strings.Contains(logged, subStr), "expected logs to contain: %v, logged: '%v'", subStr, logged) } for _, subStr := range tc.expectLogNotContains { assert.False(t, strings.Contains(logged, subStr), "expected logs not to contain: %v, logged: '%v'", subStr, logged) } }) } } // as we are spawning multiple coroutines - one for http server, one for request, one by timeout middleware, one by testcase // we are accessing logger (writing/reading) from multiple coroutines and causing dataraces (most often reported on macos) // we could be writing to logger in logger middleware and at the same time our tests is getting logger buffer contents // in testcase coroutine. type coroutineSafeBuffer struct { bytes.Buffer lock sync.RWMutex } func (b *coroutineSafeBuffer) Write(p []byte) (n int, err error) { b.lock.Lock() defer b.lock.Unlock() return b.Buffer.Write(p) } func (b *coroutineSafeBuffer) Bytes() []byte { b.lock.RLock() defer b.lock.RUnlock() return b.Buffer.Bytes() } func (b *coroutineSafeBuffer) String() string { b.lock.RLock() defer b.lock.RUnlock() return b.Buffer.String() } func startServer(e *echo.Echo) (*http.Server, string, error) { l, err := net.Listen("tcp", ":0") if err != nil { return nil, "", err } s := http.Server{ Handler: e, ErrorLog: log.New(e.Logger.Output(), "echo:", 0), } errCh := make(chan error) go func() { if err := s.Serve(l); err != http.ErrServerClosed { errCh <- err } }() select { case <-time.After(10 * time.Millisecond): return &s, l.Addr().String(), nil case err := <-errCh: return nil, "", err } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/extractor_test.go
middleware/extractor_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "bytes" "fmt" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" "mime/multipart" "net/http" "net/http/httptest" "net/url" "strings" "testing" ) type pathParam struct { name string value string } func setPathParams(c echo.Context, params []pathParam) { names := make([]string, 0, len(params)) values := make([]string, 0, len(params)) for _, pp := range params { names = append(names, pp.name) values = append(values, pp.value) } c.SetParamNames(names...) c.SetParamValues(values...) } func TestCreateExtractors(t *testing.T) { var testCases = []struct { name string givenRequest func() *http.Request givenPathParams []pathParam whenLoopups string expectValues []string expectCreateError string expectError string }{ { name: "ok, header", givenRequest: func() *http.Request { req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderAuthorization, "Bearer token") return req }, whenLoopups: "header:Authorization:Bearer ", expectValues: []string{"token"}, }, { name: "ok, form", givenRequest: func() *http.Request { f := make(url.Values) f.Set("name", "Jon Snow") req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(f.Encode())) req.Header.Add(echo.HeaderContentType, echo.MIMEApplicationForm) return req }, whenLoopups: "form:name", expectValues: []string{"Jon Snow"}, }, { name: "ok, cookie", givenRequest: func() *http.Request { req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderCookie, "_csrf=token") return req }, whenLoopups: "cookie:_csrf", expectValues: []string{"token"}, }, { name: "ok, param", givenPathParams: []pathParam{ {name: "id", value: "123"}, }, whenLoopups: "param:id", expectValues: []string{"123"}, }, { name: "ok, query", givenRequest: func() *http.Request { req := httptest.NewRequest(http.MethodGet, "/?id=999", nil) return req }, whenLoopups: "query:id", expectValues: []string{"999"}, }, { name: "nok, invalid lookup", whenLoopups: "query", expectCreateError: "extractor source for lookup could not be split into needed parts: query", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) if tc.givenRequest != nil { req = tc.givenRequest() } rec := httptest.NewRecorder() c := e.NewContext(req, rec) if tc.givenPathParams != nil { setPathParams(c, tc.givenPathParams) } extractors, err := CreateExtractors(tc.whenLoopups) if tc.expectCreateError != "" { assert.EqualError(t, err, tc.expectCreateError) return } assert.NoError(t, err) for _, e := range extractors { values, eErr := e(c) assert.Equal(t, tc.expectValues, values) if tc.expectError != "" { assert.EqualError(t, eErr, tc.expectError) return } assert.NoError(t, eErr) } }) } } func TestValuesFromHeader(t *testing.T) { exampleRequest := func(req *http.Request) { req.Header.Set(echo.HeaderAuthorization, "basic dXNlcjpwYXNzd29yZA==") } var testCases = []struct { name string givenRequest func(req *http.Request) whenName string whenValuePrefix string expectValues []string expectError string }{ { name: "ok, single value", givenRequest: exampleRequest, whenName: echo.HeaderAuthorization, whenValuePrefix: "basic ", expectValues: []string{"dXNlcjpwYXNzd29yZA=="}, }, { name: "ok, single value, case insensitive", givenRequest: exampleRequest, whenName: echo.HeaderAuthorization, whenValuePrefix: "Basic ", expectValues: []string{"dXNlcjpwYXNzd29yZA=="}, }, { name: "ok, multiple value", givenRequest: func(req *http.Request) { req.Header.Set(echo.HeaderAuthorization, "basic dXNlcjpwYXNzd29yZA==") req.Header.Add(echo.HeaderAuthorization, "basic dGVzdDp0ZXN0") }, whenName: echo.HeaderAuthorization, whenValuePrefix: "basic ", expectValues: []string{"dXNlcjpwYXNzd29yZA==", "dGVzdDp0ZXN0"}, }, { name: "ok, empty prefix", givenRequest: exampleRequest, whenName: echo.HeaderAuthorization, whenValuePrefix: "", expectValues: []string{"basic dXNlcjpwYXNzd29yZA=="}, }, { name: "nok, no matching due different prefix", givenRequest: func(req *http.Request) { req.Header.Set(echo.HeaderAuthorization, "basic dXNlcjpwYXNzd29yZA==") req.Header.Add(echo.HeaderAuthorization, "basic dGVzdDp0ZXN0") }, whenName: echo.HeaderAuthorization, whenValuePrefix: "Bearer ", expectError: errHeaderExtractorValueInvalid.Error(), }, { name: "nok, no matching due different prefix", givenRequest: func(req *http.Request) { req.Header.Set(echo.HeaderAuthorization, "basic dXNlcjpwYXNzd29yZA==") req.Header.Add(echo.HeaderAuthorization, "basic dGVzdDp0ZXN0") }, whenName: echo.HeaderWWWAuthenticate, whenValuePrefix: "", expectError: errHeaderExtractorValueMissing.Error(), }, { name: "nok, no headers", givenRequest: nil, whenName: echo.HeaderAuthorization, whenValuePrefix: "basic ", expectError: errHeaderExtractorValueMissing.Error(), }, { name: "ok, prefix, cut values over extractorLimit", givenRequest: func(req *http.Request) { for i := 1; i <= 25; i++ { req.Header.Add(echo.HeaderAuthorization, fmt.Sprintf("basic %v", i)) } }, whenName: echo.HeaderAuthorization, whenValuePrefix: "basic ", expectValues: []string{ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", }, }, { name: "ok, cut values over extractorLimit", givenRequest: func(req *http.Request) { for i := 1; i <= 25; i++ { req.Header.Add(echo.HeaderAuthorization, fmt.Sprintf("%v", i)) } }, whenName: echo.HeaderAuthorization, whenValuePrefix: "", expectValues: []string{ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", }, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) if tc.givenRequest != nil { tc.givenRequest(req) } rec := httptest.NewRecorder() c := e.NewContext(req, rec) extractor := valuesFromHeader(tc.whenName, tc.whenValuePrefix) values, err := extractor(c) assert.Equal(t, tc.expectValues, values) if tc.expectError != "" { assert.EqualError(t, err, tc.expectError) } else { assert.NoError(t, err) } }) } } func TestValuesFromQuery(t *testing.T) { var testCases = []struct { name string givenQueryPart string whenName string expectValues []string expectError string }{ { name: "ok, single value", givenQueryPart: "?id=123&name=test", whenName: "id", expectValues: []string{"123"}, }, { name: "ok, multiple value", givenQueryPart: "?id=123&id=456&name=test", whenName: "id", expectValues: []string{"123", "456"}, }, { name: "nok, missing value", givenQueryPart: "?id=123&name=test", whenName: "nope", expectError: errQueryExtractorValueMissing.Error(), }, { name: "ok, cut values over extractorLimit", givenQueryPart: "?name=test" + "&id=1&id=2&id=3&id=4&id=5&id=6&id=7&id=8&id=9&id=10" + "&id=11&id=12&id=13&id=14&id=15&id=16&id=17&id=18&id=19&id=20" + "&id=21&id=22&id=23&id=24&id=25", whenName: "id", expectValues: []string{ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", }, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/"+tc.givenQueryPart, nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) extractor := valuesFromQuery(tc.whenName) values, err := extractor(c) assert.Equal(t, tc.expectValues, values) if tc.expectError != "" { assert.EqualError(t, err, tc.expectError) } else { assert.NoError(t, err) } }) } } func TestValuesFromParam(t *testing.T) { examplePathParams := []pathParam{ {name: "id", value: "123"}, {name: "gid", value: "456"}, {name: "gid", value: "789"}, } examplePathParams20 := make([]pathParam, 0) for i := 1; i < 25; i++ { examplePathParams20 = append(examplePathParams20, pathParam{name: "id", value: fmt.Sprintf("%v", i)}) } var testCases = []struct { name string givenPathParams []pathParam whenName string expectValues []string expectError string }{ { name: "ok, single value", givenPathParams: examplePathParams, whenName: "id", expectValues: []string{"123"}, }, { name: "ok, multiple value", givenPathParams: examplePathParams, whenName: "gid", expectValues: []string{"456", "789"}, }, { name: "nok, no values", givenPathParams: nil, whenName: "nope", expectValues: nil, expectError: errParamExtractorValueMissing.Error(), }, { name: "nok, no matching value", givenPathParams: examplePathParams, whenName: "nope", expectValues: nil, expectError: errParamExtractorValueMissing.Error(), }, { name: "ok, cut values over extractorLimit", givenPathParams: examplePathParams20, whenName: "id", expectValues: []string{ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", }, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) if tc.givenPathParams != nil { setPathParams(c, tc.givenPathParams) } extractor := valuesFromParam(tc.whenName) values, err := extractor(c) assert.Equal(t, tc.expectValues, values) if tc.expectError != "" { assert.EqualError(t, err, tc.expectError) } else { assert.NoError(t, err) } }) } } func TestValuesFromCookie(t *testing.T) { exampleRequest := func(req *http.Request) { req.Header.Set(echo.HeaderCookie, "_csrf=token") } var testCases = []struct { name string givenRequest func(req *http.Request) whenName string expectValues []string expectError string }{ { name: "ok, single value", givenRequest: exampleRequest, whenName: "_csrf", expectValues: []string{"token"}, }, { name: "ok, multiple value", givenRequest: func(req *http.Request) { req.Header.Add(echo.HeaderCookie, "_csrf=token") req.Header.Add(echo.HeaderCookie, "_csrf=token2") }, whenName: "_csrf", expectValues: []string{"token", "token2"}, }, { name: "nok, no matching cookie", givenRequest: exampleRequest, whenName: "xxx", expectValues: nil, expectError: errCookieExtractorValueMissing.Error(), }, { name: "nok, no cookies at all", givenRequest: nil, whenName: "xxx", expectValues: nil, expectError: errCookieExtractorValueMissing.Error(), }, { name: "ok, cut values over extractorLimit", givenRequest: func(req *http.Request) { for i := 1; i < 25; i++ { req.Header.Add(echo.HeaderCookie, fmt.Sprintf("_csrf=%v", i)) } }, whenName: "_csrf", expectValues: []string{ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", }, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) if tc.givenRequest != nil { tc.givenRequest(req) } rec := httptest.NewRecorder() c := e.NewContext(req, rec) extractor := valuesFromCookie(tc.whenName) values, err := extractor(c) assert.Equal(t, tc.expectValues, values) if tc.expectError != "" { assert.EqualError(t, err, tc.expectError) } else { assert.NoError(t, err) } }) } } func TestValuesFromForm(t *testing.T) { examplePostFormRequest := func(mod func(v *url.Values)) *http.Request { f := make(url.Values) f.Set("name", "Jon Snow") f.Set("emails[]", "jon@labstack.com") if mod != nil { mod(&f) } req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(f.Encode())) req.Header.Add(echo.HeaderContentType, echo.MIMEApplicationForm) return req } exampleGetFormRequest := func(mod func(v *url.Values)) *http.Request { f := make(url.Values) f.Set("name", "Jon Snow") f.Set("emails[]", "jon@labstack.com") if mod != nil { mod(&f) } req := httptest.NewRequest(http.MethodGet, "/?"+f.Encode(), nil) return req } exampleMultiPartFormRequest := func(mod func(w *multipart.Writer)) *http.Request { var b bytes.Buffer w := multipart.NewWriter(&b) w.WriteField("name", "Jon Snow") w.WriteField("emails[]", "jon@labstack.com") if mod != nil { mod(w) } fw, _ := w.CreateFormFile("upload", "my.file") fw.Write([]byte(`<div>hi</div>`)) w.Close() req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(b.String())) req.Header.Add(echo.HeaderContentType, w.FormDataContentType()) return req } var testCases = []struct { name string givenRequest *http.Request whenName string expectValues []string expectError string }{ { name: "ok, POST form, single value", givenRequest: examplePostFormRequest(nil), whenName: "emails[]", expectValues: []string{"jon@labstack.com"}, }, { name: "ok, POST form, multiple value", givenRequest: examplePostFormRequest(func(v *url.Values) { v.Add("emails[]", "snow@labstack.com") }), whenName: "emails[]", expectValues: []string{"jon@labstack.com", "snow@labstack.com"}, }, { name: "ok, POST multipart/form, multiple value", givenRequest: exampleMultiPartFormRequest(func(w *multipart.Writer) { w.WriteField("emails[]", "snow@labstack.com") }), whenName: "emails[]", expectValues: []string{"jon@labstack.com", "snow@labstack.com"}, }, { name: "ok, GET form, single value", givenRequest: exampleGetFormRequest(nil), whenName: "emails[]", expectValues: []string{"jon@labstack.com"}, }, { name: "ok, GET form, multiple value", givenRequest: examplePostFormRequest(func(v *url.Values) { v.Add("emails[]", "snow@labstack.com") }), whenName: "emails[]", expectValues: []string{"jon@labstack.com", "snow@labstack.com"}, }, { name: "nok, POST form, value missing", givenRequest: examplePostFormRequest(nil), whenName: "nope", expectError: errFormExtractorValueMissing.Error(), }, { name: "ok, cut values over extractorLimit", givenRequest: examplePostFormRequest(func(v *url.Values) { for i := 1; i < 25; i++ { v.Add("id[]", fmt.Sprintf("%v", i)) } }), whenName: "id[]", expectValues: []string{ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", }, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() req := tc.givenRequest rec := httptest.NewRecorder() c := e.NewContext(req, rec) extractor := valuesFromForm(tc.whenName) values, err := extractor(c) assert.Equal(t, tc.expectValues, values) if tc.expectError != "" { assert.EqualError(t, err, tc.expectError) } else { assert.NoError(t, err) } }) } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/request_id_test.go
middleware/request_id_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "net/http" "net/http/httptest" "testing" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func TestRequestID(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) handler := func(c echo.Context) error { return c.String(http.StatusOK, "test") } rid := RequestIDWithConfig(RequestIDConfig{}) h := rid(handler) h(c) assert.Len(t, rec.Header().Get(echo.HeaderXRequestID), 32) // Custom generator and handler customID := "customGenerator" calledHandler := false rid = RequestIDWithConfig(RequestIDConfig{ Generator: func() string { return customID }, RequestIDHandler: func(_ echo.Context, id string) { calledHandler = true assert.Equal(t, customID, id) }, }) h = rid(handler) h(c) assert.Equal(t, rec.Header().Get(echo.HeaderXRequestID), "customGenerator") assert.True(t, calledHandler) } func TestRequestID_IDNotAltered(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Add(echo.HeaderXRequestID, "<sample-request-id>") rec := httptest.NewRecorder() c := e.NewContext(req, rec) handler := func(c echo.Context) error { return c.String(http.StatusOK, "test") } rid := RequestIDWithConfig(RequestIDConfig{}) h := rid(handler) _ = h(c) assert.Equal(t, rec.Header().Get(echo.HeaderXRequestID), "<sample-request-id>") } func TestRequestIDConfigDifferentHeader(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) handler := func(c echo.Context) error { return c.String(http.StatusOK, "test") } rid := RequestIDWithConfig(RequestIDConfig{TargetHeader: echo.HeaderXCorrelationID}) h := rid(handler) h(c) assert.Len(t, rec.Header().Get(echo.HeaderXCorrelationID), 32) // Custom generator and handler customID := "customGenerator" calledHandler := false rid = RequestIDWithConfig(RequestIDConfig{ Generator: func() string { return customID }, TargetHeader: echo.HeaderXCorrelationID, RequestIDHandler: func(_ echo.Context, id string) { calledHandler = true assert.Equal(t, customID, id) }, }) h = rid(handler) h(c) assert.Equal(t, rec.Header().Get(echo.HeaderXCorrelationID), "customGenerator") assert.True(t, calledHandler) }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/util.go
middleware/util.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "bufio" "crypto/rand" "fmt" "io" "net/url" "strings" "sync" ) func matchScheme(domain, pattern string) bool { didx := strings.Index(domain, ":") pidx := strings.Index(pattern, ":") return didx != -1 && pidx != -1 && domain[:didx] == pattern[:pidx] } // matchSubdomain compares authority with wildcard func matchSubdomain(domain, pattern string) bool { if !matchScheme(domain, pattern) { return false } didx := strings.Index(domain, "://") pidx := strings.Index(pattern, "://") if didx == -1 || pidx == -1 { return false } domAuth := domain[didx+3:] // to avoid long loop by invalid long domain if len(domAuth) > 253 { return false } patAuth := pattern[pidx+3:] domComp := strings.Split(domAuth, ".") patComp := strings.Split(patAuth, ".") for i := len(domComp)/2 - 1; i >= 0; i-- { opp := len(domComp) - 1 - i domComp[i], domComp[opp] = domComp[opp], domComp[i] } for i := len(patComp)/2 - 1; i >= 0; i-- { opp := len(patComp) - 1 - i patComp[i], patComp[opp] = patComp[opp], patComp[i] } for i, v := range domComp { if len(patComp) <= i { return false } p := patComp[i] if p == "*" { return true } if p != v { return false } } return false } // https://tip.golang.org/doc/go1.19#:~:text=Read%20no%20longer%20buffers%20random%20data%20obtained%20from%20the%20operating%20system%20between%20calls var randomReaderPool = sync.Pool{New: func() interface{} { return bufio.NewReader(rand.Reader) }} const randomStringCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" const randomStringCharsetLen = 52 // len(randomStringCharset) const randomStringMaxByte = 255 - (256 % randomStringCharsetLen) func randomString(length uint8) string { reader := randomReaderPool.Get().(*bufio.Reader) defer randomReaderPool.Put(reader) b := make([]byte, length) r := make([]byte, length+(length/4)) // perf: avoid read from rand.Reader many times var i uint8 = 0 // security note: // we can't just simply do b[i]=randomStringCharset[rb%len(randomStringCharset)], // len(len(randomStringCharset)) is 52, and rb is [0, 255], 256 = 52 * 4 + 48. // make the first 48 characters more possibly to be generated then others. // So we have to skip bytes when rb > randomStringMaxByte for { _, err := io.ReadFull(reader, r) if err != nil { panic("unexpected error happened when reading from bufio.NewReader(crypto/rand.Reader)") } for _, rb := range r { if rb > randomStringMaxByte { // Skip this number to avoid bias. continue } b[i] = randomStringCharset[rb%randomStringCharsetLen] i++ if i == length { return string(b) } } } } func validateOrigins(origins []string, what string) error { for _, o := range origins { if err := validateOrigin(o, what); err != nil { return err } } return nil } func validateOrigin(origin string, what string) error { u, err := url.Parse(origin) if err != nil { return fmt.Errorf("can not parse %s: %w", what, err) } if u.Scheme == "" || u.Host == "" { return fmt.Errorf("%s is missing scheme or host: %s", what, origin) } if u.Path != "" || u.RawQuery != "" || u.Fragment != "" { return fmt.Errorf("%s can not have path, query, and fragments: %s", what, origin) } return nil }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/logger_strings_test.go
middleware/logger_strings_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "bytes" "testing" "github.com/stretchr/testify/assert" ) func TestWriteJSONSafeString(t *testing.T) { testCases := []struct { name string whenInput string expect string expectN int }{ // Basic cases { name: "empty string", whenInput: "", expect: "", expectN: 0, }, { name: "simple ASCII without special chars", whenInput: "hello", expect: "hello", expectN: 5, }, { name: "single character", whenInput: "a", expect: "a", expectN: 1, }, { name: "alphanumeric", whenInput: "Hello123World", expect: "Hello123World", expectN: 13, }, // Special character escaping { name: "backslash", whenInput: `path\to\file`, expect: `path\\to\\file`, expectN: 14, }, { name: "double quote", whenInput: `say "hello"`, expect: `say \"hello\"`, expectN: 13, }, { name: "backslash and quote combined", whenInput: `a\b"c`, expect: `a\\b\"c`, expectN: 7, }, { name: "single backslash", whenInput: `\`, expect: `\\`, expectN: 2, }, { name: "single quote", whenInput: `"`, expect: `\"`, expectN: 2, }, // Control character escaping { name: "backspace", whenInput: "hello\bworld", expect: `hello\bworld`, expectN: 12, }, { name: "form feed", whenInput: "hello\fworld", expect: `hello\fworld`, expectN: 12, }, { name: "newline", whenInput: "hello\nworld", expect: `hello\nworld`, expectN: 12, }, { name: "carriage return", whenInput: "hello\rworld", expect: `hello\rworld`, expectN: 12, }, { name: "tab", whenInput: "hello\tworld", expect: `hello\tworld`, expectN: 12, }, { name: "multiple newlines", whenInput: "line1\nline2\nline3", expect: `line1\nline2\nline3`, expectN: 19, }, // Low control characters (< 0x20) { name: "null byte", whenInput: "hello\x00world", expect: `hello\u0000world`, expectN: 16, }, { name: "control character 0x01", whenInput: "test\x01value", expect: `test\u0001value`, expectN: 15, }, { name: "control character 0x0e", whenInput: "test\x0evalue", expect: `test\u000evalue`, expectN: 15, }, { name: "control character 0x1f", whenInput: "test\x1fvalue", expect: `test\u001fvalue`, expectN: 15, }, { name: "multiple control characters", whenInput: "\x00\x01\x02", expect: `\u0000\u0001\u0002`, expectN: 18, }, // UTF-8 handling { name: "valid UTF-8 Chinese", whenInput: "hello 世界", expect: "hello 世界", expectN: 12, }, { name: "valid UTF-8 emoji", whenInput: "party 🎉 time", expect: "party 🎉 time", expectN: 15, }, { name: "mixed ASCII and UTF-8", whenInput: "Hello世界123", expect: "Hello世界123", expectN: 14, }, { name: "UTF-8 with special chars", whenInput: "世界\n\"test\"", expect: `世界\n\"test\"`, expectN: 16, }, // Invalid UTF-8 { name: "invalid UTF-8 sequence", whenInput: "hello\xff\xfeworld", expect: `hello\ufffd\ufffdworld`, expectN: 22, }, { name: "incomplete UTF-8 sequence", whenInput: "test\xc3value", expect: `test\ufffdvalue`, expectN: 15, }, // Complex mixed cases { name: "all common escapes", whenInput: "tab\there\nquote\"backslash\\", expect: `tab\there\nquote\"backslash\\`, expectN: 29, }, { name: "mixed controls and UTF-8", whenInput: "hello\t世界\ntest\"", expect: `hello\t世界\ntest\"`, expectN: 21, }, { name: "all control characters", whenInput: "\b\f\n\r\t", expect: `\b\f\n\r\t`, expectN: 10, }, { name: "control and low ASCII", whenInput: "a\nb\x00c", expect: `a\nb\u0000c`, expectN: 11, }, // Edge cases { name: "starts with special char", whenInput: "\\start", expect: `\\start`, expectN: 7, }, { name: "ends with special char", whenInput: "end\"", expect: `end\"`, expectN: 5, }, { name: "consecutive special chars", whenInput: "\\\\\"\"", expect: `\\\\\"\"`, expectN: 8, }, { name: "only special characters", whenInput: "\"\\\n\t", expect: `\"\\\n\t`, expectN: 8, }, { name: "spaces and punctuation", whenInput: "Hello, World! How are you?", expect: "Hello, World! How are you?", expectN: 26, }, { name: "JSON-like string", whenInput: "{\"key\":\"value\"}", expect: `{\"key\":\"value\"}`, expectN: 19, }, } for _, tt := range testCases { t.Run(tt.name, func(t *testing.T) { buf := &bytes.Buffer{} n, err := writeJSONSafeString(buf, tt.whenInput) assert.NoError(t, err) assert.Equal(t, tt.expect, buf.String()) assert.Equal(t, tt.expectN, n) }) } } func BenchmarkWriteJSONSafeString(b *testing.B) { testCases := []struct { name string input string }{ {"simple", "hello world"}, {"with escapes", "tab\there\nquote\"backslash\\"}, {"utf8", "hello 世界 🎉"}, {"mixed", "Hello\t世界\ntest\"value\\path"}, {"long simple", "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789"}, {"long complex", "line1\nline2\tline3\"quote\\slash\x00null世界🎉"}, } for _, tc := range testCases { b.Run(tc.name, func(b *testing.B) { buf := &bytes.Buffer{} b.ResetTimer() for i := 0; i < b.N; i++ { buf.Reset() writeJSONSafeString(buf, tc.input) } }) } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/proxy_test.go
middleware/proxy_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "bytes" "context" "crypto/tls" "errors" "fmt" "io" "net" "net/http" "net/http/httptest" "net/url" "regexp" "sync" "testing" "time" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" "golang.org/x/net/websocket" ) // Assert expected with url.EscapedPath method to obtain the path. func TestProxy(t *testing.T) { // Setup t1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "target 1") })) defer t1.Close() url1, _ := url.Parse(t1.URL) t2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "target 2") })) defer t2.Close() url2, _ := url.Parse(t2.URL) targets := []*ProxyTarget{ { Name: "target 1", URL: url1, }, { Name: "target 2", URL: url2, }, } rb := NewRandomBalancer(nil) // must add targets: for _, target := range targets { assert.True(t, rb.AddTarget(target)) } // must ignore duplicates: for _, target := range targets { assert.False(t, rb.AddTarget(target)) } // Random e := echo.New() e.Use(Proxy(rb)) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) body := rec.Body.String() expected := map[string]bool{ "target 1": true, "target 2": true, } assert.Condition(t, func() bool { return expected[body] }) for _, target := range targets { assert.True(t, rb.RemoveTarget(target.Name)) } assert.False(t, rb.RemoveTarget("unknown target")) // Round-robin rrb := NewRoundRobinBalancer(targets) e = echo.New() e.Use(Proxy(rrb)) rec = httptest.NewRecorder() e.ServeHTTP(rec, req) body = rec.Body.String() assert.Equal(t, "target 1", body) rec = httptest.NewRecorder() e.ServeHTTP(rec, req) body = rec.Body.String() assert.Equal(t, "target 2", body) // ModifyResponse e = echo.New() e.Use(ProxyWithConfig(ProxyConfig{ Balancer: rrb, ModifyResponse: func(res *http.Response) error { res.Body = io.NopCloser(bytes.NewBuffer([]byte("modified"))) res.Header.Set("X-Modified", "1") return nil }, })) rec = httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, "modified", rec.Body.String()) assert.Equal(t, "1", rec.Header().Get("X-Modified")) // ProxyTarget is set in context contextObserver := func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) (err error) { next(c) assert.Contains(t, targets, c.Get("target"), "target is not set in context") return nil } } rrb1 := NewRoundRobinBalancer(targets) e = echo.New() e.Use(contextObserver) e.Use(Proxy(rrb1)) rec = httptest.NewRecorder() e.ServeHTTP(rec, req) } type testProvider struct { commonBalancer target *ProxyTarget err error } func (p *testProvider) Next(c echo.Context) *ProxyTarget { return &ProxyTarget{} } func (p *testProvider) NextTarget(c echo.Context) (*ProxyTarget, error) { return p.target, p.err } func TestTargetProvider(t *testing.T) { t1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "target 1") })) defer t1.Close() url1, _ := url.Parse(t1.URL) e := echo.New() tp := &testProvider{} tp.target = &ProxyTarget{Name: "target 1", URL: url1} e.Use(Proxy(tp)) rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/", nil) e.ServeHTTP(rec, req) body := rec.Body.String() assert.Equal(t, "target 1", body) } func TestFailNextTarget(t *testing.T) { url1, err := url.Parse("http://dummy:8080") assert.Nil(t, err) e := echo.New() tp := &testProvider{} tp.target = &ProxyTarget{Name: "target 1", URL: url1} tp.err = echo.NewHTTPError(http.StatusInternalServerError, "method could not select target") e.Use(Proxy(tp)) rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/", nil) e.ServeHTTP(rec, req) body := rec.Body.String() assert.Equal(t, "{\"message\":\"method could not select target\"}\n", body) } func TestProxyRealIPHeader(t *testing.T) { // Setup upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) defer upstream.Close() url, _ := url.Parse(upstream.URL) rrb := NewRoundRobinBalancer([]*ProxyTarget{{Name: "upstream", URL: url}}) e := echo.New() e.Use(Proxy(rrb)) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() remoteAddrIP, _, _ := net.SplitHostPort(req.RemoteAddr) realIPHeaderIP := "203.0.113.1" extractedRealIP := "203.0.113.10" tests := []*struct { hasRealIPheader bool hasIPExtractor bool expectedXRealIP string }{ {false, false, remoteAddrIP}, {false, true, extractedRealIP}, {true, false, realIPHeaderIP}, {true, true, extractedRealIP}, } for _, tt := range tests { if tt.hasRealIPheader { req.Header.Set(echo.HeaderXRealIP, realIPHeaderIP) } else { req.Header.Del(echo.HeaderXRealIP) } if tt.hasIPExtractor { e.IPExtractor = func(*http.Request) string { return extractedRealIP } } else { e.IPExtractor = nil } e.ServeHTTP(rec, req) assert.Equal(t, tt.expectedXRealIP, req.Header.Get(echo.HeaderXRealIP), "hasRealIPheader: %t / hasIPExtractor: %t", tt.hasRealIPheader, tt.hasIPExtractor) } } func TestProxyRewrite(t *testing.T) { var testCases = []struct { whenPath string expectProxiedURI string expectStatus int }{ { whenPath: "/api/users", expectProxiedURI: "/users", expectStatus: http.StatusOK, }, { whenPath: "/js/main.js", expectProxiedURI: "/public/javascripts/main.js", expectStatus: http.StatusOK, }, { whenPath: "/old", expectProxiedURI: "/new", expectStatus: http.StatusOK, }, { whenPath: "/users/jack/orders/1", expectProxiedURI: "/user/jack/order/1", expectStatus: http.StatusOK, }, { whenPath: "/user/jill/order/T%2FcO4lW%2Ft%2FVp%2F", expectProxiedURI: "/user/jill/order/T%2FcO4lW%2Ft%2FVp%2F", expectStatus: http.StatusOK, }, { // ` ` (space) is encoded by httpClient to `%20` when doing request to Echo. `%20` should not be double escaped when proxying request whenPath: "/api/new users", expectProxiedURI: "/new%20users", expectStatus: http.StatusOK, }, { // query params should be proxied and not be modified whenPath: "/api/users?limit=10", expectProxiedURI: "/users?limit=10", expectStatus: http.StatusOK, }, } for _, tc := range testCases { t.Run(tc.whenPath, func(t *testing.T) { receivedRequestURI := make(chan string, 1) upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // RequestURI is the unmodified request-target of the Request-Line (RFC 7230, Section 3.1.1) as sent by the client to a server // we need unmodified target to see if we are encoding/decoding the url in addition to rewrite/replace logic // if original request had `%2F` we should not magically decode it to `/` as it would change what was requested receivedRequestURI <- r.RequestURI })) defer upstream.Close() serverURL, _ := url.Parse(upstream.URL) rrb := NewRoundRobinBalancer([]*ProxyTarget{{Name: "upstream", URL: serverURL}}) // Rewrite e := echo.New() e.Use(ProxyWithConfig(ProxyConfig{ Balancer: rrb, Rewrite: map[string]string{ "/old": "/new", "/api/*": "/$1", "/js/*": "/public/javascripts/$1", "/users/*/orders/*": "/user/$1/order/$2", }, })) targetURL, _ := serverURL.Parse(tc.whenPath) req := httptest.NewRequest(http.MethodGet, targetURL.String(), nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, tc.expectStatus, rec.Code) actualRequestURI := <-receivedRequestURI assert.Equal(t, tc.expectProxiedURI, actualRequestURI) }) } } func TestProxyRewriteRegex(t *testing.T) { // Setup receivedRequestURI := make(chan string, 1) upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // RequestURI is the unmodified request-target of the Request-Line (RFC 7230, Section 3.1.1) as sent by the client to a server // we need unmodified target to see if we are encoding/decoding the url in addition to rewrite/replace logic // if original request had `%2F` we should not magically decode it to `/` as it would change what was requested receivedRequestURI <- r.RequestURI })) defer upstream.Close() tmpUrL, _ := url.Parse(upstream.URL) rrb := NewRoundRobinBalancer([]*ProxyTarget{{Name: "upstream", URL: tmpUrL}}) // Rewrite e := echo.New() e.Use(ProxyWithConfig(ProxyConfig{ Balancer: rrb, Rewrite: map[string]string{ "^/a/*": "/v1/$1", "^/b/*/c/*": "/v2/$2/$1", "^/c/*/*": "/v3/$2", }, RegexRewrite: map[*regexp.Regexp]string{ regexp.MustCompile("^/x/.+?/(.*)"): "/v4/$1", regexp.MustCompile("^/y/(.+?)/(.*)"): "/v5/$2/$1", }, })) testCases := []struct { requestPath string statusCode int expectPath string }{ {"/unmatched", http.StatusOK, "/unmatched"}, {"/a/test", http.StatusOK, "/v1/test"}, {"/b/foo/c/bar/baz", http.StatusOK, "/v2/bar/baz/foo"}, {"/c/ignore/test", http.StatusOK, "/v3/test"}, {"/c/ignore1/test/this", http.StatusOK, "/v3/test/this"}, {"/x/ignore/test", http.StatusOK, "/v4/test"}, {"/y/foo/bar", http.StatusOK, "/v5/bar/foo"}, // NB: fragment is not added by golang httputil.NewSingleHostReverseProxy implementation // $2 = `bar?q=1#frag`, $1 = `foo`. replaced uri = `/v5/bar?q=1#frag/foo` but httputil.NewSingleHostReverseProxy does not send `#frag/foo` (currently) {"/y/foo/bar?q=1#frag", http.StatusOK, "/v5/bar?q=1"}, } for _, tc := range testCases { t.Run(tc.requestPath, func(t *testing.T) { targetURL, _ := url.Parse(tc.requestPath) req := httptest.NewRequest(http.MethodGet, targetURL.String(), nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) actualRequestURI := <-receivedRequestURI assert.Equal(t, tc.expectPath, actualRequestURI) assert.Equal(t, tc.statusCode, rec.Code) }) } } func TestProxyError(t *testing.T) { // Setup url1, _ := url.Parse("http://127.0.0.1:27121") url2, _ := url.Parse("http://127.0.0.1:27122") targets := []*ProxyTarget{ { Name: "target 1", URL: url1, }, { Name: "target 2", URL: url2, }, } rb := NewRandomBalancer(nil) // must add targets: for _, target := range targets { assert.True(t, rb.AddTarget(target)) } // must ignore duplicates: for _, target := range targets { assert.False(t, rb.AddTarget(target)) } // Random e := echo.New() e.Use(Proxy(rb)) req := httptest.NewRequest(http.MethodGet, "/", nil) // Remote unreachable rec := httptest.NewRecorder() req.URL.Path = "/api/users" e.ServeHTTP(rec, req) assert.Equal(t, "/api/users", req.URL.Path) assert.Equal(t, http.StatusBadGateway, rec.Code) } func TestProxyRetries(t *testing.T) { newServer := func(res int) (*url.URL, *httptest.Server) { server := httptest.NewServer( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(res) }), ) targetURL, _ := url.Parse(server.URL) return targetURL, server } targetURL, server := newServer(http.StatusOK) defer server.Close() goodTarget := &ProxyTarget{ Name: "Good", URL: targetURL, } targetURL, server = newServer(http.StatusBadRequest) defer server.Close() goodTargetWith40X := &ProxyTarget{ Name: "Good with 40X", URL: targetURL, } targetURL, _ = url.Parse("http://127.0.0.1:27121") badTarget := &ProxyTarget{ Name: "Bad", URL: targetURL, } alwaysRetryFilter := func(c echo.Context, e error) bool { return true } neverRetryFilter := func(c echo.Context, e error) bool { return false } testCases := []struct { name string retryCount int retryFilters []func(c echo.Context, e error) bool targets []*ProxyTarget expectedResponse int }{ { name: "retry count 0 does not attempt retry on fail", targets: []*ProxyTarget{ badTarget, goodTarget, }, expectedResponse: http.StatusBadGateway, }, { name: "retry count 1 does not attempt retry on success", retryCount: 1, targets: []*ProxyTarget{ goodTarget, }, expectedResponse: http.StatusOK, }, { name: "retry count 1 does retry on handler return true", retryCount: 1, retryFilters: []func(c echo.Context, e error) bool{ alwaysRetryFilter, }, targets: []*ProxyTarget{ badTarget, goodTarget, }, expectedResponse: http.StatusOK, }, { name: "retry count 1 does not retry on handler return false", retryCount: 1, retryFilters: []func(c echo.Context, e error) bool{ neverRetryFilter, }, targets: []*ProxyTarget{ badTarget, goodTarget, }, expectedResponse: http.StatusBadGateway, }, { name: "retry count 2 returns error when no more retries left", retryCount: 2, retryFilters: []func(c echo.Context, e error) bool{ alwaysRetryFilter, alwaysRetryFilter, }, targets: []*ProxyTarget{ badTarget, badTarget, badTarget, goodTarget, //Should never be reached as only 2 retries }, expectedResponse: http.StatusBadGateway, }, { name: "retry count 2 returns error when retries left but handler returns false", retryCount: 3, retryFilters: []func(c echo.Context, e error) bool{ alwaysRetryFilter, alwaysRetryFilter, neverRetryFilter, }, targets: []*ProxyTarget{ badTarget, badTarget, badTarget, goodTarget, //Should never be reached as retry handler returns false on 2nd check }, expectedResponse: http.StatusBadGateway, }, { name: "retry count 3 succeeds", retryCount: 3, retryFilters: []func(c echo.Context, e error) bool{ alwaysRetryFilter, alwaysRetryFilter, alwaysRetryFilter, }, targets: []*ProxyTarget{ badTarget, badTarget, badTarget, goodTarget, }, expectedResponse: http.StatusOK, }, { name: "40x responses are not retried", retryCount: 1, targets: []*ProxyTarget{ goodTargetWith40X, goodTarget, }, expectedResponse: http.StatusBadRequest, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { retryFilterCall := 0 retryFilter := func(c echo.Context, e error) bool { if len(tc.retryFilters) == 0 { assert.FailNow(t, fmt.Sprintf("unexpected calls, %d, to retry handler", retryFilterCall)) } retryFilterCall++ nextRetryFilter := tc.retryFilters[0] tc.retryFilters = tc.retryFilters[1:] return nextRetryFilter(c, e) } e := echo.New() e.Use(ProxyWithConfig( ProxyConfig{ Balancer: NewRoundRobinBalancer(tc.targets), RetryCount: tc.retryCount, RetryFilter: retryFilter, }, )) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, tc.expectedResponse, rec.Code) if len(tc.retryFilters) > 0 { assert.FailNow(t, fmt.Sprintf("expected %d more retry handler calls", len(tc.retryFilters))) } }) } } func TestProxyRetryWithBackendTimeout(t *testing.T) { transport := http.DefaultTransport.(*http.Transport).Clone() transport.ResponseHeaderTimeout = time.Millisecond * 500 timeoutBackend := httptest.NewServer( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(1 * time.Second) w.WriteHeader(404) }), ) defer timeoutBackend.Close() timeoutTargetURL, _ := url.Parse(timeoutBackend.URL) goodBackend := httptest.NewServer( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }), ) defer goodBackend.Close() goodTargetURL, _ := url.Parse(goodBackend.URL) e := echo.New() e.Use(ProxyWithConfig( ProxyConfig{ Transport: transport, Balancer: NewRoundRobinBalancer([]*ProxyTarget{ { Name: "Timeout", URL: timeoutTargetURL, }, { Name: "Good", URL: goodTargetURL, }, }), RetryCount: 1, }, )) var wg sync.WaitGroup for i := 0; i < 20; i++ { wg.Add(1) go func() { defer wg.Done() req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, 200, rec.Code) }() } wg.Wait() } func TestProxyErrorHandler(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })) goodURL, _ := url.Parse(server.URL) defer server.Close() goodTarget := &ProxyTarget{ Name: "Good", URL: goodURL, } badURL, _ := url.Parse("http://127.0.0.1:27121") badTarget := &ProxyTarget{ Name: "Bad", URL: badURL, } transformedError := errors.New("a new error") testCases := []struct { name string target *ProxyTarget errorHandler func(c echo.Context, e error) error expectFinalError func(t *testing.T, err error) }{ { name: "Error handler not invoked when request success", target: goodTarget, errorHandler: func(c echo.Context, e error) error { assert.FailNow(t, "error handler should not be invoked") return e }, }, { name: "Error handler invoked when request fails", target: badTarget, errorHandler: func(c echo.Context, e error) error { httpErr, ok := e.(*echo.HTTPError) assert.True(t, ok, "expected http error to be passed to handler") assert.Equal(t, http.StatusBadGateway, httpErr.Code, "expected http bad gateway error to be passed to handler") return transformedError }, expectFinalError: func(t *testing.T, err error) { assert.Equal(t, transformedError, err, "transformed error not returned from proxy") }, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() e.Use(ProxyWithConfig( ProxyConfig{ Balancer: NewRoundRobinBalancer([]*ProxyTarget{tc.target}), ErrorHandler: tc.errorHandler, }, )) errorHandlerCalled := false e.HTTPErrorHandler = func(err error, c echo.Context) { errorHandlerCalled = true tc.expectFinalError(t, err) e.DefaultHTTPErrorHandler(err, c) } req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) if !errorHandlerCalled && tc.expectFinalError != nil { t.Fatalf("error handler was not called") } }) } } func TestClientCancelConnectionResultsHTTPCode499(t *testing.T) { var timeoutStop sync.WaitGroup timeoutStop.Add(1) HTTPTarget := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { timeoutStop.Wait() // wait until we have canceled the request w.WriteHeader(http.StatusOK) })) defer HTTPTarget.Close() targetURL, _ := url.Parse(HTTPTarget.URL) target := &ProxyTarget{ Name: "target", URL: targetURL, } rb := NewRandomBalancer(nil) assert.True(t, rb.AddTarget(target)) e := echo.New() e.Use(Proxy(rb)) rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/", nil) ctx, cancel := context.WithCancel(req.Context()) req = req.WithContext(ctx) go func() { time.Sleep(10 * time.Millisecond) cancel() }() e.ServeHTTP(rec, req) timeoutStop.Done() assert.Equal(t, 499, rec.Code) } // Assert balancer with empty targets does return `nil` on `Next()` func TestProxyBalancerWithNoTargets(t *testing.T) { rb := NewRandomBalancer(nil) assert.Nil(t, rb.Next(nil)) rrb := NewRoundRobinBalancer([]*ProxyTarget{}) assert.Nil(t, rrb.Next(nil)) } type testContextKey string type customBalancer struct { target *ProxyTarget } func (b *customBalancer) AddTarget(target *ProxyTarget) bool { return false } func (b *customBalancer) RemoveTarget(name string) bool { return false } func (b *customBalancer) Next(c echo.Context) *ProxyTarget { ctx := context.WithValue(c.Request().Context(), testContextKey("FROM_BALANCER"), "CUSTOM_BALANCER") c.SetRequest(c.Request().WithContext(ctx)) return b.target } func TestModifyResponseUseContext(t *testing.T) { server := httptest.NewServer( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) }), ) defer server.Close() targetURL, _ := url.Parse(server.URL) e := echo.New() e.Use(ProxyWithConfig( ProxyConfig{ Balancer: &customBalancer{ target: &ProxyTarget{ Name: "tst", URL: targetURL, }, }, RetryCount: 1, ModifyResponse: func(res *http.Response) error { val := res.Request.Context().Value(testContextKey("FROM_BALANCER")) if valStr, ok := val.(string); ok { res.Header.Set("FROM_BALANCER", valStr) } return nil }, }, )) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, "OK", rec.Body.String()) assert.Equal(t, "CUSTOM_BALANCER", rec.Header().Get("FROM_BALANCER")) } func createSimpleWebSocketServer(serveTLS bool) *httptest.Server { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { wsHandler := func(conn *websocket.Conn) { defer conn.Close() for { var msg string err := websocket.Message.Receive(conn, &msg) if err != nil { return } // message back to the client websocket.Message.Send(conn, msg) } } websocket.Server{Handler: wsHandler}.ServeHTTP(w, r) }) if serveTLS { return httptest.NewTLSServer(handler) } return httptest.NewServer(handler) } func createSimpleProxyServer(t *testing.T, srv *httptest.Server, serveTLS bool, toTLS bool) *httptest.Server { e := echo.New() if toTLS { // proxy to tls target tgtURL, _ := url.Parse(srv.URL) tgtURL.Scheme = "wss" balancer := NewRandomBalancer([]*ProxyTarget{{URL: tgtURL}}) defaultTransport, ok := http.DefaultTransport.(*http.Transport) if !ok { t.Fatal("Default transport is not of type *http.Transport") } transport := defaultTransport.Clone() transport.TLSClientConfig = &tls.Config{ InsecureSkipVerify: true, } e.Use(ProxyWithConfig(ProxyConfig{Balancer: balancer, Transport: transport})) } else { // proxy to non-TLS target tgtURL, _ := url.Parse(srv.URL) balancer := NewRandomBalancer([]*ProxyTarget{{URL: tgtURL}}) e.Use(ProxyWithConfig(ProxyConfig{Balancer: balancer})) } if serveTLS { // serve proxy server with TLS ts := httptest.NewTLSServer(e) return ts } // serve proxy server without TLS ts := httptest.NewServer(e) return ts } // TestProxyWithConfigWebSocketNonTLS2NonTLS tests the proxy with non-TLS to non-TLS WebSocket connection. func TestProxyWithConfigWebSocketNonTLS2NonTLS(t *testing.T) { /* Arrange */ // Create a WebSocket test server (non-TLS) srv := createSimpleWebSocketServer(false) defer srv.Close() // create proxy server (non-TLS to non-TLS) ts := createSimpleProxyServer(t, srv, false, false) defer ts.Close() tsURL, _ := url.Parse(ts.URL) tsURL.Scheme = "ws" tsURL.Path = "/" /* Act */ // Connect to the proxy WebSocket wsConn, err := websocket.Dial(tsURL.String(), "", "http://localhost/") assert.NoError(t, err) defer wsConn.Close() // Send message sendMsg := "Hello, Non TLS WebSocket!" err = websocket.Message.Send(wsConn, sendMsg) assert.NoError(t, err) /* Assert */ // Read response var recvMsg string err = websocket.Message.Receive(wsConn, &recvMsg) assert.NoError(t, err) assert.Equal(t, sendMsg, recvMsg) } // TestProxyWithConfigWebSocketTLS2TLS tests the proxy with TLS to TLS WebSocket connection. func TestProxyWithConfigWebSocketTLS2TLS(t *testing.T) { /* Arrange */ // Create a WebSocket test server (TLS) srv := createSimpleWebSocketServer(true) defer srv.Close() // create proxy server (TLS to TLS) ts := createSimpleProxyServer(t, srv, true, true) defer ts.Close() tsURL, _ := url.Parse(ts.URL) tsURL.Scheme = "wss" tsURL.Path = "/" /* Act */ origin, err := url.Parse(ts.URL) assert.NoError(t, err) config := &websocket.Config{ Location: tsURL, Origin: origin, TlsConfig: &tls.Config{InsecureSkipVerify: true}, // skip verify for testing Version: websocket.ProtocolVersionHybi13, } wsConn, err := websocket.DialConfig(config) assert.NoError(t, err) defer wsConn.Close() // Send message sendMsg := "Hello, TLS to TLS WebSocket!" err = websocket.Message.Send(wsConn, sendMsg) assert.NoError(t, err) // Read response var recvMsg string err = websocket.Message.Receive(wsConn, &recvMsg) assert.NoError(t, err) assert.Equal(t, sendMsg, recvMsg) } // TestProxyWithConfigWebSocketNonTLS2TLS tests the proxy with non-TLS to TLS WebSocket connection. func TestProxyWithConfigWebSocketNonTLS2TLS(t *testing.T) { /* Arrange */ // Create a WebSocket test server (TLS) srv := createSimpleWebSocketServer(true) defer srv.Close() // create proxy server (Non-TLS to TLS) ts := createSimpleProxyServer(t, srv, false, true) defer ts.Close() tsURL, _ := url.Parse(ts.URL) tsURL.Scheme = "ws" tsURL.Path = "/" /* Act */ // Connect to the proxy WebSocket wsConn, err := websocket.Dial(tsURL.String(), "", "http://localhost/") assert.NoError(t, err) defer wsConn.Close() // Send message sendMsg := "Hello, Non TLS to TLS WebSocket!" err = websocket.Message.Send(wsConn, sendMsg) assert.NoError(t, err) /* Assert */ // Read response var recvMsg string err = websocket.Message.Receive(wsConn, &recvMsg) assert.NoError(t, err) assert.Equal(t, sendMsg, recvMsg) } // TestProxyWithConfigWebSocketTLSToNoneTLS tests the proxy with TLS to non-TLS WebSocket connection. (TLS termination) func TestProxyWithConfigWebSocketTLS2NonTLS(t *testing.T) { /* Arrange */ // Create a WebSocket test server (non-TLS) srv := createSimpleWebSocketServer(false) defer srv.Close() // create proxy server (TLS to non-TLS) ts := createSimpleProxyServer(t, srv, true, false) defer ts.Close() tsURL, _ := url.Parse(ts.URL) tsURL.Scheme = "wss" tsURL.Path = "/" /* Act */ origin, err := url.Parse(ts.URL) assert.NoError(t, err) config := &websocket.Config{ Location: tsURL, Origin: origin, TlsConfig: &tls.Config{InsecureSkipVerify: true}, // skip verify for testing Version: websocket.ProtocolVersionHybi13, } wsConn, err := websocket.DialConfig(config) assert.NoError(t, err) defer wsConn.Close() // Send message sendMsg := "Hello, TLS to NoneTLS WebSocket!" err = websocket.Message.Send(wsConn, sendMsg) assert.NoError(t, err) // Read response var recvMsg string err = websocket.Message.Receive(wsConn, &recvMsg) assert.NoError(t, err) assert.Equal(t, sendMsg, recvMsg) }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/request_id.go
middleware/request_id.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "github.com/labstack/echo/v4" ) // RequestIDConfig defines the config for RequestID middleware. type RequestIDConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // Generator defines a function to generate an ID. // Optional. Defaults to generator for random string of length 32. Generator func() string // RequestIDHandler defines a function which is executed for a request id. RequestIDHandler func(echo.Context, string) // TargetHeader defines what header to look for to populate the id TargetHeader string } // DefaultRequestIDConfig is the default RequestID middleware config. var DefaultRequestIDConfig = RequestIDConfig{ Skipper: DefaultSkipper, Generator: generator, TargetHeader: echo.HeaderXRequestID, } // RequestID returns a X-Request-ID middleware. func RequestID() echo.MiddlewareFunc { return RequestIDWithConfig(DefaultRequestIDConfig) } // RequestIDWithConfig returns a X-Request-ID middleware with config. func RequestIDWithConfig(config RequestIDConfig) echo.MiddlewareFunc { // Defaults if config.Skipper == nil { config.Skipper = DefaultRequestIDConfig.Skipper } if config.Generator == nil { config.Generator = generator } if config.TargetHeader == "" { config.TargetHeader = echo.HeaderXRequestID } return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { if config.Skipper(c) { return next(c) } req := c.Request() res := c.Response() rid := req.Header.Get(config.TargetHeader) if rid == "" { rid = config.Generator() } res.Header().Set(config.TargetHeader, rid) if config.RequestIDHandler != nil { config.RequestIDHandler(c, rid) } return next(c) } } } func generator() string { return randomString(32) }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/timeout.go
middleware/timeout.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "context" "github.com/labstack/echo/v4" "net/http" "sync" "time" ) // --------------------------------------------------------------------------------------------------------------- // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING // WARNING: Timeout middleware causes more problems than it solves. // WARNING: This middleware should be first middleware as it messes with request Writer and could cause data race if // it is in other position // // Depending on out requirements you could be better of setting timeout to context and // check its deadline from handler. // // For example: create middleware to set timeout to context // func RequestTimeout(timeout time.Duration) echo.MiddlewareFunc { // return func(next echo.HandlerFunc) echo.HandlerFunc { // return func(c echo.Context) error { // timeoutCtx, cancel := context.WithTimeout(c.Request().Context(), timeout) // c.SetRequest(c.Request().WithContext(timeoutCtx)) // defer cancel() // return next(c) // } // } //} // // Create handler that checks for context deadline and runs actual task in separate coroutine // Note: separate coroutine may not be even if you do not want to process continue executing and // just want to stop long-running handler to stop and you are using "context aware" methods (ala db queries with ctx) // e.GET("/", func(c echo.Context) error { // // doneCh := make(chan error) // go func(ctx context.Context) { // doneCh <- myPossiblyLongRunningBackgroundTaskWithCtx(ctx) // }(c.Request().Context()) // // select { // wait for task to finish or context to timeout/cancelled // case err := <-doneCh: // if err != nil { // return err // } // return c.String(http.StatusOK, "OK") // case <-c.Request().Context().Done(): // if c.Request().Context().Err() == context.DeadlineExceeded { // return c.String(http.StatusServiceUnavailable, "timeout") // } // return c.Request().Context().Err() // } // // }) // // TimeoutConfig defines the config for Timeout middleware. // // Deprecated: Use ContextTimeoutConfig with ContextTimeout or ContextTimeoutWithConfig instead. // The Timeout middleware has architectural issues that cause data races due to response writer // manipulation across goroutines. It must be the first middleware in the chain, making it fragile. // The ContextTimeout middleware provides timeout functionality using Go's context mechanism, // which is race-free and can be placed anywhere in the middleware chain. type TimeoutConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // ErrorMessage is written to response on timeout in addition to http.StatusServiceUnavailable (503) status code // It can be used to define a custom timeout error message ErrorMessage string // OnTimeoutRouteErrorHandler is an error handler that is executed for error that was returned from wrapped route after // request timeouted and we already had sent the error code (503) and message response to the client. // NB: do not write headers/body inside this handler. The response has already been sent to the client and response writer // will not accept anything no more. If you want to know what actual route middleware timeouted use `c.Path()` OnTimeoutRouteErrorHandler func(err error, c echo.Context) // Timeout configures a timeout for the middleware, defaults to 0 for no timeout // NOTE: when difference between timeout duration and handler execution time is almost the same (in range of 100microseconds) // the result of timeout does not seem to be reliable - could respond timeout, could respond handler output // difference over 500microseconds (0.5millisecond) response seems to be reliable Timeout time.Duration } // DefaultTimeoutConfig is the default Timeout middleware config. var DefaultTimeoutConfig = TimeoutConfig{ Skipper: DefaultSkipper, Timeout: 0, ErrorMessage: "", } // Timeout returns a middleware which returns error (503 Service Unavailable error) to client immediately when handler // call runs for longer than its time limit. NB: timeout does not stop handler execution. // // Deprecated: Use ContextTimeout instead. This middleware has known data race issues due to response writer // manipulation. See https://github.com/labstack/echo/blob/master/middleware/context_timeout.go for the // recommended alternative. // // Example migration: // // // Before: // e.Use(middleware.Timeout()) // // // After: // e.Use(middleware.ContextTimeout(30 * time.Second)) func Timeout() echo.MiddlewareFunc { return TimeoutWithConfig(DefaultTimeoutConfig) } // TimeoutWithConfig returns a Timeout middleware with config or panics on invalid configuration. // // Deprecated: Use ContextTimeoutWithConfig instead. This middleware has architectural data race issues. // See the ContextTimeout middleware for a race-free alternative that uses Go's context mechanism. // // Example migration: // // // Before: // e.Use(middleware.TimeoutWithConfig(middleware.TimeoutConfig{ // Timeout: 30 * time.Second, // })) // // // After: // e.Use(middleware.ContextTimeoutWithConfig(middleware.ContextTimeoutConfig{ // Timeout: 30 * time.Second, // })) func TimeoutWithConfig(config TimeoutConfig) echo.MiddlewareFunc { mw, err := config.ToMiddleware() if err != nil { panic(err) } return mw } // ToMiddleware converts Config to middleware or returns an error for invalid configuration // // Deprecated: Use ContextTimeoutConfig.ToMiddleware instead. func (config TimeoutConfig) ToMiddleware() (echo.MiddlewareFunc, error) { if config.Skipper == nil { config.Skipper = DefaultTimeoutConfig.Skipper } return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { if config.Skipper(c) || config.Timeout == 0 { return next(c) } errChan := make(chan error, 1) handlerWrapper := echoHandlerFuncWrapper{ writer: &ignorableWriter{ResponseWriter: c.Response().Writer}, ctx: c, handler: next, errChan: errChan, errHandler: config.OnTimeoutRouteErrorHandler, } handler := http.TimeoutHandler(handlerWrapper, config.Timeout, config.ErrorMessage) handler.ServeHTTP(handlerWrapper.writer, c.Request()) select { case err := <-errChan: return err default: return nil } } }, nil } type echoHandlerFuncWrapper struct { writer *ignorableWriter ctx echo.Context handler echo.HandlerFunc errHandler func(err error, c echo.Context) errChan chan error } func (t echoHandlerFuncWrapper) ServeHTTP(rw http.ResponseWriter, r *http.Request) { // replace echo.Context Request with the one provided by TimeoutHandler to let later middlewares/handler on the chain // handle properly it's cancellation t.ctx.SetRequest(r) // replace writer with TimeoutHandler custom one. This will guarantee that // `writes by h to its ResponseWriter will return ErrHandlerTimeout.` originalWriter := t.ctx.Response().Writer t.ctx.Response().Writer = rw // in case of panic we restore original writer and call panic again // so it could be handled with global middleware Recover() defer func() { if err := recover(); err != nil { t.ctx.Response().Writer = originalWriter panic(err) } }() err := t.handler(t.ctx) if ctxErr := r.Context().Err(); ctxErr == context.DeadlineExceeded { if err != nil && t.errHandler != nil { t.errHandler(err, t.ctx) } return // on timeout we can not send handler error to client because `http.TimeoutHandler` has already sent headers } if err != nil { // This is needed as `http.TimeoutHandler` will write status code by itself on error and after that our tries to write // status code will not work anymore as Echo.Response thinks it has been already "committed" and further writes // create errors in log about `superfluous response.WriteHeader call from` t.writer.Ignore(true) t.ctx.Response().Writer = originalWriter // make sure we restore writer before we signal original coroutine about the error // we pass error from handler to middlewares up in handler chain to act on it if needed. t.errChan <- err return } // we restore original writer only for cases we did not timeout. On timeout we have already sent response to client // and should not anymore send additional headers/data // so on timeout writer stays what http.TimeoutHandler uses and prevents writing headers/body t.ctx.Response().Writer = originalWriter } // ignorableWriter is ResponseWriter implementations that allows us to mark writer to ignore further write calls. This // is handy in cases when you do not have direct control of code being executed (3rd party middleware) but want to make // sure that external code will not be able to write response to the client. // Writer is coroutine safe for writes. type ignorableWriter struct { http.ResponseWriter lock sync.Mutex ignoreWrites bool } func (w *ignorableWriter) Ignore(ignore bool) { w.lock.Lock() w.ignoreWrites = ignore w.lock.Unlock() } func (w *ignorableWriter) WriteHeader(code int) { w.lock.Lock() defer w.lock.Unlock() if w.ignoreWrites { return } w.ResponseWriter.WriteHeader(code) } func (w *ignorableWriter) Write(b []byte) (int, error) { w.lock.Lock() defer w.lock.Unlock() if w.ignoreWrites { return len(b), nil } return w.ResponseWriter.Write(b) }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/static_other.go
middleware/static_other.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors //go:build !windows package middleware import ( "os" ) // We ignore these errors as there could be handler that matches request path. func isIgnorableOpenFileError(err error) bool { return os.IsNotExist(err) }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/context_timeout_test.go
middleware/context_timeout_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "context" "errors" "net/http" "net/http/httptest" "net/url" "strings" "testing" "time" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func TestContextTimeoutSkipper(t *testing.T) { t.Parallel() m := ContextTimeoutWithConfig(ContextTimeoutConfig{ Skipper: func(context echo.Context) bool { return true }, Timeout: 10 * time.Millisecond, }) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e := echo.New() c := e.NewContext(req, rec) err := m(func(c echo.Context) error { if err := sleepWithContext(c.Request().Context(), time.Duration(20*time.Millisecond)); err != nil { return err } return errors.New("response from handler") })(c) // if not skipped we would have not returned error due context timeout logic assert.EqualError(t, err, "response from handler") } func TestContextTimeoutWithTimeout0(t *testing.T) { t.Parallel() assert.Panics(t, func() { ContextTimeout(time.Duration(0)) }) } func TestContextTimeoutErrorOutInHandler(t *testing.T) { t.Parallel() m := ContextTimeoutWithConfig(ContextTimeoutConfig{ // Timeout has to be defined or the whole flow for timeout middleware will be skipped Timeout: 10 * time.Millisecond, }) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e := echo.New() c := e.NewContext(req, rec) rec.Code = 1 // we want to be sure that even 200 will not be sent err := m(func(c echo.Context) error { // this error must not be written to the client response. Middlewares upstream of timeout middleware must be able // to handle returned error and this can be done only then handler has not yet committed (written status code) // the response. return echo.NewHTTPError(http.StatusTeapot, "err") })(c) assert.Error(t, err) assert.EqualError(t, err, "code=418, message=err") assert.Equal(t, 1, rec.Code) assert.Equal(t, "", rec.Body.String()) } func TestContextTimeoutSuccessfulRequest(t *testing.T) { t.Parallel() m := ContextTimeoutWithConfig(ContextTimeoutConfig{ // Timeout has to be defined or the whole flow for timeout middleware will be skipped Timeout: 10 * time.Millisecond, }) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e := echo.New() c := e.NewContext(req, rec) err := m(func(c echo.Context) error { return c.JSON(http.StatusCreated, map[string]string{"data": "ok"}) })(c) assert.NoError(t, err) assert.Equal(t, http.StatusCreated, rec.Code) assert.Equal(t, "{\"data\":\"ok\"}\n", rec.Body.String()) } func TestContextTimeoutTestRequestClone(t *testing.T) { t.Parallel() req := httptest.NewRequest(http.MethodPost, "/uri?query=value", strings.NewReader(url.Values{"form": {"value"}}.Encode())) req.AddCookie(&http.Cookie{Name: "cookie", Value: "value"}) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") rec := httptest.NewRecorder() m := ContextTimeoutWithConfig(ContextTimeoutConfig{ // Timeout has to be defined or the whole flow for timeout middleware will be skipped Timeout: 1 * time.Second, }) e := echo.New() c := e.NewContext(req, rec) err := m(func(c echo.Context) error { // Cookie test cookie, err := c.Request().Cookie("cookie") if assert.NoError(t, err) { assert.EqualValues(t, "cookie", cookie.Name) assert.EqualValues(t, "value", cookie.Value) } // Form values if assert.NoError(t, c.Request().ParseForm()) { assert.EqualValues(t, "value", c.Request().FormValue("form")) } // Query string assert.EqualValues(t, "value", c.Request().URL.Query()["query"][0]) return nil })(c) assert.NoError(t, err) } func TestContextTimeoutWithDefaultErrorMessage(t *testing.T) { t.Parallel() timeout := 10 * time.Millisecond m := ContextTimeoutWithConfig(ContextTimeoutConfig{ Timeout: timeout, }) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e := echo.New() c := e.NewContext(req, rec) err := m(func(c echo.Context) error { if err := sleepWithContext(c.Request().Context(), time.Duration(80*time.Millisecond)); err != nil { return err } return c.String(http.StatusOK, "Hello, World!") })(c) assert.IsType(t, &echo.HTTPError{}, err) assert.Error(t, err) assert.Equal(t, http.StatusServiceUnavailable, err.(*echo.HTTPError).Code) assert.Equal(t, "Service Unavailable", err.(*echo.HTTPError).Message) } func TestContextTimeoutCanHandleContextDeadlineOnNextHandler(t *testing.T) { t.Parallel() timeoutErrorHandler := func(err error, c echo.Context) error { if err != nil { if errors.Is(err, context.DeadlineExceeded) { return &echo.HTTPError{ Code: http.StatusServiceUnavailable, Message: "Timeout! change me", } } return err } return nil } timeout := 50 * time.Millisecond m := ContextTimeoutWithConfig(ContextTimeoutConfig{ Timeout: timeout, ErrorHandler: timeoutErrorHandler, }) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e := echo.New() c := e.NewContext(req, rec) err := m(func(c echo.Context) error { // NOTE: Very short periods are not reliable for tests due to Go routine scheduling and the unpredictable order // for 1) request and 2) time goroutine. For most OS this works as expected, but MacOS seems most flaky. if err := sleepWithContext(c.Request().Context(), 100*time.Millisecond); err != nil { return err } // The Request Context should have a Deadline set by http.ContextTimeoutHandler if _, ok := c.Request().Context().Deadline(); !ok { assert.Fail(t, "No timeout set on Request Context") } return c.String(http.StatusOK, "Hello, World!") })(c) assert.IsType(t, &echo.HTTPError{}, err) assert.Error(t, err) assert.Equal(t, http.StatusServiceUnavailable, err.(*echo.HTTPError).Code) assert.Equal(t, "Timeout! change me", err.(*echo.HTTPError).Message) } func sleepWithContext(ctx context.Context, d time.Duration) error { timer := time.NewTimer(d) defer func() { _ = timer.Stop() }() select { case <-ctx.Done(): return context.DeadlineExceeded case <-timer.C: return nil } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/request_logger_test.go
middleware/request_logger_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "bytes" "encoding/json" "errors" "log/slog" "net/http" "net/http/httptest" "net/url" "strconv" "strings" "testing" "time" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func TestRequestLoggerOK(t *testing.T) { old := slog.Default() t.Cleanup(func() { slog.SetDefault(old) }) buf := new(bytes.Buffer) slog.SetDefault(slog.New(slog.NewJSONHandler(buf, nil))) e := echo.New() e.Use(RequestLogger()) e.POST("/test", func(c echo.Context) error { return c.String(http.StatusTeapot, "OK") }) reader := strings.NewReader(`{"foo":"bar"}`) req := httptest.NewRequest(http.MethodPost, "/test", reader) req.Header.Set(echo.HeaderContentLength, strconv.Itoa(int(reader.Size()))) req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) req.Header.Set(echo.HeaderXRealIP, "8.8.8.8") req.Header.Set("User-Agent", "curl/7.68.0") rec := httptest.NewRecorder() e.ServeHTTP(rec, req) logAttrs := map[string]interface{}{} assert.NoError(t, json.Unmarshal(buf.Bytes(), &logAttrs)) logAttrs["latency"] = 123 logAttrs["time"] = "x" expect := map[string]interface{}{ "level": "INFO", "msg": "REQUEST", "method": "POST", "uri": "/test", "status": float64(418), "bytes_in": "13", "host": "example.com", "bytes_out": float64(2), "user_agent": "curl/7.68.0", "remote_ip": "8.8.8.8", "request_id": "", "time": "x", "latency": 123, } assert.Equal(t, expect, logAttrs) } func TestRequestLoggerError(t *testing.T) { old := slog.Default() t.Cleanup(func() { slog.SetDefault(old) }) buf := new(bytes.Buffer) slog.SetDefault(slog.New(slog.NewJSONHandler(buf, nil))) e := echo.New() e.Use(RequestLogger()) e.GET("/test", func(c echo.Context) error { return errors.New("nope") }) req := httptest.NewRequest(http.MethodGet, "/test", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) logAttrs := map[string]interface{}{} assert.NoError(t, json.Unmarshal(buf.Bytes(), &logAttrs)) logAttrs["latency"] = 123 logAttrs["time"] = "x" expect := map[string]interface{}{ "level": "ERROR", "msg": "REQUEST_ERROR", "method": "GET", "uri": "/test", "status": float64(500), "bytes_in": "", "host": "example.com", "bytes_out": float64(36.0), "user_agent": "", "remote_ip": "192.0.2.1", "request_id": "", "error": "nope", "latency": 123, "time": "x", } assert.Equal(t, expect, logAttrs) } func TestRequestLoggerWithConfig(t *testing.T) { e := echo.New() var expect RequestLoggerValues e.Use(RequestLoggerWithConfig(RequestLoggerConfig{ LogRoutePath: true, LogURI: true, LogValuesFunc: func(c echo.Context, values RequestLoggerValues) error { expect = values return nil }, })) e.GET("/test", func(c echo.Context) error { return c.String(http.StatusTeapot, "OK") }) req := httptest.NewRequest(http.MethodGet, "/test", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, http.StatusTeapot, rec.Code) assert.Equal(t, "/test", expect.RoutePath) } func TestRequestLoggerWithConfig_missingOnLogValuesPanics(t *testing.T) { assert.Panics(t, func() { RequestLoggerWithConfig(RequestLoggerConfig{ LogValuesFunc: nil, }) }) } func TestRequestLogger_skipper(t *testing.T) { e := echo.New() loggerCalled := false e.Use(RequestLoggerWithConfig(RequestLoggerConfig{ Skipper: func(c echo.Context) bool { return true }, LogValuesFunc: func(c echo.Context, values RequestLoggerValues) error { loggerCalled = true return nil }, })) e.GET("/test", func(c echo.Context) error { return c.String(http.StatusTeapot, "OK") }) req := httptest.NewRequest(http.MethodGet, "/test", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, http.StatusTeapot, rec.Code) assert.False(t, loggerCalled) } func TestRequestLogger_beforeNextFunc(t *testing.T) { e := echo.New() var myLoggerInstance int e.Use(RequestLoggerWithConfig(RequestLoggerConfig{ BeforeNextFunc: func(c echo.Context) { c.Set("myLoggerInstance", 42) }, LogValuesFunc: func(c echo.Context, values RequestLoggerValues) error { myLoggerInstance = c.Get("myLoggerInstance").(int) return nil }, })) e.GET("/test", func(c echo.Context) error { return c.String(http.StatusTeapot, "OK") }) req := httptest.NewRequest(http.MethodGet, "/test", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, http.StatusTeapot, rec.Code) assert.Equal(t, 42, myLoggerInstance) } func TestRequestLogger_logError(t *testing.T) { e := echo.New() var actual RequestLoggerValues e.Use(RequestLoggerWithConfig(RequestLoggerConfig{ LogError: true, LogStatus: true, LogValuesFunc: func(c echo.Context, values RequestLoggerValues) error { actual = values return nil }, })) e.GET("/test", func(c echo.Context) error { return echo.NewHTTPError(http.StatusNotAcceptable, "nope") }) req := httptest.NewRequest(http.MethodGet, "/test", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, http.StatusNotAcceptable, rec.Code) assert.Equal(t, http.StatusNotAcceptable, actual.Status) assert.EqualError(t, actual.Error, "code=406, message=nope") } func TestRequestLogger_HandleError(t *testing.T) { e := echo.New() var actual RequestLoggerValues e.Use(RequestLoggerWithConfig(RequestLoggerConfig{ timeNow: func() time.Time { return time.Unix(1631045377, 0).UTC() }, HandleError: true, LogError: true, LogStatus: true, LogValuesFunc: func(c echo.Context, values RequestLoggerValues) error { actual = values return nil }, })) // to see if "HandleError" works we create custom error handler that uses its own status codes e.HTTPErrorHandler = func(err error, c echo.Context) { if c.Response().Committed { return } c.JSON(http.StatusTeapot, "custom error handler") } e.GET("/test", func(c echo.Context) error { return echo.NewHTTPError(http.StatusForbidden, "nope") }) req := httptest.NewRequest(http.MethodGet, "/test", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, http.StatusTeapot, rec.Code) expect := RequestLoggerValues{ StartTime: time.Unix(1631045377, 0).UTC(), Status: http.StatusTeapot, Error: echo.NewHTTPError(http.StatusForbidden, "nope"), } assert.Equal(t, expect, actual) } func TestRequestLogger_LogValuesFuncError(t *testing.T) { e := echo.New() var expect RequestLoggerValues e.Use(RequestLoggerWithConfig(RequestLoggerConfig{ LogError: true, LogStatus: true, LogValuesFunc: func(c echo.Context, values RequestLoggerValues) error { expect = values return echo.NewHTTPError(http.StatusNotAcceptable, "LogValuesFuncError") }, })) e.GET("/test", func(c echo.Context) error { return c.String(http.StatusTeapot, "OK") }) req := httptest.NewRequest(http.MethodGet, "/test", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) // NOTE: when global error handler received error returned from middleware the status has already // been written to the client and response has been "committed" therefore global error handler does not do anything // and error that bubbled up in middleware chain will not be reflected in response code. assert.Equal(t, http.StatusTeapot, rec.Code) assert.Equal(t, http.StatusTeapot, expect.Status) } func TestRequestLogger_ID(t *testing.T) { var testCases = []struct { name string whenFromRequest bool expect string }{ { name: "ok, ID is provided from request headers", whenFromRequest: true, expect: "123", }, { name: "ok, ID is from response headers", whenFromRequest: false, expect: "321", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() var expect RequestLoggerValues e.Use(RequestLoggerWithConfig(RequestLoggerConfig{ LogRequestID: true, LogValuesFunc: func(c echo.Context, values RequestLoggerValues) error { expect = values return nil }, })) e.GET("/test", func(c echo.Context) error { c.Response().Header().Set(echo.HeaderXRequestID, "321") return c.String(http.StatusTeapot, "OK") }) req := httptest.NewRequest(http.MethodGet, "/test", nil) if tc.whenFromRequest { req.Header.Set(echo.HeaderXRequestID, "123") } rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, http.StatusTeapot, rec.Code) assert.Equal(t, tc.expect, expect.RequestID) }) } } func TestRequestLogger_headerIsCaseInsensitive(t *testing.T) { e := echo.New() var expect RequestLoggerValues mw := RequestLoggerWithConfig(RequestLoggerConfig{ LogValuesFunc: func(c echo.Context, values RequestLoggerValues) error { expect = values return nil }, LogHeaders: []string{"referer", "User-Agent"}, })(func(c echo.Context) error { c.Request().Header.Set(echo.HeaderXRequestID, "123") c.FormValue("to force parse form") return c.String(http.StatusTeapot, "OK") }) req := httptest.NewRequest(http.MethodGet, "/test?lang=en&checked=1&checked=2", nil) req.Header.Set("referer", "https://echo.labstack.com/") rec := httptest.NewRecorder() c := e.NewContext(req, rec) err := mw(c) assert.NoError(t, err) assert.Len(t, expect.Headers, 1) assert.Equal(t, []string{"https://echo.labstack.com/"}, expect.Headers["Referer"]) } func TestRequestLogger_allFields(t *testing.T) { e := echo.New() isFirstNowCall := true var expect RequestLoggerValues mw := RequestLoggerWithConfig(RequestLoggerConfig{ LogValuesFunc: func(c echo.Context, values RequestLoggerValues) error { expect = values return nil }, LogLatency: true, LogProtocol: true, LogRemoteIP: true, LogHost: true, LogMethod: true, LogURI: true, LogURIPath: true, LogRoutePath: true, LogRequestID: true, LogReferer: true, LogUserAgent: true, LogStatus: true, LogError: true, LogContentLength: true, LogResponseSize: true, LogHeaders: []string{"accept-encoding", "User-Agent"}, LogQueryParams: []string{"lang", "checked"}, LogFormValues: []string{"csrf", "multiple"}, timeNow: func() time.Time { if isFirstNowCall { isFirstNowCall = false return time.Unix(1631045377, 0) } return time.Unix(1631045377+10, 0) }, })(func(c echo.Context) error { c.Request().Header.Set(echo.HeaderXRequestID, "123") c.FormValue("to force parse form") return c.String(http.StatusTeapot, "OK") }) f := make(url.Values) f.Set("csrf", "token") f.Set("multiple", "1") f.Add("multiple", "2") reader := strings.NewReader(f.Encode()) req := httptest.NewRequest(http.MethodPost, "/test?lang=en&checked=1&checked=2", reader) req.Header.Set("Referer", "https://echo.labstack.com/") req.Header.Set("User-Agent", "curl/7.68.0") req.Header.Set(echo.HeaderContentLength, strconv.Itoa(int(reader.Size()))) req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationForm) req.Header.Set(echo.HeaderXRealIP, "8.8.8.8") rec := httptest.NewRecorder() c := e.NewContext(req, rec) c.SetPath("/test*") err := mw(c) assert.NoError(t, err) assert.Equal(t, time.Unix(1631045377, 0), expect.StartTime) assert.Equal(t, 10*time.Second, expect.Latency) assert.Equal(t, "HTTP/1.1", expect.Protocol) assert.Equal(t, "8.8.8.8", expect.RemoteIP) assert.Equal(t, "example.com", expect.Host) assert.Equal(t, http.MethodPost, expect.Method) assert.Equal(t, "/test?lang=en&checked=1&checked=2", expect.URI) assert.Equal(t, "/test", expect.URIPath) assert.Equal(t, "/test*", expect.RoutePath) assert.Equal(t, "123", expect.RequestID) assert.Equal(t, "https://echo.labstack.com/", expect.Referer) assert.Equal(t, "curl/7.68.0", expect.UserAgent) assert.Equal(t, 418, expect.Status) assert.Equal(t, nil, expect.Error) assert.Equal(t, "32", expect.ContentLength) assert.Equal(t, int64(2), expect.ResponseSize) assert.Len(t, expect.Headers, 1) assert.Equal(t, []string{"curl/7.68.0"}, expect.Headers["User-Agent"]) assert.Len(t, expect.QueryParams, 2) assert.Equal(t, []string{"en"}, expect.QueryParams["lang"]) assert.Equal(t, []string{"1", "2"}, expect.QueryParams["checked"]) assert.Len(t, expect.FormValues, 2) assert.Equal(t, []string{"token"}, expect.FormValues["csrf"]) assert.Equal(t, []string{"1", "2"}, expect.FormValues["multiple"]) } func BenchmarkRequestLogger_withoutMapFields(b *testing.B) { e := echo.New() mw := RequestLoggerWithConfig(RequestLoggerConfig{ Skipper: nil, LogValuesFunc: func(c echo.Context, values RequestLoggerValues) error { return nil }, LogLatency: true, LogProtocol: true, LogRemoteIP: true, LogHost: true, LogMethod: true, LogURI: true, LogURIPath: true, LogRoutePath: true, LogRequestID: true, LogReferer: true, LogUserAgent: true, LogStatus: true, LogError: true, LogContentLength: true, LogResponseSize: true, })(func(c echo.Context) error { c.Request().Header.Set(echo.HeaderXRequestID, "123") return c.String(http.StatusTeapot, "OK") }) req := httptest.NewRequest(http.MethodGet, "/test?lang=en", nil) req.Header.Set("Referer", "https://echo.labstack.com/") req.Header.Set("User-Agent", "curl/7.68.0") b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { rec := httptest.NewRecorder() c := e.NewContext(req, rec) mw(c) } } func BenchmarkRequestLogger_withMapFields(b *testing.B) { e := echo.New() mw := RequestLoggerWithConfig(RequestLoggerConfig{ LogValuesFunc: func(c echo.Context, values RequestLoggerValues) error { return nil }, LogLatency: true, LogProtocol: true, LogRemoteIP: true, LogHost: true, LogMethod: true, LogURI: true, LogURIPath: true, LogRoutePath: true, LogRequestID: true, LogReferer: true, LogUserAgent: true, LogStatus: true, LogError: true, LogContentLength: true, LogResponseSize: true, LogHeaders: []string{"accept-encoding", "User-Agent"}, LogQueryParams: []string{"lang", "checked"}, LogFormValues: []string{"csrf", "multiple"}, })(func(c echo.Context) error { c.Request().Header.Set(echo.HeaderXRequestID, "123") c.FormValue("to force parse form") return c.String(http.StatusTeapot, "OK") }) f := make(url.Values) f.Set("csrf", "token") f.Add("multiple", "1") f.Add("multiple", "2") req := httptest.NewRequest(http.MethodPost, "/test?lang=en&checked=1&checked=2", strings.NewReader(f.Encode())) req.Header.Set("Referer", "https://echo.labstack.com/") req.Header.Set("User-Agent", "curl/7.68.0") req.Header.Add(echo.HeaderContentType, echo.MIMEApplicationForm) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { rec := httptest.NewRecorder() c := e.NewContext(req, rec) mw(c) } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/logger_strings.go
middleware/logger_strings.go
// SPDX-License-Identifier: BSD-3-Clause // SPDX-FileCopyrightText: Copyright 2010 The Go Authors // // Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // // // Go LICENSE https://raw.githubusercontent.com/golang/go/36bca3166e18db52687a4d91ead3f98ffe6d00b8/LICENSE /** Copyright 2009 The Go Authors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google LLC nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package middleware import ( "bytes" "unicode/utf8" ) // This function is modified copy from Go standard library encoding/json/encode.go `appendString` function // Source: https://github.com/golang/go/blob/36bca3166e18db52687a4d91ead3f98ffe6d00b8/src/encoding/json/encode.go#L999 func writeJSONSafeString(buf *bytes.Buffer, src string) (int, error) { const hex = "0123456789abcdef" written := 0 start := 0 for i := 0; i < len(src); { if b := src[i]; b < utf8.RuneSelf { if safeSet[b] { i++ continue } n, err := buf.Write([]byte(src[start:i])) written += n if err != nil { return written, err } switch b { case '\\', '"': n, err := buf.Write([]byte{'\\', b}) written += n if err != nil { return written, err } case '\b': n, err := buf.Write([]byte{'\\', 'b'}) written += n if err != nil { return n, err } case '\f': n, err := buf.Write([]byte{'\\', 'f'}) written += n if err != nil { return written, err } case '\n': n, err := buf.Write([]byte{'\\', 'n'}) written += n if err != nil { return written, err } case '\r': n, err := buf.Write([]byte{'\\', 'r'}) written += n if err != nil { return written, err } case '\t': n, err := buf.Write([]byte{'\\', 't'}) written += n if err != nil { return written, err } default: // This encodes bytes < 0x20 except for \b, \f, \n, \r and \t. n, err := buf.Write([]byte{'\\', 'u', '0', '0', hex[b>>4], hex[b&0xF]}) written += n if err != nil { return written, err } } i++ start = i continue } srcN := min(len(src)-i, utf8.UTFMax) c, size := utf8.DecodeRuneInString(src[i : i+srcN]) if c == utf8.RuneError && size == 1 { n, err := buf.Write([]byte(src[start:i])) written += n if err != nil { return written, err } n, err = buf.Write([]byte(`\ufffd`)) written += n if err != nil { return written, err } i += size start = i continue } i += size } n, err := buf.Write([]byte(src[start:])) written += n return written, err } // safeSet holds the value true if the ASCII character with the given array // position can be represented inside a JSON string without any further // escaping. // // All values are true except for the ASCII control characters (0-31), the // double quote ("), and the backslash character ("\"). var safeSet = [utf8.RuneSelf]bool{ ' ': true, '!': true, '"': false, '#': true, '$': true, '%': true, '&': true, '\'': true, '(': true, ')': true, '*': true, '+': true, ',': true, '-': true, '.': true, '/': true, '0': true, '1': true, '2': true, '3': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true, ':': true, ';': true, '<': true, '=': true, '>': true, '?': true, '@': true, 'A': true, 'B': true, 'C': true, 'D': true, 'E': true, 'F': true, 'G': true, 'H': true, 'I': true, 'J': true, 'K': true, 'L': true, 'M': true, 'N': true, 'O': true, 'P': true, 'Q': true, 'R': true, 'S': true, 'T': true, 'U': true, 'V': true, 'W': true, 'X': true, 'Y': true, 'Z': true, '[': true, '\\': false, ']': true, '^': true, '_': true, '`': true, 'a': true, 'b': true, 'c': true, 'd': true, 'e': true, 'f': true, 'g': true, 'h': true, 'i': true, 'j': true, 'k': true, 'l': true, 'm': true, 'n': true, 'o': true, 'p': true, 'q': true, 'r': true, 's': true, 't': true, 'u': true, 'v': true, 'w': true, 'x': true, 'y': true, 'z': true, '{': true, '|': true, '}': true, '~': true, '\u007f': true, }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/logger_test.go
middleware/logger_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "bytes" "cmp" "encoding/json" "errors" "net/http" "net/http/httptest" "net/url" "regexp" "strings" "testing" "time" "unsafe" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func TestLoggerDefaultMW(t *testing.T) { var testCases = []struct { name string whenHeader map[string]string whenStatusCode int whenResponse string whenError error expect string }{ { name: "ok, status 200", whenStatusCode: http.StatusOK, whenResponse: "test", expect: `{"time":"2020-04-28T01:26:40Z","id":"","remote_ip":"192.0.2.1","host":"example.com","method":"GET","uri":"/","user_agent":"","status":200,"error":"","latency":1,"latency_human":"1µs","bytes_in":0,"bytes_out":4}` + "\n", }, { name: "ok, status 300", whenStatusCode: http.StatusTemporaryRedirect, whenResponse: "test", expect: `{"time":"2020-04-28T01:26:40Z","id":"","remote_ip":"192.0.2.1","host":"example.com","method":"GET","uri":"/","user_agent":"","status":307,"error":"","latency":1,"latency_human":"1µs","bytes_in":0,"bytes_out":4}` + "\n", }, { name: "ok, handler error = status 500", whenError: errors.New("error"), expect: `{"time":"2020-04-28T01:26:40Z","id":"","remote_ip":"192.0.2.1","host":"example.com","method":"GET","uri":"/","user_agent":"","status":500,"error":"error","latency":1,"latency_human":"1µs","bytes_in":0,"bytes_out":36}` + "\n", }, { name: "error with invalid UTF-8 sequences", whenError: errors.New("invalid data: \xFF\xFE"), expect: `{"time":"2020-04-28T01:26:40Z","id":"","remote_ip":"192.0.2.1","host":"example.com","method":"GET","uri":"/","user_agent":"","status":500,"error":"invalid data: \ufffd\ufffd","latency":1,"latency_human":"1µs","bytes_in":0,"bytes_out":36}` + "\n", }, { name: "error with JSON special characters (quotes and backslashes)", whenError: errors.New(`error with "quotes" and \backslash`), expect: `{"time":"2020-04-28T01:26:40Z","id":"","remote_ip":"192.0.2.1","host":"example.com","method":"GET","uri":"/","user_agent":"","status":500,"error":"error with \"quotes\" and \\backslash","latency":1,"latency_human":"1µs","bytes_in":0,"bytes_out":36}` + "\n", }, { name: "error with control characters (newlines and tabs)", whenError: errors.New("error\nwith\nnewlines\tand\ttabs"), expect: `{"time":"2020-04-28T01:26:40Z","id":"","remote_ip":"192.0.2.1","host":"example.com","method":"GET","uri":"/","user_agent":"","status":500,"error":"error\nwith\nnewlines\tand\ttabs","latency":1,"latency_human":"1µs","bytes_in":0,"bytes_out":36}` + "\n", }, { name: "ok, remote_ip from X-Real-Ip header", whenHeader: map[string]string{echo.HeaderXRealIP: "127.0.0.1"}, whenStatusCode: http.StatusOK, whenResponse: "test", expect: `{"time":"2020-04-28T01:26:40Z","id":"","remote_ip":"127.0.0.1","host":"example.com","method":"GET","uri":"/","user_agent":"","status":200,"error":"","latency":1,"latency_human":"1µs","bytes_in":0,"bytes_out":4}` + "\n", }, { name: "ok, remote_ip from X-Forwarded-For header", whenHeader: map[string]string{echo.HeaderXForwardedFor: "127.0.0.1"}, whenStatusCode: http.StatusOK, whenResponse: "test", expect: `{"time":"2020-04-28T01:26:40Z","id":"","remote_ip":"127.0.0.1","host":"example.com","method":"GET","uri":"/","user_agent":"","status":200,"error":"","latency":1,"latency_human":"1µs","bytes_in":0,"bytes_out":4}` + "\n", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) if len(tc.whenHeader) > 0 { for k, v := range tc.whenHeader { req.Header.Add(k, v) } } rec := httptest.NewRecorder() c := e.NewContext(req, rec) DefaultLoggerConfig.timeNow = func() time.Time { return time.Unix(1588037200, 0).UTC() } h := Logger()(func(c echo.Context) error { if tc.whenError != nil { return tc.whenError } return c.String(tc.whenStatusCode, tc.whenResponse) }) buf := new(bytes.Buffer) e.Logger.SetOutput(buf) err := h(c) assert.NoError(t, err) result := buf.String() // handle everchanging latency numbers result = regexp.MustCompile(`"latency":\d+,`).ReplaceAllString(result, `"latency":1,`) result = regexp.MustCompile(`"latency_human":"[^"]+"`).ReplaceAllString(result, `"latency_human":"1µs"`) assert.Equal(t, tc.expect, result) }) } } func TestLoggerWithLoggerConfig(t *testing.T) { // to handle everchanging latency numbers jsonLatency := map[string]*regexp.Regexp{ `"latency":1,`: regexp.MustCompile(`"latency":\d+,`), `"latency_human":"1µs"`: regexp.MustCompile(`"latency_human":"[^"]+"`), } form := make(url.Values) form.Set("csrf", "token") form.Add("multiple", "1") form.Add("multiple", "2") var testCases = []struct { name string givenConfig LoggerConfig whenURI string whenMethod string whenHost string whenPath string whenRoute string whenProto string whenRequestURI string whenHeader map[string]string whenFormValues url.Values whenStatusCode int whenResponse string whenError error whenReplacers map[string]*regexp.Regexp expect string }{ { name: "ok, skipper", givenConfig: LoggerConfig{ Skipper: func(c echo.Context) bool { return true }, }, expect: ``, }, { // this is an example how format that does not seem to be JSON is not currently escaped name: "ok, NON json string is not escaped: method", givenConfig: LoggerConfig{Format: `method:"${method}"`}, whenMethod: `","method":":D"`, expect: `method:"","method":":D""`, }, { name: "ok, json string escape: method", givenConfig: LoggerConfig{Format: `{"method":"${method}"}`}, whenMethod: `","method":":D"`, expect: `{"method":"\",\"method\":\":D\""}`, }, { name: "ok, json string escape: id", givenConfig: LoggerConfig{Format: `{"id":"${id}"}`}, whenHeader: map[string]string{echo.HeaderXRequestID: `\"127.0.0.1\"`}, expect: `{"id":"\\\"127.0.0.1\\\""}`, }, { name: "ok, json string escape: remote_ip", givenConfig: LoggerConfig{Format: `{"remote_ip":"${remote_ip}"}`}, whenHeader: map[string]string{echo.HeaderXForwardedFor: `\"127.0.0.1\"`}, expect: `{"remote_ip":"\\\"127.0.0.1\\\""}`, }, { name: "ok, json string escape: host", givenConfig: LoggerConfig{Format: `{"host":"${host}"}`}, whenHost: `\"127.0.0.1\"`, expect: `{"host":"\\\"127.0.0.1\\\""}`, }, { name: "ok, json string escape: path", givenConfig: LoggerConfig{Format: `{"path":"${path}"}`}, whenPath: `\","` + "\n", expect: `{"path":"\\\",\"\n"}`, }, { name: "ok, json string escape: route", givenConfig: LoggerConfig{Format: `{"route":"${route}"}`}, whenRoute: `\","` + "\n", expect: `{"route":"\\\",\"\n"}`, }, { name: "ok, json string escape: proto", givenConfig: LoggerConfig{Format: `{"protocol":"${protocol}"}`}, whenProto: `\","` + "\n", expect: `{"protocol":"\\\",\"\n"}`, }, { name: "ok, json string escape: referer", givenConfig: LoggerConfig{Format: `{"referer":"${referer}"}`}, whenHeader: map[string]string{"Referer": `\","` + "\n"}, expect: `{"referer":"\\\",\"\n"}`, }, { name: "ok, json string escape: user_agent", givenConfig: LoggerConfig{Format: `{"user_agent":"${user_agent}"}`}, whenHeader: map[string]string{"User-Agent": `\","` + "\n"}, expect: `{"user_agent":"\\\",\"\n"}`, }, { name: "ok, json string escape: bytes_in", givenConfig: LoggerConfig{Format: `{"bytes_in":"${bytes_in}"}`}, whenHeader: map[string]string{echo.HeaderContentLength: `\","` + "\n"}, expect: `{"bytes_in":"\\\",\"\n"}`, }, { name: "ok, json string escape: query param", givenConfig: LoggerConfig{Format: `{"query":"${query:test}"}`}, whenURI: `/?test=1","`, expect: `{"query":"1\",\""}`, }, { name: "ok, json string escape: header", givenConfig: LoggerConfig{Format: `{"header":"${header:referer}"}`}, whenHeader: map[string]string{"referer": `\","` + "\n"}, expect: `{"header":"\\\",\"\n"}`, }, { name: "ok, json string escape: form", givenConfig: LoggerConfig{Format: `{"csrf":"${form:csrf}"}`}, whenMethod: http.MethodPost, whenFormValues: url.Values{"csrf": {`token","`}}, expect: `{"csrf":"token\",\""}`, }, { name: "nok, json string escape: cookie - will not accept invalid chars", // net/cookie.go: validCookieValueByte function allows these byte in cookie value // only `0x20 <= b && b < 0x7f && b != '"' && b != ';' && b != '\\'` givenConfig: LoggerConfig{Format: `{"cookie":"${cookie:session}"}`}, whenHeader: map[string]string{"Cookie": `_ga=GA1.2.000000000.0000000000; session=test\n`}, expect: `{"cookie":""}`, }, { name: "ok, format time_unix", givenConfig: LoggerConfig{Format: `${time_unix}`}, whenStatusCode: http.StatusOK, whenResponse: "test", expect: `1588037200`, }, { name: "ok, format time_unix_milli", givenConfig: LoggerConfig{Format: `${time_unix_milli}`}, whenStatusCode: http.StatusOK, whenResponse: "test", expect: `1588037200000`, }, { name: "ok, format time_unix_micro", givenConfig: LoggerConfig{Format: `${time_unix_micro}`}, whenStatusCode: http.StatusOK, whenResponse: "test", expect: `1588037200000000`, }, { name: "ok, format time_unix_nano", givenConfig: LoggerConfig{Format: `${time_unix_nano}`}, whenStatusCode: http.StatusOK, whenResponse: "test", expect: `1588037200000000000`, }, { name: "ok, format time_rfc3339", givenConfig: LoggerConfig{Format: `${time_rfc3339}`}, whenStatusCode: http.StatusOK, whenResponse: "test", expect: `2020-04-28T01:26:40Z`, }, { name: "ok, status 200", whenStatusCode: http.StatusOK, whenResponse: "test", whenReplacers: jsonLatency, expect: `{"time":"2020-04-28T01:26:40Z","id":"","remote_ip":"192.0.2.1","host":"example.com","method":"GET","uri":"/","user_agent":"","status":200,"error":"","latency":1,"latency_human":"1µs","bytes_in":0,"bytes_out":4}` + "\n", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, cmp.Or(tc.whenURI, "/"), nil) if tc.whenFormValues != nil { req = httptest.NewRequest(http.MethodGet, cmp.Or(tc.whenURI, "/"), strings.NewReader(tc.whenFormValues.Encode())) req.Header.Add(echo.HeaderContentType, echo.MIMEApplicationForm) } for k, v := range tc.whenHeader { req.Header.Add(k, v) } if tc.whenHost != "" { req.Host = tc.whenHost } if tc.whenMethod != "" { req.Method = tc.whenMethod } if tc.whenProto != "" { req.Proto = tc.whenProto } if tc.whenRequestURI != "" { req.RequestURI = tc.whenRequestURI } if tc.whenPath != "" { req.URL.Path = tc.whenPath } rec := httptest.NewRecorder() c := e.NewContext(req, rec) if tc.whenFormValues != nil { c.FormValue("to trigger form parsing") } if tc.whenRoute != "" { c.SetPath(tc.whenRoute) } config := tc.givenConfig if config.timeNow == nil { config.timeNow = func() time.Time { return time.Unix(1588037200, 0).UTC() } } buf := new(bytes.Buffer) if config.Output == nil { e.Logger.SetOutput(buf) } h := LoggerWithConfig(config)(func(c echo.Context) error { if tc.whenError != nil { return tc.whenError } return c.String(cmp.Or(tc.whenStatusCode, http.StatusOK), cmp.Or(tc.whenResponse, "test")) }) err := h(c) assert.NoError(t, err) result := buf.String() for replaceTo, replacer := range tc.whenReplacers { result = replacer.ReplaceAllString(result, replaceTo) } assert.Equal(t, tc.expect, result) }) } } func TestLoggerTemplate(t *testing.T) { buf := new(bytes.Buffer) e := echo.New() e.Use(LoggerWithConfig(LoggerConfig{ Format: `{"time":"${time_rfc3339_nano}","id":"${id}","remote_ip":"${remote_ip}","host":"${host}","user_agent":"${user_agent}",` + `"method":"${method}","uri":"${uri}","status":${status}, "latency":${latency},` + `"latency_human":"${latency_human}","bytes_in":${bytes_in}, "path":"${path}", "route":"${route}", "referer":"${referer}",` + `"bytes_out":${bytes_out},"ch":"${header:X-Custom-Header}", "protocol":"${protocol}"` + `"us":"${query:username}", "cf":"${form:username}", "session":"${cookie:session}"}` + "\n", Output: buf, })) e.GET("/users/:id", func(c echo.Context) error { return c.String(http.StatusOK, "Header Logged") }) req := httptest.NewRequest(http.MethodGet, "/users/1?username=apagano-param&password=secret", nil) req.RequestURI = "/" req.Header.Add(echo.HeaderXRealIP, "127.0.0.1") req.Header.Add("Referer", "google.com") req.Header.Add("User-Agent", "echo-tests-agent") req.Header.Add("X-Custom-Header", "AAA-CUSTOM-VALUE") req.Header.Add("X-Request-ID", "6ba7b810-9dad-11d1-80b4-00c04fd430c8") req.Header.Add("Cookie", "_ga=GA1.2.000000000.0000000000; session=ac08034cd216a647fc2eb62f2bcf7b810") req.Form = url.Values{ "username": []string{"apagano-form"}, "password": []string{"secret-form"}, } rec := httptest.NewRecorder() e.ServeHTTP(rec, req) cases := map[string]bool{ "apagano-param": true, "apagano-form": true, "AAA-CUSTOM-VALUE": true, "BBB-CUSTOM-VALUE": false, "secret-form": false, "hexvalue": false, "GET": true, "127.0.0.1": true, "\"path\":\"/users/1\"": true, "\"route\":\"/users/:id\"": true, "\"uri\":\"/\"": true, "\"status\":200": true, "\"bytes_in\":0": true, "google.com": true, "echo-tests-agent": true, "6ba7b810-9dad-11d1-80b4-00c04fd430c8": true, "ac08034cd216a647fc2eb62f2bcf7b810": true, } for token, present := range cases { assert.True(t, strings.Contains(buf.String(), token) == present, "Case: "+token) } } func TestLoggerCustomTimestamp(t *testing.T) { buf := new(bytes.Buffer) customTimeFormat := "2006-01-02 15:04:05.00000" e := echo.New() e.Use(LoggerWithConfig(LoggerConfig{ Format: `{"time":"${time_custom}","id":"${id}","remote_ip":"${remote_ip}","host":"${host}","user_agent":"${user_agent}",` + `"method":"${method}","uri":"${uri}","status":${status}, "latency":${latency},` + `"latency_human":"${latency_human}","bytes_in":${bytes_in}, "path":"${path}", "referer":"${referer}",` + `"bytes_out":${bytes_out},"ch":"${header:X-Custom-Header}",` + `"us":"${query:username}", "cf":"${form:username}", "session":"${cookie:session}"}` + "\n", CustomTimeFormat: customTimeFormat, Output: buf, })) e.GET("/", func(c echo.Context) error { return c.String(http.StatusOK, "custom time stamp test") }) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) var objs map[string]*json.RawMessage if err := json.Unmarshal(buf.Bytes(), &objs); err != nil { panic(err) } loggedTime := *(*string)(unsafe.Pointer(objs["time"])) _, err := time.Parse(customTimeFormat, loggedTime) assert.Error(t, err) } func TestLoggerCustomTagFunc(t *testing.T) { e := echo.New() buf := new(bytes.Buffer) e.Use(LoggerWithConfig(LoggerConfig{ Format: `{"method":"${method}",${custom}}` + "\n", CustomTagFunc: func(c echo.Context, buf *bytes.Buffer) (int, error) { return buf.WriteString(`"tag":"my-value"`) }, Output: buf, })) e.GET("/", func(c echo.Context) error { return c.String(http.StatusOK, "custom time stamp test") }) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, `{"method":"GET","tag":"my-value"}`+"\n", buf.String()) } func BenchmarkLoggerWithConfig_withoutMapFields(b *testing.B) { e := echo.New() buf := new(bytes.Buffer) mw := LoggerWithConfig(LoggerConfig{ Format: `{"time":"${time_rfc3339_nano}","id":"${id}","remote_ip":"${remote_ip}","host":"${host}","user_agent":"${user_agent}",` + `"method":"${method}","uri":"${uri}","status":${status}, "latency":${latency},` + `"latency_human":"${latency_human}","bytes_in":${bytes_in}, "path":"${path}", "referer":"${referer}",` + `"bytes_out":${bytes_out}, "protocol":"${protocol}"}` + "\n", Output: buf, })(func(c echo.Context) error { c.Request().Header.Set(echo.HeaderXRequestID, "123") c.FormValue("to force parse form") return c.String(http.StatusTeapot, "OK") }) f := make(url.Values) f.Set("csrf", "token") f.Add("multiple", "1") f.Add("multiple", "2") req := httptest.NewRequest(http.MethodPost, "/test?lang=en&checked=1&checked=2", strings.NewReader(f.Encode())) req.Header.Set("Referer", "https://echo.labstack.com/") req.Header.Set("User-Agent", "curl/7.68.0") req.Header.Add(echo.HeaderContentType, echo.MIMEApplicationForm) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { rec := httptest.NewRecorder() c := e.NewContext(req, rec) mw(c) buf.Reset() } } func BenchmarkLoggerWithConfig_withMapFields(b *testing.B) { e := echo.New() buf := new(bytes.Buffer) mw := LoggerWithConfig(LoggerConfig{ Format: `{"time":"${time_rfc3339_nano}","id":"${id}","remote_ip":"${remote_ip}","host":"${host}","user_agent":"${user_agent}",` + `"method":"${method}","uri":"${uri}","status":${status}, "latency":${latency},` + `"latency_human":"${latency_human}","bytes_in":${bytes_in}, "path":"${path}", "referer":"${referer}",` + `"bytes_out":${bytes_out},"ch":"${header:X-Custom-Header}", "protocol":"${protocol}"` + `"us":"${query:username}", "cf":"${form:csrf}", "Referer2":"${header:Referer}"}` + "\n", Output: buf, })(func(c echo.Context) error { c.Request().Header.Set(echo.HeaderXRequestID, "123") c.FormValue("to force parse form") return c.String(http.StatusTeapot, "OK") }) f := make(url.Values) f.Set("csrf", "token") f.Add("multiple", "1") f.Add("multiple", "2") req := httptest.NewRequest(http.MethodPost, "/test?lang=en&checked=1&checked=2", strings.NewReader(f.Encode())) req.Header.Set("Referer", "https://echo.labstack.com/") req.Header.Set("User-Agent", "curl/7.68.0") req.Header.Add(echo.HeaderContentType, echo.MIMEApplicationForm) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { rec := httptest.NewRecorder() c := e.NewContext(req, rec) mw(c) buf.Reset() } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/basic_auth_test.go
middleware/basic_auth_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "encoding/base64" "errors" "net/http" "net/http/httptest" "strings" "testing" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func TestBasicAuth(t *testing.T) { e := echo.New() mockValidator := func(u, p string, c echo.Context) (bool, error) { if u == "joe" && p == "secret" { return true, nil } return false, nil } tests := []struct { name string authHeader string expectedCode int expectedAuth string skipperResult bool expectedErr bool expectedErrMsg string }{ { name: "Valid credentials", authHeader: basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:secret")), expectedCode: http.StatusOK, }, { name: "Case-insensitive header scheme", authHeader: strings.ToUpper(basic) + " " + base64.StdEncoding.EncodeToString([]byte("joe:secret")), expectedCode: http.StatusOK, }, { name: "Invalid credentials", authHeader: basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:invalid-password")), expectedCode: http.StatusUnauthorized, expectedAuth: basic + ` realm="someRealm"`, expectedErr: true, expectedErrMsg: "Unauthorized", }, { name: "Invalid base64 string", authHeader: basic + " invalidString", expectedCode: http.StatusBadRequest, expectedErr: true, expectedErrMsg: "Bad Request", }, { name: "Missing Authorization header", expectedCode: http.StatusUnauthorized, expectedErr: true, expectedErrMsg: "Unauthorized", }, { name: "Invalid Authorization header", authHeader: base64.StdEncoding.EncodeToString([]byte("invalid")), expectedCode: http.StatusUnauthorized, expectedErr: true, expectedErrMsg: "Unauthorized", }, { name: "Skipped Request", authHeader: basic + " " + base64.StdEncoding.EncodeToString([]byte("joe:skip")), expectedCode: http.StatusOK, skipperResult: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/", nil) res := httptest.NewRecorder() c := e.NewContext(req, res) if tt.authHeader != "" { req.Header.Set(echo.HeaderAuthorization, tt.authHeader) } h := BasicAuthWithConfig(BasicAuthConfig{ Validator: mockValidator, Realm: "someRealm", Skipper: func(c echo.Context) bool { return tt.skipperResult }, })(func(c echo.Context) error { return c.String(http.StatusOK, "test") }) err := h(c) if tt.expectedErr { var he *echo.HTTPError errors.As(err, &he) assert.Equal(t, tt.expectedCode, he.Code) if tt.expectedAuth != "" { assert.Equal(t, tt.expectedAuth, res.Header().Get(echo.HeaderWWWAuthenticate)) } } else { assert.NoError(t, err) assert.Equal(t, tt.expectedCode, res.Code) } }) } } func TestBasicAuthRealm(t *testing.T) { e := echo.New() mockValidator := func(u, p string, c echo.Context) (bool, error) { return false, nil // Always fail to trigger WWW-Authenticate header } tests := []struct { name string realm string expectedAuth string }{ { name: "Default realm", realm: "Restricted", expectedAuth: `basic realm="Restricted"`, }, { name: "Custom realm", realm: "My API", expectedAuth: `basic realm="My API"`, }, { name: "Realm with special characters", realm: `Realm with "quotes" and \backslashes`, expectedAuth: `basic realm="Realm with \"quotes\" and \\backslashes"`, }, { name: "Empty realm (falls back to default)", realm: "", expectedAuth: `basic realm="Restricted"`, }, { name: "Realm with unicode", realm: "测试领域", expectedAuth: `basic realm="测试领域"`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/", nil) res := httptest.NewRecorder() c := e.NewContext(req, res) h := BasicAuthWithConfig(BasicAuthConfig{ Validator: mockValidator, Realm: tt.realm, })(func(c echo.Context) error { return c.String(http.StatusOK, "test") }) err := h(c) var he *echo.HTTPError errors.As(err, &he) assert.Equal(t, http.StatusUnauthorized, he.Code) assert.Equal(t, tt.expectedAuth, res.Header().Get(echo.HeaderWWWAuthenticate)) }) } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/secure.go
middleware/secure.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "fmt" "github.com/labstack/echo/v4" ) // SecureConfig defines the config for Secure middleware. type SecureConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // XSSProtection provides protection against cross-site scripting attack (XSS) // by setting the `X-XSS-Protection` header. // Optional. Default value "1; mode=block". XSSProtection string `yaml:"xss_protection"` // ContentTypeNosniff provides protection against overriding Content-Type // header by setting the `X-Content-Type-Options` header. // Optional. Default value "nosniff". ContentTypeNosniff string `yaml:"content_type_nosniff"` // XFrameOptions can be used to indicate whether or not a browser should // be allowed to render a page in a <frame>, <iframe> or <object> . // Sites can use this to avoid clickjacking attacks, by ensuring that their // content is not embedded into other sites.provides protection against // clickjacking. // Optional. Default value "SAMEORIGIN". // Possible values: // - "SAMEORIGIN" - The page can only be displayed in a frame on the same origin as the page itself. // - "DENY" - The page cannot be displayed in a frame, regardless of the site attempting to do so. // - "ALLOW-FROM uri" - The page can only be displayed in a frame on the specified origin. XFrameOptions string `yaml:"x_frame_options"` // HSTSMaxAge sets the `Strict-Transport-Security` header to indicate how // long (in seconds) browsers should remember that this site is only to // be accessed using HTTPS. This reduces your exposure to some SSL-stripping // man-in-the-middle (MITM) attacks. // Optional. Default value 0. HSTSMaxAge int `yaml:"hsts_max_age"` // HSTSExcludeSubdomains won't include subdomains tag in the `Strict Transport Security` // header, excluding all subdomains from security policy. It has no effect // unless HSTSMaxAge is set to a non-zero value. // Optional. Default value false. HSTSExcludeSubdomains bool `yaml:"hsts_exclude_subdomains"` // ContentSecurityPolicy sets the `Content-Security-Policy` header providing // security against cross-site scripting (XSS), clickjacking and other code // injection attacks resulting from execution of malicious content in the // trusted web page context. // Optional. Default value "". ContentSecurityPolicy string `yaml:"content_security_policy"` // CSPReportOnly would use the `Content-Security-Policy-Report-Only` header instead // of the `Content-Security-Policy` header. This allows iterative updates of the // content security policy by only reporting the violations that would // have occurred instead of blocking the resource. // Optional. Default value false. CSPReportOnly bool `yaml:"csp_report_only"` // HSTSPreloadEnabled will add the preload tag in the `Strict Transport Security` // header, which enables the domain to be included in the HSTS preload list // maintained by Chrome (and used by Firefox and Safari): https://hstspreload.org/ // Optional. Default value false. HSTSPreloadEnabled bool `yaml:"hsts_preload_enabled"` // ReferrerPolicy sets the `Referrer-Policy` header providing security against // leaking potentially sensitive request paths to third parties. // Optional. Default value "". ReferrerPolicy string `yaml:"referrer_policy"` } // DefaultSecureConfig is the default Secure middleware config. var DefaultSecureConfig = SecureConfig{ Skipper: DefaultSkipper, XSSProtection: "1; mode=block", ContentTypeNosniff: "nosniff", XFrameOptions: "SAMEORIGIN", HSTSPreloadEnabled: false, } // Secure returns a Secure middleware. // Secure middleware provides protection against cross-site scripting (XSS) attack, // content type sniffing, clickjacking, insecure connection and other code injection // attacks. func Secure() echo.MiddlewareFunc { return SecureWithConfig(DefaultSecureConfig) } // SecureWithConfig returns a Secure middleware with config. // See: `Secure()`. func SecureWithConfig(config SecureConfig) echo.MiddlewareFunc { // Defaults if config.Skipper == nil { config.Skipper = DefaultSecureConfig.Skipper } return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { if config.Skipper(c) { return next(c) } req := c.Request() res := c.Response() if config.XSSProtection != "" { res.Header().Set(echo.HeaderXXSSProtection, config.XSSProtection) } if config.ContentTypeNosniff != "" { res.Header().Set(echo.HeaderXContentTypeOptions, config.ContentTypeNosniff) } if config.XFrameOptions != "" { res.Header().Set(echo.HeaderXFrameOptions, config.XFrameOptions) } if (c.IsTLS() || (req.Header.Get(echo.HeaderXForwardedProto) == "https")) && config.HSTSMaxAge != 0 { subdomains := "" if !config.HSTSExcludeSubdomains { subdomains = "; includeSubdomains" } if config.HSTSPreloadEnabled { subdomains = fmt.Sprintf("%s; preload", subdomains) } res.Header().Set(echo.HeaderStrictTransportSecurity, fmt.Sprintf("max-age=%d%s", config.HSTSMaxAge, subdomains)) } if config.ContentSecurityPolicy != "" { if config.CSPReportOnly { res.Header().Set(echo.HeaderContentSecurityPolicyReportOnly, config.ContentSecurityPolicy) } else { res.Header().Set(echo.HeaderContentSecurityPolicy, config.ContentSecurityPolicy) } } if config.ReferrerPolicy != "" { res.Header().Set(echo.HeaderReferrerPolicy, config.ReferrerPolicy) } return next(c) } } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/slash.go
middleware/slash.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "strings" "github.com/labstack/echo/v4" ) // TrailingSlashConfig defines the config for TrailingSlash middleware. type TrailingSlashConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // Status code to be used when redirecting the request. // Optional, but when provided the request is redirected using this code. RedirectCode int `yaml:"redirect_code"` } // DefaultTrailingSlashConfig is the default TrailingSlash middleware config. var DefaultTrailingSlashConfig = TrailingSlashConfig{ Skipper: DefaultSkipper, } // AddTrailingSlash returns a root level (before router) middleware which adds a // trailing slash to the request `URL#Path`. // // Usage `Echo#Pre(AddTrailingSlash())` func AddTrailingSlash() echo.MiddlewareFunc { return AddTrailingSlashWithConfig(DefaultTrailingSlashConfig) } // AddTrailingSlashWithConfig returns an AddTrailingSlash middleware with config. // See `AddTrailingSlash()`. func AddTrailingSlashWithConfig(config TrailingSlashConfig) echo.MiddlewareFunc { // Defaults if config.Skipper == nil { config.Skipper = DefaultTrailingSlashConfig.Skipper } return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { if config.Skipper(c) { return next(c) } req := c.Request() url := req.URL path := url.Path qs := c.QueryString() if !strings.HasSuffix(path, "/") { path += "/" uri := path if qs != "" { uri += "?" + qs } // Redirect if config.RedirectCode != 0 { return c.Redirect(config.RedirectCode, sanitizeURI(uri)) } // Forward req.RequestURI = uri url.Path = path } return next(c) } } } // RemoveTrailingSlash returns a root level (before router) middleware which removes // a trailing slash from the request URI. // // Usage `Echo#Pre(RemoveTrailingSlash())` func RemoveTrailingSlash() echo.MiddlewareFunc { return RemoveTrailingSlashWithConfig(TrailingSlashConfig{}) } // RemoveTrailingSlashWithConfig returns a RemoveTrailingSlash middleware with config. // See `RemoveTrailingSlash()`. func RemoveTrailingSlashWithConfig(config TrailingSlashConfig) echo.MiddlewareFunc { // Defaults if config.Skipper == nil { config.Skipper = DefaultTrailingSlashConfig.Skipper } return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { if config.Skipper(c) { return next(c) } req := c.Request() url := req.URL path := url.Path qs := c.QueryString() l := len(path) - 1 if l > 0 && strings.HasSuffix(path, "/") { path = path[:l] uri := path if qs != "" { uri += "?" + qs } // Redirect if config.RedirectCode != 0 { return c.Redirect(config.RedirectCode, sanitizeURI(uri)) } // Forward req.RequestURI = uri url.Path = path } return next(c) } } } func sanitizeURI(uri string) string { // double slash `\\`, `//` or even `\/` is absolute uri for browsers and by redirecting request to that uri // we are vulnerable to open redirect attack. so replace all slashes from the beginning with single slash if len(uri) > 1 && (uri[0] == '\\' || uri[0] == '/') && (uri[1] == '\\' || uri[1] == '/') { uri = "/" + strings.TrimLeft(uri, `/\`) } return uri }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/rewrite.go
middleware/rewrite.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "regexp" "github.com/labstack/echo/v4" ) // RewriteConfig defines the config for Rewrite middleware. type RewriteConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // Rules defines the URL path rewrite rules. The values captured in asterisk can be // retrieved by index e.g. $1, $2 and so on. // Example: // "/old": "/new", // "/api/*": "/$1", // "/js/*": "/public/javascripts/$1", // "/users/*/orders/*": "/user/$1/order/$2", // Required. Rules map[string]string `yaml:"rules"` // RegexRules defines the URL path rewrite rules using regexp.Rexexp with captures // Every capture group in the values can be retrieved by index e.g. $1, $2 and so on. // Example: // "^/old/[0.9]+/": "/new", // "^/api/.+?/(.*)": "/v2/$1", RegexRules map[*regexp.Regexp]string `yaml:"-"` } // DefaultRewriteConfig is the default Rewrite middleware config. var DefaultRewriteConfig = RewriteConfig{ Skipper: DefaultSkipper, } // Rewrite returns a Rewrite middleware. // // Rewrite middleware rewrites the URL path based on the provided rules. func Rewrite(rules map[string]string) echo.MiddlewareFunc { c := DefaultRewriteConfig c.Rules = rules return RewriteWithConfig(c) } // RewriteWithConfig returns a Rewrite middleware with config. // See: `Rewrite()`. func RewriteWithConfig(config RewriteConfig) echo.MiddlewareFunc { // Defaults if config.Rules == nil && config.RegexRules == nil { panic("echo: rewrite middleware requires url path rewrite rules or regex rules") } if config.Skipper == nil { config.Skipper = DefaultBodyDumpConfig.Skipper } if config.RegexRules == nil { config.RegexRules = make(map[*regexp.Regexp]string) } for k, v := range rewriteRulesRegex(config.Rules) { config.RegexRules[k] = v } return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) (err error) { if config.Skipper(c) { return next(c) } if err := rewriteURL(config.RegexRules, c.Request()); err != nil { return err } return next(c) } } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/extractor.go
middleware/extractor.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "errors" "fmt" "github.com/labstack/echo/v4" "net/textproto" "strings" ) const ( // extractorLimit is arbitrary number to limit values extractor can return. this limits possible resource exhaustion // attack vector extractorLimit = 20 ) var errHeaderExtractorValueMissing = errors.New("missing value in request header") var errHeaderExtractorValueInvalid = errors.New("invalid value in request header") var errQueryExtractorValueMissing = errors.New("missing value in the query string") var errParamExtractorValueMissing = errors.New("missing value in path params") var errCookieExtractorValueMissing = errors.New("missing value in cookies") var errFormExtractorValueMissing = errors.New("missing value in the form") // ValuesExtractor defines a function for extracting values (keys/tokens) from the given context. type ValuesExtractor func(c echo.Context) ([]string, error) // CreateExtractors creates ValuesExtractors from given lookups. // Lookups is a string in the form of "<source>:<name>" or "<source>:<name>,<source>:<name>" that is used // to extract key from the request. // Possible values: // - "header:<name>" or "header:<name>:<cut-prefix>" // `<cut-prefix>` is argument value to cut/trim prefix of the extracted value. This is useful if header // value has static prefix like `Authorization: <auth-scheme> <authorisation-parameters>` where part that we // want to cut is `<auth-scheme> ` note the space at the end. // In case of basic authentication `Authorization: Basic <credentials>` prefix we want to remove is `Basic `. // - "query:<name>" // - "param:<name>" // - "form:<name>" // - "cookie:<name>" // // Multiple sources example: // - "header:Authorization,header:X-Api-Key" func CreateExtractors(lookups string) ([]ValuesExtractor, error) { return createExtractors(lookups, "") } func createExtractors(lookups string, authScheme string) ([]ValuesExtractor, error) { if lookups == "" { return nil, nil } sources := strings.Split(lookups, ",") var extractors = make([]ValuesExtractor, 0) for _, source := range sources { parts := strings.Split(source, ":") if len(parts) < 2 { return nil, fmt.Errorf("extractor source for lookup could not be split into needed parts: %v", source) } switch parts[0] { case "query": extractors = append(extractors, valuesFromQuery(parts[1])) case "param": extractors = append(extractors, valuesFromParam(parts[1])) case "cookie": extractors = append(extractors, valuesFromCookie(parts[1])) case "form": extractors = append(extractors, valuesFromForm(parts[1])) case "header": prefix := "" if len(parts) > 2 { prefix = parts[2] } else if authScheme != "" && parts[1] == echo.HeaderAuthorization { // backwards compatibility for JWT and KeyAuth: // * we only apply this fix to Authorization as header we use and uses prefixes like "Bearer <token-value>" etc // * previously header extractor assumed that auth-scheme/prefix had a space as suffix we need to retain that // behaviour for default values and Authorization header. prefix = authScheme if !strings.HasSuffix(prefix, " ") { prefix += " " } } extractors = append(extractors, valuesFromHeader(parts[1], prefix)) } } return extractors, nil } // valuesFromHeader returns a functions that extracts values from the request header. // valuePrefix is parameter to remove first part (prefix) of the extracted value. This is useful if header value has static // prefix like `Authorization: <auth-scheme> <authorisation-parameters>` where part that we want to remove is `<auth-scheme> ` // note the space at the end. In case of basic authentication `Authorization: Basic <credentials>` prefix we want to remove // is `Basic `. In case of JWT tokens `Authorization: Bearer <token>` prefix is `Bearer `. // If prefix is left empty the whole value is returned. func valuesFromHeader(header string, valuePrefix string) ValuesExtractor { prefixLen := len(valuePrefix) // standard library parses http.Request header keys in canonical form but we may provide something else so fix this header = textproto.CanonicalMIMEHeaderKey(header) return func(c echo.Context) ([]string, error) { values := c.Request().Header.Values(header) if len(values) == 0 { return nil, errHeaderExtractorValueMissing } result := make([]string, 0) for i, value := range values { if prefixLen == 0 { result = append(result, value) if i >= extractorLimit-1 { break } continue } if len(value) > prefixLen && strings.EqualFold(value[:prefixLen], valuePrefix) { result = append(result, value[prefixLen:]) if i >= extractorLimit-1 { break } } } if len(result) == 0 { if prefixLen > 0 { return nil, errHeaderExtractorValueInvalid } return nil, errHeaderExtractorValueMissing } return result, nil } } // valuesFromQuery returns a function that extracts values from the query string. func valuesFromQuery(param string) ValuesExtractor { return func(c echo.Context) ([]string, error) { result := c.QueryParams()[param] if len(result) == 0 { return nil, errQueryExtractorValueMissing } else if len(result) > extractorLimit-1 { result = result[:extractorLimit] } return result, nil } } // valuesFromParam returns a function that extracts values from the url param string. func valuesFromParam(param string) ValuesExtractor { return func(c echo.Context) ([]string, error) { result := make([]string, 0) paramVales := c.ParamValues() for i, p := range c.ParamNames() { if param == p { result = append(result, paramVales[i]) if i >= extractorLimit-1 { break } } } if len(result) == 0 { return nil, errParamExtractorValueMissing } return result, nil } } // valuesFromCookie returns a function that extracts values from the named cookie. func valuesFromCookie(name string) ValuesExtractor { return func(c echo.Context) ([]string, error) { cookies := c.Cookies() if len(cookies) == 0 { return nil, errCookieExtractorValueMissing } result := make([]string, 0) for i, cookie := range cookies { if name == cookie.Name { result = append(result, cookie.Value) if i >= extractorLimit-1 { break } } } if len(result) == 0 { return nil, errCookieExtractorValueMissing } return result, nil } } // valuesFromForm returns a function that extracts values from the form field. func valuesFromForm(name string) ValuesExtractor { return func(c echo.Context) ([]string, error) { if c.Request().Form == nil { _ = c.Request().ParseMultipartForm(32 << 20) // same what `c.Request().FormValue(name)` does } values := c.Request().Form[name] if len(values) == 0 { return nil, errFormExtractorValueMissing } if len(values) > extractorLimit-1 { values = values[:extractorLimit] } result := append([]string{}, values...) return result, nil } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/redirect.go
middleware/redirect.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "net/http" "strings" "github.com/labstack/echo/v4" ) // RedirectConfig defines the config for Redirect middleware. type RedirectConfig struct { // Skipper defines a function to skip middleware. Skipper // Status code to be used when redirecting the request. // Optional. Default value http.StatusMovedPermanently. Code int `yaml:"code"` } // redirectLogic represents a function that given a scheme, host and uri // can both: 1) determine if redirect is needed (will set ok accordingly) and // 2) return the appropriate redirect url. type redirectLogic func(scheme, host, uri string) (ok bool, url string) const www = "www." // DefaultRedirectConfig is the default Redirect middleware config. var DefaultRedirectConfig = RedirectConfig{ Skipper: DefaultSkipper, Code: http.StatusMovedPermanently, } // HTTPSRedirect redirects http requests to https. // For example, http://labstack.com will be redirect to https://labstack.com. // // Usage `Echo#Pre(HTTPSRedirect())` func HTTPSRedirect() echo.MiddlewareFunc { return HTTPSRedirectWithConfig(DefaultRedirectConfig) } // HTTPSRedirectWithConfig returns an HTTPSRedirect middleware with config. // See `HTTPSRedirect()`. func HTTPSRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc { return redirect(config, func(scheme, host, uri string) (bool, string) { if scheme != "https" { return true, "https://" + host + uri } return false, "" }) } // HTTPSWWWRedirect redirects http requests to https www. // For example, http://labstack.com will be redirect to https://www.labstack.com. // // Usage `Echo#Pre(HTTPSWWWRedirect())` func HTTPSWWWRedirect() echo.MiddlewareFunc { return HTTPSWWWRedirectWithConfig(DefaultRedirectConfig) } // HTTPSWWWRedirectWithConfig returns an HTTPSRedirect middleware with config. // See `HTTPSWWWRedirect()`. func HTTPSWWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc { return redirect(config, func(scheme, host, uri string) (bool, string) { if scheme != "https" && !strings.HasPrefix(host, www) { return true, "https://www." + host + uri } return false, "" }) } // HTTPSNonWWWRedirect redirects http requests to https non www. // For example, http://www.labstack.com will be redirect to https://labstack.com. // // Usage `Echo#Pre(HTTPSNonWWWRedirect())` func HTTPSNonWWWRedirect() echo.MiddlewareFunc { return HTTPSNonWWWRedirectWithConfig(DefaultRedirectConfig) } // HTTPSNonWWWRedirectWithConfig returns an HTTPSRedirect middleware with config. // See `HTTPSNonWWWRedirect()`. func HTTPSNonWWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc { return redirect(config, func(scheme, host, uri string) (ok bool, url string) { if scheme != "https" { host = strings.TrimPrefix(host, www) return true, "https://" + host + uri } return false, "" }) } // WWWRedirect redirects non www requests to www. // For example, http://labstack.com will be redirect to http://www.labstack.com. // // Usage `Echo#Pre(WWWRedirect())` func WWWRedirect() echo.MiddlewareFunc { return WWWRedirectWithConfig(DefaultRedirectConfig) } // WWWRedirectWithConfig returns an HTTPSRedirect middleware with config. // See `WWWRedirect()`. func WWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc { return redirect(config, func(scheme, host, uri string) (bool, string) { if !strings.HasPrefix(host, www) { return true, scheme + "://www." + host + uri } return false, "" }) } // NonWWWRedirect redirects www requests to non www. // For example, http://www.labstack.com will be redirect to http://labstack.com. // // Usage `Echo#Pre(NonWWWRedirect())` func NonWWWRedirect() echo.MiddlewareFunc { return NonWWWRedirectWithConfig(DefaultRedirectConfig) } // NonWWWRedirectWithConfig returns an HTTPSRedirect middleware with config. // See `NonWWWRedirect()`. func NonWWWRedirectWithConfig(config RedirectConfig) echo.MiddlewareFunc { return redirect(config, func(scheme, host, uri string) (bool, string) { if strings.HasPrefix(host, www) { return true, scheme + "://" + host[4:] + uri } return false, "" }) } func redirect(config RedirectConfig, cb redirectLogic) echo.MiddlewareFunc { if config.Skipper == nil { config.Skipper = DefaultRedirectConfig.Skipper } if config.Code == 0 { config.Code = DefaultRedirectConfig.Code } return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { if config.Skipper(c) { return next(c) } req, scheme := c.Request(), c.Scheme() host := req.Host if ok, url := cb(scheme, host, req.RequestURI); ok { return c.Redirect(config.Code, url) } return next(c) } } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/static_windows.go
middleware/static_windows.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "os" ) // We ignore these errors as there could be handler that matches request path. // // As of Go 1.20 filepath.Clean has different behaviour on OS related filesystems so we need to use path.Clean // on Windows which has some caveats. The Open methods might return different errors than earlier versions and // as of 1.20 path checks are more strict on the provided path and considers [UNC](https://en.wikipedia.org/wiki/Path_(computing)#UNC) // paths with missing host etc parts as invalid. Previously it would result you `fs.ErrNotExist`. // // For 1.20@Windows we need to treat those errors the same as `fs.ErrNotExists` so we can continue handling // errors in the middleware/handler chain. Otherwise we might end up with status 500 instead of finding a route // or return 404 not found. func isIgnorableOpenFileError(err error) bool { if os.IsNotExist(err) { return true } errTxt := err.Error() return errTxt == "http: invalid or unsafe file path" || errTxt == "invalid path" }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/cors_test.go
middleware/cors_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "errors" "net/http" "net/http/httptest" "testing" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func TestCORS(t *testing.T) { var testCases = []struct { name string givenMW echo.MiddlewareFunc whenMethod string whenHeaders map[string]string expectHeaders map[string]string notExpectHeaders map[string]string }{ { name: "ok, wildcard origin", whenHeaders: map[string]string{echo.HeaderOrigin: "localhost"}, expectHeaders: map[string]string{echo.HeaderAccessControlAllowOrigin: "*"}, }, { name: "ok, wildcard AllowedOrigin with no Origin header in request", notExpectHeaders: map[string]string{echo.HeaderAccessControlAllowOrigin: ""}, }, { name: "ok, invalid pattern is ignored", givenMW: CORSWithConfig(CORSConfig{ AllowOrigins: []string{ "\xff", // Invalid UTF-8 makes regexp.Compile to error "*.example.com", }, }), whenMethod: http.MethodOptions, whenHeaders: map[string]string{echo.HeaderOrigin: "http://aaa.example.com"}, expectHeaders: map[string]string{echo.HeaderAccessControlAllowOrigin: "http://aaa.example.com"}, }, { name: "ok, specific AllowOrigins and AllowCredentials", givenMW: CORSWithConfig(CORSConfig{ AllowOrigins: []string{"localhost"}, AllowCredentials: true, MaxAge: 3600, }), whenHeaders: map[string]string{echo.HeaderOrigin: "localhost"}, expectHeaders: map[string]string{ echo.HeaderAccessControlAllowOrigin: "localhost", echo.HeaderAccessControlAllowCredentials: "true", }, }, { name: "ok, preflight request with matching origin for `AllowOrigins`", givenMW: CORSWithConfig(CORSConfig{ AllowOrigins: []string{"localhost"}, AllowCredentials: true, MaxAge: 3600, }), whenMethod: http.MethodOptions, whenHeaders: map[string]string{ echo.HeaderOrigin: "localhost", echo.HeaderContentType: echo.MIMEApplicationJSON, }, expectHeaders: map[string]string{ echo.HeaderAccessControlAllowOrigin: "localhost", echo.HeaderAccessControlAllowMethods: "GET,HEAD,PUT,PATCH,POST,DELETE", echo.HeaderAccessControlAllowCredentials: "true", echo.HeaderAccessControlMaxAge: "3600", }, }, { name: "ok, preflight request when `Access-Control-Max-Age` is set", givenMW: CORSWithConfig(CORSConfig{ AllowOrigins: []string{"localhost"}, AllowCredentials: true, MaxAge: 1, }), whenMethod: http.MethodOptions, whenHeaders: map[string]string{ echo.HeaderOrigin: "localhost", echo.HeaderContentType: echo.MIMEApplicationJSON, }, expectHeaders: map[string]string{ echo.HeaderAccessControlMaxAge: "1", }, }, { name: "ok, preflight request when `Access-Control-Max-Age` is set to 0 - not to cache response", givenMW: CORSWithConfig(CORSConfig{ AllowOrigins: []string{"localhost"}, AllowCredentials: true, MaxAge: -1, // forces `Access-Control-Max-Age: 0` }), whenMethod: http.MethodOptions, whenHeaders: map[string]string{ echo.HeaderOrigin: "localhost", echo.HeaderContentType: echo.MIMEApplicationJSON, }, expectHeaders: map[string]string{ echo.HeaderAccessControlMaxAge: "0", }, }, { name: "ok, CORS check are skipped", givenMW: CORSWithConfig(CORSConfig{ AllowOrigins: []string{"localhost"}, AllowCredentials: true, Skipper: func(c echo.Context) bool { return true }, }), whenMethod: http.MethodOptions, whenHeaders: map[string]string{ echo.HeaderOrigin: "localhost", echo.HeaderContentType: echo.MIMEApplicationJSON, }, notExpectHeaders: map[string]string{ echo.HeaderAccessControlAllowOrigin: "localhost", echo.HeaderAccessControlAllowMethods: "GET,HEAD,PUT,PATCH,POST,DELETE", echo.HeaderAccessControlAllowCredentials: "true", echo.HeaderAccessControlMaxAge: "3600", }, }, { name: "ok, preflight request with wildcard `AllowOrigins` and `AllowCredentials` true", givenMW: CORSWithConfig(CORSConfig{ AllowOrigins: []string{"*"}, AllowCredentials: true, MaxAge: 3600, }), whenMethod: http.MethodOptions, whenHeaders: map[string]string{ echo.HeaderOrigin: "localhost", echo.HeaderContentType: echo.MIMEApplicationJSON, }, expectHeaders: map[string]string{ echo.HeaderAccessControlAllowOrigin: "*", // Note: browsers will ignore and complain about responses having `*` echo.HeaderAccessControlAllowMethods: "GET,HEAD,PUT,PATCH,POST,DELETE", echo.HeaderAccessControlAllowCredentials: "true", echo.HeaderAccessControlMaxAge: "3600", }, }, { name: "ok, preflight request with wildcard `AllowOrigins` and `AllowCredentials` false", givenMW: CORSWithConfig(CORSConfig{ AllowOrigins: []string{"*"}, AllowCredentials: false, // important for this testcase MaxAge: 3600, }), whenMethod: http.MethodOptions, whenHeaders: map[string]string{ echo.HeaderOrigin: "localhost", echo.HeaderContentType: echo.MIMEApplicationJSON, }, expectHeaders: map[string]string{ echo.HeaderAccessControlAllowOrigin: "*", echo.HeaderAccessControlAllowMethods: "GET,HEAD,PUT,PATCH,POST,DELETE", echo.HeaderAccessControlMaxAge: "3600", }, notExpectHeaders: map[string]string{ echo.HeaderAccessControlAllowCredentials: "", }, }, { name: "ok, INSECURE preflight request with wildcard `AllowOrigins` and `AllowCredentials` true", givenMW: CORSWithConfig(CORSConfig{ AllowOrigins: []string{"*"}, AllowCredentials: true, UnsafeWildcardOriginWithAllowCredentials: true, // important for this testcase MaxAge: 3600, }), whenMethod: http.MethodOptions, whenHeaders: map[string]string{ echo.HeaderOrigin: "localhost", echo.HeaderContentType: echo.MIMEApplicationJSON, }, expectHeaders: map[string]string{ echo.HeaderAccessControlAllowOrigin: "localhost", // This could end up as cross-origin attack echo.HeaderAccessControlAllowMethods: "GET,HEAD,PUT,PATCH,POST,DELETE", echo.HeaderAccessControlAllowCredentials: "true", echo.HeaderAccessControlMaxAge: "3600", }, }, { name: "ok, preflight request with Access-Control-Request-Headers", givenMW: CORSWithConfig(CORSConfig{ AllowOrigins: []string{"*"}, }), whenMethod: http.MethodOptions, whenHeaders: map[string]string{ echo.HeaderOrigin: "localhost", echo.HeaderContentType: echo.MIMEApplicationJSON, echo.HeaderAccessControlRequestHeaders: "Special-Request-Header", }, expectHeaders: map[string]string{ echo.HeaderAccessControlAllowOrigin: "*", echo.HeaderAccessControlAllowHeaders: "Special-Request-Header", echo.HeaderAccessControlAllowMethods: "GET,HEAD,PUT,PATCH,POST,DELETE", }, }, { name: "ok, preflight request with `AllowOrigins` which allow all subdomains aaa with *", givenMW: CORSWithConfig(CORSConfig{ AllowOrigins: []string{"http://*.example.com"}, }), whenMethod: http.MethodOptions, whenHeaders: map[string]string{echo.HeaderOrigin: "http://aaa.example.com"}, expectHeaders: map[string]string{echo.HeaderAccessControlAllowOrigin: "http://aaa.example.com"}, }, { name: "ok, preflight request with `AllowOrigins` which allow all subdomains bbb with *", givenMW: CORSWithConfig(CORSConfig{ AllowOrigins: []string{"http://*.example.com"}, }), whenMethod: http.MethodOptions, whenHeaders: map[string]string{echo.HeaderOrigin: "http://bbb.example.com"}, expectHeaders: map[string]string{echo.HeaderAccessControlAllowOrigin: "http://bbb.example.com"}, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() mw := CORS() if tc.givenMW != nil { mw = tc.givenMW } h := mw(func(c echo.Context) error { return nil }) method := http.MethodGet if tc.whenMethod != "" { method = tc.whenMethod } req := httptest.NewRequest(method, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) for k, v := range tc.whenHeaders { req.Header.Set(k, v) } err := h(c) assert.NoError(t, err) header := rec.Header() for k, v := range tc.expectHeaders { assert.Equal(t, v, header.Get(k), "header: `%v` should be `%v`", k, v) } for k, v := range tc.notExpectHeaders { if v == "" { assert.Len(t, header.Values(k), 0, "header: `%v` should not be set", k) } else { assert.NotEqual(t, v, header.Get(k), "header: `%v` should not be `%v`", k, v) } } }) } } func Test_allowOriginScheme(t *testing.T) { tests := []struct { domain, pattern string expected bool }{ { domain: "http://example.com", pattern: "http://example.com", expected: true, }, { domain: "https://example.com", pattern: "https://example.com", expected: true, }, { domain: "http://example.com", pattern: "https://example.com", expected: false, }, { domain: "https://example.com", pattern: "http://example.com", expected: false, }, } e := echo.New() for _, tt := range tests { req := httptest.NewRequest(http.MethodOptions, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) req.Header.Set(echo.HeaderOrigin, tt.domain) cors := CORSWithConfig(CORSConfig{ AllowOrigins: []string{tt.pattern}, }) h := cors(echo.NotFoundHandler) h(c) if tt.expected { assert.Equal(t, tt.domain, rec.Header().Get(echo.HeaderAccessControlAllowOrigin)) } else { assert.NotContains(t, rec.Header(), echo.HeaderAccessControlAllowOrigin) } } } func Test_allowOriginSubdomain(t *testing.T) { tests := []struct { domain, pattern string expected bool }{ { domain: "http://aaa.example.com", pattern: "http://*.example.com", expected: true, }, { domain: "http://bbb.aaa.example.com", pattern: "http://*.example.com", expected: true, }, { domain: "http://bbb.aaa.example.com", pattern: "http://*.aaa.example.com", expected: true, }, { domain: "http://aaa.example.com:8080", pattern: "http://*.example.com:8080", expected: true, }, { domain: "http://fuga.hoge.com", pattern: "http://*.example.com", expected: false, }, { domain: "http://ccc.bbb.example.com", pattern: "http://*.aaa.example.com", expected: false, }, { domain: `http://1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890\ .1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890\ .1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890\ .1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.example.com`, pattern: "http://*.example.com", expected: false, }, { domain: `http://1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.example.com`, pattern: "http://*.example.com", expected: false, }, { domain: "http://ccc.bbb.example.com", pattern: "http://example.com", expected: false, }, { domain: "https://prod-preview--aaa.bbb.com", pattern: "https://*--aaa.bbb.com", expected: true, }, { domain: "http://ccc.bbb.example.com", pattern: "http://*.example.com", expected: true, }, { domain: "http://ccc.bbb.example.com", pattern: "http://foo.[a-z]*.example.com", expected: false, }, } e := echo.New() for _, tt := range tests { req := httptest.NewRequest(http.MethodOptions, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) req.Header.Set(echo.HeaderOrigin, tt.domain) cors := CORSWithConfig(CORSConfig{ AllowOrigins: []string{tt.pattern}, }) h := cors(echo.NotFoundHandler) h(c) if tt.expected { assert.Equal(t, tt.domain, rec.Header().Get(echo.HeaderAccessControlAllowOrigin)) } else { assert.NotContains(t, rec.Header(), echo.HeaderAccessControlAllowOrigin) } } } func TestCORSWithConfig_AllowMethods(t *testing.T) { var testCases = []struct { name string allowOrigins []string allowContextKey string whenOrigin string whenAllowMethods []string expectAllow string expectAccessControlAllowMethods string }{ { name: "custom AllowMethods, preflight, no origin, sets only allow header from context key", allowContextKey: "OPTIONS, GET", whenAllowMethods: []string{http.MethodGet, http.MethodHead}, whenOrigin: "", expectAllow: "OPTIONS, GET", }, { name: "default AllowMethods, preflight, no origin, no allow header in context key and in response", allowContextKey: "", whenAllowMethods: nil, whenOrigin: "", expectAllow: "", }, { name: "custom AllowMethods, preflight, existing origin, sets both headers different values", allowContextKey: "OPTIONS, GET", whenAllowMethods: []string{http.MethodGet, http.MethodHead}, whenOrigin: "http://google.com", expectAllow: "OPTIONS, GET", expectAccessControlAllowMethods: "GET,HEAD", }, { name: "default AllowMethods, preflight, existing origin, sets both headers", allowContextKey: "OPTIONS, GET", whenAllowMethods: nil, whenOrigin: "http://google.com", expectAllow: "OPTIONS, GET", expectAccessControlAllowMethods: "OPTIONS, GET", }, { name: "default AllowMethods, preflight, existing origin, no allows, sets only CORS allow methods", allowContextKey: "", whenAllowMethods: nil, whenOrigin: "http://google.com", expectAllow: "", expectAccessControlAllowMethods: "GET,HEAD,PUT,PATCH,POST,DELETE", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() e.GET("/test", func(c echo.Context) error { return c.String(http.StatusOK, "OK") }) cors := CORSWithConfig(CORSConfig{ AllowOrigins: tc.allowOrigins, AllowMethods: tc.whenAllowMethods, }) req := httptest.NewRequest(http.MethodOptions, "/test", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) req.Header.Set(echo.HeaderOrigin, tc.whenOrigin) if tc.allowContextKey != "" { c.Set(echo.ContextKeyHeaderAllow, tc.allowContextKey) } h := cors(echo.NotFoundHandler) h(c) assert.Equal(t, tc.expectAllow, rec.Header().Get(echo.HeaderAllow)) assert.Equal(t, tc.expectAccessControlAllowMethods, rec.Header().Get(echo.HeaderAccessControlAllowMethods)) }) } } func TestCorsHeaders(t *testing.T) { tests := []struct { name string originDomain string method string allowedOrigin string expected bool expectStatus int expectAllowHeader string }{ { name: "non-preflight request, allow any origin, missing origin header = no CORS logic done", originDomain: "", allowedOrigin: "*", method: http.MethodGet, expected: false, expectStatus: http.StatusOK, }, { name: "non-preflight request, allow any origin, specific origin domain", originDomain: "http://example.com", allowedOrigin: "*", method: http.MethodGet, expected: true, expectStatus: http.StatusOK, }, { name: "non-preflight request, allow specific origin, missing origin header = no CORS logic done", originDomain: "", // Request does not have Origin header allowedOrigin: "http://example.com", method: http.MethodGet, expected: false, expectStatus: http.StatusOK, }, { name: "non-preflight request, allow specific origin, different origin header = CORS logic failure", originDomain: "http://bar.com", allowedOrigin: "http://example.com", method: http.MethodGet, expected: false, expectStatus: http.StatusOK, }, { name: "non-preflight request, allow specific origin, matching origin header = CORS logic done", originDomain: "http://example.com", allowedOrigin: "http://example.com", method: http.MethodGet, expected: true, expectStatus: http.StatusOK, }, { name: "preflight, allow any origin, missing origin header = no CORS logic done", originDomain: "", // Request does not have Origin header allowedOrigin: "*", method: http.MethodOptions, expected: false, expectStatus: http.StatusNoContent, expectAllowHeader: "OPTIONS, GET, POST", }, { name: "preflight, allow any origin, existing origin header = CORS logic done", originDomain: "http://example.com", allowedOrigin: "*", method: http.MethodOptions, expected: true, expectStatus: http.StatusNoContent, expectAllowHeader: "OPTIONS, GET, POST", }, { name: "preflight, allow any origin, missing origin header = no CORS logic done", originDomain: "", // Request does not have Origin header allowedOrigin: "http://example.com", method: http.MethodOptions, expected: false, expectStatus: http.StatusNoContent, expectAllowHeader: "OPTIONS, GET, POST", }, { name: "preflight, allow specific origin, different origin header = no CORS logic done", originDomain: "http://bar.com", allowedOrigin: "http://example.com", method: http.MethodOptions, expected: false, expectStatus: http.StatusNoContent, expectAllowHeader: "OPTIONS, GET, POST", }, { name: "preflight, allow specific origin, matching origin header = CORS logic done", originDomain: "http://example.com", allowedOrigin: "http://example.com", method: http.MethodOptions, expected: true, expectStatus: http.StatusNoContent, expectAllowHeader: "OPTIONS, GET, POST", }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { e := echo.New() e.Use(CORSWithConfig(CORSConfig{ AllowOrigins: []string{tc.allowedOrigin}, //AllowCredentials: true, //MaxAge: 3600, })) e.GET("/", func(c echo.Context) error { return c.String(http.StatusOK, "OK") }) e.POST("/", func(c echo.Context) error { return c.String(http.StatusCreated, "OK") }) req := httptest.NewRequest(tc.method, "/", nil) rec := httptest.NewRecorder() if tc.originDomain != "" { req.Header.Set(echo.HeaderOrigin, tc.originDomain) } // we run through whole Echo handler chain to see how CORS works with Router OPTIONS handler e.ServeHTTP(rec, req) assert.Equal(t, echo.HeaderOrigin, rec.Header().Get(echo.HeaderVary)) assert.Equal(t, tc.expectAllowHeader, rec.Header().Get(echo.HeaderAllow)) assert.Equal(t, tc.expectStatus, rec.Code) expectedAllowOrigin := "" if tc.allowedOrigin == "*" { expectedAllowOrigin = "*" } else { expectedAllowOrigin = tc.originDomain } switch { case tc.expected && tc.method == http.MethodOptions: assert.Contains(t, rec.Header(), echo.HeaderAccessControlAllowMethods) assert.Equal(t, expectedAllowOrigin, rec.Header().Get(echo.HeaderAccessControlAllowOrigin)) assert.Equal(t, 3, len(rec.Header()[echo.HeaderVary])) case tc.expected && tc.method == http.MethodGet: assert.Equal(t, expectedAllowOrigin, rec.Header().Get(echo.HeaderAccessControlAllowOrigin)) assert.Equal(t, 1, len(rec.Header()[echo.HeaderVary])) // Vary: Origin default: assert.NotContains(t, rec.Header(), echo.HeaderAccessControlAllowOrigin) assert.Equal(t, 1, len(rec.Header()[echo.HeaderVary])) // Vary: Origin } }) } } func Test_allowOriginFunc(t *testing.T) { returnTrue := func(origin string) (bool, error) { return true, nil } returnFalse := func(origin string) (bool, error) { return false, nil } returnError := func(origin string) (bool, error) { return true, errors.New("this is a test error") } allowOriginFuncs := []func(origin string) (bool, error){ returnTrue, returnFalse, returnError, } const origin = "http://example.com" e := echo.New() for _, allowOriginFunc := range allowOriginFuncs { req := httptest.NewRequest(http.MethodOptions, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) req.Header.Set(echo.HeaderOrigin, origin) cors := CORSWithConfig(CORSConfig{ AllowOriginFunc: allowOriginFunc, }) h := cors(echo.NotFoundHandler) err := h(c) expected, expectedErr := allowOriginFunc(origin) if expectedErr != nil { assert.Equal(t, expectedErr, err) assert.Equal(t, "", rec.Header().Get(echo.HeaderAccessControlAllowOrigin)) continue } if expected { assert.Equal(t, origin, rec.Header().Get(echo.HeaderAccessControlAllowOrigin)) } else { assert.Equal(t, "", rec.Header().Get(echo.HeaderAccessControlAllowOrigin)) } } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/basic_auth.go
middleware/basic_auth.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "encoding/base64" "net/http" "strconv" "strings" "github.com/labstack/echo/v4" ) // BasicAuthConfig defines the config for BasicAuth middleware. type BasicAuthConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // Validator is a function to validate BasicAuth credentials. // Required. Validator BasicAuthValidator // Realm is a string to define realm attribute of BasicAuth. // Default value "Restricted". Realm string } // BasicAuthValidator defines a function to validate BasicAuth credentials. // The function should return a boolean indicating whether the credentials are valid, // and an error if any error occurs during the validation process. type BasicAuthValidator func(string, string, echo.Context) (bool, error) const ( basic = "basic" defaultRealm = "Restricted" ) // DefaultBasicAuthConfig is the default BasicAuth middleware config. var DefaultBasicAuthConfig = BasicAuthConfig{ Skipper: DefaultSkipper, Realm: defaultRealm, } // BasicAuth returns an BasicAuth middleware. // // For valid credentials it calls the next handler. // For missing or invalid credentials, it sends "401 - Unauthorized" response. func BasicAuth(fn BasicAuthValidator) echo.MiddlewareFunc { c := DefaultBasicAuthConfig c.Validator = fn return BasicAuthWithConfig(c) } // BasicAuthWithConfig returns an BasicAuth middleware with config. // See `BasicAuth()`. func BasicAuthWithConfig(config BasicAuthConfig) echo.MiddlewareFunc { // Defaults if config.Validator == nil { panic("echo: basic-auth middleware requires a validator function") } if config.Skipper == nil { config.Skipper = DefaultBasicAuthConfig.Skipper } if config.Realm == "" { config.Realm = defaultRealm } // Pre-compute the quoted realm for WWW-Authenticate header (RFC 7617) quotedRealm := strconv.Quote(config.Realm) return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { if config.Skipper(c) { return next(c) } auth := c.Request().Header.Get(echo.HeaderAuthorization) l := len(basic) if len(auth) > l+1 && strings.EqualFold(auth[:l], basic) { // Invalid base64 shouldn't be treated as error // instead should be treated as invalid client input b, err := base64.StdEncoding.DecodeString(auth[l+1:]) if err != nil { return echo.NewHTTPError(http.StatusBadRequest).SetInternal(err) } cred := string(b) user, pass, ok := strings.Cut(cred, ":") if ok { // Verify credentials valid, err := config.Validator(user, pass, c) if err != nil { return err } else if valid { return next(c) } } } // Need to return `401` for browsers to pop-up login box. // Realm is case-insensitive, so we can use "basic" directly. See RFC 7617. c.Response().Header().Set(echo.HeaderWWWAuthenticate, basic+" realm="+quotedRealm) return echo.ErrUnauthorized } } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/body_limit_test.go
middleware/body_limit_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "bytes" "io" "net/http" "net/http/httptest" "testing" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func TestBodyLimit(t *testing.T) { e := echo.New() hw := []byte("Hello, World!") req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(hw)) rec := httptest.NewRecorder() c := e.NewContext(req, rec) h := func(c echo.Context) error { body, err := io.ReadAll(c.Request().Body) if err != nil { return err } return c.String(http.StatusOK, string(body)) } // Based on content length (within limit) if assert.NoError(t, BodyLimit("2M")(h)(c)) { assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, hw, rec.Body.Bytes()) } // Based on content length (overlimit) he := BodyLimit("2B")(h)(c).(*echo.HTTPError) assert.Equal(t, http.StatusRequestEntityTooLarge, he.Code) // Based on content read (within limit) req = httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(hw)) req.ContentLength = -1 rec = httptest.NewRecorder() c = e.NewContext(req, rec) if assert.NoError(t, BodyLimit("2M")(h)(c)) { assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, "Hello, World!", rec.Body.String()) } // Based on content read (overlimit) req = httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(hw)) req.ContentLength = -1 rec = httptest.NewRecorder() c = e.NewContext(req, rec) he = BodyLimit("2B")(h)(c).(*echo.HTTPError) assert.Equal(t, http.StatusRequestEntityTooLarge, he.Code) } func TestBodyLimitReader(t *testing.T) { hw := []byte("Hello, World!") config := BodyLimitConfig{ Skipper: DefaultSkipper, Limit: "2B", limit: 2, } reader := &limitedReader{ BodyLimitConfig: config, reader: io.NopCloser(bytes.NewReader(hw)), } // read all should return ErrStatusRequestEntityTooLarge _, err := io.ReadAll(reader) he := err.(*echo.HTTPError) assert.Equal(t, http.StatusRequestEntityTooLarge, he.Code) // reset reader and read two bytes must succeed bt := make([]byte, 2) reader.Reset(io.NopCloser(bytes.NewReader(hw))) n, err := reader.Read(bt) assert.Equal(t, 2, n) assert.Equal(t, nil, err) } func TestBodyLimitWithConfig_Skipper(t *testing.T) { e := echo.New() h := func(c echo.Context) error { body, err := io.ReadAll(c.Request().Body) if err != nil { return err } return c.String(http.StatusOK, string(body)) } mw := BodyLimitWithConfig(BodyLimitConfig{ Skipper: func(c echo.Context) bool { return true }, Limit: "2B", // if not skipped this limit would make request to fail limit check }) hw := []byte("Hello, World!") req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(hw)) rec := httptest.NewRecorder() c := e.NewContext(req, rec) err := mw(h)(c) assert.NoError(t, err) assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, hw, rec.Body.Bytes()) } func TestBodyLimitWithConfig(t *testing.T) { var testCases = []struct { name string givenLimit string whenBody []byte expectBody []byte expectError string }{ { name: "ok, body is less than limit", givenLimit: "10B", whenBody: []byte("123456789"), expectBody: []byte("123456789"), expectError: "", }, { name: "nok, body is more than limit", givenLimit: "9B", whenBody: []byte("1234567890"), expectBody: []byte(nil), expectError: "code=413, message=Request Entity Too Large", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() h := func(c echo.Context) error { body, err := io.ReadAll(c.Request().Body) if err != nil { return err } return c.String(http.StatusOK, string(body)) } mw := BodyLimitWithConfig(BodyLimitConfig{ Limit: tc.givenLimit, }) req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(tc.whenBody)) rec := httptest.NewRecorder() c := e.NewContext(req, rec) err := mw(h)(c) if tc.expectError != "" { assert.EqualError(t, err, tc.expectError) } else { assert.NoError(t, err) } // not testing status as middlewares return error instead of committing it and OK cases are anyway 200 assert.Equal(t, tc.expectBody, rec.Body.Bytes()) }) } } func TestBodyLimit_panicOnInvalidLimit(t *testing.T) { assert.PanicsWithError( t, "echo: invalid body-limit=", func() { BodyLimit("") }, ) }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/key_auth.go
middleware/key_auth.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "errors" "github.com/labstack/echo/v4" "net/http" ) // KeyAuthConfig defines the config for KeyAuth middleware. type KeyAuthConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // KeyLookup is a string in the form of "<source>:<name>" or "<source>:<name>,<source>:<name>" that is used // to extract key from the request. // Optional. Default value "header:Authorization". // Possible values: // - "header:<name>" or "header:<name>:<cut-prefix>" // `<cut-prefix>` is argument value to cut/trim prefix of the extracted value. This is useful if header // value has static prefix like `Authorization: <auth-scheme> <authorisation-parameters>` where part that we // want to cut is `<auth-scheme> ` note the space at the end. // In case of basic authentication `Authorization: Basic <credentials>` prefix we want to remove is `Basic `. // - "query:<name>" // - "form:<name>" // - "cookie:<name>" // Multiple sources example: // - "header:Authorization,header:X-Api-Key" KeyLookup string // AuthScheme to be used in the Authorization header. // Optional. Default value "Bearer". AuthScheme string // Validator is a function to validate key. // Required. Validator KeyAuthValidator // ErrorHandler defines a function which is executed for an invalid key. // It may be used to define a custom error. ErrorHandler KeyAuthErrorHandler // ContinueOnIgnoredError allows the next middleware/handler to be called when ErrorHandler decides to // ignore the error (by returning `nil`). // This is useful when parts of your site/api allow public access and some authorized routes provide extra functionality. // In that case you can use ErrorHandler to set a default public key auth value in the request context // and continue. Some logic down the remaining execution chain needs to check that (public) key auth value then. ContinueOnIgnoredError bool } // KeyAuthValidator defines a function to validate KeyAuth credentials. type KeyAuthValidator func(auth string, c echo.Context) (bool, error) // KeyAuthErrorHandler defines a function which is executed for an invalid key. type KeyAuthErrorHandler func(err error, c echo.Context) error // ErrKeyAuthMissing is error type when KeyAuth middleware is unable to extract value from lookups type ErrKeyAuthMissing struct { Err error } // DefaultKeyAuthConfig is the default KeyAuth middleware config. var DefaultKeyAuthConfig = KeyAuthConfig{ Skipper: DefaultSkipper, KeyLookup: "header:" + echo.HeaderAuthorization, AuthScheme: "Bearer", } // Error returns errors text func (e *ErrKeyAuthMissing) Error() string { return e.Err.Error() } // Unwrap unwraps error func (e *ErrKeyAuthMissing) Unwrap() error { return e.Err } // KeyAuth returns an KeyAuth middleware. // // For valid key it calls the next handler. // For invalid key, it sends "401 - Unauthorized" response. // For missing key, it sends "400 - Bad Request" response. func KeyAuth(fn KeyAuthValidator) echo.MiddlewareFunc { c := DefaultKeyAuthConfig c.Validator = fn return KeyAuthWithConfig(c) } // KeyAuthWithConfig returns an KeyAuth middleware with config. // See `KeyAuth()`. func KeyAuthWithConfig(config KeyAuthConfig) echo.MiddlewareFunc { // Defaults if config.Skipper == nil { config.Skipper = DefaultKeyAuthConfig.Skipper } // Defaults if config.AuthScheme == "" { config.AuthScheme = DefaultKeyAuthConfig.AuthScheme } if config.KeyLookup == "" { config.KeyLookup = DefaultKeyAuthConfig.KeyLookup } if config.Validator == nil { panic("echo: key-auth middleware requires a validator function") } extractors, cErr := createExtractors(config.KeyLookup, config.AuthScheme) if cErr != nil { panic(cErr) } return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { if config.Skipper(c) { return next(c) } var lastExtractorErr error var lastValidatorErr error for _, extractor := range extractors { keys, err := extractor(c) if err != nil { lastExtractorErr = err continue } for _, key := range keys { valid, err := config.Validator(key, c) if err != nil { lastValidatorErr = err continue } if valid { return next(c) } lastValidatorErr = errors.New("invalid key") } } // we are here only when we did not successfully extract and validate any of keys err := lastValidatorErr if err == nil { // prioritize validator errors over extracting errors // ugly part to preserve backwards compatible errors. someone could rely on them if lastExtractorErr == errQueryExtractorValueMissing { err = errors.New("missing key in the query string") } else if lastExtractorErr == errCookieExtractorValueMissing { err = errors.New("missing key in cookies") } else if lastExtractorErr == errFormExtractorValueMissing { err = errors.New("missing key in the form") } else if lastExtractorErr == errHeaderExtractorValueMissing { err = errors.New("missing key in request header") } else if lastExtractorErr == errHeaderExtractorValueInvalid { err = errors.New("invalid key in the request header") } else { err = lastExtractorErr } err = &ErrKeyAuthMissing{Err: err} } if config.ErrorHandler != nil { tmpErr := config.ErrorHandler(err, c) if config.ContinueOnIgnoredError && tmpErr == nil { return next(c) } return tmpErr } if lastValidatorErr != nil { // prioritize validator errors over extracting errors return &echo.HTTPError{ Code: http.StatusUnauthorized, Message: "Unauthorized", Internal: lastValidatorErr, } } return echo.NewHTTPError(http.StatusBadRequest, err.Error()) } } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/static_test.go
middleware/static_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "io/fs" "net/http" "net/http/httptest" "os" "strings" "testing" "testing/fstest" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func TestStatic(t *testing.T) { var testCases = []struct { name string givenConfig *StaticConfig givenAttachedToGroup string whenURL string expectContains string expectLength string expectCode int }{ { name: "ok, serve index with Echo message", whenURL: "/", expectCode: http.StatusOK, expectContains: "<title>Echo</title>", }, { name: "ok, serve file from subdirectory", whenURL: "/images/walle.png", expectCode: http.StatusOK, expectLength: "219885", }, { name: "ok, when html5 mode serve index for any static file that does not exist", givenConfig: &StaticConfig{ Root: "../_fixture", HTML5: true, }, whenURL: "/random", expectCode: http.StatusOK, expectContains: "<title>Echo</title>", }, { name: "ok, serve index as directory index listing files directory", givenConfig: &StaticConfig{ Root: "../_fixture/certs", Browse: true, }, whenURL: "/", expectCode: http.StatusOK, expectContains: "cert.pem", }, { name: "ok, serve directory index with IgnoreBase and browse", givenConfig: &StaticConfig{ Root: "../_fixture/_fixture/", // <-- last `_fixture/` is overlapping with group path and needs to be ignored IgnoreBase: true, Browse: true, }, givenAttachedToGroup: "/_fixture", whenURL: "/_fixture/", expectCode: http.StatusOK, expectContains: `<a class="file" href="README.md">README.md</a>`, }, { name: "ok, serve file with IgnoreBase", givenConfig: &StaticConfig{ Root: "../_fixture/_fixture/", // <-- last `_fixture/` is overlapping with group path and needs to be ignored IgnoreBase: true, Browse: true, }, givenAttachedToGroup: "/_fixture", whenURL: "/_fixture/README.md", expectCode: http.StatusOK, expectContains: "This directory is used for the static middleware test", }, { name: "nok, file not found", whenURL: "/none", expectCode: http.StatusNotFound, expectContains: "{\"message\":\"Not Found\"}\n", }, { name: "nok, do not allow directory traversal (backslash - windows separator)", whenURL: `/..\\middleware/basic_auth.go`, expectCode: http.StatusNotFound, expectContains: "{\"message\":\"Not Found\"}\n", }, { name: "nok,do not allow directory traversal (slash - unix separator)", whenURL: `/../middleware/basic_auth.go`, expectCode: http.StatusNotFound, expectContains: "{\"message\":\"Not Found\"}\n", }, { name: "nok, URL encoded path traversal (single encoding)", whenURL: "/%2e%2e%2fmiddleware/basic_auth.go", expectCode: http.StatusNotFound, expectContains: "{\"message\":\"Not Found\"}\n", }, { name: "nok, URL encoded path traversal (double encoding)", whenURL: "/%252e%252e%252fmiddleware/basic_auth.go", expectCode: http.StatusNotFound, expectContains: "{\"message\":\"Not Found\"}\n", }, { name: "nok, URL encoded path traversal (mixed encoding)", whenURL: "/%2e%2e/middleware/basic_auth.go", expectCode: http.StatusNotFound, expectContains: "{\"message\":\"Not Found\"}\n", }, { name: "nok, backslash URL encoded", whenURL: "/..%5c..%5cmiddleware/basic_auth.go", expectCode: http.StatusNotFound, expectContains: "{\"message\":\"Not Found\"}\n", }, //{ // Disabled: returns 404 under Windows // name: "nok, null byte injection", // whenURL: "/index.html%00.jpg", // expectCode: http.StatusInternalServerError, // expectContains: "{\"message\":\"Internal Server Error\"}\n", //}, { name: "nok, mixed backslash and forward slash traversal", whenURL: "/..\\../middleware/basic_auth.go", expectCode: http.StatusNotFound, expectContains: "{\"message\":\"Not Found\"}\n", }, { name: "nok, trailing dots (Windows edge case)", whenURL: "/../middleware/basic_auth.go...", expectCode: http.StatusNotFound, expectContains: "{\"message\":\"Not Found\"}\n", }, { name: "ok, do not serve file, when a handler took care of the request", whenURL: "/regular-handler", expectCode: http.StatusOK, expectContains: "ok", }, { name: "nok, when html5 fail if the index file does not exist", givenConfig: &StaticConfig{ Root: "../_fixture", HTML5: true, Index: "missing.html", }, whenURL: "/random", expectCode: http.StatusInternalServerError, }, { name: "ok, serve from http.FileSystem", givenConfig: &StaticConfig{ Root: "_fixture", Filesystem: http.Dir(".."), }, whenURL: "/", expectCode: http.StatusOK, expectContains: "<title>Echo</title>", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() config := StaticConfig{Root: "../_fixture"} if tc.givenConfig != nil { config = *tc.givenConfig } middlewareFunc := StaticWithConfig(config) if tc.givenAttachedToGroup != "" { // middleware is attached to group subGroup := e.Group(tc.givenAttachedToGroup, middlewareFunc) // group without http handlers (routes) does not do anything. // Request is matched against http handlers (routes) that have group middleware attached to them subGroup.GET("", echo.NotFoundHandler) subGroup.GET("/*", echo.NotFoundHandler) } else { // middleware is on root level e.Use(middlewareFunc) e.GET("/regular-handler", func(c echo.Context) error { return c.String(http.StatusOK, "ok") }) } req := httptest.NewRequest(http.MethodGet, tc.whenURL, nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, tc.expectCode, rec.Code) if tc.expectContains != "" { responseBody := rec.Body.String() assert.Contains(t, responseBody, tc.expectContains) } if tc.expectLength != "" { assert.Equal(t, rec.Header().Get(echo.HeaderContentLength), tc.expectLength) } }) } } func TestStatic_GroupWithStatic(t *testing.T) { var testCases = []struct { name string givenGroup string givenPrefix string givenRoot string whenURL string expectStatus int expectHeaderLocation string expectBodyStartsWith string }{ { name: "ok", givenPrefix: "/images", givenRoot: "../_fixture/images", whenURL: "/group/images/walle.png", expectStatus: http.StatusOK, expectBodyStartsWith: string([]byte{0x89, 0x50, 0x4e, 0x47}), }, { name: "No file", givenPrefix: "/images", givenRoot: "../_fixture/scripts", whenURL: "/group/images/bolt.png", expectStatus: http.StatusNotFound, expectBodyStartsWith: "{\"message\":\"Not Found\"}\n", }, { name: "Directory not found (no trailing slash)", givenPrefix: "/images", givenRoot: "../_fixture/images", whenURL: "/group/images/", expectStatus: http.StatusNotFound, expectBodyStartsWith: "{\"message\":\"Not Found\"}\n", }, { name: "Directory redirect", givenPrefix: "/", givenRoot: "../_fixture", whenURL: "/group/folder", expectStatus: http.StatusMovedPermanently, expectHeaderLocation: "/group/folder/", expectBodyStartsWith: "", }, { name: "Directory redirect", givenPrefix: "/", givenRoot: "../_fixture", whenURL: "/group/folder%2f..", expectStatus: http.StatusMovedPermanently, expectHeaderLocation: "/group/folder/../", expectBodyStartsWith: "", }, { name: "Prefixed directory 404 (request URL without slash)", givenGroup: "_fixture", givenPrefix: "/folder/", // trailing slash will intentionally not match "/folder" givenRoot: "../_fixture", whenURL: "/_fixture/folder", // no trailing slash expectStatus: http.StatusNotFound, expectBodyStartsWith: "{\"message\":\"Not Found\"}\n", }, { name: "Prefixed directory redirect (without slash redirect to slash)", givenGroup: "_fixture", givenPrefix: "/folder", // no trailing slash shall match /folder and /folder/* givenRoot: "../_fixture", whenURL: "/_fixture/folder", // no trailing slash expectStatus: http.StatusMovedPermanently, expectHeaderLocation: "/_fixture/folder/", expectBodyStartsWith: "", }, { name: "Directory with index.html", givenPrefix: "/", givenRoot: "../_fixture", whenURL: "/group/", expectStatus: http.StatusOK, expectBodyStartsWith: "<!doctype html>", }, { name: "Prefixed directory with index.html (prefix ending with slash)", givenPrefix: "/assets/", givenRoot: "../_fixture", whenURL: "/group/assets/", expectStatus: http.StatusOK, expectBodyStartsWith: "<!doctype html>", }, { name: "Prefixed directory with index.html (prefix ending without slash)", givenPrefix: "/assets", givenRoot: "../_fixture", whenURL: "/group/assets/", expectStatus: http.StatusOK, expectBodyStartsWith: "<!doctype html>", }, { name: "Sub-directory with index.html", givenPrefix: "/", givenRoot: "../_fixture", whenURL: "/group/folder/", expectStatus: http.StatusOK, expectBodyStartsWith: "<!doctype html>", }, { name: "do not allow directory traversal (backslash - windows separator)", givenPrefix: "/", givenRoot: "../_fixture/", whenURL: `/group/..\\middleware/basic_auth.go`, expectStatus: http.StatusNotFound, expectBodyStartsWith: "{\"message\":\"Not Found\"}\n", }, { name: "do not allow directory traversal (slash - unix separator)", givenPrefix: "/", givenRoot: "../_fixture/", whenURL: `/group/../middleware/basic_auth.go`, expectStatus: http.StatusNotFound, expectBodyStartsWith: "{\"message\":\"Not Found\"}\n", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() group := "/group" if tc.givenGroup != "" { group = tc.givenGroup } g := e.Group(group) g.Static(tc.givenPrefix, tc.givenRoot) req := httptest.NewRequest(http.MethodGet, tc.whenURL, nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, tc.expectStatus, rec.Code) body := rec.Body.String() if tc.expectBodyStartsWith != "" { assert.True(t, strings.HasPrefix(body, tc.expectBodyStartsWith)) } else { assert.Equal(t, "", body) } if tc.expectHeaderLocation != "" { assert.Equal(t, tc.expectHeaderLocation, rec.Header().Get(echo.HeaderLocation)) } else { _, ok := rec.Result().Header[echo.HeaderLocation] assert.False(t, ok) } }) } } func TestStatic_CustomFS(t *testing.T) { var testCases = []struct { name string filesystem fs.FS root string whenURL string expectContains string expectCode int }{ { name: "ok, serve index with Echo message", whenURL: "/", filesystem: os.DirFS("../_fixture"), expectCode: http.StatusOK, expectContains: "<title>Echo</title>", }, { name: "ok, serve index with Echo message", whenURL: "/_fixture/", filesystem: os.DirFS(".."), expectCode: http.StatusOK, expectContains: "<title>Echo</title>", }, { name: "ok, serve file from map fs", whenURL: "/file.txt", filesystem: fstest.MapFS{ "file.txt": &fstest.MapFile{Data: []byte("file.txt is ok")}, }, expectCode: http.StatusOK, expectContains: "file.txt is ok", }, { name: "nok, missing file in map fs", whenURL: "/file.txt", expectCode: http.StatusNotFound, filesystem: fstest.MapFS{ "file2.txt": &fstest.MapFile{Data: []byte("file2.txt is ok")}, }, }, { name: "nok, file is not a subpath of root", whenURL: `/../../secret.txt`, root: "/nested/folder", filesystem: fstest.MapFS{ "secret.txt": &fstest.MapFile{Data: []byte("this is a secret")}, }, expectCode: http.StatusNotFound, }, { name: "nok, backslash is forbidden", whenURL: `/..\..\secret.txt`, expectCode: http.StatusNotFound, root: "/nested/folder", filesystem: fstest.MapFS{ "secret.txt": &fstest.MapFile{Data: []byte("this is a secret")}, }, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() config := StaticConfig{ Root: ".", Filesystem: http.FS(tc.filesystem), } if tc.root != "" { config.Root = tc.root } middlewareFunc := StaticWithConfig(config) e.Use(middlewareFunc) req := httptest.NewRequest(http.MethodGet, tc.whenURL, nil) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, tc.expectCode, rec.Code) if tc.expectContains != "" { responseBody := rec.Body.String() assert.Contains(t, responseBody, tc.expectContains) } }) } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/logger.go
middleware/logger.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "bytes" "io" "strconv" "strings" "sync" "time" "github.com/labstack/echo/v4" "github.com/labstack/gommon/color" "github.com/valyala/fasttemplate" ) // LoggerConfig defines the config for Logger middleware. // // # Configuration Examples // // ## Basic Usage with Default Settings // // e.Use(middleware.Logger()) // // This uses the default JSON format that logs all common request/response details. // // ## Custom Simple Format // // e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ // Format: "${time_rfc3339_nano} ${status} ${method} ${uri} ${latency_human}\n", // })) // // ## JSON Format with Custom Fields // // e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ // Format: `{"timestamp":"${time_rfc3339_nano}","level":"info","remote_ip":"${remote_ip}",` + // `"method":"${method}","uri":"${uri}","status":${status},"latency":"${latency_human}",` + // `"user_agent":"${user_agent}","error":"${error}"}` + "\n", // })) // // ## Custom Time Format // // e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ // Format: "${time_custom} ${method} ${uri} ${status}\n", // CustomTimeFormat: "2006-01-02 15:04:05", // })) // // ## Logging Headers and Parameters // // e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ // Format: `{"time":"${time_rfc3339_nano}","method":"${method}","uri":"${uri}",` + // `"status":${status},"auth":"${header:Authorization}","user":"${query:user}",` + // `"form_data":"${form:action}","session":"${cookie:session_id}"}` + "\n", // })) // // ## Custom Output (File Logging) // // file, err := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) // if err != nil { // log.Fatal(err) // } // defer file.Close() // // e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ // Output: file, // })) // // ## Custom Tag Function // // e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ // Format: `{"time":"${time_rfc3339_nano}","user_id":"${custom}","method":"${method}"}` + "\n", // CustomTagFunc: func(c echo.Context, buf *bytes.Buffer) (int, error) { // userID := getUserIDFromContext(c) // Your custom logic // return buf.WriteString(strconv.Itoa(userID)) // }, // })) // // ## Conditional Logging (Skip Certain Requests) // // e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ // Skipper: func(c echo.Context) bool { // // Skip logging for health check endpoints // return c.Request().URL.Path == "/health" || c.Request().URL.Path == "/metrics" // }, // })) // // ## Integration with External Logging Service // // logBuffer := &SyncBuffer{} // Thread-safe buffer for external service // // e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ // Format: `{"timestamp":"${time_rfc3339_nano}","service":"my-api","level":"info",` + // `"method":"${method}","uri":"${uri}","status":${status},"latency_ms":${latency},` + // `"remote_ip":"${remote_ip}","user_agent":"${user_agent}","error":"${error}"}` + "\n", // Output: logBuffer, // })) // // # Available Tags // // ## Time Tags // - time_unix: Unix timestamp (seconds) // - time_unix_milli: Unix timestamp (milliseconds) // - time_unix_micro: Unix timestamp (microseconds) // - time_unix_nano: Unix timestamp (nanoseconds) // - time_rfc3339: RFC3339 format (2006-01-02T15:04:05Z07:00) // - time_rfc3339_nano: RFC3339 with nanoseconds // - time_custom: Uses CustomTimeFormat field // // ## Request Information // - id: Request ID from X-Request-ID header // - remote_ip: Client IP address (respects proxy headers) // - uri: Full request URI with query parameters // - host: Host header value // - method: HTTP method (GET, POST, etc.) // - path: URL path without query parameters // - route: Echo route pattern (e.g., /users/:id) // - protocol: HTTP protocol version // - referer: Referer header value // - user_agent: User-Agent header value // // ## Response Information // - status: HTTP status code // - error: Error message if request failed // - latency: Request processing time in nanoseconds // - latency_human: Human-readable processing time // - bytes_in: Request body size in bytes // - bytes_out: Response body size in bytes // // ## Dynamic Tags // - header:<NAME>: Value of specific header (e.g., header:Authorization) // - query:<NAME>: Value of specific query parameter (e.g., query:user_id) // - form:<NAME>: Value of specific form field (e.g., form:username) // - cookie:<NAME>: Value of specific cookie (e.g., cookie:session_id) // - custom: Output from CustomTagFunc // // # Troubleshooting // // ## Common Issues // // 1. **Missing logs**: Check if Skipper function is filtering out requests // 2. **Invalid JSON**: Ensure CustomTagFunc outputs valid JSON content // 3. **Performance issues**: Consider using a buffered writer for high-traffic applications // 4. **File permission errors**: Ensure write permissions when logging to files // // ## Performance Tips // // - Use time_unix formats for better performance than time_rfc3339 // - Minimize the number of dynamic tags (header:, query:, form:, cookie:) // - Use Skipper to exclude high-frequency, low-value requests (health checks, etc.) // - Consider async logging for very high-traffic applications type LoggerConfig struct { // Skipper defines a function to skip middleware. // Use this to exclude certain requests from logging (e.g., health checks). // // Example: // Skipper: func(c echo.Context) bool { // return c.Request().URL.Path == "/health" // }, Skipper Skipper // Format defines the logging format using template tags. // Tags are enclosed in ${} and replaced with actual values. // See the detailed tag documentation above for all available options. // // Default: JSON format with common fields // Example: "${time_rfc3339_nano} ${status} ${method} ${uri} ${latency_human}\n" Format string `yaml:"format"` // CustomTimeFormat specifies the time format used by ${time_custom} tag. // Uses Go's reference time: Mon Jan 2 15:04:05 MST 2006 // // Default: "2006-01-02 15:04:05.00000" // Example: "2006-01-02 15:04:05" or "15:04:05.000" CustomTimeFormat string `yaml:"custom_time_format"` // CustomTagFunc is called when ${custom} tag is encountered. // Use this to add application-specific information to logs. // The function should write valid content for your log format. // // Example: // CustomTagFunc: func(c echo.Context, buf *bytes.Buffer) (int, error) { // userID := getUserFromContext(c) // return buf.WriteString(`"user_id":"` + userID + `"`) // }, CustomTagFunc func(c echo.Context, buf *bytes.Buffer) (int, error) // Output specifies where logs are written. // Can be any io.Writer: files, buffers, network connections, etc. // // Default: os.Stdout // Example: Custom file, syslog, or external logging service Output io.Writer template *fasttemplate.Template colorer *color.Color pool *sync.Pool timeNow func() time.Time } // DefaultLoggerConfig is the default Logger middleware config. var DefaultLoggerConfig = LoggerConfig{ Skipper: DefaultSkipper, Format: `{"time":"${time_rfc3339_nano}","id":"${id}","remote_ip":"${remote_ip}",` + `"host":"${host}","method":"${method}","uri":"${uri}","user_agent":"${user_agent}",` + `"status":${status},"error":"${error}","latency":${latency},"latency_human":"${latency_human}"` + `,"bytes_in":${bytes_in},"bytes_out":${bytes_out}}` + "\n", CustomTimeFormat: "2006-01-02 15:04:05.00000", colorer: color.New(), timeNow: time.Now, } // Logger returns a middleware that logs HTTP requests using the default configuration. // // The default format logs requests as JSON with the following fields: // - time: RFC3339 nano timestamp // - id: Request ID from X-Request-ID header // - remote_ip: Client IP address // - host: Host header // - method: HTTP method // - uri: Request URI // - user_agent: User-Agent header // - status: HTTP status code // - error: Error message (if any) // - latency: Processing time in nanoseconds // - latency_human: Human-readable processing time // - bytes_in: Request body size // - bytes_out: Response body size // // Example output: // // {"time":"2023-01-15T10:30:45.123456789Z","id":"","remote_ip":"127.0.0.1", // "host":"localhost:8080","method":"GET","uri":"/users/123","user_agent":"curl/7.81.0", // "status":200,"error":"","latency":1234567,"latency_human":"1.234567ms", // "bytes_in":0,"bytes_out":42} // // For custom configurations, use LoggerWithConfig instead. // // Deprecated: please use middleware.RequestLogger or middleware.RequestLoggerWithConfig instead. func Logger() echo.MiddlewareFunc { return LoggerWithConfig(DefaultLoggerConfig) } // LoggerWithConfig returns a Logger middleware with custom configuration. // // This function allows you to customize all aspects of request logging including: // - Log format and fields // - Output destination // - Time formatting // - Custom tags and logic // - Request filtering // // See LoggerConfig documentation for detailed configuration examples and options. // // Example: // // e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ // Format: "${time_rfc3339} ${status} ${method} ${uri} ${latency_human}\n", // Output: customLogWriter, // Skipper: func(c echo.Context) bool { // return c.Request().URL.Path == "/health" // }, // })) // // Deprecated: please use middleware.RequestLoggerWithConfig instead. func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc { // Defaults if config.Skipper == nil { config.Skipper = DefaultLoggerConfig.Skipper } if config.Format == "" { config.Format = DefaultLoggerConfig.Format } writeString := func(buf *bytes.Buffer, in string) (int, error) { return buf.WriteString(in) } if config.Format[0] == '{' { // format looks like JSON, so we need to escape invalid characters writeString = writeJSONSafeString } if config.Output == nil { config.Output = DefaultLoggerConfig.Output } timeNow := DefaultLoggerConfig.timeNow if config.timeNow != nil { timeNow = config.timeNow } config.template = fasttemplate.New(config.Format, "${", "}") config.colorer = color.New() config.colorer.SetOutput(config.Output) config.pool = &sync.Pool{ New: func() interface{} { return bytes.NewBuffer(make([]byte, 256)) }, } return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) (err error) { if config.Skipper(c) { return next(c) } req := c.Request() res := c.Response() start := time.Now() if err = next(c); err != nil { c.Error(err) } stop := time.Now() buf := config.pool.Get().(*bytes.Buffer) buf.Reset() defer config.pool.Put(buf) if _, err = config.template.ExecuteFunc(buf, func(w io.Writer, tag string) (int, error) { switch tag { case "custom": if config.CustomTagFunc == nil { return 0, nil } return config.CustomTagFunc(c, buf) case "time_unix": return buf.WriteString(strconv.FormatInt(timeNow().Unix(), 10)) case "time_unix_milli": return buf.WriteString(strconv.FormatInt(timeNow().UnixMilli(), 10)) case "time_unix_micro": return buf.WriteString(strconv.FormatInt(timeNow().UnixMicro(), 10)) case "time_unix_nano": return buf.WriteString(strconv.FormatInt(timeNow().UnixNano(), 10)) case "time_rfc3339": return buf.WriteString(timeNow().Format(time.RFC3339)) case "time_rfc3339_nano": return buf.WriteString(timeNow().Format(time.RFC3339Nano)) case "time_custom": return buf.WriteString(timeNow().Format(config.CustomTimeFormat)) case "id": id := req.Header.Get(echo.HeaderXRequestID) if id == "" { id = res.Header().Get(echo.HeaderXRequestID) } return writeString(buf, id) case "remote_ip": return writeString(buf, c.RealIP()) case "host": return writeString(buf, req.Host) case "uri": return writeString(buf, req.RequestURI) case "method": return writeString(buf, req.Method) case "path": p := req.URL.Path if p == "" { p = "/" } return writeString(buf, p) case "route": return writeString(buf, c.Path()) case "protocol": return writeString(buf, req.Proto) case "referer": return writeString(buf, req.Referer()) case "user_agent": return writeString(buf, req.UserAgent()) case "status": n := res.Status s := config.colorer.Green(n) switch { case n >= 500: s = config.colorer.Red(n) case n >= 400: s = config.colorer.Yellow(n) case n >= 300: s = config.colorer.Cyan(n) } return buf.WriteString(s) case "error": if err != nil { return writeJSONSafeString(buf, err.Error()) } case "latency": l := stop.Sub(start) return buf.WriteString(strconv.FormatInt(int64(l), 10)) case "latency_human": return buf.WriteString(stop.Sub(start).String()) case "bytes_in": cl := req.Header.Get(echo.HeaderContentLength) if cl == "" { cl = "0" } return writeString(buf, cl) case "bytes_out": return buf.WriteString(strconv.FormatInt(res.Size, 10)) default: switch { case strings.HasPrefix(tag, "header:"): return writeString(buf, c.Request().Header.Get(tag[7:])) case strings.HasPrefix(tag, "query:"): return writeString(buf, c.QueryParam(tag[6:])) case strings.HasPrefix(tag, "form:"): return writeString(buf, c.FormValue(tag[5:])) case strings.HasPrefix(tag, "cookie:"): cookie, err := c.Cookie(tag[7:]) if err == nil { return buf.Write([]byte(cookie.Value)) } } } return 0, nil }); err != nil { return } if config.Output == nil { _, err = c.Logger().Output().Write(buf.Bytes()) return } _, err = config.Output.Write(buf.Bytes()) return } } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/slash_test.go
middleware/slash_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "net/http" "net/http/httptest" "testing" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func TestAddTrailingSlashWithConfig(t *testing.T) { var testCases = []struct { whenURL string whenMethod string expectPath string expectLocation []string expectStatus int }{ { whenURL: "/add-slash", whenMethod: http.MethodGet, expectPath: "/add-slash", expectLocation: []string{`/add-slash/`}, }, { whenURL: "/add-slash?key=value", whenMethod: http.MethodGet, expectPath: "/add-slash", expectLocation: []string{`/add-slash/?key=value`}, }, { whenURL: "/", whenMethod: http.MethodConnect, expectPath: "/", expectLocation: nil, expectStatus: http.StatusOK, }, // cases for open redirect vulnerability { whenURL: "http://localhost:1323/%5Cexample.com", expectPath: `/\example.com`, expectLocation: []string{`/example.com/`}, }, { whenURL: `http://localhost:1323/\example.com`, expectPath: `/\example.com`, expectLocation: []string{`/example.com/`}, }, { whenURL: `http://localhost:1323/\\%5C////%5C\\\example.com`, expectPath: `/\\\////\\\\example.com`, expectLocation: []string{`/example.com/`}, }, { whenURL: "http://localhost:1323//example.com", expectPath: `//example.com`, expectLocation: []string{`/example.com/`}, }, { whenURL: "http://localhost:1323/%5C%5C", expectPath: `/\\`, expectLocation: []string{`/`}, }, } for _, tc := range testCases { t.Run(tc.whenURL, func(t *testing.T) { e := echo.New() mw := AddTrailingSlashWithConfig(TrailingSlashConfig{ RedirectCode: http.StatusMovedPermanently, }) h := mw(func(c echo.Context) error { return nil }) rec := httptest.NewRecorder() req := httptest.NewRequest(tc.whenMethod, tc.whenURL, nil) c := e.NewContext(req, rec) err := h(c) assert.NoError(t, err) assert.Equal(t, tc.expectPath, req.URL.Path) assert.Equal(t, tc.expectLocation, rec.Header()[echo.HeaderLocation]) if tc.expectStatus == 0 { assert.Equal(t, http.StatusMovedPermanently, rec.Code) } else { assert.Equal(t, tc.expectStatus, rec.Code) } }) } } func TestAddTrailingSlash(t *testing.T) { var testCases = []struct { whenURL string whenMethod string expectPath string expectLocation []string }{ { whenURL: "/add-slash", whenMethod: http.MethodGet, expectPath: "/add-slash/", }, { whenURL: "/add-slash?key=value", whenMethod: http.MethodGet, expectPath: "/add-slash/", }, { whenURL: "/", whenMethod: http.MethodConnect, expectPath: "/", expectLocation: nil, }, } for _, tc := range testCases { t.Run(tc.whenURL, func(t *testing.T) { e := echo.New() h := AddTrailingSlash()(func(c echo.Context) error { return nil }) rec := httptest.NewRecorder() req := httptest.NewRequest(tc.whenMethod, tc.whenURL, nil) c := e.NewContext(req, rec) err := h(c) assert.NoError(t, err) assert.Equal(t, tc.expectPath, req.URL.Path) assert.Equal(t, []string(nil), rec.Header()[echo.HeaderLocation]) assert.Equal(t, http.StatusOK, rec.Code) }) } } func TestRemoveTrailingSlashWithConfig(t *testing.T) { var testCases = []struct { whenURL string whenMethod string expectPath string expectLocation []string expectStatus int }{ { whenURL: "/remove-slash/", whenMethod: http.MethodGet, expectPath: "/remove-slash/", expectLocation: []string{`/remove-slash`}, }, { whenURL: "/remove-slash/?key=value", whenMethod: http.MethodGet, expectPath: "/remove-slash/", expectLocation: []string{`/remove-slash?key=value`}, }, { whenURL: "/", whenMethod: http.MethodConnect, expectPath: "/", expectLocation: nil, expectStatus: http.StatusOK, }, { whenURL: "http://localhost", whenMethod: http.MethodGet, expectPath: "", expectLocation: nil, expectStatus: http.StatusOK, }, // cases for open redirect vulnerability { whenURL: "http://localhost:1323/%5Cexample.com/", expectPath: `/\example.com/`, expectLocation: []string{`/example.com`}, }, { whenURL: `http://localhost:1323/\example.com/`, expectPath: `/\example.com/`, expectLocation: []string{`/example.com`}, }, { whenURL: `http://localhost:1323/\\%5C////%5C\\\example.com/`, expectPath: `/\\\////\\\\example.com/`, expectLocation: []string{`/example.com`}, }, { whenURL: "http://localhost:1323//example.com/", expectPath: `//example.com/`, expectLocation: []string{`/example.com`}, }, { whenURL: "http://localhost:1323/%5C%5C/", expectPath: `/\\/`, expectLocation: []string{`/`}, }, } for _, tc := range testCases { t.Run(tc.whenURL, func(t *testing.T) { e := echo.New() mw := RemoveTrailingSlashWithConfig(TrailingSlashConfig{ RedirectCode: http.StatusMovedPermanently, }) h := mw(func(c echo.Context) error { return nil }) rec := httptest.NewRecorder() req := httptest.NewRequest(tc.whenMethod, tc.whenURL, nil) c := e.NewContext(req, rec) err := h(c) assert.NoError(t, err) assert.Equal(t, tc.expectPath, req.URL.Path) assert.Equal(t, tc.expectLocation, rec.Header()[echo.HeaderLocation]) if tc.expectStatus == 0 { assert.Equal(t, http.StatusMovedPermanently, rec.Code) } else { assert.Equal(t, tc.expectStatus, rec.Code) } }) } } func TestRemoveTrailingSlash(t *testing.T) { var testCases = []struct { whenURL string whenMethod string expectPath string }{ { whenURL: "/remove-slash/", whenMethod: http.MethodGet, expectPath: "/remove-slash", }, { whenURL: "/remove-slash/?key=value", whenMethod: http.MethodGet, expectPath: "/remove-slash", }, { whenURL: "/", whenMethod: http.MethodConnect, expectPath: "/", }, { whenURL: "http://localhost", whenMethod: http.MethodGet, expectPath: "", }, } for _, tc := range testCases { t.Run(tc.whenURL, func(t *testing.T) { e := echo.New() h := RemoveTrailingSlash()(func(c echo.Context) error { return nil }) rec := httptest.NewRecorder() req := httptest.NewRequest(tc.whenMethod, tc.whenURL, nil) c := e.NewContext(req, rec) err := h(c) assert.NoError(t, err) assert.Equal(t, tc.expectPath, req.URL.Path) assert.Equal(t, []string(nil), rec.Header()[echo.HeaderLocation]) assert.Equal(t, http.StatusOK, rec.Code) }) } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/recover_test.go
middleware/recover_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "bytes" "errors" "fmt" "net/http" "net/http/httptest" "testing" "github.com/labstack/echo/v4" "github.com/labstack/gommon/log" "github.com/stretchr/testify/assert" ) func TestRecover(t *testing.T) { e := echo.New() buf := new(bytes.Buffer) e.Logger.SetOutput(buf) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) h := Recover()(echo.HandlerFunc(func(c echo.Context) error { panic("test") })) err := h(c) assert.NoError(t, err) assert.Equal(t, http.StatusInternalServerError, rec.Code) assert.Contains(t, buf.String(), "PANIC RECOVER") } func TestRecoverErrAbortHandler(t *testing.T) { e := echo.New() buf := new(bytes.Buffer) e.Logger.SetOutput(buf) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) h := Recover()(echo.HandlerFunc(func(c echo.Context) error { panic(http.ErrAbortHandler) })) defer func() { r := recover() if r == nil { assert.Fail(t, "expecting `http.ErrAbortHandler`, got `nil`") } else { if err, ok := r.(error); ok { assert.ErrorIs(t, err, http.ErrAbortHandler) } else { assert.Fail(t, "not of error type") } } }() h(c) assert.Equal(t, http.StatusInternalServerError, rec.Code) assert.NotContains(t, buf.String(), "PANIC RECOVER") } func TestRecoverWithConfig_LogLevel(t *testing.T) { tests := []struct { logLevel log.Lvl levelName string }{{ logLevel: log.DEBUG, levelName: "DEBUG", }, { logLevel: log.INFO, levelName: "INFO", }, { logLevel: log.WARN, levelName: "WARN", }, { logLevel: log.ERROR, levelName: "ERROR", }, { logLevel: log.OFF, levelName: "OFF", }} for _, tt := range tests { tt := tt t.Run(tt.levelName, func(t *testing.T) { e := echo.New() e.Logger.SetLevel(log.DEBUG) buf := new(bytes.Buffer) e.Logger.SetOutput(buf) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) config := DefaultRecoverConfig config.LogLevel = tt.logLevel h := RecoverWithConfig(config)(echo.HandlerFunc(func(c echo.Context) error { panic("test") })) h(c) assert.Equal(t, http.StatusInternalServerError, rec.Code) output := buf.String() if tt.logLevel == log.OFF { assert.Empty(t, output) } else { assert.Contains(t, output, "PANIC RECOVER") assert.Contains(t, output, fmt.Sprintf(`"level":"%s"`, tt.levelName)) } }) } } func TestRecoverWithConfig_LogErrorFunc(t *testing.T) { e := echo.New() e.Logger.SetLevel(log.DEBUG) buf := new(bytes.Buffer) e.Logger.SetOutput(buf) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) testError := errors.New("test") config := DefaultRecoverConfig config.LogErrorFunc = func(c echo.Context, err error, stack []byte) error { msg := fmt.Sprintf("[PANIC RECOVER] %v %s\n", err, stack) if errors.Is(err, testError) { c.Logger().Debug(msg) } else { c.Logger().Error(msg) } return err } t.Run("first branch case for LogErrorFunc", func(t *testing.T) { buf.Reset() h := RecoverWithConfig(config)(echo.HandlerFunc(func(c echo.Context) error { panic(testError) })) h(c) assert.Equal(t, http.StatusInternalServerError, rec.Code) output := buf.String() assert.Contains(t, output, "PANIC RECOVER") assert.Contains(t, output, `"level":"DEBUG"`) }) t.Run("else branch case for LogErrorFunc", func(t *testing.T) { buf.Reset() h := RecoverWithConfig(config)(echo.HandlerFunc(func(c echo.Context) error { panic("other") })) h(c) assert.Equal(t, http.StatusInternalServerError, rec.Code) output := buf.String() assert.Contains(t, output, "PANIC RECOVER") assert.Contains(t, output, `"level":"ERROR"`) }) } func TestRecoverWithDisabled_ErrorHandler(t *testing.T) { e := echo.New() buf := new(bytes.Buffer) e.Logger.SetOutput(buf) req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) config := DefaultRecoverConfig config.DisableErrorHandler = true h := RecoverWithConfig(config)(echo.HandlerFunc(func(c echo.Context) error { panic("test") })) err := h(c) assert.Equal(t, http.StatusOK, rec.Code) assert.Contains(t, buf.String(), "PANIC RECOVER") assert.EqualError(t, err, "test") }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/body_dump.go
middleware/body_dump.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "bufio" "bytes" "errors" "io" "net" "net/http" "github.com/labstack/echo/v4" ) // BodyDumpConfig defines the config for BodyDump middleware. type BodyDumpConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // Handler receives request and response payload. // Required. Handler BodyDumpHandler } // BodyDumpHandler receives the request and response payload. type BodyDumpHandler func(echo.Context, []byte, []byte) type bodyDumpResponseWriter struct { io.Writer http.ResponseWriter } // DefaultBodyDumpConfig is the default BodyDump middleware config. var DefaultBodyDumpConfig = BodyDumpConfig{ Skipper: DefaultSkipper, } // BodyDump returns a BodyDump middleware. // // BodyDump middleware captures the request and response payload and calls the // registered handler. func BodyDump(handler BodyDumpHandler) echo.MiddlewareFunc { c := DefaultBodyDumpConfig c.Handler = handler return BodyDumpWithConfig(c) } // BodyDumpWithConfig returns a BodyDump middleware with config. // See: `BodyDump()`. func BodyDumpWithConfig(config BodyDumpConfig) echo.MiddlewareFunc { // Defaults if config.Handler == nil { panic("echo: body-dump middleware requires a handler function") } if config.Skipper == nil { config.Skipper = DefaultBodyDumpConfig.Skipper } return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) (err error) { if config.Skipper(c) { return next(c) } // Request reqBody := []byte{} if c.Request().Body != nil { var readErr error reqBody, readErr = io.ReadAll(c.Request().Body) if readErr != nil { return readErr } } c.Request().Body = io.NopCloser(bytes.NewBuffer(reqBody)) // Reset // Response resBody := new(bytes.Buffer) mw := io.MultiWriter(c.Response().Writer, resBody) writer := &bodyDumpResponseWriter{Writer: mw, ResponseWriter: c.Response().Writer} c.Response().Writer = writer if err = next(c); err != nil { c.Error(err) } // Callback config.Handler(c, reqBody, resBody.Bytes()) return } } } func (w *bodyDumpResponseWriter) WriteHeader(code int) { w.ResponseWriter.WriteHeader(code) } func (w *bodyDumpResponseWriter) Write(b []byte) (int, error) { return w.Writer.Write(b) } func (w *bodyDumpResponseWriter) Flush() { err := http.NewResponseController(w.ResponseWriter).Flush() if err != nil && errors.Is(err, http.ErrNotSupported) { panic(errors.New("response writer flushing is not supported")) } } func (w *bodyDumpResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { return http.NewResponseController(w.ResponseWriter).Hijack() } func (w *bodyDumpResponseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/util_test.go
middleware/util_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func Test_matchScheme(t *testing.T) { tests := []struct { domain, pattern string expected bool }{ { domain: "http://example.com", pattern: "http://example.com", expected: true, }, { domain: "https://example.com", pattern: "https://example.com", expected: true, }, { domain: "http://example.com", pattern: "https://example.com", expected: false, }, { domain: "https://example.com", pattern: "http://example.com", expected: false, }, } for _, v := range tests { assert.Equal(t, v.expected, matchScheme(v.domain, v.pattern)) } } func Test_matchSubdomain(t *testing.T) { tests := []struct { domain, pattern string expected bool }{ { domain: "http://aaa.example.com", pattern: "http://*.example.com", expected: true, }, { domain: "http://bbb.aaa.example.com", pattern: "http://*.example.com", expected: true, }, { domain: "http://bbb.aaa.example.com", pattern: "http://*.aaa.example.com", expected: true, }, { domain: "http://aaa.example.com:8080", pattern: "http://*.example.com:8080", expected: true, }, { domain: "http://fuga.hoge.com", pattern: "http://*.example.com", expected: false, }, { domain: "http://ccc.bbb.example.com", pattern: "http://*.aaa.example.com", expected: false, }, { domain: `http://1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890\ .1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890\ .1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890\ .1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.example.com`, pattern: "http://*.example.com", expected: false, }, { domain: "http://ccc.bbb.example.com", pattern: "http://example.com", expected: false, }, } for _, v := range tests { assert.Equal(t, v.expected, matchSubdomain(v.domain, v.pattern)) } } func TestRandomString(t *testing.T) { var testCases = []struct { name string whenLength uint8 expect string }{ { name: "ok, 16", whenLength: 16, }, { name: "ok, 32", whenLength: 32, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { uid := randomString(tc.whenLength) assert.Len(t, uid, int(tc.whenLength)) }) } } func TestRandomStringBias(t *testing.T) { t.Parallel() const slen = 33 const loop = 100000 counts := make(map[rune]int) var count int64 for i := 0; i < loop; i++ { s := randomString(slen) require.Equal(t, slen, len(s)) for _, b := range s { counts[b]++ count++ } } require.Equal(t, randomStringCharsetLen, len(counts)) avg := float64(count) / float64(len(counts)) for k, n := range counts { diff := float64(n) / avg if diff < 0.95 || diff > 1.05 { t.Errorf("Bias on '%c': expected average %f, got %d", k, avg, n) } } } func TestValidateOrigins(t *testing.T) { var testCases = []struct { name string givenOrigins []string givenWhat string expectErr string }{ // Valid cases { name: "ok, empty origins", givenOrigins: []string{}, }, { name: "ok, basic http", givenOrigins: []string{"http://example.com"}, }, { name: "ok, basic https", givenOrigins: []string{"https://example.com"}, }, { name: "ok, with port", givenOrigins: []string{"http://localhost:8080"}, }, { name: "ok, with subdomain", givenOrigins: []string{"https://api.example.com"}, }, { name: "ok, subdomain with port", givenOrigins: []string{"https://api.example.com:8080"}, }, { name: "ok, localhost", givenOrigins: []string{"http://localhost"}, }, { name: "ok, IPv4 address", givenOrigins: []string{"http://192.168.1.1"}, }, { name: "ok, IPv4 with port", givenOrigins: []string{"http://192.168.1.1:8080"}, }, { name: "ok, IPv6 loopback", givenOrigins: []string{"http://[::1]"}, }, { name: "ok, IPv6 with port", givenOrigins: []string{"http://[::1]:8080"}, }, { name: "ok, IPv6 full address", givenOrigins: []string{"http://[2001:db8::1]"}, }, { name: "ok, multiple valid origins", givenOrigins: []string{"http://example.com", "https://api.example.com:8080"}, }, { name: "ok, different schemes", givenOrigins: []string{"http://example.com", "https://example.com", "ws://example.com"}, }, // Invalid - missing scheme { name: "nok, plain domain", givenOrigins: []string{"example.com"}, expectErr: "trusted origin is missing scheme or host: example.com", }, { name: "nok, with slashes but no scheme", givenOrigins: []string{"//example.com"}, expectErr: "trusted origin is missing scheme or host: //example.com", }, { name: "nok, www without scheme", givenOrigins: []string{"www.example.com"}, expectErr: "trusted origin is missing scheme or host: www.example.com", }, { name: "nok, localhost without scheme", givenOrigins: []string{"localhost:8080"}, expectErr: "trusted origin is missing scheme or host: localhost:8080", }, // Invalid - missing host { name: "nok, scheme only http", givenOrigins: []string{"http://"}, expectErr: "trusted origin is missing scheme or host: http://", }, { name: "nok, scheme only https", givenOrigins: []string{"https://"}, expectErr: "trusted origin is missing scheme or host: https://", }, // Invalid - has path { name: "nok, has simple path", givenOrigins: []string{"http://example.com/path"}, expectErr: "trusted origin can not have path, query, and fragments: http://example.com/path", }, { name: "nok, has nested path", givenOrigins: []string{"https://example.com/api/v1"}, expectErr: "trusted origin can not have path, query, and fragments: https://example.com/api/v1", }, { name: "nok, has root path", givenOrigins: []string{"http://example.com/"}, expectErr: "trusted origin can not have path, query, and fragments: http://example.com/", }, // Invalid - has query { name: "nok, has single query param", givenOrigins: []string{"http://example.com?foo=bar"}, expectErr: "trusted origin can not have path, query, and fragments: http://example.com?foo=bar", }, { name: "nok, has multiple query params", givenOrigins: []string{"https://example.com?foo=bar&baz=qux"}, expectErr: "trusted origin can not have path, query, and fragments: https://example.com?foo=bar&baz=qux", }, // Invalid - has fragment { name: "nok, has simple fragment", givenOrigins: []string{"http://example.com#section"}, expectErr: "trusted origin can not have path, query, and fragments: http://example.com#section", }, // Invalid - combinations { name: "nok, has path and query", givenOrigins: []string{"http://example.com/path?foo=bar"}, expectErr: "trusted origin can not have path, query, and fragments: http://example.com/path?foo=bar", }, { name: "nok, has path and fragment", givenOrigins: []string{"http://example.com/path#section"}, expectErr: "trusted origin can not have path, query, and fragments: http://example.com/path#section", }, { name: "nok, has query and fragment", givenOrigins: []string{"http://example.com?foo=bar#section"}, expectErr: "trusted origin can not have path, query, and fragments: http://example.com?foo=bar#section", }, { name: "nok, has path, query, and fragment", givenOrigins: []string{"http://example.com/path?foo=bar#section"}, expectErr: "trusted origin can not have path, query, and fragments: http://example.com/path?foo=bar#section", }, // Edge cases { name: "nok, empty string", givenOrigins: []string{""}, expectErr: "trusted origin is missing scheme or host: ", }, { name: "nok, whitespace only", givenOrigins: []string{" "}, expectErr: "trusted origin is missing scheme or host: ", }, { name: "nok, multiple origins - first invalid", givenOrigins: []string{"example.com", "http://valid.com"}, expectErr: "trusted origin is missing scheme or host: example.com", }, { name: "nok, multiple origins - middle invalid", givenOrigins: []string{"http://valid1.com", "invalid.com", "http://valid2.com"}, expectErr: "trusted origin is missing scheme or host: invalid.com", }, { name: "nok, multiple origins - last invalid", givenOrigins: []string{"http://valid.com", "invalid.com"}, expectErr: "trusted origin is missing scheme or host: invalid.com", }, // Different "what" parameter { name: "nok, custom what parameter - missing scheme", givenOrigins: []string{"example.com"}, givenWhat: "allowed origin", expectErr: "allowed origin is missing scheme or host: example.com", }, { name: "nok, custom what parameter - has path", givenOrigins: []string{"http://example.com/path"}, givenWhat: "cors origin", expectErr: "cors origin can not have path, query, and fragments: http://example.com/path", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { what := tc.givenWhat if what == "" { what = "trusted origin" } err := validateOrigins(tc.givenOrigins, what) if tc.expectErr != "" { assert.EqualError(t, err, tc.expectErr) } else { assert.NoError(t, err) } }) } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/compress_test.go
middleware/compress_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "bytes" "compress/gzip" "io" "net/http" "net/http/httptest" "os" "testing" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func TestGzip(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) // Skip if no Accept-Encoding header h := Gzip()(func(c echo.Context) error { c.Response().Write([]byte("test")) // For Content-Type sniffing return nil }) h(c) assert.Equal(t, "test", rec.Body.String()) // Gzip req = httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) rec = httptest.NewRecorder() c = e.NewContext(req, rec) h(c) assert.Equal(t, gzipScheme, rec.Header().Get(echo.HeaderContentEncoding)) assert.Contains(t, rec.Header().Get(echo.HeaderContentType), echo.MIMETextPlain) r, err := gzip.NewReader(rec.Body) if assert.NoError(t, err) { buf := new(bytes.Buffer) defer r.Close() buf.ReadFrom(r) assert.Equal(t, "test", buf.String()) } chunkBuf := make([]byte, 5) // Gzip chunked req = httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) rec = httptest.NewRecorder() c = e.NewContext(req, rec) Gzip()(func(c echo.Context) error { c.Response().Header().Set("Content-Type", "text/event-stream") c.Response().Header().Set("Transfer-Encoding", "chunked") // Write and flush the first part of the data c.Response().Write([]byte("test\n")) c.Response().Flush() // Read the first part of the data assert.True(t, rec.Flushed) assert.Equal(t, gzipScheme, rec.Header().Get(echo.HeaderContentEncoding)) r.Reset(rec.Body) _, err = io.ReadFull(r, chunkBuf) assert.NoError(t, err) assert.Equal(t, "test\n", string(chunkBuf)) // Write and flush the second part of the data c.Response().Write([]byte("test\n")) c.Response().Flush() _, err = io.ReadFull(r, chunkBuf) assert.NoError(t, err) assert.Equal(t, "test\n", string(chunkBuf)) // Write the final part of the data and return c.Response().Write([]byte("test")) return nil })(c) buf := new(bytes.Buffer) defer r.Close() buf.ReadFrom(r) assert.Equal(t, "test", buf.String()) } func TestGzipWithMinLength(t *testing.T) { e := echo.New() // Minimal response length e.Use(GzipWithConfig(GzipConfig{MinLength: 10})) e.GET("/", func(c echo.Context) error { c.Response().Write([]byte("foobarfoobar")) return nil }) req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, gzipScheme, rec.Header().Get(echo.HeaderContentEncoding)) r, err := gzip.NewReader(rec.Body) if assert.NoError(t, err) { buf := new(bytes.Buffer) defer r.Close() buf.ReadFrom(r) assert.Equal(t, "foobarfoobar", buf.String()) } } func TestGzipWithMinLengthTooShort(t *testing.T) { e := echo.New() // Minimal response length e.Use(GzipWithConfig(GzipConfig{MinLength: 10})) e.GET("/", func(c echo.Context) error { c.Response().Write([]byte("test")) return nil }) req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, "", rec.Header().Get(echo.HeaderContentEncoding)) assert.Contains(t, rec.Body.String(), "test") } func TestGzipWithResponseWithoutBody(t *testing.T) { e := echo.New() e.Use(Gzip()) e.GET("/", func(c echo.Context) error { return c.Redirect(http.StatusMovedPermanently, "http://localhost") }) req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, http.StatusMovedPermanently, rec.Code) assert.Equal(t, "", rec.Header().Get(echo.HeaderContentEncoding)) } func TestGzipWithMinLengthChunked(t *testing.T) { e := echo.New() // Gzip chunked chunkBuf := make([]byte, 5) req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) rec := httptest.NewRecorder() var r *gzip.Reader = nil c := e.NewContext(req, rec) GzipWithConfig(GzipConfig{MinLength: 10})(func(c echo.Context) error { c.Response().Header().Set("Content-Type", "text/event-stream") c.Response().Header().Set("Transfer-Encoding", "chunked") // Write and flush the first part of the data c.Response().Write([]byte("test\n")) c.Response().Flush() // Read the first part of the data assert.True(t, rec.Flushed) assert.Equal(t, gzipScheme, rec.Header().Get(echo.HeaderContentEncoding)) var err error r, err = gzip.NewReader(rec.Body) assert.NoError(t, err) _, err = io.ReadFull(r, chunkBuf) assert.NoError(t, err) assert.Equal(t, "test\n", string(chunkBuf)) // Write and flush the second part of the data c.Response().Write([]byte("test\n")) c.Response().Flush() _, err = io.ReadFull(r, chunkBuf) assert.NoError(t, err) assert.Equal(t, "test\n", string(chunkBuf)) // Write the final part of the data and return c.Response().Write([]byte("test")) return nil })(c) assert.NotNil(t, r) buf := new(bytes.Buffer) buf.ReadFrom(r) assert.Equal(t, "test", buf.String()) r.Close() } func TestGzipWithMinLengthNoContent(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) rec := httptest.NewRecorder() c := e.NewContext(req, rec) h := GzipWithConfig(GzipConfig{MinLength: 10})(func(c echo.Context) error { return c.NoContent(http.StatusNoContent) }) if assert.NoError(t, h(c)) { assert.Empty(t, rec.Header().Get(echo.HeaderContentEncoding)) assert.Empty(t, rec.Header().Get(echo.HeaderContentType)) assert.Equal(t, 0, len(rec.Body.Bytes())) } } func TestGzipNoContent(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) rec := httptest.NewRecorder() c := e.NewContext(req, rec) h := Gzip()(func(c echo.Context) error { return c.NoContent(http.StatusNoContent) }) if assert.NoError(t, h(c)) { assert.Empty(t, rec.Header().Get(echo.HeaderContentEncoding)) assert.Empty(t, rec.Header().Get(echo.HeaderContentType)) assert.Equal(t, 0, len(rec.Body.Bytes())) } } func TestGzipEmpty(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) rec := httptest.NewRecorder() c := e.NewContext(req, rec) h := Gzip()(func(c echo.Context) error { return c.String(http.StatusOK, "") }) if assert.NoError(t, h(c)) { assert.Equal(t, gzipScheme, rec.Header().Get(echo.HeaderContentEncoding)) assert.Equal(t, "text/plain; charset=UTF-8", rec.Header().Get(echo.HeaderContentType)) r, err := gzip.NewReader(rec.Body) if assert.NoError(t, err) { var buf bytes.Buffer buf.ReadFrom(r) assert.Equal(t, "", buf.String()) } } } func TestGzipErrorReturned(t *testing.T) { e := echo.New() e.Use(Gzip()) e.GET("/", func(c echo.Context) error { return echo.ErrNotFound }) req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, http.StatusNotFound, rec.Code) assert.Empty(t, rec.Header().Get(echo.HeaderContentEncoding)) } func TestGzipErrorReturnedInvalidConfig(t *testing.T) { e := echo.New() // Invalid level e.Use(GzipWithConfig(GzipConfig{Level: 12})) e.GET("/", func(c echo.Context) error { c.Response().Write([]byte("test")) return nil }) req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, http.StatusInternalServerError, rec.Code) assert.Contains(t, rec.Body.String(), `{"message":"invalid pool object"}`) } // Issue #806 func TestGzipWithStatic(t *testing.T) { e := echo.New() e.Use(Gzip()) e.Static("/test", "../_fixture/images") req := httptest.NewRequest(http.MethodGet, "/test/walle.png", nil) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) rec := httptest.NewRecorder() e.ServeHTTP(rec, req) assert.Equal(t, http.StatusOK, rec.Code) // Data is written out in chunks when Content-Length == "", so only // validate the content length if it's not set. if cl := rec.Header().Get("Content-Length"); cl != "" { assert.Equal(t, cl, rec.Body.Len()) } r, err := gzip.NewReader(rec.Body) if assert.NoError(t, err) { defer r.Close() want, err := os.ReadFile("../_fixture/images/walle.png") if assert.NoError(t, err) { buf := new(bytes.Buffer) buf.ReadFrom(r) assert.Equal(t, want, buf.Bytes()) } } } func TestGzipResponseWriter_CanUnwrap(t *testing.T) { trwu := &testResponseWriterUnwrapper{rw: httptest.NewRecorder()} bdrw := gzipResponseWriter{ ResponseWriter: trwu, } result := bdrw.Unwrap() assert.Equal(t, trwu, result) } func TestGzipResponseWriter_CanHijack(t *testing.T) { trwu := testResponseWriterUnwrapperHijack{testResponseWriterUnwrapper: testResponseWriterUnwrapper{rw: httptest.NewRecorder()}} bdrw := gzipResponseWriter{ ResponseWriter: &trwu, // this RW supports hijacking through unwrapping } _, _, err := bdrw.Hijack() assert.EqualError(t, err, "can hijack") } func TestGzipResponseWriter_CanNotHijack(t *testing.T) { trwu := testResponseWriterUnwrapper{rw: httptest.NewRecorder()} bdrw := gzipResponseWriter{ ResponseWriter: &trwu, // this RW supports hijacking through unwrapping } _, _, err := bdrw.Hijack() assert.EqualError(t, err, "feature not supported") } func BenchmarkGzip(b *testing.B) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) h := Gzip()(func(c echo.Context) error { c.Response().Write([]byte("test")) // For Content-Type sniffing return nil }) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { // Gzip rec := httptest.NewRecorder() c := e.NewContext(req, rec) h(c) } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/request_logger.go
middleware/request_logger.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "context" "errors" "log/slog" "net/http" "time" "github.com/labstack/echo/v4" ) // Example for `slog` https://pkg.go.dev/log/slog // logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) // e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{ // LogStatus: true, // LogURI: true, // LogError: true, // HandleError: true, // forwards error to the global error handler, so it can decide appropriate status code // LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error { // if v.Error == nil { // logger.LogAttrs(context.Background(), slog.LevelInfo, "REQUEST", // slog.String("uri", v.URI), // slog.Int("status", v.Status), // ) // } else { // logger.LogAttrs(context.Background(), slog.LevelError, "REQUEST_ERROR", // slog.String("uri", v.URI), // slog.Int("status", v.Status), // slog.String("err", v.Error.Error()), // ) // } // return nil // }, // })) // // Example for `fmt.Printf` // e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{ // LogStatus: true, // LogURI: true, // LogError: true, // HandleError: true, // forwards error to the global error handler, so it can decide appropriate status code // LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error { // if v.Error == nil { // fmt.Printf("REQUEST: uri: %v, status: %v\n", v.URI, v.Status) // } else { // fmt.Printf("REQUEST_ERROR: uri: %v, status: %v, err: %v\n", v.URI, v.Status, v.Error) // } // return nil // }, // })) // // Example for Zerolog (https://github.com/rs/zerolog) // logger := zerolog.New(os.Stdout) // e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{ // LogURI: true, // LogStatus: true, // LogError: true, // HandleError: true, // forwards error to the global error handler, so it can decide appropriate status code // LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error { // if v.Error == nil { // logger.Info(). // Str("URI", v.URI). // Int("status", v.Status). // Msg("request") // } else { // logger.Error(). // Err(v.Error). // Str("URI", v.URI). // Int("status", v.Status). // Msg("request error") // } // return nil // }, // })) // // Example for Zap (https://github.com/uber-go/zap) // logger, _ := zap.NewProduction() // e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{ // LogURI: true, // LogStatus: true, // LogError: true, // HandleError: true, // forwards error to the global error handler, so it can decide appropriate status code // LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error { // if v.Error == nil { // logger.Info("request", // zap.String("URI", v.URI), // zap.Int("status", v.Status), // ) // } else { // logger.Error("request error", // zap.String("URI", v.URI), // zap.Int("status", v.Status), // zap.Error(v.Error), // ) // } // return nil // }, // })) // // Example for Logrus (https://github.com/sirupsen/logrus) // log := logrus.New() // e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{ // LogURI: true, // LogStatus: true, // LogError: true, // HandleError: true, // forwards error to the global error handler, so it can decide appropriate status code // LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error { // if v.Error == nil { // log.WithFields(logrus.Fields{ // "URI": v.URI, // "status": v.Status, // }).Info("request") // } else { // log.WithFields(logrus.Fields{ // "URI": v.URI, // "status": v.Status, // "error": v.Error, // }).Error("request error") // } // return nil // }, // })) // RequestLoggerConfig is configuration for Request Logger middleware. type RequestLoggerConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // BeforeNextFunc defines a function that is called before next middleware or handler is called in chain. BeforeNextFunc func(c echo.Context) // LogValuesFunc defines a function that is called with values extracted by logger from request/response. // Mandatory. LogValuesFunc func(c echo.Context, v RequestLoggerValues) error // HandleError instructs logger to call global error handler when next middleware/handler returns an error. // This is useful when you have custom error handler that can decide to use different status codes. // // A side-effect of calling global error handler is that now Response has been committed and sent to the client // and middlewares up in chain can not change Response status code or response body. HandleError bool // LogLatency instructs logger to record duration it took to execute rest of the handler chain (next(c) call). LogLatency bool // LogProtocol instructs logger to extract request protocol (i.e. `HTTP/1.1` or `HTTP/2`) LogProtocol bool // LogRemoteIP instructs logger to extract request remote IP. See `echo.Context.RealIP()` for implementation details. LogRemoteIP bool // LogHost instructs logger to extract request host value (i.e. `example.com`) LogHost bool // LogMethod instructs logger to extract request method value (i.e. `GET` etc) LogMethod bool // LogURI instructs logger to extract request URI (i.e. `/list?lang=en&page=1`) LogURI bool // LogURIPath instructs logger to extract request URI path part (i.e. `/list`) LogURIPath bool // LogRoutePath instructs logger to extract route path part to which request was matched to (i.e. `/user/:id`) LogRoutePath bool // LogRequestID instructs logger to extract request ID from request `X-Request-ID` header or response if request did not have value. LogRequestID bool // LogReferer instructs logger to extract request referer values. LogReferer bool // LogUserAgent instructs logger to extract request user agent values. LogUserAgent bool // LogStatus instructs logger to extract response status code. If handler chain returns an echo.HTTPError, // the status code is extracted from the echo.HTTPError returned LogStatus bool // LogError instructs logger to extract error returned from executed handler chain. LogError bool // LogContentLength instructs logger to extract content length header value. Note: this value could be different from // actual request body size as it could be spoofed etc. LogContentLength bool // LogResponseSize instructs logger to extract response content length value. Note: when used with Gzip middleware // this value may not be always correct. LogResponseSize bool // LogHeaders instructs logger to extract given list of headers from request. Note: request can contain more than // one header with same value so slice of values is been logger for each given header. // // Note: header values are converted to canonical form with http.CanonicalHeaderKey as this how request parser converts header // names to. For example, the canonical key for "accept-encoding" is "Accept-Encoding". LogHeaders []string // LogQueryParams instructs logger to extract given list of query parameters from request URI. Note: request can // contain more than one query parameter with same name so slice of values is been logger for each given query param name. LogQueryParams []string // LogFormValues instructs logger to extract given list of form values from request body+URI. Note: request can // contain more than one form value with same name so slice of values is been logger for each given form value name. LogFormValues []string timeNow func() time.Time } // RequestLoggerValues contains extracted values from logger. type RequestLoggerValues struct { // StartTime is time recorded before next middleware/handler is executed. StartTime time.Time // Latency is duration it took to execute rest of the handler chain (next(c) call). Latency time.Duration // Protocol is request protocol (i.e. `HTTP/1.1` or `HTTP/2`) Protocol string // RemoteIP is request remote IP. See `echo.Context.RealIP()` for implementation details. RemoteIP string // Host is request host value (i.e. `example.com`) Host string // Method is request method value (i.e. `GET` etc) Method string // URI is request URI (i.e. `/list?lang=en&page=1`) URI string // URIPath is request URI path part (i.e. `/list`) URIPath string // RoutePath is route path part to which request was matched to (i.e. `/user/:id`) RoutePath string // RequestID is request ID from request `X-Request-ID` header or response if request did not have value. RequestID string // Referer is request referer values. Referer string // UserAgent is request user agent values. UserAgent string // Status is response status code. Then handler returns an echo.HTTPError then code from there. Status int // Error is error returned from executed handler chain. Error error // ContentLength is content length header value. Note: this value could be different from actual request body size // as it could be spoofed etc. ContentLength string // ResponseSize is response content length value. Note: when used with Gzip middleware this value may not be always correct. ResponseSize int64 // Headers are list of headers from request. Note: request can contain more than one header with same value so slice // of values is been logger for each given header. // Note: header values are converted to canonical form with http.CanonicalHeaderKey as this how request parser converts header // names to. For example, the canonical key for "accept-encoding" is "Accept-Encoding". Headers map[string][]string // QueryParams are list of query parameters from request URI. Note: request can contain more than one query parameter // with same name so slice of values is been logger for each given query param name. QueryParams map[string][]string // FormValues are list of form values from request body+URI. Note: request can contain more than one form value with // same name so slice of values is been logger for each given form value name. FormValues map[string][]string } // RequestLoggerWithConfig returns a RequestLogger middleware with config. func RequestLoggerWithConfig(config RequestLoggerConfig) echo.MiddlewareFunc { mw, err := config.ToMiddleware() if err != nil { panic(err) } return mw } // RequestLogger returns a RequestLogger middleware with default configuration which // uses default slog.slog logger. // // To customize slog output format replace slog default logger: // For JSON format: `slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil)))` func RequestLogger() echo.MiddlewareFunc { config := RequestLoggerConfig{ LogLatency: true, LogProtocol: false, LogRemoteIP: true, LogHost: true, LogMethod: true, LogURI: true, LogURIPath: false, LogRoutePath: false, LogRequestID: true, LogReferer: false, LogUserAgent: true, LogStatus: true, LogError: true, LogContentLength: true, LogResponseSize: true, LogHeaders: nil, LogQueryParams: nil, LogFormValues: nil, HandleError: true, // forwards error to the global error handler, so it can decide appropriate status code LogValuesFunc: func(c echo.Context, v RequestLoggerValues) error { if v.Error == nil { slog.LogAttrs(context.Background(), slog.LevelInfo, "REQUEST", slog.String("method", v.Method), slog.String("uri", v.URI), slog.Int("status", v.Status), slog.Duration("latency", v.Latency), slog.String("host", v.Host), slog.String("bytes_in", v.ContentLength), slog.Int64("bytes_out", v.ResponseSize), slog.String("user_agent", v.UserAgent), slog.String("remote_ip", v.RemoteIP), slog.String("request_id", v.RequestID), ) } else { slog.LogAttrs(context.Background(), slog.LevelError, "REQUEST_ERROR", slog.String("method", v.Method), slog.String("uri", v.URI), slog.Int("status", v.Status), slog.Duration("latency", v.Latency), slog.String("host", v.Host), slog.String("bytes_in", v.ContentLength), slog.Int64("bytes_out", v.ResponseSize), slog.String("user_agent", v.UserAgent), slog.String("remote_ip", v.RemoteIP), slog.String("request_id", v.RequestID), slog.String("error", v.Error.Error()), ) } return nil }, } mw, err := config.ToMiddleware() if err != nil { panic(err) } return mw } // ToMiddleware converts RequestLoggerConfig into middleware or returns an error for invalid configuration. func (config RequestLoggerConfig) ToMiddleware() (echo.MiddlewareFunc, error) { if config.Skipper == nil { config.Skipper = DefaultSkipper } now := time.Now if config.timeNow != nil { now = config.timeNow } if config.LogValuesFunc == nil { return nil, errors.New("missing LogValuesFunc callback function for request logger middleware") } logHeaders := len(config.LogHeaders) > 0 headers := append([]string(nil), config.LogHeaders...) for i, v := range headers { headers[i] = http.CanonicalHeaderKey(v) } logQueryParams := len(config.LogQueryParams) > 0 logFormValues := len(config.LogFormValues) > 0 return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { if config.Skipper(c) { return next(c) } req := c.Request() res := c.Response() start := now() if config.BeforeNextFunc != nil { config.BeforeNextFunc(c) } err := next(c) if err != nil && config.HandleError { c.Error(err) } v := RequestLoggerValues{ StartTime: start, } if config.LogLatency { v.Latency = now().Sub(start) } if config.LogProtocol { v.Protocol = req.Proto } if config.LogRemoteIP { v.RemoteIP = c.RealIP() } if config.LogHost { v.Host = req.Host } if config.LogMethod { v.Method = req.Method } if config.LogURI { v.URI = req.RequestURI } if config.LogURIPath { p := req.URL.Path if p == "" { p = "/" } v.URIPath = p } if config.LogRoutePath { v.RoutePath = c.Path() } if config.LogRequestID { id := req.Header.Get(echo.HeaderXRequestID) if id == "" { id = res.Header().Get(echo.HeaderXRequestID) } v.RequestID = id } if config.LogReferer { v.Referer = req.Referer() } if config.LogUserAgent { v.UserAgent = req.UserAgent() } if config.LogStatus { v.Status = res.Status if err != nil && !config.HandleError { // this block should not be executed in case of HandleError=true as the global error handler will decide // the status code. In that case status code could be different from what err contains. var httpErr *echo.HTTPError if errors.As(err, &httpErr) { v.Status = httpErr.Code } } } if config.LogError && err != nil { v.Error = err } if config.LogContentLength { v.ContentLength = req.Header.Get(echo.HeaderContentLength) } if config.LogResponseSize { v.ResponseSize = res.Size } if logHeaders { v.Headers = map[string][]string{} for _, header := range headers { if values, ok := req.Header[header]; ok { v.Headers[header] = values } } } if logQueryParams { queryParams := c.QueryParams() v.QueryParams = map[string][]string{} for _, param := range config.LogQueryParams { if values, ok := queryParams[param]; ok { v.QueryParams[param] = values } } } if logFormValues { v.FormValues = map[string][]string{} for _, formValue := range config.LogFormValues { if values, ok := req.Form[formValue]; ok { v.FormValues[formValue] = values } } } if errOnLog := config.LogValuesFunc(c, v); errOnLog != nil { return errOnLog } // in case of HandleError=true we are returning the error that we already have handled with global error handler // this is deliberate as this error could be useful for upstream middlewares and default global error handler // will ignore that error when it bubbles up in middleware chain. return err } }, nil }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/csrf_test.go
middleware/csrf_test.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "cmp" "net/http" "net/http/httptest" "net/url" "strings" "testing" "github.com/labstack/echo/v4" "github.com/stretchr/testify/assert" ) func TestCSRF_tokenExtractors(t *testing.T) { var testCases = []struct { name string whenTokenLookup string whenCookieName string givenCSRFCookie string givenMethod string givenQueryTokens map[string][]string givenFormTokens map[string][]string givenHeaderTokens map[string][]string expectError string expectToMiddlewareError string }{ { name: "ok, multiple token lookups sources, succeeds on last one", whenTokenLookup: "header:X-CSRF-Token,form:csrf", givenCSRFCookie: "token", givenMethod: http.MethodPost, givenHeaderTokens: map[string][]string{ echo.HeaderXCSRFToken: {"invalid_token"}, }, givenFormTokens: map[string][]string{ "csrf": {"token"}, }, }, { name: "ok, token from POST form", whenTokenLookup: "form:csrf", givenCSRFCookie: "token", givenMethod: http.MethodPost, givenFormTokens: map[string][]string{ "csrf": {"token"}, }, }, { name: "ok, token from POST form, second token passes", whenTokenLookup: "form:csrf", givenCSRFCookie: "token", givenMethod: http.MethodPost, givenFormTokens: map[string][]string{ "csrf": {"invalid", "token"}, }, }, { name: "nok, invalid token from POST form", whenTokenLookup: "form:csrf", givenCSRFCookie: "token", givenMethod: http.MethodPost, givenFormTokens: map[string][]string{ "csrf": {"invalid_token"}, }, expectError: "code=403, message=invalid csrf token", }, { name: "nok, missing token from POST form", whenTokenLookup: "form:csrf", givenCSRFCookie: "token", givenMethod: http.MethodPost, givenFormTokens: map[string][]string{}, expectError: "code=400, message=missing csrf token in the form parameter", }, { name: "ok, token from POST header", whenTokenLookup: "", // will use defaults givenCSRFCookie: "token", givenMethod: http.MethodPost, givenHeaderTokens: map[string][]string{ echo.HeaderXCSRFToken: {"token"}, }, }, { name: "ok, token from POST header, second token passes", whenTokenLookup: "header:" + echo.HeaderXCSRFToken, givenCSRFCookie: "token", givenMethod: http.MethodPost, givenHeaderTokens: map[string][]string{ echo.HeaderXCSRFToken: {"invalid", "token"}, }, }, { name: "nok, invalid token from POST header", whenTokenLookup: "header:" + echo.HeaderXCSRFToken, givenCSRFCookie: "token", givenMethod: http.MethodPost, givenHeaderTokens: map[string][]string{ echo.HeaderXCSRFToken: {"invalid_token"}, }, expectError: "code=403, message=invalid csrf token", }, { name: "nok, missing token from POST header", whenTokenLookup: "header:" + echo.HeaderXCSRFToken, givenCSRFCookie: "token", givenMethod: http.MethodPost, givenHeaderTokens: map[string][]string{}, expectError: "code=400, message=missing csrf token in request header", }, { name: "ok, token from PUT query param", whenTokenLookup: "query:csrf-param", givenCSRFCookie: "token", givenMethod: http.MethodPut, givenQueryTokens: map[string][]string{ "csrf-param": {"token"}, }, }, { name: "ok, token from PUT query form, second token passes", whenTokenLookup: "query:csrf", givenCSRFCookie: "token", givenMethod: http.MethodPut, givenQueryTokens: map[string][]string{ "csrf": {"invalid", "token"}, }, }, { name: "nok, invalid token from PUT query form", whenTokenLookup: "query:csrf", givenCSRFCookie: "token", givenMethod: http.MethodPut, givenQueryTokens: map[string][]string{ "csrf": {"invalid_token"}, }, expectError: "code=403, message=invalid csrf token", }, { name: "nok, missing token from PUT query form", whenTokenLookup: "query:csrf", givenCSRFCookie: "token", givenMethod: http.MethodPut, givenQueryTokens: map[string][]string{}, expectError: "code=400, message=missing csrf token in the query string", }, { name: "nok, invalid TokenLookup", whenTokenLookup: "q", givenCSRFCookie: "token", givenMethod: http.MethodPut, givenQueryTokens: map[string][]string{}, expectToMiddlewareError: "extractor source for lookup could not be split into needed parts: q", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() q := make(url.Values) for queryParam, values := range tc.givenQueryTokens { for _, v := range values { q.Add(queryParam, v) } } f := make(url.Values) for formKey, values := range tc.givenFormTokens { for _, v := range values { f.Add(formKey, v) } } var req *http.Request switch tc.givenMethod { case http.MethodGet: req = httptest.NewRequest(http.MethodGet, "/?"+q.Encode(), nil) case http.MethodPost, http.MethodPut: req = httptest.NewRequest(http.MethodPost, "/?"+q.Encode(), strings.NewReader(f.Encode())) req.Header.Add(echo.HeaderContentType, echo.MIMEApplicationForm) } for header, values := range tc.givenHeaderTokens { for _, v := range values { req.Header.Add(header, v) } } if tc.givenCSRFCookie != "" { req.Header.Set(echo.HeaderCookie, "_csrf="+tc.givenCSRFCookie) } rec := httptest.NewRecorder() c := e.NewContext(req, rec) config := CSRFConfig{ TokenLookup: tc.whenTokenLookup, CookieName: tc.whenCookieName, } csrf, err := config.ToMiddleware() if tc.expectToMiddlewareError != "" { assert.EqualError(t, err, tc.expectToMiddlewareError) return } else if err != nil { assert.NoError(t, err) } h := csrf(func(c echo.Context) error { return c.String(http.StatusOK, "test") }) err = h(c) if tc.expectError != "" { assert.EqualError(t, err, tc.expectError) } else { assert.NoError(t, err) } }) } } func TestCSRFWithConfig(t *testing.T) { token := randomString(16) var testCases = []struct { name string givenConfig *CSRFConfig whenMethod string whenHeaders map[string]string expectEmptyBody bool expectMWError string expectCookieContains string expectErr string }{ { name: "ok, GET", whenMethod: http.MethodGet, expectCookieContains: "_csrf", }, { name: "ok, POST valid token", whenHeaders: map[string]string{ echo.HeaderCookie: "_csrf=" + token, echo.HeaderXCSRFToken: token, }, whenMethod: http.MethodPost, expectCookieContains: "_csrf", }, { name: "nok, POST without token", whenMethod: http.MethodPost, expectEmptyBody: true, expectErr: `code=400, message=missing csrf token in request header`, }, { name: "nok, POST empty token", whenHeaders: map[string]string{echo.HeaderXCSRFToken: ""}, whenMethod: http.MethodPost, expectEmptyBody: true, expectErr: `code=403, message=invalid csrf token`, }, { name: "nok, invalid trusted origin in Config", givenConfig: &CSRFConfig{ TrustedOrigins: []string{"http://example.com", "invalid"}, }, expectMWError: `trusted origin is missing scheme or host: invalid`, }, { name: "ok, TokenLength", givenConfig: &CSRFConfig{ TokenLength: 16, }, whenMethod: http.MethodGet, expectCookieContains: "_csrf", }, { name: "ok, unsafe method + SecFetchSite=same-origin passes", whenHeaders: map[string]string{ echo.HeaderSecFetchSite: "same-origin", }, whenMethod: http.MethodPost, }, { name: "nok, unsafe method + SecFetchSite=same-cross blocked", whenHeaders: map[string]string{ echo.HeaderSecFetchSite: "same-cross", }, whenMethod: http.MethodPost, expectEmptyBody: true, expectErr: `code=403, message=cross-site request blocked by CSRF`, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() req := httptest.NewRequest(cmp.Or(tc.whenMethod, http.MethodPost), "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) for key, value := range tc.whenHeaders { req.Header.Set(key, value) } config := CSRFConfig{} if tc.givenConfig != nil { config = *tc.givenConfig } mw, err := config.ToMiddleware() if tc.expectMWError != "" { assert.EqualError(t, err, tc.expectMWError) return } assert.NoError(t, err) h := mw(func(c echo.Context) error { return c.String(http.StatusOK, "test") }) err = h(c) if tc.expectErr != "" { assert.EqualError(t, err, tc.expectErr) } else { assert.NoError(t, err) } expect := "test" if tc.expectEmptyBody { expect = "" } assert.Equal(t, expect, rec.Body.String()) if tc.expectCookieContains != "" { assert.Contains(t, rec.Header().Get(echo.HeaderSetCookie), tc.expectCookieContains) } }) } } func TestCSRF(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) csrf := CSRF() h := csrf(func(c echo.Context) error { return c.String(http.StatusOK, "test") }) // Generate CSRF token h(c) assert.Contains(t, rec.Header().Get(echo.HeaderSetCookie), "_csrf") } func TestCSRFSetSameSiteMode(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) csrf := CSRFWithConfig(CSRFConfig{ CookieSameSite: http.SameSiteStrictMode, }) h := csrf(func(c echo.Context) error { return c.String(http.StatusOK, "test") }) r := h(c) assert.NoError(t, r) assert.Regexp(t, "SameSite=Strict", rec.Header()["Set-Cookie"]) } func TestCSRFWithoutSameSiteMode(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) csrf := CSRFWithConfig(CSRFConfig{}) h := csrf(func(c echo.Context) error { return c.String(http.StatusOK, "test") }) r := h(c) assert.NoError(t, r) assert.NotRegexp(t, "SameSite=", rec.Header()["Set-Cookie"]) } func TestCSRFWithSameSiteDefaultMode(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) csrf := CSRFWithConfig(CSRFConfig{ CookieSameSite: http.SameSiteDefaultMode, }) h := csrf(func(c echo.Context) error { return c.String(http.StatusOK, "test") }) r := h(c) assert.NoError(t, r) assert.NotRegexp(t, "SameSite=", rec.Header()["Set-Cookie"]) } func TestCSRFWithSameSiteModeNone(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) csrf, err := CSRFConfig{ CookieSameSite: http.SameSiteNoneMode, }.ToMiddleware() assert.NoError(t, err) h := csrf(func(c echo.Context) error { return c.String(http.StatusOK, "test") }) r := h(c) assert.NoError(t, r) assert.Regexp(t, "SameSite=None", rec.Header()["Set-Cookie"]) assert.Regexp(t, "Secure", rec.Header()["Set-Cookie"]) } func TestCSRFConfig_skipper(t *testing.T) { var testCases = []struct { name string whenSkip bool expectCookies int }{ { name: "do skip", whenSkip: true, expectCookies: 0, }, { name: "do not skip", whenSkip: false, expectCookies: 1, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { e := echo.New() req := httptest.NewRequest(http.MethodGet, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) csrf := CSRFWithConfig(CSRFConfig{ Skipper: func(c echo.Context) bool { return tc.whenSkip }, }) h := csrf(func(c echo.Context) error { return c.String(http.StatusOK, "test") }) r := h(c) assert.NoError(t, r) cookie := rec.Header()["Set-Cookie"] assert.Len(t, cookie, tc.expectCookies) }) } } func TestCSRFErrorHandling(t *testing.T) { cfg := CSRFConfig{ ErrorHandler: func(err error, c echo.Context) error { return echo.NewHTTPError(http.StatusTeapot, "error_handler_executed") }, } e := echo.New() e.POST("/", func(c echo.Context) error { return c.String(http.StatusNotImplemented, "should not end up here") }) e.Use(CSRFWithConfig(cfg)) req := httptest.NewRequest(http.MethodPost, "/", nil) res := httptest.NewRecorder() e.ServeHTTP(res, req) assert.Equal(t, http.StatusTeapot, res.Code) assert.Equal(t, "{\"message\":\"error_handler_executed\"}\n", res.Body.String()) } func TestCSRFConfig_checkSecFetchSiteRequest(t *testing.T) { var testCases = []struct { name string givenConfig CSRFConfig whenMethod string whenSecFetchSite string whenOrigin string expectAllow bool expectErr string }{ { name: "ok, unsafe POST, no SecFetchSite is not blocked", givenConfig: CSRFConfig{}, whenMethod: http.MethodPost, whenSecFetchSite: "", expectAllow: false, // should fall back to token CSRF }, { name: "ok, safe GET + same-origin passes", givenConfig: CSRFConfig{}, whenMethod: http.MethodGet, whenSecFetchSite: "same-origin", expectAllow: true, }, { name: "ok, safe GET + none passes", givenConfig: CSRFConfig{}, whenMethod: http.MethodGet, whenSecFetchSite: "none", expectAllow: true, }, { name: "ok, safe GET + same-site passes", givenConfig: CSRFConfig{}, whenMethod: http.MethodGet, whenSecFetchSite: "same-site", expectAllow: true, }, { name: "ok, safe GET + cross-site passes", givenConfig: CSRFConfig{}, whenMethod: http.MethodGet, whenSecFetchSite: "cross-site", expectAllow: true, }, { name: "nok, unsafe POST + cross-site is blocked", givenConfig: CSRFConfig{}, whenMethod: http.MethodPost, whenSecFetchSite: "cross-site", expectAllow: false, expectErr: `code=403, message=cross-site request blocked by CSRF`, }, { name: "nok, unsafe POST + same-site is blocked", givenConfig: CSRFConfig{}, whenMethod: http.MethodPost, whenSecFetchSite: "same-site", expectAllow: false, expectErr: ``, }, { name: "ok, unsafe POST + same-origin passes", givenConfig: CSRFConfig{}, whenMethod: http.MethodPost, whenSecFetchSite: "same-origin", expectAllow: true, }, { name: "ok, unsafe POST + none passes", givenConfig: CSRFConfig{}, whenMethod: http.MethodPost, whenSecFetchSite: "none", expectAllow: true, }, { name: "ok, unsafe PUT + same-origin passes", givenConfig: CSRFConfig{}, whenMethod: http.MethodPut, whenSecFetchSite: "same-origin", expectAllow: true, }, { name: "ok, unsafe PUT + none passes", givenConfig: CSRFConfig{}, whenMethod: http.MethodPut, whenSecFetchSite: "none", expectAllow: true, }, { name: "ok, unsafe DELETE + same-origin passes", givenConfig: CSRFConfig{}, whenMethod: http.MethodDelete, whenSecFetchSite: "same-origin", expectAllow: true, }, { name: "ok, unsafe PATCH + same-origin passes", givenConfig: CSRFConfig{}, whenMethod: http.MethodPatch, whenSecFetchSite: "same-origin", expectAllow: true, }, { name: "nok, unsafe PUT + cross-site is blocked", givenConfig: CSRFConfig{}, whenMethod: http.MethodPut, whenSecFetchSite: "cross-site", expectAllow: false, expectErr: `code=403, message=cross-site request blocked by CSRF`, }, { name: "nok, unsafe PUT + same-site is blocked", givenConfig: CSRFConfig{}, whenMethod: http.MethodPut, whenSecFetchSite: "same-site", expectAllow: false, expectErr: ``, }, { name: "nok, unsafe DELETE + cross-site is blocked", givenConfig: CSRFConfig{}, whenMethod: http.MethodDelete, whenSecFetchSite: "cross-site", expectAllow: false, expectErr: `code=403, message=cross-site request blocked by CSRF`, }, { name: "nok, unsafe DELETE + same-site is blocked", givenConfig: CSRFConfig{}, whenMethod: http.MethodDelete, whenSecFetchSite: "same-site", expectAllow: false, expectErr: ``, }, { name: "nok, unsafe PATCH + cross-site is blocked", givenConfig: CSRFConfig{}, whenMethod: http.MethodPatch, whenSecFetchSite: "cross-site", expectAllow: false, expectErr: `code=403, message=cross-site request blocked by CSRF`, }, { name: "ok, safe HEAD + same-origin passes", givenConfig: CSRFConfig{}, whenMethod: http.MethodHead, whenSecFetchSite: "same-origin", expectAllow: true, }, { name: "ok, safe HEAD + cross-site passes", givenConfig: CSRFConfig{}, whenMethod: http.MethodHead, whenSecFetchSite: "cross-site", expectAllow: true, }, { name: "ok, safe OPTIONS + cross-site passes", givenConfig: CSRFConfig{}, whenMethod: http.MethodOptions, whenSecFetchSite: "cross-site", expectAllow: true, }, { name: "ok, safe TRACE + cross-site passes", givenConfig: CSRFConfig{}, whenMethod: http.MethodTrace, whenSecFetchSite: "cross-site", expectAllow: true, }, { name: "ok, unsafe POST + cross-site + matching trusted origin passes", givenConfig: CSRFConfig{ TrustedOrigins: []string{"https://trusted.example.com"}, }, whenMethod: http.MethodPost, whenSecFetchSite: "cross-site", whenOrigin: "https://trusted.example.com", expectAllow: true, }, { name: "ok, unsafe POST + same-site + matching trusted origin passes", givenConfig: CSRFConfig{ TrustedOrigins: []string{"https://trusted.example.com"}, }, whenMethod: http.MethodPost, whenSecFetchSite: "same-site", whenOrigin: "https://trusted.example.com", expectAllow: true, }, { name: "nok, unsafe POST + cross-site + non-matching origin is blocked", givenConfig: CSRFConfig{ TrustedOrigins: []string{"https://trusted.example.com"}, }, whenMethod: http.MethodPost, whenSecFetchSite: "cross-site", whenOrigin: "https://evil.example.com", expectAllow: false, expectErr: `code=403, message=cross-site request blocked by CSRF`, }, { name: "ok, unsafe POST + cross-site + case-insensitive trusted origin match passes", givenConfig: CSRFConfig{ TrustedOrigins: []string{"https://trusted.example.com"}, }, whenMethod: http.MethodPost, whenSecFetchSite: "cross-site", whenOrigin: "https://TRUSTED.example.com", expectAllow: true, }, { name: "ok, unsafe POST + same-origin + trusted origins configured but not matched passes", givenConfig: CSRFConfig{ TrustedOrigins: []string{"https://trusted.example.com"}, }, whenMethod: http.MethodPost, whenSecFetchSite: "same-origin", whenOrigin: "https://different.example.com", expectAllow: true, }, { name: "nok, unsafe POST + cross-site + empty origin + trusted origins configured is blocked", givenConfig: CSRFConfig{ TrustedOrigins: []string{"https://trusted.example.com"}, }, whenMethod: http.MethodPost, whenSecFetchSite: "cross-site", whenOrigin: "", expectAllow: false, expectErr: `code=403, message=cross-site request blocked by CSRF`, }, { name: "ok, unsafe POST + cross-site + multiple trusted origins, second one matches", givenConfig: CSRFConfig{ TrustedOrigins: []string{"https://first.example.com", "https://second.example.com"}, }, whenMethod: http.MethodPost, whenSecFetchSite: "cross-site", whenOrigin: "https://second.example.com", expectAllow: true, }, { name: "ok, unsafe POST + same-site + custom func allows", givenConfig: CSRFConfig{ AllowSecFetchSiteFunc: func(c echo.Context) (bool, error) { return true, nil }, }, whenMethod: http.MethodPost, whenSecFetchSite: "same-site", expectAllow: true, }, { name: "ok, unsafe POST + cross-site + custom func allows", givenConfig: CSRFConfig{ AllowSecFetchSiteFunc: func(c echo.Context) (bool, error) { return true, nil }, }, whenMethod: http.MethodPost, whenSecFetchSite: "cross-site", expectAllow: true, }, { name: "nok, unsafe POST + same-site + custom func returns custom error", givenConfig: CSRFConfig{ AllowSecFetchSiteFunc: func(c echo.Context) (bool, error) { return false, echo.NewHTTPError(http.StatusTeapot, "custom error from func") }, }, whenMethod: http.MethodPost, whenSecFetchSite: "same-site", expectAllow: false, expectErr: `code=418, message=custom error from func`, }, { name: "nok, unsafe POST + cross-site + custom func returns false with nil error", givenConfig: CSRFConfig{ AllowSecFetchSiteFunc: func(c echo.Context) (bool, error) { return false, nil }, }, whenMethod: http.MethodPost, whenSecFetchSite: "cross-site", expectAllow: false, expectErr: "", // custom func returns nil error, so no error expected }, { name: "nok, unsafe POST + invalid Sec-Fetch-Site value treated as cross-site", givenConfig: CSRFConfig{}, whenMethod: http.MethodPost, whenSecFetchSite: "invalid-value", expectAllow: false, expectErr: `code=403, message=cross-site request blocked by CSRF`, }, { name: "ok, unsafe POST + cross-site + trusted origin takes precedence over custom func", givenConfig: CSRFConfig{ TrustedOrigins: []string{"https://trusted.example.com"}, AllowSecFetchSiteFunc: func(c echo.Context) (bool, error) { return false, echo.NewHTTPError(http.StatusTeapot, "should not be called") }, }, whenMethod: http.MethodPost, whenSecFetchSite: "cross-site", whenOrigin: "https://trusted.example.com", expectAllow: true, }, { name: "nok, unsafe POST + cross-site + trusted origin not matched, custom func blocks", givenConfig: CSRFConfig{ TrustedOrigins: []string{"https://trusted.example.com"}, AllowSecFetchSiteFunc: func(c echo.Context) (bool, error) { return false, echo.NewHTTPError(http.StatusTeapot, "custom block") }, }, whenMethod: http.MethodPost, whenSecFetchSite: "cross-site", whenOrigin: "https://evil.example.com", expectAllow: false, expectErr: `code=418, message=custom block`, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { req := httptest.NewRequest(tc.whenMethod, "/", nil) if tc.whenSecFetchSite != "" { req.Header.Set(echo.HeaderSecFetchSite, tc.whenSecFetchSite) } if tc.whenOrigin != "" { req.Header.Set(echo.HeaderOrigin, tc.whenOrigin) } res := httptest.NewRecorder() e := echo.New() c := e.NewContext(req, res) allow, err := tc.givenConfig.checkSecFetchSiteRequest(c) assert.Equal(t, tc.expectAllow, allow) if tc.expectErr != "" { assert.EqualError(t, err, tc.expectErr) } else { assert.NoError(t, err) } }) } }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
labstack/echo
https://github.com/labstack/echo/blob/482bb46fe5c7eb7c9fd7bec7d3128433dea21bee/middleware/context_timeout.go
middleware/context_timeout.go
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors package middleware import ( "context" "errors" "time" "github.com/labstack/echo/v4" ) // ContextTimeout Middleware // // ContextTimeout provides request timeout functionality using Go's context mechanism. // It is the recommended replacement for the deprecated Timeout middleware. // // // Basic Usage: // // e.Use(middleware.ContextTimeout(30 * time.Second)) // // With Configuration: // // e.Use(middleware.ContextTimeoutWithConfig(middleware.ContextTimeoutConfig{ // Timeout: 30 * time.Second, // Skipper: middleware.DefaultSkipper, // })) // // Handler Example: // // e.GET("/task", func(c echo.Context) error { // ctx := c.Request().Context() // // result, err := performTaskWithContext(ctx) // if err != nil { // if errors.Is(err, context.DeadlineExceeded) { // return echo.NewHTTPError(http.StatusServiceUnavailable, "timeout") // } // return err // } // // return c.JSON(http.StatusOK, result) // }) // ContextTimeoutConfig defines the config for ContextTimeout middleware. type ContextTimeoutConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // ErrorHandler is a function when error arises in middleware execution. ErrorHandler func(err error, c echo.Context) error // Timeout configures a timeout for the middleware, defaults to 0 for no timeout Timeout time.Duration } // ContextTimeout returns a middleware which returns error (503 Service Unavailable error) to client // when underlying method returns context.DeadlineExceeded error. func ContextTimeout(timeout time.Duration) echo.MiddlewareFunc { return ContextTimeoutWithConfig(ContextTimeoutConfig{Timeout: timeout}) } // ContextTimeoutWithConfig returns a Timeout middleware with config. func ContextTimeoutWithConfig(config ContextTimeoutConfig) echo.MiddlewareFunc { mw, err := config.ToMiddleware() if err != nil { panic(err) } return mw } // ToMiddleware converts Config to middleware. func (config ContextTimeoutConfig) ToMiddleware() (echo.MiddlewareFunc, error) { if config.Timeout == 0 { return nil, errors.New("timeout must be set") } if config.Skipper == nil { config.Skipper = DefaultSkipper } if config.ErrorHandler == nil { config.ErrorHandler = func(err error, c echo.Context) error { if err != nil && errors.Is(err, context.DeadlineExceeded) { return echo.ErrServiceUnavailable.WithInternal(err) } return err } } return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { if config.Skipper(c) { return next(c) } timeoutContext, cancel := context.WithTimeout(c.Request().Context(), config.Timeout) defer cancel() c.SetRequest(c.Request().WithContext(timeoutContext)) if err := next(c); err != nil { return config.ErrorHandler(err, c) } return nil } }, nil }
go
MIT
482bb46fe5c7eb7c9fd7bec7d3128433dea21bee
2026-01-07T08:36:24.147689Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/pubsub/wire.go
pubsub/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package pubsub import ( "github.com/go-redis/redis/v8" "github.com/google/wire" ) var WireSet = wire.NewSet( ProvidePubSub, ) func ProvidePubSub(config Config, client redis.UniversalClient) PubSub { switch config.Provider { case ProviderRedis: return NewRedis(client, WithApp(config.App), WithNamespace(config.Namespace), WithHealthCheckInterval(config.HealthInterval), WithSendTimeout(config.SendTimeout), WithSize(config.ChannelSize), ) case ProviderMemory: fallthrough default: return NewInMemory( WithApp(config.App), WithNamespace(config.Namespace), WithHealthCheckInterval(config.HealthInterval), WithSendTimeout(config.SendTimeout), WithSize(config.ChannelSize), ) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/pubsub/pubsub.go
pubsub/pubsub.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package pubsub import "context" type Publisher interface { // Publish topic to message broker with payload. Publish(ctx context.Context, topic string, payload []byte, options ...PublishOption) error } type PubSub interface { Publisher // Subscribe consumer to process the topic with payload, this should be // blocking operation. Subscribe(ctx context.Context, topic string, handler func(payload []byte) error, options ...SubscribeOption) Consumer } type Consumer interface { Subscribe(ctx context.Context, topics ...string) error Unsubscribe(ctx context.Context, topics ...string) error Close() error }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/pubsub/redis.go
pubsub/redis.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package pubsub import ( "context" "fmt" "strings" "sync" "time" "github.com/go-redis/redis/v8" "github.com/rs/zerolog/log" ) type Redis struct { config Config client redis.UniversalClient mutex sync.RWMutex registry []Consumer } // NewRedis create an instance of redis PubSub implementation. func NewRedis(client redis.UniversalClient, options ...Option) *Redis { config := Config{ App: "app", Namespace: "default", HealthInterval: 3 * time.Second, SendTimeout: 60, ChannelSize: 100, } for _, f := range options { f.Apply(&config) } return &Redis{ config: config, client: client, registry: make([]Consumer, 0, 16), } } // Subscribe consumer to process the event with payload. func (r *Redis) Subscribe( ctx context.Context, topic string, handler func(payload []byte) error, options ...SubscribeOption, ) Consumer { r.mutex.Lock() defer r.mutex.Unlock() config := SubscribeConfig{ topics: make([]string, 0, 8), app: r.config.App, namespace: r.config.Namespace, healthInterval: r.config.HealthInterval, sendTimeout: r.config.SendTimeout, channelSize: r.config.ChannelSize, } for _, f := range options { f.Apply(&config) } // create subscriber and map it to the registry subscriber := &redisSubscriber{ config: &config, handler: handler, } config.topics = append(config.topics, topic) topics := subscriber.formatTopics(config.topics...) subscriber.rdb = r.client.Subscribe(ctx, topics...) // start subscriber go subscriber.start(ctx) // register subscriber r.registry = append(r.registry, subscriber) return subscriber } // Publish event topic to message broker with payload. func (r *Redis) Publish(ctx context.Context, topic string, payload []byte, opts ...PublishOption) error { pubConfig := PublishConfig{ app: r.config.App, namespace: r.config.Namespace, } for _, f := range opts { f.Apply(&pubConfig) } topic = formatTopic(pubConfig.app, pubConfig.namespace, topic) err := r.client.Publish(ctx, topic, payload).Err() if err != nil { return fmt.Errorf("failed to write to pubsub topic '%s'. Error: %w", topic, err) } return nil } func (r *Redis) Close(_ context.Context) error { for _, subscriber := range r.registry { err := subscriber.Close() if err != nil { return err } } return nil } type redisSubscriber struct { config *SubscribeConfig rdb *redis.PubSub handler func([]byte) error } func (s *redisSubscriber) start(ctx context.Context) { // Go channel which receives messages. ch := s.rdb.Channel( redis.WithChannelHealthCheckInterval(s.config.healthInterval), redis.WithChannelSendTimeout(s.config.sendTimeout), redis.WithChannelSize(s.config.channelSize), ) for { select { case <-ctx.Done(): return case msg, ok := <-ch: if !ok { log.Ctx(ctx).Debug().Msg("redis channel was closed") return } if err := s.handler([]byte(msg.Payload)); err != nil { log.Ctx(ctx).Err(err).Msg("received an error from handler function") } } } } func (s *redisSubscriber) Subscribe(ctx context.Context, topics ...string) error { err := s.rdb.Subscribe(ctx, s.formatTopics(topics...)...) if err != nil { return fmt.Errorf("subscribe failed for chanels %v with error: %w", strings.Join(topics, ","), err) } return nil } func (s *redisSubscriber) Unsubscribe(ctx context.Context, topics ...string) error { err := s.rdb.Unsubscribe(ctx, s.formatTopics(topics...)...) if err != nil { return fmt.Errorf("unsubscribe failed for chanels %v with error: %w", strings.Join(topics, ","), err) } return nil } func (s *redisSubscriber) Close() error { err := s.rdb.Close() if err != nil { return fmt.Errorf("failed while closing subscriber with error: %w", err) } return nil } func (s *redisSubscriber) formatTopics(topics ...string) []string { result := make([]string, len(topics)) for i, topic := range topics { result[i] = formatTopic(s.config.app, s.config.namespace, topic) } return result }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/pubsub/config.go
pubsub/config.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package pubsub import "time" type Provider string const ( ProviderMemory Provider = "inmemory" ProviderRedis Provider = "redis" ) type Config struct { App string // app namespace prefix Namespace string Provider Provider HealthInterval time.Duration SendTimeout time.Duration ChannelSize int }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/pubsub/options.go
pubsub/options.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package pubsub import ( "time" ) // An Option configures a pubsub instance. type Option interface { Apply(*Config) } // OptionFunc is a function that configures a pubsub config. type OptionFunc func(*Config) // Apply calls f(config). func (f OptionFunc) Apply(config *Config) { f(config) } // WithApp returns an option that set config app name. func WithApp(value string) Option { return OptionFunc(func(m *Config) { m.App = value }) } // WithNamespace returns an option that set config namespace. func WithNamespace(value string) Option { return OptionFunc(func(m *Config) { m.Namespace = value }) } // WithHealthCheckInterval specifies the config health check interval. // PubSub will ping Server if it does not receive any messages // within the interval (redis, ...). // To disable health check, use zero interval. func WithHealthCheckInterval(value time.Duration) Option { return OptionFunc(func(m *Config) { m.HealthInterval = value }) } // WithSendTimeout specifies the pubsub send timeout after which // the message is dropped. func WithSendTimeout(value time.Duration) Option { return OptionFunc(func(m *Config) { m.SendTimeout = value }) } // WithSize specifies the Go chan size in config that is used to buffer // incoming messages. func WithSize(value int) Option { return OptionFunc(func(m *Config) { m.ChannelSize = value }) } type SubscribeConfig struct { topics []string app string namespace string healthInterval time.Duration sendTimeout time.Duration channelSize int } // SubscribeOption configures a subscription config. type SubscribeOption interface { Apply(*SubscribeConfig) } // SubscribeOptionFunc is a function that configures a subscription config. type SubscribeOptionFunc func(*SubscribeConfig) // Apply calls f(subscribeConfig). func (f SubscribeOptionFunc) Apply(config *SubscribeConfig) { f(config) } // WithTopics specifies the topics to subsribe. func WithTopics(topics ...string) SubscribeOption { return SubscribeOptionFunc(func(c *SubscribeConfig) { c.topics = topics }) } // WithNamespace returns an channel option that configures namespace. func WithChannelNamespace(value string) SubscribeOption { return SubscribeOptionFunc(func(c *SubscribeConfig) { c.namespace = value }) } // WithChannelHealthCheckInterval specifies the channel health check interval. // PubSub will ping Server if it does not receive any messages // within the interval. To disable health check, use zero interval. func WithChannelHealthCheckInterval(value time.Duration) SubscribeOption { return SubscribeOptionFunc(func(c *SubscribeConfig) { c.healthInterval = value }) } // WithChannelSendTimeout specifies the channel send timeout after which // the message is dropped. func WithChannelSendTimeout(value time.Duration) SubscribeOption { return SubscribeOptionFunc(func(c *SubscribeConfig) { c.sendTimeout = value }) } // WithChannelSize specifies the Go chan size that is used to buffer // incoming messages for subscriber. func WithChannelSize(value int) SubscribeOption { return SubscribeOptionFunc(func(c *SubscribeConfig) { c.channelSize = value }) } type PublishConfig struct { app string namespace string } type PublishOption interface { Apply(*PublishConfig) } // PublishOptionFunc is a function that configures a publish config. type PublishOptionFunc func(*PublishConfig) // Apply calls f(publishConfig). func (f PublishOptionFunc) Apply(config *PublishConfig) { f(config) } // WithPublishApp modifies publish config app identifier. func WithPublishApp(value string) PublishOption { return PublishOptionFunc(func(c *PublishConfig) { c.app = value }) } // WithPublishNamespace modifies publish config namespace. func WithPublishNamespace(value string) PublishOption { return PublishOptionFunc(func(c *PublishConfig) { c.namespace = value }) } func formatTopic(app, ns, topic string) string { return app + ":" + ns + ":" + topic }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/pubsub/inmem.go
pubsub/inmem.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package pubsub import ( "context" "errors" "sync" "time" "github.com/rs/zerolog/log" "golang.org/x/exp/slices" ) var ( ErrClosed = errors.New("pubsub: subscriber is closed") ) type InMemory struct { config Config mutex sync.Mutex registry []*inMemorySubscriber } // NewInMemory create an instance of memory pubsub implementation. func NewInMemory(options ...Option) *InMemory { config := Config{ App: "app", Namespace: "default", HealthInterval: 3 * time.Second, SendTimeout: 60, ChannelSize: 100, } for _, f := range options { f.Apply(&config) } return &InMemory{ config: config, registry: make([]*inMemorySubscriber, 0, 16), } } // Subscribe consumer to process the event with payload. func (r *InMemory) Subscribe( ctx context.Context, topic string, handler func(payload []byte) error, options ...SubscribeOption, ) Consumer { r.mutex.Lock() defer r.mutex.Unlock() config := SubscribeConfig{ topics: make([]string, 0, 8), app: r.config.App, namespace: r.config.Namespace, sendTimeout: r.config.SendTimeout, channelSize: r.config.ChannelSize, } for _, f := range options { f.Apply(&config) } // create subscriber and map it to the registry subscriber := &inMemorySubscriber{ config: &config, handler: handler, } config.topics = append(config.topics, topic) subscriber.topics = subscriber.formatTopics(config.topics...) // start subscriber go subscriber.start(ctx) // register subscriber r.registry = append(r.registry, subscriber) return subscriber } // Publish event to message broker with payload. func (r *InMemory) Publish(ctx context.Context, topic string, payload []byte, opts ...PublishOption) error { if len(r.registry) == 0 { log.Ctx(ctx).Warn().Msg("in pubsub Publish: no subscribers registered") return nil } pubConfig := PublishConfig{ app: r.config.App, namespace: r.config.Namespace, } for _, f := range opts { f.Apply(&pubConfig) } topic = formatTopic(pubConfig.app, pubConfig.namespace, topic) wg := sync.WaitGroup{} for _, sub := range r.registry { if slices.Contains(sub.topics, topic) && !sub.isClosed() { wg.Add(1) go func(subscriber *inMemorySubscriber) { defer wg.Done() // timer is based on subscriber data t := time.NewTimer(subscriber.config.sendTimeout) defer t.Stop() select { case <-ctx.Done(): return case subscriber.channel <- payload: log.Ctx(ctx).Trace().Msgf("in pubsub Publish: message %v sent to topic %s", string(payload), topic) case <-t.C: // channel is full for topic (message is dropped) log.Ctx(ctx).Warn().Msgf("in pubsub Publish: %s topic is full for %s (message is dropped)", topic, subscriber.config.sendTimeout) } }(sub) } } // Wait for all subscribers to complete // Otherwise, we might fail notifying some subscribers due to context completion. wg.Wait() return nil } func (r *InMemory) Close(_ context.Context) error { for _, subscriber := range r.registry { if err := subscriber.Close(); err != nil { return err } } return nil } type inMemorySubscriber struct { config *SubscribeConfig handler func([]byte) error channel chan []byte once sync.Once mutex sync.RWMutex topics []string closed bool } func (s *inMemorySubscriber) start(ctx context.Context) { s.channel = make(chan []byte, s.config.channelSize) for { select { case <-ctx.Done(): return case msg, ok := <-s.channel: if !ok { return } if err := s.handler(msg); err != nil { // TODO: bump err to caller log.Ctx(ctx).Err(err).Msgf("in pubsub start: error while running handler for topic") } } } } func (s *inMemorySubscriber) Subscribe(_ context.Context, topics ...string) error { s.mutex.RLock() defer s.mutex.RUnlock() topics = s.formatTopics(topics...) for _, ch := range topics { if slices.Contains(s.topics, ch) { continue } s.topics = append(s.topics, ch) } return nil } func (s *inMemorySubscriber) Unsubscribe(_ context.Context, topics ...string) error { s.mutex.RLock() defer s.mutex.RUnlock() topics = s.formatTopics(topics...) for i, ch := range topics { if slices.Contains(s.topics, ch) { s.topics[i] = s.topics[len(s.topics)-1] s.topics = s.topics[:len(s.topics)-1] } } return nil } func (s *inMemorySubscriber) Close() error { s.mutex.Lock() defer s.mutex.Unlock() if s.closed { return ErrClosed } s.closed = true s.once.Do(func() { close(s.channel) }) return nil } func (s *inMemorySubscriber) isClosed() bool { s.mutex.Lock() defer s.mutex.Unlock() return s.closed } func (s *inMemorySubscriber) formatTopics(topics ...string) []string { result := make([]string, len(topics)) for i, topic := range topics { result[i] = formatTopic(s.config.app, s.config.namespace, topic) } return result }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/profiler/noopprofiler.go
profiler/noopprofiler.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package profiler import "github.com/rs/zerolog/log" type NoopProfiler struct { } func (noopProfiler *NoopProfiler) StartProfiling(serviceName, serviceVersion string) { log.Info().Msgf("Not starting profiler for service '%s' with version '%s'", serviceName, serviceVersion) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/profiler/profiler.go
profiler/profiler.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package profiler import ( "fmt" "strings" ) type Profiler interface { StartProfiling(serviceName, serviceVersion string) } type Type string const ( TypeGCP Type = "gcp" ) func ParseType(profilerType string) (Type, bool) { switch strings.ToLower(strings.TrimSpace(profilerType)) { case string(TypeGCP): return TypeGCP, true default: return "", false } } func New(profiler Type) (Profiler, error) { switch profiler { case TypeGCP: return &GCPProfiler{}, nil default: return &NoopProfiler{}, fmt.Errorf("profiler '%s' not supported", profiler) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/profiler/gcpprofiler.go
profiler/gcpprofiler.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package profiler import ( "cloud.google.com/go/profiler" "github.com/rs/zerolog/log" ) type GCPProfiler struct { } func (gcpProfiler *GCPProfiler) StartProfiling(serviceName, serviceVersion string) { // Need to add env/namespace with service name to uniquely identify this cfg := profiler.Config{ Service: serviceName, ServiceVersion: serviceVersion, } if err := profiler.Start(cfg); err != nil { log.Warn().Err(err).Msg("unable to start profiler") } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/profiler/profiler_test.go
profiler/profiler_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package profiler import ( "testing" "github.com/stretchr/testify/assert" ) func TestParseType(t *testing.T) { var tests = []struct { raw string expectedType Type expectedOk bool }{ // basic invalid tests {"", Type(""), false}, {"a", Type(""), false}, {"g cp", Type(""), false}, // ensure case insensitivity {"gcp", TypeGCP, true}, {"GCP", TypeGCP, true}, // ensure trim space works {" gcp ", TypeGCP, true}, {" GCP ", TypeGCP, true}, // testing all valid values {"gcp", TypeGCP, true}, } for i, test := range tests { parsedType, ok := ParseType(test.raw) assert.Equal(t, test.expectedOk, ok, "test case %d with input '%s'", i, test.raw) assert.Equal(t, test.expectedType, parsedType, "test case %d with input '%s'", i, test.raw) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/cmd/gitness/wire.go
cmd/gitness/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build wireinject // +build wireinject package main import ( "context" checkcontroller "github.com/harness/gitness/app/api/controller/check" "github.com/harness/gitness/app/api/controller/connector" "github.com/harness/gitness/app/api/controller/execution" githookCtrl "github.com/harness/gitness/app/api/controller/githook" gitspaceCtrl "github.com/harness/gitness/app/api/controller/gitspace" infraproviderCtrl "github.com/harness/gitness/app/api/controller/infraprovider" controllerkeywordsearch "github.com/harness/gitness/app/api/controller/keywordsearch" "github.com/harness/gitness/app/api/controller/lfs" "github.com/harness/gitness/app/api/controller/limiter" controllerlogs "github.com/harness/gitness/app/api/controller/logs" "github.com/harness/gitness/app/api/controller/migrate" "github.com/harness/gitness/app/api/controller/pipeline" "github.com/harness/gitness/app/api/controller/plugin" "github.com/harness/gitness/app/api/controller/principal" "github.com/harness/gitness/app/api/controller/pullreq" "github.com/harness/gitness/app/api/controller/repo" "github.com/harness/gitness/app/api/controller/reposettings" "github.com/harness/gitness/app/api/controller/secret" "github.com/harness/gitness/app/api/controller/service" "github.com/harness/gitness/app/api/controller/serviceaccount" "github.com/harness/gitness/app/api/controller/space" "github.com/harness/gitness/app/api/controller/system" "github.com/harness/gitness/app/api/controller/template" controllertrigger "github.com/harness/gitness/app/api/controller/trigger" "github.com/harness/gitness/app/api/controller/upload" "github.com/harness/gitness/app/api/controller/user" "github.com/harness/gitness/app/api/controller/usergroup" controllerwebhook "github.com/harness/gitness/app/api/controller/webhook" "github.com/harness/gitness/app/api/openapi" "github.com/harness/gitness/app/auth/authn" "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/bootstrap" connectorservice "github.com/harness/gitness/app/connector" aitaskevent "github.com/harness/gitness/app/events/aitask" checkevents "github.com/harness/gitness/app/events/check" gitevents "github.com/harness/gitness/app/events/git" gitspaceevents "github.com/harness/gitness/app/events/gitspace" gitspacedeleteevents "github.com/harness/gitness/app/events/gitspacedelete" gitspaceinfraevents "github.com/harness/gitness/app/events/gitspaceinfra" gitspaceoperationsevents "github.com/harness/gitness/app/events/gitspaceoperations" pipelineevents "github.com/harness/gitness/app/events/pipeline" pullreqevents "github.com/harness/gitness/app/events/pullreq" repoevents "github.com/harness/gitness/app/events/repo" ruleevents "github.com/harness/gitness/app/events/rule" userevents "github.com/harness/gitness/app/events/user" infrastructure "github.com/harness/gitness/app/gitspace/infrastructure" "github.com/harness/gitness/app/gitspace/logutil" "github.com/harness/gitness/app/gitspace/orchestrator" containerorchestrator "github.com/harness/gitness/app/gitspace/orchestrator/container" "github.com/harness/gitness/app/gitspace/orchestrator/ide" "github.com/harness/gitness/app/gitspace/orchestrator/runarg" "github.com/harness/gitness/app/gitspace/platformconnector" "github.com/harness/gitness/app/gitspace/platformsecret" "github.com/harness/gitness/app/gitspace/scm" gitspacesecret "github.com/harness/gitness/app/gitspace/secret" "github.com/harness/gitness/app/pipeline/canceler" "github.com/harness/gitness/app/pipeline/commit" "github.com/harness/gitness/app/pipeline/converter" "github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/app/pipeline/manager" "github.com/harness/gitness/app/pipeline/resolver" "github.com/harness/gitness/app/pipeline/runner" "github.com/harness/gitness/app/pipeline/scheduler" "github.com/harness/gitness/app/pipeline/triggerer" "github.com/harness/gitness/app/router" "github.com/harness/gitness/app/server" "github.com/harness/gitness/app/services" "github.com/harness/gitness/app/services/branch" "github.com/harness/gitness/app/services/cleanup" "github.com/harness/gitness/app/services/codecomments" "github.com/harness/gitness/app/services/codeowners" "github.com/harness/gitness/app/services/exporter" gitspacedeleteeventservice "github.com/harness/gitness/app/services/gitspacedeleteevent" "github.com/harness/gitness/app/services/gitspaceevent" "github.com/harness/gitness/app/services/gitspaceservice" "github.com/harness/gitness/app/services/gitspacesettings" "github.com/harness/gitness/app/services/importer" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/app/services/keyfetcher" "github.com/harness/gitness/app/services/keywordsearch" svclabel "github.com/harness/gitness/app/services/label" locker "github.com/harness/gitness/app/services/locker" "github.com/harness/gitness/app/services/metric" migrateservice "github.com/harness/gitness/app/services/migrate" "github.com/harness/gitness/app/services/notification" "github.com/harness/gitness/app/services/notification/mailer" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/app/services/publicaccess" "github.com/harness/gitness/app/services/publickey" pullreqservice "github.com/harness/gitness/app/services/pullreq" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/services/remoteauth" reposervice "github.com/harness/gitness/app/services/repo" "github.com/harness/gitness/app/services/rules" secretservice "github.com/harness/gitness/app/services/secret" "github.com/harness/gitness/app/services/settings" spaceSvc "github.com/harness/gitness/app/services/space" "github.com/harness/gitness/app/services/tokengenerator" "github.com/harness/gitness/app/services/trigger" "github.com/harness/gitness/app/services/usage" usergroupservice "github.com/harness/gitness/app/services/usergroup" "github.com/harness/gitness/app/services/webhook" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" "github.com/harness/gitness/app/store/cache" "github.com/harness/gitness/app/store/database" "github.com/harness/gitness/app/store/logs" "github.com/harness/gitness/app/url" "github.com/harness/gitness/audit" "github.com/harness/gitness/blob" cliserver "github.com/harness/gitness/cli/operations/server" "github.com/harness/gitness/encrypt" "github.com/harness/gitness/events" "github.com/harness/gitness/git" "github.com/harness/gitness/git/api" "github.com/harness/gitness/git/storage" infraproviderpkg "github.com/harness/gitness/infraprovider" "github.com/harness/gitness/job" "github.com/harness/gitness/livelog" "github.com/harness/gitness/lock" "github.com/harness/gitness/pubsub" registryevents "github.com/harness/gitness/registry/app/events/artifact" registrypostporcessingevents "github.com/harness/gitness/registry/app/events/asyncprocessing" replicationevents "github.com/harness/gitness/registry/app/events/replication" registryhelpers "github.com/harness/gitness/registry/app/helpers" "github.com/harness/gitness/registry/app/pkg/docker" cargoutils "github.com/harness/gitness/registry/app/utils/cargo" gopackageutils "github.com/harness/gitness/registry/app/utils/gopackage" registryhandlers "github.com/harness/gitness/registry/job" registryindex "github.com/harness/gitness/registry/services/asyncprocessing" registrywebhooks "github.com/harness/gitness/registry/services/webhook" "github.com/harness/gitness/ssh" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" "github.com/google/wire" ) func initSystem(ctx context.Context, config *types.Config) (*cliserver.System, error) { wire.Build( cliserver.NewSystem, cliserver.ProvideRedis, bootstrap.WireSet, cliserver.ProvideDatabaseConfig, database.WireSet, cliserver.ProvideBlobStoreConfig, mailer.WireSet, notification.WireSet, blob.WireSet, dbtx.WireSet, cache.WireSetSpace, cache.WireSetRepo, refcache.WireSet, router.WireSet, pullreqservice.WireSet, services.WireSet, services.ProvideGitspaceServices, server.WireSet, url.WireSet, spaceSvc.WireSet, space.WireSet, limiter.WireSet, publicaccess.WireSet, repo.WireSet, reposettings.WireSet, pullreq.WireSet, controllerwebhook.WireSet, controllerwebhook.ProvidePreprocessor, svclabel.WireSet, serviceaccount.WireSet, user.WireSet, upload.WireSet, service.WireSet, principal.WireSet, usergroupservice.WireSet, system.WireSet, authn.WireSet, authz.WireSet, infrastructure.WireSet, infraproviderpkg.WireSet, gitspaceevents.WireSet, pipelineevents.WireSet, infraproviderCtrl.WireSet, gitspaceCtrl.WireSet, gitevents.WireSet, pullreqevents.WireSet, repoevents.WireSet, ruleevents.WireSet, userevents.WireSet, storage.WireSet, api.WireSet, cliserver.ProvideGitConfig, git.WireSet, store.WireSet, check.WireSet, encrypt.WireSet, cliserver.ProvideEventsConfig, events.WireSet, cliserver.ProvideWebhookConfig, cliserver.ProvideNotificationConfig, webhook.WireSet, cliserver.ProvideTriggerConfig, trigger.WireSet, tokengenerator.WireSet, githookCtrl.ExtenderWireSet, githookCtrl.WireSet, cliserver.ProvideLockConfig, lock.WireSet, locker.WireSet, cliserver.ProvidePubsubConfig, pubsub.WireSet, cliserver.ProvideJobsConfig, job.WireSet, cliserver.ProvideCleanupConfig, cleanup.WireSet, codecomments.WireSet, protection.WireSet, checkcontroller.WireSet, execution.WireSet, pipeline.WireSet, logs.WireSet, livelog.WireSet, controllerlogs.WireSet, secret.WireSet, connector.WireSet, connectorservice.WireSet, template.WireSet, manager.WireSet, triggerer.WireSet, file.WireSet, converter.WireSet, runner.WireSet, sse.WireSet, scheduler.WireSet, commit.WireSet, controllertrigger.WireSet, plugin.WireSet, resolver.WireSet, importer.WireSet, importer.ProvideConnectorService, migrateservice.WireSet, canceler.WireSet, exporter.WireSet, metric.WireSet, reposervice.WireSet, cliserver.ProvideCodeOwnerConfig, codeowners.WireSet, gitspaceevent.WireSet, cliserver.ProvideKeywordSearchConfig, keywordsearch.WireSet, rules.WireSet, rules.ProvideValidator, controllerkeywordsearch.WireSet, settings.WireSet, usergroup.WireSet, openapi.WireSet, repo.ProvideRepoCheck, audit.WireSet, ssh.WireSet, publickey.WireSet, keyfetcher.ProvideService, remoteauth.WireSet, migrate.WireSet, scm.WireSet, platformconnector.WireSet, platformsecret.WireSet, gitspacesecret.WireSet, orchestrator.WireSet, containerorchestrator.WireSet, cliserver.ProvideIDEVSCodeWebConfig, cliserver.ProvideDockerConfig, cliserver.ProvideGitspaceEventConfig, cliserver.ProvideGitspaceDeleteEventConfig, logutil.WireSet, cliserver.ProvideGitspaceOrchestratorConfig, ide.WireSet, gitspaceinfraevents.WireSet, aitaskevent.WireSet, gitspaceservice.WireSet, gitspacesettings.WireSet, gitspaceoperationsevents.WireSet, cliserver.ProvideGitspaceInfraProvisionerConfig, cliserver.ProvideIDEVSCodeConfig, cliserver.ProvideIDECursorConfig, cliserver.ProvideIDEWindsurfConfig, cliserver.ProvideIDEJetBrainsConfig, instrument.WireSet, docker.ProvideReporter, secretservice.WireSet, runarg.WireSet, lfs.WireSet, usage.WireSet, registryevents.WireSet, registrywebhooks.WireSet, gitspacedeleteevents.WireSet, gitspacedeleteeventservice.WireSet, registryindex.WireSet, cliserver.ProvideBranchConfig, branch.WireSet, cargoutils.WireSet, gopackageutils.WireSet, registrypostporcessingevents.ProvideAsyncProcessingReporter, registrypostporcessingevents.ProvideReaderFactory, checkevents.WireSet, registryhelpers.WireSet, replicationevents.ProvideNoOpReplicationReporter, registryhandlers.WireSet, ) return &cliserver.System{}, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/cmd/gitness/driver_sqlite.go
cmd/gitness/driver_sqlite.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !nosqlite // +build !nosqlite package main import ( _ "github.com/mattn/go-sqlite3" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/cmd/gitness/wire_gen.go
cmd/gitness/wire_gen.go
// Code generated by Wire. DO NOT EDIT. //go:generate go run -mod=mod github.com/google/wire/cmd/wire //go:build !wireinject // +build !wireinject package main import ( "context" check2 "github.com/harness/gitness/app/api/controller/check" connector2 "github.com/harness/gitness/app/api/controller/connector" "github.com/harness/gitness/app/api/controller/execution" "github.com/harness/gitness/app/api/controller/githook" gitspace2 "github.com/harness/gitness/app/api/controller/gitspace" infraprovider3 "github.com/harness/gitness/app/api/controller/infraprovider" keywordsearch2 "github.com/harness/gitness/app/api/controller/keywordsearch" "github.com/harness/gitness/app/api/controller/lfs" "github.com/harness/gitness/app/api/controller/limiter" logs2 "github.com/harness/gitness/app/api/controller/logs" migrate2 "github.com/harness/gitness/app/api/controller/migrate" "github.com/harness/gitness/app/api/controller/pipeline" "github.com/harness/gitness/app/api/controller/plugin" "github.com/harness/gitness/app/api/controller/principal" pullreq2 "github.com/harness/gitness/app/api/controller/pullreq" "github.com/harness/gitness/app/api/controller/repo" "github.com/harness/gitness/app/api/controller/reposettings" secret2 "github.com/harness/gitness/app/api/controller/secret" "github.com/harness/gitness/app/api/controller/service" "github.com/harness/gitness/app/api/controller/serviceaccount" space2 "github.com/harness/gitness/app/api/controller/space" "github.com/harness/gitness/app/api/controller/system" "github.com/harness/gitness/app/api/controller/template" "github.com/harness/gitness/app/api/controller/trigger" "github.com/harness/gitness/app/api/controller/upload" "github.com/harness/gitness/app/api/controller/user" usergroup2 "github.com/harness/gitness/app/api/controller/usergroup" webhook2 "github.com/harness/gitness/app/api/controller/webhook" "github.com/harness/gitness/app/api/openapi" "github.com/harness/gitness/app/auth/authn" "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/bootstrap" "github.com/harness/gitness/app/connector" events13 "github.com/harness/gitness/app/events/aitask" events12 "github.com/harness/gitness/app/events/check" events11 "github.com/harness/gitness/app/events/git" events5 "github.com/harness/gitness/app/events/gitspace" events8 "github.com/harness/gitness/app/events/gitspacedelete" events6 "github.com/harness/gitness/app/events/gitspaceinfra" events7 "github.com/harness/gitness/app/events/gitspaceoperations" events9 "github.com/harness/gitness/app/events/pipeline" events10 "github.com/harness/gitness/app/events/pullreq" events3 "github.com/harness/gitness/app/events/repo" events4 "github.com/harness/gitness/app/events/rule" events2 "github.com/harness/gitness/app/events/user" "github.com/harness/gitness/app/gitspace/infrastructure" "github.com/harness/gitness/app/gitspace/logutil" "github.com/harness/gitness/app/gitspace/orchestrator" "github.com/harness/gitness/app/gitspace/orchestrator/container" "github.com/harness/gitness/app/gitspace/orchestrator/ide" "github.com/harness/gitness/app/gitspace/orchestrator/runarg" "github.com/harness/gitness/app/gitspace/platformconnector" "github.com/harness/gitness/app/gitspace/platformsecret" "github.com/harness/gitness/app/gitspace/scm" "github.com/harness/gitness/app/gitspace/secret" "github.com/harness/gitness/app/pipeline/canceler" "github.com/harness/gitness/app/pipeline/commit" "github.com/harness/gitness/app/pipeline/converter" "github.com/harness/gitness/app/pipeline/file" "github.com/harness/gitness/app/pipeline/manager" "github.com/harness/gitness/app/pipeline/resolver" "github.com/harness/gitness/app/pipeline/runner" "github.com/harness/gitness/app/pipeline/scheduler" "github.com/harness/gitness/app/pipeline/triggerer" router2 "github.com/harness/gitness/app/router" server2 "github.com/harness/gitness/app/server" "github.com/harness/gitness/app/services" "github.com/harness/gitness/app/services/aitaskevent" "github.com/harness/gitness/app/services/branch" "github.com/harness/gitness/app/services/cleanup" "github.com/harness/gitness/app/services/codecomments" "github.com/harness/gitness/app/services/codeowners" "github.com/harness/gitness/app/services/exporter" "github.com/harness/gitness/app/services/gitspace" "github.com/harness/gitness/app/services/gitspacedeleteevent" "github.com/harness/gitness/app/services/gitspaceevent" "github.com/harness/gitness/app/services/gitspaceinfraevent" "github.com/harness/gitness/app/services/gitspaceoperationsevent" "github.com/harness/gitness/app/services/gitspacesettings" "github.com/harness/gitness/app/services/importer" infraprovider2 "github.com/harness/gitness/app/services/infraprovider" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/app/services/keyfetcher" "github.com/harness/gitness/app/services/keywordsearch" "github.com/harness/gitness/app/services/label" "github.com/harness/gitness/app/services/locker" "github.com/harness/gitness/app/services/metric" "github.com/harness/gitness/app/services/migrate" "github.com/harness/gitness/app/services/notification" "github.com/harness/gitness/app/services/notification/mailer" "github.com/harness/gitness/app/services/protection" "github.com/harness/gitness/app/services/publicaccess" "github.com/harness/gitness/app/services/publickey" "github.com/harness/gitness/app/services/pullreq" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/services/remoteauth" repo2 "github.com/harness/gitness/app/services/repo" "github.com/harness/gitness/app/services/rules" secret3 "github.com/harness/gitness/app/services/secret" "github.com/harness/gitness/app/services/settings" "github.com/harness/gitness/app/services/space" "github.com/harness/gitness/app/services/tokengenerator" trigger2 "github.com/harness/gitness/app/services/trigger" "github.com/harness/gitness/app/services/usage" "github.com/harness/gitness/app/services/usergroup" "github.com/harness/gitness/app/services/webhook" "github.com/harness/gitness/app/sse" "github.com/harness/gitness/app/store" "github.com/harness/gitness/app/store/cache" "github.com/harness/gitness/app/store/database" "github.com/harness/gitness/app/store/logs" "github.com/harness/gitness/app/url" "github.com/harness/gitness/audit" "github.com/harness/gitness/blob" "github.com/harness/gitness/cli/operations/server" "github.com/harness/gitness/encrypt" "github.com/harness/gitness/events" "github.com/harness/gitness/git" "github.com/harness/gitness/git/api" "github.com/harness/gitness/git/storage" "github.com/harness/gitness/infraprovider" "github.com/harness/gitness/job" "github.com/harness/gitness/livelog" "github.com/harness/gitness/lock" "github.com/harness/gitness/pubsub" api2 "github.com/harness/gitness/registry/app/api" cargo3 "github.com/harness/gitness/registry/app/api/controller/pkg/cargo" "github.com/harness/gitness/registry/app/api/controller/pkg/generic" gopackage2 "github.com/harness/gitness/registry/app/api/controller/pkg/gopackage" huggingface2 "github.com/harness/gitness/registry/app/api/controller/pkg/huggingface" npm2 "github.com/harness/gitness/registry/app/api/controller/pkg/npm" nuget2 "github.com/harness/gitness/registry/app/api/controller/pkg/nuget" python2 "github.com/harness/gitness/registry/app/api/controller/pkg/python" rpm2 "github.com/harness/gitness/registry/app/api/controller/pkg/rpm" huggingface3 "github.com/harness/gitness/registry/app/api/handler/huggingface" "github.com/harness/gitness/registry/app/api/router" "github.com/harness/gitness/registry/app/events/artifact" "github.com/harness/gitness/registry/app/events/asyncprocessing" "github.com/harness/gitness/registry/app/events/replication" "github.com/harness/gitness/registry/app/helpers" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" cargo2 "github.com/harness/gitness/registry/app/pkg/cargo" "github.com/harness/gitness/registry/app/pkg/docker" "github.com/harness/gitness/registry/app/pkg/filemanager" generic2 "github.com/harness/gitness/registry/app/pkg/generic" "github.com/harness/gitness/registry/app/pkg/gopackage" "github.com/harness/gitness/registry/app/pkg/huggingface" "github.com/harness/gitness/registry/app/pkg/maven" "github.com/harness/gitness/registry/app/pkg/npm" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/python" "github.com/harness/gitness/registry/app/pkg/quarantine" "github.com/harness/gitness/registry/app/pkg/rpm" publicaccess2 "github.com/harness/gitness/registry/app/services/publicaccess" refcache2 "github.com/harness/gitness/registry/app/services/refcache" cache2 "github.com/harness/gitness/registry/app/store/cache" database2 "github.com/harness/gitness/registry/app/store/database" "github.com/harness/gitness/registry/app/utils/cargo" gopackage3 "github.com/harness/gitness/registry/app/utils/gopackage" "github.com/harness/gitness/registry/gc" job2 "github.com/harness/gitness/registry/job" asyncprocessing2 "github.com/harness/gitness/registry/services/asyncprocessing" webhook3 "github.com/harness/gitness/registry/services/webhook" "github.com/harness/gitness/ssh" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types" "github.com/harness/gitness/types/check" _ "github.com/lib/pq" _ "github.com/mattn/go-sqlite3" ) // Injectors from wire.go: func initSystem(ctx context.Context, config *types.Config) (*server.System, error) { databaseConfig := server.ProvideDatabaseConfig(config) db, err := database.ProvideDatabase(ctx, databaseConfig) if err != nil { return nil, err } accessorTx := dbtx.ProvideAccessorTx(db) transactor := dbtx.ProvideTransactor(accessorTx) principalUID := check.ProvidePrincipalUIDCheck() spacePathTransformation := store.ProvidePathTransformation() spacePathStore := database.ProvideSpacePathStore(db, spacePathTransformation) pubsubConfig := server.ProvidePubsubConfig(config) universalClient, err := server.ProvideRedis(config) if err != nil { return nil, err } pubSub := pubsub.ProvidePubSub(pubsubConfig, universalClient) evictor := cache.ProvideEvictorSpaceCore(pubSub) spacePathCache := cache.ProvideSpacePathCache(ctx, spacePathStore, evictor, spacePathTransformation) spaceStore := database.ProvideSpaceStore(db, spacePathCache, spacePathStore) spaceIDCache := cache.ProvideSpaceIDCache(ctx, spaceStore, evictor) spaceFinder := refcache.ProvideSpaceFinder(spaceIDCache, spacePathCache, evictor) principalInfoView := database.ProvidePrincipalInfoView(db) principalInfoCache := cache.ProvidePrincipalInfoCache(principalInfoView) membershipStore := database.ProvideMembershipStore(db, principalInfoCache, spacePathStore, spaceStore) permissionCache := authz.ProvidePermissionCache(spaceFinder, membershipStore) publicAccessStore := database.ProvidePublicAccessStore(db) repoStore := database.ProvideRepoStore(db, spacePathCache, spacePathStore, spaceStore) cacheEvictor := cache.ProvideEvictorRepositoryCore(pubSub) repoIDCache := cache.ProvideRepoIDCache(ctx, repoStore, evictor, cacheEvictor) repoRefCache := cache.ProvideRepoRefCache(ctx, repoStore, evictor, cacheEvictor) repoFinder := refcache.ProvideRepoFinder(repoStore, spacePathCache, repoIDCache, repoRefCache, cacheEvictor) mediaTypesRepository := database2.ProvideMediaTypeDao(db) registryRepository := database2.ProvideRegistryDao(db, mediaTypesRepository) evictor2 := cache2.ProvideEvictorRegistryCore(pubSub) registryIDCache := cache2.ProvideRegistryIDCache(ctx, registryRepository, evictor2) registryRootRefCache := cache2.ProvideRegRootRefCache(ctx, registryRepository, evictor2) registryFinder := refcache2.ProvideRegistryFinder(registryRepository, registryIDCache, registryRootRefCache, evictor2, spaceFinder) publicaccessService := publicaccess.ProvidePublicAccess(config, publicAccessStore, spaceFinder, repoFinder, registryFinder) authorizer := authz.ProvideAuthorizer(permissionCache, spaceFinder, publicaccessService) principalUIDTransformation := store.ProvidePrincipalUIDTransformation() principalStore := database.ProvidePrincipalStore(db, principalUIDTransformation) tokenStore := database.ProvideTokenStore(db) publicKeyStore := database.ProvidePublicKeyStore(db) publicKeySubKeyStore := database.ProvidePublicKeySubKeyStore(db) gitSignatureResultStore := database.ProvideGitSignatureResultStore(db) eventsConfig := server.ProvideEventsConfig(config) eventsSystem, err := events.ProvideSystem(eventsConfig, universalClient) if err != nil { return nil, err } reporter, err := events2.ProvideReporter(eventsSystem) if err != nil { return nil, err } favoriteStore := database.ProvideFavoriteStore(db) controller := user.ProvideController(transactor, principalUID, authorizer, principalStore, tokenStore, membershipStore, publicKeyStore, publicKeySubKeyStore, gitSignatureResultStore, reporter, repoFinder, favoriteStore) serviceController := service.NewController(principalUID, authorizer, principalStore) bootstrapBootstrap := bootstrap.ProvideBootstrap(config, controller, serviceController) authenticator := authn.ProvideAuthenticator(config, principalStore, tokenStore) provider, err := url.ProvideURLProvider(config) if err != nil { return nil, err } linkedRepoStore := database.ProvideLinkRepoStore(db) pipelineStore := database.ProvidePipelineStore(db) executionStore := database.ProvideExecutionStore(db) ruleStore := database.ProvideRuleStore(db, principalInfoCache) checkStore := database.ProvideCheckStore(db, principalInfoCache) pullReqStore := database.ProvidePullReqStore(db, principalInfoCache) settingsStore := database.ProvideSettingsStore(db) settingsService := settings.ProvideService(settingsStore) protectionManager, err := protection.ProvideManager(ruleStore) if err != nil { return nil, err } typesConfig := server.ProvideGitConfig(config) cacheCache, err := api.ProvideLastCommitCache(typesConfig, universalClient) if err != nil { return nil, err } clientFactory := githook.ProvideFactory() apiGit, err := git.ProvideGITAdapter(typesConfig, cacheCache, clientFactory) if err != nil { return nil, err } storageStore := storage.ProvideLocalStore() gitInterface, err := git.ProvideService(typesConfig, apiGit, clientFactory, storageStore) if err != nil { return nil, err } encrypter, err := encrypt.ProvideEncrypter(config) if err != nil { return nil, err } jobStore := database.ProvideJobStore(db) executor := job.ProvideExecutor(jobStore, pubSub) lockConfig := server.ProvideLockConfig(config) mutexManager := lock.ProvideMutexManager(lockConfig, universalClient) jobConfig := server.ProvideJobsConfig(config) jobScheduler, err := job.ProvideScheduler(jobStore, executor, mutexManager, pubSub, jobConfig) if err != nil { return nil, err } triggerStore := database.ProvideTriggerStore(db) streamer := sse.ProvideEventsStreaming(pubSub) localIndexSearcher := keywordsearch.ProvideLocalIndexSearcher() indexer := keywordsearch.ProvideIndexer(localIndexSearcher) eventsReporter, err := events3.ProvideReporter(eventsSystem) if err != nil { return nil, err } auditService := audit.ProvideAuditService() importerImporter := importer.ProvideImporter(config, provider, gitInterface, transactor, repoStore, pipelineStore, triggerStore, repoFinder, streamer, indexer, publicaccessService, eventsReporter, auditService, settingsService) jobRepository, err := importer.ProvideJobRepositoryImport(encrypter, jobScheduler, executor, importerImporter) if err != nil { return nil, err } jobReferenceSync, err := importer.ProvideJobReferenceSync(config, provider, gitInterface, repoStore, repoFinder, jobScheduler, executor, indexer, eventsReporter) if err != nil { return nil, err } connectorService := importer.ProvideConnectorService() jobRepositoryLink, err := importer.ProvideJobRepositoryLink(ctx, config, jobScheduler, executor, provider, gitInterface, connectorService, repoStore, linkedRepoStore, repoFinder, streamer, indexer, eventsReporter) if err != nil { return nil, err } codeownersConfig := server.ProvideCodeOwnerConfig(config) usergroupResolver := usergroup.ProvideUserGroupResolver() codeownersService := codeowners.ProvideCodeOwners(gitInterface, repoStore, codeownersConfig, principalStore, usergroupResolver) resourceLimiter, err := limiter.ProvideLimiter() if err != nil { return nil, err } lockerLocker := locker.ProvideLocker(mutexManager) repoIdentifier := check.ProvideRepoIdentifierCheck() repoCheck := repo.ProvideRepoCheck() labelStore := database.ProvideLabelStore(db) labelValueStore := database.ProvideLabelValueStore(db) pullReqLabelAssignmentStore := database.ProvidePullReqLabelStore(db) labelService := label.ProvideLabel(transactor, spaceStore, labelStore, labelValueStore, pullReqLabelAssignmentStore, spaceFinder) instrumentService := instrument.ProvideService() userGroupStore := database.ProvideUserGroupStore(db) usergroupService := usergroup.ProvideService() reporter2, err := events4.ProvideReporter(eventsSystem) if err != nil { return nil, err } validator := rules.ProvideValidator() rulesService := rules.ProvideService(transactor, ruleStore, repoStore, spaceStore, protectionManager, auditService, instrumentService, principalInfoCache, userGroupStore, usergroupService, reporter2, streamer, validator, repoIDCache) lfsObjectStore := database.ProvideLFSObjectStore(db) blobConfig, err := server.ProvideBlobStoreConfig(config) if err != nil { return nil, err } blobStore, err := blob.ProvideStore(ctx, blobConfig) if err != nil { return nil, err } remoteauthService := remoteauth.ProvideRemoteAuth(tokenStore, principalStore) lfsController := lfs.ProvideController(authorizer, repoFinder, repoStore, principalStore, lfsObjectStore, blobStore, remoteauthService, provider, settingsService) keyfetcherService := keyfetcher.ProvideService(publicKeyStore) signatureVerifyService := publickey.ProvideSignatureVerifyService(principalStore, keyfetcherService, gitSignatureResultStore) repoController := repo.ProvideController(config, transactor, provider, authorizer, repoStore, linkedRepoStore, spaceStore, pipelineStore, principalStore, executionStore, ruleStore, checkStore, pullReqStore, settingsService, principalInfoCache, protectionManager, gitInterface, spaceFinder, repoFinder, jobRepository, jobReferenceSync, jobRepositoryLink, codeownersService, eventsReporter, indexer, resourceLimiter, lockerLocker, auditService, mutexManager, repoIdentifier, repoCheck, publicaccessService, labelService, instrumentService, userGroupStore, usergroupService, rulesService, streamer, lfsController, favoriteStore, signatureVerifyService, connectorService) reposettingsController := reposettings.ProvideController(authorizer, repoFinder, settingsService, auditService) stageStore := database.ProvideStageStore(db) schedulerScheduler, err := scheduler.ProvideScheduler(stageStore, mutexManager) if err != nil { return nil, err } stepStore := database.ProvideStepStore(db) cancelerCanceler := canceler.ProvideCanceler(executionStore, streamer, repoStore, schedulerScheduler, stageStore, stepStore) commitService := commit.ProvideService(gitInterface) fileService := file.ProvideService(gitInterface) converterService := converter.ProvideService(fileService, publicaccessService) templateStore := database.ProvideTemplateStore(db) pluginStore := database.ProvidePluginStore(db) triggererTriggerer := triggerer.ProvideTriggerer(executionStore, checkStore, stageStore, transactor, pipelineStore, fileService, converterService, schedulerScheduler, repoStore, provider, templateStore, pluginStore, publicaccessService) executionController := execution.ProvideController(transactor, authorizer, executionStore, checkStore, cancelerCanceler, commitService, triggererTriggerer, stageStore, pipelineStore, repoFinder) logStore := logs.ProvideLogStore(db, config) logStream := livelog.ProvideLogStream() logsController := logs2.ProvideController(authorizer, executionStore, pipelineStore, stageStore, stepStore, logStore, logStream, repoFinder) spaceIdentifier := check.ProvideSpaceIdentifierCheck() secretStore := database.ProvideSecretStore(db) connectorStore := database.ProvideConnectorStore(db, secretStore) listService := pullreq.ProvideListService(transactor, gitInterface, authorizer, spaceStore, pullReqStore, checkStore, repoFinder, labelService, protectionManager) repository, err := exporter.ProvideSpaceExporter(provider, gitInterface, repoStore, jobScheduler, executor, encrypter, streamer) if err != nil { return nil, err } infraProviderResourceView := database.ProvideInfraProviderResourceView(db, spaceStore) infraProviderResourceCache := cache.ProvideInfraProviderResourceCache(infraProviderResourceView) gitspaceConfigStore := database.ProvideGitspaceConfigStore(db, principalInfoCache, infraProviderResourceCache, spaceIDCache) gitspaceInstanceStore := database.ProvideGitspaceInstanceStore(db, spaceIDCache) reporter3, err := events5.ProvideReporter(eventsSystem) if err != nil { return nil, err } gitspaceEventStore := database.ProvideGitspaceEventStore(db) infraProviderResourceStore := database.ProvideInfraProviderResourceStore(db, spaceIDCache) infraProviderConfigStore := database.ProvideInfraProviderConfigStore(db, spaceIDCache) infraProviderTemplateStore := database.ProvideInfraProviderTemplateStore(db) dockerConfig, err := server.ProvideDockerConfig(config) if err != nil { return nil, err } dockerClientFactory := infraprovider.ProvideDockerClientFactory(dockerConfig) reporter4, err := events6.ProvideReporter(eventsSystem) if err != nil { return nil, err } dockerProvider := infraprovider.ProvideDockerProvider(dockerConfig, dockerClientFactory, reporter4) factory := infraprovider.ProvideFactory(dockerProvider) cdeGatewayStore := database.ProvideCDEGatewayStore(db) infraproviderService := infraprovider2.ProvideInfraProvider(transactor, gitspaceConfigStore, infraProviderResourceStore, infraProviderConfigStore, infraProviderTemplateStore, factory, spaceFinder, cdeGatewayStore) gitnessSCM := scm.ProvideGitnessSCM(repoStore, repoFinder, gitInterface, tokenStore, principalStore, provider) genericSCM := scm.ProvideGenericSCM() scmFactory := scm.ProvideFactory(gitnessSCM, genericSCM) scmSCM := scm.ProvideSCM(scmFactory) platformConnector := platformconnector.ProvideGitnessPlatformConnector() platformSecret := platformsecret.ProvideGitnessPlatformSecret() infraProvisionedStore := database.ProvideInfraProvisionedStore(db) infrastructureConfig := server.ProvideGitspaceInfraProvisionerConfig(config) infraProvisioner := infrastructure.ProvideInfraProvisionerService(infraProviderConfigStore, infraProviderResourceStore, factory, infraProviderTemplateStore, infraProvisionedStore, infrastructureConfig) statefulLogger := logutil.ProvideStatefulLogger(logStream) runargResolver, err := runarg.ProvideResolver() if err != nil { return nil, err } runargProvider, err := runarg.ProvideStaticProvider(runargResolver) if err != nil { return nil, err } reporter5, err := events7.ProvideReporter(eventsSystem) if err != nil { return nil, err } embeddedDockerOrchestrator := container.ProvideEmbeddedDockerOrchestrator(dockerClientFactory, statefulLogger, runargProvider, reporter5) containerFactory := container.ProvideContainerOrchestratorFactory(embeddedDockerOrchestrator) orchestratorConfig := server.ProvideGitspaceOrchestratorConfig(config) vsCodeConfig := server.ProvideIDEVSCodeConfig(config) vsCode := ide.ProvideVSCodeService(vsCodeConfig) vsCodeWebConfig := server.ProvideIDEVSCodeWebConfig(config) vsCodeWeb := ide.ProvideVSCodeWebService(vsCodeWebConfig) jetBrainsIDEConfig := server.ProvideIDEJetBrainsConfig(config) v := ide.ProvideJetBrainsIDEsService(jetBrainsIDEConfig) cursorConfig := server.ProvideIDECursorConfig(config) cursor := ide.ProvideCursorService(cursorConfig) windsurfConfig := server.ProvideIDEWindsurfConfig(config) windsurf := ide.ProvideWindsurfService(windsurfConfig) ideFactory := ide.ProvideIDEFactory(vsCode, vsCodeWeb, v, cursor, windsurf) passwordResolver := secret.ProvidePasswordResolver() resolverFactory := secret.ProvideResolverFactory(passwordResolver) gitspaceSettingsStore := database.ProvideGitspaceSettingsStore(db) gitspacesettingsService, err := gitspacesettings.ProvideService(ctx, gitspaceSettingsStore) if err != nil { return nil, err } orchestratorOrchestrator := orchestrator.ProvideOrchestrator(scmSCM, platformConnector, platformSecret, infraProvisioner, containerFactory, reporter3, orchestratorConfig, ideFactory, resolverFactory, gitspaceInstanceStore, gitspaceConfigStore, gitspacesettingsService, spaceStore, infraproviderService) reporter6, err := events8.ProvideReporter(eventsSystem) if err != nil { return nil, err } tokenGenerator := tokengenerator.ProvideTokenGenerator() gitspaceService := gitspace.ProvideGitspace(transactor, gitspaceConfigStore, gitspaceInstanceStore, reporter3, gitspaceEventStore, spaceFinder, infraproviderService, orchestratorOrchestrator, scmSCM, config, reporter6, ideFactory, spaceStore, tokenGenerator) usageMetricStore := database.ProvideUsageMetricStore(db) webhookStore := database.ProvideWebhookStore(db) spaceService, err := space.ProvideService(transactor, jobScheduler, executor, encrypter, repoStore, spaceStore, spacePathStore, labelStore, ruleStore, webhookStore, spaceFinder, gitspaceService, infraproviderService, repoController) if err != nil { return nil, err } spaceController := space2.ProvideController(config, transactor, provider, streamer, spaceIdentifier, authorizer, spacePathStore, pipelineStore, secretStore, connectorStore, templateStore, spaceStore, repoStore, principalStore, repoController, membershipStore, listService, spaceFinder, repoFinder, jobRepository, repository, resourceLimiter, publicaccessService, auditService, gitspaceService, labelService, instrumentService, executionStore, rulesService, usageMetricStore, repoIdentifier, infraproviderService, favoriteStore, spaceService) reporter7, err := events9.ProvideReporter(eventsSystem) if err != nil { return nil, err } pipelineController := pipeline.ProvideController(triggerStore, authorizer, pipelineStore, reporter7, repoFinder) secretController := secret2.ProvideController(encrypter, secretStore, authorizer, spaceFinder) triggerController := trigger.ProvideController(authorizer, triggerStore, pipelineStore, repoFinder) scmService := connector.ProvideSCMConnectorHandler(secretStore) service2 := connector.ProvideConnectorHandler(secretStore, scmService) connectorController := connector2.ProvideController(connectorStore, service2, authorizer, spaceFinder) templateController := template.ProvideController(templateStore, authorizer, spaceFinder) pluginController := plugin.ProvideController(pluginStore) pullReqActivityStore := database.ProvidePullReqActivityStore(db, principalInfoCache) codeCommentView := database.ProvideCodeCommentView(db) pullReqReviewStore := database.ProvidePullReqReviewStore(db) pullReqReviewerStore := database.ProvidePullReqReviewerStore(db, principalInfoCache) userGroupReviewerStore := database.ProvideUserGroupReviewerStore(db, principalInfoCache, userGroupStore) pullReqFileViewStore := database.ProvidePullReqFileViewStore(db) reporter8, err := events10.ProvideReporter(eventsSystem) if err != nil { return nil, err } migrator := codecomments.ProvideMigrator(gitInterface) readerFactory, err := events11.ProvideReaderFactory(eventsSystem) if err != nil { return nil, err } eventsReaderFactory, err := events10.ProvideReaderFactory(eventsSystem) if err != nil { return nil, err } pullreqService, err := pullreq.ProvideService(ctx, config, readerFactory, eventsReaderFactory, reporter8, gitInterface, repoFinder, repoStore, pullReqStore, pullReqActivityStore, principalInfoCache, codeCommentView, migrator, pullReqFileViewStore, pubSub, provider, streamer) if err != nil { return nil, err } pullReq := migrate.ProvidePullReqImporter(provider, gitInterface, principalStore, spaceStore, repoStore, pullReqStore, pullReqActivityStore, labelStore, labelValueStore, pullReqLabelAssignmentStore, pullReqReviewerStore, pullReqReviewStore, repoFinder, transactor, mutexManager) branchStore := database.ProvideBranchStore(db) pullreqController := pullreq2.ProvideController(transactor, provider, authorizer, auditService, pullReqStore, pullReqActivityStore, codeCommentView, pullReqReviewStore, pullReqReviewerStore, repoStore, principalStore, userGroupStore, userGroupReviewerStore, principalInfoCache, pullReqFileViewStore, membershipStore, checkStore, gitInterface, repoFinder, reporter8, migrator, pullreqService, listService, protectionManager, streamer, codeownersService, lockerLocker, pullReq, labelService, instrumentService, usergroupService, branchStore, usergroupResolver) webhookConfig := server.ProvideWebhookConfig(config) webhookExecutionStore := database.ProvideWebhookExecutionStore(db) urlProvider := webhook.ProvideURLProvider(ctx) secretService := secret3.ProvideSecretService(secretStore, encrypter, spaceFinder) webhookService, err := webhook.ProvideService(ctx, webhookConfig, transactor, readerFactory, eventsReaderFactory, webhookStore, webhookExecutionStore, spaceStore, repoStore, pullReqStore, pullReqActivityStore, provider, principalStore, gitInterface, encrypter, labelStore, urlProvider, labelValueStore, auditService, streamer, secretService, spacePathStore) if err != nil { return nil, err } preprocessor := webhook2.ProvidePreprocessor() webhookController := webhook2.ProvideController(authorizer, spaceFinder, repoFinder, webhookService, encrypter, preprocessor) reporter9, err := events11.ProvideReporter(eventsSystem) if err != nil { return nil, err } preReceiveExtender, err := githook.ProvidePreReceiveExtender() if err != nil { return nil, err } updateExtender, err := githook.ProvideUpdateExtender() if err != nil { return nil, err } postReceiveExtender, err := githook.ProvidePostReceiveExtender() if err != nil { return nil, err } githookController := githook.ProvideController(authorizer, principalStore, repoStore, repoFinder, reporter9, eventsReporter, gitInterface, pullReqStore, provider, protectionManager, clientFactory, resourceLimiter, settingsService, preReceiveExtender, updateExtender, postReceiveExtender, streamer, lfsObjectStore, auditService, usergroupService) serviceaccountController := serviceaccount.NewController(principalUID, authorizer, principalStore, spaceStore, repoStore, tokenStore) principalController := principal.ProvideController(principalStore, authorizer) usergroupController := usergroup2.ProvideController(userGroupStore, spaceStore, spaceFinder, authorizer, usergroupService) v2 := check2.ProvideCheckSanitizers() reporter10, err := events12.ProvideReporter(eventsSystem) if err != nil { return nil, err } checkController := check2.ProvideController(transactor, authorizer, spaceStore, checkStore, spaceFinder, repoFinder, gitInterface, v2, streamer, reporter10) systemController := system.NewController(principalStore, config) uploadController := upload.ProvideController(authorizer, repoFinder, blobStore, config) searcher := keywordsearch.ProvideSearcher(localIndexSearcher) keywordsearchController := keywordsearch2.ProvideController(authorizer, searcher, repoController, spaceController) infraproviderController := infraprovider3.ProvideController(authorizer, spaceFinder, infraproviderService) limiterGitspace := limiter.ProvideGitspaceLimiter() gitspaceController := gitspace2.ProvideController(transactor, authorizer, infraproviderService, spaceStore, spaceFinder, gitspaceEventStore, statefulLogger, scmSCM, gitspaceService, limiterGitspace, repoFinder, gitspacesettingsService) rule := migrate.ProvideRuleImporter(ruleStore, transactor, principalStore) migrateWebhook := migrate.ProvideWebhookImporter(webhookConfig, transactor, webhookStore) migrateLabel := migrate.ProvideLabelImporter(transactor, labelStore, labelValueStore, spaceStore) migrateController := migrate2.ProvideController(authorizer, publicaccessService, gitInterface, provider, pullReq, rule, migrateWebhook, migrateLabel, resourceLimiter, auditService, repoIdentifier, transactor, spaceStore, repoStore, spaceFinder, repoFinder, eventsReporter) openapiService := openapi.ProvideOpenAPIService() storageDriver, err := api2.BlobStorageProvider(ctx, config)
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
true
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/cmd/gitness/driver_pq.go
cmd/gitness/driver_pq.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( _ "github.com/lib/pq" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/cmd/gitness/main.go
cmd/gitness/main.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "github.com/harness/gitness/app/api/openapi" "github.com/harness/gitness/cli" "github.com/harness/gitness/cli/operations/account" "github.com/harness/gitness/cli/operations/hooks" "github.com/harness/gitness/cli/operations/migrate" "github.com/harness/gitness/cli/operations/server" "github.com/harness/gitness/cli/operations/swagger" "github.com/harness/gitness/cli/operations/user" "github.com/harness/gitness/cli/operations/users" "github.com/harness/gitness/version" "gopkg.in/alecthomas/kingpin.v2" ) const ( application = "gitness" description = "Gitness Open source edition" ) func main() { args := cli.GetArguments() app := kingpin.New(application, description) migrate.Register(app) server.Register(app, initSystem) user.Register(app) users.Register(app) account.RegisterLogin(app) account.RegisterRegister(app) account.RegisterLogout(app) hooks.Register(app) swagger.Register(app, openapi.NewOpenAPIService()) kingpin.Version(version.Version.String()) kingpin.MustParse(app.Parse(args)) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/pkg.go
app/pkg.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build tools // +build tools // following https://github.com/golang/go/wiki/Modules#how-can-i-track-tool-dependencies-for-a-module package pkg import ( _ "github.com/google/wire/cmd/wire" )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/wire.go
app/services/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package services import ( "github.com/harness/gitness/app/services/aitaskevent" "github.com/harness/gitness/app/services/branch" "github.com/harness/gitness/app/services/cleanup" "github.com/harness/gitness/app/services/gitspace" "github.com/harness/gitness/app/services/gitspacedeleteevent" "github.com/harness/gitness/app/services/gitspaceevent" "github.com/harness/gitness/app/services/gitspaceinfraevent" "github.com/harness/gitness/app/services/gitspaceoperationsevent" "github.com/harness/gitness/app/services/infraprovider" "github.com/harness/gitness/app/services/instrument" "github.com/harness/gitness/app/services/keywordsearch" "github.com/harness/gitness/app/services/metric" "github.com/harness/gitness/app/services/notification" "github.com/harness/gitness/app/services/pullreq" "github.com/harness/gitness/app/services/repo" "github.com/harness/gitness/app/services/trigger" "github.com/harness/gitness/app/services/webhook" "github.com/harness/gitness/job" "github.com/harness/gitness/registry/job/handler" registryasyncprocessing "github.com/harness/gitness/registry/services/asyncprocessing" registrywebhooks "github.com/harness/gitness/registry/services/webhook" "github.com/google/wire" ) var WireSet = wire.NewSet( ProvideServices, ) type Services struct { Webhook *webhook.Service PullReq *pullreq.Service Trigger *trigger.Service JobScheduler *job.Scheduler MetricCollector *metric.CollectorJob RepoSizeCalculator *repo.SizeCalculator Repo *repo.Service Cleanup *cleanup.Service Notification *notification.Service Keywordsearch *keywordsearch.Service GitspaceService *GitspaceServices Instrumentation instrument.Service instrumentConsumer instrument.Consumer instrumentRepoCounter *instrument.RepositoryCount registryWebhooksService *registrywebhooks.Service Branch *branch.Service registryAsyncProcessingService *registryasyncprocessing.Service } type GitspaceServices struct { GitspaceEvent *gitspaceevent.Service infraProvider *infraprovider.Service gitspace *gitspace.Service gitspaceInfraEventSvc *gitspaceinfraevent.Service gitspaceOperationsEventSvc *gitspaceoperationsevent.Service gitspaceDeleteEventSvc *gitspacedeleteevent.Service aiTaskEventSvc *aitaskevent.Service } func ProvideGitspaceServices( gitspaceEventSvc *gitspaceevent.Service, gitspaceDeleteEventSvc *gitspacedeleteevent.Service, infraProviderSvc *infraprovider.Service, gitspaceSvc *gitspace.Service, gitspaceInfraEventSvc *gitspaceinfraevent.Service, gitspaceOperationsEventSvc *gitspaceoperationsevent.Service, aiTaskEventSvc *aitaskevent.Service, ) *GitspaceServices { return &GitspaceServices{ GitspaceEvent: gitspaceEventSvc, infraProvider: infraProviderSvc, gitspace: gitspaceSvc, gitspaceInfraEventSvc: gitspaceInfraEventSvc, gitspaceOperationsEventSvc: gitspaceOperationsEventSvc, gitspaceDeleteEventSvc: gitspaceDeleteEventSvc, aiTaskEventSvc: aiTaskEventSvc, } } func ProvideServices( webhooksSvc *webhook.Service, pullReqSvc *pullreq.Service, triggerSvc *trigger.Service, jobScheduler *job.Scheduler, metricCollector *metric.CollectorJob, repoSizeCalculator *repo.SizeCalculator, repo *repo.Service, cleanupSvc *cleanup.Service, notificationSvc *notification.Service, keywordsearchSvc *keywordsearch.Service, gitspaceSvc *GitspaceServices, instrumentation instrument.Service, instrumentConsumer instrument.Consumer, instrumentRepoCounter *instrument.RepositoryCount, registryWebhooksService *registrywebhooks.Service, branchSvc *branch.Service, registryAsyncProcessingService *registryasyncprocessing.Service, registryJobRpmRegistryIndex *handler.JobRpmRegistryIndex, ) Services { return Services{ Webhook: webhooksSvc, PullReq: pullReqSvc, Trigger: triggerSvc, JobScheduler: jobScheduler, MetricCollector: metricCollector, RepoSizeCalculator: repoSizeCalculator, Repo: repo, Cleanup: cleanupSvc, Notification: notificationSvc, Keywordsearch: keywordsearchSvc, GitspaceService: gitspaceSvc, Instrumentation: instrumentation, instrumentConsumer: instrumentConsumer, instrumentRepoCounter: instrumentRepoCounter, registryWebhooksService: registryWebhooksService, Branch: branchSvc, registryAsyncProcessingService: registryAsyncProcessingService, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/publicaccess/wire.go
app/services/publicaccess/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package publicaccess import ( "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/store" registryrefcache "github.com/harness/gitness/registry/app/services/refcache" "github.com/harness/gitness/types" "github.com/google/wire" ) var WireSet = wire.NewSet( ProvidePublicAccess, ) func ProvidePublicAccess( config *types.Config, publicAccessStore store.PublicAccessStore, spaceFinder refcache.SpaceFinder, repoFinder refcache.RepoFinder, registryFinder registryrefcache.RegistryFinder, ) Service { return NewService(config.PublicResourceCreationEnabled, publicAccessStore, spaceFinder, repoFinder, registryFinder) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/publicaccess/resources.go
app/services/publicaccess/resources.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package publicaccess import ( "context" "fmt" "github.com/harness/gitness/app/paths" "github.com/harness/gitness/types/enum" ) func (s *service) getResourceID( ctx context.Context, resourceType enum.PublicResourceType, resourcePath string, ) (int64, error) { var id int64 var err error switch resourceType { case enum.PublicResourceTypeRepo: id, err = s.getResourceRepo(ctx, resourcePath) case enum.PublicResourceTypeSpace: id, err = s.getResourceSpace(ctx, resourcePath) case enum.PublicResourceTypeRegistry: id, err = s.getResourceRegistry(ctx, resourcePath) default: return 0, fmt.Errorf("invalid public resource type") } if err != nil { return 0, fmt.Errorf("failed to get public resource id: %w", err) } return id, nil } func (s *service) getResourceRepo( ctx context.Context, path string, ) (int64, error) { repo, err := s.repoFinder.FindByRef(ctx, path) if err != nil { return 0, fmt.Errorf("failed to find repo: %w", err) } return repo.ID, nil } func (s *service) getResourceSpace( ctx context.Context, path string, ) (int64, error) { space, err := s.spaceFinder.FindByRef(ctx, path) if err != nil { return 0, fmt.Errorf("failed to find space: %w", err) } return space.ID, nil } func (s *service) getResourceRegistry( ctx context.Context, path string, ) (int64, error) { rootRef, _, err := paths.DisectRoot(path) if err != nil { return 0, fmt.Errorf("failed to disect root from path: %w", err) } _, registryIdentifier, err := paths.DisectLeaf(path) if err != nil { return 0, fmt.Errorf("failed to disect leaf from path: %w", err) } repo, err := s.registryFinder.FindByRootRef(ctx, rootRef, registryIdentifier) if err != nil { return 0, fmt.Errorf("failed to find repo: %w", err) } return repo.ID, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/publicaccess/service.go
app/services/publicaccess/service.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package publicaccess import ( "context" "errors" "fmt" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/store" registryrefcache "github.com/harness/gitness/registry/app/services/refcache" gitness_store "github.com/harness/gitness/store" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) var _ Service = (*service)(nil) type service struct { publicResourceCreationEnabled bool publicAccessStore store.PublicAccessStore spaceFinder refcache.SpaceFinder repoFinder refcache.RepoFinder registryFinder registryrefcache.RegistryFinder } func NewService( publicResourceCreationEnabled bool, publicAccessStore store.PublicAccessStore, spaceFinder refcache.SpaceFinder, repoFinder refcache.RepoFinder, registryFinder registryrefcache.RegistryFinder, ) Service { return &service{ publicResourceCreationEnabled: publicResourceCreationEnabled, publicAccessStore: publicAccessStore, spaceFinder: spaceFinder, repoFinder: repoFinder, registryFinder: registryFinder, } } func (s *service) Get( ctx context.Context, resourceType enum.PublicResourceType, resourcePath string, ) (bool, error) { pubResID, err := s.getResourceID(ctx, resourceType, resourcePath) if err != nil { return false, fmt.Errorf("failed to get resource id: %w", err) } isPublic, err := s.publicAccessStore.Find(ctx, resourceType, pubResID) if err != nil { return false, fmt.Errorf("failed to get public access resource: %w", err) } return isPublic, nil } func (s *service) Set( ctx context.Context, resourceType enum.PublicResourceType, resourcePath string, enable bool, ) error { if enable && !s.publicResourceCreationEnabled { return ErrPublicAccessNotAllowed } pubResID, err := s.getResourceID(ctx, resourceType, resourcePath) if err != nil { return fmt.Errorf("failed to get resource id: %w", err) } if !enable { err = s.publicAccessStore.Delete(ctx, resourceType, pubResID) if err != nil { return fmt.Errorf("failed to disable resource's public access: %w", err) } return nil } err = s.publicAccessStore.Create(ctx, resourceType, pubResID) if errors.Is(err, gitness_store.ErrDuplicate) { log.Ctx(ctx).Warn().Msgf("%s %d is already set for public access", resourceType, pubResID) return nil } if err != nil { return fmt.Errorf("failed to enable resource's public access: %w", err) } return nil } func (s *service) Delete( ctx context.Context, resourceType enum.PublicResourceType, resourcePath string, ) error { // setting the value to false will remove it from the store. err := s.Set(ctx, resourceType, resourcePath, false) if errors.Is(err, gitness_store.ErrResourceNotFound) { return nil } return err } func (s *service) IsPublicAccessSupported(context.Context, enum.PublicResourceType, string) (bool, error) { return s.publicResourceCreationEnabled, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/publicaccess/public_access.go
app/services/publicaccess/public_access.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package publicaccess import ( "context" "errors" "github.com/harness/gitness/types/enum" ) var ( ErrPublicAccessNotAllowed = errors.New("public access is not allowed") ) // Service is an abstraction of an entity responsible for managing public access to resources. type Service interface { // Get returns whether public access is enabled on the resource. Get( ctx context.Context, resourceType enum.PublicResourceType, resourcePath string, ) (bool, error) // Sets the public access mode for the resource based on the value of 'enable'. Set( ctx context.Context, resourceType enum.PublicResourceType, resourcePath string, enable bool, ) error // Deletes any public access data stored for the resource. Delete( ctx context.Context, resourceType enum.PublicResourceType, resourcePath string, ) error // IsPublicAccessSupported return true iff public access is supported under the provided space. IsPublicAccessSupported( ctx context.Context, resourceType enum.PublicResourceType, parentSpacePath string, ) (bool, error) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/tokengenerator/wire.go
app/services/tokengenerator/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tokengenerator import ( "github.com/google/wire" ) var WireSet = wire.NewSet( ProvideTokenGenerator, ) func ProvideTokenGenerator() TokenGenerator { return NewNoopTokenGenerator() }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/tokengenerator/noop.go
app/services/tokengenerator/noop.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tokengenerator import ( "context" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type NoopTokenGenerator struct{} func NewNoopTokenGenerator() TokenGenerator { return NoopTokenGenerator{} } func (ntg NoopTokenGenerator) GenerateToken( _ context.Context, _ *types.GitspaceConfig, _ string, _ enum.PrincipalType, _ *types.InfraProviderConfig, ) (string, error) { return "", nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/tokengenerator/tokengenerator.go
app/services/tokengenerator/tokengenerator.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tokengenerator import ( "context" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" ) type TokenGenerator interface { GenerateToken( ctx context.Context, gitspaceConfig *types.GitspaceConfig, principalID string, principalType enum.PrincipalType, infraProviderConfig *types.InfraProviderConfig, ) (string, error) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/usergroup/wire.go
app/services/usergroup/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package usergroup import ( "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideUserGroupResolver, ProvideService, ) func ProvideUserGroupResolver() Resolver { return NewGitnessResolver() } func ProvideService() Service { return NewService() }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/usergroup/service.go
app/services/usergroup/service.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package usergroup import ( "context" "fmt" "github.com/harness/gitness/types" ) type service struct { } func NewService() Service { return &service{} } func (s *service) List( _ context.Context, _ *types.ListQueryFilter, _ *types.SpaceCore, ) ([]*types.UserGroupInfo, error) { return nil, fmt.Errorf("not implemented") } func (s *service) ListUserIDsByGroupIDs( _ context.Context, _ []int64, ) ([]int64, error) { return []int64{}, nil } func (s *service) MapGroupIDsToPrincipals( _ context.Context, _ []int64, ) (map[int64][]*types.Principal, error) { return map[int64][]*types.Principal{}, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/usergroup/resolver.go
app/services/usergroup/resolver.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package usergroup import ( "context" "github.com/harness/gitness/types" ) var _ Resolver = (*GitnessResolver)(nil) type GitnessResolver struct { } func NewGitnessResolver() *GitnessResolver { return &GitnessResolver{} } func (s *GitnessResolver) Resolve(context.Context, string) (*types.UserGroup, error) { // todo: implement once usergroup is supported return nil, ErrNotFound }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/usergroup/interface.go
app/services/usergroup/interface.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package usergroup import ( "context" "github.com/harness/gitness/types" ) type Service interface { List( ctx context.Context, filter *types.ListQueryFilter, space *types.SpaceCore, ) ([]*types.UserGroupInfo, error) ListUserIDsByGroupIDs( ctx context.Context, userGroupIDs []int64, ) ([]int64, error) MapGroupIDsToPrincipals( ctx context.Context, groupIDs []int64, ) (map[int64][]*types.Principal, error) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/usergroup/user_group_resolver.go
app/services/usergroup/user_group_resolver.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package usergroup import ( "context" "errors" "github.com/harness/gitness/types" ) var ErrNotFound = errors.New("usergroup not found") type Resolver interface { Resolve(ctx context.Context, scopedID string) (*types.UserGroup, error) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/codeowners/wire.go
app/services/codeowners/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package codeowners import ( "github.com/harness/gitness/app/services/usergroup" "github.com/harness/gitness/app/store" "github.com/harness/gitness/git" "github.com/google/wire" ) var WireSet = wire.NewSet( ProvideCodeOwners, ) func ProvideCodeOwners( git git.Interface, repoStore store.RepoStore, config Config, principalStore store.PrincipalStore, userGroupResolver usergroup.Resolver, ) *Service { return New(repoStore, git, config, principalStore, userGroupResolver) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/codeowners/service.go
app/services/codeowners/service.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package codeowners import ( "bufio" "context" "fmt" "io" "sort" "strings" "github.com/harness/gitness/app/services/usergroup" "github.com/harness/gitness/app/store" "github.com/harness/gitness/errors" "github.com/harness/gitness/git" "github.com/harness/gitness/git/api" gitness_store "github.com/harness/gitness/store" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/bmatcuk/doublestar/v4" "github.com/rs/zerolog/log" "golang.org/x/exp/slices" ) const ( oneMegabyte = 1048576 // maxGetContentFileSize specifies the maximum number of bytes a file content response contains. // If a file is any larger, the content is truncated. maxGetContentFileSize = oneMegabyte * 4 // 4 MB // userGroupPrefixMarker is a prefix which will be used to identify if a given codeowner is usergroup. userGroupPrefixMarker = "@" ) var ( ErrNotFound = errors.New("file not found") // escapableControlCharactersInPattern are control characters that are used to // control the parsing of the codeowners file. escapableControlCharactersInPattern = []rune{' ', '\t', '#'} // escapableSpecialCharactersInPattern are special characters that are available in the pattern syntax // to allow for more complex pattern matching. escapableSpecialCharactersInPattern = []rune{'*', '?', '[', ']', '{', '}', '-', '!', '^'} ErrFileParseInvalidEscapingInPattern = errors.New( "a pattern requires '\\' to be escaped with another '\\', or used to escape control characters " + "[space, tab, '#'] or any of the available special characters " + "['*', '?', '[', ']', '{', '}', '-', '!', '^']", ) ErrFileParseTrailingBackslashInPattern = errors.New("a pattern can't end with a trailing '\\'") ) // TooLargeError represents an error if codeowners file is too large. type TooLargeError struct { FileSize int64 } func (e *TooLargeError) Error() string { return fmt.Sprintf( "The repository's CODEOWNERS file size %.2fMB exceeds the maximum supported size of %dMB", float32(e.FileSize)/oneMegabyte, maxGetContentFileSize/oneMegabyte, ) } //nolint:errorlint // the purpose of this method is to check whether the target itself if of this type. func (e *TooLargeError) Is(target error) bool { _, ok := target.(*TooLargeError) return ok } // FileParseError represents an error if codeowners file is not parsable. type FileParseError struct { LineNumber int64 Line string Err error } func (e *FileParseError) Error() string { return fmt.Sprintf( "The repository's CODEOWNERS file has an error at line %d: %s", e.LineNumber, e.Err, ) } func (e *FileParseError) Unwrap() error { return e.Err } func (e *FileParseError) Is(target error) bool { _, ok := target.(*FileParseError) return ok } type Config struct { FilePaths []string } type Service struct { repoStore store.RepoStore git git.Interface principalStore store.PrincipalStore config Config userGroupResolver usergroup.Resolver } type File struct { Content string SHA string TotalSize int64 } type CodeOwners struct { FileSHA string Entries []Entry } type Entry struct { // LineNumber is the line number of the code owners entry. LineNumber int64 // Pattern is a glob star pattern used to match the entry against a given file path. Pattern string // Owners is the list of owners for the given pattern. // NOTE: Could be empty in case of an entry that clears previously defined ownerships. Owners []string } // IsOwnershipReset returns true iff the entry resets any previously defined ownerships. func (e *Entry) IsOwnershipReset() bool { return len(e.Owners) == 0 } type Evaluation struct { EvaluationEntries []EvaluationEntry FileSha string } type EvaluationEntry struct { LineNumber int64 Pattern string UserEvaluations []UserEvaluation UserGroupEvaluations []UserGroupEvaluation } type UserGroupEvaluation struct { Identifier string Name string Evaluations []UserEvaluation } type UserEvaluation struct { Owner types.PrincipalInfo ReviewDecision enum.PullReqReviewDecision ReviewSHA string } func New( repoStore store.RepoStore, git git.Interface, config Config, principalStore store.PrincipalStore, userGroupResolver usergroup.Resolver, ) *Service { service := &Service{ repoStore: repoStore, git: git, config: config, principalStore: principalStore, userGroupResolver: userGroupResolver, } return service } func (s *Service) get( ctx context.Context, repo *types.RepositoryCore, ref string, ) (*CodeOwners, error) { file, err := s.getCodeOwnerFile(ctx, repo, ref) if err != nil { return nil, fmt.Errorf("failed to get CODEOWNERS file: %w", err) } if file.TotalSize > maxGetContentFileSize { return nil, &TooLargeError{FileSize: file.TotalSize} } entries, err := s.parseCodeOwnerFile(file.Content) if err != nil { return nil, fmt.Errorf("failed to parse codeowner %w", err) } return &CodeOwners{ FileSHA: file.SHA, Entries: entries, }, nil } func (s *Service) parseCodeOwnerFile(content string) ([]Entry, error) { var lineNumber int64 var entries []Entry scanner := bufio.NewScanner(strings.NewReader(content)) for scanner.Scan() { lineNumber++ originalLine := scanner.Text() line := strings.TrimSpace(originalLine) if line == "" || strings.HasPrefix(line, "#") { continue } isSeparator := func(r rune) bool { return r == ' ' || r == '\t' } lineAsRunes := []rune(line) pattern := strings.Builder{} // important to iterate over runes and not bytes to support utf-8 encoding. for len(lineAsRunes) > 0 { if isSeparator(lineAsRunes[0]) || lineAsRunes[0] == '#' { break } if lineAsRunes[0] == '\\' { // ensure pattern doesn't end with trailing backslash. if len(lineAsRunes) == 1 { return nil, &FileParseError{ LineNumber: lineNumber, Line: originalLine, Err: ErrFileParseTrailingBackslashInPattern, } } switch { // escape character and special characters need to stay escaped ("\\", "\*", ...) case lineAsRunes[1] == '\\' || slices.Contains(escapableSpecialCharactersInPattern, lineAsRunes[1]): pattern.WriteRune('\\') lineAsRunes = lineAsRunes[1:] // control characters aren't special characters in pattern syntax, so escaping should be removed. case slices.Contains(escapableControlCharactersInPattern, lineAsRunes[1]): lineAsRunes = lineAsRunes[1:] default: return nil, &FileParseError{ LineNumber: lineNumber, Line: originalLine, Err: ErrFileParseInvalidEscapingInPattern, } } } pattern.WriteRune(lineAsRunes[0]) lineAsRunes = lineAsRunes[1:] } // remove inline comment (can't be escaped in owners, only pattern supports escaping) if i := slices.Index(lineAsRunes, '#'); i >= 0 { lineAsRunes = lineAsRunes[:i] } entries = append(entries, Entry{ LineNumber: lineNumber, Pattern: pattern.String(), // could be empty list in case of removing ownership Owners: strings.FieldsFunc(string(lineAsRunes), isSeparator), }) } if err := scanner.Err(); err != nil { return nil, fmt.Errorf("error reading input: %w", err) } return entries, nil } func (s *Service) getCodeOwnerFile( ctx context.Context, repo *types.RepositoryCore, ref string, ) (*File, error) { params := git.CreateReadParams(repo) if ref == "" { ref = api.BranchPrefix + repo.DefaultBranch } node, err := s.getCodeOwnerFileNode(ctx, params, ref) if err != nil { return nil, fmt.Errorf("failed to get CODEOWNERS file node: %w", err) } if node.Node.Mode != git.TreeNodeModeFile { return nil, fmt.Errorf( "CODEOWNERS file is of format '%s' but expected to be of format '%s'", node.Node.Mode, git.TreeNodeModeFile, ) } output, err := s.git.GetBlob(ctx, &git.GetBlobParams{ ReadParams: params, SHA: node.Node.SHA, SizeLimit: maxGetContentFileSize, }) if err != nil { return nil, fmt.Errorf("failed to get blob: %w", err) } defer func() { if err := output.Content.Close(); err != nil { log.Ctx(ctx).Warn().Err(err).Msgf("failed to close blob content reader.") } }() content, err := io.ReadAll(output.Content) if err != nil { return nil, fmt.Errorf("failed to read blob content: %w", err) } return &File{ Content: string(content), SHA: output.SHA.String(), TotalSize: output.Size, }, nil } func (s *Service) getCodeOwnerFileNode( ctx context.Context, params git.ReadParams, ref string, ) (*git.GetTreeNodeOutput, error) { // iterating over multiple possible CODEOWNERS file path to get the file // todo: once we have api to get multi file we can simplify for _, path := range s.config.FilePaths { node, err := s.git.GetTreeNode(ctx, &git.GetTreeNodeParams{ ReadParams: params, GitREF: ref, Path: path, }) if errors.IsNotFound(err) { continue } if err != nil { return nil, fmt.Errorf("failed to get tree node: %w", err) } log.Ctx(ctx).Debug().Msgf("using CODEOWNERS file from path %s", path) return node, nil } log.Ctx(ctx).Debug().Msgf("CODEOWNERS file not found in any of the configured paths: %v", s.config.FilePaths) return nil, fmt.Errorf("failed to find CODEOWNERS: %w", ErrNotFound) } func (s *Service) GetApplicableCodeOwners( ctx context.Context, repo *types.RepositoryCore, targetBranch string, baseRef string, headRef string, ) (*CodeOwners, error) { owners, err := s.get(ctx, repo, targetBranch) if err != nil { return nil, err } diffFileNames, err := s.git.DiffFileNames(ctx, &git.DiffParams{ ReadParams: git.CreateReadParams(repo), BaseRef: baseRef, // MergeBaseSHA, HeadRef: headRef, // SourceSHA, }) if err != nil { return nil, fmt.Errorf("failed to get diff file stat: %w", err) } entryIDs := map[int]struct{}{} for _, file := range diffFileNames.Files { // last rule that matches wins (hence simply go in reverse order) for i := len(owners.Entries) - 1; i >= 0; i-- { pattern := owners.Entries[i].Pattern if ok, err := match(pattern, file); err != nil { return nil, fmt.Errorf("failed to match pattern %q for file %q: %w", pattern, file, err) } else if ok { entryIDs[i] = struct{}{} break } } } filteredEntries := make([]Entry, 0, len(entryIDs)) for i := range entryIDs { if !owners.Entries[i].IsOwnershipReset() { filteredEntries = append(filteredEntries, owners.Entries[i]) } } // sort output to match order of occurrence in source CODEOWNERS file sort.Slice( filteredEntries, func(i, j int) bool { return filteredEntries[i].LineNumber <= filteredEntries[j].LineNumber }, ) return &CodeOwners{ FileSHA: owners.FileSHA, Entries: filteredEntries, }, err } // Evaluate evaluates the code owners for a given pull request. // //nolint:gocognit func (s *Service) Evaluate( ctx context.Context, repo *types.RepositoryCore, pr *types.PullReq, reviewers []*types.PullReqReviewer, ) (*Evaluation, error) { owners, err := s.GetApplicableCodeOwners( ctx, repo, pr.TargetBranch, pr.MergeBaseSHA, pr.SourceSHA, ) if err != nil { return &Evaluation{}, fmt.Errorf("failed to get codeOwners: %w", err) } if owners == nil || len(owners.Entries) == 0 { return &Evaluation{}, nil } evaluationEntries := make([]EvaluationEntry, 0, len(owners.Entries)) for _, entry := range owners.Entries { userEvaluations := make([]UserEvaluation, 0, len(owners.Entries)) userGroupEvaluations := make([]UserGroupEvaluation, 0, len(owners.Entries)) for _, owner := range entry.Owners { // user group identifier specified codeowner if userGroupOwner, ok := ParseUserGroupOwner(owner); ok { userGroupEvaluation, err := s.resolveUserGroupCodeOwner(ctx, userGroupOwner, reviewers) if errors.Is(err, usergroup.ErrNotFound) { log.Ctx(ctx).Debug().Msgf("user group %q not found", userGroupOwner) continue } if err != nil { log.Ctx(ctx).Warn().Err(err).Msgf("failed to resolve usergroup %q", userGroupOwner) continue } userGroupEvaluations = append(userGroupEvaluations, *userGroupEvaluation) continue } // user email specified codeowner userCodeOwner, err := s.resolveUserCodeOwnerByEmail(ctx, owner, reviewers) if errors.Is(err, gitness_store.ErrResourceNotFound) { log.Ctx(ctx).Debug().Msgf("user %q not found in database hence skipping for code owner", owner) continue } if err != nil { log.Ctx(ctx).Warn().Err(err).Msgf("error resolving user by email : %q", owner) continue } if pr.CreatedBy == userCodeOwner.Owner.ID { continue } userEvaluations = append(userEvaluations, *userCodeOwner) } if len(userEvaluations) != 0 || len(userGroupEvaluations) != 0 { evaluationEntries = append(evaluationEntries, EvaluationEntry{ LineNumber: entry.LineNumber, Pattern: entry.Pattern, UserEvaluations: userEvaluations, UserGroupEvaluations: userGroupEvaluations, }) } } return &Evaluation{ EvaluationEntries: evaluationEntries, FileSha: owners.FileSHA, }, nil } func (s *Service) resolveUserGroupCodeOwner( ctx context.Context, owner string, reviewers []*types.PullReqReviewer, ) (*UserGroupEvaluation, error) { userGroup, err := s.userGroupResolver.Resolve(ctx, owner) if err != nil { return nil, fmt.Errorf("failed to resolve usergroup : %w", err) } principalInfos, err := s.principalStore.FindManyByUID(ctx, userGroup.Users) if err != nil { return nil, fmt.Errorf( "error finding user by uids %v for usergroup %s: %w", userGroup.Users, userGroup.Identifier, err, ) } userEvaluations := make([]UserEvaluation, 0, len(userGroup.Users)) for _, principalInfo := range principalInfos { pullreqReviewer := findReviewerInList(principalInfo.Email, principalInfo.UID, reviewers) // Only append a user from the user group to the evaluations if they have reviewed a pullreq. if pullreqReviewer != nil { userEvaluations = append(userEvaluations, UserEvaluation{ Owner: pullreqReviewer.Reviewer, ReviewDecision: pullreqReviewer.ReviewDecision, ReviewSHA: pullreqReviewer.SHA, }, ) continue } } userGroupEvaluation := &UserGroupEvaluation{ Identifier: userGroup.Identifier, Name: userGroup.Name, Evaluations: userEvaluations, } return userGroupEvaluation, nil } func (s *Service) resolveUserCodeOwnerByEmail( ctx context.Context, owner string, reviewers []*types.PullReqReviewer, ) (*UserEvaluation, error) { pullreqReviewer := findReviewerInList(owner, "", reviewers) if pullreqReviewer != nil { return &UserEvaluation{ Owner: pullreqReviewer.Reviewer, ReviewDecision: pullreqReviewer.ReviewDecision, ReviewSHA: pullreqReviewer.SHA, }, nil } principal, err := s.principalStore.FindByEmail(ctx, owner) if err != nil { return nil, fmt.Errorf("error finding user by email: %w", err) } return &UserEvaluation{ Owner: *principal.ToPrincipalInfo(), }, nil } func (s *Service) Validate( ctx context.Context, repo *types.RepositoryCore, branch string, ) (*types.CodeOwnersValidation, error) { var codeOwnerValidation types.CodeOwnersValidation // check file parsing, existence and size codeowners, err := s.get(ctx, repo, branch) if err != nil { return nil, err } validatedOwners := make(map[string]struct{}) // tracks resolved owners for _, entry := range codeowners.Entries { // check for users and user groups in file for _, owner := range entry.Owners { if _, validated := validatedOwners[owner]; validated { continue } validatedOwners[owner] = struct{}{} if usrGrpOwner, ok := ParseUserGroupOwner(owner); ok { // user group owner _, err = s.userGroupResolver.Resolve(ctx, usrGrpOwner) if errors.Is(err, usergroup.ErrNotFound) { codeOwnerValidation.Addf( enum.CodeOwnerViolationCodeUserGroupNotFound, "usergroup %q not found", usrGrpOwner, ) } } else { // user owner _, err = s.principalStore.FindByEmail(ctx, owner) if errors.Is(err, gitness_store.ErrResourceNotFound) { codeOwnerValidation.Addf( enum.CodeOwnerViolationCodeUserNotFound, "user %q not found", owner, ) } } if err != nil { return nil, fmt.Errorf("error encountered fetching user %q by email: %w", owner, err) } } // check for pattern if entry.Pattern == "" { codeOwnerValidation.Add(enum.CodeOwnerViolationCodePatternEmpty, "empty pattern") continue } ok := doublestar.ValidatePathPattern(entry.Pattern) if !ok { codeOwnerValidation.Addf(enum.CodeOwnerViolationCodePatternInvalid, "pattern %q is invalid", entry.Pattern) } } return &codeOwnerValidation, nil } func findReviewerInList(email string, uid string, reviewers []*types.PullReqReviewer) *types.PullReqReviewer { for _, reviewer := range reviewers { if uid == reviewer.Reviewer.UID || strings.EqualFold(email, reviewer.Reviewer.Email) { return reviewer } } return nil } // Match matches a file path against the provided CODEOWNERS pattern. // The code follows the .gitignore syntax closely (similar to github): // https://git-scm.com/docs/gitignore#_pattern_format // // IMPORTANT: It seems that doublestar has a bug, as `*k/**` matches `k` but `k*/**` doesnt (incorrect)'. // Because of that, we currently match patterns like `test*` only partially: // - `test2`, `test/abc`, `test2/abc` are matching // - `test` is not matching // As a workaround, the user will have to add the same rule without a trailing `*` for now. func match(pattern string, path string) (bool, error) { if pattern == "" { return false, fmt.Errorf("empty pattern not allowed") } if path == "" { return false, fmt.Errorf("empty path not allowed") } // catch easy cases immediately to simplify code if pattern == "/" || pattern == "*" || pattern == "**" { return true, nil } // cleanup path to simplify matching (always start with "/" and remove trailing "/") if path[0] != '/' { path = "/" + path } if path[len(path)-1] == '/' { path = path[0 : len(path)-1] } // if the pattern contains a slash anywhere but at the end, it's treated as an absolute path. // Otherwise, the pattern can match on any level. if !strings.Contains(pattern[:len(pattern)-1], "/") { pattern = "**/" + pattern } else if pattern[0] != '/' { pattern = "/" + pattern } // if the pattern ends with "/**", then it matches everything inside. // Since doublestar matches pattern "x/**" with target "x", we replace it with "x/*/**". if strings.HasSuffix(pattern, "/**") { pattern = pattern[:len(pattern)-3] + "/*/**" } // If CODEOWNERS matches a file, it also matches a folder with the same name, and anything inside that folder. // Special case is a rule ending with "/", it only matches files inside the folder, not the folder itself. // Since doublestar matches pattern "x/**" with target "x", we extend the pattern with "*/**" in such a case. // Another special case is "/*", where the user explicitly stops nested matching. if pattern[len(pattern)-1] == '/' { pattern += "*/**" } else if !strings.HasSuffix(pattern, "/**") && !strings.HasSuffix(pattern, "/*") { pattern += "/**" } match, err := doublestar.PathMatch(pattern, path) if err != nil { return false, fmt.Errorf("failed doublestar path match: %w", err) } return match, nil } // ParseUserGroupOwner parses a user group owner scoped identifier. func ParseUserGroupOwner(owner string) (string, bool) { isOwner := strings.HasPrefix(owner, userGroupPrefixMarker) if isOwner { return owner[1:], true } return "", false }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/codeowners/service_test.go
app/services/codeowners/service_test.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package codeowners import ( "reflect" "testing" "github.com/harness/gitness/app/store" "github.com/harness/gitness/git" ) func TestService_ParseCodeOwner(t *testing.T) { type fields struct { repoStore store.RepoStore git git.Interface Config Config } type args struct { codeOwnersContent string } tests := []struct { name string fields fields args args want []Entry wantErr bool }{ { name: "Code owners Single", args: args{`**/contracts/openapi/v1/ user1@harness.io user2@harness.io`}, want: []Entry{ { LineNumber: 1, Pattern: "**/contracts/openapi/v1/", Owners: []string{"user1@harness.io", "user2@harness.io"}, }, }, }, { name: "Code owners Multiple", args: args{` **/contracts/openapi/v1/ user1@harness.io user2@harness.io /scripts/api user3@harness.io user4@harness.io `}, want: []Entry{ { LineNumber: 2, Pattern: "**/contracts/openapi/v1/", Owners: []string{"user1@harness.io", "user2@harness.io"}, }, { LineNumber: 3, Pattern: "/scripts/api", Owners: []string{"user3@harness.io", "user4@harness.io"}, }, }, }, { name: " Code owners with full line comments", args: args{` # codeowner file **/contracts/openapi/v1/ user1@harness.io user2@harness.io # /scripts/api user1@harness.io user2@harness.io `}, want: []Entry{ { LineNumber: 3, Pattern: "**/contracts/openapi/v1/", Owners: []string{"user1@harness.io", "user2@harness.io"}, }, { LineNumber: 5, Pattern: "/scripts/api", Owners: []string{"user1@harness.io", "user2@harness.io"}, }, }, }, { name: " Code owners with reset", args: args{` * user1@harness.io /scripts/api `}, want: []Entry{ { LineNumber: 2, Pattern: "*", Owners: []string{"user1@harness.io"}, }, { LineNumber: 3, Pattern: "/scripts/api", Owners: []string{}, }, }, }, { name: " Code owners with escaped characters in pattern", args: args{` # escaped escape character \\ user1@harness.io # escaped control characters (are unescaped) \ \ \# user2@harness.io # escaped special pattern syntax characters (stay escaped) \*\?\[\]\{\}\-\!\^ user3@harness.io # mix of escapes \\\ \*\\\\\? user4@harness.io `}, want: []Entry{ { LineNumber: 3, Pattern: "\\\\", Owners: []string{"user1@harness.io"}, }, { LineNumber: 5, Pattern: " #", Owners: []string{"user2@harness.io"}, }, { LineNumber: 7, Pattern: "\\*\\?\\[\\]\\{\\}\\-\\!\\^", Owners: []string{"user3@harness.io"}, }, { LineNumber: 9, Pattern: "\\\\ \\*\\\\\\\\\\?", Owners: []string{"user4@harness.io"}, }, }, }, { name: " Code owners with multiple spaces as divider", args: args{` * user1@harness.io user2@harness.io `}, want: []Entry{ { LineNumber: 2, Pattern: "*", Owners: []string{"user1@harness.io", "user2@harness.io"}, }, }, }, { name: " Code owners with invalid escaping standalone '\\'", args: args{` \ `}, wantErr: true, }, { name: " Code owners with invalid escaping unsupported char", args: args{` \a `}, wantErr: true, }, { name: " Code owners with utf8", args: args{` D∆NCE user@h∆rness.io `}, want: []Entry{ { LineNumber: 2, Pattern: "D∆NCE", Owners: []string{"user@h∆rness.io"}, }, }, }, { name: " Code owners with tabs and spaces", args: args{` a\ user1@harness.io user2@harness.io user3@harness.io `}, want: []Entry{ { LineNumber: 2, Pattern: "a ", Owners: []string{"user1@harness.io", "user2@harness.io", "user3@harness.io"}, }, }, }, { name: " Code owners with inline comments", args: args{` a #user1@harness.io b # user1@harness.io c # d# e# user1@harness.io f user1@harness.io#user2@harness.io g user1@harness.io # user2@harness.io `}, want: []Entry{ { LineNumber: 2, Pattern: "a", Owners: []string{}, }, { LineNumber: 3, Pattern: "b", Owners: []string{}, }, { LineNumber: 4, Pattern: "c", Owners: []string{}, }, { LineNumber: 5, Pattern: "d", Owners: []string{}, }, { LineNumber: 6, Pattern: "e", Owners: []string{}, }, { LineNumber: 7, Pattern: "f", Owners: []string{"user1@harness.io"}, }, { LineNumber: 8, Pattern: "g", Owners: []string{"user1@harness.io"}, }, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { s := &Service{ repoStore: tt.fields.repoStore, git: tt.fields.git, config: tt.fields.Config, } got, err := s.parseCodeOwnerFile(tt.args.codeOwnersContent) if (err != nil) != tt.wantErr { t.Errorf("ParseCodeOwner() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("ParseCodeOwner() got = %v, want %v", got, tt.want) } }) } } func Test_match(t *testing.T) { type args struct { pattern string matchingTargets []string nonMatchingTargets []string } tests := []struct { name string args args }{ { name: "root", args: args{ pattern: "/", matchingTargets: []string{"a.txt", "x/a.txt", "x/y/a.txt"}, nonMatchingTargets: []string{}, }, }, { name: "file exact match", args: args{ pattern: "/a.txt", matchingTargets: []string{"a.txt", "a.txt/b.go", "a.txt/b.go/c.ar"}, nonMatchingTargets: []string{"a.txt2", "b.txt", "a.go", "x/a.txt"}, }, }, { name: "file exact match with directory", args: args{ pattern: "/x/a.txt", matchingTargets: []string{"x/a.txt", "x/a.txt/b.txt", "x/a.txt/b.go/c.ar"}, nonMatchingTargets: []string{"a.txt", "x/a.txt2", "x/b.txt", "x/a.go"}, }, }, { name: "file relative match", args: args{ pattern: "a.txt", matchingTargets: []string{"a.txt", "x/a.txt", "x/y/a.txt", "x/y/a.txt/b.go/c.ar"}, nonMatchingTargets: []string{"a.txt2", "b.txt", "a.go", "x/a.txt2"}, }, }, { name: "file relative match with directory", args: args{ pattern: "x/a.txt", matchingTargets: []string{"x/a.txt", "x/a.txt/b.go", "x/a.txt/b.go/c.ar"}, nonMatchingTargets: []string{"a.txt2", "b.txt", "a.go", "x/a.txt2", "v/x/a.txt", "y/a.txt"}, }, }, { name: "folder exact match", args: args{ pattern: "/x/", matchingTargets: []string{"x/a.txt", "x/b.go", "x/y/a.txt"}, nonMatchingTargets: []string{"x", "a.txt", "y/a.txt", "w/x/a.txt"}, }, }, { name: "folder relative match", args: args{ pattern: "x/", matchingTargets: []string{"x/a.txt", "x/b.txt", "w/x/a.txt", "w/x/y/a.txt"}, nonMatchingTargets: []string{"x", "w/x", "a.txt", "y/a.txt"}, }, }, { name: "match-all", args: args{ pattern: "*", matchingTargets: []string{"a", "a.txt", "x/a.txt", "x/y/a.txt"}, nonMatchingTargets: []string{}, }, }, { name: "match-all in relative dir", args: args{ pattern: "x/*", matchingTargets: []string{"x/a.txt"}, nonMatchingTargets: []string{"x", "y/a.txt", "w/x/b.go", "x/a.txt/b.txt"}, }, }, { name: "match-all in absolute dir", args: args{ pattern: "/x/*", matchingTargets: []string{"x/a.txt", "x/b.go"}, nonMatchingTargets: []string{"x", "y/a.txt", "w/x/a.txt", "x/a.txt/b.go"}, }, }, { name: "file match-all type", args: args{ pattern: "*.txt", matchingTargets: []string{"a.txt", "x/a.txt", "x/y/a.txt", "x/y/a.txt/b.go", "x/y/a.txt/c.ar"}, nonMatchingTargets: []string{"a.txt2", "a.go"}, }, }, { name: "file match-all type in root folder", args: args{ pattern: "/*.txt", matchingTargets: []string{"a.txt", "a.txt/b.go", "a.txt/b.go/c.ar"}, nonMatchingTargets: []string{"a.txt2", "a.go", "x/a.txt", "x/y/a.txt"}, }, }, { name: "file match-all type in absolute sub folder", args: args{ pattern: "/x/*.txt", matchingTargets: []string{"x/a.txt", "x/a.txt/b.go", "x/a.txt/b.go/c.ar"}, nonMatchingTargets: []string{"a.txt", "x/a.txt2", "x/a.go", "w/x/a.txt", "y/a.txt"}, }, }, { name: "file match-all types in relative sub folder", args: args{ pattern: "x/*.txt", matchingTargets: []string{"x/a.txt", "x/a.txt/b.go", "x/a.txt/b.go/c.ar"}, nonMatchingTargets: []string{"a.txt", "x/a.txt2", "x/a.go", "w/x/a.txt", "y/a.txt"}, }, }, { name: "inner match-all", args: args{ pattern: "/x/*/a.txt", matchingTargets: []string{"x/y/a.txt", "x/y/a.txt/b.go", "x/y/a.txt/b.go/c.ar"}, nonMatchingTargets: []string{"a.txt", "x/a.txt", "w/x/y/a.txt", "x/y/z/a.txt"}, }, }, { name: "escaped match-all", args: args{ pattern: "\\*", matchingTargets: []string{"*", "x/y/*", "x/y/*/b.go/c.ar"}, nonMatchingTargets: []string{"a.txt"}, }, }, /* TODO: Fix bug in doublestar library, currently doesn't match `a.` ... { name: "trailing match-all on string", args: args{ pattern: "a.*", matchingTargets: []string{"a.", "a.txt", "x/a.txt", "x/a.txt/b.go", "x/a.txt/b.go/c.ar"}, nonMatchingTargets: []string{"atxt", "b.txt"}, }, }, */ { name: "globstar", args: args{ pattern: "**", matchingTargets: []string{"a", "a.txt", "x/a.txt", "x/y/a.txt"}, nonMatchingTargets: []string{}, }, }, { name: "trailing globstar absolute path", args: args{ pattern: "/x/**", matchingTargets: []string{"x/a.txt", "x/b.txt", "x/y/a.txt"}, nonMatchingTargets: []string{"a.txt", "x", "y/a.txt", "w/x/a.txt"}, }, }, { name: "trailing globstar relative path", args: args{ pattern: "x/**", matchingTargets: []string{"x/a.txt", "x/b.txt", "x/y/a.txt"}, nonMatchingTargets: []string{"a.txt", "x", "y/a.txt", "w/x/a.txt"}, }, }, /* TODO: Fix bug in doublestar library, currently doesn't match `a.` ... { name: "trailing globstar on string", args: args{ pattern: "a.**", matchingTargets: []string{"a.", "a.txt", "x/a.txt", "x/a.txt/b.go", "x/a.txt/b.go/c.ar"}, nonMatchingTargets: []string{"atxt", "b.txt"}, }, }, */ { name: "leading globstar", args: args{ pattern: "**/a.txt", matchingTargets: []string{"a.txt", "x/a.txt", "x/y/a.txt", "x/y/a.txt/b.go", "x/y/a.txt/b.go/c.ar"}, nonMatchingTargets: []string{"b.txt", "a.txt2"}, }, }, { name: "surrounding globstar", args: args{ pattern: "**/x/**", matchingTargets: []string{"x/a.txt", "w/x/a.txt", "x/y/a.txt", "w/x/y/a.txt"}, nonMatchingTargets: []string{"a.txt", "x", "w/x"}, }, }, { name: "inner globstar", args: args{ pattern: "/x/**/a.txt", matchingTargets: []string{ "x/a.txt", "x/y/a.txt", "x/y/z/a.txt", "x/y/z/a.txt/b.go", "x/y/z/a.txt/b.go/c.ar"}, nonMatchingTargets: []string{"a.txt", "w/x/a.txt", "y/a.txt"}, }, }, { name: "multi-inner globstar", args: args{ pattern: "/x/**/z/**/a.txt", matchingTargets: []string{ "x/z/a.txt", "x/y/z/l/a.txt", "x/y/yy/z/l/ll/a.txt", "x/y/yy/z/l/ll/a.txt/b.go", "x/y/yy/z/l/ll/a.txt/b.go/c.ar", }, nonMatchingTargets: []string{"a.txt", "x/a.txt", "z/a.txt", "w/x/a.txt", "y/a.txt"}, }, }, { name: "dirty globstar", args: args{ pattern: "/a**.txt", matchingTargets: []string{"a.txt", "abc.txt", "a.txt/b.go", "a.txt/b.go/c.ar"}, nonMatchingTargets: []string{"a/b/.txt"}, }, }, { name: "escaped globstar", args: args{ pattern: "\\*\\*", matchingTargets: []string{"**", "x/**", "**/y", "x/**/y"}, nonMatchingTargets: []string{"x"}, }, }, { name: "partially escaped globstar", args: args{ pattern: "*\\*", matchingTargets: []string{"*", "**", "a*", "x/*", "x/a*", "*/y", "a*/", "x/*/y", "x/a*/y"}, nonMatchingTargets: []string{"x"}, }, }, { name: "single wildchar", args: args{ pattern: "/a.?xt", matchingTargets: []string{"a.txt", "a.xxt/b.go", "a.xxt/b.go/c.ar"}, nonMatchingTargets: []string{"x/a.txt", "z/a.txt", "w/x/a.txt", "y/a.txt", "a./xt"}, }, }, { name: "escaped single wildchar", args: args{ pattern: "/a.\\?xt", matchingTargets: []string{"a.?xt", "a.?xt/b.go", "a.?xt/b.go/c.ar"}, nonMatchingTargets: []string{"a.\\?xt", "a.txt", "x/a.?xt"}, }, }, { name: "class", args: args{ pattern: "/[abc].txt", matchingTargets: []string{"a.txt", "b.txt", "c.txt"}, nonMatchingTargets: []string{"[a-c].txt", "d.txt", "A.txt"}, }, }, { name: "range class", args: args{ pattern: "/[a-c].txt", matchingTargets: []string{"a.txt", "b.txt", "c.txt"}, nonMatchingTargets: []string{"[a-c].txt", "d.txt", "A.txt"}, }, }, { name: "escaped class", args: args{ pattern: "/\\[a-c\\].txt", matchingTargets: []string{"[a-c].txt"}, nonMatchingTargets: []string{"\\[a-c\\].txt", "a.txt", "b.txt", "c.txt"}, }, }, { name: "class escaped control chars", args: args{ pattern: "/[\\!\\^\\-a-c].txt", matchingTargets: []string{"a.txt", "b.txt", "c.txt", "^.txt", "!.txt", "-.txt"}, nonMatchingTargets: []string{"d.txt", "[\\!\\^\\-a-c].txt", "[!^-a-c].txt"}, }, }, { name: "inverted class ^", args: args{ pattern: "/[^a-c].txt", matchingTargets: []string{"d.txt", "B.txt"}, nonMatchingTargets: []string{"a.txt", "b.txt", "c.txt", "[^a-c].txt", "[a-c].txt"}, }, }, { name: "escaped inverted class ^", args: args{ pattern: "/\\[^a-c\\].txt", matchingTargets: []string{"[^a-c].txt"}, nonMatchingTargets: []string{"\\[^a-c\\].txt", "a.txt", "b.txt", "c.txt", "d.txt", "[a-c].txt"}, }, }, { name: "inverted class !", args: args{ pattern: "/[!a-c].txt", matchingTargets: []string{"d.txt", "B.txt"}, nonMatchingTargets: []string{"a.txt", "b.txt", "c.txt", "[!a-c].txt", "[a-c].txt"}, }, }, { name: "escaped inverted class !", args: args{ pattern: "/\\[!a-c\\].txt", matchingTargets: []string{"[!a-c].txt"}, nonMatchingTargets: []string{"\\[!a-c\\].txt", "a.txt", "b.txt", "c.txt", "d.txt", "[a-c].txt"}, }, }, { name: "alternate matches", args: args{ pattern: "/{a,b,[c-d],e?,f\\*}.txt", matchingTargets: []string{ "a.txt", "b.txt", "c.txt", "d.txt", "e2.txt", "f*.txt", "a.txt/b.go", "a.txt/b.go/c.ar"}, nonMatchingTargets: []string{ "{a,b,[c-d],e?,f\\*}.txt", "{a,b,[c-d],e?,f*}.txt", "e.txt", "f.txt", "g.txt", "ab.txt"}, }, }, { name: "space", args: args{ pattern: "/a b.txt", matchingTargets: []string{"a b.txt"}, nonMatchingTargets: []string{"a.txt", "b.txt", "ab.txt", "a b.txt"}, }, }, { name: "tab", args: args{ pattern: "/a b.txt", matchingTargets: []string{"a b.txt"}, nonMatchingTargets: []string{"a.txt", "b.txt", "ab.txt", "a b.txt", "a b.txt"}, }, }, { // Note: it's debatable which behavior is correct - for now keep doublestar default behavior on this. // Keeping UT to ensure we don't accidentally change behavior. name: "escaped backslash", args: args{ pattern: "/a\\\\/b.txt", matchingTargets: []string{"a\\/b.txt"}, nonMatchingTargets: []string{"a\\\\/b.txt", "a/b.txt", "a/b.txt/c.ar"}, }, }, { // Note: it's debatable which behavior is correct - for now keep doublestar default behavior on this. // Keeping UT to ensure we don't accidentally change behavior. name: "escaped path separator", args: args{ pattern: "/a\\/b.txt", matchingTargets: []string{"a/b.txt", "a/b.txt/c.ar"}, nonMatchingTargets: []string{"a\\/b.txt"}, }, }, } testMatch := func(pattern string, target string, want bool) { got, err := match(pattern, target) if err != nil { t.Errorf("failed with error: %s", err) } else if got != want { t.Errorf("match(%q, %q) = %t but wanted %t)", pattern, target, got, want) } } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { for _, target := range tt.args.matchingTargets { if len(target) > 0 && target[0] == '/' { t.Errorf("target shouldn't start with leading '/'") } testMatch(tt.args.pattern, target, true) testMatch(tt.args.pattern, "/"+target, true) } for _, target := range tt.args.nonMatchingTargets { if len(target) > 0 && target[0] == '/' { t.Errorf("target shouldn't start with leading '/'") } testMatch(tt.args.pattern, target, false) testMatch(tt.args.pattern, "/"+target, false) } }) } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/branch/wire.go
app/services/branch/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package branch import ( "context" gitevents "github.com/harness/gitness/app/events/git" pullreqevents "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/app/store" "github.com/harness/gitness/events" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideService, ) // ProvideService creates a new branch service. func ProvideService( ctx context.Context, config Config, branchStore store.BranchStore, pullReqStore store.PullReqStore, gitReaderFactory *events.ReaderFactory[*gitevents.Reader], pullreqReaderFactory *events.ReaderFactory[*pullreqevents.Reader], ) (*Service, error) { return New( ctx, config, branchStore, gitReaderFactory, pullreqReaderFactory, pullReqStore, ) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/branch/handler_branch.go
app/services/branch/handler_branch.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package branch import ( "context" "fmt" "strings" "time" gitevents "github.com/harness/gitness/app/events/git" "github.com/harness/gitness/events" "github.com/harness/gitness/git/sha" "github.com/harness/gitness/types" ) func ExtractBranchName(ref string) string { return strings.TrimPrefix(ref, refsBranchPrefix) } func (s *Service) handleEventBranchCreated( ctx context.Context, event *events.Event[*gitevents.BranchCreatedPayload], ) error { branchName := ExtractBranchName(event.Payload.Ref) branchSHA, err := sha.New(event.Payload.SHA) if err != nil { return fmt.Errorf("branch sha format invalid: %w", err) } now := time.Now().UnixMilli() branch := &types.BranchTable{ Name: branchName, SHA: branchSHA, CreatedBy: event.Payload.PrincipalID, Created: now, UpdatedBy: event.Payload.PrincipalID, Updated: now, } err = s.branchStore.Upsert(ctx, event.Payload.RepoID, branch) if err != nil { return fmt.Errorf("failed to create branch in database: %w", err) } return nil } // handleEventBranchUpdated handles the branch updated event. func (s *Service) handleEventBranchUpdated( ctx context.Context, event *events.Event[*gitevents.BranchUpdatedPayload], ) error { branchName := ExtractBranchName(event.Payload.Ref) branchSHA, err := sha.New(event.Payload.NewSHA) if err != nil { return fmt.Errorf("branch sha format invalid: %w", err) } now := time.Now().UnixMilli() branch := &types.BranchTable{ Name: branchName, SHA: branchSHA, CreatedBy: event.Payload.PrincipalID, Created: now, UpdatedBy: event.Payload.PrincipalID, Updated: now, } if err := s.branchStore.Upsert(ctx, event.Payload.RepoID, branch); err != nil { return fmt.Errorf("failed to upsert branch in database: %w", err) } return nil } // handleEventBranchDeleted handles the branch deleted event. func (s *Service) handleEventBranchDeleted( ctx context.Context, event *events.Event[*gitevents.BranchDeletedPayload], ) error { branchName := ExtractBranchName(event.Payload.Ref) err := s.branchStore.Delete( ctx, event.Payload.RepoID, branchName, ) if err != nil { return fmt.Errorf("failed to delete branch from database: %w", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/branch/handler_pullreq.go
app/services/branch/handler_pullreq.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package branch import ( "context" "fmt" pullreqevents "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/events" "github.com/rs/zerolog/log" ) // handleEventPullReqCreated handles the pull request created event by updating the source branch // with the ID of the newly created pull request. func (s *Service) handleEventPullReqCreated( ctx context.Context, event *events.Event[*pullreqevents.CreatedPayload], ) error { payload := event.Payload if payload == nil { return fmt.Errorf("payload is nil") } sourceRepoID := payload.SourceRepoID sourceBranch := payload.SourceBranch pullReqID := payload.PullReqID if sourceRepoID == nil { return events.NewDiscardEventErrorf("pullreq %d event missing sourceRepoID", pullReqID) } logger := log.Ctx(ctx).With(). Int64("source_repo_id", *sourceRepoID). Str("source_branch", sourceBranch). Int64("pullreq_id", pullReqID). Logger() err := s.branchStore.UpdateLastPR(ctx, *sourceRepoID, sourceBranch, &pullReqID) if err != nil { return fmt.Errorf("failed to update last PR: %w", err) } logger.Debug().Msg("successfully updated branch's last created pullreq") return nil } // handleEventPullReqClosed handles the pull request closed event. func (s *Service) handleEventPullReqClosed( ctx context.Context, event *events.Event[*pullreqevents.ClosedPayload], ) error { payload := event.Payload if payload == nil { return fmt.Errorf("payload is nil") } if payload.SourceRepoID == nil { return events.NewDiscardEventErrorf("pullreq %d event missing sourceRepoID", payload.PullReqID) } logger := log.Ctx(ctx).With(). Int64("source_repo_id", *payload.SourceRepoID). Int64("pullreq_id", payload.PullReqID). Str("source_branch", payload.SourceBranch). Logger() sourceRepoID := payload.SourceRepoID sourceBranch := payload.SourceBranch err := s.branchStore.UpdateLastPR(ctx, *sourceRepoID, sourceBranch, nil) if err != nil { return fmt.Errorf("failed to update last PR: %w", err) } logger.Debug().Msg("successfully updated branch's last created pullreq for closed pullreq") return nil } // handleEventPullReqReopened handles the pull request reopened event. func (s *Service) handleEventPullReqReopened( ctx context.Context, event *events.Event[*pullreqevents.ReopenedPayload], ) error { payload := event.Payload if payload == nil { return fmt.Errorf("payload is nil") } if payload.SourceRepoID == nil { return events.NewDiscardEventErrorf("pullreq %d event missing sourceRepoID", payload.PullReqID) } logger := log.Ctx(ctx).With(). Int64("source_repo_id", *payload.SourceRepoID). Int64("pullreq_id", payload.PullReqID). Str("source_branch", payload.SourceBranch). Logger() sourceRepoID := payload.SourceRepoID sourceBranch := payload.SourceBranch pullReqID := payload.PullReqID err := s.branchStore.UpdateLastPR(ctx, *sourceRepoID, sourceBranch, &pullReqID) if err != nil { return fmt.Errorf("failed to update last PR: %w", err) } logger.Debug().Msg("successfully updated branch's last created pullreq for reopened pullreq") return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/branch/service.go
app/services/branch/service.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package branch import ( "context" "errors" "fmt" "time" gitevents "github.com/harness/gitness/app/events/git" pullreqevents "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/app/store" "github.com/harness/gitness/events" "github.com/harness/gitness/stream" "github.com/rs/zerolog/log" ) const ( eventsReaderGroupName = "gitness:branch" refsBranchPrefix = "refs/heads/" ) type Config struct { EventReaderName string Concurrency int MaxRetries int } // Prepare validates the configuration. func (c *Config) Prepare() error { if c == nil { return errors.New("config is required") } if c.EventReaderName == "" { return errors.New("config.EventReaderName is required") } if c.Concurrency < 1 { return errors.New("config.Concurrency has to be a positive number") } if c.MaxRetries < 0 { return errors.New("config.MaxRetries can't be negative") } return nil } type Service struct { branchStore store.BranchStore pullReqStore store.PullReqStore } func New( ctx context.Context, config Config, branchStore store.BranchStore, gitReaderFactory *events.ReaderFactory[*gitevents.Reader], pullreqReaderFactory *events.ReaderFactory[*pullreqevents.Reader], pullReqStore store.PullReqStore, ) (*Service, error) { if err := config.Prepare(); err != nil { return nil, fmt.Errorf("provided branch service config is invalid: %w", err) } log.Ctx(ctx).Info().Msgf("[branch service] event reader name: %s, concurrency: %d, maxRetries: %d", config.EventReaderName, config.Concurrency, config.MaxRetries) service := &Service{ branchStore: branchStore, pullReqStore: pullReqStore, } _, err := gitReaderFactory.Launch(ctx, eventsReaderGroupName, config.EventReaderName, func(r *gitevents.Reader) error { const idleTimeout = 10 * time.Second r.Configure( stream.WithConcurrency(config.Concurrency), stream.WithHandlerOptions( stream.WithIdleTimeout(idleTimeout), stream.WithMaxRetries(config.MaxRetries), )) _ = r.RegisterBranchCreated(service.handleEventBranchCreated) _ = r.RegisterBranchUpdated(service.handleEventBranchUpdated) _ = r.RegisterBranchDeleted(service.handleEventBranchDeleted) return nil }) if err != nil { return nil, fmt.Errorf("failed to launch git events reader: %w", err) } // Register for pull request events to update branch information _, err = pullreqReaderFactory.Launch(ctx, eventsReaderGroupName, config.EventReaderName, func(r *pullreqevents.Reader) error { const idleTimeout = 10 * time.Second r.Configure( stream.WithConcurrency(config.Concurrency), stream.WithHandlerOptions( stream.WithIdleTimeout(idleTimeout), stream.WithMaxRetries(config.MaxRetries), )) _ = r.RegisterCreated(service.handleEventPullReqCreated) _ = r.RegisterClosed(service.handleEventPullReqClosed) _ = r.RegisterReopened(service.handleEventPullReqReopened) return nil }) if err != nil { return nil, fmt.Errorf("failed to launch pullreq events reader: %w", err) } return service, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/instrument/wire.go
app/services/instrument/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package instrument import ( "context" gitevents "github.com/harness/gitness/app/events/git" "github.com/harness/gitness/app/store" "github.com/harness/gitness/events" "github.com/harness/gitness/job" "github.com/harness/gitness/types" "github.com/google/wire" ) var WireSet = wire.NewSet( ProvideService, ProvideRepositoryCount, ProvideGitConsumer, ) func ProvideGitConsumer( ctx context.Context, config *types.Config, gitReaderFactory *events.ReaderFactory[*gitevents.Reader], repoStore store.RepoStore, principalInfoCache store.PrincipalInfoCache, instrumentation Service, ) (Consumer, error) { return NewConsumer( ctx, config, gitReaderFactory, repoStore, principalInfoCache, instrumentation, ) } func ProvideRepositoryCount( ctx context.Context, config *types.Config, svc Service, repoStore store.RepoStore, scheduler *job.Scheduler, executor *job.Executor, ) (*RepositoryCount, error) { return NewRepositoryCount( ctx, config, svc, repoStore, scheduler, executor, ) } func ProvideService() Service { return Noop{} }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/instrument/git_consumer.go
app/services/instrument/git_consumer.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package instrument import ( "context" "fmt" "time" gitevents "github.com/harness/gitness/app/events/git" "github.com/harness/gitness/app/store" "github.com/harness/gitness/events" "github.com/harness/gitness/stream" "github.com/harness/gitness/types" "github.com/rs/zerolog/log" ) type Consumer struct { repoStore store.RepoStore principalInfoCache store.PrincipalInfoCache instrumentation Service } func NewConsumer(ctx context.Context, config *types.Config, gitReaderFactory *events.ReaderFactory[*gitevents.Reader], repoStore store.RepoStore, principalInfoCache store.PrincipalInfoCache, instrumentation Service, ) (Consumer, error) { c := Consumer{ repoStore: repoStore, principalInfoCache: principalInfoCache, instrumentation: instrumentation, } const groupCommitInstrument = "gitness:git:instrumentation" _, err := gitReaderFactory.Launch(ctx, groupCommitInstrument, config.InstanceID, func(r *gitevents.Reader) error { const idleTimeout = 10 * time.Second r.Configure( stream.WithConcurrency(3), stream.WithHandlerOptions( stream.WithIdleTimeout(idleTimeout), stream.WithMaxRetries(2), )) _ = r.RegisterBranchUpdated(c.instrumentTrackOnBranchUpdate) return nil }) if err != nil { return Consumer{}, fmt.Errorf("failed to launch git consumer: %w", err) } return c, nil } func (c Consumer) instrumentTrackOnBranchUpdate( ctx context.Context, event *events.Event[*gitevents.BranchUpdatedPayload], ) error { repo, err := c.repoStore.Find(ctx, event.Payload.RepoID) if err != nil { return fmt.Errorf("failed to get repo git info: %w", err) } principal, err := c.principalInfoCache.Get(ctx, event.Payload.PrincipalID) if err != nil { return fmt.Errorf("failed to get principal info: %w", err) } err = c.instrumentation.Track(ctx, Event{ Type: EventTypeCreateCommit, Principal: principal, Path: repo.Path, Properties: map[Property]any{ PropertyRepositoryID: repo.ID, PropertyRepositoryName: repo.Identifier, PropertyIsDefaultBranch: event.Payload.Ref == repo.DefaultBranch, }, }) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert instrumentation record for create commit operation: %s", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/instrument/noop.go
app/services/instrument/noop.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package instrument import "context" type Noop struct { } func (n Noop) Track( context.Context, Event, ) error { return nil } func (n Noop) Close(context.Context) error { return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/instrument/instrument.go
app/services/instrument/instrument.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package instrument import ( "context" "time" "github.com/harness/gitness/types" ) type CreationType string const ( CreationTypeCreate CreationType = "CREATE" CreationTypeImport CreationType = "IMPORT" CreationTypeLink CreationType = "LINK" ) type Property string const ( PropertyRepositoryID Property = "repository_id" PropertyRepositoryName Property = "repository_name" PropertyRepositoryCreationType Property = "creation_type" PropertyPullRequestID Property = "pull_request_id" PropertyCommentIsReplied Property = "comment_is_replied" PropertyCommentContainsSuggestion Property = "contains_suggestion" PropertyMergeStrategy Property = "merge_strategy" PropertyRuleID Property = "rule_id" PropertyIsDefaultBranch Property = "is_default_branch" PropertyDecision Property = "decision" PropertyRepositories Property = "repositories" PropertyTargetBranch Property = "target_branch" PropertySpaceID Property = "space_id" PropertySpaceName Property = "space_name" ) type EventType string const ( EventTypeRepositoryCreate EventType = "Repository create" EventTypeRepositoryCount EventType = "Repository count" EventTypeCommitCount EventType = "Commit count" EventTypeCreateCommit EventType = "Create commit" EventTypeCreateBranch EventType = "Create branch" EventTypeChangeTargetBranch EventType = "Change target branch" EventTypeCreateTag EventType = "Create tag" EventTypeCreatePullRequest EventType = "Create pull request" EventTypeMergePullRequest EventType = "Merge pull request" EventTypeReviewPullRequest EventType = "Review pull request" EventTypeCreatePRComment EventType = "Create PR comment" EventTypeCreateBranchRule EventType = "Create branch rule" EventTypePRSuggestionApplied EventType = "Pull request suggestion applied" ) func (e EventType) String() string { return string(e) } type Event struct { Type EventType `json:"event"` Category string `json:"category"` Principal *types.PrincipalInfo `json:"user_id,omitempty"` GroupID string `json:"group_id,omitempty"` Timestamp time.Time `json:"timestamp"` Path string `json:"path"` RemoteAddr string `json:"remote_addr"` Properties map[Property]any `json:"properties,omitempty"` } type Service interface { Track(ctx context.Context, event Event) error Close(ctx context.Context) error }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/instrument/tasks.go
app/services/instrument/tasks.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package instrument import ( "context" "fmt" "time" "github.com/harness/gitness/app/bootstrap" "github.com/harness/gitness/app/store" "github.com/harness/gitness/errors" "github.com/harness/gitness/job" "github.com/harness/gitness/types" "github.com/rs/zerolog/log" ) const ( jobType = "instrumentation-total-repositories" ) type RepositoryCount struct { enabled bool svc Service repoStore store.RepoStore } func NewRepositoryCount( ctx context.Context, config *types.Config, svc Service, repoStore store.RepoStore, scheduler *job.Scheduler, executor *job.Executor, ) (*RepositoryCount, error) { r := &RepositoryCount{ enabled: config.Instrumentation.Enable, svc: svc, repoStore: repoStore, } err := executor.Register(jobType, r) if err != nil { return nil, fmt.Errorf("failed to register instrumentation job: %w", err) } if scheduler == nil { return nil, errors.New("job scheduler is nil") } err = scheduler.AddRecurring(ctx, jobType, jobType, config.Instrumentation.Cron, time.Minute) if err != nil { return nil, fmt.Errorf("failed to register recurring job for instrumentation: %w", err) } return r, nil } func (c *RepositoryCount) Handle(ctx context.Context, _ string, _ job.ProgressReporter) (string, error) { if !c.enabled { return "", errors.New("instrumentation service is disabled") } if c.repoStore == nil { return "", errors.New("repository store not initialized") } // total repos in the system totalRepos, err := c.repoStore.CountByRootSpaces(ctx) if err != nil { return "", fmt.Errorf("failed to get repositories total count: %w", err) } if c.svc == nil { return "", errors.New("service not initialized") } systemPrincipal := bootstrap.NewSystemServiceSession().Principal for _, item := range totalRepos { err = c.svc.Track(ctx, Event{ Type: EventTypeRepositoryCount, Principal: systemPrincipal.ToPrincipalInfo(), GroupID: item.SpaceUID, Properties: map[Property]any{ PropertyRepositories: item.Total, }, }) if err != nil { log.Ctx(ctx).Warn().Msgf("failed to insert instrumentation record for repository count operation: %s", err) } } return "", nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/gitspaceoperationsevent/wire.go
app/services/gitspaceoperationsevent/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gitspaceoperationsevent import ( "context" gitspaceevents "github.com/harness/gitness/app/events/gitspace" gitspaceoperationsevents "github.com/harness/gitness/app/events/gitspaceoperations" "github.com/harness/gitness/app/gitspace/orchestrator" "github.com/harness/gitness/app/services/gitspace" "github.com/harness/gitness/app/services/gitspaceevent" "github.com/harness/gitness/events" "github.com/google/wire" ) // WireSet provides a wire set for this package. var WireSet = wire.NewSet( ProvideService, ) func ProvideService( ctx context.Context, config *gitspaceevent.Config, gitspaceInfraEventReaderFactory *events.ReaderFactory[*gitspaceoperationsevents.Reader], orchestrator orchestrator.Orchestrator, gitspaceSvc *gitspace.Service, eventReporter *gitspaceevents.Reporter, ) (*Service, error) { return NewService( ctx, config, gitspaceInfraEventReaderFactory, orchestrator, gitspaceSvc, eventReporter, ) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/gitspaceoperationsevent/service.go
app/services/gitspaceoperationsevent/service.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gitspaceoperationsevent import ( "context" "fmt" "time" gitspaceevents "github.com/harness/gitness/app/events/gitspace" gitspaceoperationsevents "github.com/harness/gitness/app/events/gitspaceoperations" "github.com/harness/gitness/app/gitspace/orchestrator" "github.com/harness/gitness/app/services/gitspace" "github.com/harness/gitness/app/services/gitspaceevent" "github.com/harness/gitness/events" "github.com/harness/gitness/stream" ) const groupGitspaceOperationsEvents = "gitness:gitspaceoperations" type Service struct { config *gitspaceevent.Config orchestrator orchestrator.Orchestrator gitspaceSvc *gitspace.Service eventReporter *gitspaceevents.Reporter } func NewService( ctx context.Context, config *gitspaceevent.Config, gitspaceOperationsEventReaderFactory *events.ReaderFactory[*gitspaceoperationsevents.Reader], orchestrator orchestrator.Orchestrator, gitspaceSvc *gitspace.Service, eventReporter *gitspaceevents.Reporter, ) (*Service, error) { if err := config.Sanitize(); err != nil { return nil, fmt.Errorf("provided gitspace operations event service config is invalid: %w", err) } service := &Service{ config: config, orchestrator: orchestrator, gitspaceSvc: gitspaceSvc, eventReporter: eventReporter, } _, err := gitspaceOperationsEventReaderFactory.Launch(ctx, groupGitspaceOperationsEvents, config.EventReaderName, func(r *gitspaceoperationsevents.Reader) error { var idleTimeout = time.Duration(config.TimeoutInMins) * time.Minute r.Configure( stream.WithConcurrency(config.Concurrency), stream.WithHandlerOptions( stream.WithIdleTimeout(idleTimeout), stream.WithMaxRetries(config.MaxRetries), )) _ = r.RegisterGitspaceOperationsEvent(service.handleGitspaceOperationsEvent) return nil }) if err != nil { return nil, fmt.Errorf("failed to launch gitspace operations event reader: %w", err) } return service, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/gitspaceoperationsevent/handler.go
app/services/gitspaceoperationsevent/handler.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gitspaceoperationsevent import ( "context" "fmt" "time" gitspaceEvents "github.com/harness/gitness/app/events/gitspace" gitspaceOperationsEvents "github.com/harness/gitness/app/events/gitspaceoperations" "github.com/harness/gitness/app/gitspace/orchestrator/container/response" "github.com/harness/gitness/events" "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) func (s *Service) handleGitspaceOperationsEvent( ctx context.Context, event *events.Event[*gitspaceOperationsEvents.GitspaceOperationsEventPayload], ) error { logr := log.With().Str("event", string(event.Payload.Type)).Logger() logr.Debug().Msgf("Received gitspace operations event, gitspace configID: %s", event.Payload.Infra.GitspaceConfigIdentifier, ) payload := event.Payload ctxWithTimedOut, cancel := context.WithTimeout(ctx, time.Duration(s.config.TimeoutInMins)*time.Minute) defer cancel() config, fetchErr := s.getConfig( ctxWithTimedOut, payload.Infra.SpacePath, payload.Infra.GitspaceConfigIdentifier) if fetchErr != nil { return fetchErr } instance := config.GitspaceInstance if payload.Infra.GitspaceInstanceIdentifier != "" { gitspaceInstance, err := s.gitspaceSvc.FindInstanceByIdentifier( ctxWithTimedOut, payload.Infra.GitspaceInstanceIdentifier, ) if err != nil { return fmt.Errorf("failed to fetch gitspace instance: %w", err) } instance = gitspaceInstance config.GitspaceInstance = instance } defer func() { updateErr := s.gitspaceSvc.UpdateInstance(ctxWithTimedOut, instance) if updateErr != nil { log.Err(updateErr).Msgf("failed to update gitspace instance") } }() var err error switch payload.Type { case enum.GitspaceOperationsEventStart: if config.GitspaceInstance.Identifier != payload.Infra.GitspaceInstanceIdentifier { return fmt.Errorf("gitspace instance is not latest, stopping provisioning") } startResponse, ok := payload.Response.(*response.StartResponse) if !ok { return fmt.Errorf("failed to cast start response") } updatedInstance, handleResumeStartErr := s.orchestrator.FinishResumeStartGitspace( ctxWithTimedOut, *config, payload.Infra, startResponse, ) if handleResumeStartErr != nil { s.emitGitspaceConfigEvent(ctxWithTimedOut, config, enum.GitspaceEventTypeGitspaceActionStartFailed) instance.State = enum.GitspaceInstanceStateError updatedInstance.ErrorMessage = handleResumeStartErr.ErrorMessage err = fmt.Errorf("failed to finish resume start gitspace: %w", handleResumeStartErr.Error) } instance = &updatedInstance case enum.GitspaceOperationsEventStop: stopResponse, ok := payload.Response.(*response.StopResponse) if !ok { return fmt.Errorf("failed to cast stop response") } finishStopErr := s.orchestrator.FinishStopGitspaceContainer( ctxWithTimedOut, *config, payload.Infra, stopResponse, ) if finishStopErr != nil { s.emitGitspaceConfigEvent(ctxWithTimedOut, config, enum.GitspaceEventTypeGitspaceActionStopFailed) instance.State = enum.GitspaceInstanceStateError instance.ErrorMessage = finishStopErr.ErrorMessage err = fmt.Errorf("failed to finish stop gitspace: %w", finishStopErr.Error) } case enum.GitspaceOperationsEventDelete: deleteResponse, ok := payload.Response.(*response.DeleteResponse) if !ok { return fmt.Errorf("failed to cast delete response") } finishRemoveErr := s.orchestrator.FinishRemoveGitspaceContainer( ctxWithTimedOut, *config, payload.Infra, deleteResponse, ) if finishRemoveErr != nil { s.emitGitspaceConfigEvent(ctxWithTimedOut, config, enum.GitspaceEventTypeGitspaceActionResetFailed) instance.State = enum.GitspaceInstanceStateError instance.ErrorMessage = finishRemoveErr.ErrorMessage err = fmt.Errorf("failed to finish remove/reset gitspace: %w", finishRemoveErr.Error) } default: return fmt.Errorf("unknown event type: %s", event.Payload.Type) } if err != nil { log.Err(err).Msgf("error while handling gitspace operations event") } return nil } func (s *Service) getConfig( ctx context.Context, spaceRef string, identifier string, ) (*types.GitspaceConfig, error) { config, err := s.gitspaceSvc.FindWithLatestInstanceWithSpacePath(ctx, spaceRef, identifier) if err != nil { return nil, fmt.Errorf( "failed to find gitspace config during infra event handling, identifier %s: %w", identifier, err) } return config, nil } func (s *Service) emitGitspaceConfigEvent(ctx context.Context, config *types.GitspaceConfig, eventType enum.GitspaceEventType, ) { s.eventReporter.EmitGitspaceEvent(ctx, gitspaceEvents.GitspaceEvent, &gitspaceEvents.GitspaceEventPayload{ QueryKey: config.Identifier, EntityID: config.ID, EntityType: enum.GitspaceEntityTypeGitspaceConfig, EventType: eventType, Timestamp: time.Now().UnixNano(), }) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/settings/wire.go
app/services/settings/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package settings import ( "github.com/harness/gitness/app/store" "github.com/google/wire" ) var WireSet = wire.NewSet( ProvideService, ) func ProvideService( settingsStore store.SettingsStore, ) *Service { return NewService(settingsStore) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/settings/service.go
app/services/settings/service.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package settings import ( "context" "encoding/json" "errors" "fmt" appstore "github.com/harness/gitness/app/store" "github.com/harness/gitness/store" "github.com/harness/gitness/types/enum" ) // KeyValue is a struct used for upserting many entries. type KeyValue struct { Key Key Value any } // SettingHandler is an abstraction of a component that's handling a single setting value as part of // calling service.Map. type SettingHandler interface { Key() Key Required() bool Handle(ctx context.Context, raw []byte) error } // Service is used to enhance interaction with the settings store. type Service struct { settingsStore appstore.SettingsStore } func NewService( settingsStore appstore.SettingsStore, ) *Service { return &Service{ settingsStore: settingsStore, } } // Set sets the value of the setting with the given key for the given scope. func (s *Service) Set( ctx context.Context, scope enum.SettingsScope, scopeID int64, key Key, value any, ) error { raw, err := json.Marshal(value) if err != nil { return fmt.Errorf("failed to marshal setting value: %w", err) } err = s.settingsStore.Upsert( ctx, scope, scopeID, string(key), raw, ) if err != nil { return fmt.Errorf("failed to upsert setting in store: %w", err) } return nil } // SetMany sets the value of the settings with the given keys for the given scope. func (s *Service) SetMany( ctx context.Context, scope enum.SettingsScope, scopeID int64, keyValues ...KeyValue, ) error { // TODO: batch upsert for _, kv := range keyValues { if err := s.Set(ctx, scope, scopeID, kv.Key, kv.Value); err != nil { return fmt.Errorf("failed to set setting for key %q: %w", kv.Key, err) } } return nil } // Get returns the value of the setting with the given key for the given scope. func (s *Service) Get( ctx context.Context, scope enum.SettingsScope, scopeID int64, key Key, out any, ) (bool, error) { raw, err := s.settingsStore.Find( ctx, scope, scopeID, string(key), ) if errors.Is(err, store.ErrResourceNotFound) { return false, nil } if err != nil { return false, fmt.Errorf("failed to find setting in store: %w", err) } err = json.Unmarshal(raw, &out) if err != nil { return false, fmt.Errorf("failed to unmarshal setting value: %w", err) } return true, nil } // Map maps all available settings using the provided handlers for the given scope. func (s *Service) Map( ctx context.Context, scope enum.SettingsScope, scopeID int64, handlers ...SettingHandler, ) error { if len(handlers) == 0 { return nil } keys := make([]string, len(handlers)) for i, m := range handlers { keys[i] = string(m.Key()) } rawValues, err := s.settingsStore.FindMany( ctx, scope, scopeID, keys..., ) if err != nil { return fmt.Errorf("failed to find settings in store: %w", err) } for _, m := range handlers { rawValue, found := rawValues[string(m.Key())] if !found && m.Required() { return fmt.Errorf("required setting %q not found", m.Key()) } if !found { continue } if err = m.Handle(ctx, rawValue); err != nil { return fmt.Errorf("failed to handle value for setting %q: %w", m.Key(), err) } } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/settings/settings.go
app/services/settings/settings.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package settings type Key string var ( // KeySecretScanningEnabled [bool] enables secret scanning if set to true. KeySecretScanningEnabled Key = "secret_scanning_enabled" DefaultSecretScanningEnabled = false KeyFileSizeLimit Key = "file_size_limit" DefaultFileSizeLimit = int64(1e+8) // 100 MB KeyInstallID Key = "install_id" DefaultInstallID = string("") KeyPrincipalCommitterMatch Key = "principal_committer_match" DefaultPrincipalCommitterMatch = false KeyGitLFSEnabled Key = "git_lfs_enabled" DefaultGitLFSEnabled = true )
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/settings/service_repo.go
app/services/settings/service_repo.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package settings import ( "context" "github.com/harness/gitness/types/enum" ) // RepoSet sets the value of the setting with the given key for the given repo. func (s *Service) RepoSet( ctx context.Context, repoID int64, key Key, value any, ) error { return s.Set( ctx, enum.SettingsScopeRepo, repoID, key, value, ) } // RepoSetMany sets the value of the settings with the given keys for the given repo. func (s *Service) RepoSetMany( ctx context.Context, repoID int64, keyValues ...KeyValue, ) error { return s.SetMany( ctx, enum.SettingsScopeRepo, repoID, keyValues..., ) } // RepoGet returns the value of the setting with the given key for the given repo. func (s *Service) RepoGet( ctx context.Context, repoID int64, key Key, out any, ) (bool, error) { return s.Get( ctx, enum.SettingsScopeRepo, repoID, key, out, ) } // RepoMap maps all available settings using the provided handlers for the given repo. func (s *Service) RepoMap( ctx context.Context, repoID int64, handlers ...SettingHandler, ) error { return s.Map( ctx, enum.SettingsScopeRepo, repoID, handlers..., ) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/settings/mapping.go
app/services/settings/mapping.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package settings import ( "context" "encoding/json" "fmt" ) // Mapping returns a SettingHandler that maps the value of the setting with the given key to the target. func Mapping[T any](key Key, target *T) SettingHandler { if target == nil { panic("mapping target can't be nil") } return &settingHandlerMapping[T]{ key: key, required: false, target: target, } } // MappingRequired returns a SettingHandler that maps the value of the setting with the given key to the target. // If the setting wasn't found an error is returned. func MappingRequired[T any](key Key, target *T) SettingHandler { if target == nil { panic("mapping target can't be nil") } return &settingHandlerMapping[T]{ key: key, required: true, target: target, } } var _ SettingHandler = (*settingHandlerMapping[any])(nil) // settingHandlerMapping is a setting handler that maps the value of a setting to the provided target. type settingHandlerMapping[T any] struct { key Key required bool target *T } func (q *settingHandlerMapping[T]) Key() Key { return q.key } func (q *settingHandlerMapping[T]) Required() bool { return q.required } func (q *settingHandlerMapping[T]) Handle(_ context.Context, raw []byte) error { err := json.Unmarshal(raw, q.target) if err != nil { return fmt.Errorf("failed to unmarshal setting value: %w", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/settings/service_system.go
app/services/settings/service_system.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package settings import ( "context" "github.com/harness/gitness/types/enum" ) // SystemSet sets the value of the setting with the given key for the system. func (s *Service) SystemSet( ctx context.Context, key Key, value any, ) error { return s.Set( ctx, enum.SettingsScopeSystem, 0, key, value, ) } // SystemSetMany sets the values of the settings with the given keys for the system. func (s *Service) SystemSetMany( ctx context.Context, keyValues ...KeyValue, ) error { return s.SetMany( ctx, enum.SettingsScopeSystem, 0, keyValues..., ) } // SystemGet returns the value of the setting with the given key for the system. func (s *Service) SystemGet( ctx context.Context, key Key, out any, ) (bool, error) { return s.Get( ctx, enum.SettingsScopeSystem, 0, key, out, ) } // SystemMap maps all available settings using the provided handlers for the system. func (s *Service) SystemMap( ctx context.Context, handlers ...SettingHandler, ) error { return s.Map( ctx, enum.SettingsScopeSystem, 0, handlers..., ) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/settings/helpers.go
app/services/settings/helpers.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package settings import ( "context" "fmt" ) // RepoGet is a helper method for getting a setting of a specific type for a repo. func RepoGet[T any]( ctx context.Context, s *Service, repoID int64, key Key, dflt T, ) (T, error) { var out T ok, err := s.RepoGet(ctx, repoID, key, &out) if err != nil { return out, err } if !ok { return dflt, nil } return out, nil } // RepoGetRequired is a helper method for getting a setting of a specific type for a repo. // If the setting isn't found, an error is returned. func RepoGetRequired[T any]( ctx context.Context, s *Service, repoID int64, key Key, ) (T, error) { var out T ok, err := s.RepoGet(ctx, repoID, key, &out) if err != nil { return out, err } if !ok { return out, fmt.Errorf("setting %q not found", key) } return out, nil } // SystemGet is a helper method for getting a setting of a specific type for the system. func SystemGet[T any]( ctx context.Context, s *Service, key Key, dflt T, ) (T, error) { var out T ok, err := s.SystemGet(ctx, key, &out) if err != nil { return out, err } if !ok { return dflt, nil } return out, nil } // SystemGetRequired is a helper method for getting a setting of a specific type for the system. // If the setting isn't found, an error is returned. func SystemGetRequired[T any]( ctx context.Context, s *Service, key Key, ) (T, error) { var out T ok, err := s.SystemGet(ctx, key, &out) if err != nil { return out, err } if !ok { return out, fmt.Errorf("setting %q not found", key) } return out, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/secret/wire.go
app/services/secret/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package secret import ( "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/store" "github.com/harness/gitness/encrypt" "github.com/harness/gitness/secret" "github.com/google/wire" ) var WireSet = wire.NewSet( ProvideSecretService, ) func ProvideSecretService( secretStore store.SecretStore, encrypter encrypt.Encrypter, spaceFinder refcache.SpaceFinder, ) secret.Service { return NewService(secretStore, encrypter, spaceFinder) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/secret/service.go
app/services/secret/service.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package secret import ( "context" secretCtrl "github.com/harness/gitness/app/api/controller/secret" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/app/store" "github.com/harness/gitness/encrypt" "github.com/harness/gitness/secret" "github.com/pkg/errors" "github.com/rs/zerolog/log" ) type service struct { secretStore store.SecretStore encrypter encrypt.Encrypter spaceFinder refcache.SpaceFinder } func NewService( secretStore store.SecretStore, encrypter encrypt.Encrypter, spaceFinder refcache.SpaceFinder, ) secret.Service { return &service{ secretStore: secretStore, encrypter: encrypter, spaceFinder: spaceFinder, } } func (s *service) DecryptSecret(ctx context.Context, spacePath string, secretIdentifier string) (string, error) { space, err := s.spaceFinder.FindByRef(ctx, spacePath) if err != nil { log.Error().Msgf("failed to find space path: %v", err) return "", errors.Wrap(err, "failed to find space path") } sec, err := s.secretStore.FindByIdentifier(ctx, space.ID, secretIdentifier) if err != nil { log.Error().Msgf("failed to find secret: %v", err) return "", errors.Wrap(err, "failed to find secret") } sec, err = secretCtrl.Dec(s.encrypter, sec) if err != nil { log.Error().Msgf("could not decrypt secret: %v", err) return "", errors.Wrap(err, "failed to decrypt secret") } return sec.Data, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/notification/wire.go
app/services/notification/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package notification import ( "context" pullreqevents "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/app/services/notification/mailer" "github.com/harness/gitness/app/store" "github.com/harness/gitness/app/url" "github.com/harness/gitness/events" "github.com/google/wire" ) var WireSet = wire.NewSet( ProvideMailClient, ProvideNotificationService, ) func ProvideNotificationService( ctx context.Context, notificationClient Client, pullReqConfig Config, prReaderFactory *events.ReaderFactory[*pullreqevents.Reader], pullReqStore store.PullReqStore, repoStore store.RepoStore, principalInfoView store.PrincipalInfoView, principalInfoCache store.PrincipalInfoCache, pullReqReviewersStore store.PullReqReviewerStore, pullReqActivityStore store.PullReqActivityStore, spacePathStore store.SpacePathStore, urlProvider url.Provider, ) (*Service, error) { return NewService( ctx, pullReqConfig, notificationClient, prReaderFactory, pullReqStore, repoStore, principalInfoView, principalInfoCache, pullReqReviewersStore, pullReqActivityStore, spacePathStore, urlProvider, ) } func ProvideMailClient(mailer mailer.Mailer) Client { return NewMailClient(mailer) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/notification/branch_updated.go
app/services/notification/branch_updated.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package notification import ( "context" "fmt" pullreqevents "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/events" "github.com/harness/gitness/types" ) type PullReqBranchUpdatedPayload struct { Base *BasePullReqPayload Committer *types.PrincipalInfo NewSHA string } func (s *Service) notifyPullReqBranchUpdated( ctx context.Context, event *events.Event[*pullreqevents.BranchUpdatedPayload], ) error { payload, reviewers, err := s.processPullReqBranchUpdatedEvent(ctx, event) if err != nil { return fmt.Errorf( "failed to process %s event for pullReqID %d: %w", pullreqevents.BranchUpdatedEvent, event.Payload.PullReqID, err, ) } if len(reviewers) == 0 { return nil } err = s.notificationClient.SendPullReqBranchUpdated(ctx, reviewers, payload) if err != nil { return fmt.Errorf( "failed to send email for event %s for pullReqID %d: %w", pullreqevents.BranchUpdatedEvent, event.Payload.PullReqID, err, ) } return nil } func (s *Service) processPullReqBranchUpdatedEvent( ctx context.Context, event *events.Event[*pullreqevents.BranchUpdatedPayload], ) (*PullReqBranchUpdatedPayload, []*types.PrincipalInfo, error) { base, err := s.getBasePayload(ctx, event.Payload.Base) if err != nil { return nil, nil, fmt.Errorf("failed to get base payload: %w", err) } committer, err := s.principalInfoCache.Get(ctx, event.Payload.PrincipalID) if err != nil { return nil, nil, fmt.Errorf("failed to get principal info for %d: %w", event.Payload.PrincipalID, err) } reviewers, err := s.pullReqReviewersStore.List(ctx, event.Payload.PullReqID) if err != nil { return nil, nil, fmt.Errorf("failed to get reviewers for pull request %d: %w", event.Payload.PullReqID, err) } reviewerPrincipals := make([]*types.PrincipalInfo, len(reviewers)) for i, reviewer := range reviewers { reviewerPrincipals[i], err = s.principalInfoCache.Get(ctx, reviewer.PrincipalID) if err != nil { return nil, nil, fmt.Errorf("failed to get principal info for %d: %w", reviewer.PrincipalID, err) } } return &PullReqBranchUpdatedPayload{ Base: base, NewSHA: event.Payload.NewSHA, Committer: committer, }, reviewerPrincipals, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/notification/service.go
app/services/notification/service.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package notification import ( "context" "embed" "fmt" "html/template" "io/fs" "path" pullreqevents "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/app/store" "github.com/harness/gitness/app/url" "github.com/harness/gitness/events" "github.com/harness/gitness/stream" "github.com/harness/gitness/types" ) const ( eventReaderGroupName = "gitness:notification" templatesDir = "templates" subjectPullReqEvent = "[%s] %s (PR #%d)" ) var ( //go:embed templates/* files embed.FS htmlTemplates map[string]*template.Template ) func init() { err := LoadTemplates() if err != nil { panic(err) } } func LoadTemplates() error { htmlTemplates = make(map[string]*template.Template) tmplFiles, err := fs.ReadDir(files, templatesDir) if err != nil { return err } for _, tmpl := range tmplFiles { if tmpl.IsDir() { continue } pt, err := template.ParseFS(files, path.Join(templatesDir, tmpl.Name())) if err != nil { return err } htmlTemplates[tmpl.Name()] = pt } return nil } type BasePullReqPayload struct { Repo *types.Repository PullReq *types.PullReq Author *types.PrincipalInfo PullReqURL string } type Config struct { EventReaderName string Concurrency int MaxRetries int } type Service struct { config Config notificationClient Client prReaderFactory *events.ReaderFactory[*pullreqevents.Reader] pullReqStore store.PullReqStore repoStore store.RepoStore principalInfoView store.PrincipalInfoView principalInfoCache store.PrincipalInfoCache pullReqReviewersStore store.PullReqReviewerStore pullReqActivityStore store.PullReqActivityStore spacePathStore store.SpacePathStore urlProvider url.Provider } func NewService( ctx context.Context, config Config, notificationClient Client, prReaderFactory *events.ReaderFactory[*pullreqevents.Reader], pullReqStore store.PullReqStore, repoStore store.RepoStore, principalInfoView store.PrincipalInfoView, principalInfoCache store.PrincipalInfoCache, pullReqReviewersStore store.PullReqReviewerStore, pullReqActivityStore store.PullReqActivityStore, spacePathStore store.SpacePathStore, urlProvider url.Provider, ) (*Service, error) { service := &Service{ config: config, notificationClient: notificationClient, prReaderFactory: prReaderFactory, pullReqStore: pullReqStore, repoStore: repoStore, principalInfoView: principalInfoView, principalInfoCache: principalInfoCache, pullReqReviewersStore: pullReqReviewersStore, pullReqActivityStore: pullReqActivityStore, spacePathStore: spacePathStore, urlProvider: urlProvider, } _, err := service.prReaderFactory.Launch( ctx, eventReaderGroupName, config.EventReaderName, func(r *pullreqevents.Reader, ) error { r.Configure( stream.WithConcurrency(config.Concurrency), stream.WithHandlerOptions( stream.WithMaxRetries(config.MaxRetries), )) _ = r.RegisterCreated(service.notifyPullReqCreated) _ = r.RegisterReviewerAdded(service.notifyReviewerAdded) _ = r.RegisterCommentCreated(service.notifyCommentCreated) _ = r.RegisterBranchUpdated(service.notifyPullReqBranchUpdated) _ = r.RegisterReviewSubmitted(service.notifyReviewSubmitted) // state changes _ = r.RegisterMerged(service.notifyPullReqStateMerged) _ = r.RegisterClosed(service.notifyPullReqStateClosed) _ = r.RegisterReopened(service.notifyPullReqStateReOpened) return nil }) if err != nil { return nil, fmt.Errorf("failed to launch event reader for %s: %w", eventReaderGroupName, err) } return service, nil } func (s *Service) getBasePayload( ctx context.Context, base pullreqevents.Base, ) (*BasePullReqPayload, error) { repo, err := s.repoStore.Find(ctx, base.TargetRepoID) if err != nil { return nil, fmt.Errorf("failed to fetch repo from repoStore: %w", err) } pullReq, err := s.pullReqStore.Find(ctx, base.PullReqID) if err != nil { return nil, fmt.Errorf("failed to fetch pullreq from pullReqStore: %w", err) } author, err := s.principalInfoCache.Get(ctx, pullReq.CreatedBy) if err != nil { return nil, fmt.Errorf("failed to fetch author %d from principalInfoCache while building base notification: %w", pullReq.CreatedBy, err) } return &BasePullReqPayload{ Repo: repo, PullReq: pullReq, Author: author, PullReqURL: s.urlProvider.GenerateUIPRURL(ctx, repo.Path, pullReq.Number), }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/notification/pullreq_created.go
app/services/notification/pullreq_created.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package notification import ( "context" "fmt" pullreqevents "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/events" "github.com/harness/gitness/types" ) func (s *Service) notifyPullReqCreated( ctx context.Context, event *events.Event[*pullreqevents.CreatedPayload], ) error { base, err := s.getBasePayload(ctx, event.Payload.Base) if err != nil { return fmt.Errorf("failed to get base payload: %w", err) } reviewers, err := s.principalInfoCache.Map(ctx, event.Payload.ReviewerIDs) if err != nil { return fmt.Errorf("failed to get principal infos from cache: %w", err) } for _, reviewer := range reviewers { payload := &ReviewerAddedPayload{ Base: base, Reviewer: reviewer, } if err := s.notificationClient.SendReviewerAdded( ctx, []*types.PrincipalInfo{base.Author, reviewer}, payload, ); err != nil { return fmt.Errorf( "failed to send email for event %s for pullReqID %d: %w", pullreqevents.CreatedEvent, event.Payload.PullReqID, err, ) } } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/app/services/notification/mail_client.go
app/services/notification/mail_client.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package notification import ( "bytes" "context" "fmt" pullreqevents "github.com/harness/gitness/app/events/pullreq" "github.com/harness/gitness/app/services/notification/mailer" "github.com/harness/gitness/types" ) const ( TemplateReviewerAdded = "reviewer_added.html" TemplateCommentPRAuthor = "comment_pr_author.html" TemplateCommentMentions = "comment_mentions.html" TemplateCommentParticipants = "comment_participants.html" TemplatePullReqBranchUpdated = "pullreq_branch_updated.html" TemplateNameReviewSubmitted = "review_submitted.html" TemplatePullReqStateChanged = "pullreq_state_changed.html" ) type MailClient struct { mailer.Mailer } func NewMailClient(mailer mailer.Mailer) MailClient { return MailClient{ Mailer: mailer, } } func (m MailClient) SendCommentPRAuthor( ctx context.Context, recipients []*types.PrincipalInfo, payload *CommentPayload, ) error { email, err := GenerateEmailFromPayload( TemplateCommentPRAuthor, recipients, payload.Base, payload, ) if err != nil { return fmt.Errorf("failed to generate mail requests after processing %s event: %w", pullreqevents.CommentCreatedEvent, err) } return m.Mailer.Send(ctx, *email) } func (m MailClient) SendCommentMentions( ctx context.Context, recipients []*types.PrincipalInfo, payload *CommentPayload, ) error { email, err := GenerateEmailFromPayload( TemplateCommentMentions, recipients, payload.Base, payload, ) if err != nil { return fmt.Errorf("failed to generate mail requests after processing %s event: %w", pullreqevents.CommentCreatedEvent, err) } return m.Mailer.Send(ctx, *email) } func (m MailClient) SendCommentParticipants( ctx context.Context, recipients []*types.PrincipalInfo, payload *CommentPayload, ) error { email, err := GenerateEmailFromPayload( TemplateCommentParticipants, recipients, payload.Base, payload, ) if err != nil { return fmt.Errorf("failed to generate mail requests after processing %s event: %w", pullreqevents.CommentCreatedEvent, err) } return m.Mailer.Send(ctx, *email) } func (m MailClient) SendReviewerAdded( ctx context.Context, recipients []*types.PrincipalInfo, payload *ReviewerAddedPayload, ) error { email, err := GenerateEmailFromPayload( TemplateReviewerAdded, recipients, payload.Base, payload, ) if err != nil { return fmt.Errorf("failed to generate mail requests after processing %s event: %w", pullreqevents.ReviewerAddedEvent, err) } return m.Mailer.Send(ctx, *email) } func (m MailClient) SendPullReqBranchUpdated( ctx context.Context, recipients []*types.PrincipalInfo, payload *PullReqBranchUpdatedPayload, ) error { email, err := GenerateEmailFromPayload( TemplatePullReqBranchUpdated, recipients, payload.Base, payload, ) if err != nil { return fmt.Errorf("failed to generate mail requests after processing %s event: %w", pullreqevents.BranchUpdatedEvent, err) } return m.Mailer.Send(ctx, *email) } func (m MailClient) SendReviewSubmitted( ctx context.Context, recipients []*types.PrincipalInfo, payload *ReviewSubmittedPayload, ) error { email, err := GenerateEmailFromPayload(TemplateNameReviewSubmitted, recipients, payload.Base, payload) if err != nil { return fmt.Errorf( "failed to generate mail requests after processing %s event: %w", pullreqevents.ReviewSubmittedEvent, err, ) } return m.Mailer.Send(ctx, *email) } func (m MailClient) SendPullReqStateChanged( ctx context.Context, recipients []*types.PrincipalInfo, payload *PullReqStateChangedPayload, ) error { email, err := GenerateEmailFromPayload(TemplatePullReqStateChanged, recipients, payload.Base, payload) if err != nil { return fmt.Errorf( "failed to generate mail requests after processing pullReqState change event: %w", err, ) } return m.Mailer.Send(ctx, *email) } func GetSubjectPullRequest( repoIdentifier string, prNum int64, prTitle string, ) string { return fmt.Sprintf(subjectPullReqEvent, repoIdentifier, prTitle, prNum) } func GetHTMLBody(templateName string, data any) ([]byte, error) { tmpl := htmlTemplates[templateName] tmplOutput := bytes.Buffer{} err := tmpl.Execute(&tmplOutput, data) if err != nil { return nil, fmt.Errorf("failed to execute template %s", templateName) } return tmplOutput.Bytes(), nil } func GenerateEmailFromPayload( templateName string, recipients []*types.PrincipalInfo, base *BasePullReqPayload, payload any, ) (*mailer.Payload, error) { subject := GetSubjectPullRequest(base.Repo.Identifier, base.PullReq.Number, base.PullReq.Title) body, err := GetHTMLBody(templateName, payload) if err != nil { return nil, err } var email mailer.Payload email.Body = string(body) email.Subject = subject email.RepoRef = base.Repo.Path recipientEmails := RetrieveEmailsFromPrincipals(recipients) email.ToRecipients = recipientEmails return &email, nil } func RetrieveEmailsFromPrincipals(principals []*types.PrincipalInfo) []string { emails := make([]string, len(principals)) for i, principal := range principals { emails[i] = principal.Email } return emails }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false