| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "net/http" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "strings" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 17 | ) |
| 18 | |
| 19 | type enrolTransport func(*http.Request) (*http.Response, error) |
| 20 | |
| 21 | func (f enrolTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| 22 | |
| 23 | type enrolOutput struct { |
| 24 | bytes.Buffer |
| 25 | cancel context.CancelFunc |
| 26 | } |
| 27 | |
| 28 | func (w *enrolOutput) Write(p []byte) (int, error) { |
| 29 | n, e := w.Buffer.Write(p) |
| 30 | w.cancel() |
| 31 | return n, e |
| 32 | } |
| 33 | func TestOnboardingPairingBound(t *testing.T) { |
| 34 | old := http.DefaultTransport |
| 35 | t.Cleanup(func() { http.DefaultTransport = old }) |
| 36 | for _, label := range []string{"", "Edited kitchen machine"} { |
| 37 | c := configFixture(t) |
| 38 | c.MachineLabel = label |
| 39 | want := label |
| 40 | if want == "" { |
| 41 | var e error |
| 42 | want, e = os.Hostname() |
| 43 | if e != nil { |
| 44 | t.Fatal(e) |
| 45 | } |
| 46 | } |
| 47 | calls := 0 |
| 48 | http.DefaultTransport = enrolTransport(func(r *http.Request) (*http.Response, error) { |
| 49 | calls++ |
| 50 | var in runnerproto.BeginEnrolmentRequest |
| 51 | if e := json.NewDecoder(r.Body).Decode(&in); e != nil { |
| 52 | t.Fatal(e) |
| 53 | } |
| 54 | if in.Label != want || in.MachinePublicKey == "" { |
| 55 | t.Fatalf("wrong machine label/key: %+v", in) |
| 56 | } |
| 57 | 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} |
| 58 | b, _ := json.Marshal(code) |
| 59 | return &http.Response{StatusCode: 201, Body: io.NopCloser(bytes.NewReader(b)), Header: http.Header{}}, nil |
| 60 | }) |
| 61 | for range 2 { |
| 62 | ctx, cancel := context.WithCancel(context.Background()) |
| 63 | out := &enrolOutput{cancel: cancel} |
| 64 | e := Enrol(ctx, c, out) |
| 65 | cancel() |
| 66 | // One tap: the link carries the code; the code is also on its own line. |
| 67 | if e == nil || !strings.Contains(out.String(), "\n0123456789\n") || !strings.Contains(out.String(), "("+c.Origin+"/runners/enrol?code=0123456789)") { |
| 68 | t.Fatalf("missing code or verification address %q %v", out.String(), e) |
| 69 | } |
| 70 | } |
| 71 | if calls != 1 { |
| 72 | t.Fatalf("retry created duplicate enrolment: %d", calls) |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | func (w *enrolOutput) WriteString(s string) (int, error) { return w.Write([]byte(s)) } |
| 77 | |
| 78 | func TestOnboardingPairingLabelRetry(t *testing.T) { |
| 79 | old := http.DefaultTransport |
| 80 | t.Cleanup(func() { http.DefaultTransport = old }) |
| 81 | for _, state := range []string{"valid", "expired", "unusable", "malformed"} { |
| 82 | t.Run(state, func(t *testing.T) { |
| 83 | c := configFixture(t) |
| 84 | c.MachineLabel = "Edited machine" |
| 85 | calls := 0 |
| 86 | http.DefaultTransport = enrolTransport(func(r *http.Request) (*http.Response, error) { |
| 87 | calls++ |
| 88 | var in runnerproto.BeginEnrolmentRequest |
| 89 | if e := json.NewDecoder(r.Body).Decode(&in); e != nil { |
| 90 | t.Fatal(e) |
| 91 | } |
| 92 | want := "Edited machine" |
| 93 | if calls > 1 { |
| 94 | want = "New label" |
| 95 | } |
| 96 | if in.Label != want { |
| 97 | t.Fatalf("label %q want %q", in.Label, want) |
| 98 | } |
| 99 | 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} |
| 100 | b, _ := json.Marshal(code) |
| 101 | return &http.Response{StatusCode: 201, Body: io.NopCloser(bytes.NewReader(b)), Header: http.Header{}}, nil |
| 102 | }) |
| 103 | attempt := func() { |
| 104 | ctx, cancel := context.WithCancel(context.Background()) |
| 105 | defer cancel() |
| 106 | out := &enrolOutput{cancel: cancel} |
| 107 | _ = Enrol(ctx, c, out) |
| 108 | if !strings.Contains(out.String(), "0123456789") { |
| 109 | t.Fatalf("retry blocked: %q", out.String()) |
| 110 | } |
| 111 | } |
| 112 | attempt() |
| 113 | defaultLabel, e := DefaultMachineLabel(c.StateDir, c.Origin, c.InstanceID) |
| 114 | if e != nil || defaultLabel != "Edited machine" { |
| 115 | t.Fatalf("saved prompt default: %q %v", defaultLabel, e) |
| 116 | } |
| 117 | path := filepath.Join(c.StateDir, "enrolment.json") |
| 118 | var saved pendingEnrolment |
| 119 | if e := privateJSON(path, &saved); e != nil { |
| 120 | t.Fatal(e) |
| 121 | } |
| 122 | switch state { |
| 123 | case "expired": |
| 124 | saved.Code.ExpiresAt = time.Now().Add(-time.Minute) |
| 125 | case "unusable": |
| 126 | saved.Code.VerificationURI = "https://wrong.example/runners/enrol" |
| 127 | } |
| 128 | if e := runnerproto.JournalCredentials(path, saved); e != nil { |
| 129 | t.Fatal(e) |
| 130 | } |
| 131 | if state == "malformed" { |
| 132 | if e := os.WriteFile(path, []byte("{"), 0600); e != nil { |
| 133 | t.Fatal(e) |
| 134 | } |
| 135 | } |
| 136 | c.MachineLabel = "New label" |
| 137 | attempt() |
| 138 | wantCalls := 2 |
| 139 | if state == "valid" { |
| 140 | wantCalls = 1 |
| 141 | } |
| 142 | if calls != wantCalls { |
| 143 | t.Fatalf("requests %d want %d", calls, wantCalls) |
| 144 | } |
| 145 | }) |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | func TestOnboardingServiceWithoutAccounts(t *testing.T) { |
| 150 | old := http.DefaultTransport |
| 151 | t.Cleanup(func() { http.DefaultTransport = old }) |
| 152 | for _, state := range []string{"missing", "empty", "invalid"} { |
| 153 | t.Run(state, func(t *testing.T) { |
| 154 | c := directRuntimeFixture(t) |
| 155 | if state == "missing" { |
| 156 | mustJournal(t, os.Remove(c.AccountBindingsPath)) |
| 157 | } else { |
| 158 | data := "[]" |
| 159 | if state == "invalid" { |
| 160 | data = "{" |
| 161 | } |
| 162 | mustJournal(t, os.WriteFile(c.AccountBindingsPath, []byte(data), 0600)) |
| 163 | } |
| 164 | ctx, cancel := context.WithCancel(context.Background()) |
| 165 | defer cancel() |
| 166 | heartbeats, polls, idle := 0, 0, 0 |
| 167 | c.Report = func(key string) { |
| 168 | if key == "runner.waiting_accounts" { |
| 169 | idle++ |
| 170 | } |
| 171 | } |
| 172 | http.DefaultTransport = enrolTransport(func(req *http.Request) (*http.Response, error) { |
| 173 | switch { |
| 174 | case strings.HasSuffix(req.URL.Path, "/heartbeat"): |
| 175 | var h runnerproto.HeartbeatRequest |
| 176 | if e := json.NewDecoder(req.Body).Decode(&h); e != nil { |
| 177 | t.Fatal(e) |
| 178 | } |
| 179 | if string(h.Reports) != "[]" { |
| 180 | t.Fatalf("invented connections: %s", h.Reports) |
| 181 | } |
| 182 | heartbeats++ |
| 183 | time.AfterFunc(20*time.Millisecond, cancel) |
| 184 | case strings.HasSuffix(req.URL.Path, "/poll"): |
| 185 | polls++ |
| 186 | default: |
| 187 | t.Fatalf("unexpected request while idle: %s", req.URL.Path) |
| 188 | } |
| 189 | return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"version":2,"result":null}`)), Header: http.Header{}}, nil |
| 190 | }) |
| 191 | err := Run(ctx, c) |
| 192 | if state == "invalid" { |
| 193 | if err == nil || heartbeats != 0 { |
| 194 | t.Fatal("invalid bindings treated as empty", err) |
| 195 | } |
| 196 | return |
| 197 | } |
| 198 | if !errors.Is(err, context.Canceled) || heartbeats != 1 || polls != 0 || idle < 1 { |
| 199 | t.Fatalf("not idle until cancelled: err=%v heartbeats=%d polls=%d idle=%d", err, heartbeats, polls, idle) |
| 200 | } |
| 201 | }) |
| 202 | } |
| 203 | } |
| 204 | |