oficina / home Public

Clone
git clone https://amadan.net/oficina/home

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package home
4
5import (
6 "context"
7 "crypto/x509"
8 "fmt"
9 "net/http"
10 "net/http/httptest"
11 "net/url"
12 "strings"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/home/internal/home/sealtest"
17 "amadan.net/rastrillo/rastrillo/harness"
18 "amadan.net/rastrillo/rastrillo/sessions"
19 "github.com/chromedp/cdproto/cdp"
20 "github.com/chromedp/cdproto/emulation"
21 "github.com/chromedp/cdproto/network"
22 "github.com/chromedp/cdproto/webauthn"
23 "github.com/chromedp/chromedp"
24)
25
26// cdpStep is one DevTools command as a step. chromedp v0.21 made
27// commands values rather than actions, so a step sends one through the
28// tab it runs on.
29func cdpStep[P, R any](c cdp.Command[P, R], params P) chromedp.Action[chromedp.Void] {
30 return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error {
31 _, err := cdp.Call(ctx, t, c, params)
32 return err
33 })
34}
35
36const browserIssuer = "https://id.example.org"
37const browserRP = "id.example.org"
38
39// Two different sites, real HTTPS and real browser cookies. DNS is redirected
40// only inside this Chrome process; the test server listens on loopback.
41func idBrowser(t *testing.T) (exchangePair, context.Context, webauthn.AuthenticatorID) {
42 return idBrowserFor(t, "https://directory.example.test")
43}
44func idBrowserFor(t *testing.T, consumer string) (exchangePair, context.Context, webauthn.AuthenticatorID) {
45 t.Helper()
46 p := newExchangePair(t)
47 consumerURL, _ := url.Parse(consumer)
48 origins := Origins{browserIssuer, consumer}
49 old := p.credential.App
50 app, err := NewWithOrigins(old.secrets, p.credential.db, quietLogger(), origins)
51 if err != nil {
52 t.Fatal(err)
53 }
54 app.flow.Classifier = old.flow.Classifier
55 app.runtime = old.runtime
56 p.credential.App = app
57 p.credential.runtime.origins = origins
58 p.credential.runtime.consumers["directory"] = consumer
59 directory, err := NewRuntime(Runtime{role: "directory", origins: origins, secrets: p.directory.secrets, keys: p.credential.runtime.keys}, p.directory.db, quietLogger())
60 if err != nil {
61 t.Fatal(err)
62 }
63 p.directory = directory
64 ch, dh := p.credential.Router(), p.directory.Router()
65 server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
66 if r.Host == browserRP {
67 ch.ServeHTTP(w, r)
68 } else if r.Host == consumerURL.Hostname() {
69 dh.ServeHTTP(w, r)
70 } else {
71 http.NotFound(w, r)
72 }
73 }))
74 t.Cleanup(server.Close)
75 u, _ := url.Parse(server.URL)
76 useChrome(t)
77 opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.NoSandbox, chromedp.Flag("ignore-certificate-errors", true), chromedp.Flag("no-proxy-server", true), chromedp.Flag("host-resolver-rules", "MAP id.example.org "+u.Host+", MAP "+consumerURL.Hostname()+" "+u.Host), chromedp.UserDataDir(t.TempDir()))
78 alloc, stop := chromedp.NewExecAllocator(context.Background(), opts...)
79 ctx, cancel := chromedp.NewContext(alloc)
80 t.Cleanup(func() { _ = chromedp.Cancel(ctx); cancel(); stop() })
81 if err := chromedp.Do(ctx); err != nil {
82 t.Fatal(err)
83 }
84 var authenticator webauthn.AuthenticatorID
85 idBrowserRun(t, ctx, cdpStep(webauthn.Enable, webauthn.EnableParams{}), chromedp.Func(func(ctx context.Context, tab *chromedp.Target) error {
86 res, e := cdp.Call(ctx, tab, webauthn.AddVirtualAuthenticator, webauthn.AddVirtualAuthenticatorParams{Options: &webauthn.VirtualAuthenticatorOptions{Protocol: webauthn.AuthenticatorProtocolCtap2, Transport: webauthn.AuthenticatorTransportInternal, HasResidentKey: true, HasUserVerification: true, IsUserVerified: true, AutomaticPresenceSimulation: true}})
87 authenticator = res.AuthenticatorID
88 return e
89 }))
90 return p, ctx, authenticator
91}
92func idBrowserRun(t *testing.T, ctx context.Context, actions ...chromedp.Action[chromedp.Void]) {
93 t.Helper()
94 ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
95 defer cancel()
96 if err := chromedp.Do(ctx, actions...); err != nil {
97 t.Fatal(err)
98 }
99}
100func idBrowserCookie(c *http.Cookie) chromedp.Action[chromedp.Void] {
101 return browserCookie(c.Name, c.Value, browserIssuer+"/", true, true)
102}
103
104// browserCookie sets one SameSite=Lax cookie for url.
105func browserCookie(name, value, url string, httpOnly, secure bool) chromedp.Action[chromedp.Void] {
106 return cdpStep(network.SetCookie, network.SetCookieParams{Name: name, Value: value, URL: url, HTTPOnly: &httpOnly, Secure: &secure, SameSite: network.CookieSameSiteLax})
107}
108
109func TestIDBrowserDirectPasskeyAndGeneratedNames(t *testing.T) {
110 p, ctx, authenticator := idBrowser(t)
111 s := signInFully(t, p.credential, sealtest.CanaryAddress)
112 subject := subjectOf(t, p.credential, s)
113 idBrowserRun(t, ctx, idBrowserCookie(s), chromedp.Navigate(browserIssuer+"/passkey/enrol"), chromedp.WaitVisible("#passkey-enrol"), chromedp.Click("#passkey-enrol"), chromedp.WaitVisible(`form[action="/passkey/codes"]`))
114 var credentials []*webauthn.Credential
115 idBrowserRun(t, ctx, chromedp.Func(func(ctx context.Context, tab *chromedp.Target) error {
116 res, e := cdp.Call(ctx, tab, webauthn.GetCredentials, webauthn.GetCredentialsParams{AuthenticatorID: authenticator})
117 credentials = res.Credentials
118 return e
119 }))
120 if len(credentials) != 1 || !credentials[0].IsResidentCredential || credentials[0].UserName != subject || credentials[0].UserDisplayName != subject {
121 t.Fatal("WebAuthn names were not generated opaque identifiers")
122 }
123 idBrowserRun(t, ctx, cdpStep(network.DeleteCookies, network.DeleteCookiesParams{Name: s.Name, URL: browserIssuer + "/"}), chromedp.Navigate(browserIssuer+"/signin?return_to=%2Fpasskey%2Fcodes&way=passkey"), chromedp.WaitVisible(`button[data-rst-passkey]:enabled`), chromedp.Click(`button[data-rst-passkey]`), chromedp.WaitVisible(`form[action="/passkey/codes"]`))
124 sealtest.AssertNoPlaintext(t, p.credential.dbPath)
125}
126
127// addCredential is WebAuthn.addCredential with only the fields an old
128// non-resident key has. cdproto's Credential always sends
129// generateCmtgKeyOnNextOperation, and Chrome refuses that field on an
130// authenticator without the CMTG extension (-32602).
131var addCredential = cdp.Command[addCredentialParams, cdp.Empty]{Method: webauthn.CommandAddCredential}
132
133type addCredentialParams struct {
134 AuthenticatorID webauthn.AuthenticatorID `json:"authenticatorId"`
135 Credential legacyCredential `json:"credential"`
136}
137
138type legacyCredential struct {
139 CredentialID []byte `json:"credentialId"`
140 IsResidentCredential bool `json:"isResidentCredential"`
141 RpID string `json:"rpId"`
142 PrivateKey []byte `json:"privateKey"`
143 SignCount int `json:"signCount"`
144}
145
146func TestIDBrowserLegacyNonresidentGate(t *testing.T) {
147 p, ctx, authenticator := idBrowser(t)
148 s := signInFully(t, p.credential, sealtest.CanaryAddress)
149 key := enrol(t, p.credential, s)
150 if _, err := p.credential.db.Writer().Exec("DELETE FROM home_id_discoverable"); err != nil {
151 t.Fatal(err)
152 }
153 gated := redeemAfterSignIn(t, p.credential, sealtest.CanaryAddress)
154 if _, err := p.credential.db.Writer().Exec("UPDATE passkey_pending SET return_to='/passkey/codes'"); err != nil {
155 t.Fatal(err)
156 }
157 private, err := x509.MarshalPKCS8PrivateKey(key.Key)
158 if err != nil {
159 t.Fatal(err)
160 }
161 actions := []chromedp.Action[chromedp.Void]{cdpStep(addCredential, addCredentialParams{AuthenticatorID: authenticator, Credential: legacyCredential{CredentialID: key.CredID, RpID: browserRP, PrivateKey: private, IsResidentCredential: false}})}
162 for _, c := range gated.Result().Cookies() {
163 if c.Value != "" {
164 actions = append(actions, idBrowserCookie(c))
165 }
166 }
167 actions = append(actions, chromedp.Navigate(browserIssuer+confirmPath), chromedp.WaitVisible("#passkey-confirm"), chromedp.Click("#passkey-confirm"), chromedp.WaitVisible(`form[action="/passkey/codes"]`))
168 idBrowserRun(t, ctx, actions...)
169}
170func TestIDBrowserScriptlessCrossSiteReturn(t *testing.T) {
171 p, ctx, _ := idBrowser(t)
172 idBrowserRun(t, ctx, cdpStep(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true}), chromedp.Navigate(p.directory.origins.Directory+"/auth/start"), chromedp.WaitVisible("#rst-signin-email"), chromedp.SendKeys("#rst-signin-email", sealtest.CanaryAddress), chromedp.Click(`form[action="/signin"] button`), chromedp.WaitVisible(`form[action="/signin/forget"] button`))
173 token := capturedLink(t, p.credential)
174 idBrowserRun(t, ctx, chromedp.Navigate(browserIssuer+linkPath+"?token="+url.QueryEscape(token)), chromedp.WaitVisible(`form[action="/signin/verify"] button`), chromedp.Click(`form[action="/signin/verify"] button`), chromedp.WaitVisible(`form[data-assertion-handoff] button`), chromedp.Click(`form[data-assertion-handoff] button`), chromedp.WaitVisible(`[estilo-account]`))
175 var location string
176 idBrowserRun(t, ctx, harness.Into(&location, chromedp.Location()))
177 if !strings.HasPrefix(location, p.directory.origins.Directory+"/") {
178 t.Fatal("cross-site finish lost browser binding")
179 }
180 sealtest.AssertNoPlaintext(t, p.credential.dbPath)
181 sealtest.AssertNoPlaintext(t, p.directoryPath)
182}
183
184func TestIDBrowserSignoutBothOrigins(t *testing.T) {
185 for _, consumer := range []string{"https://example.org", "https://directory.example.test"} {
186 for _, scripts := range []bool{true, false} {
187 t.Run(fmt.Sprintf("%s/scripts=%v", consumer, scripts), func(t *testing.T) {
188 p, ctx, _ := idBrowserFor(t, consumer)
189 credential := signInFully(t, p.credential, sealtest.CanaryAddress)
190 w := httptest.NewRecorder()
191 req := httptest.NewRequest("POST", consumer+"/", nil)
192 if err := p.directory.sessions.SignIn(w, req, sessions.Session{Subject: subjectOf(t, p.credential, credential), Method: "assertion", AuthTime: time.Now()}); err != nil {
193 t.Fatal(err)
194 }
195 directory := sessionCookie(w)
196 if directory == nil {
197 t.Fatal("missing directory session")
198 }
199 idBrowserRun(t, ctx, cdpStep(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: !scripts}), idBrowserCookie(credential), browserCookie(directory.Name, directory.Value, consumer+"/", true, true), chromedp.Navigate(consumer+"/"), chromedp.WaitVisible(`[estilo-account] > summary`), chromedp.Click(`[estilo-account] > summary`), chromedp.Click(`form[action="/signout"] button`))
200 if !scripts {
201 idBrowserRun(t, ctx, chromedp.WaitVisible(`form[data-assertion-handoff] button`), chromedp.Click(`form[data-assertion-handoff] button`))
202 }
203
204 if consumer == "https://directory.example.test" {
205 // Lax cookies do not ride a cross-site POST. The same-origin fallback
206 // button on ID must complete that second hop with the credential cookie.
207 idBrowserRun(t, ctx, chromedp.WaitVisible(`form[rst-form][action="/signout"] button`), chromedp.Click(`form[rst-form][action="/signout"] button`))
208 }
209 idBrowserRun(t, ctx, chromedp.WaitVisible(`a[rst-btn="primary"]`))
210 var rows int
211 p.credential.db.Writer().QueryRow("SELECT count(*) FROM sessions").Scan(&rows)
212 if rows != 0 {
213 t.Fatal("browser signout retained ID session", rows)
214 }
215 p.directory.db.Writer().QueryRow("SELECT count(*) FROM sessions").Scan(&rows)
216 if rows != 0 {
217 t.Fatal("browser signout retained directory session", rows)
218 }
219 })
220 }
221 }
222}
223