From dbd583fa4d9e1b327f06cfe9abc97b044b273289 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Mon, 15 Sep 2025 21:53:07 -0700 Subject: [PATCH] Add comprehensive tests for realm quoting behavior MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tests cover: - Default realm quoting - Custom realm with spaces - Special characters (quotes, backslashes) - Empty realm fallback to default - Unicode realm support Addresses review feedback about testing strconv.Quote behavior in WWW-Authenticate header per RFC 7617 compliance. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- middleware/basic_auth_test.go | 61 +++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/middleware/basic_auth_test.go b/middleware/basic_auth_test.go index b3abfa17..2d319261 100644 --- a/middleware/basic_auth_test.go +++ b/middleware/basic_auth_test.go @@ -117,3 +117,64 @@ func TestBasicAuth(t *testing.T) { }) } } + +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)) + }) + } +}