//go:build e2elive package e2elivetest import ( "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/rastrillo/rastrillo/pow" "context" "crypto/ed25519" "crypto/rand" "encoding/base64" "html" "io" "net/http" "net/http/cookiejar" "net/url" "regexp" "strings" "sync" "testing" "time" ) type capturingMailer struct { mu sync.Mutex bodies []string } func (m *capturingMailer) link(t *testing.T) string { t.Helper() m.mu.Lock() defer m.mu.Unlock() if len(m.bodies) == 0 { t.Fatal("no email") } for _, word := range strings.Fields(m.bodies[len(m.bodies)-1]) { if strings.Contains(word, "/auth/verify?") { return word } } t.Fatal("no link in email") return "" } func mustURL(t *testing.T, s string) *url.URL { t.Helper() u, err := url.Parse(s) if err != nil { t.Fatal(err) } return u } func signinClient(t *testing.T, base string) *http.Client { t.Helper() jar, err := cookiejar.New(nil) if err != nil { t.Fatal(err) } return &http.Client{Jar: jar, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} } func clientGet(t *testing.T, c *http.Client, target string) *http.Response { t.Helper() res, err := c.Get(target) if err != nil { t.Fatal(err) } return res } func clientPost(t *testing.T, c *http.Client, target, origin string, form url.Values) *http.Response { t.Helper() req, err := http.NewRequest(http.MethodPost, target, strings.NewReader(form.Encode())) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") if origin != "" { req.Header.Set("Origin", origin) } res, err := c.Do(req) if err != nil { t.Fatal(err) } return res } func readBody(t *testing.T, res *http.Response) string { t.Helper() defer res.Body.Close() b, err := io.ReadAll(res.Body) if err != nil { t.Fatal(err) } return string(b) } func formFields(t *testing.T, body, action string) url.Values { t.Helper() values := url.Values{} found := false for _, form := range regexp.MustCompile(`(?s)]*>.*?`).FindAllString(body, -1) { if !strings.Contains(form, `action="`+action+`"`) { continue } found = true for _, input := range regexp.MustCompile(`]*>`).FindAllString(form, -1) { attrs := map[string]string{} for _, pair := range regexp.MustCompile(`([a-z_-]+)="([^"]*)"`).FindAllStringSubmatch(input, -1) { attrs[pair[1]] = html.UnescapeString(pair[2]) } if attrs["name"] != "" { values.Set(attrs["name"], attrs["value"]) } } } if !found { t.Fatalf("missing form %s", action) } return values } type emailChallenge struct { values url.Values ready time.Time } func prepareEmail(t *testing.T, c *http.Client, base, address string) emailChallenge { t.Helper() res := clientGet(t, c, base+"/signin?force=1") if res.StatusCode != 200 { t.Fatalf("signin page: %d", res.StatusCode) } values := formFields(t, readBody(t, res), "/auth/begin") values.Set("address", address) if values.Get("force") != "1" { t.Fatal("email fallback not rendered") } return emailChallenge{values: values, ready: time.Now().Add(pow.DefaultMinAge + 50*time.Millisecond)} } func submitEmail(t *testing.T, c *http.Client, base, origin string, challenge emailChallenge) { t.Helper() time.Sleep(time.Until(challenge.ready)) res := clientPost(t, c, base+"/auth/begin", origin, challenge.values) defer res.Body.Close() if res.StatusCode != 303 || !strings.Contains(res.Header.Get("Location"), "sent=1") { t.Fatalf("begin: %d %s", res.StatusCode, res.Header.Get("Location")) } } func beginEmail(t *testing.T, c *http.Client, base, origin, address string) { t.Helper() submitEmail(t, c, base, origin, prepareEmail(t, c, base, address)) } func confirmEmail(t *testing.T, c *http.Client, base, origin string, m *capturingMailer) *http.Response { t.Helper() link := mustURL(t, m.link(t)) local := mustURL(t, base).ResolveReference(&url.URL{Path: link.Path, RawQuery: link.RawQuery}) res := clientGet(t, c, local.String()) if res.StatusCode != 200 { t.Fatalf("confirm: %d", res.StatusCode) } values := formFields(t, readBody(t, res), "/auth/verify") return clientPost(t, c, base+"/auth/verify", origin, values) } // signinEmail is shared by HTTP, browser setup and performance callers. // The client keeps real cookies; every credential comes from the rendered flow. func machine(t *testing.T) (string, ed25519.PrivateKey) { t.Helper() pub, key, err := ed25519.GenerateKey(rand.Reader) executionMust(t, err) return base64.RawURLEncoding.EncodeToString(pub), key } func beginDevice(t *testing.T, s *equipo.Store) (runnerproto.DeviceCode, ed25519.PrivateKey) { t.Helper() pub, key := machine(t) code, err := s.BeginEnrolment(context.Background(), pub, "Desk machine") executionMust(t, err) return code, key } func deviceProof(code runnerproto.DeviceCode, key ed25519.PrivateKey) runnerproto.ExchangeProof { nonce := make([]byte, 32) rand.Read(nonce) p := runnerproto.ExchangeProof{EnrolmentID: code.EnrolmentID, Challenge: code.Challenge, ExchangeNonce: base64.RawURLEncoding.EncodeToString(nonce)} p.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, runnerproto.EnrolmentProofMessage(code.InstanceID, p))) return p } func approveDevice(t *testing.T, s *equipo.Store, code runnerproto.DeviceCode, person string) { t.Helper() if err := s.ApproveEnrolment(context.Background(), equipo.Actor{Address: person}, code.UserCode); err != nil { t.Fatal(err) } } func claimDevice(t *testing.T, s *equipo.Store, code runnerproto.DeviceCode, key ed25519.PrivateKey) runnerproto.RunnerCredential { t.Helper() c, err := s.ExchangeEnrolment(context.Background(), code.DeviceSecret, deviceProof(code, key)) executionMust(t, err) return c } func executionMust(t *testing.T, err error) { t.Helper() if err != nil { t.Fatal(err) } } func pageBody(t *testing.T, c *http.Client, base, path string) string { t.Helper() res := clientGet(t, c, base+path) if res.StatusCode != 200 { t.Fatalf("stage page %s: HTTP %d", path, res.StatusCode) } return readBody(t, res) } func pagePost(t *testing.T, c *http.Client, base, path, origin string, fields url.Values, want int) { t.Helper() res := clientPost(t, c, base+path, origin, fields) defer res.Body.Close() if res.StatusCode != want { t.Fatalf("stage form %s: HTTP %d", path, res.StatusCode) } }