package runner import ( "bytes" "context" "encoding/json" "errors" "io" "net/http" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runnerproto" ) type enrolTransport func(*http.Request) (*http.Response, error) func (f enrolTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } type enrolOutput struct { bytes.Buffer cancel context.CancelFunc } func (w *enrolOutput) Write(p []byte) (int, error) { n, e := w.Buffer.Write(p) w.cancel() return n, e } func TestOnboardingPairingBound(t *testing.T) { old := http.DefaultTransport t.Cleanup(func() { http.DefaultTransport = old }) for _, label := range []string{"", "Edited kitchen machine"} { c := configFixture(t) c.MachineLabel = label want := label if want == "" { var e error want, e = os.Hostname() if e != nil { t.Fatal(e) } } calls := 0 http.DefaultTransport = enrolTransport(func(r *http.Request) (*http.Response, error) { calls++ var in runnerproto.BeginEnrolmentRequest if e := json.NewDecoder(r.Body).Decode(&in); e != nil { t.Fatal(e) } if in.Label != want || in.MachinePublicKey == "" { t.Fatalf("wrong machine label/key: %+v", in) } code := runnerproto.DeviceCode{Version: 1, EnrolmentID: "fixture", InstanceID: c.InstanceID, DeviceSecret: strings.Repeat("s", 43), UserCode: "0123456789", Challenge: "challenge", VerificationURI: c.Origin + "/runners/enrol", ExpiresAt: time.Now().Add(time.Minute), PollIntervalSeconds: 5} b, _ := json.Marshal(code) return &http.Response{StatusCode: 201, Body: io.NopCloser(bytes.NewReader(b)), Header: http.Header{}}, nil }) for range 2 { ctx, cancel := context.WithCancel(context.Background()) out := &enrolOutput{cancel: cancel} e := Enrol(ctx, c, out) cancel() // One tap: the link carries the code; the code is also on its own line. if e == nil || !strings.Contains(out.String(), "\n0123456789\n") || !strings.Contains(out.String(), "("+c.Origin+"/runners/enrol?code=0123456789)") { t.Fatalf("missing code or verification address %q %v", out.String(), e) } } if calls != 1 { t.Fatalf("retry created duplicate enrolment: %d", calls) } } } func (w *enrolOutput) WriteString(s string) (int, error) { return w.Write([]byte(s)) } func TestOnboardingPairingLabelRetry(t *testing.T) { old := http.DefaultTransport t.Cleanup(func() { http.DefaultTransport = old }) for _, state := range []string{"valid", "expired", "unusable", "malformed"} { t.Run(state, func(t *testing.T) { c := configFixture(t) c.MachineLabel = "Edited machine" calls := 0 http.DefaultTransport = enrolTransport(func(r *http.Request) (*http.Response, error) { calls++ var in runnerproto.BeginEnrolmentRequest if e := json.NewDecoder(r.Body).Decode(&in); e != nil { t.Fatal(e) } want := "Edited machine" if calls > 1 { want = "New label" } if in.Label != want { t.Fatalf("label %q want %q", in.Label, want) } code := runnerproto.DeviceCode{Version: 1, EnrolmentID: "fixture", InstanceID: c.InstanceID, DeviceSecret: strings.Repeat("s", 43), UserCode: "0123456789", Challenge: "challenge", VerificationURI: c.Origin + "/runners/enrol", ExpiresAt: time.Now().Add(time.Minute), PollIntervalSeconds: 5} b, _ := json.Marshal(code) return &http.Response{StatusCode: 201, Body: io.NopCloser(bytes.NewReader(b)), Header: http.Header{}}, nil }) attempt := func() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() out := &enrolOutput{cancel: cancel} _ = Enrol(ctx, c, out) if !strings.Contains(out.String(), "0123456789") { t.Fatalf("retry blocked: %q", out.String()) } } attempt() defaultLabel, e := DefaultMachineLabel(c.StateDir, c.Origin, c.InstanceID) if e != nil || defaultLabel != "Edited machine" { t.Fatalf("saved prompt default: %q %v", defaultLabel, e) } path := filepath.Join(c.StateDir, "enrolment.json") var saved pendingEnrolment if e := privateJSON(path, &saved); e != nil { t.Fatal(e) } switch state { case "expired": saved.Code.ExpiresAt = time.Now().Add(-time.Minute) case "unusable": saved.Code.VerificationURI = "https://wrong.example/runners/enrol" } if e := runnerproto.JournalCredentials(path, saved); e != nil { t.Fatal(e) } if state == "malformed" { if e := os.WriteFile(path, []byte("{"), 0600); e != nil { t.Fatal(e) } } c.MachineLabel = "New label" attempt() wantCalls := 2 if state == "valid" { wantCalls = 1 } if calls != wantCalls { t.Fatalf("requests %d want %d", calls, wantCalls) } }) } } func TestOnboardingServiceWithoutAccounts(t *testing.T) { old := http.DefaultTransport t.Cleanup(func() { http.DefaultTransport = old }) for _, state := range []string{"missing", "empty", "invalid"} { t.Run(state, func(t *testing.T) { c := directRuntimeFixture(t) if state == "missing" { mustJournal(t, os.Remove(c.AccountBindingsPath)) } else { data := "[]" if state == "invalid" { data = "{" } mustJournal(t, os.WriteFile(c.AccountBindingsPath, []byte(data), 0600)) } ctx, cancel := context.WithCancel(context.Background()) defer cancel() heartbeats, polls, idle := 0, 0, 0 c.Report = func(key string) { if key == "runner.waiting_accounts" { idle++ } } http.DefaultTransport = enrolTransport(func(req *http.Request) (*http.Response, error) { switch { case strings.HasSuffix(req.URL.Path, "/heartbeat"): var h runnerproto.HeartbeatRequest if e := json.NewDecoder(req.Body).Decode(&h); e != nil { t.Fatal(e) } if string(h.Reports) != "[]" { t.Fatalf("invented connections: %s", h.Reports) } heartbeats++ time.AfterFunc(20*time.Millisecond, cancel) case strings.HasSuffix(req.URL.Path, "/poll"): polls++ default: t.Fatalf("unexpected request while idle: %s", req.URL.Path) } return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"version":2,"result":null}`)), Header: http.Header{}}, nil }) err := Run(ctx, c) if state == "invalid" { if err == nil || heartbeats != 0 { t.Fatal("invalid bindings treated as empty", err) } return } if !errors.Is(err, context.Canceled) || heartbeats != 1 || polls != 0 || idle < 1 { t.Fatalf("not idle until cancelled: err=%v heartbeats=%d polls=%d idle=%d", err, heartbeats, polls, idle) } }) } }