package server import ( "context" "encoding/json" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "strings" "testing" "time" "pageswiki/internal/store" ) func TestCLIConsentChromium(t *testing.T) { if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" { t.Skip("opt-in Chromium") } for _, width := range []string{"1440", "390"} { t.Run(width, func(t *testing.T) { s, api, domain := configFixture(t) if err := s.store.SetAuthProviderConfig(domain, store.AuthProviderConfig{Kind: "oidc", Enabled: true, Issuer: "https://id.example", ClientID: "client"}); err != nil { t.Fatal(err) } browser, err := s.store.CreateBrowserAuthSession(domain, s.mustCLIPrincipal(t, domain, api), 0) if err != nil { t.Fatal(err) } var code string server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" && r.URL.Path == "/_/auth/cli/verify" { r.AddCookie(&http.Cookie{Name: authCookieName, Value: browser}) rec := httptest.NewRecorder() s.handleAuth(rec, r) for k, values := range rec.Header() { w.Header()[k] = values } s.setAuthCookie(w, r, browser) encoded, _ := json.Marshal(code) script := `` w.WriteHeader(rec.Code) _, _ = w.Write([]byte(strings.Replace(rec.Body.String(), "", script+"", 1))) return } if strings.HasPrefix(r.URL.Path, "/_/auth/") { s.withAuthorization(http.HandlerFunc(s.handleAuth)).ServeHTTP(w, r) return } s.withAuthorization(s.mux).ServeHTTP(w, r) })) defer server.Close() origin := strings.Replace(server.URL, "127.0.0.1", "localhost", 1) id, _, c, err := s.store.StartCLIAuth(context.Background(), domain, origin, strings.Repeat("c", 43)) if err != nil { t.Fatal(err) } code = c if err := s.store.BindCLIAuth(context.Background(), domain, origin, id, browser); err != nil { t.Fatal(err) } ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second) defer cancel() screenshot := "" if dir := os.Getenv("PAGESWIKI_BROWSER_ARTIFACTS"); dir != "" { if err := os.MkdirAll(dir, 0755); err != nil { t.Fatal(err) } screenshot = filepath.Join(dir, "cli-consent-"+width+".png") } command := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", origin+cliVerifyPath(id), t.TempDir(), screenshot, width, "900") if out, err := command.CombinedOutput(); err != nil { t.Fatalf("consent browser: %v %s", err, out) } grant, err := s.store.CLIAuthRequest(context.Background(), domain, origin, id) if err != nil || grant.State != "approved" { t.Fatalf("not persisted: %+v %v", grant, err) } }) } }