From 534b4f9c30f106b90ef22f4c66ada2980795762a Mon Sep 17 00:00:00 2001 From: tracyhatemice Date: Sun, 29 Nov 2026 18:26:32 +0800 Subject: [PATCH 01/10] fix(ui,auth): prevent mobile header shrink, add OIDC UserInfo fallback and DDNS endpoint flag --- internal/auth/oidc.go | 43 +++++ internal/auth/oidc_test.go | 280 +++++++++++++++++++++++++++- main.go | 14 +- main_test.go | 45 +++++ ui/src/components/PageHeader.svelte | 2 +- ui/src/lib/viewEffects.test.js | 39 ++++ 6 files changed, 407 insertions(+), 16 deletions(-) diff --git a/internal/auth/oidc.go b/internal/auth/oidc.go index 98b029f..ef809d3 100644 --- a/internal/auth/oidc.go +++ b/internal/auth/oidc.go @@ -560,9 +560,52 @@ func (m *Manager) exchangeAndVerify( if err := idToken.Claims(&claims); err != nil { return nil, idTokenClaims{}, fmt.Errorf("decode id_token claims: %w", err) } + if claims.Email == "" || claims.EmailVerified == nil || claims.Name == "" { + if hydrateErr := hydrateClaimsFromUserInfo(exchangeCtx, provider, token, idToken.Subject, &claims); hydrateErr != nil { + return nil, idTokenClaims{}, hydrateErr + } + } return idToken, claims, nil } +func hydrateClaimsFromUserInfo( + ctx context.Context, + provider *oidc.Provider, + token *oauth2.Token, + expectedSub string, + claims *idTokenClaims, +) error { + if provider.UserInfoEndpoint() == "" { + return nil + } + ui, err := provider.UserInfo(ctx, oauth2.StaticTokenSource(token)) + if err != nil { + if claims.Email != "" && claims.EmailVerified != nil { + log.Printf("AUTH: OIDC userinfo request failed; continuing with ID token claims: %v", err) + return nil + } + return fmt.Errorf("fetch userinfo: %w", err) + } + if subtle.ConstantTimeCompare([]byte(ui.Subject), []byte(expectedSub)) != 1 { + return errors.New("userinfo subject mismatch") + } + + var uiClaims idTokenClaims + if claimErr := ui.Claims(&uiClaims); claimErr != nil { + return fmt.Errorf("decode userinfo claims: %w", claimErr) + } + if claims.Email == "" { + claims.Email = uiClaims.Email + } + if claims.EmailVerified == nil { + claims.EmailVerified = uiClaims.EmailVerified + } + if claims.Name == "" { + claims.Name = uiClaims.Name + } + return nil +} + func (m *Manager) isAllowed(sub, email string, emailVerified *bool) bool { return m.isIdentityAllowed(sub, email, emailVerified != nil && *emailVerified) } diff --git a/internal/auth/oidc_test.go b/internal/auth/oidc_test.go index 25e092f..1dcae8c 100644 --- a/internal/auth/oidc_test.go +++ b/internal/auth/oidc_test.go @@ -45,6 +45,7 @@ type discoveryDoc struct { AuthorizationEndpoint string `json:"authorization_endpoint"` TokenEndpoint string `json:"token_endpoint"` JWKSURI string `json:"jwks_uri"` + UserInfoEndpoint string `json:"userinfo_endpoint,omitempty"` ResponseTypesSupported []string `json:"response_types_supported"` SubjectTypesSupported []string `json:"subject_types_supported"` IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"` @@ -71,14 +72,17 @@ type tokenEndpointResponse struct { } type mockOIDCIdP struct { - server *httptest.Server - privKey *rsa.PrivateKey - kid string - mu sync.Mutex - codes map[string]authCodeRecord - nextClaims idTokenClaimsSpec - discoveryHits atomic.Int64 - tokenCalls atomic.Int64 + server *httptest.Server + privKey *rsa.PrivateKey + kid string + mu sync.Mutex + codes map[string]authCodeRecord + nextClaims idTokenClaimsSpec + userInfoEnabled bool + userInfoHandler func(w http.ResponseWriter, r *http.Request) + discoveryHits atomic.Int64 + tokenCalls atomic.Int64 + userInfoCalls atomic.Int64 } func newMockOIDCIdP(t *testing.T) *mockOIDCIdP { @@ -105,6 +109,7 @@ func newMockOIDCIdP(t *testing.T) *mockOIDCIdP { mux.HandleFunc("GET /jwks", idp.handleJWKS) mux.HandleFunc("GET /authorize", idp.handleAuthorize) mux.HandleFunc("POST /token", idp.handleToken) + mux.HandleFunc("GET /userinfo", idp.handleUserInfo) idp.server = httptest.NewServer(mux) t.Cleanup(idp.server.Close) @@ -117,6 +122,13 @@ func (m *mockOIDCIdP) setNextClaims(spec idTokenClaimsSpec) { m.nextClaims = spec } +func (m *mockOIDCIdP) setUserInfoHandler(fn func(w http.ResponseWriter, r *http.Request)) { + m.mu.Lock() + defer m.mu.Unlock() + m.userInfoEnabled = true + m.userInfoHandler = fn +} + func (m *mockOIDCIdP) issueCode(t *testing.T, authRedirectURL string) (code, state string) { t.Helper() @@ -160,7 +172,7 @@ func (m *mockOIDCIdP) issueCode(t *testing.T, authRedirectURL string) (code, sta func (m *mockOIDCIdP) handleDiscovery(w http.ResponseWriter, _ *http.Request) { m.discoveryHits.Add(1) - writeTestJSON(w, discoveryDoc{ + doc := discoveryDoc{ Issuer: m.server.URL, AuthorizationEndpoint: m.server.URL + "/authorize", TokenEndpoint: m.server.URL + "/token", @@ -168,7 +180,25 @@ func (m *mockOIDCIdP) handleDiscovery(w http.ResponseWriter, _ *http.Request) { ResponseTypesSupported: []string{"code"}, SubjectTypesSupported: []string{"public"}, IDTokenSigningAlgValuesSupported: []string{"RS256"}, - }) + } + m.mu.Lock() + if m.userInfoEnabled { + doc.UserInfoEndpoint = m.server.URL + "/userinfo" + } + m.mu.Unlock() + writeTestJSON(w, doc) +} + +func (m *mockOIDCIdP) handleUserInfo(w http.ResponseWriter, r *http.Request) { + m.userInfoCalls.Add(1) + m.mu.Lock() + fn := m.userInfoHandler + m.mu.Unlock() + if fn == nil { + http.Error(w, `{"error":"not_found"}`, http.StatusNotFound) + return + } + fn(w, r) } func (m *mockOIDCIdP) handleJWKS(w http.ResponseWriter, _ *http.Request) { @@ -1172,3 +1202,233 @@ func verifyCrossSiteAndVerifiedSession(t *testing.T, idp *mockOIDCIdP, mux2 *htt mux2.ServeHTTP(sameOriginRec, sameOriginReq) mustStatus(t, sameOriginRec, http.StatusOK, "RequireAdmin same-origin") } + +func TestOIDCCallbackHydratesClaimsFromUserInfo(t *testing.T) { + ctx := context.Background() + db := openAuthTestDB(t) + idp := newMockOIDCIdP(t) + idp.setNextClaims(idTokenClaimsSpec{Sub: "user-1"}) + idp.setUserInfoHandler(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer mock-access-token" { + http.Error(w, `{"error":"invalid_token"}`, http.StatusUnauthorized) + return + } + writeTestJSON(w, map[string]any{ + "sub": "user-1", + "email": "admin@example.com", + "email_verified": true, + "name": "Admin User", + }) + }) + + mgr, err := auth.NewManager(auth.Config{ + Issuer: idp.server.URL, + ClientID: "who-admin", + ClientSecret: "super-secret", + BasePath: "/who", + AllowedEmails: []string{"admin@example.com"}, + HTTPClient: idp.server.Client(), + }, db, fixedClientIP) + mustNoErr(t, err, "NewManager") + + mux := http.NewServeMux() + mgr.RegisterRoutes(mux) + + cbRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true) + mustRedirect(t, cbRec, "/who/", "OIDC callback with UserInfo hydration") + sessCookie := findCookie(cbRec.Result().Cookies(), "who_session") + if sessCookie == nil || sessCookie.Value == "" || !sessCookie.HttpOnly || !sessCookie.Secure || + sessCookie.SameSite != http.SameSiteLaxMode || sessCookie.Path != "/who/" { + t.Fatalf("expected HttpOnly Secure Lax who_session cookie on Path=/who/, got %+v", sessCookie) + } + if got := idp.userInfoCalls.Load(); got != 1 { + t.Fatalf("expected 1 /userinfo call, got %d", got) + } + + sessions, err := db.ListSessions(ctx) + mustNoErr(t, err, "ListSessions") + if len(sessions) != 1 { + t.Fatalf("expected 1 session in DB, got %d", len(sessions)) + } + if sessions[0].Sub != "user-1" || + sessions[0].Email != "admin@example.com" || + !sessions[0].EmailVerified || + sessions[0].Name != "Admin User" { + t.Fatalf("unexpected hydrated session in DB: %+v", sessions[0]) + } +} + +func TestOIDCCallbackRejectsUserInfoSubMismatch(t *testing.T) { + ctx := context.Background() + db := openAuthTestDB(t) + idp := newMockOIDCIdP(t) + idp.setNextClaims(idTokenClaimsSpec{Sub: "user-1"}) + idp.setUserInfoHandler(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer mock-access-token" { + http.Error(w, `{"error":"invalid_token"}`, http.StatusUnauthorized) + return + } + writeTestJSON(w, map[string]any{ + "sub": "attacker-sub", + "email": "admin@example.com", + "email_verified": true, + "name": "Attacker", + }) + }) + + mgr, err := auth.NewManager(auth.Config{ + Issuer: idp.server.URL, + ClientID: "who-admin", + ClientSecret: "super-secret", + BasePath: "/who", + AllowedEmails: []string{"admin@example.com"}, + HTTPClient: idp.server.Client(), + }, db, fixedClientIP) + mustNoErr(t, err, "NewManager") + + mux := http.NewServeMux() + mgr.RegisterRoutes(mux) + + cbRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true) + mustRedirect(t, cbRec, "/who/?auth_error=auth_failed", "OIDC callback with mismatched UserInfo sub") + if c := findCookie(cbRec.Result().Cookies(), "who_session"); c != nil && c.Value != "" { + t.Fatalf("expected no who_session cookie on UserInfo sub mismatch, got %+v", c) + } + + sessions, err := db.ListSessions(ctx) + mustNoErr(t, err, "ListSessions") + if len(sessions) != 0 { + t.Fatalf("expected 0 sessions in DB on UserInfo sub mismatch, got %d", len(sessions)) + } +} + +func TestOIDCCallbackSkipsUserInfoWhenIDTokenComplete(t *testing.T) { + ctx := context.Background() + db := openAuthTestDB(t) + idp := newMockOIDCIdP(t) + verified := true + idp.setNextClaims(idTokenClaimsSpec{ + Sub: "user-1", + Email: "admin@example.com", + EmailVerified: &verified, + Name: "Admin User", + }) + idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, `{"error":"internal_error"}`, http.StatusInternalServerError) + }) + + mgr, err := auth.NewManager(auth.Config{ + Issuer: idp.server.URL, + ClientID: "who-admin", + ClientSecret: "super-secret", + BasePath: "/who", + AllowedEmails: []string{"admin@example.com"}, + HTTPClient: idp.server.Client(), + }, db, fixedClientIP) + mustNoErr(t, err, "NewManager") + + mux := http.NewServeMux() + mgr.RegisterRoutes(mux) + + cbRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true) + mustRedirect(t, cbRec, "/who/", "OIDC callback with complete ID token") + if got := idp.userInfoCalls.Load(); got != 0 { + t.Fatalf("expected 0 /userinfo calls when ID token is complete, got %d", got) + } + + sessions, err := db.ListSessions(ctx) + mustNoErr(t, err, "ListSessions") + if len(sessions) != 1 || sessions[0].Email != "admin@example.com" { + t.Fatalf("expected 1 session for admin@example.com, got %+v", sessions) + } +} + +func TestOIDCCallbackUserInfoPreservesIDTokenClaimsAndHandlesNameFallback(t *testing.T) { + ctx := context.Background() + db := openAuthTestDB(t) + idp := newMockOIDCIdP(t) + verified := true + + // 1. When ID token already has email + email_verified (only name missing), a 500 from /userinfo is non-fatal. + idp.setNextClaims(idTokenClaimsSpec{ + Sub: "user-1", + Email: "admin@example.com", + EmailVerified: &verified, + }) + idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, `{"error":"unavailable"}`, http.StatusInternalServerError) + }) + + mgr, err := auth.NewManager(auth.Config{ + Issuer: idp.server.URL, + ClientID: "who-admin", + ClientSecret: "super-secret", + BasePath: "/who", + AllowedEmails: []string{"admin@example.com"}, + HTTPClient: idp.server.Client(), + }, db, fixedClientIP) + mustNoErr(t, err, "NewManager") + + mux := http.NewServeMux() + mgr.RegisterRoutes(mux) + + cbRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true) + mustRedirect(t, cbRec, "/who/", "non-fatal /userinfo failure when only name missing") + + // 2. UserInfo fills only missing fields without overwriting signed ID token claims. + idp.setNextClaims(idTokenClaimsSpec{ + Sub: "user-2", + Email: "admin@example.com", + EmailVerified: &verified, + }) + idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) { + writeTestJSON(w, map[string]any{ + "sub": "user-2", + "email": "other@example.com", + "email_verified": false, + "name": "Hydrated Name", + }) + }) + + partialRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true) + mustRedirect(t, partialRec, "/who/", "partial UserInfo hydration keeps signed ID token claims") + + unverified := false + idp.setNextClaims(idTokenClaimsSpec{ + Sub: "user-3", + Email: "signed@example.com", + EmailVerified: &unverified, + }) + idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) { + writeTestJSON(w, map[string]any{ + "sub": "user-3", + "email": "admin@example.com", + "email_verified": true, + "name": "Denied Name", + }) + }) + + deniedRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true) + mustRedirect(t, deniedRec, "/who/?auth_error=access_denied", "signed ID token claims not overwritten by UserInfo") + + sessions, err := db.ListSessions(ctx) + mustNoErr(t, err, "ListSessions") + if len(sessions) != 2 { + t.Fatalf("expected 2 sessions, got %+v", sessions) + } + bySub := map[string]storage.Session{} + for _, s := range sessions { + bySub[s.Sub] = s + } + if u2 := bySub["user-2"]; u2.Email != "admin@example.com" || !u2.EmailVerified || u2.Name != "Hydrated Name" { + t.Fatalf("expected user-2 to preserve signed email/email_verified and hydrate Name, got %+v", u2) + } + + // 3. When ID token lacks email and advertised /userinfo returns 500, fail closed with auth_failed. + idp.setNextClaims(idTokenClaimsSpec{Sub: "user-4"}) + idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, `{"error":"internal_error"}`, http.StatusInternalServerError) + }) + errRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true) + mustRedirect(t, errRec, "/who/?auth_error=auth_failed", "/userinfo 500 when ID token lacks email") +} diff --git a/main.go b/main.go index 9ee0565..bd6da11 100644 --- a/main.go +++ b/main.go @@ -37,6 +37,7 @@ type RuntimeOptions struct { ConfigPath string DataDir string BasePath string + DDNSEndpoint string OIDCIssuer string OIDCClientID string OIDCClientSecret string @@ -99,6 +100,7 @@ func parseRuntimeOptions(args []string, getenv func(string) string) (RuntimeOpti } opts.BasePath = normalizedBase + opts.DDNSEndpoint = strings.TrimSpace(opts.DDNSEndpoint) opts.OIDCIssuer = strings.TrimSpace(opts.OIDCIssuer) opts.OIDCClientID = strings.TrimSpace(opts.OIDCClientID) opts.OIDCRedirectURL = strings.TrimSpace(opts.OIDCRedirectURL) @@ -122,6 +124,7 @@ func newRuntimeFlagSet( fset.StringVar(&opts.ConfigPath, "config", strings.TrimSpace(getenv("WHO_CONFIG")), "Optional seed config.json file path (env: WHO_CONFIG)") fset.StringVar(&opts.DataDir, "data-dir", envOrDefault(getenv, "WHO_DATA_DIR", defaultDataDir), "Directory holding who.db SQLite database (env: WHO_DATA_DIR)") fset.StringVar(rawBasePath, "base-path", strings.TrimSpace(getenv("WHO_BASE_PATH")), "URL prefix for admin UI, /auth/*, and /api/v1/* (env: WHO_BASE_PATH)") + fset.StringVar(&opts.DDNSEndpoint, "ddns-endpoint", strings.TrimSpace(getenv("WHO_DDNS_ENDPOINT")), "Optional DDNS provider endpoint override (env: WHO_DDNS_ENDPOINT)") fset.StringVar(&opts.OIDCIssuer, "oidc-issuer", strings.TrimSpace(getenv("WHO_OIDC_ISSUER")), "OIDC issuer URL (env: WHO_OIDC_ISSUER)") fset.StringVar(&opts.OIDCClientID, "oidc-client-id", strings.TrimSpace(getenv("WHO_OIDC_CLIENT_ID")), "OIDC client ID (env: WHO_OIDC_CLIENT_ID)") fset.StringVar(&opts.OIDCClientSecret, "oidc-client-secret", getenv("WHO_OIDC_CLIENT_SECRET"), "OIDC client secret (env: WHO_OIDC_CLIENT_SECRET)") @@ -266,11 +269,12 @@ func initServer(ctx context.Context, opts *RuntimeOptions, db *storage.DB, acces } server := &Server{ - db: db, - store: NewStore(), - accessLog: accessLogger, - auth: authMgr, - verbose: opts.Verbose, + db: db, + store: NewStore(), + accessLog: accessLogger, + auth: authMgr, + ddnsEndpoint: opts.DDNSEndpoint, + verbose: opts.Verbose, } if err := server.ReloadFromDB(ctx); err != nil { return nil, fmt.Errorf("reload runtime configuration: %w", err) diff --git a/main_test.go b/main_test.go index 45b3484..9db0e20 100644 --- a/main_test.go +++ b/main_test.go @@ -720,6 +720,51 @@ func assertRuntimeOptionVerboseAndValidation(t *testing.T) { } } +func TestParseRuntimeOptionsDDNSEndpoint(t *testing.T) { + defaults, err := parseRuntimeOptions(nil, func(string) string { return "" }) + if err != nil { + t.Fatalf("parseRuntimeOptions defaults error: %v", err) + } + if defaults.DDNSEndpoint != "" { + t.Fatalf("default DDNSEndpoint = %q, want empty string", defaults.DDNSEndpoint) + } + + getenv := func(k string) string { + if k == "WHO_DDNS_ENDPOINT" { + return " http://mock-sink:9999 " + } + return "" + } + fromEnv, err := parseRuntimeOptions(nil, getenv) + if err != nil { + t.Fatalf("parseRuntimeOptions env error: %v", err) + } + if fromEnv.DDNSEndpoint != "http://mock-sink:9999" { + t.Fatalf("env DDNSEndpoint = %q, want %q", fromEnv.DDNSEndpoint, "http://mock-sink:9999") + } + + overridden, err := parseRuntimeOptions([]string{"--ddns-endpoint", " http://override:8080 "}, getenv) + if err != nil { + t.Fatalf("parseRuntimeOptions CLI override error: %v", err) + } + if overridden.DDNSEndpoint != "http://override:8080" { + t.Fatalf("CLI override DDNSEndpoint = %q, want %q", overridden.DDNSEndpoint, "http://override:8080") + } + + db, _ := openAccessLogTestDB(t) + logger := NewAccessLogger(db) + t.Cleanup(func() { + _ = logger.Close(context.Background()) + }) + srv, initErr := initServer(context.Background(), &fromEnv, db, logger) + if initErr != nil { + t.Fatalf("initServer: %v", initErr) + } + if srv.ddnsEndpoint != "http://mock-sink:9999" { + t.Fatalf("srv.ddnsEndpoint = %q, want %q", srv.ddnsEndpoint, "http://mock-sink:9999") + } +} + func TestRetentionPassPrunesLogsAndExpiredSessions(t *testing.T) { ctx := context.Background() db, _ := openAccessLogTestDB(t) diff --git a/ui/src/components/PageHeader.svelte b/ui/src/components/PageHeader.svelte index ce8c0aa..47d5f85 100644 --- a/ui/src/components/PageHeader.svelte +++ b/ui/src/components/PageHeader.svelte @@ -27,7 +27,7 @@ $effect(() => {
+
e.stopPropagation()} style="position-anchor: {anchorName};" class="who-popover-anchored min-w-44 rounded-xl border border-border bg-popover p-1 text-popover-foreground shadow-overlay" > diff --git a/ui/src/lib/viewEffects.test.js b/ui/src/lib/viewEffects.test.js index b3f3ffa..a392b5a 100644 --- a/ui/src/lib/viewEffects.test.js +++ b/ui/src/lib/viewEffects.test.js @@ -284,3 +284,51 @@ test("PageHeader root
includes shrink-0 so mobile top bar does not coll `expected
static classes to include "shrink-0", got: ${staticClasses.join(" ")}`, ); }); + +test("ActionMenu avoids native click addEventListener so Svelte 5 delegated item onclick handlers fire", () => { + const relPath = "components/ActionMenu.svelte"; + const src = fs.readFileSync(path.join(SRC_DIR, relPath), "utf8"); + const ast = parse(src, { modern: true, filename: relPath }); + const compiled = compile(src, { generate: "client", filename: relPath }); + + assert.deepEqual( + compiled.warnings, + [], + `expected 0 Svelte compiler warnings in ${relPath}, got: ${JSON.stringify(compiled.warnings)}`, + ); + + let hasNativeClickListener = false; + walkAst(ast.instance, (node) => { + if ( + node.type === "CallExpression" && + node.callee?.type === "MemberExpression" && + node.callee.property?.type === "Identifier" && + node.callee.property.name === "addEventListener" && + node.arguments?.[0]?.type === "Literal" && + node.arguments[0].value === "click" + ) { + hasNativeClickListener = true; + } + }); + assert.equal( + hasNativeClickListener, + false, + "ActionMenu.svelte must not register native addEventListener('click', ...) on the popover container, which stops propagation before Svelte 5 root delegation", + ); + + let popoverHasDelegatedOnclick = false; + walkAst(ast.fragment, (node) => { + if (node.type !== "RegularElement" || node.name !== "div") return; + const attrs = node.attributes ?? []; + const hasPopover = attrs.some((a) => a.type === "Attribute" && a.name === "popover"); + const hasOnclick = attrs.some((a) => a.type === "Attribute" && a.name === "onclick"); + if (hasPopover && hasOnclick) { + popoverHasDelegatedOnclick = true; + } + }); + assert.equal( + popoverHasDelegatedOnclick, + true, + "ActionMenu.svelte popover container should use Svelte-delegated onclick to isolate row clicks", + ); +}); From 9ab0f59af5008295411c9035fed6c9d7530b7cdb Mon Sep 17 00:00:00 2001 From: tracyhatemice Date: Sun, 29 Nov 2026 19:33:48 +0800 Subject: [PATCH 06/10] test(e2e): add desktop UI, CRUD, live side-effect, logs, and settings Playwright suites --- e2e/tests/ddns-webhooks-touch.spec.mjs | 536 +++++++++++++++++++++ e2e/tests/logs-and-settings.spec.mjs | 487 +++++++++++++++++++ e2e/tests/navigation-and-overview.spec.mjs | 231 +++++++++ e2e/tests/records-and-drawer.spec.mjs | 296 ++++++++++++ 4 files changed, 1550 insertions(+) create mode 100644 e2e/tests/ddns-webhooks-touch.spec.mjs create mode 100644 e2e/tests/logs-and-settings.spec.mjs create mode 100644 e2e/tests/navigation-and-overview.spec.mjs create mode 100644 e2e/tests/records-and-drawer.spec.mjs diff --git a/e2e/tests/ddns-webhooks-touch.spec.mjs b/e2e/tests/ddns-webhooks-touch.spec.mjs new file mode 100644 index 0000000..3d0f8a8 --- /dev/null +++ b/e2e/tests/ddns-webhooks-touch.spec.mjs @@ -0,0 +1,536 @@ +import fs from "node:fs"; +import path from "node:path"; +import { expect, test } from "@playwright/test"; +import { + TOUCH_HOST_DIR, + apiFetch, + getSinkRequests, + rawAppFetch, + readTouchFile, + resetMockSink, + waitForSinkRequest, +} from "./helpers.mjs"; + +const HOST_IAM = "e2e-fx-host"; +const ALIAS_IAM = "e2e-fx-alias"; +const SECRET_NAME = "e2e-r53-sec"; +const ACCESS_KEY = "AKIAIOSFODNN7EXAMPLE"; +const SECRET_KEY = "e2e-secret-access-key-0123456789"; +const DDNS_DOMAIN = "ddns.e2e.example"; +const HOOK_OK_URL = "http://mock-sink:9999/hook/e2e"; +const HOOK_FAIL_URL = "http://mock-sink:9999/hook/fail"; +const TOUCH_PATH_1 = "/touch/e2e-alias.json"; +const TOUCH_FILE_1 = "e2e-alias.json"; +const TOUCH_PATH_2 = "/touch/e2e-alias-v2.json"; +const TOUCH_FILE_2 = "e2e-alias-v2.json"; + +function attachErrorCollector(page) { + const pageErrors = []; + const consoleErrors = []; + page.on("pageerror", (err) => { + pageErrors.push(err?.message || String(err)); + }); + page.on("console", (msg) => { + if (msg.type() === "error") { + consoleErrors.push(msg.text()); + } + }); + return { pageErrors, consoleErrors }; +} + +async function cleanupSideEffectFixtures() { + const touchRes = await apiFetch("GET", "/touch"); + if (touchRes.ok) { + for (const item of touchRes.data?.items ?? []) { + if ( + item.iam === ALIAS_IAM || + item.iam === HOST_IAM || + item.path === TOUCH_PATH_1 || + item.path === TOUCH_PATH_2 + ) { + const del = await apiFetch("DELETE", `/touch/${item.id}`); + expect([200, 204, 404]).toContain(del.status); + } + } + } + + const whRes = await apiFetch("GET", "/webhooks"); + if (whRes.ok) { + for (const item of whRes.data?.items ?? []) { + if ( + item.iam === HOST_IAM || + item.url === HOOK_OK_URL || + item.url === HOOK_FAIL_URL + ) { + const del = await apiFetch("DELETE", `/webhooks/${item.id}`); + expect([200, 204, 404]).toContain(del.status); + } + } + } + + const ddnsRes = await apiFetch("GET", "/ddns"); + if (ddnsRes.ok) { + for (const item of ddnsRes.data?.items ?? []) { + if (item.iam === HOST_IAM || item.domain === DDNS_DOMAIN) { + const del = await apiFetch("DELETE", `/ddns/${item.id}`); + expect([200, 204, 404]).toContain(del.status); + } + } + } + + const secRes = await apiFetch("GET", "/secrets"); + if (secRes.ok) { + for (const sec of secRes.data?.items ?? []) { + if (sec.name === SECRET_NAME) { + const del = await apiFetch("DELETE", `/secrets/${sec.id}`); + expect([200, 204, 404]).toContain(del.status); + } + } + } + + for (const iam of [ALIAS_IAM, HOST_IAM]) { + const del = await apiFetch("DELETE", `/records/${encodeURIComponent(iam)}`); + expect([200, 204, 404]).toContain(del.status); + } + + for (const filename of [TOUCH_FILE_1, TOUCH_FILE_2]) { + await fs.promises.rm(path.join(TOUCH_HOST_DIR, filename), { force: true }); + } +} + +test.describe("DDNS, Webhooks, Touch Files CRUD & Live Side Effects", () => { + test.beforeAll(async () => { + await cleanupSideEffectFixtures(); + await resetMockSink(); + + const hostCreate = await apiFetch("POST", "/records", { + body: { iam: HOST_IAM, isAlias: false, ip: "198.51.100.70" }, + }); + expect(hostCreate.status).toBe(201); + + const aliasCreate = await apiFetch("POST", "/records", { + body: { iam: ALIAS_IAM, isAlias: true, alias: [HOST_IAM] }, + }); + expect(aliasCreate.status).toBe(201); + }); + + test.afterAll(async () => { + await cleanupSideEffectFixtures(); + await resetMockSink(); + }); + + test("verifies Provider Secrets, DDNS Route53 XML, Webhooks, and Touch disk JSON end-to-end", async ({ + page, + }) => { + test.setTimeout(60_000); + const { pageErrors, consoleErrors } = attachErrorCollector(page); + + // ========================================================================= + // 1. Provider Secrets + DDNS CRUD & Live Route53 Side Effects + // ========================================================================= + await page.goto("/who/#/ddns"); + await expect(page.locator("#main header h1")).toHaveText("DDNS"); + + await page.getByRole("button", { name: "New DDNS Rule" }).click(); + const ddnsDialog = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { name: /DDNS Rule/i, level: 1 }), + }); + await expect(ddnsDialog).toBeVisible(); + + await ddnsDialog.getByRole("button", { name: "New Secret" }).click(); + const secretDialog = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { name: "New Provider Secret", level: 1 }), + }); + await expect(secretDialog).toBeVisible(); + + await secretDialog.getByLabel(/Secret Name/i).fill(SECRET_NAME); + await secretDialog.getByLabel(/AWS Access Key ID/i).fill(ACCESS_KEY); + await secretDialog.getByLabel(/AWS Secret Access Key/i).fill(SECRET_KEY); + await secretDialog.getByRole("button", { name: "Create Secret" }).click(); + await expect(secretDialog).toBeHidden(); + + await expect(ddnsDialog.locator('select[name="secretId"]')).toContainText(SECRET_NAME); + await ddnsDialog.getByLabel(/IAM Host Record/i).fill(HOST_IAM); + await ddnsDialog.getByLabel(/DNS Domain/i).fill(DDNS_DOMAIN); + await ddnsDialog.getByLabel(/Hosted Zone ID/i).fill("Z1E2EZONE"); + await ddnsDialog.getByLabel(/TTL \(seconds\)/i).fill("120"); + await expect(ddnsDialog.getByLabel("Auto (A/AAAA)")).toBeChecked(); + await ddnsDialog.getByRole("button", { name: "Create Rule" }).click(); + await expect(ddnsDialog).toBeHidden(); + + const ddnsRow = page.locator("tbody tr", { hasText: DDNS_DOMAIN }); + await expect(ddnsRow).toBeVisible(); + const ddnsDomainCell = ddnsRow.locator('th[scope="row"]'); + await expect(ddnsDomainCell).toContainText(DDNS_DOMAIN); + await expect(ddnsDomainCell).not.toContainText("Zone:"); + await expect(ddnsDomainCell).not.toContainText("Z1E2EZONE"); + + const ddnsProviderCell = ddnsRow.locator('td[data-col="Provider"]'); + await expect(ddnsProviderCell).toContainText("AWS Route53"); + await expect(ddnsProviderCell).not.toContainText(SECRET_NAME); + + // Verify ON DELETE RESTRICT guard in Settings -> Provider Secrets + await page.goto("/who/#/settings/secrets"); + await expect(page.locator("#main header h1")).toHaveText("Settings"); + const secretRow = page.locator("#settings-secrets tbody tr", { + has: page.locator('th[scope="row"]', { hasText: SECRET_NAME }), + }); + await expect(secretRow).toBeVisible(); + await expect(secretRow).toContainText(ACCESS_KEY); + await expect(secretRow).not.toContainText(SECRET_KEY); + await expect(secretRow).toContainText("1 rule"); + const secretDeleteBtn = secretRow.getByRole("button", { + name: `Delete secret ${SECRET_NAME}`, + }); + await expect(secretDeleteBtn).toBeDisabled(); + + // Check API masking and edit modal mask placeholder + const secretsApiRes = await apiFetch("GET", "/secrets"); + expect(secretsApiRes.status).toBe(200); + const createdSecret = (secretsApiRes.data?.items ?? []).find( + (s) => s.name === SECRET_NAME, + ); + expect(createdSecret).toBeTruthy(); + expect(createdSecret.credentials?.secret_key).toBe("••••••••"); + const blockedDeleteRes = await apiFetch("DELETE", `/secrets/${createdSecret.id}`); + expect(blockedDeleteRes.status).toBe(409); + + // Trigger live DDNS Route53 XML UPSERT via /iam + await resetMockSink(); + const ddnsIamRes = await rawAppFetch("GET", `/iam/${HOST_IAM}/198.51.100.71`); + expect(ddnsIamRes.status).toBe(200); + + const ddnsReq = await waitForSinkRequest( + (entry) => + entry.path === "/2013-04-01/hostedzone/Z1E2EZONE/rrset" && + entry.body.includes("198.51.100.71"), + { kind: "ddns", timeoutMs: 10_000 }, + ); + expect(ddnsReq.headers.authorization).toMatch( + new RegExp( + `^AWS4-HMAC-SHA256 Credential=${ACCESS_KEY}/\\d{8}/us-east-1/route53/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=[0-9a-f]{64}$`, + ), + ); + expect(ddnsReq.body).toContain(`${DDNS_DOMAIN}.`); + expect(ddnsReq.body).toContain("UPSERT"); + expect(ddnsReq.body).toContain("A"); + expect(ddnsReq.body).toContain("120"); + expect(ddnsReq.body).toContain("198.51.100.71"); + + // Return to DDNS page and confirm 200 OK badge + RecordDrawer delivery entry + await page.goto("/who/#/ddns"); + await expect(page.locator("#main header h1")).toHaveText("DDNS"); + await expect + .poll( + async () => { + await page.getByRole("button", { name: "Refresh" }).click(); + return await ddnsRow.locator('td[data-col="Last Delivery"]').textContent(); + }, + { timeout: 10_000, intervals: [300] }, + ) + .toContain("200 OK"); + + await ddnsRow.getByRole("button", { name: HOST_IAM, exact: true }).click(); + const drawer = page.locator("dialog.who-drawer[open]"); + await expect(drawer).toBeVisible(); + await expect( + drawer.getByRole("heading", { name: HOST_IAM, level: 1 }), + ).toBeVisible(); + const ddnsHistoryItem = drawer + .locator("ol > li") + .filter({ hasText: "198.51.100.71" }) + .first(); + await expect(ddnsHistoryItem).toContainText("DDNS"); + await expect(ddnsHistoryItem).toContainText(DDNS_DOMAIN); + await expect(ddnsHistoryItem).toContainText("200 OK"); + await drawer.getByRole("button", { name: "Close drawer" }).click(); + await expect(drawer).toHaveCount(0); + await expect(page.locator("dialog.who-drawer")).toBeHidden(); + + // Edit DDNS TTL to 300 and trigger Sync + await ddnsRow.getByRole("button", { name: `Edit ${DDNS_DOMAIN}` }).click(); + await expect(ddnsDialog).toBeVisible(); + await ddnsDialog.getByLabel(/TTL \(seconds\)/i).fill("300"); + await ddnsDialog.getByRole("button", { name: "Save Changes" }).click(); + await expect(ddnsDialog).toBeHidden(); + await expect(ddnsRow.locator('td[data-col="Type & TTL"]')).toContainText("300s"); + + await resetMockSink(); + await ddnsRow.getByRole("button", { name: `Sync ${DDNS_DOMAIN}` }).click(); + const ttlSyncReq = await waitForSinkRequest( + (entry) => + entry.path === "/2013-04-01/hostedzone/Z1E2EZONE/rrset" && + entry.body.includes("300"), + { kind: "ddns", timeoutMs: 10_000 }, + ); + expect(ttlSyncReq.body).toContain("198.51.100.71"); + + // Pause DDNS rule -> verify zero deliveries while paused + const ddnsSwitch = ddnsRow.getByRole("switch", { + name: `DDNS rule for ${DDNS_DOMAIN}`, + }); + await ddnsSwitch.click(); + await expect(ddnsSwitch).toHaveAttribute("aria-checked", "false"); + + await resetMockSink(); + const pausedDdnsIam = await rawAppFetch("GET", `/iam/${HOST_IAM}/198.51.100.72`); + expect(pausedDdnsIam.status).toBe(200); + await page.waitForTimeout(800); + expect(await getSinkRequests("ddns")).toEqual([]); + + // Edit zoneId to FAILZONE, re-enable, Sync -> verify 400 error badge + await ddnsRow.getByRole("button", { name: `Edit ${DDNS_DOMAIN}` }).click(); + await expect(ddnsDialog).toBeVisible(); + await ddnsDialog.getByLabel(/Hosted Zone ID/i).fill("FAILZONE"); + await ddnsDialog.getByRole("switch", { name: "Enable DDNS rule" }).click(); + await ddnsDialog.getByRole("button", { name: "Save Changes" }).click(); + await expect(ddnsDialog).toBeHidden(); + await expect(ddnsSwitch).toHaveAttribute("aria-checked", "true"); + + await ddnsRow.getByRole("button", { name: `Sync ${DDNS_DOMAIN}` }).click(); + await expect(ddnsRow.locator('td[data-col="Last Delivery"]')).toContainText( + "400 Error", + ); + + // Delete DDNS rule, then delete secret cleanly in Settings + await ddnsRow.getByRole("button", { name: `Delete ${DDNS_DOMAIN}` }).click(); + const ddnsDelConfirm = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { + name: `Delete DDNS rule for ${DDNS_DOMAIN}?`, + level: 1, + }), + }); + await expect(ddnsDelConfirm).toBeVisible(); + await ddnsDelConfirm.getByRole("button", { name: "Delete Rule" }).click(); + await expect(ddnsDelConfirm).toBeHidden(); + await expect(ddnsRow).toHaveCount(0); + + await page.goto("/who/#/settings/secrets"); + await expect(secretRow).toContainText("Unused"); + await expect(secretDeleteBtn).toBeEnabled(); + await secretDeleteBtn.click(); + const secDelConfirm = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { + name: `Delete secret "${SECRET_NAME}"?`, + level: 1, + }), + }); + await expect(secDelConfirm).toBeVisible(); + await secDelConfirm.getByRole("button", { name: "Delete Secret" }).click(); + await expect(secDelConfirm).toBeHidden(); + await expect(secretRow).toHaveCount(0); + + // ========================================================================= + // 2. Webhooks CRUD & Live Delivery Side Effects + // ========================================================================= + await page.goto("/who/#/webhooks"); + await expect(page.locator("#main header h1")).toHaveText("Webhooks"); + + await page.getByRole("button", { name: "New Webhook" }).click(); + const webhookDialog = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { name: /Webhook/i, level: 1 }), + }); + await expect(webhookDialog).toBeVisible(); + + await webhookDialog.getByLabel(/IAM Host Record/i).fill(HOST_IAM); + await webhookDialog.getByLabel("Method").selectOption("POST"); + await webhookDialog.getByLabel(/Destination URL/i).fill(HOOK_OK_URL); + await webhookDialog.getByRole("button", { name: "Add Header" }).click(); + await webhookDialog.getByLabel("Header 1 name").fill("X-E2E-Hook"); + await webhookDialog.getByLabel("Header 1 value").fill("secret-val"); + await webhookDialog.getByRole("button", { name: "Create Webhook" }).click(); + await expect(webhookDialog).toBeHidden(); + + const hookRow = page.locator("tbody tr", { hasText: HOOK_OK_URL }); + await expect(hookRow).toBeVisible(); + await expect(hookRow.locator('td[data-col="Headers"]')).toContainText("1 header"); + + await resetMockSink(); + const hookIamRes = await rawAppFetch("GET", `/iam/${HOST_IAM}/198.51.100.73`); + expect(hookIamRes.status).toBe(200); + + const hookReq = await waitForSinkRequest( + (entry) => + entry.path === "/hook/e2e" && entry.body.includes("198.51.100.73"), + { kind: "webhook", timeoutMs: 10_000 }, + ); + expect(hookReq.method).toBe("POST"); + expect(hookReq.headers["x-e2e-hook"]).toBe("secret-val"); + const hookPayload = JSON.parse(hookReq.body); + expect(hookPayload).toMatchObject({ + iam: HOST_IAM, + ip: "198.51.100.73", + timestamp: expect.any(String), + }); + expect(Number.isNaN(Date.parse(hookPayload.timestamp))).toBe(false); + + await expect + .poll( + async () => { + await page.getByRole("button", { name: "Refresh" }).click(); + return await hookRow.locator('td[data-col="Last Delivery"]').textContent(); + }, + { timeout: 10_000, intervals: [300] }, + ) + .toContain("200 OK"); + + await hookRow.getByRole("button", { name: HOST_IAM, exact: true }).click(); + await expect(drawer).toBeVisible(); + const hookHistoryItem = drawer + .locator("ol > li") + .filter({ hasText: "198.51.100.73" }) + .first(); + await expect(hookHistoryItem).toContainText("Webhook"); + await expect(hookHistoryItem).toContainText(HOOK_OK_URL); + await expect(hookHistoryItem).toContainText("200 OK"); + await drawer.getByRole("button", { name: "Close drawer" }).click(); + await expect(drawer).toHaveCount(0); + await expect(page.locator("dialog.who-drawer")).toBeHidden(); + + // Exercise row Test button + await resetMockSink(); + await hookRow.getByRole("button", { name: `Test ${HOOK_OK_URL}` }).click(); + const testHookReq = await waitForSinkRequest( + (entry) => + entry.path === "/hook/e2e" && entry.body.includes("198.51.100.73"), + { kind: "webhook", timeoutMs: 10_000 }, + ); + expect(testHookReq.headers["x-e2e-hook"]).toBe("secret-val"); + + // Pause webhook -> update IP (keep .74 unused for Touch Files) -> assert 0 deliveries + const hookSwitch = hookRow.getByRole("switch", { + name: `Webhook to ${HOOK_OK_URL}`, + }); + await hookSwitch.click(); + await expect(hookSwitch).toHaveAttribute("aria-checked", "false"); + + await resetMockSink(); + const pausedHookIam = await rawAppFetch("GET", `/iam/${HOST_IAM}/198.51.100.83`); + expect(pausedHookIam.status).toBe(200); + await page.waitForTimeout(800); + expect(await getSinkRequests("webhook")).toEqual([]); + + // Edit URL to /hook/fail, re-enable, Test -> verify 500 error badge + await hookRow.getByRole("button", { name: `Edit ${HOOK_OK_URL}` }).click(); + await expect(webhookDialog).toBeVisible(); + await webhookDialog.getByLabel(/Destination URL/i).fill(HOOK_FAIL_URL); + await webhookDialog.getByRole("switch", { name: "Enable webhook" }).click(); + await webhookDialog.getByRole("button", { name: "Save Changes" }).click(); + await expect(webhookDialog).toBeHidden(); + + const failHookRow = page.locator("tbody tr", { hasText: HOOK_FAIL_URL }); + await expect(failHookRow).toBeVisible(); + await failHookRow.getByRole("button", { name: `Test ${HOOK_FAIL_URL}` }).click(); + await expect(failHookRow.locator('td[data-col="Last Delivery"]')).toContainText( + "500 Error", + ); + + await failHookRow.getByRole("button", { name: `Delete ${HOOK_FAIL_URL}` }).click(); + const hookDelConfirm = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { name: "Delete webhook?", level: 1 }), + }); + await expect(hookDelConfirm).toBeVisible(); + await hookDelConfirm.getByRole("button", { name: "Delete Webhook" }).click(); + await expect(hookDelConfirm).toBeHidden(); + await expect(failHookRow).toHaveCount(0); + + // ========================================================================= + // 3. Touch Files CRUD & Live Disk JSON Output + // ========================================================================= + await page.goto("/who/#/touch"); + await expect(page.locator("#main header h1")).toHaveText("Touch Files"); + + await page.getByRole("button", { name: "New Touch File" }).click(); + const touchDialog = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { name: /Touch File/i, level: 1 }), + }); + await expect(touchDialog).toBeVisible(); + + await touchDialog.getByLabel(/IAM Record or Alias/i).fill(ALIAS_IAM); + await touchDialog.getByLabel(/Destination File Path/i).fill(TOUCH_PATH_1); + await touchDialog.getByRole("button", { name: "Create Touch File" }).click(); + await expect(touchDialog).toBeHidden(); + + const touchRow1 = page.locator("tbody tr", { hasText: TOUCH_PATH_1 }); + await expect(touchRow1).toBeVisible(); + + const touchIamRes = await rawAppFetch("GET", `/iam/${HOST_IAM}/198.51.100.74`); + expect(touchIamRes.status).toBe(200); + + await expect + .poll(async () => await readTouchFile(TOUCH_FILE_1), { + timeout: 10_000, + intervals: [150], + }) + .toMatchObject({ + iam: ALIAS_IAM, + ip: ["198.51.100.74"], + last_update: expect.any(Number), + }); + const written1 = await readTouchFile(TOUCH_FILE_1); + expect(written1.last_update).toBeGreaterThan(0); + + await page.getByRole("button", { name: "Refresh" }).click(); + await touchRow1 + .getByRole("button", { name: `Preview JSON for ${TOUCH_PATH_1}` }) + .click(); + const previewDialog = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { name: "Live TouchRecord Preview", level: 1 }), + }); + await expect(previewDialog).toBeVisible(); + await expect(previewDialog.locator("pre")).toContainText(ALIAS_IAM); + await expect(previewDialog.locator("pre")).toContainText("198.51.100.74"); + await previewDialog.getByRole("button", { name: "Done" }).click(); + await expect(previewDialog).toBeHidden(); + + // Edit touch path to v2 and click Write Now + await touchRow1.getByRole("button", { name: `Edit ${TOUCH_PATH_1}` }).click(); + await expect(touchDialog).toBeVisible(); + await touchDialog.getByLabel(/Destination File Path/i).fill(TOUCH_PATH_2); + await touchDialog.getByRole("button", { name: "Save Changes" }).click(); + await expect(touchDialog).toBeHidden(); + + const touchRow2 = page.locator("tbody tr", { hasText: TOUCH_PATH_2 }); + await expect(touchRow2).toBeVisible(); + await touchRow2 + .getByRole("button", { name: `Write Now ${TOUCH_PATH_2}` }) + .click(); + + await expect + .poll(async () => await readTouchFile(TOUCH_FILE_2), { + timeout: 10_000, + intervals: [150], + }) + .toMatchObject({ + iam: ALIAS_IAM, + ip: ["198.51.100.74"], + last_update: expect.any(Number), + }); + + // Pause touch rule -> update IP -> assert v2 JSON file retains old IP + const touchSwitch = touchRow2.getByRole("switch", { + name: `Touch file ${TOUCH_PATH_2}`, + }); + await touchSwitch.click(); + await expect(touchSwitch).toHaveAttribute("aria-checked", "false"); + + const pausedTouchIam = await rawAppFetch("GET", `/iam/${HOST_IAM}/198.51.100.75`); + expect(pausedTouchIam.status).toBe(200); + await page.waitForTimeout(800); + const v2AfterPause = await readTouchFile(TOUCH_FILE_2); + expect(v2AfterPause?.ip).toEqual(["198.51.100.74"]); + + // Delete touch rule + await touchRow2.getByRole("button", { name: `Delete ${TOUCH_PATH_2}` }).click(); + const touchDelConfirm = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { name: "Delete touch file rule?", level: 1 }), + }); + await expect(touchDelConfirm).toBeVisible(); + await touchDelConfirm.getByRole("button", { name: "Delete Rule" }).click(); + await expect(touchDelConfirm).toBeHidden(); + await expect(touchRow2).toHaveCount(0); + + expect(pageErrors).toEqual([]); + expect(consoleErrors).toEqual([]); + }); +}); diff --git a/e2e/tests/logs-and-settings.spec.mjs b/e2e/tests/logs-and-settings.spec.mjs new file mode 100644 index 0000000..e0f4d68 --- /dev/null +++ b/e2e/tests/logs-and-settings.spec.mjs @@ -0,0 +1,487 @@ +import fs from "node:fs"; +import { expect, test } from "@playwright/test"; +import { ADMIN_USER, apiFetch, rawAppFetch } from "./helpers.mjs"; + +const LOG_HOST = "e2e-log-host"; +const BACKUP_REC = "e2e-backup-rec"; + +let originalSettings = { + accessLogRetentionDays: 30, + auditLogRetentionDays: 90, + ipHistoryRetentionDays: 0, +}; + +function attachErrorCollector(page) { + const pageErrors = []; + const consoleErrors = []; + page.on("pageerror", (err) => { + pageErrors.push(err?.message || String(err)); + }); + page.on("console", (msg) => { + if (msg.type() === "error") { + consoleErrors.push(msg.text()); + } + }); + return { pageErrors, consoleErrors }; +} + +function toLocalDatetimeInput(ms) { + const pad2 = (n) => String(n).padStart(2, "0"); + const d = new Date(ms); + return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}T${pad2(d.getHours())}:${pad2(d.getMinutes())}`; +} + +test.describe("Access Log, Audit Log & Settings", () => { + test.beforeAll(async () => { + for (const iam of [LOG_HOST, BACKUP_REC]) { + await apiFetch("DELETE", `/records/${encodeURIComponent(iam)}`); + } + + const settingsRes = await apiFetch("GET", "/settings"); + if (settingsRes.ok && settingsRes.data) { + originalSettings = { + accessLogRetentionDays: settingsRes.data.accessLogRetentionDays ?? 30, + auditLogRetentionDays: settingsRes.data.auditLogRetentionDays ?? 90, + ipHistoryRetentionDays: settingsRes.data.ipHistoryRetentionDays ?? 0, + }; + } + + const createRes = await apiFetch("POST", "/records", { + body: { iam: LOG_HOST, isAlias: false, ip: "198.51.100.90" }, + }); + expect(createRes.status).toBe(201); + + const updateRes = await apiFetch("PUT", `/records/${LOG_HOST}`, { + body: { iam: LOG_HOST, isAlias: false, ip: "198.51.100.91" }, + }); + expect(updateRes.status).toBe(200); + + const headers = { "User-Agent": "who-e2e-logs/1.0" }; + for (let i = 0; i < 18; i++) { + const res = await rawAppFetch("GET", "/whoami", { headers }); + expect(res.status).toBe(200); + } + for (let i = 0; i < 6; i++) { + const ip = `198.51.100.${92 + (i % 2)}`; + const res = await rawAppFetch("GET", `/iam/${LOG_HOST}/${ip}`, { headers }); + expect(res.status).toBe(200); + } + for (let i = 0; i < 6; i++) { + const res = await rawAppFetch("GET", `/whois/${LOG_HOST}`, { headers }); + expect(res.status).toBe(200); + } + + await expect + .poll( + async () => { + const all = await apiFetch("GET", "/access-logs?range=1h&pageSize=1"); + const iam = await apiFetch( + "GET", + `/access-logs?range=1h&endpoint=iam&iam=${LOG_HOST}&pageSize=1`, + ); + return { + total: all.data?.total ?? 0, + iamTotal: iam.data?.total ?? 0, + }; + }, + { timeout: 10_000, intervals: [150] }, + ) + .toEqual({ + total: expect.any(Number), + iamTotal: expect.any(Number), + }); + + await expect + .poll( + async () => { + const all = await apiFetch("GET", "/access-logs?range=1h&pageSize=1"); + return all.data?.total ?? 0; + }, + { timeout: 10_000, intervals: [150] }, + ) + .toBeGreaterThanOrEqual(30); + + await expect + .poll( + async () => { + const iam = await apiFetch( + "GET", + `/access-logs?range=1h&endpoint=iam&iam=${LOG_HOST}&pageSize=1`, + ); + return iam.data?.total ?? 0; + }, + { timeout: 10_000, intervals: [150] }, + ) + .toBeGreaterThanOrEqual(6); + }); + + test.afterAll(async () => { + await apiFetch("PUT", "/settings", { body: originalSettings }); + for (const iam of [LOG_HOST, BACKUP_REC]) { + const res = await apiFetch("DELETE", `/records/${encodeURIComponent(iam)}`); + expect([200, 204, 404]).toContain(res.status); + } + }); + + test("Access Log: TimeRangePicker layout/presets/custom, FilterBar autocomplete, AccessDrawer, Top view, and Pagination", async ({ + page, + }) => { + const { pageErrors, consoleErrors } = attachErrorCollector(page); + + await page.goto("/who/#/access"); + await expect(page.locator("#main header h1")).toHaveText("Access Log"); + await expect(page.locator("tbody tr").first()).toBeVisible(); + + // Refresh sits to the left of TimeRangePicker + const refreshBtn = page.getByRole("button", { name: "Refresh" }); + const timePickerBtn = page.getByRole("button", { name: /^Time range:/ }); + const [refreshBox, pickerBox] = await Promise.all([ + refreshBtn.boundingBox(), + timePickerBtn.boundingBox(), + ]); + expect(refreshBox).not.toBeNull(); + expect(pickerBox).not.toBeNull(); + expect(refreshBox.x).toBeLessThan(pickerBox.x); + expect(refreshBox.x + refreshBox.width).toBeLessThanOrEqual(pickerBox.x + 2); + + // Presets 1h -> 24h -> custom range -> Reset + await timePickerBtn.click(); + const pickerPopover = page.locator('[popover="auto"]:popover-open'); + await expect(pickerPopover).toBeVisible(); + await Promise.all([ + page.waitForResponse( + (res) => + res.url().includes("/who/api/v1/access-logs") && + res.url().includes("range=1h") && + res.status() === 200, + ), + pickerPopover.getByRole("button", { name: /Last 1 hour/ }).click(), + ]); + await expect(timePickerBtn).toHaveAttribute("aria-label", /Last 1 hour/); + + await timePickerBtn.click(); + await expect(pickerPopover).toBeVisible(); + await Promise.all([ + page.waitForResponse( + (res) => + res.url().includes("/who/api/v1/access-logs") && + res.url().includes("range=24h") && + res.status() === 200, + ), + pickerPopover.getByRole("button", { name: /Last 24 hours/ }).click(), + ]); + await expect(timePickerBtn).toHaveAttribute("aria-label", /Last 24 hours/); + + const nowMs = Date.now(); + await timePickerBtn.click(); + await expect(pickerPopover).toBeVisible(); + await pickerPopover + .getByLabel("Start") + .fill(toLocalDatetimeInput(nowMs - 2 * 3_600_000)); + await pickerPopover + .getByLabel("End") + .fill(toLocalDatetimeInput(nowMs + 3_600_000)); + await Promise.all([ + page.waitForResponse( + (res) => + res.url().includes("/who/api/v1/access-logs") && + res.url().includes("from=") && + res.url().includes("to=") && + res.status() === 200, + ), + pickerPopover.getByRole("button", { name: "Apply" }).click(), + ]); + await expect(timePickerBtn).not.toHaveAttribute("aria-label", /Last 24 hours/); + + await timePickerBtn.click(); + await expect(pickerPopover).toBeVisible(); + await Promise.all([ + page.waitForResponse( + (res) => + res.url().includes("/who/api/v1/access-logs") && + res.url().includes("range=24h") && + res.status() === 200, + ), + pickerPopover.getByRole("button", { name: "Reset" }).click(), + ]); + await expect(timePickerBtn).toHaveAttribute("aria-label", /Last 24 hours/); + + // FilterBar autocomplete -> endpoint:iam -> AccessDrawer + const filterInput = page.locator("[data-search-input]"); + await filterInput.click(); + await filterInput.fill("endpoint:"); + const suggestions = page.getByRole("listbox", { name: "endpoint suggestions" }); + await expect(suggestions).toBeVisible(); + await Promise.all([ + page.waitForResponse( + (res) => + res.url().includes("/who/api/v1/access-logs") && + res.url().includes("endpoint=iam") && + res.status() === 200, + ), + suggestions.getByRole("option", { name: /\/iam/ }).click(), + ]); + await expect( + page.getByRole("button", { name: "Remove endpoint:iam filter" }), + ).toBeVisible(); + + const firstRow = page.locator("tbody tr").first(); + await expect(firstRow.locator('th[scope="row"]')).toContainText("/iam"); + await firstRow.click(); + + const drawer = page.locator("#main dialog.who-drawer"); + await expect(drawer).toBeVisible(); + await expect(drawer).toContainText("Client & Resolution Metadata"); + await expect(drawer).toContainText("Timestamps"); + await drawer.getByRole("button", { name: "Close drawer" }).click(); + await expect(drawer).toBeHidden(); + + // Toggle List | Top -> 5 TopBreakdown cards -> click Top item -> chip added -> List + const viewModeGroup = page.getByRole("group", { name: "View mode" }); + await Promise.all([ + page.waitForResponse( + (res) => + res.url().includes("/who/api/v1/access-logs") && + res.url().includes("view=top") && + res.status() === 200, + ), + viewModeGroup.getByRole("button", { name: "Top" }).click(), + ]); + + const topCards = page.locator("section", { + has: page.locator("h2", { hasText: /^Top / }), + }); + await expect(topCards).toHaveCount(5); + + const topIamsCard = page.locator("section", { + has: page.locator("h2", { hasText: "Top IAMs" }), + }); + const firstTopIamBtn = topIamsCard.locator("ul button").first(); + await expect(firstTopIamBtn).toBeVisible(); + await firstTopIamBtn.click(); + await expect( + page.locator('button[aria-label^="Remove iam:"][aria-label$=" filter"]'), + ).toBeVisible(); + + await viewModeGroup.getByRole("button", { name: "List" }).click(); + await page.getByRole("button", { name: "Clear all filters" }).click(); + await expect(page.locator("tbody tr").first()).toBeVisible(); + + // Pagination page size change + Next page navigation + const rowsPerPage = page.getByLabel("Rows per page"); + await expect(rowsPerPage).toBeVisible(); + await Promise.all([ + page.waitForResponse( + (res) => + res.url().includes("/who/api/v1/access-logs") && + res.url().includes("pageSize=25") && + res.status() === 200, + ), + rowsPerPage.selectOption("25"), + ]); + await expect(page.locator("#main")).toContainText("Showing 1–25 of"); + + await Promise.all([ + page.waitForResponse( + (res) => + res.url().includes("/who/api/v1/access-logs") && + res.url().includes("page=2") && + res.status() === 200, + ), + page.getByRole("button", { name: "Next page" }).click(), + ]); + await expect(page.locator("#main")).toContainText("Showing 26–"); + + expect(pageErrors).toEqual([]); + expect(consoleErrors).toEqual([]); + }); + + test("Audit Log: TimeRangePicker default All time reset, category:record filter, and Top drill-down", async ({ + page, + }) => { + const { pageErrors, consoleErrors } = attachErrorCollector(page); + + await page.goto("/who/#/audit"); + await expect(page.locator("#main header h1")).toHaveText("Audit Log"); + await expect(page.locator("tbody tr").first()).toBeVisible(); + + const refreshBtn = page.getByRole("button", { name: "Refresh" }); + const timePickerBtn = page.getByRole("button", { name: /^Time range:/ }); + const [refreshBox, pickerBox] = await Promise.all([ + refreshBtn.boundingBox(), + timePickerBtn.boundingBox(), + ]); + expect(refreshBox).not.toBeNull(); + expect(pickerBox).not.toBeNull(); + expect(refreshBox.x).toBeLessThan(pickerBox.x); + expect(refreshBox.x + refreshBox.width).toBeLessThanOrEqual(pickerBox.x + 2); + + await expect(timePickerBtn).toHaveAttribute("aria-label", /All time/); + await timePickerBtn.click(); + const pickerPopover = page.locator('[popover="auto"]:popover-open'); + await expect(pickerPopover).toBeVisible(); + await pickerPopover.getByRole("button", { name: /Last 1 hour/ }).click(); + await expect(timePickerBtn).toHaveAttribute("aria-label", /Last 1 hour/); + + await timePickerBtn.click(); + await expect(pickerPopover).toBeVisible(); + await pickerPopover.getByRole("button", { name: "Reset" }).click(); + await expect(timePickerBtn).toHaveAttribute("aria-label", /All time/); + + const filterInput = page.locator("[data-search-input]"); + await filterInput.click(); + await filterInput.fill("category:"); + const suggestions = page.getByRole("listbox", { name: "category suggestions" }); + await expect(suggestions).toBeVisible(); + await Promise.all([ + page.waitForResponse( + (res) => + res.url().includes("/who/api/v1/audit-logs") && + res.url().includes("category=record") && + res.status() === 200, + ), + suggestions.getByRole("option", { name: /^record\b/ }).click(), + ]); + await expect( + page.getByRole("button", { name: "Remove category:record filter" }), + ).toBeVisible(); + await expect( + page.locator("tbody tr").first().locator('td[data-col="Action"]'), + ).toContainText("record"); + + const viewModeGroup = page.getByRole("group", { name: "View mode" }); + await Promise.all([ + page.waitForResponse( + (res) => + res.url().includes("/who/api/v1/audit-logs") && + res.url().includes("view=top") && + res.status() === 200, + ), + viewModeGroup.getByRole("button", { name: "Top" }).click(), + ]); + + const topCards = page.locator("section", { + has: page.locator("h2", { hasText: /^Top / }), + }); + await expect(topCards).toHaveCount(5); + + const topActionsCard = page.locator("section", { + has: page.locator("h2", { hasText: "Top Actions" }), + }); + const firstActionBtn = topActionsCard.locator("ul button").first(); + await expect(firstActionBtn).toBeVisible(); + await firstActionBtn.click(); + await expect( + page.locator('button[aria-label^="Remove action:"][aria-label$=" filter"]'), + ).toBeVisible(); + + await viewModeGroup.getByRole("button", { name: "List" }).click(); + await expect(page.locator("tbody tr").first()).toBeVisible(); + + expect(pageErrors).toEqual([]); + expect(consoleErrors).toEqual([]); + }); + + test("Settings: retention persistence, Backup export/merge import, and active session badge", async ({ + page, + }) => { + const { pageErrors, consoleErrors } = attachErrorCollector(page); + + await page.goto("/who/#/settings"); + await expect(page.locator("#main header h1")).toHaveText("Settings"); + + // 1. Retention persistence across reload + const retentionSection = page.locator("#settings-retention"); + const accessDaysInput = page.getByLabel(/Access log retention \(days\)/i); + await expect(accessDaysInput).toHaveValue( + String(originalSettings.accessLogRetentionDays), + ); + + await accessDaysInput.fill("45"); + await Promise.all([ + page.waitForResponse( + (res) => + res.url().endsWith("/who/api/v1/settings") && + res.request().method() === "PUT" && + res.status() === 200, + ), + retentionSection.getByRole("button", { name: "Save", exact: true }).click(), + ]); + + await page.reload(); + await expect(page.locator("#main header h1")).toHaveText("Settings"); + await expect(page.getByLabel(/Access log retention \(days\)/i)).toHaveValue("45"); + + await page + .getByLabel(/Access log retention \(days\)/i) + .fill(String(originalSettings.accessLogRetentionDays)); + await Promise.all([ + page.waitForResponse( + (res) => + res.url().endsWith("/who/api/v1/settings") && + res.request().method() === "PUT" && + res.status() === 200, + ), + page + .locator("#settings-retention") + .getByRole("button", { name: "Save", exact: true }) + .click(), + ]); + + // 2. Export Backup JSON via download event + const backupSection = page.locator("#settings-backup"); + const [download] = await Promise.all([ + page.waitForEvent("download"), + backupSection.getByRole("button", { name: "Export JSON" }).click(), + ]); + expect(download.suggestedFilename()).toBe("who-backup.json"); + const downloadPath = await download.path(); + expect(downloadPath).toBeTruthy(); + const exported = JSON.parse(await fs.promises.readFile(downloadPath, "utf8")); + expect(exported).toMatchObject({ + who: expect.any(Array), + secrets: expect.any(Array), + ddns: expect.any(Array), + webhooks: expect.any(Array), + touch: expect.any(Array), + }); + + // 3. Merge Backup JSON import + /whois verification + cleanup + const mergeBackup = { + who: [{ iam: BACKUP_REC, ip: "198.51.100.99" }], + }; + await page.getByLabel("Backup JSON File").setInputFiles({ + name: "e2e-merge-backup.json", + mimeType: "application/json", + buffer: Buffer.from(JSON.stringify(mergeBackup)), + }); + await expect(backupSection).toContainText("e2e-merge-backup.json"); + await Promise.all([ + page.waitForResponse( + (res) => + res.url().includes("/who/api/v1/backup/import") && + res.request().method() === "POST" && + res.status() === 200, + ), + backupSection.getByRole("button", { name: "Import JSON" }).click(), + ]); + + const importedWhois = await rawAppFetch("GET", `/whois/${BACKUP_REC}`); + expect(importedWhois.status).toBe(200); + expect(importedWhois.text.trim()).toBe("198.51.100.99"); + + const cleanupBackupRec = await apiFetch("DELETE", `/records/${BACKUP_REC}`); + expect([200, 204, 404]).toContain(cleanupBackupRec.status); + + // 4. Active Sign-In Sessions shows admin@who.localhost with Current badge + const sessionsList = page.getByRole("list", { name: "Active OIDC sessions" }); + await expect(sessionsList).toBeVisible(); + const currentSession = sessionsList + .locator("li", { hasText: ADMIN_USER.email }) + .filter({ hasText: "Current" }); + await expect(currentSession.first()).toBeVisible(); + + expect(pageErrors).toEqual([]); + expect(consoleErrors).toEqual([]); + }); +}); diff --git a/e2e/tests/navigation-and-overview.spec.mjs b/e2e/tests/navigation-and-overview.spec.mjs new file mode 100644 index 0000000..f1805c0 --- /dev/null +++ b/e2e/tests/navigation-and-overview.spec.mjs @@ -0,0 +1,231 @@ +import { expect, test } from "@playwright/test"; +import { APP_URL } from "./helpers.mjs"; + +const SECTIONS = [ + { id: "overview", label: "Overview" }, + { id: "records", label: "Records" }, + { id: "ddns", label: "DDNS" }, + { id: "webhooks", label: "Webhooks" }, + { id: "touch", label: "Touch Files" }, + { id: "access", label: "Access Log" }, + { id: "audit", label: "Audit Log" }, + { id: "settings", label: "Settings" }, +]; + +function attachErrorCollector(page) { + const pageErrors = []; + const consoleErrors = []; + page.on("pageerror", (err) => { + pageErrors.push(err?.message || String(err)); + }); + page.on("console", (msg) => { + if (msg.type() === "error") { + consoleErrors.push(msg.text()); + } + }); + return { pageErrors, consoleErrors }; +} + +test.describe("Desktop Navigation, Overview, Shortcuts, Theme & Zero Idle Polling", () => { + test("loads Overview KPI cards and 24h traffic chart with zero console or page errors", async ({ + page, + }) => { + const { pageErrors, consoleErrors } = attachErrorCollector(page); + + await page.goto("/who/"); + await expect(page).toHaveURL(`${APP_URL}/who/#/overview`); + await expect( + page.locator("#main header h1"), + ).toHaveText("Overview"); + + const kpiSection = page.locator('section[aria-label="Key metrics"]'); + await expect(kpiSection).toBeVisible(); + await expect(kpiSection.getByText("Managed Records")).toBeVisible(); + await expect(kpiSection.getByText("24h IP Changes")).toBeVisible(); + await expect(kpiSection.getByText("DDNS Health")).toBeVisible(); + await expect(kpiSection.getByText("24h Traffic")).toBeVisible(); + + const chartSection = page.locator('section[aria-label="24-hour request volume"]'); + await expect(chartSection).toBeVisible(); + await expect( + chartSection.getByRole("heading", { name: "24-Hour Request Strip", level: 2 }), + ).toBeVisible(); + await expect( + chartSection.getByRole("group", { name: "Hourly request buckets" }), + ).toBeVisible(); + + await expect( + page.getByRole("heading", { name: "Recent IP Transitions", level: 2 }), + ).toBeVisible(); + await expect( + page.getByRole("heading", { name: "Recent Delivery Failures", level: 2 }), + ).toBeVisible(); + + expect(pageErrors).toEqual([]); + expect(consoleErrors).toEqual([]); + }); + + test("navigates across all 8 sections via Sidebar and redirects legacy integrations routes", async ({ + page, + }) => { + const { pageErrors, consoleErrors } = attachErrorCollector(page); + + await page.goto("/who/"); + await expect(page.locator("#main header h1")).toHaveText("Overview"); + + const sidebar = page.locator('aside[aria-label="Main navigation"]'); + for (const section of SECTIONS) { + await sidebar.getByRole("link", { name: section.label, exact: true }).click(); + await expect(page).toHaveURL(`${APP_URL}/who/#/${section.id}`); + await expect(page.locator("#main header h1")).toHaveText(section.label); + } + + // Legacy hashchange redirect: #/integrations -> #/ddns + await page.goto("/who/#/integrations"); + await expect(page).toHaveURL(`${APP_URL}/who/#/ddns`); + await expect(page.locator("#main header h1")).toHaveText("DDNS"); + + // Cold load legacy redirect: #/integrations/webhooks -> #/webhooks + await page.goto("about:blank"); + await page.goto("/who/#/integrations/webhooks"); + await expect(page).toHaveURL(`${APP_URL}/who/#/webhooks`); + await expect(page.locator("#main header h1")).toHaveText("Webhooks"); + + expect(pageErrors).toEqual([]); + expect(consoleErrors).toEqual([]); + }); + + test("supports keyboard navigation chords (g r, g a), slash search focus, and Ctrl+B sidebar toggle", async ({ + page, + }) => { + const { pageErrors, consoleErrors } = attachErrorCollector(page); + + await page.goto("/who/#/overview"); + const mainHeading = page.locator("#main header h1"); + await expect(mainHeading).toHaveText("Overview"); + + // Ensure focus is outside any form field before sending chord shortcuts. + await mainHeading.click(); + + await page.keyboard.press("g"); + await page.keyboard.press("r"); + await expect(page).toHaveURL(`${APP_URL}/who/#/records`); + await expect(mainHeading).toHaveText("Records"); + + await page.keyboard.press("g"); + await page.keyboard.press("a"); + await expect(page).toHaveURL(`${APP_URL}/who/#/audit`); + await expect(mainHeading).toHaveText("Audit Log"); + + await page.keyboard.press("/"); + await expect(page.locator("[data-search-input]")).toBeFocused(); + + const sidebar = page.locator('aside[aria-label="Main navigation"]'); + const sidebarWrapper = sidebar.locator(".."); + await expect(sidebarWrapper).not.toHaveAttribute("inert", ""); + await expect( + sidebar.getByRole("button", { name: "Collapse sidebar" }), + ).toBeVisible(); + + await page.keyboard.press("Control+b"); + await expect(sidebarWrapper).toHaveAttribute("inert", ""); + await expect( + page.getByRole("button", { name: "Expand sidebar" }), + ).toBeVisible(); + + await page.keyboard.press("Control+b"); + await expect(sidebarWrapper).not.toHaveAttribute("inert", ""); + await expect( + page.getByRole("button", { name: "Expand sidebar" }), + ).toHaveCount(0); + + expect(pageErrors).toEqual([]); + expect(consoleErrors).toEqual([]); + }); + + test("persists light/dark theme toggle across page reload", async ({ page }) => { + const { pageErrors, consoleErrors } = attachErrorCollector(page); + + await page.goto("/who/#/overview"); + await expect(page.locator("#main header h1")).toHaveText("Overview"); + + const html = page.locator("html"); + const sidebar = page.locator('aside[aria-label="Main navigation"]'); + const initiallyDark = await html.evaluate((el) => el.classList.contains("dark")); + + const toggleName = initiallyDark ? "Switch to light theme" : "Switch to dark theme"; + await sidebar.getByRole("button", { name: toggleName }).click(); + await expect + .poll(() => html.evaluate((el) => el.classList.contains("dark"))) + .toBe(!initiallyDark); + + await page.reload(); + await expect(page.locator("#main header h1")).toHaveText("Overview"); + await expect + .poll(() => html.evaluate((el) => el.classList.contains("dark"))) + .toBe(!initiallyDark); + + // Restore original theme state so subsequent tests start cleanly. + const restoreName = !initiallyDark ? "Switch to light theme" : "Switch to dark theme"; + await sidebar.getByRole("button", { name: restoreName }).click(); + await expect + .poll(() => html.evaluate((el) => el.classList.contains("dark"))) + .toBe(initiallyDark); + + expect(pageErrors).toEqual([]); + expect(consoleErrors).toEqual([]); + }); + + test("triggers zero idle polling /api/v1/ requests on Overview, Records, DDNS, and Settings", async ({ + page, + }) => { + const { pageErrors, consoleErrors } = attachErrorCollector(page); + + const targets = [ + { + id: "overview", + heading: "Overview", + readyLocator: () => page.locator('section[aria-label="Key metrics"]'), + }, + { + id: "records", + heading: "Records", + readyLocator: () => page.locator("#main header h1"), + }, + { + id: "ddns", + heading: "DDNS", + readyLocator: () => page.locator("#main header h1"), + }, + { + id: "settings", + heading: "Settings", + readyLocator: () => page.locator("#settings-backup"), + }, + ]; + + for (const target of targets) { + await page.goto(`/who/#/${target.id}`); + await expect(page.locator("#main header h1")).toHaveText(target.heading); + await expect(target.readyLocator()).toBeVisible(); + await expect(page.locator('#main [aria-busy="true"]')).toHaveCount(0); + await page.waitForLoadState("networkidle"); + + const idleRequests = []; + const onRequest = (req) => { + if (req.url().includes("/who/api/v1/")) { + idleRequests.push(`${req.method()} ${req.url()}`); + } + }; + + page.on("request", onRequest); + await page.waitForTimeout(2500); + page.off("request", onRequest); + + expect(idleRequests, `Unexpected idle API calls on #/${target.id}`).toEqual([]); + } + + expect(pageErrors).toEqual([]); + expect(consoleErrors).toEqual([]); + }); +}); diff --git a/e2e/tests/records-and-drawer.spec.mjs b/e2e/tests/records-and-drawer.spec.mjs new file mode 100644 index 0000000..6f5f8b5 --- /dev/null +++ b/e2e/tests/records-and-drawer.spec.mjs @@ -0,0 +1,296 @@ +import { expect, test } from "@playwright/test"; +import { apiFetch, rawAppFetch } from "./helpers.mjs"; + +const MAIN_RECORD = "e2e-rec-main"; +const EPHEMERAL_RECORD = "e2e-rec-eph"; +const ALIAS_RECORD = "e2e-alias-group"; + +function attachErrorCollector(page) { + const pageErrors = []; + const consoleErrors = []; + page.on("pageerror", (err) => { + pageErrors.push(err?.message || String(err)); + }); + page.on("console", (msg) => { + if (msg.type() === "error") { + consoleErrors.push(msg.text()); + } + }); + return { pageErrors, consoleErrors }; +} + +function recordRow(page, iam) { + return page.locator(`tr[aria-label="Inspect history for ${iam}"]`); +} + +test.describe("Records CRUD, Ephemeral Persist, Alias Drawer & Bearer Token Lifecycle", () => { + test.beforeAll(async () => { + for (const iam of [ALIAS_RECORD, MAIN_RECORD, EPHEMERAL_RECORD]) { + await apiFetch("DELETE", `/records/${encodeURIComponent(iam)}`); + } + }); + + test.afterAll(async () => { + for (const iam of [ALIAS_RECORD, MAIN_RECORD, EPHEMERAL_RECORD]) { + const res = await apiFetch("DELETE", `/records/${encodeURIComponent(iam)}`); + expect([200, 204, 404]).toContain(res.status); + } + }); + + test("exercises plain CRUD, ephemeral persist, alias drawer navigation, token auth, filter chips, and delete", async ({ + page, + }) => { + const { pageErrors, consoleErrors } = attachErrorCollector(page); + + await page.goto("/who/#/records"); + await expect(page.locator("#main header h1")).toHaveText("Records"); + + // 1. Plain record add + /whois verification + await page.getByRole("button", { name: "New Record" }).click(); + let dialog = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { name: "Create Record or Alias", level: 1 }), + }); + await expect(dialog).toBeVisible(); + await dialog.locator("#record-iam-input").fill(MAIN_RECORD); + await dialog.locator("#record-ip-input").fill("198.51.100.51"); + await dialog.getByRole("button", { name: "Create Record" }).click(); + await expect(dialog).toBeHidden(); + + const mainRow = recordRow(page, MAIN_RECORD); + await expect(mainRow).toBeVisible(); + await expect(mainRow.locator('td[data-col="State & Type"]')).toContainText("Persisted"); + await expect(mainRow.locator('td[data-col="State & Type"]')).toContainText("IPv4"); + await expect(mainRow.locator('td[data-col="Current IP(s)"]')).toContainText("198.51.100.51"); + + const whoisCreated = await rawAppFetch("GET", `/whois/${MAIN_RECORD}`); + expect(whoisCreated.status).toBe(200); + expect(whoisCreated.text.trim()).toBe("198.51.100.51"); + + // 2. Plain record edit + /whois verification + await mainRow.getByRole("button", { name: `Edit ${MAIN_RECORD}` }).click(); + dialog = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { name: `Edit ${MAIN_RECORD}`, level: 1 }), + }); + await expect(dialog).toBeVisible(); + await dialog.locator("#record-ip-input").fill("198.51.100.52"); + await dialog.getByRole("button", { name: "Save Changes" }).click(); + await expect(dialog).toBeHidden(); + + await expect(mainRow.locator('td[data-col="Current IP(s)"]')).toContainText("198.51.100.52"); + const whoisEdited = await rawAppFetch("GET", `/whois/${MAIN_RECORD}`); + expect(whoisEdited.status).toBe(200); + expect(whoisEdited.text.trim()).toBe("198.51.100.52"); + + // 3. Ephemeral record -> Persist flow + const ephRes = await rawAppFetch("GET", `/iam/${EPHEMERAL_RECORD}/198.51.100.61`); + expect(ephRes.status).toBe(200); + expect(ephRes.text.trim()).toBe("198.51.100.61"); + + await page.getByRole("button", { name: "Refresh" }).click(); + const ephRow = recordRow(page, EPHEMERAL_RECORD); + await expect(ephRow).toBeVisible(); + await expect(ephRow.locator('td[data-col="State & Type"]')).toContainText("Ephemeral"); + + const ephMenuTrigger = ephRow.getByRole("button", { + name: `More actions for ${EPHEMERAL_RECORD}`, + }); + await ephMenuTrigger.click(); + const openMenu = page.locator('[popover="auto"]:popover-open'); + await expect(openMenu).toBeVisible(); + await expect(page.locator("dialog.who-drawer[open]")).toHaveCount(0); + + // Toggling the trigger closed must not bubble to row click / RecordDrawer. + await ephMenuTrigger.click(); + await expect(openMenu).toHaveCount(0); + await expect(page.locator("dialog.who-drawer[open]")).toHaveCount(0); + + await ephMenuTrigger.click(); + await expect(openMenu).toBeVisible(); + await openMenu.locator("button", { hasText: "Persist to SQLite" }).click(); + await expect(openMenu).toHaveCount(0); + await expect(page.locator("dialog.who-drawer[open]")).toHaveCount(0); + await expect(ephRow.locator('td[data-col="State & Type"]')).toContainText("Persisted"); + + // 4. Alias create + IAM Name column verification + /whois verification + await page.getByRole("button", { name: "New Record" }).click(); + dialog = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { name: "Create Record or Alias", level: 1 }), + }); + await expect(dialog).toBeVisible(); + await dialog.getByRole("button", { name: "Alias Group" }).click(); + await dialog.locator("#record-iam-input").fill(ALIAS_RECORD); + + const memberInput = dialog.locator("#alias-member-input"); + await memberInput.fill(MAIN_RECORD); + await memberInput.press("Enter"); + await memberInput.fill(EPHEMERAL_RECORD); + await memberInput.press("Enter"); + await dialog.getByRole("button", { name: "Create Alias" }).click(); + await expect(dialog).toBeHidden(); + + const aliasRow = recordRow(page, ALIAS_RECORD); + await expect(aliasRow).toBeVisible(); + await expect(aliasRow.locator('td[data-col="State & Type"]')).toContainText("Persisted"); + await expect(aliasRow.locator('td[data-col="State & Type"]')).toContainText("Alias"); + + // IAM Name cell must show only the alias name (no "->" or member names). + const aliasNameCell = aliasRow.locator('th[scope="row"]'); + await expect(aliasNameCell).toHaveText(ALIAS_RECORD); + await expect(aliasNameCell).not.toContainText("→"); + await expect(aliasNameCell).not.toContainText(MAIN_RECORD); + await expect(aliasNameCell).not.toContainText(EPHEMERAL_RECORD); + + const whoisAlias = await rawAppFetch("GET", `/whois/${ALIAS_RECORD}`); + expect(whoisAlias.status).toBe(200); + expect(whoisAlias.text.trim()).toBe("198.51.100.52\n198.51.100.61"); + + // 5. Alias RecordDrawer inspection + member IP update history + member chip jump + await aliasRow.click(); + const drawer = page.locator("dialog.who-drawer[open]"); + await expect(drawer).toBeVisible(); + await expect( + drawer.getByRole("heading", { name: ALIAS_RECORD, level: 1 }), + ).toBeVisible(); + await expect( + drawer.getByRole("button", { name: MAIN_RECORD, exact: true }), + ).toBeVisible(); + await expect( + drawer.getByRole("button", { name: EPHEMERAL_RECORD, exact: true }), + ).toBeVisible(); + + const updateMainRes = await rawAppFetch("GET", `/iam/${MAIN_RECORD}/198.51.100.53`); + expect(updateMainRes.status).toBe(200); + expect(updateMainRes.text.trim()).toBe("198.51.100.53"); + + await drawer.getByRole("button", { name: "Refresh" }).click(); + const latestHistoryItem = drawer.locator("ol > li").first(); + const memberBadgeBtn = latestHistoryItem.getByRole("button", { + name: `Inspect member record ${MAIN_RECORD}`, + }); + await expect(memberBadgeBtn).toBeVisible(); + await expect(latestHistoryItem).toContainText("198.51.100.52"); + await expect(latestHistoryItem).toContainText("198.51.100.53"); + + const oldIpEl = latestHistoryItem.getByText("198.51.100.52", { exact: true }); + const newIpEl = latestHistoryItem.getByText("198.51.100.53", { exact: true }); + const timeEl = latestHistoryItem.locator("div.text-right"); + const [badgeBox, oldBox, newBox, timeBox] = await Promise.all([ + memberBadgeBtn.boundingBox(), + oldIpEl.boundingBox(), + newIpEl.boundingBox(), + timeEl.boundingBox(), + ]); + expect(badgeBox).not.toBeNull(); + expect(oldBox).not.toBeNull(); + expect(newBox).not.toBeNull(); + expect(timeBox).not.toBeNull(); + expect(badgeBox.x + badgeBox.width).toBeLessThanOrEqual(timeBox.x); + expect(oldBox.x + oldBox.width).toBeLessThan(newBox.x); + expect(Math.abs(oldBox.y - newBox.y)).toBeLessThan(8); + + // Click member chip to jump directly to e2e-rec-main's drawer. + await drawer.getByRole("button", { name: MAIN_RECORD, exact: true }).click(); + await expect( + drawer.getByRole("heading", { name: MAIN_RECORD, level: 1 }), + ).toBeVisible(); + await expect(drawer).toContainText("198.51.100.53"); + + await drawer.getByRole("button", { name: "Close drawer" }).click(); + await expect(drawer).toHaveCount(0); + await expect(page.locator("dialog.who-drawer")).toBeHidden(); + + await page.locator("#main").getByRole("button", { name: "Refresh" }).click(); + await expect(mainRow.locator('td[data-col="Current IP(s)"]')).toContainText("198.51.100.53"); + + // 6. Bearer token lifecycle via ActionMenu -> Reveal Dialog -> /iam check -> Clear Token + await mainRow + .getByRole("button", { name: `More actions for ${MAIN_RECORD}` }) + .click(); + await expect(openMenu).toBeVisible(); + await openMenu.locator("button", { hasText: "Add Token" }).click(); + + const tokenDialog = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { name: "Bearer Token Generated", level: 1 }), + }); + await expect(tokenDialog).toBeVisible(); + const plaintextToken = ( + await tokenDialog + .locator('div:has(> button[aria-label="Copy bearer token"]) code') + .textContent() + ).trim(); + expect(plaintextToken.length).toBeGreaterThan(16); + await tokenDialog.getByRole("button", { name: "I've saved this token" }).click(); + await expect(tokenDialog).toBeHidden(); + + await expect(mainRow.locator('td[data-col="/iam Auth"]')).toContainText("Token"); + + const unauthUpdate = await rawAppFetch("GET", `/iam/${MAIN_RECORD}/198.51.100.54`); + expect(unauthUpdate.status).toBe(401); + + const authUpdate = await rawAppFetch("GET", `/iam/${MAIN_RECORD}/198.51.100.54`, { + headers: { Authorization: `Bearer ${plaintextToken}` }, + }); + expect(authUpdate.status).toBe(200); + expect(authUpdate.text.trim()).toBe("198.51.100.54"); + + await mainRow + .getByRole("button", { name: `More actions for ${MAIN_RECORD}` }) + .click(); + await expect(openMenu).toBeVisible(); + await openMenu.locator("button", { hasText: "Clear Token" }).click(); + + const clearConfirm = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { + name: `Clear bearer token for ${MAIN_RECORD}?`, + level: 1, + }), + }); + await expect(clearConfirm).toBeVisible(); + await clearConfirm.getByRole("button", { name: "Clear Token", exact: true }).click(); + await expect(clearConfirm).toBeHidden(); + await expect(mainRow.locator('td[data-col="/iam Auth"]')).toContainText("Open"); + + // 7. FilterBar structured chips + Pagination + Delete verification + const filterInput = page.locator("[data-search-input]"); + await filterInput.click(); + await filterInput.fill("state:persisted "); + await expect( + page.getByRole("button", { name: "Remove state:persisted filter" }), + ).toBeVisible(); + await filterInput.fill("type:alias "); + await expect( + page.getByRole("button", { name: "Remove type:alias filter" }), + ).toBeVisible(); + + await expect(aliasRow).toBeVisible(); + await expect(mainRow).toHaveCount(0); + await expect(ephRow).toHaveCount(0); + + await page.getByRole("button", { name: "Clear all filters" }).click(); + await page.keyboard.press("Escape"); + await expect(page.locator("[data-search-input]")).toHaveAttribute("aria-expanded", "false"); + await expect(mainRow).toBeVisible(); + await expect(ephRow).toBeVisible(); + await expect(aliasRow).toBeVisible(); + await expect(page.getByLabel("Rows per page")).toBeVisible(); + await expect(page.getByRole("navigation", { name: "Pagination" })).toBeVisible(); + + for (const iam of [ALIAS_RECORD, MAIN_RECORD, EPHEMERAL_RECORD]) { + const row = recordRow(page, iam); + await row.getByRole("button", { name: `Delete ${iam}` }).click(); + const deleteConfirm = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { name: `Delete ${iam}?`, level: 1 }), + }); + await expect(deleteConfirm).toBeVisible(); + await deleteConfirm.getByRole("button", { name: "Delete", exact: true }).click(); + await expect(deleteConfirm).toBeHidden(); + await expect(row).toHaveCount(0); + } + + const whoisDeleted = await rawAppFetch("GET", `/whois/${MAIN_RECORD}`); + expect(whoisDeleted.status).toBe(404); + + expect(pageErrors).toEqual([]); + expect(consoleErrors).toEqual([]); + }); +}); From ca9a767f276c81948bdc7be07e51921e6e421e91 Mon Sep 17 00:00:00 2001 From: tracyhatemice Date: Sun, 29 Nov 2026 19:41:12 +0800 Subject: [PATCH 07/10] test(e2e): harden pause waits, secret UI masking check, and alias edit coverage --- e2e/tests/ddns-webhooks-touch.spec.mjs | 47 +++++++++++++++++++++++--- e2e/tests/logs-and-settings.spec.mjs | 20 ----------- e2e/tests/records-and-drawer.spec.mjs | 25 ++++++++++++++ 3 files changed, 68 insertions(+), 24 deletions(-) diff --git a/e2e/tests/ddns-webhooks-touch.spec.mjs b/e2e/tests/ddns-webhooks-touch.spec.mjs index 3d0f8a8..032fb25 100644 --- a/e2e/tests/ddns-webhooks-touch.spec.mjs +++ b/e2e/tests/ddns-webhooks-touch.spec.mjs @@ -184,7 +184,22 @@ test.describe("DDNS, Webhooks, Touch Files CRUD & Live Side Effects", () => { }); await expect(secretDeleteBtn).toBeDisabled(); - // Check API masking and edit modal mask placeholder + // Check UI masking inside Edit SecretModal plus API masking + await secretRow.getByRole("button", { name: `Edit secret ${SECRET_NAME}` }).click(); + const editSecretDialog = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { name: "Edit Provider Secret", level: 1 }), + }); + await expect(editSecretDialog).toBeVisible(); + await expect(editSecretDialog.locator('input[name="access_key"]')).toHaveValue( + ACCESS_KEY, + ); + const editSecretKeyInput = editSecretDialog.locator('input[name="secret_key"]'); + await expect(editSecretKeyInput).toHaveAttribute("placeholder", /^••••••••/); + await expect(editSecretKeyInput).toHaveValue(""); + await expect(editSecretDialog).not.toContainText(SECRET_KEY); + await editSecretDialog.getByRole("button", { name: "Cancel" }).click(); + await expect(editSecretDialog).toBeHidden(); + const secretsApiRes = await apiFetch("GET", "/secrets"); expect(secretsApiRes.status).toBe(200); const createdSecret = (secretsApiRes.data?.items ?? []).find( @@ -269,7 +284,15 @@ test.describe("DDNS, Webhooks, Touch Files CRUD & Live Side Effects", () => { const ddnsSwitch = ddnsRow.getByRole("switch", { name: `DDNS rule for ${DDNS_DOMAIN}`, }); - await ddnsSwitch.click(); + await Promise.all([ + page.waitForResponse( + (res) => + res.request().method() === "PUT" && + res.url().includes("/who/api/v1/ddns/") && + res.status() === 200, + ), + ddnsSwitch.click(), + ]); await expect(ddnsSwitch).toHaveAttribute("aria-checked", "false"); await resetMockSink(); @@ -401,7 +424,15 @@ test.describe("DDNS, Webhooks, Touch Files CRUD & Live Side Effects", () => { const hookSwitch = hookRow.getByRole("switch", { name: `Webhook to ${HOOK_OK_URL}`, }); - await hookSwitch.click(); + await Promise.all([ + page.waitForResponse( + (res) => + res.request().method() === "PUT" && + res.url().includes("/who/api/v1/webhooks/") && + res.status() === 200, + ), + hookSwitch.click(), + ]); await expect(hookSwitch).toHaveAttribute("aria-checked", "false"); await resetMockSink(); @@ -511,7 +542,15 @@ test.describe("DDNS, Webhooks, Touch Files CRUD & Live Side Effects", () => { const touchSwitch = touchRow2.getByRole("switch", { name: `Touch file ${TOUCH_PATH_2}`, }); - await touchSwitch.click(); + await Promise.all([ + page.waitForResponse( + (res) => + res.request().method() === "PUT" && + res.url().includes("/who/api/v1/touch/") && + res.status() === 200, + ), + touchSwitch.click(), + ]); await expect(touchSwitch).toHaveAttribute("aria-checked", "false"); const pausedTouchIam = await rawAppFetch("GET", `/iam/${HOST_IAM}/198.51.100.75`); diff --git a/e2e/tests/logs-and-settings.spec.mjs b/e2e/tests/logs-and-settings.spec.mjs index e0f4d68..32242b7 100644 --- a/e2e/tests/logs-and-settings.spec.mjs +++ b/e2e/tests/logs-and-settings.spec.mjs @@ -71,26 +71,6 @@ test.describe("Access Log, Audit Log & Settings", () => { expect(res.status).toBe(200); } - await expect - .poll( - async () => { - const all = await apiFetch("GET", "/access-logs?range=1h&pageSize=1"); - const iam = await apiFetch( - "GET", - `/access-logs?range=1h&endpoint=iam&iam=${LOG_HOST}&pageSize=1`, - ); - return { - total: all.data?.total ?? 0, - iamTotal: iam.data?.total ?? 0, - }; - }, - { timeout: 10_000, intervals: [150] }, - ) - .toEqual({ - total: expect.any(Number), - iamTotal: expect.any(Number), - }); - await expect .poll( async () => { diff --git a/e2e/tests/records-and-drawer.spec.mjs b/e2e/tests/records-and-drawer.spec.mjs index 6f5f8b5..e6dae11 100644 --- a/e2e/tests/records-and-drawer.spec.mjs +++ b/e2e/tests/records-and-drawer.spec.mjs @@ -144,6 +144,31 @@ test.describe("Records CRUD, Ephemeral Persist, Alias Drawer & Bearer Token Life expect(whoisAlias.status).toBe(200); expect(whoisAlias.text.trim()).toBe("198.51.100.52\n198.51.100.61"); + // 4b. Alias edit (remove member -> verify /whois -> restore member) + await aliasRow.getByRole("button", { name: `Edit ${ALIAS_RECORD}` }).click(); + dialog = page.locator("dialog[open]").filter({ + has: page.getByRole("heading", { name: `Edit ${ALIAS_RECORD}`, level: 1 }), + }); + await expect(dialog).toBeVisible(); + await dialog.getByRole("button", { name: `Remove ${EPHEMERAL_RECORD}` }).click(); + await dialog.getByRole("button", { name: "Save Changes" }).click(); + await expect(dialog).toBeHidden(); + + const whoisAliasEdited = await rawAppFetch("GET", `/whois/${ALIAS_RECORD}`); + expect(whoisAliasEdited.status).toBe(200); + expect(whoisAliasEdited.text.trim()).toBe("198.51.100.52"); + + await aliasRow.getByRole("button", { name: `Edit ${ALIAS_RECORD}` }).click(); + await expect(dialog).toBeVisible(); + await dialog.locator("#alias-member-input").fill(EPHEMERAL_RECORD); + await dialog.locator("#alias-member-input").press("Enter"); + await dialog.getByRole("button", { name: "Save Changes" }).click(); + await expect(dialog).toBeHidden(); + + const whoisAliasRestored = await rawAppFetch("GET", `/whois/${ALIAS_RECORD}`); + expect(whoisAliasRestored.status).toBe(200); + expect(whoisAliasRestored.text.trim()).toBe("198.51.100.52\n198.51.100.61"); + // 5. Alias RecordDrawer inspection + member IP update history + member chip jump await aliasRow.click(); const drawer = page.locator("dialog.who-drawer[open]"); From 5b241fd44476d1c9588208f40bcf506f43ee3d83 Mon Sep 17 00:00:00 2001 From: tracyhatemice Date: Sun, 29 Nov 2026 19:49:04 +0800 Subject: [PATCH 08/10] test(e2e,ci): add mobile layout spec, Makefile targets, and GitHub Actions E2E job --- .github/workflows/docker-build.yml | 61 ++++++- Makefile | 11 +- README.md | 27 +++ e2e/tests/mobile-layout.spec.mjs | 265 +++++++++++++++++++++++++++++ 4 files changed, 362 insertions(+), 2 deletions(-) create mode 100644 e2e/tests/mobile-layout.spec.mjs diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml index cd47146..3c71f93 100644 --- a/.github/workflows/docker-build.yml +++ b/.github/workflows/docker-build.yml @@ -31,8 +31,67 @@ jobs: - name: Run Go tests run: go test -race -v ./... + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: "24" + + - name: Enable pnpm + env: + COREPACK_ENABLE_DOWNLOAD_PROMPT: "0" + run: corepack enable && corepack prepare pnpm@10.33.0 --activate + + - name: Run UI checks + run: pnpm --dir ui install --frozen-lockfile && pnpm --dir ui run check + + e2e: + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: "24" + + - name: Enable pnpm + env: + COREPACK_ENABLE_DOWNLOAD_PROMPT: "0" + run: corepack enable && corepack prepare pnpm@10.33.0 --activate + + - name: Install E2E dependencies + run: pnpm --dir e2e install --frozen-lockfile + + - name: Cache Playwright browsers + uses: actions/cache@v4 + with: + path: ~/.cache/ms-playwright + key: ${{ runner.os }}-playwright-${{ hashFiles('e2e/pnpm-lock.yaml') }} + + - name: Install Playwright Chromium + run: pnpm --dir e2e exec playwright install --with-deps chromium + + - name: Run E2E tests + run: bash e2e/scripts/run.sh + + - name: Upload E2E diagnostics on failure + if: failure() + uses: actions/upload-artifact@v4 + with: + name: e2e-diagnostics + path: | + e2e/playwright-report + e2e/test-results + e2e/.generated/compose-logs.txt + if-no-files-found: ignore + build-and-push: - needs: [test] + needs: [test, e2e] runs-on: ubuntu-latest permissions: contents: read diff --git a/Makefile b/Makefile index d40b21e..6e77a5a 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: default ui check test build image +.PHONY: default ui check test build image e2e e2e-up e2e-down IMAGE_NAME := ghcr.io/tracyhatemice/who @@ -18,3 +18,12 @@ check: image: docker build -t $(IMAGE_NAME) . + +e2e: + bash e2e/scripts/run.sh + +e2e-up: + bash e2e/scripts/run.sh --up-only + +e2e-down: + bash e2e/scripts/run.sh --down-only diff --git a/README.md b/README.md index 105fda1..970ca22 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,7 @@ Every CLI flag has a matching `WHO_*` environment variable (CLI flags take prece | `--data-dir` | `WHO_DATA_DIR` | `./data` (`/data` in Docker) | Directory holding the `who.db` SQLite database | | `--config` | `WHO_CONFIG` | *(empty)* | Optional seed `config.json` imported once when `who.db` is empty | | `--base-path` | `WHO_BASE_PATH` | `/` | Sub-path prefix for Admin UI, `/auth/*`, and `/api/v1/*` (e.g. `/admin`) | +| `--ddns-endpoint` | `WHO_DDNS_ENDPOINT` | *(empty)* | Optional DDNS provider endpoint override (defaults to AWS Route53; used for local/E2E mock endpoints) | | `--oidc-issuer` | `WHO_OIDC_ISSUER` | *(empty)* | OIDC provider issuer URL (e.g. Pocket ID, Authelia, Authentik, Keycloak) | | `--oidc-client-id` | `WHO_OIDC_CLIENT_ID` | *(empty)* | OIDC relying-party client ID | | `--oidc-client-secret` | `WHO_OIDC_CLIENT_SECRET` | *(empty)* | OIDC client secret (optional for public PKCE clients) | @@ -317,3 +318,29 @@ $ make # Build container image locally $ make image ``` + +## End-to-End Testing (`make e2e`) + +The `e2e/` workspace runs full-stack browser and API verification with Playwright Chromium against a self-contained Docker Compose stack (`e2e/docker-compose.yml`): + +- **Traefik (`traefik:v3.6`)**: TLS termination on `https://app.who.localhost:18443` and `https://auth.who.localhost:18443` using ephemerally generated CA and server certificates in `e2e/.generated/`. +- **GLAuth (`ghcr.io/glauth/glauth:v2.5.4`)**: Lightweight LDAP directory backing `admin@who.localhost` and `denied@who.localhost`. +- **Authelia (`authelia/authelia:4.39`)**: OIDC Identity Provider (Authorization Code + `S256` PKCE + `UserInfo`) backed by GLAuth and generated RSA JWKS. +- **`who` (built from root `Dockerfile`)**: Configured with `WHO_BASE_PATH=/who`, `WHO_OIDC_ALLOWED_EMAILS=admin@who.localhost`, and `WHO_DDNS_ENDPOINT=http://mock-sink:9999`. +- **`mock-sink` (`node:24-alpine`)**: HTTP sink capturing outbound Route53 XML `UPSERT` requests and webhook deliveries on `http://127.0.0.1:19999`. + +```console +# One-time Playwright setup (installs e2e deps and Chromium browser binary) +$ pnpm --dir e2e install --frozen-lockfile +$ pnpm --dir e2e exec playwright install --with-deps chromium + +# Cold-boot the full Compose stack, run all 5 Playwright projects, and tear down cleanly +$ make e2e + +# Keep stack running while iterating on individual Playwright specs +$ make e2e-up +$ NODE_EXTRA_CA_CERTS=e2e/.generated/certs/ca.crt pnpm --dir e2e exec playwright test tests/mobile-layout.spec.mjs +$ make e2e-down +``` + +GitHub Actions (`.github/workflows/docker-build.yml`) runs both `test` (`go test -race -v ./...` and `pnpm --dir ui run check`) and `e2e` (`bash e2e/scripts/run.sh`, uploading `e2e/playwright-report`, `e2e/test-results`, and `e2e/.generated/compose-logs.txt` on failure) before `build-and-push`. diff --git a/e2e/tests/mobile-layout.spec.mjs b/e2e/tests/mobile-layout.spec.mjs new file mode 100644 index 0000000..587a212 --- /dev/null +++ b/e2e/tests/mobile-layout.spec.mjs @@ -0,0 +1,265 @@ +import { expect, test } from "@playwright/test"; +import { APP_URL, apiFetch, rawAppFetch } from "./helpers.mjs"; + +const MOBILE_RECORDS = Array.from( + { length: 25 }, + (_, idx) => `e2e-mob-${String(idx + 1).padStart(2, "0")}`, +); + +const OVERFLOW_VIEWS = [ + { + id: "overview", + heading: "Overview", + waitReady: async (page) => { + await expect(page.locator('section[aria-label="Key metrics"]')).toBeVisible(); + await expect(page.locator('#main [aria-busy="true"]')).toHaveCount(0); + }, + }, + { + id: "records", + heading: "Records", + waitReady: async (page) => { + await expect(page.locator('#main [aria-busy="true"]')).toHaveCount(0); + await expect(page.locator("tbody tr").first()).toBeVisible(); + }, + }, + { + id: "access", + heading: "Access Log", + waitReady: async (page) => { + await expect(page.locator('#main [aria-busy="true"]')).toHaveCount(0); + await expect(page.locator("tbody tr").first()).toBeVisible(); + }, + }, + { + id: "audit", + heading: "Audit Log", + waitReady: async (page) => { + await expect(page.locator('#main [aria-busy="true"]')).toHaveCount(0); + await expect(page.locator("tbody tr").first()).toBeVisible(); + }, + }, + { + id: "settings", + heading: "Settings", + waitReady: async (page) => { + await expect(page.locator("#settings-backup")).toBeVisible(); + await expect(page.locator('#main [aria-busy="true"]')).toHaveCount(0); + }, + }, +]; + +function attachErrorCollector(page) { + const pageErrors = []; + const consoleErrors = []; + page.on("pageerror", (err) => { + pageErrors.push(err?.message || String(err)); + }); + page.on("console", (msg) => { + if (msg.type() === "error") { + consoleErrors.push(msg.text()); + } + }); + return { pageErrors, consoleErrors }; +} + +async function measureMainAndHeader(page, scrollTarget) { + return await page.evaluate(async (targetTop) => { + const main = document.getElementById("main"); + const header = main?.querySelector("header"); + if (!main || !header) { + return null; + } + + if (typeof targetTop === "number") { + main.scrollTop = targetTop; + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(resolve)), + ); + } + + const rect = header.getBoundingClientRect(); + return { + scrollHeight: main.scrollHeight, + clientHeight: main.clientHeight, + scrollTop: main.scrollTop, + headerHeight: rect.height, + headerTop: rect.top, + docScrollWidth: document.documentElement.scrollWidth, + innerWidth: window.innerWidth, + }; + }, scrollTarget); +} + +test.describe("Mobile Viewport Layout, Sticky Header & Navigation Drawer (390x844)", () => { + test.beforeAll(async () => { + for (const iam of MOBILE_RECORDS) { + await apiFetch("DELETE", `/records/${encodeURIComponent(iam)}`); + } + + const beforeAccessRes = await apiFetch("GET", "/access-logs?range=1h&pageSize=1"); + expect(beforeAccessRes.status).toBe(200); + const beforeAccessTotal = beforeAccessRes.data?.total ?? 0; + + for (let i = 0; i < MOBILE_RECORDS.length; i++) { + const iam = MOBILE_RECORDS[i]; + const res = await apiFetch("POST", "/records", { + body: { + iam, + isAlias: false, + ip: `198.51.100.${101 + i}`, + }, + }); + expect(res.status).toBe(201); + } + + const headers = { "User-Agent": "who-e2e-mobile/1.0" }; + for (let i = 0; i < 10; i++) { + const res = await rawAppFetch("GET", "/whoami", { headers }); + expect(res.status).toBe(200); + } + for (let i = 0; i < 10; i++) { + const iam = MOBILE_RECORDS[i]; + const res = await rawAppFetch("GET", `/iam/${iam}/198.51.100.${201 + i}`, { + headers, + }); + expect(res.status).toBe(200); + } + for (let i = 0; i < 10; i++) { + const iam = MOBILE_RECORDS[i]; + const res = await rawAppFetch("GET", `/whois/${iam}`, { headers }); + expect(res.status).toBe(200); + } + + await expect + .poll( + async () => { + const all = await apiFetch("GET", "/access-logs?range=1h&pageSize=1"); + return all.data?.total ?? 0; + }, + { timeout: 10_000, intervals: [150] }, + ) + .toBeGreaterThanOrEqual(beforeAccessTotal + 30); + + const auditCheck = await apiFetch("GET", "/audit-logs?pageSize=1"); + expect(auditCheck.status).toBe(200); + expect(auditCheck.data?.total ?? 0).toBeGreaterThanOrEqual(25); + }); + + test.afterAll(async () => { + for (const iam of MOBILE_RECORDS) { + const res = await apiFetch("DELETE", `/records/${encodeURIComponent(iam)}`); + expect([200, 204, 404]).toContain(res.status); + } + }); + + test("keeps 48px sticky header height before/after scroll and zero horizontal overflow across views", async ({ + page, + }) => { + const { pageErrors, consoleErrors } = attachErrorCollector(page); + + for (const view of OVERFLOW_VIEWS) { + await page.goto(`/who/#/${view.id}`); + await expect(page.locator("#main header h1")).toHaveText(view.heading); + await view.waitReady(page); + await page.waitForLoadState("networkidle"); + + const before = await measureMainAndHeader(page, 0); + expect(before, `Missing #main or
on #/${view.id}`).not.toBeNull(); + expect( + before.scrollHeight, + `Expected #main to overflow 844px viewport on #/${view.id}`, + ).toBeGreaterThan(before.clientHeight); + expect( + before.headerHeight, + `Initial header height on #/${view.id}`, + ).toBeGreaterThanOrEqual(47); + expect( + before.headerHeight, + `Initial header height on #/${view.id}`, + ).toBeLessThanOrEqual(49); + expect( + before.headerTop, + `Initial header top on #/${view.id}`, + ).toBeGreaterThanOrEqual(-1); + expect( + before.headerTop, + `Initial header top on #/${view.id}`, + ).toBeLessThanOrEqual(1); + expect( + before.docScrollWidth, + `Initial horizontal overflow on #/${view.id}`, + ).toBeLessThanOrEqual(before.innerWidth + 1); + + const after = await measureMainAndHeader(page, 400); + expect(after, `Missing #main or
after scroll on #/${view.id}`).not.toBeNull(); + expect( + after.scrollTop, + `Expected #main to scroll on #/${view.id}`, + ).toBeGreaterThan(0); + expect( + after.headerHeight, + `Scrolled header height on #/${view.id}`, + ).toBeGreaterThanOrEqual(47); + expect( + after.headerHeight, + `Scrolled header height on #/${view.id}`, + ).toBeLessThanOrEqual(49); + expect( + after.headerTop, + `Sticky header top after scroll on #/${view.id}`, + ).toBeGreaterThanOrEqual(-1); + expect( + after.headerTop, + `Sticky header top after scroll on #/${view.id}`, + ).toBeLessThanOrEqual(1); + expect( + after.docScrollWidth, + `Horizontal overflow after scroll on #/${view.id}`, + ).toBeLessThanOrEqual(after.innerWidth + 1); + + console.log( + `[mobile-layout] #/${view.id}: scrollHeight=${before.scrollHeight} clientHeight=${before.clientHeight} scrollTop=${after.scrollTop} header0=${before.headerHeight}px header400=${after.headerHeight}px top=${after.headerTop}px docWidth=${after.docScrollWidth}/${after.innerWidth}`, + ); + } + + expect(pageErrors).toEqual([]); + expect(consoleErrors).toEqual([]); + }); + + test("opens mobile navigation drawer via hamburger, navigates to Touch Files, and closes cleanly", async ({ + page, + }) => { + const { pageErrors, consoleErrors } = attachErrorCollector(page); + + await page.goto("/who/#/overview"); + await expect(page.locator("#main header h1")).toHaveText("Overview"); + await expect(page.locator('aside[aria-label="Main navigation"]')).toBeHidden(); + + const menuButton = page.getByRole("button", { name: "Open navigation menu" }); + await expect(menuButton).toBeVisible(); + await menuButton.click(); + + const mobileDrawer = page.locator( + 'dialog.mobile-nav-dialog[aria-label="Main navigation"]', + ); + await expect(mobileDrawer).toBeVisible(); + await expect(mobileDrawer).toHaveAttribute("open", ""); + + await mobileDrawer.getByRole("link", { name: "Touch Files", exact: true }).click(); + + await expect(mobileDrawer).toBeHidden(); + await expect(mobileDrawer).not.toHaveAttribute("open", ""); + await expect(page).toHaveURL(`${APP_URL}/who/#/touch`); + await expect(page.locator("#main header h1")).toHaveText("Touch Files"); + + const touchMetrics = await measureMainAndHeader(page, 0); + expect(touchMetrics).not.toBeNull(); + expect(touchMetrics.headerHeight).toBeGreaterThanOrEqual(47); + expect(touchMetrics.headerHeight).toBeLessThanOrEqual(49); + expect(touchMetrics.docScrollWidth).toBeLessThanOrEqual(touchMetrics.innerWidth + 1); + + expect(pageErrors).toEqual([]); + expect(consoleErrors).toEqual([]); + }); +}); From 2b9928521b6b954750060af6aca7f9fc73d484c3 Mon Sep 17 00:00:00 2001 From: tracyhatemice Date: Sun, 29 Nov 2026 19:53:11 +0800 Subject: [PATCH 09/10] docs(e2e): use absolute NODE_EXTRA_CA_CERTS path in README example --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 970ca22..cb7971e 100644 --- a/README.md +++ b/README.md @@ -339,7 +339,7 @@ $ make e2e # Keep stack running while iterating on individual Playwright specs $ make e2e-up -$ NODE_EXTRA_CA_CERTS=e2e/.generated/certs/ca.crt pnpm --dir e2e exec playwright test tests/mobile-layout.spec.mjs +$ NODE_EXTRA_CA_CERTS="$PWD/e2e/.generated/certs/ca.crt" pnpm --dir e2e exec playwright test tests/mobile-layout.spec.mjs $ make e2e-down ``` From 76abf91b635871ae1d902ba33084847d7a78c7b8 Mon Sep 17 00:00:00 2001 From: tracyhatemice Date: Sun, 29 Nov 2026 20:04:47 +0800 Subject: [PATCH 10/10] fix(e2e,auth): ignore e2e in Docker build context, harden run.sh traps/resolve, and guard UserInfo email_verified --- .dockerignore | 1 + e2e/mock-sink/server.mjs | 133 ++++++++++++++++++++----------------- e2e/scripts/prepare.mjs | 4 +- e2e/scripts/run.sh | 10 ++- internal/auth/oidc.go | 3 +- internal/auth/oidc_test.go | 98 +++++++++++++++++++++++++++ 6 files changed, 184 insertions(+), 65 deletions(-) diff --git a/.dockerignore b/.dockerignore index 3839cad..e347a55 100644 --- a/.dockerignore +++ b/.dockerignore @@ -6,6 +6,7 @@ vendor GEMINI.md docs +e2e data who whoami diff --git a/e2e/mock-sink/server.mjs b/e2e/mock-sink/server.mjs index da867d4..57908cf 100644 --- a/e2e/mock-sink/server.mjs +++ b/e2e/mock-sink/server.mjs @@ -18,44 +18,45 @@ function send(res, statusCode, contentType, body) { } const server = http.createServer(async (req, res) => { - const url = new URL(req.url || "/", "http://localhost"); - const { pathname } = url; + try { + const url = new URL(req.url || "/", "http://localhost"); + const { pathname } = url; - if (req.method === "GET" && pathname === "/healthz") { - return send(res, 200, "text/plain; charset=utf-8", "ok\n"); - } + if (req.method === "GET" && pathname === "/healthz") { + return send(res, 200, "text/plain; charset=utf-8", "ok\n"); + } - if (req.method === "GET" && pathname === "/_requests") { - const kind = url.searchParams.get("kind"); - const filtered = kind ? requests.filter((entry) => entry.kind === kind) : requests; - return send(res, 200, "application/json; charset=utf-8", JSON.stringify(filtered)); - } + if (req.method === "GET" && pathname === "/_requests") { + const kind = url.searchParams.get("kind"); + const filtered = kind ? requests.filter((entry) => entry.kind === kind) : requests; + return send(res, 200, "application/json; charset=utf-8", JSON.stringify(filtered)); + } - if (req.method === "DELETE" && pathname === "/_requests") { - requests.length = 0; - return send(res, 200, "application/json; charset=utf-8", JSON.stringify({ ok: true })); - } + if (req.method === "DELETE" && pathname === "/_requests") { + requests.length = 0; + return send(res, 200, "application/json; charset=utf-8", JSON.stringify({ ok: true })); + } - const ddnsMatch = /^\/2013-04-01\/hostedzone\/([^/]+)\/rrset$/.exec(pathname); - if (req.method === "POST" && ddnsMatch) { - const zoneId = decodeURIComponent(ddnsMatch[1]); - const body = await readBody(req); - requests.push({ - kind: "ddns", - method: req.method, - path: pathname, - zoneId, - headers: req.headers, - body, - receivedAt: new Date().toISOString(), - }); - - if (zoneId === "FAILZONE") { - return send( - res, - 400, - "application/xml; charset=utf-8", - ` + const ddnsMatch = /^\/2013-04-01\/hostedzone\/([^/]+)\/rrset$/.exec(pathname); + if (req.method === "POST" && ddnsMatch) { + const zoneId = decodeURIComponent(ddnsMatch[1]); + const body = await readBody(req); + requests.push({ + kind: "ddns", + method: req.method, + path: pathname, + zoneId, + headers: req.headers, + body, + receivedAt: new Date().toISOString(), + }); + + if (zoneId === "FAILZONE") { + return send( + res, + 400, + "application/xml; charset=utf-8", + ` Sender @@ -64,42 +65,54 @@ const server = http.createServer(async (req, res) => { e2e-failzone `, + ); + } + + return send( + res, + 200, + "application/xml; charset=utf-8", + ` +/change/C1E2EPENDING`, ); } - return send( - res, - 200, - "application/xml; charset=utf-8", - ` -/change/C1E2EPENDING`, - ); - } + if (pathname === "/hook" || pathname.startsWith("/hook/")) { + const body = await readBody(req); + requests.push({ + kind: "webhook", + method: req.method || "GET", + path: pathname, + headers: req.headers, + body, + receivedAt: new Date().toISOString(), + }); + + if (pathname === "/hook/fail" || pathname.startsWith("/hook/fail/")) { + return send( + res, + 500, + "application/json; charset=utf-8", + JSON.stringify({ ok: false, error: "simulated webhook failure" }), + ); + } + + return send(res, 200, "application/json; charset=utf-8", JSON.stringify({ ok: true })); + } - if (pathname === "/hook" || pathname.startsWith("/hook/")) { - const body = await readBody(req); - requests.push({ - kind: "webhook", - method: req.method || "GET", - path: pathname, - headers: req.headers, - body, - receivedAt: new Date().toISOString(), - }); - - if (pathname === "/hook/fail" || pathname.startsWith("/hook/fail/")) { + return send(res, 404, "application/json; charset=utf-8", JSON.stringify({ error: "not found" })); + } catch (err) { + if (!res.headersSent) { + const statusCode = err instanceof URIError ? 400 : 500; return send( res, - 500, + statusCode, "application/json; charset=utf-8", - JSON.stringify({ ok: false, error: "simulated webhook failure" }), + JSON.stringify({ error: statusCode === 400 ? "bad request" : "internal server error" }), ); } - - return send(res, 200, "application/json; charset=utf-8", JSON.stringify({ ok: true })); + res.destroy(); } - - return send(res, 404, "application/json; charset=utf-8", JSON.stringify({ error: "not found" })); }); server.listen(port, "0.0.0.0", () => { diff --git a/e2e/scripts/prepare.mjs b/e2e/scripts/prepare.mjs index a3b3b78..dcf3d6b 100644 --- a/e2e/scripts/prepare.mjs +++ b/e2e/scripts/prepare.mjs @@ -142,8 +142,8 @@ function renderAutheliaConfig() { const template = fs.readFileSync(autheliaTemplatePath, "utf8"); const rendered = template - .replace("{{JWKS_PEM_INDENTED}}", indentedPem) - .replace("{{CLIENT_SECRET_HASH}}", autheliaPBKDF2Hash(CLIENT_SECRET)); + .replace("{{JWKS_PEM_INDENTED}}", () => indentedPem) + .replace("{{CLIENT_SECRET_HASH}}", () => autheliaPBKDF2Hash(CLIENT_SECRET)); fs.writeFileSync(autheliaConfigPath, rendered, "utf8"); fs.chmodSync(autheliaConfigPath, 0o644); diff --git a/e2e/scripts/run.sh b/e2e/scripts/run.sh index 3e4d1b1..f7149c7 100755 --- a/e2e/scripts/run.sh +++ b/e2e/scripts/run.sh @@ -51,7 +51,7 @@ fi cleanup() { local exit_code=$? - trap - EXIT + trap - EXIT INT TERM if [[ "$exit_code" -ne 0 ]]; then dump_logs fi @@ -61,6 +61,8 @@ cleanup() { if [[ "$mode" == "full" ]]; then trap cleanup EXIT + trap 'exit 130' INT + trap 'exit 143' TERM fi wait_for_stack() { @@ -75,7 +77,10 @@ wait_for_stack() { for url in "${endpoints[@]}"; do while true; do if [[ "$url" == https://* ]]; then - if curl -fsS --cacert "$CA_CERT" --max-time 5 "$url" >/dev/null 2>&1; then + if curl -fsS --cacert "$CA_CERT" \ + --resolve "app.who.localhost:18443:127.0.0.1" \ + --resolve "auth.who.localhost:18443:127.0.0.1" \ + --max-time 5 "$url" >/dev/null 2>&1; then break fi else @@ -97,6 +102,7 @@ wait_for_stack() { } node "$E2E_DIR/scripts/prepare.mjs" +rm -f "$LOGS_OUT" compose up -d --build wait_for_stack diff --git a/internal/auth/oidc.go b/internal/auth/oidc.go index ef809d3..4b07634 100644 --- a/internal/auth/oidc.go +++ b/internal/auth/oidc.go @@ -597,7 +597,8 @@ func hydrateClaimsFromUserInfo( if claims.Email == "" { claims.Email = uiClaims.Email } - if claims.EmailVerified == nil { + if claims.EmailVerified == nil && + (claims.Email == "" || uiClaims.Email == "" || strings.EqualFold(claims.Email, uiClaims.Email)) { claims.EmailVerified = uiClaims.EmailVerified } if claims.Name == "" { diff --git a/internal/auth/oidc_test.go b/internal/auth/oidc_test.go index 1dcae8c..e51eeeb 100644 --- a/internal/auth/oidc_test.go +++ b/internal/auth/oidc_test.go @@ -1432,3 +1432,101 @@ func TestOIDCCallbackUserInfoPreservesIDTokenClaimsAndHandlesNameFallback(t *tes errRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true) mustRedirect(t, errRec, "/who/?auth_error=auth_failed", "/userinfo 500 when ID token lacks email") } + +func TestOIDCCallbackDoesNotCrossBindUserInfoEmailVerified(t *testing.T) { + ctx := context.Background() + db := openAuthTestDB(t) + idp := newMockOIDCIdP(t) + + mgr, err := auth.NewManager(auth.Config{ + Issuer: idp.server.URL, + ClientID: "who-admin", + ClientSecret: "super-secret", + BasePath: "/who", + AllowedEmails: []string{"admin@example.com"}, + HTTPClient: idp.server.Client(), + }, db, fixedClientIP) + mustNoErr(t, err, "NewManager") + + mux := http.NewServeMux() + mgr.RegisterRoutes(mux) + + // 1. UserInfo email_verified=true for a different email must NOT verify ID token email. + idp.setNextClaims(idTokenClaimsSpec{ + Sub: "user-cross", + Email: "admin@example.com", + }) + idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) { + writeTestJSON(w, map[string]any{ + "sub": "user-cross", + "email": "other@example.com", + "email_verified": true, + "name": "Other Email User", + }) + }) + + deniedRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true) + mustRedirect(t, deniedRec, "/who/?auth_error=access_denied", "cross-email email_verified must not be adopted") + if c := findCookie(deniedRec.Result().Cookies(), "who_session"); c != nil && c.Value != "" { + t.Fatalf("expected no who_session cookie on cross-bound UserInfo email_verified, got %+v", c) + } + + sessions, err := db.ListSessions(ctx) + mustNoErr(t, err, "ListSessions after cross-bind attempt") + if len(sessions) != 0 { + t.Fatalf("expected 0 sessions after cross-bind attempt, got %+v", sessions) + } + + audits, _, err := db.QueryAuditLogs(ctx, storage.AuditLogFilter{Category: "auth", Limit: 10}) + mustNoErr(t, err, "QueryAuditLogs") + if len(audits) != 1 || audits[0].Action != "login_denied" { + t.Fatalf("expected 1 login_denied audit log, got %+v", audits) + } + + // 2. Case-insensitive matching email in UserInfo adopts email_verified=true. + idp.setNextClaims(idTokenClaimsSpec{ + Sub: "user-case", + Email: "Admin@Example.COM", + Name: "Admin User", + }) + idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) { + writeTestJSON(w, map[string]any{ + "sub": "user-case", + "email": "admin@example.com", + "email_verified": true, + }) + }) + caseRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true) + mustRedirect(t, caseRec, "/who/", "case-insensitive matching UserInfo email") + + // 3. Omitted email in UserInfo still adopts email_verified=true for the ID token email. + idp.setNextClaims(idTokenClaimsSpec{ + Sub: "user-omitted-ui-email", + Email: "admin@example.com", + }) + idp.setUserInfoHandler(func(w http.ResponseWriter, _ *http.Request) { + writeTestJSON(w, map[string]any{ + "sub": "user-omitted-ui-email", + "email_verified": true, + "name": "Omitted Email User", + }) + }) + omittedRec := runMockOIDCFlow(t, mux, idp, "https://who.example.org/who", true) + mustRedirect(t, omittedRec, "/who/", "omitted UserInfo email adopts email_verified") + + sessions, err = db.ListSessions(ctx) + mustNoErr(t, err, "ListSessions") + if len(sessions) != 2 { + t.Fatalf("expected 2 sessions, got %+v", sessions) + } + bySub := map[string]storage.Session{} + for _, s := range sessions { + bySub[s.Sub] = s + } + if u := bySub["user-case"]; !u.EmailVerified || u.Email != "Admin@Example.COM" { + t.Fatalf("unexpected user-case session: %+v", u) + } + if u := bySub["user-omitted-ui-email"]; !u.EmailVerified || u.Email != "admin@example.com" || u.Name != "Omitted Email User" { + t.Fatalf("unexpected user-omitted-ui-email session: %+v", u) + } +}