| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "net" |
| 9 | "net/http" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/wire" |
| 18 | ) |
| 19 | |
| 20 | // enrolScript is a fake instance whose answers to each route are given in |
| 21 | // order (the last repeats): a status, or 0 to drop the connection |
| 22 | // unanswered. The code it hands out expires after expires. |
| 23 | type enrolScript struct { |
| 24 | mu sync.Mutex |
| 25 | protocol, begin, token []int |
| 26 | expires time.Duration |
| 27 | asked []string |
| 28 | } |
| 29 | |
| 30 | func (s *enrolScript) next(path string, answers *[]int) int { |
| 31 | s.mu.Lock() |
| 32 | defer s.mu.Unlock() |
| 33 | s.asked = append(s.asked, path) |
| 34 | a := (*answers)[0] |
| 35 | if len(*answers) > 1 { |
| 36 | *answers = (*answers)[1:] |
| 37 | } |
| 38 | return a |
| 39 | } |
| 40 | |
| 41 | func (s *enrolScript) run(t *testing.T, worker bool) ([]EnrolNotice, string, error) { |
| 42 | t.Helper() |
| 43 | old := enrolPollUnit |
| 44 | enrolPollUnit = 5 * time.Millisecond |
| 45 | t.Cleanup(func() { enrolPollUnit = old }) |
| 46 | l, err := net.Listen("tcp", "127.0.0.1:0") |
| 47 | if err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 51 | var status int |
| 52 | switch r.URL.Path { |
| 53 | case wire.RunnerProtocolPath: |
| 54 | status = s.next(r.URL.Path, &s.protocol) |
| 55 | case "/api/enrolments": |
| 56 | status = s.next(r.URL.Path, &s.begin) |
| 57 | case "/api/enrolments/token": |
| 58 | status = s.next(r.URL.Path, &s.token) |
| 59 | default: |
| 60 | status = 404 |
| 61 | } |
| 62 | switch status { |
| 63 | case 0: |
| 64 | conn, _, _ := w.(http.Hijacker).Hijack() |
| 65 | conn.Close() |
| 66 | case 200, 201: |
| 67 | switch r.URL.Path { |
| 68 | case wire.RunnerProtocolPath: |
| 69 | _, _ = w.Write([]byte(`{"protocol":2}`)) |
| 70 | case "/api/enrolments": |
| 71 | _, _ = fmt.Fprintf(w, `{"version":1,"enrolment_id":"e1","instance_id":"inst","device_secret":"s3cret-device","user_code":"ABCDEFGHJK","challenge":"c","verification_uri":"http://%s/runners/enrol","expires_at":%q,"poll_interval_seconds":5}`, r.Host, time.Now().Add(s.expires).UTC().Format(time.RFC3339Nano)) |
| 72 | default: |
| 73 | _, _ = fmt.Fprintf(w, `{"version":1,"token":"t0ken","token_type":"Bearer","runner_id":"R2","credential_id":"C2","person":"p@x","expires_at":%q,"role":"worker"}`, time.Now().Add(time.Hour).UTC().Format(time.RFC3339)) |
| 74 | } |
| 75 | default: |
| 76 | key := map[int]string{409: "runner.pending", 403: "form.forbidden", 503: "service.unavailable", 429: "runner.rate-limited"}[status] |
| 77 | w.WriteHeader(status) |
| 78 | _, _ = fmt.Fprintf(w, `{"version":2,"error":%q}`, key) |
| 79 | } |
| 80 | })} |
| 81 | go srv.Serve(l) |
| 82 | t.Cleanup(func() { srv.Close() }) |
| 83 | var mu sync.Mutex |
| 84 | var notices []EnrolNotice |
| 85 | state := filepath.Join(t.TempDir(), "state") |
| 86 | c := Config{Origin: "http://" + l.Addr().String(), InstanceID: "inst", StateDir: state, MachineLabel: "Tito Studio", WorkerOnly: worker, EnrolNotify: func(n EnrolNotice) { |
| 87 | mu.Lock() |
| 88 | defer mu.Unlock() |
| 89 | notices = append(notices, n) |
| 90 | }} |
| 91 | err = Enrol(context.Background(), c, io.Discard) |
| 92 | mu.Lock() |
| 93 | defer mu.Unlock() |
| 94 | return notices, state, err |
| 95 | } |
| 96 | |
| 97 | func retries(notices []EnrolNotice) []string { |
| 98 | var out []string |
| 99 | for _, n := range notices { |
| 100 | if n.Retry != nil { |
| 101 | out = append(out, EnrolDetail(n.Retry)) |
| 102 | } |
| 103 | } |
| 104 | return out |
| 105 | } |
| 106 | |
| 107 | // Paul's Studio, 2026-11-10: one server error while waiting ended the |
| 108 | // install. Server errors, dropped connections and "too soon" are waited |
| 109 | // out, backing off, and each is reported in words; the wait itself is |
| 110 | // announced once. |
| 111 | func TestEnrolWaitsOutTransientFailures(t *testing.T) { |
| 112 | s := &enrolScript{protocol: []int{503, 200}, begin: []int{0, 201}, token: []int{409, 503, 0, 429, 409, 200}, expires: time.Minute} |
| 113 | notices, state, err := s.run(t, true) |
| 114 | if err != nil { |
| 115 | t.Fatalf("enrol: %v (%s)", err, EnrolDetail(err)) |
| 116 | } |
| 117 | if ReadRole(state) != wire.RoleWorker { |
| 118 | t.Fatal("not enrolled") |
| 119 | } |
| 120 | got := retries(notices) |
| 121 | if len(got) != 5 || got[0] != "Equipo answered HTTP 503" || !strings.HasPrefix(got[1], "no answer from Equipo: ") || got[2] != "Equipo answered HTTP 503 (service.unavailable)" || !strings.HasPrefix(got[3], "no answer from Equipo: ") || got[4] != "Equipo answered HTTP 429 (runner.rate-limited)" { |
| 122 | t.Fatalf("retries %q", got) |
| 123 | } |
| 124 | waiting := 0 |
| 125 | for _, n := range notices { |
| 126 | if n.Waiting { |
| 127 | waiting++ |
| 128 | } |
| 129 | } |
| 130 | // The link notice comes once, directly before the link and the wait. |
| 131 | if waiting != 1 || !notices[2].Link || !notices[3].Waiting { |
| 132 | t.Fatalf("waiting announced %d times: %+v", waiting, notices) |
| 133 | } |
| 134 | for _, d := range got { |
| 135 | if strings.Contains(d, "s3cret") || strings.Contains(d, "t0ken") { |
| 136 | t.Fatalf("a secret in %q", d) |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | // Expired and turned down each end the wait with their own error, and the |
| 142 | // saved code is dropped so the next run asks for a new one. A failure |
| 143 | // still happening when the code runs out is reported as that failure. |
| 144 | func TestEnrolEndsInWords(t *testing.T) { |
| 145 | for name, c := range map[string]struct { |
| 146 | s *enrolScript |
| 147 | want error |
| 148 | code string |
| 149 | }{ |
| 150 | "turned down": {&enrolScript{begin: []int{201}, token: []int{409, 403}, expires: 10 * time.Minute}, ErrEnrolmentRefused, "runner.enrolment_refused"}, |
| 151 | "expired by its clock": {&enrolScript{begin: []int{201}, token: []int{409, 403}, expires: 30 * time.Second}, ErrEnrolmentExpired, "runner.enrolment_expired"}, |
| 152 | "ran out": {&enrolScript{begin: []int{201}, token: []int{409}, expires: 300 * time.Millisecond}, ErrEnrolmentExpired, "runner.enrolment_expired"}, |
| 153 | } { |
| 154 | t.Run(name, func(t *testing.T) { |
| 155 | _, state, err := c.s.run(t, false) |
| 156 | if code, _ := Diagnostic(err); !errors.Is(err, c.want) || code != c.code { |
| 157 | t.Fatalf("%v %q", err, code) |
| 158 | } |
| 159 | if _, err := os.Stat(filepath.Join(state, "enrolment.json")); !os.IsNotExist(err) { |
| 160 | t.Fatal("the used code was kept") |
| 161 | } |
| 162 | }) |
| 163 | } |
| 164 | s := &enrolScript{begin: []int{201}, token: []int{503}, expires: 300 * time.Millisecond} |
| 165 | _, _, err := s.run(t, false) |
| 166 | if errors.Is(err, ErrEnrolmentExpired) || EnrolDetail(err) != "Equipo answered HTTP 503 (service.unavailable)" { |
| 167 | t.Fatalf("a failing instance reported as %v (%s)", err, EnrolDetail(err)) |
| 168 | } |
| 169 | } |
| 170 | |