oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "log/slog"
9 "net/http"
10 "net/http/httptest"
11 "os"
12 "path/filepath"
13 "strings"
14 "sync"
15 "testing"
16 "time"
17
18 "amadan.net/oficina/equipo/internal/runner/forge"
19 "amadan.net/oficina/equipo/internal/runner/workspace"
20 "amadan.net/oficina/equipo/internal/wire"
21)
22
23// mergeCredRig is a runner forge whose credential file has per-repository
24// entries only (no agent-wide api), as on the runner of tkbstr6cjl7h, and
25// whose state lists created as a repository it made. The hub answers the
26// repository list per bearer (lists), or with listStatus when set, and
27// records every merge request's path and bearer.
28type mergeCredRig struct {
29 f *fileForge
30 path string
31 mu sync.Mutex
32 merges []string
33 lists map[string][]string
34 listStatus int
35 // etag, when set, is a validator that ignores the caller (a cache
36 // keyed by URL): a request carrying it is answered 304.
37 etag string
38}
39
40func newMergeCredRig(t *testing.T, file string, created, listed []string) *mergeCredRig {
41 t.Helper()
42 rig := &mergeCredRig{lists: map[string][]string{"api-first": listed}}
43 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
44 rig.mu.Lock()
45 defer rig.mu.Unlock()
46 if r.Method == http.MethodGet && r.URL.Path == "/api/v1/repos" {
47 if rig.listStatus != 0 {
48 w.WriteHeader(rig.listStatus)
49 return
50 }
51 if rig.etag != "" {
52 if r.Header.Get("If-None-Match") == rig.etag {
53 w.WriteHeader(http.StatusNotModified)
54 return
55 }
56 w.Header().Set("ETag", rig.etag)
57 }
58 var parts []string
59 for _, repo := range rig.lists[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")] {
60 p := strings.Split(strings.TrimPrefix(repo, "amadan.net/"), "/")
61 parts = append(parts, fmt.Sprintf(`{"ns":%q,"name":%q}`, p[0], p[1]))
62 }
63 fmt.Fprintf(w, `{"repos":[%s]}`, strings.Join(parts, ","))
64 return
65 }
66 if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/merge") {
67 rig.merges = append(rig.merges, r.URL.EscapedPath()+" "+r.Header.Get("Authorization"))
68 fmt.Fprintf(w, `{"merged":true,"sha":%q,"into":"main","branch_closed":true}`, strings.Repeat("8", 40))
69 return
70 }
71 w.WriteHeader(http.StatusNotFound)
72 }))
73 t.Cleanup(srv.Close)
74 dir := t.TempDir()
75 rig.path = filepath.Join(dir, "amadan.json")
76 if file != "" {
77 if err := os.WriteFile(rig.path, []byte(file), 0600); err != nil {
78 t.Fatal(err)
79 }
80 }
81 rig.f = NewFileForge(rig.path, dir, true).(*fileForge)
82 rig.f.hub, rig.f.client = srv.URL, srv.Client()
83 for _, repo := range created {
84 if err := rig.f.record(repo); err != nil {
85 t.Fatal(err)
86 }
87 }
88 return rig
89}
90
91func (rig *mergeCredRig) requests() []string {
92 rig.mu.Lock()
93 defer rig.mu.Unlock()
94 return append([]string(nil), rig.merges...)
95}
96
97func (rig *mergeCredRig) set(fn func()) {
98 rig.mu.Lock()
99 defer rig.mu.Unlock()
100 fn()
101}
102
103const perRepoOnly = `{"agent":"equipo~owner@example.com","repositories":{"amadan.net/paulca/first":{"api":"api-first","git":"git-first"},"amadan.net/paulca/stale":{"git":"git-stale"}}}`
104
105var mergeReq = forge.MergeRequest{ExpectSHA: strings.Repeat("a", 40), Strategy: "merge", Agent: forge.AgentMeta{Session: "equipo-tk1", Harness: "equipo", Host: "test"}}
106
107// TestMergeCredentialFallsBackForCreatedRepos: a repository the runner
108// created, absent from the credential file and listed by the hub for the
109// agent's bearer, merges with the agent-wide credential, the one push and
110// Create use for it.
111func TestMergeCredentialFallsBackForCreatedRepos(t *testing.T) {
112 rig := newMergeCredRig(t, perRepoOnly, []string{"amadan.net/paulca/nearys"}, []string{"amadan.net/paulca/nearys"})
113 res, err := rig.f.Merge(context.Background(), "amadan.net/paulca/nearys", "equipo/tk1-x", mergeReq)
114 if err != nil || !res.Merged {
115 t.Fatalf("created repository: %+v %v", res, err)
116 }
117 if got := rig.requests(); len(got) != 1 || got[0] != "/api/v1/repos/paulca/nearys/branches/equipo%2Ftk1-x/merge Bearer api-first" {
118 t.Fatalf("merge requests %q", got)
119 }
120 // The hub's CI is read with the same credential.
121 if c, err := rig.f.ciCredential(context.Background(), "amadan.net/paulca/nearys"); err != nil || c.Bearer != "api-first" || c.Remote != "https://amadan.net/paulca/nearys" {
122 t.Fatalf("CI credential %+v %v", c.Remote, err)
123 }
124 // A repository the hub lists as writable by the agent is in scope too.
125 rig = newMergeCredRig(t, perRepoOnly, nil, []string{"amadan.net/paulca/listed"})
126 if _, err := rig.f.Merge(context.Background(), "amadan.net/paulca/listed", "equipo/tk1-x", mergeReq); err != nil || len(rig.requests()) != 1 {
127 t.Fatalf("listed repository: %v %q", err, rig.requests())
128 }
129}
130
131// TestMergeCredentialStaysInScope: a repository that is neither in the
132// credential file, nor created here, nor listed by the hub is refused by
133// policy before any request; one whose own entry is unusable never falls
134// back to the agent-wide credential. Both refusals are definite and name
135// the repository, never a credential.
136func TestMergeCredentialStaysInScope(t *testing.T) {
137 rig := newMergeCredRig(t, perRepoOnly, []string{"amadan.net/paulca/nearys"}, []string{"amadan.net/paulca/listed"})
138 for repo, want := range map[string]error{"amadan.net/paulca/unrelated": forge.ErrMergeRefused, "amadan.net/paulca/stale": forge.ErrMergeNoCredential} {
139 _, err := rig.f.Merge(context.Background(), repo, "equipo/tk1-x", mergeReq)
140 var ns *forge.NotSentError
141 if !errors.Is(err, want) || !errors.As(err, &ns) || errors.Is(err, forge.ErrMergeUncertain) {
142 t.Fatalf("%s: %v", repo, err)
143 }
144 if !strings.Contains(err.Error(), repo) || strings.Contains(err.Error(), "api-") || strings.Contains(err.Error(), "git-") {
145 t.Fatalf("%s: refusal words %q", repo, err)
146 }
147 if _, err := rig.f.ciCredential(context.Background(), repo); err == nil {
148 t.Fatalf("%s: CI credential out of scope", repo)
149 }
150 }
151 if got := rig.requests(); len(got) != 0 {
152 t.Fatalf("out-of-scope merge reached the hub: %q", got)
153 }
154 // No agent-wide credential at all: a created repository is refused too.
155 rig = newMergeCredRig(t, `{"agent":"equipo~owner@example.com","repositories":{}}`, []string{"amadan.net/paulca/nearys"}, nil)
156 if _, err := rig.f.Merge(context.Background(), "amadan.net/paulca/nearys", "equipo/tk1-x", mergeReq); !errors.Is(err, forge.ErrMergeNoCredential) || len(rig.requests()) != 0 {
157 t.Fatalf("no agent credential: %v", err)
158 }
159}
160
161// TestMergeStepLocalRefusal: a merge refused on the runner before the hub
162// was contacted ends the step at once (one attempt, no retries) with its
163// own reason, and the log tail names the repository, not "outcome
164// unknown"; the forge record is back at prepared.
165func TestMergeStepLocalRefusal(t *testing.T) {
166 old := mergeBackoff
167 mergeBackoff = time.Millisecond
168 t.Cleanup(func() { mergeBackoff = old })
169 e, f, r, _ := hubRig(t)
170 f.answer = func(int, func() (forge.MergeResult, error)) (forge.MergeResult, error) {
171 return forge.MergeResult{}, forge.NotSent(r.Repo, forge.ErrMergeNoCredential)
172 }
173 rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
174 if rep.State != wire.StepFailed || rep.Reason != "merge_credential" || !rep.Termination || f.requests != 1 {
175 t.Fatalf("report %+v (%d requests)", rep, f.requests)
176 }
177 if !strings.Contains(rep.LogTail, r.Repo) || strings.Contains(rep.LogTail, "outcome unknown") {
178 t.Fatalf("log tail %q", rep.LogTail)
179 }
180 paths, _ := filepath.Glob(filepath.Join(e.root(), "merge", "merge-*.json"))
181 if len(paths) != 1 {
182 t.Fatalf("merge records %v", paths)
183 }
184 if raw, err := os.ReadFile(paths[0]); err != nil || !strings.Contains(string(raw), `"phase":"prepared"`) {
185 t.Fatalf("record %s %v", raw, err)
186 }
187 // A later Merge tap asks the hub again and lands it.
188 f.answer = nil
189 if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != wire.StepDone || f.requests != 2 {
190 t.Fatalf("again %+v (%d requests)", rep, f.requests)
191 }
192}
193
194// TestCheckCreatedCredentials: at start, with repository creation on,
195// every repository the runner created is checked for a usable credential
196// by the merge lookup; each missing one gets one fixed warning naming it,
197// and no credential is logged.
198func TestCheckCreatedCredentials(t *testing.T) {
199 var buf bytes.Buffer
200 log := slog.New(slog.NewTextHandler(&buf, nil))
201 rig := newMergeCredRig(t, perRepoOnly, []string{"amadan.net/paulca/nearys"}, nil)
202 rig.f.checkCreated(context.Background(), log)
203 if strings.Contains(buf.String(), createdNoCredential) {
204 t.Fatalf("warned with a usable credential: %s", buf.String())
205 }
206 rig = newMergeCredRig(t, `{"agent":"equipo~owner@example.com","repositories":{}}`, []string{"amadan.net/paulca/nearys", "amadan.net/paulca/other"}, nil)
207 rig.f.checkCreated(context.Background(), log)
208 out := buf.String()
209 if strings.Count(out, createdNoCredential) != 2 || !strings.Contains(out, "amadan.net/paulca/nearys") || !strings.Contains(out, "amadan.net/paulca/other") || !strings.Contains(out, "level=WARN") {
210 t.Fatalf("warnings %s", out)
211 }
212 if len(rig.requests()) != 0 {
213 t.Fatal("the check contacted the hub")
214 }
215 // Creation off: nothing is checked.
216 buf.Reset()
217 rig.f.enabled = false
218 rig.f.checkCreated(context.Background(), log)
219 if buf.Len() != 0 {
220 t.Fatalf("checked with creation off: %s", buf.String())
221 }
222}
223
224// TestMergeFallbackNeedsCurrentWriteScope: the agent-wide fallback writes
225// only to a repository the hub lists now, for the credential in the file
226// now. A grant revoked (no longer listed), a list the hub fails to give,
227// a replaced credential and a repository renamed after the runner created
228// it all refuse the merge and the push before any merge request.
229func TestMergeFallbackNeedsCurrentWriteScope(t *testing.T) {
230 ctx := context.Background()
231 repo := "amadan.net/paulca/nearys"
232 blocked := func(t *testing.T, rig *mergeCredRig, what string, want error) {
233 t.Helper()
234 before := len(rig.requests())
235 _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq)
236 var ns *forge.NotSentError
237 if !errors.Is(err, want) || !errors.As(err, &ns) || len(rig.requests()) != before {
238 t.Fatalf("%s: merge %v (%d requests)", what, err, len(rig.requests())-before)
239 }
240 if _, err := rig.f.Remote(ctx, repo, Push); err == nil {
241 t.Fatalf("%s: push credential", what)
242 }
243 }
244 refused := func(t *testing.T, rig *mergeCredRig, what string) {
245 t.Helper()
246 blocked(t, rig, what, forge.ErrMergeRefused)
247 }
248 t.Run("revoked", func(t *testing.T) {
249 rig := newMergeCredRig(t, perRepoOnly, []string{repo}, []string{repo})
250 if _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq); err != nil {
251 t.Fatal(err)
252 }
253 rig.set(func() { rig.lists["api-first"] = nil })
254 refused(t, rig, "grant revoked")
255 })
256 t.Run("list fails", func(t *testing.T) {
257 rig := newMergeCredRig(t, perRepoOnly, []string{repo}, []string{repo})
258 if _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq); err != nil {
259 t.Fatal(err)
260 }
261 // The cached list expires; the refresh fails: the cache no longer
262 // authorises a fallback write.
263 rig.f.mu.Lock()
264 rig.f.nsAt = time.Now().Add(-2 * reachEvery)
265 rig.f.mu.Unlock()
266 // A 500 is not a denial: write access is unconfirmed (it recovers,
267 // see TestWriteScopeUnavailableRecovers), and nothing is sent. A 401
268 // is the hub refusing the credential: a denial.
269 for status, want := range map[int]error{http.StatusInternalServerError: workspace.ErrHubUnavailable, http.StatusUnauthorized: forge.ErrMergeRefused} {
270 rig.set(func() { rig.listStatus = status })
271 blocked(t, rig, fmt.Sprint("list ", status), want)
272 }
273 })
274 t.Run("credential replaced", func(t *testing.T) {
275 rig := newMergeCredRig(t, perRepoOnly, []string{repo}, []string{repo})
276 if _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq); err != nil {
277 t.Fatal(err)
278 }
279 // Within the minute the list is cached, another agent's credential
280 // replaces the file; the hub lists nothing for it.
281 replaced := `{"agent":"other~owner@example.com","repositories":{"amadan.net/paulca/first":{"api":"api-other","git":"git-other"}}}`
282 if err := os.WriteFile(rig.path, []byte(replaced), 0600); err != nil {
283 t.Fatal(err)
284 }
285 refused(t, rig, "credential replaced")
286 })
287 t.Run("credential replaced behind a validator", func(t *testing.T) {
288 // The list's validator ignores who asks: the old credential's
289 // validator must not confirm its list for the new one.
290 rig := newMergeCredRig(t, perRepoOnly, []string{repo}, []string{repo})
291 rig.set(func() { rig.etag = `"v1"` })
292 if _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq); err != nil {
293 t.Fatal(err)
294 }
295 replaced := `{"agent":"other~owner@example.com","repositories":{"amadan.net/paulca/first":{"api":"api-other","git":"git-other"}}}`
296 if err := os.WriteFile(rig.path, []byte(replaced), 0600); err != nil {
297 t.Fatal(err)
298 }
299 refused(t, rig, "credential replaced behind a validator")
300 })
301 t.Run("renamed", func(t *testing.T) {
302 rig := newMergeCredRig(t, perRepoOnly, []string{repo}, []string{"amadan.net/paulca/nearys-site"})
303 refused(t, rig, "created, then renamed on the hub")
304 })
305 // Created a moment ago, not yet in the cached list: the write asks
306 // the hub afresh, which lists it.
307 rig := newMergeCredRig(t, perRepoOnly, nil, nil)
308 rig.f.list(ctx)
309 rig.set(func() { rig.lists["api-first"] = []string{repo} })
310 if err := rig.f.record(repo); err != nil {
311 t.Fatal(err)
312 }
313 if _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq); err != nil || len(rig.requests()) != 1 {
314 t.Fatalf("just created: %v %q", err, rig.requests())
315 }
316}
317
318// TestMergeStepCredentialIntegrated: through the runner's real forge (the
319// inspection needs the credential too), a missing credential file and an
320// unusable entry for the repository each end the step merge_credential at
321// once, naming the repository, with no merge request and no retries.
322func TestMergeStepCredentialIntegrated(t *testing.T) {
323 old := mergeBackoff
324 mergeBackoff = time.Millisecond
325 t.Cleanup(func() { mergeBackoff = old })
326 for name, file := range map[string]string{
327 "missing file": "",
328 "unusable entry": `{"agent":"equipo~owner@example.com","repositories":{"amadan.net/oficina/sample":{"git":"git-only"}}}`,
329 } {
330 t.Run(name, func(t *testing.T) {
331 e, _, r, _ := hubRig(t)
332 rig := newMergeCredRig(t, file, []string{r.Repo}, []string{r.Repo})
333 fg, err := NewForges(rig.f)
334 if err != nil {
335 t.Fatal(err)
336 }
337 e.Forge, e.Clones.Forge = fg, fg
338 rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
339 if rep.State != wire.StepFailed || rep.Reason != wire.ReasonMergeCredential || !rep.Termination {
340 t.Fatalf("report %+v", rep)
341 }
342 if !strings.Contains(rep.LogTail, r.Repo) || strings.Contains(rep.LogTail, "outcome unknown") || strings.Contains(rep.LogTail, "git-only") {
343 t.Fatalf("log tail %q", rep.LogTail)
344 }
345 if got := rig.requests(); len(got) != 0 {
346 t.Fatalf("merge requests %q", got)
347 }
348 })
349 }
350}
351
352// TestCheckCredentialsWarnsOnLegacyFiles: at start a credential file with
353// no agent-wide entry gets one fixed warning that its per-repository
354// credential serves as the agent's; one with an agent-wide entry none.
355func TestCheckCredentialsWarnsOnLegacyFiles(t *testing.T) {
356 var buf bytes.Buffer
357 log := slog.New(slog.NewTextHandler(&buf, nil))
358 newMergeCredRig(t, perRepoOnly, nil, nil).f.checkCreated(context.Background(), log)
359 if strings.Count(buf.String(), legacyAgentCredential) != 1 || strings.Contains(buf.String(), "api-first") {
360 t.Fatalf("legacy warning %s", buf.String())
361 }
362 buf.Reset()
363 newMergeCredRig(t, `{"agent":"equipo~owner@example.com","api":"api-first","git":"git-first"}`, nil, nil).f.checkCreated(context.Background(), log)
364 if buf.Len() != 0 {
365 t.Fatalf("warned with an agent-wide entry: %s", buf.String())
366 }
367}
368
369// TestWriteScopeUnavailableRecovers: a hub list that fails (a 500, a 502)
370// is not a denial: the merge is refused as "hub
371// unavailable", the push says so rather than asking for a git password,
372// and both go through once the hub answers again. A list that answers
373// without the repository is the denial.
374func TestWriteScopeUnavailableRecovers(t *testing.T) {
375 ctx := context.Background()
376 repo := "amadan.net/paulca/nearys"
377 rig := newMergeCredRig(t, perRepoOnly, []string{repo}, []string{repo})
378 for _, fail := range []func(){
379 func() { rig.listStatus = http.StatusInternalServerError },
380 func() { rig.listStatus = http.StatusBadGateway },
381 } {
382 rig.set(fail)
383 _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq)
384 var ns *forge.NotSentError
385 if !errors.Is(err, workspace.ErrHubUnavailable) || errors.Is(err, forge.ErrMergeRefused) || !errors.As(err, &ns) {
386 t.Fatalf("merge while the list fails: %v", err)
387 }
388 if _, err := rig.f.Remote(ctx, repo, Push); !errors.Is(err, workspace.ErrHubUnavailable) || errors.Is(err, workspace.ErrGitPassword) {
389 t.Fatalf("push while the list fails: %v", err)
390 }
391 }
392 rig.set(func() { rig.listStatus = 0 })
393 if _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq); err != nil {
394 t.Fatalf("merge after recovery: %v", err)
395 }
396 if remote, err := rig.f.Remote(ctx, repo, Push); err != nil || remote.GitPassword != "git-first" {
397 t.Fatalf("push after recovery: %v", err)
398 }
399 // Answered, without the repository: a denial.
400 rig.set(func() { rig.lists["api-first"] = nil })
401 if _, err := rig.f.Merge(ctx, repo, "equipo/tk1-x", mergeReq); !errors.Is(err, forge.ErrMergeRefused) || errors.Is(err, workspace.ErrHubUnavailable) {
402 t.Fatalf("denied: %v", err)
403 }
404}
405
406// TestMergeStepHubUnavailable: the hub cannot confirm write access. The
407// step tries again in place, and goes through once the hub answers; still
408// unavailable, it is deferred (the queue moves on), and past the wait it
409// ends amadan_unreachable, naming the repository.
410func TestMergeStepHubUnavailable(t *testing.T) {
411 old := []time.Duration{mergeBackoff, mergeHubWait}
412 mergeBackoff, mergeHubWait = time.Millisecond, 50*time.Millisecond
413 t.Cleanup(func() { mergeBackoff, mergeHubWait = old[0], old[1] })
414 e, f, r, _ := hubRig(t)
415 f.answer = func(n int, merge func() (forge.MergeResult, error)) (forge.MergeResult, error) {
416 if n == 1 {
417 return forge.MergeResult{}, forge.NotSent(r.Repo, workspace.ErrHubUnavailable)
418 }
419 return merge()
420 }
421 if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != wire.StepDone || f.requests != 2 {
422 t.Fatalf("recovered %+v (%d requests)", rep, f.requests)
423 }
424 e, f, r, _ = hubRig(t)
425 f.answer = func(int, func() (forge.MergeResult, error)) (forge.MergeResult, error) {
426 return forge.MergeResult{}, forge.NotSent(r.Repo, workspace.ErrHubUnavailable)
427 }
428 if err := e.O.State.AcceptDispatch(context.Background(), "d1", r.DispatchCommand); err != nil {
429 t.Fatal(err)
430 }
431 if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != stepDeferred || f.requests != mergeAttempts {
432 t.Fatalf("unavailable %+v (%d requests)", rep, f.requests)
433 }
434 e.O.State.deferStep(context.Background(), r, time.Millisecond)
435 e.O.State.db.Exec("UPDATE steps SET deferred_since=? WHERE step_id=?", stamp(time.Now().Add(-time.Hour)), r.StepID)
436 rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
437 if rep.State != wire.StepFailed || rep.Reason != wire.ReasonAmadanUnreachable || !strings.Contains(rep.LogTail, r.Repo) {
438 t.Fatalf("after the wait %+v", rep)
439 }
440}
441