package thin import ( "context" "errors" "net" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/wire" ) // fakeDevbox is `carlos devbox` as the runner sees it: share prints the // link and serves the folder it was given; unshare takes it down. type fakeDevbox struct { t *testing.T calls [][]string envs [][]string headers string served string gone bool unshare string } func (f *fakeDevbox) run(_ context.Context, dir string, env []string, args []string) (string, error) { f.calls, f.envs = append(f.calls, args), append(f.envs, env) if entries, _ := os.ReadDir(dir); len(entries) != 0 { f.t.Fatalf("devbox ran from a directory holding %v", entries) } switch args[1] { case "list": return "name owner kind\n", nil case "share": f.served = args[3] raw, err := os.ReadFile(filepath.Join(f.served, "_headers")) if err != nil { f.t.Fatal(err) } f.headers = string(raw) return "\x1b[32mhttps://" + args[4] + ".devbox.dev.example\x1b[0m\n", nil case "unshare": if f.unshare != "" { return f.unshare, errors.New("exit status 1") } f.gone = true return "removed https://" + args[2] + ".devbox.dev.example\n", nil } f.t.Fatalf("a devbox command outside the templates: %v", args) return "", nil } // devboxRig is previewRig paired with a fake devbox (and no Carloku // credential); the marker is fetched from what devbox serves, whatever // host the link names, and no redirect is followed. func devboxRig(t *testing.T) (*Engineer, *fakeDevbox, *[]string, stepRow) { t.Helper() e, _, confirms, r := previewRig(t, mockups, nil) fd := &fakeDevbox{t: t} origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if fd.served == "" || fd.gone || req.URL.Path != "/"+previewMarker || req.Host != "eq-tk1.devbox.dev.example" { http.NotFound(w, req) return } w.Header().Set("Content-Security-Policy", previewCSP("https://equipo.example")) http.ServeFile(w, req, filepath.Join(fd.served, previewMarker)) })) t.Cleanup(origin.Close) addr := strings.TrimPrefix(origin.URL, "http://") // The link is https on the devbox domain; the fake answers plain http // on its own port, so every connection goes there as if TLS were done. dial := func(ctx context.Context, _, _ string) (net.Conn, error) { return (&net.Dialer{}).DialContext(ctx, "tcp", addr) } client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, Transport: &http.Transport{DialContext: dial, DialTLSContext: dial}} e.Preview = nil e.Devbox = &DevboxOptions{Carlos: "/usr/local/bin/carlos", State: filepath.Join(e.O.Runner.StateDir, "devbox"), Run: fd.run, Client: client} os.MkdirAll(e.Devbox.State, 0o700) return e, fd, confirms, r } // TestDevboxPreviewShares: paired with CARLOS devbox, a preview is one // publish check and one share of the export as eq-, from the fixed // template with no credential; the link devbox prints is confirmed by the // marker, the domain is learnt for the hello, and the export goes (devbox // serves its own copy) but for the marker. func TestDevboxPreviewShares(t *testing.T) { e, fd, confirms, r := devboxRig(t) learnt := 0 e.Devbox.Learnt = func() { learnt++ } fd.served = "" httpsOnly(t, e) rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) 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 { t.Fatalf("report %+v %+v", rep, rep.Preview) } if fd.headers != previewHeaders(e.O.Runner.Origin) || !strings.Contains(fd.headers, "default-src 'none'") { t.Fatalf("private headers: %q", fd.headers) } stage := filepath.Join(e.root(), stepKey(r), "preview") if len(fd.calls) != 1 || strings.Join(fd.calls[0], " ") != "devbox share --dir "+stage+" eq-tk1" || len(*confirms) != 1 { t.Fatalf("commands %v, checks %v", fd.calls, *confirms) } for _, kv := range fd.envs[0] { if strings.HasPrefix(kv, "CARLOS_SERVICE_TOKEN") { t.Fatal("a credential in devbox's environment") } } if e.Devbox.domainNow() != "devbox.dev.example" || learnt != 1 { t.Fatalf("domain %q learnt %d", e.Devbox.domainNow(), learnt) } if host := PreviewHostOf(e.Devbox, nil)(); host == nil || host.Kind != wire.PreviewHostDevbox || host.Domain != "devbox.dev.example" { t.Fatalf("hello host %+v", host) } if entries, _ := os.ReadDir(stage); len(entries) != 1 || entries[0].Name() != previewMarker { t.Fatalf("export kept: %v", entries) } rec, ok := e.Devbox.recorded("tk1") if !ok || rec.URL != "https://eq-tk1.devbox.dev.example" { t.Fatalf("record %+v", rec) } } // httpsOnly refuses the marker fetch's https link anywhere but the fake. func httpsOnly(t *testing.T, e *Engineer) { t.Helper() if e.Devbox.Origin("eq-tk1") != "" { t.Fatal("an origin before any share") } } // TestDevboxPreviewReplacesAndEnds: a newer candidate's preview shares the // same name again (in place); when the task ends the link is unshared once // by the fixed template, its record goes, and a second end does nothing. func TestDevboxPreviewReplacesAndEnds(t *testing.T) { e, fd, _, r := devboxRig(t) e.Exec(context.Background(), r, func(wire.StepReport) {}) r2 := r r2.StepID = "s_pv2" if err := e.O.State.AcceptDispatch(context.Background(), "d2", r2.DispatchCommand); err != nil { t.Fatal(err) } if rep := e.Exec(context.Background(), r2, func(wire.StepReport) {}); rep.Preview == nil || rep.Preview.Outcome != wire.PreviewDeployed { t.Fatalf("again %+v", rep.Preview) } if len(fd.calls) != 2 || fd.calls[1][4] != "eq-tk1" { t.Fatalf("commands %v", fd.calls) } e.PreviewTaskEnded(context.Background(), "tk1") if len(fd.calls) != 3 || strings.Join(fd.calls[2], " ") != "devbox unshare eq-tk1" || !fd.gone { t.Fatalf("end %v", fd.calls) } if _, ok := e.Devbox.recorded("tk1"); ok { t.Fatal("record kept") } e.PreviewTaskEnded(context.Background(), "tk1") e.PreviewTaskEnded(context.Background(), "other") if len(fd.calls) != 3 { t.Fatalf("unshared again or another: %v", fd.calls) } // A link already gone counts as gone; any other failure keeps the // record for the next end. e2, fd2, _, r3 := devboxRig(t) e2.Exec(context.Background(), r3, func(wire.StepReport) {}) fd2.unshare = "permission denied\n" e2.PreviewTaskEnded(context.Background(), "tk1") if _, ok := e2.Devbox.recorded("tk1"); !ok { t.Fatal("record dropped after a failed unshare") } fd2.unshare = "no link called eq-tk1. see what exists with: carlos devbox list\n" e2.PreviewTaskEnded(context.Background(), "tk1") if _, ok := e2.Devbox.recorded("tk1"); ok { t.Fatal("record kept for a link already gone") } } // TestDevboxAllowlistAndPairing: only the fixed templates run; devbox // pairs only when configured and its carlos answers; with both hosts, // devbox wins, and without devbox the Carloku credential is the host. func TestDevboxAllowlistAndPairing(t *testing.T) { d := &DevboxOptions{State: t.TempDir(), Run: func(context.Context, string, []string, []string) (string, error) { return "", nil }} 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"}} { if _, err := d.command(context.Background(), c[0], c[1:]...); !errors.Is(err, errDevboxCommand) { t.Fatalf("%v ran", c) } } dir := t.TempDir() carlos := filepath.Join(dir, "carlos") os.WriteFile(carlos, []byte("#!/bin/sh\n"), 0o755) ran := 0 ok := func(context.Context, string, []string, []string) (string, error) { ran++; return "", nil } bad := func(context.Context, string, []string, []string) (string, error) { return "", errors.New("no registrar") } cfg := runner.Config{CarlosPath: carlos, StateDir: dir} if ProbeDevbox(cfg, nil, ok) != nil || ran != 0 { t.Fatal("paired without being configured") } cfg.PreviewHost = wire.PreviewHostDevbox if ProbeDevbox(cfg, nil, bad) != nil { t.Fatal("paired with a devbox that does not answer") } got := ProbeDevbox(cfg, nil, ok) if got == nil || ran != 1 { t.Fatal("not paired") } p := &PreviewOptions{Domain: "bds.oncarlos.com"} if h := PreviewHostOf(got, p)(); h.Kind != wire.PreviewHostDevbox { t.Fatalf("both: %+v", h) } if h := PreviewHostOf(nil, p)(); h.Kind != wire.PreviewHostCarlokuTemp || h.Domain != "bds.oncarlos.com" { t.Fatalf("carloku: %+v", h) } if PreviewHostOf(nil, nil)() != nil { t.Fatal("a host from nothing") } e := &Engineer{Devbox: got, Preview: p} if e.activePreviewHost().Kind() != wire.PreviewHostDevbox { t.Fatal("Carloku won over devbox") } }