package runner import ( "context" "errors" "fmt" "io" "net" "net/http" "os" "path/filepath" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) // enrolScript is a fake instance whose answers to each route are given in // order (the last repeats): a status, or 0 to drop the connection // unanswered. The code it hands out expires after expires. type enrolScript struct { mu sync.Mutex protocol, begin, token []int expires time.Duration asked []string } func (s *enrolScript) next(path string, answers *[]int) int { s.mu.Lock() defer s.mu.Unlock() s.asked = append(s.asked, path) a := (*answers)[0] if len(*answers) > 1 { *answers = (*answers)[1:] } return a } func (s *enrolScript) run(t *testing.T, worker bool) ([]EnrolNotice, string, error) { t.Helper() old := enrolPollUnit enrolPollUnit = 5 * time.Millisecond t.Cleanup(func() { enrolPollUnit = old }) l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var status int switch r.URL.Path { case wire.RunnerProtocolPath: status = s.next(r.URL.Path, &s.protocol) case "/api/enrolments": status = s.next(r.URL.Path, &s.begin) case "/api/enrolments/token": status = s.next(r.URL.Path, &s.token) default: status = 404 } switch status { case 0: conn, _, _ := w.(http.Hijacker).Hijack() conn.Close() case 200, 201: switch r.URL.Path { case wire.RunnerProtocolPath: _, _ = w.Write([]byte(`{"protocol":2}`)) case "/api/enrolments": _, _ = 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)) default: _, _ = 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)) } default: key := map[int]string{409: "runner.pending", 403: "form.forbidden", 503: "service.unavailable", 429: "runner.rate-limited"}[status] w.WriteHeader(status) _, _ = fmt.Fprintf(w, `{"version":2,"error":%q}`, key) } })} go srv.Serve(l) t.Cleanup(func() { srv.Close() }) var mu sync.Mutex var notices []EnrolNotice state := filepath.Join(t.TempDir(), "state") c := Config{Origin: "http://" + l.Addr().String(), InstanceID: "inst", StateDir: state, MachineLabel: "Tito Studio", WorkerOnly: worker, EnrolNotify: func(n EnrolNotice) { mu.Lock() defer mu.Unlock() notices = append(notices, n) }} err = Enrol(context.Background(), c, io.Discard) mu.Lock() defer mu.Unlock() return notices, state, err } func retries(notices []EnrolNotice) []string { var out []string for _, n := range notices { if n.Retry != nil { out = append(out, EnrolDetail(n.Retry)) } } return out } // Paul's Studio, 2026-11-10: one server error while waiting ended the // install. Server errors, dropped connections and "too soon" are waited // out, backing off, and each is reported in words; the wait itself is // announced once. func TestEnrolWaitsOutTransientFailures(t *testing.T) { s := &enrolScript{protocol: []int{503, 200}, begin: []int{0, 201}, token: []int{409, 503, 0, 429, 409, 200}, expires: time.Minute} notices, state, err := s.run(t, true) if err != nil { t.Fatalf("enrol: %v (%s)", err, EnrolDetail(err)) } if ReadRole(state) != wire.RoleWorker { t.Fatal("not enrolled") } got := retries(notices) 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)" { t.Fatalf("retries %q", got) } waiting := 0 for _, n := range notices { if n.Waiting { waiting++ } } // The link notice comes once, directly before the link and the wait. if waiting != 1 || !notices[2].Link || !notices[3].Waiting { t.Fatalf("waiting announced %d times: %+v", waiting, notices) } for _, d := range got { if strings.Contains(d, "s3cret") || strings.Contains(d, "t0ken") { t.Fatalf("a secret in %q", d) } } } // Expired and turned down each end the wait with their own error, and the // saved code is dropped so the next run asks for a new one. A failure // still happening when the code runs out is reported as that failure. func TestEnrolEndsInWords(t *testing.T) { for name, c := range map[string]struct { s *enrolScript want error code string }{ "turned down": {&enrolScript{begin: []int{201}, token: []int{409, 403}, expires: 10 * time.Minute}, ErrEnrolmentRefused, "runner.enrolment_refused"}, "expired by its clock": {&enrolScript{begin: []int{201}, token: []int{409, 403}, expires: 30 * time.Second}, ErrEnrolmentExpired, "runner.enrolment_expired"}, "ran out": {&enrolScript{begin: []int{201}, token: []int{409}, expires: 300 * time.Millisecond}, ErrEnrolmentExpired, "runner.enrolment_expired"}, } { t.Run(name, func(t *testing.T) { _, state, err := c.s.run(t, false) if code, _ := Diagnostic(err); !errors.Is(err, c.want) || code != c.code { t.Fatalf("%v %q", err, code) } if _, err := os.Stat(filepath.Join(state, "enrolment.json")); !os.IsNotExist(err) { t.Fatal("the used code was kept") } }) } s := &enrolScript{begin: []int{201}, token: []int{503}, expires: 300 * time.Millisecond} _, _, err := s.run(t, false) if errors.Is(err, ErrEnrolmentExpired) || EnrolDetail(err) != "Equipo answered HTTP 503 (service.unavailable)" { t.Fatalf("a failing instance reported as %v (%s)", err, EnrolDetail(err)) } }