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 "context"
5 "errors"
6 "net"
7 "net/http"
8 "net/http/httptest"
9 "os"
10 "path/filepath"
11 "strings"
12 "testing"
13
14 "amadan.net/oficina/equipo/internal/runner"
15 "amadan.net/oficina/equipo/internal/wire"
16)
17
18// fakeDevbox is `carlos devbox` as the runner sees it: share prints the
19// link and serves the folder it was given; unshare takes it down.
20type fakeDevbox struct {
21 t *testing.T
22 calls [][]string
23 envs [][]string
24 headers string
25 served string
26 gone bool
27 unshare string
28}
29
30func (f *fakeDevbox) run(_ context.Context, dir string, env []string, args []string) (string, error) {
31 f.calls, f.envs = append(f.calls, args), append(f.envs, env)
32 if entries, _ := os.ReadDir(dir); len(entries) != 0 {
33 f.t.Fatalf("devbox ran from a directory holding %v", entries)
34 }
35 switch args[1] {
36 case "list":
37 return "name owner kind\n", nil
38 case "share":
39 f.served = args[3]
40 raw, err := os.ReadFile(filepath.Join(f.served, "_headers"))
41 if err != nil {
42 f.t.Fatal(err)
43 }
44 f.headers = string(raw)
45 return "\x1b[32mhttps://" + args[4] + ".devbox.dev.example\x1b[0m\n", nil
46 case "unshare":
47 if f.unshare != "" {
48 return f.unshare, errors.New("exit status 1")
49 }
50 f.gone = true
51 return "removed https://" + args[2] + ".devbox.dev.example\n", nil
52 }
53 f.t.Fatalf("a devbox command outside the templates: %v", args)
54 return "", nil
55}
56
57// devboxRig is previewRig paired with a fake devbox (and no Carloku
58// credential); the marker is fetched from what devbox serves, whatever
59// host the link names, and no redirect is followed.
60func devboxRig(t *testing.T) (*Engineer, *fakeDevbox, *[]string, stepRow) {
61 t.Helper()
62 e, _, confirms, r := previewRig(t, mockups, nil)
63 fd := &fakeDevbox{t: t}
64 origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
65 if fd.served == "" || fd.gone || req.URL.Path != "/"+previewMarker || req.Host != "eq-tk1.devbox.dev.example" {
66 http.NotFound(w, req)
67 return
68 }
69 w.Header().Set("Content-Security-Policy", previewCSP("https://equipo.example"))
70 http.ServeFile(w, req, filepath.Join(fd.served, previewMarker))
71 }))
72 t.Cleanup(origin.Close)
73 addr := strings.TrimPrefix(origin.URL, "http://")
74 // The link is https on the devbox domain; the fake answers plain http
75 // on its own port, so every connection goes there as if TLS were done.
76 dial := func(ctx context.Context, _, _ string) (net.Conn, error) {
77 return (&net.Dialer{}).DialContext(ctx, "tcp", addr)
78 }
79 client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, Transport: &http.Transport{DialContext: dial, DialTLSContext: dial}}
80 e.Preview = nil
81 e.Devbox = &DevboxOptions{Carlos: "/usr/local/bin/carlos", State: filepath.Join(e.O.Runner.StateDir, "devbox"), Run: fd.run, Client: client}
82 os.MkdirAll(e.Devbox.State, 0o700)
83 return e, fd, confirms, r
84}
85
86// TestDevboxPreviewShares: paired with CARLOS devbox, a preview is one
87// publish check and one share of the export as eq-<task>, from the fixed
88// template with no credential; the link devbox prints is confirmed by the
89// marker, the domain is learnt for the hello, and the export goes (devbox
90// serves its own copy) but for the marker.
91func TestDevboxPreviewShares(t *testing.T) {
92 e, fd, confirms, r := devboxRig(t)
93 learnt := 0
94 e.Devbox.Learnt = func() { learnt++ }
95 fd.served = ""
96 httpsOnly(t, e)
97 rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
98 if rep.State != wire.StepDone || rep.Preview == nil || rep.Preview.Outcome != wire.PreviewDeployed || rep.Preview.App != "eq-tk1" || rep.Preview.URL != "https://eq-tk1.devbox.dev.example/" || rep.Preview.ExpiresAt != nil {
99 t.Fatalf("report %+v %+v", rep, rep.Preview)
100 }
101 if fd.headers != previewHeaders(e.O.Runner.Origin) || !strings.Contains(fd.headers, "default-src 'none'") {
102 t.Fatalf("private headers: %q", fd.headers)
103 }
104 stage := filepath.Join(e.root(), stepKey(r), "preview")
105 if len(fd.calls) != 1 || strings.Join(fd.calls[0], " ") != "devbox share --dir "+stage+" eq-tk1" || len(*confirms) != 1 {
106 t.Fatalf("commands %v, checks %v", fd.calls, *confirms)
107 }
108 for _, kv := range fd.envs[0] {
109 if strings.HasPrefix(kv, "CARLOS_SERVICE_TOKEN") {
110 t.Fatal("a credential in devbox's environment")
111 }
112 }
113 if e.Devbox.domainNow() != "devbox.dev.example" || learnt != 1 {
114 t.Fatalf("domain %q learnt %d", e.Devbox.domainNow(), learnt)
115 }
116 if host := PreviewHostOf(e.Devbox, nil)(); host == nil || host.Kind != wire.PreviewHostDevbox || host.Domain != "devbox.dev.example" {
117 t.Fatalf("hello host %+v", host)
118 }
119 if entries, _ := os.ReadDir(stage); len(entries) != 1 || entries[0].Name() != previewMarker {
120 t.Fatalf("export kept: %v", entries)
121 }
122 rec, ok := e.Devbox.recorded("tk1")
123 if !ok || rec.URL != "https://eq-tk1.devbox.dev.example" {
124 t.Fatalf("record %+v", rec)
125 }
126}
127
128// httpsOnly refuses the marker fetch's https link anywhere but the fake.
129func httpsOnly(t *testing.T, e *Engineer) {
130 t.Helper()
131 if e.Devbox.Origin("eq-tk1") != "" {
132 t.Fatal("an origin before any share")
133 }
134}
135
136// TestDevboxPreviewReplacesAndEnds: a newer candidate's preview shares the
137// same name again (in place); when the task ends the link is unshared once
138// by the fixed template, its record goes, and a second end does nothing.
139func TestDevboxPreviewReplacesAndEnds(t *testing.T) {
140 e, fd, _, r := devboxRig(t)
141 e.Exec(context.Background(), r, func(wire.StepReport) {})
142 r2 := r
143 r2.StepID = "s_pv2"
144 if err := e.O.State.AcceptDispatch(context.Background(), "d2", r2.DispatchCommand); err != nil {
145 t.Fatal(err)
146 }
147 if rep := e.Exec(context.Background(), r2, func(wire.StepReport) {}); rep.Preview == nil || rep.Preview.Outcome != wire.PreviewDeployed {
148 t.Fatalf("again %+v", rep.Preview)
149 }
150 if len(fd.calls) != 2 || fd.calls[1][4] != "eq-tk1" {
151 t.Fatalf("commands %v", fd.calls)
152 }
153 e.PreviewTaskEnded(context.Background(), "tk1")
154 if len(fd.calls) != 3 || strings.Join(fd.calls[2], " ") != "devbox unshare eq-tk1" || !fd.gone {
155 t.Fatalf("end %v", fd.calls)
156 }
157 if _, ok := e.Devbox.recorded("tk1"); ok {
158 t.Fatal("record kept")
159 }
160 e.PreviewTaskEnded(context.Background(), "tk1")
161 e.PreviewTaskEnded(context.Background(), "other")
162 if len(fd.calls) != 3 {
163 t.Fatalf("unshared again or another: %v", fd.calls)
164 }
165 // A link already gone counts as gone; any other failure keeps the
166 // record for the next end.
167 e2, fd2, _, r3 := devboxRig(t)
168 e2.Exec(context.Background(), r3, func(wire.StepReport) {})
169 fd2.unshare = "permission denied\n"
170 e2.PreviewTaskEnded(context.Background(), "tk1")
171 if _, ok := e2.Devbox.recorded("tk1"); !ok {
172 t.Fatal("record dropped after a failed unshare")
173 }
174 fd2.unshare = "no link called eq-tk1. see what exists with: carlos devbox list\n"
175 e2.PreviewTaskEnded(context.Background(), "tk1")
176 if _, ok := e2.Devbox.recorded("tk1"); ok {
177 t.Fatal("record kept for a link already gone")
178 }
179}
180
181// TestDevboxAllowlistAndPairing: only the fixed templates run; devbox
182// pairs only when configured and its carlos answers; with both hosts,
183// devbox wins, and without devbox the Carloku credential is the host.
184func TestDevboxAllowlistAndPairing(t *testing.T) {
185 d := &DevboxOptions{State: t.TempDir(), Run: func(context.Context, string, []string, []string) (string, error) { return "", nil }}
186 for _, c := range [][]string{{"share", "--dir", "relative", "eq-tk1"}, {"share", "--dir", "/abs", "tmp-tk1"}, {"share", "--port", "80", "eq-tk1"}, {"unshare", "eq-tk1", "--x"}, {"unshare", "tmp-tk1"}, {"delete", "eq-tk1"}, {"list", "--allowed"}} {
187 if _, err := d.command(context.Background(), c[0], c[1:]...); !errors.Is(err, errDevboxCommand) {
188 t.Fatalf("%v ran", c)
189 }
190 }
191 dir := t.TempDir()
192 carlos := filepath.Join(dir, "carlos")
193 os.WriteFile(carlos, []byte("#!/bin/sh\n"), 0o755)
194 ran := 0
195 ok := func(context.Context, string, []string, []string) (string, error) { ran++; return "", nil }
196 bad := func(context.Context, string, []string, []string) (string, error) {
197 return "", errors.New("no registrar")
198 }
199 cfg := runner.Config{CarlosPath: carlos, StateDir: dir}
200 if ProbeDevbox(cfg, nil, ok) != nil || ran != 0 {
201 t.Fatal("paired without being configured")
202 }
203 cfg.PreviewHost = wire.PreviewHostDevbox
204 if ProbeDevbox(cfg, nil, bad) != nil {
205 t.Fatal("paired with a devbox that does not answer")
206 }
207 got := ProbeDevbox(cfg, nil, ok)
208 if got == nil || ran != 1 {
209 t.Fatal("not paired")
210 }
211 p := &PreviewOptions{Domain: "bds.oncarlos.com"}
212 if h := PreviewHostOf(got, p)(); h.Kind != wire.PreviewHostDevbox {
213 t.Fatalf("both: %+v", h)
214 }
215 if h := PreviewHostOf(nil, p)(); h.Kind != wire.PreviewHostCarlokuTemp || h.Domain != "bds.oncarlos.com" {
216 t.Fatalf("carloku: %+v", h)
217 }
218 if PreviewHostOf(nil, nil)() != nil {
219 t.Fatal("a host from nothing")
220 }
221 e := &Engineer{Devbox: got, Preview: p}
222 if e.activePreviewHost().Kind() != wire.PreviewHostDevbox {
223 t.Fatal("Carloku won over devbox")
224 }
225}
226