//go:build browser package equipotest import ( "context" "fmt" "net/http" "net/http/httptest" "net/url" "strings" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/browsertest" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/runner/forge/forgetest" "amadan.net/rastrillo/rastrillo" "amadan.net/rastrillo/rastrillo/harness" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/network" "github.com/chromedp/chromedp" ) func TestBrowserGitHubManifestCSP(t *testing.T) { const origin = "https://equipo.example.test" d, logger := foundationDB(t) mail := &capturingMailer{} g := forgetest.NewGitHub(t) cfg := testConfig(origin) cfg.AllowLoggedMail = false cfg.MailConfigured = true cfg.GitHubEnabled = true cfg.GitHubTransport = g.Transport() router, e := equipo.Router(d, cfg, mail, logger) if e != nil { t.Fatal(e) } handler, closeHandler, e := rastrillo.Handler(rastrillo.Options{Mux: equipo.Mux(router), Logger: logger}) if e != nil { t.Fatal(e) } defer closeHandler() var posts atomic.Int32 server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Host == "github.com" { if r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/settings/apps/new") { posts.Add(1) if r.ParseForm() != nil || r.Form.Get("manifest") == "" { t.Error("manifest POST missing") } http.Redirect(w, r, origin+"/github/connect/manifest?"+url.Values{"code": {g.Code}, "state": {r.URL.Query().Get("state")}}.Encode(), http.StatusSeeOther) return } if strings.HasSuffix(r.URL.Path, "/installations/new") { http.Redirect(w, r, origin+"/github/connect/installation?"+url.Values{"state": {r.URL.Query().Get("state")}, "installation_id": {"999999"}}.Encode(), http.StatusSeeOther) return } http.NotFound(w, r) return } handler.ServeHTTP(w, r) })) defer server.Close() client := signinClient(t, server.URL) client.Transport = server.Client().Transport signinEmail(t, client, server.URL, origin, mail, ownerAddress) source, _ := url.Parse(server.URL) opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.NoSandbox, chromedp.UserDataDir(t.TempDir()), chromedp.Flag("ignore-certificate-errors", true), chromedp.Flag("no-proxy-server", true), chromedp.Flag("host-resolver-rules", "MAP equipo.example.test "+source.Host+", MAP github.com "+source.Host)) alloc, stop := chromedp.NewExecAllocator(context.Background(), opts...) defer stop() ctx, cancel := chromedp.NewContext(alloc) defer cancel() ctx, deadline := context.WithTimeout(ctx, 45*time.Second) defer deadline() run := func(actions ...chromedp.Action[chromedp.Void]) { t.Helper() if err := chromedp.Do(ctx, actions...); err != nil { t.Fatal(err) } } yes := true for _, cookie := range client.Jar.Cookies(source) { run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, e := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: cookie.Name, Value: cookie.Value, URL: origin + "/", Path: "/", Secure: &yes, HTTPOnly: &yes}) return e })) } run(chromedp.Navigate(origin+"/conversation/settings/github"), browsertest.Wait(`!!document.querySelector('#github-account')`)) run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, e := chromedp.Evaluate[any](fmt.Sprintf(`document.querySelector('#github-account').value=%q`, g.Login))(ctx, target) return e }), browsertest.Click("#github-start button"), browsertest.Wait(`(()=>{const b=document.querySelector('form[action^="https://github.com/"] button');if(!b)return false;const r=b.getBoundingClientRect();return document.elementFromPoint(r.x+r.width/2,r.y+r.height/2)===b})()`), browsertest.Click(`form[action^="https://github.com/"] button`), browsertest.Wait(`location.origin==="https://equipo.example.test" && location.pathname==="/conversation/settings/github" && location.search==="" && !!document.querySelector('form[action="/github/connect/confirm"]')`)) if posts.Load() != 1 { t.Fatal("manifest POST did not reach GitHub") } // A normal Settings document still cannot submit to GitHub. run(chromedp.Navigate(origin+"/conversation/settings/thinking"), browsertest.Wait(`!!document.querySelector('form')`), chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, e := chromedp.Evaluate[any](`(()=>{window.addEventListener('securitypolicyviolation',()=>window.githubBlocked=true,{once:true});const f=document.createElement('form');f.method='post';f.action='https://github.com/organizations/test/settings/apps/new';document.body.append(f);f.submit()})()`)(ctx, target) return e })) run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { current, e := chromedp.Evaluate[string](`location.origin+location.pathname`)(ctx, target) if e != nil { return e } if current != origin+"/conversation/settings/thinking" { return fmt.Errorf("unrelated Settings page submitted externally") } return nil })) run(browsertest.Wait(`window.githubBlocked===true`)) if posts.Load() != 1 { t.Fatal("CSP exception spread to other Settings") } }