| 1 | //go:build e2elive |
| 2 | |
| 3 | package e2elivetest |
| 4 | |
| 5 | import ( |
| 6 | "amadan.net/oficina/equipo/internal/equipo" |
| 7 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 8 | "amadan.net/rastrillo/rastrillo/pow" |
| 9 | "context" |
| 10 | "crypto/ed25519" |
| 11 | "crypto/rand" |
| 12 | "encoding/base64" |
| 13 | "html" |
| 14 | "io" |
| 15 | "net/http" |
| 16 | "net/http/cookiejar" |
| 17 | "net/url" |
| 18 | "regexp" |
| 19 | "strings" |
| 20 | "sync" |
| 21 | "testing" |
| 22 | "time" |
| 23 | ) |
| 24 | |
| 25 | type capturingMailer struct { |
| 26 | mu sync.Mutex |
| 27 | bodies []string |
| 28 | } |
| 29 | |
| 30 | func (m *capturingMailer) link(t *testing.T) string { |
| 31 | t.Helper() |
| 32 | m.mu.Lock() |
| 33 | defer m.mu.Unlock() |
| 34 | if len(m.bodies) == 0 { |
| 35 | t.Fatal("no email") |
| 36 | } |
| 37 | for _, word := range strings.Fields(m.bodies[len(m.bodies)-1]) { |
| 38 | if strings.Contains(word, "/auth/verify?") { |
| 39 | return word |
| 40 | } |
| 41 | } |
| 42 | t.Fatal("no link in email") |
| 43 | return "" |
| 44 | } |
| 45 | |
| 46 | func mustURL(t *testing.T, s string) *url.URL { |
| 47 | t.Helper() |
| 48 | u, err := url.Parse(s) |
| 49 | if err != nil { |
| 50 | t.Fatal(err) |
| 51 | } |
| 52 | return u |
| 53 | } |
| 54 | |
| 55 | func signinClient(t *testing.T, base string) *http.Client { |
| 56 | t.Helper() |
| 57 | jar, err := cookiejar.New(nil) |
| 58 | if err != nil { |
| 59 | t.Fatal(err) |
| 60 | } |
| 61 | return &http.Client{Jar: jar, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| 62 | } |
| 63 | |
| 64 | func clientGet(t *testing.T, c *http.Client, target string) *http.Response { |
| 65 | t.Helper() |
| 66 | res, err := c.Get(target) |
| 67 | if err != nil { |
| 68 | t.Fatal(err) |
| 69 | } |
| 70 | return res |
| 71 | } |
| 72 | |
| 73 | func clientPost(t *testing.T, c *http.Client, target, origin string, form url.Values) *http.Response { |
| 74 | t.Helper() |
| 75 | req, err := http.NewRequest(http.MethodPost, target, strings.NewReader(form.Encode())) |
| 76 | if err != nil { |
| 77 | t.Fatal(err) |
| 78 | } |
| 79 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 80 | if origin != "" { |
| 81 | req.Header.Set("Origin", origin) |
| 82 | } |
| 83 | res, err := c.Do(req) |
| 84 | if err != nil { |
| 85 | t.Fatal(err) |
| 86 | } |
| 87 | return res |
| 88 | } |
| 89 | |
| 90 | func readBody(t *testing.T, res *http.Response) string { |
| 91 | t.Helper() |
| 92 | defer res.Body.Close() |
| 93 | b, err := io.ReadAll(res.Body) |
| 94 | if err != nil { |
| 95 | t.Fatal(err) |
| 96 | } |
| 97 | return string(b) |
| 98 | } |
| 99 | |
| 100 | func formFields(t *testing.T, body, action string) url.Values { |
| 101 | t.Helper() |
| 102 | values := url.Values{} |
| 103 | found := false |
| 104 | for _, form := range regexp.MustCompile(`(?s)<form\b[^>]*>.*?</form>`).FindAllString(body, -1) { |
| 105 | if !strings.Contains(form, `action="`+action+`"`) { |
| 106 | continue |
| 107 | } |
| 108 | found = true |
| 109 | for _, input := range regexp.MustCompile(`<input\b[^>]*>`).FindAllString(form, -1) { |
| 110 | attrs := map[string]string{} |
| 111 | for _, pair := range regexp.MustCompile(`([a-z_-]+)="([^"]*)"`).FindAllStringSubmatch(input, -1) { |
| 112 | attrs[pair[1]] = html.UnescapeString(pair[2]) |
| 113 | } |
| 114 | if attrs["name"] != "" { |
| 115 | values.Set(attrs["name"], attrs["value"]) |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | if !found { |
| 120 | t.Fatalf("missing form %s", action) |
| 121 | } |
| 122 | return values |
| 123 | } |
| 124 | |
| 125 | type emailChallenge struct { |
| 126 | values url.Values |
| 127 | ready time.Time |
| 128 | } |
| 129 | |
| 130 | func prepareEmail(t *testing.T, c *http.Client, base, address string) emailChallenge { |
| 131 | t.Helper() |
| 132 | res := clientGet(t, c, base+"/signin?force=1") |
| 133 | if res.StatusCode != 200 { |
| 134 | t.Fatalf("signin page: %d", res.StatusCode) |
| 135 | } |
| 136 | values := formFields(t, readBody(t, res), "/auth/begin") |
| 137 | values.Set("address", address) |
| 138 | if values.Get("force") != "1" { |
| 139 | t.Fatal("email fallback not rendered") |
| 140 | } |
| 141 | return emailChallenge{values: values, ready: time.Now().Add(pow.DefaultMinAge + 50*time.Millisecond)} |
| 142 | } |
| 143 | |
| 144 | func submitEmail(t *testing.T, c *http.Client, base, origin string, challenge emailChallenge) { |
| 145 | t.Helper() |
| 146 | time.Sleep(time.Until(challenge.ready)) |
| 147 | res := clientPost(t, c, base+"/auth/begin", origin, challenge.values) |
| 148 | defer res.Body.Close() |
| 149 | if res.StatusCode != 303 || !strings.Contains(res.Header.Get("Location"), "sent=1") { |
| 150 | t.Fatalf("begin: %d %s", res.StatusCode, res.Header.Get("Location")) |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | func beginEmail(t *testing.T, c *http.Client, base, origin, address string) { |
| 155 | t.Helper() |
| 156 | submitEmail(t, c, base, origin, prepareEmail(t, c, base, address)) |
| 157 | } |
| 158 | |
| 159 | func confirmEmail(t *testing.T, c *http.Client, base, origin string, m *capturingMailer) *http.Response { |
| 160 | t.Helper() |
| 161 | link := mustURL(t, m.link(t)) |
| 162 | local := mustURL(t, base).ResolveReference(&url.URL{Path: link.Path, RawQuery: link.RawQuery}) |
| 163 | res := clientGet(t, c, local.String()) |
| 164 | if res.StatusCode != 200 { |
| 165 | t.Fatalf("confirm: %d", res.StatusCode) |
| 166 | } |
| 167 | values := formFields(t, readBody(t, res), "/auth/verify") |
| 168 | return clientPost(t, c, base+"/auth/verify", origin, values) |
| 169 | } |
| 170 | |
| 171 | // signinEmail is shared by HTTP, browser setup and performance callers. |
| 172 | // The client keeps real cookies; every credential comes from the rendered flow. |
| 173 | |
| 174 | func machine(t *testing.T) (string, ed25519.PrivateKey) { |
| 175 | t.Helper() |
| 176 | pub, key, err := ed25519.GenerateKey(rand.Reader) |
| 177 | executionMust(t, err) |
| 178 | return base64.RawURLEncoding.EncodeToString(pub), key |
| 179 | } |
| 180 | |
| 181 | func beginDevice(t *testing.T, s *equipo.Store) (runnerproto.DeviceCode, ed25519.PrivateKey) { |
| 182 | t.Helper() |
| 183 | pub, key := machine(t) |
| 184 | code, err := s.BeginEnrolment(context.Background(), pub, "Desk machine") |
| 185 | executionMust(t, err) |
| 186 | return code, key |
| 187 | } |
| 188 | |
| 189 | func deviceProof(code runnerproto.DeviceCode, key ed25519.PrivateKey) runnerproto.ExchangeProof { |
| 190 | nonce := make([]byte, 32) |
| 191 | rand.Read(nonce) |
| 192 | p := runnerproto.ExchangeProof{EnrolmentID: code.EnrolmentID, Challenge: code.Challenge, ExchangeNonce: base64.RawURLEncoding.EncodeToString(nonce)} |
| 193 | p.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, runnerproto.EnrolmentProofMessage(code.InstanceID, p))) |
| 194 | return p |
| 195 | } |
| 196 | |
| 197 | func approveDevice(t *testing.T, s *equipo.Store, code runnerproto.DeviceCode, person string) { |
| 198 | t.Helper() |
| 199 | if err := s.ApproveEnrolment(context.Background(), equipo.Actor{Address: person}, code.UserCode); err != nil { |
| 200 | t.Fatal(err) |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | func claimDevice(t *testing.T, s *equipo.Store, code runnerproto.DeviceCode, key ed25519.PrivateKey) runnerproto.RunnerCredential { |
| 205 | t.Helper() |
| 206 | c, err := s.ExchangeEnrolment(context.Background(), code.DeviceSecret, deviceProof(code, key)) |
| 207 | executionMust(t, err) |
| 208 | return c |
| 209 | } |
| 210 | func executionMust(t *testing.T, err error) { |
| 211 | t.Helper() |
| 212 | if err != nil { |
| 213 | t.Fatal(err) |
| 214 | } |
| 215 | } |
| 216 | func pageBody(t *testing.T, c *http.Client, base, path string) string { |
| 217 | t.Helper() |
| 218 | res := clientGet(t, c, base+path) |
| 219 | if res.StatusCode != 200 { |
| 220 | t.Fatalf("stage page %s: HTTP %d", path, res.StatusCode) |
| 221 | } |
| 222 | return readBody(t, res) |
| 223 | } |
| 224 | func pagePost(t *testing.T, c *http.Client, base, path, origin string, fields url.Values, want int) { |
| 225 | t.Helper() |
| 226 | res := clientPost(t, c, base+path, origin, fields) |
| 227 | defer res.Body.Close() |
| 228 | if res.StatusCode != want { |
| 229 | t.Fatalf("stage form %s: HTTP %d", path, res.StatusCode) |
| 230 | } |
| 231 | } |
| 232 | |