From 695ff742d62742c193719236509d431a8b6e3bbb Mon Sep 17 00:00:00 2001 From: Gabriel20xx Date: Thu, 3 Sep 2026 00:15:58 +0200 Subject: [PATCH] Sync shared snapshot from 7b5a4e6 --- shared/backend/authproxy/authproxy.go | 135 +++++++++++++++++++ shared/backend/authproxy/authproxy_test.go | 150 +++++++++++++++++++++ 2 files changed, 285 insertions(+) create mode 100644 shared/backend/authproxy/authproxy.go create mode 100644 shared/backend/authproxy/authproxy_test.go diff --git a/shared/backend/authproxy/authproxy.go b/shared/backend/authproxy/authproxy.go new file mode 100644 index 0000000..a1bbdba --- /dev/null +++ b/shared/backend/authproxy/authproxy.go @@ -0,0 +1,135 @@ +// Package authproxy holds small helpers shared by every Go service in this +// workspace that proxies its own /auth/... (or /api/auth/...) HTTP surface +// to a centralized AuthGuard instance via shared/backend/authclient, instead +// of embedding its own local user table. +// +// Three services independently reimplemented the same handful of pieces +// below before this package existed (Forks/Bitmagnet/backend/internal/auth/service.go, +// Original/GameStream/backend/cmd/gamestreamd/auth.go, +// Central/shared/media-backend/internal/auth/auth.go — read any one of +// their top-of-file doc comments for the fuller AuthGuard-migration +// rationale: session cookie forwarding, the local one-time setup-claim +// flag, "auth disabled" mode, etc.). Those pieces stay project-specific +// (they depend on each project's own storage/framework/response shape) — +// only the pieces below were duplicated near-verbatim everywhere: +// +// - SessionToken / ClearSessionCookies: reading and clearing AuthGuard's +// own session cookie is identical logic in every caller, since none of +// them mint a session token of their own anymore. +// - NormalizeUsername / NormalizeEmail / ValidPassword: the same +// trim+shape checks, just with different max/min lengths and (kept +// deliberately un-touched by this package) different caller-owned +// error messages — see each function's doc comment for why this +// package returns a plain (value, bool) rather than an error. +// - APIErrorResponse: unwrapping an authclient.APIError into the +// (status code, message) pair every caller's own writeError-equivalent +// forwards close to verbatim. +package authproxy + +import ( + "errors" + "net/http" + "strings" + "unicode/utf8" + + authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient" +) + +// CookieReader is the minimal interface SessionToken needs from an incoming +// request — just *http.Request.Cookie's signature, not the whole request. +// *http.Request satisfies this trivially; a caller (like Bitmagnet's own +// internal/auth.HTTPContext) that deliberately abstracts its request behind +// a narrower interface of its own, e.g. for testability, can pass that +// directly instead of needing a concrete *http.Request. +type CookieReader interface { + Cookie(name string) (*http.Cookie, error) +} + +// SessionToken reads AuthGuard's own session cookie +// (authclient.DefaultCookieName) off an incoming request, returning "" if +// it is absent or empty. Every AuthGuard-proxying service in this workspace +// mints no session token of its own — AuthGuard's cookie *is* the session — +// so this same read is duplicated in every one of them. +func SessionToken(r CookieReader) string { + cookie, err := r.Cookie(authclient.DefaultCookieName) + if err != nil || cookie.Value == "" { + return "" + } + return cookie.Value +} + +// ClearSessionCookies clears AuthGuard's own session cookie plus one +// legacy, pre-migration cookie name a caller's browser might still be +// holding (each project's own cookie name from before it adopted +// AuthGuard — e.g. "gamestream_session", "bitmagnet_session", +// "mediacollection_session"; pass "" if a given caller has none). Normally +// AuthGuard's own Set-Cookie header, forwarded via authclient.ForwardCookies, +// already clears its cookie on logout — every project's own Logout handler +// also calls this explicitly as a fallback and to clear the legacy cookie, +// which AuthGuard has no way to know about. +func ClearSessionCookies(w http.ResponseWriter, legacyCookieName string, secure bool) { + http.SetCookie(w, &http.Cookie{ + Name: authclient.DefaultCookieName, Value: "", Path: "/", HttpOnly: true, + Secure: secure, SameSite: http.SameSiteLaxMode, MaxAge: -1, + }) + if legacyCookieName != "" && legacyCookieName != authclient.DefaultCookieName { + http.SetCookie(w, &http.Cookie{ + Name: legacyCookieName, Value: "", Path: "/", HttpOnly: true, + Secure: secure, SameSite: http.SameSiteLaxMode, MaxAge: -1, + }) + } +} + +// NormalizeUsername reports whether value, once trimmed, is non-empty and +// no longer than maxLen runes, and returns the trimmed value either way. +// +// This returns (value, bool) rather than (value, error) deliberately: every +// existing caller already owns its own error value/message for this +// failure (e.g. "username is required", "invalid authentication input: +// username must be between 1 and 64 characters") as part of its public API +// response shape, and unifying those messages was not part of what made +// this duplicated — only the trim+shape check was. A caller with "empty +// means leave this field unchanged" update semantics (a partial-update +// endpoint) should special-case an empty value itself before calling this, +// since this function always reports false for one. +func NormalizeUsername(value string, maxLen int) (normalized string, ok bool) { + normalized = strings.TrimSpace(value) + return normalized, normalized != "" && utf8.RuneCountInString(normalized) <= maxLen +} + +// NormalizeEmail reports whether value, once lowercased and trimmed, looks +// like a valid email address (exactly one "@", a non-empty local part, and +// a domain part containing at least one ".") and is no longer than maxLen +// runes, and returns the normalized value either way. Same (value, bool) +// shape and rationale as NormalizeUsername. +func NormalizeEmail(value string, maxLen int) (normalized string, ok bool) { + normalized = strings.ToLower(strings.TrimSpace(value)) + if normalized == "" || utf8.RuneCountInString(normalized) > maxLen || strings.Count(normalized, "@") != 1 { + return normalized, false + } + local, domain, _ := strings.Cut(normalized, "@") + if local == "" || domain == "" || !strings.Contains(domain, ".") { + return normalized, false + } + return normalized, true +} + +// ValidPassword reports whether password is at least minLen runes long. +func ValidPassword(password string, minLen int) bool { + return utf8.RuneCountInString(password) >= minLen +} + +// APIErrorResponse extracts the HTTP status code and message an +// authclient.APIError carries, for a caller's own writeError-equivalent to +// forward. ok is false when err is not an *authclient.APIError (a +// transport failure actually reaching AuthGuard, as opposed to AuthGuard +// giving a real answer the caller didn't like) — callers should fall back +// to a generic 500 with their own message in that case, matching every +// existing writeAuthGuardError implementation's behavior. +func APIErrorResponse(err error) (statusCode int, message string, ok bool) { + var apiErr *authclient.APIError + if errors.As(err, &apiErr) { + return apiErr.StatusCode, apiErr.Message, true + } + return 0, "", false +} diff --git a/shared/backend/authproxy/authproxy_test.go b/shared/backend/authproxy/authproxy_test.go new file mode 100644 index 0000000..1354b66 --- /dev/null +++ b/shared/backend/authproxy/authproxy_test.go @@ -0,0 +1,150 @@ +package authproxy + +import ( + "errors" + "net/http" + "net/http/httptest" + "testing" + + authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient" +) + +func TestSessionToken(t *testing.T) { + cases := []struct { + name string + cookie *http.Cookie + want string + }{ + {name: "no cookie", want: ""}, + {name: "present", cookie: &http.Cookie{Name: authclient.DefaultCookieName, Value: "tok123"}, want: "tok123"}, + {name: "empty value", cookie: &http.Cookie{Name: authclient.DefaultCookieName, Value: ""}, want: ""}, + {name: "wrong cookie name", cookie: &http.Cookie{Name: "other", Value: "tok123"}, want: ""}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + r := httptest.NewRequest(http.MethodGet, "/", nil) + if tc.cookie != nil { + r.AddCookie(tc.cookie) + } + if got := SessionToken(r); got != tc.want { + t.Fatalf("SessionToken() = %q, want %q", got, tc.want) + } + }) + } +} + +func TestClearSessionCookies(t *testing.T) { + w := httptest.NewRecorder() + ClearSessionCookies(w, "legacy_session", true) + + resp := w.Result() + cookies := resp.Cookies() + if len(cookies) != 2 { + t.Fatalf("got %d Set-Cookie headers, want 2: %+v", len(cookies), cookies) + } + byName := map[string]*http.Cookie{} + for _, c := range cookies { + byName[c.Name] = c + } + for _, name := range []string{authclient.DefaultCookieName, "legacy_session"} { + c, ok := byName[name] + if !ok { + t.Fatalf("missing Set-Cookie for %q", name) + } + if c.Value != "" || c.MaxAge != -1 || !c.HttpOnly || !c.Secure { + t.Fatalf("cookie %q not cleared correctly: %+v", name, c) + } + } +} + +func TestClearSessionCookiesNoLegacyName(t *testing.T) { + w := httptest.NewRecorder() + ClearSessionCookies(w, "", false) + + if got := len(w.Result().Cookies()); got != 1 { + t.Fatalf("got %d Set-Cookie headers, want 1 (no legacy name given)", got) + } +} + +func TestClearSessionCookiesLegacyEqualsDefault(t *testing.T) { + w := httptest.NewRecorder() + ClearSessionCookies(w, authclient.DefaultCookieName, false) + + if got := len(w.Result().Cookies()); got != 1 { + t.Fatalf("got %d Set-Cookie headers, want 1 (legacy name equals AuthGuard's own)", got) + } +} + +func TestNormalizeUsername(t *testing.T) { + cases := []struct { + name string + input string + want string + ok bool + }{ + {name: "valid", input: " gabriel ", want: "gabriel", ok: true}, + {name: "empty", input: " ", want: "", ok: false}, + {name: "too long", input: string(make([]byte, 65)), want: string(make([]byte, 65)), ok: false}, + {name: "exactly max", input: "1234567890", want: "1234567890", ok: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, ok := NormalizeUsername(tc.input, 10) + if got != tc.want || ok != tc.ok { + t.Fatalf("NormalizeUsername(%q, 10) = (%q, %v), want (%q, %v)", tc.input, got, ok, tc.want, tc.ok) + } + }) + } +} + +func TestNormalizeEmail(t *testing.T) { + cases := []struct { + name string + input string + want string + ok bool + }{ + {name: "valid", input: " Gabriel@Example.COM ", want: "gabriel@example.com", ok: true}, + {name: "empty", input: "", want: "", ok: false}, + {name: "no at", input: "gabriel.example.com", want: "gabriel.example.com", ok: false}, + {name: "two ats", input: "a@b@c.com", want: "a@b@c.com", ok: false}, + {name: "empty local part", input: "@example.com", want: "@example.com", ok: false}, + {name: "empty domain", input: "gabriel@", want: "gabriel@", ok: false}, + {name: "domain without dot", input: "gabriel@localhost", want: "gabriel@localhost", ok: false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, ok := NormalizeEmail(tc.input, 254) + if got != tc.want || ok != tc.ok { + t.Fatalf("NormalizeEmail(%q, 254) = (%q, %v), want (%q, %v)", tc.input, got, ok, tc.want, tc.ok) + } + }) + } +} + +func TestValidPassword(t *testing.T) { + if ValidPassword("short", 8) { + t.Fatal("expected 5-char password to fail an 8-char minimum") + } + if !ValidPassword("longenough", 8) { + t.Fatal("expected 10-char password to pass an 8-char minimum") + } +} + +func TestAPIErrorResponse(t *testing.T) { + t.Run("api error", func(t *testing.T) { + apiErr := &authclient.APIError{StatusCode: http.StatusConflict, Message: "already exists"} + status, message, ok := APIErrorResponse(apiErr) + if !ok || status != http.StatusConflict || message != "already exists" { + t.Fatalf("APIErrorResponse() = (%d, %q, %v), want (409, %q, true)", status, message, ok, "already exists") + } + }) + + t.Run("non-api error", func(t *testing.T) { + _, _, ok := APIErrorResponse(errors.New("transport failure")) + if ok { + t.Fatal("expected ok=false for a non-APIError") + } + }) +}