//go:build browser
package idtest
import (
"context"
"fmt"
"html/template"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"amadan.net/oficina/equipo/internal/browsertest"
"amadan.net/rastrillo/rastrillo/harness"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/chromedp"
)
// The test Home uses the production assertion signer and closed authorize
// contract. Its identity is fixed; Home's own WebAuthn browser tests exercise
// earning that identity. This test covers Equipo's real cross-site door.
func TestBrowserOficinaIDDoor(t *testing.T) {
const origin = "https://equipo.example.test"
const home = "https://id.example.org"
f := fixtureAt(t, true, origin, home)
local := f.link(t)
var callbacks atomic.Int32
var nonce string
continuePage := template.Must(template.New("continue").Parse(`
Oficina ID`))
receiptPage := template.Must(template.New("receipt").Parse(`Oficina ID`))
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Host == "equipo.example.test" {
if r.URL.Path == "/auth/assertion" {
callbacks.Add(1)
if r.Header.Get("Origin") != home {
t.Error("callback lost issuer Origin")
}
for _, c := range r.Cookies() {
if c.Name == "__Host-equipo-id-pending" {
t.Error("Lax pending cookie sent on cross-site POST")
}
}
}
f.h.ServeHTTP(w, r)
return
}
if r.Host != "id.example.org" {
http.NotFound(w, r)
return
}
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
switch r.URL.Path {
case "/authorize":
q := r.URL.Query()
if r.Method != "GET" || len(q) != 2 || len(q["consumer"]) != 1 || q.Get("consumer") != "equipo" || len(q["nonce"]) != 1 {
http.Error(w, "invalid test authorization", 400)
return
}
nonce = q.Get("nonce")
_ = continuePage.Execute(w, nil)
case "/continue":
if r.Method != "POST" || r.Header.Get("Origin") != home || nonce == "" {
http.Error(w, "invalid test continuation", 400)
return
}
token := f.signed(t, nonce, person, time.Now())
nonce = ""
_ = receiptPage.Execute(w, struct{ Target, Token string }{origin + "/auth/assertion", token})
default:
http.NotFound(w, r)
}
}))
defer server.Close()
u, _ := url.Parse(server.URL)
profile := t.TempDir()
opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.NoSandbox, chromedp.UserDataDir(profile), chromedp.Flag("ignore-certificate-errors", true), chromedp.Flag("no-proxy-server", true), chromedp.Flag("host-resolver-rules", "MAP equipo.example.test "+u.Host+", MAP id.example.org "+u.Host))
alloc, stop := chromedp.NewExecAllocator(context.Background(), opts...)
defer stop()
ctx, cancel := chromedp.NewContext(alloc)
defer cancel()
ctx, deadline := context.WithTimeout(ctx, 60*time.Second)
defer deadline()
run := func(actions ...chromedp.Action[chromedp.Void]) {
t.Helper()
if e := chromedp.Do(ctx, actions...); e != nil {
t.Fatal(e)
}
}
run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
_, e := cdp.Call(ctx, target, emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true})
return e
}))
run(chromedp.Navigate(origin+"/signin"), browsertest.Wait(`!!document.querySelector('a[href^="/signin/oficina"]')`))
capture := func(name string) {
for _, width := range []int64{390, 1280} {
run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
_, e := cdp.Call(ctx, target, emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: width, Height: 900, DeviceScaleFactor: 1, Mobile: width == 390})
if e != nil {
return e
}
overflow, e := chromedp.Evaluate[bool](`document.documentElement.scrollWidth>innerWidth`)(ctx, target)
if e != nil {
return e
}
if overflow {
return fmt.Errorf("%s overflows at %d", name, width)
}
if dir := os.Getenv("EQUIPO_BROWSER_ARTIFACTS"); dir != "" {
shot, e := chromedp.CaptureScreenshot()(ctx, target)
if e != nil {
return e
}
if e = os.MkdirAll(dir, 0700); e != nil {
return e
}
return os.WriteFile(filepath.Join(dir, fmt.Sprintf("%s-%d.png", name, width)), shot, 0600)
}
return nil
}))
}
}
capture("oficina-id-door")
run(browsertest.Click(`a[href^="/signin/oficina"]`), browsertest.Wait(`location.origin==="https://id.example.org" && !!document.querySelector('#continue')`), browsertest.Click("#continue"), browsertest.Wait(`!!document.querySelector('#return')`), browsertest.Click("#return"), browsertest.Wait(`location.origin==="https://equipo.example.test" && location.pathname==="/conversation"`))
if callbacks.Load() != 1 {
t.Fatal("full callback did not run", callbacks.Load())
}
run(chromedp.Navigate(origin+"/conversation/settings/oficina-id"), browsertest.Wait(`document.body.textContent.includes("pr_aaaaaaaaaaaaaaaaaaaaaaaaaa")`))
capture("oficina-id-settings")
run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
body, e := chromedp.Evaluate[string](`document.body.textContent`)(ctx, target)
if e != nil {
return e
}
if strings.Contains(body, homeAddress) {
return fmt.Errorf("Home address leaked")
}
return nil
}))
// Local credentials remain valid after the browser signs in through Home.
if r := f.request("GET", "/work", "", nil, local); r.Code != 200 {
t.Fatal("email session changed", r.Code)
}
}