| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "log/slog" |
| 9 | "net/http" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "regexp" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/runner" |
| 19 | "amadan.net/oficina/equipo/internal/wire" |
| 20 | ) |
| 21 | |
| 22 | // Equipo is designed to pair with a CARLOS preview host. A preview host is |
| 23 | // an adapter behind one interface: where an approved candidate's export |
| 24 | // is published, under which app name, and where its marker is fetched. |
| 25 | // CARLOS devbox (links on the tailnet) and Carloku temporary sites are |
| 26 | // the two adapters; devbox wins when both are there. |
| 27 | type previewHost interface { |
| 28 | Kind() string |
| 29 | App(task string) string |
| 30 | // Origin is where the app's marker is fetched, "" when not known. |
| 31 | Origin(app string) string |
| 32 | HTTP() *http.Client |
| 33 | } |
| 34 | |
| 35 | func (o *PreviewOptions) Kind() string { return wire.PreviewHostCarlokuTemp } |
| 36 | func (o *PreviewOptions) App(task string) string { return previewApp(task) } |
| 37 | func (o *PreviewOptions) Origin(app string) string { return o.origin(app) } |
| 38 | func (o *PreviewOptions) HTTP() *http.Client { return o.Client } |
| 39 | func (o *PreviewOptions) host() *wire.PreviewHost { |
| 40 | return &wire.PreviewHost{Kind: o.Kind(), Domain: o.Domain} |
| 41 | } |
| 42 | func (d *DevboxOptions) Kind() string { return wire.PreviewHostDevbox } |
| 43 | func (d *DevboxOptions) App(task string) string { return devboxName(task) } |
| 44 | func (d *DevboxOptions) HTTP() *http.Client { return d.Client } |
| 45 | func devboxName(task string) string { return "eq-" + task } |
| 46 | func (d *DevboxOptions) host() *wire.PreviewHost { |
| 47 | return &wire.PreviewHost{Kind: d.Kind(), Domain: d.domainNow()} |
| 48 | } |
| 49 | func (d *DevboxOptions) domainNow() string { d.mu.Lock(); defer d.mu.Unlock(); return d.Domain } |
| 50 | func (d *DevboxOptions) recordPath(task string) string { return filepath.Join(d.State, task+".json") } |
| 51 | |
| 52 | // activePreviewHost is the paired host previews use: devbox first. |
| 53 | func (e *Engineer) activePreviewHost() previewHost { |
| 54 | switch { |
| 55 | case e.Devbox != nil: |
| 56 | return e.Devbox |
| 57 | case e.Preview != nil: |
| 58 | return e.Preview |
| 59 | } |
| 60 | return nil |
| 61 | } |
| 62 | |
| 63 | // PreviewHostOf is the host a runner reports in its hello: devbox when |
| 64 | // usable, else Carloku temporary sites with a credential, else none. |
| 65 | func PreviewHostOf(d *DevboxOptions, p *PreviewOptions) func() *wire.PreviewHost { |
| 66 | return func() *wire.PreviewHost { |
| 67 | switch { |
| 68 | case d != nil: |
| 69 | return d.host() |
| 70 | case p != nil: |
| 71 | return p.host() |
| 72 | } |
| 73 | return nil |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | // DevboxOptions is CARLOS devbox as a preview host: the carlos binary, run |
| 78 | // by this runner's process outside every namespace (devbox needs AF_UNIX |
| 79 | // to reach its registrar), and the domain links live under, learnt from a |
| 80 | // share. State holds one record per task this runner shared. |
| 81 | type DevboxOptions struct { |
| 82 | Carlos string |
| 83 | State string |
| 84 | // Run and Client are seams for the tests (nil: exec, and a client |
| 85 | // that follows no redirect). Learnt is called once the domain is known. |
| 86 | Run func(ctx context.Context, dir string, env []string, args []string) (string, error) |
| 87 | Client *http.Client |
| 88 | Learnt func() |
| 89 | |
| 90 | mu sync.Mutex |
| 91 | Domain string |
| 92 | } |
| 93 | |
| 94 | // Origin is the app's link: https://<name>.<domain>, "" until a share told |
| 95 | // the domain. |
| 96 | func (d *DevboxOptions) Origin(app string) string { |
| 97 | if dom := d.domainNow(); dom != "" { |
| 98 | return "https://" + app + "." + dom |
| 99 | } |
| 100 | return "" |
| 101 | } |
| 102 | |
| 103 | var devboxDomain = regexp.MustCompile(`^[a-z0-9-]+(\.[a-z0-9-]+)+$`) |
| 104 | |
| 105 | // ProbeDevbox pairs the runner with CARLOS devbox when its configuration |
| 106 | // selects devbox (the default) and its carlos can list links for this |
| 107 | // user (`carlos devbox |
| 108 | // list` answers): the binary from EQUIPO_CARLOS_PATH, else PATH, else |
| 109 | // ~/.local/bin. nil when not. |
| 110 | func ProbeDevbox(c runner.Config, logger *slog.Logger, run func(ctx context.Context, dir string, env []string, args []string) (string, error)) *DevboxOptions { |
| 111 | if c.PreviewHost != wire.PreviewHostDevbox { |
| 112 | return nil |
| 113 | } |
| 114 | carlos := c.CarlosPath |
| 115 | if carlos == "" { |
| 116 | if p, err := exec.LookPath("carlos"); err == nil { |
| 117 | carlos = p |
| 118 | } else if home, err := os.UserHomeDir(); err == nil { |
| 119 | carlos = filepath.Join(home, ".local", "bin", "carlos") |
| 120 | } |
| 121 | } |
| 122 | if !filepath.IsAbs(carlos) || c.StateDir == "" { |
| 123 | return nil |
| 124 | } |
| 125 | if info, err := os.Stat(carlos); err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 { |
| 126 | return nil |
| 127 | } |
| 128 | d := &DevboxOptions{Carlos: carlos, State: filepath.Join(c.StateDir, "devbox"), Run: run} |
| 129 | if err := os.MkdirAll(d.State, 0o700); err != nil { |
| 130 | return nil |
| 131 | } |
| 132 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 133 | defer cancel() |
| 134 | if _, err := d.command(ctx, "list"); err != nil { |
| 135 | return nil |
| 136 | } |
| 137 | if raw, err := os.ReadFile(filepath.Join(d.State, "domain")); err == nil && devboxDomain.MatchString(strings.TrimSpace(string(raw))) { |
| 138 | d.Domain = strings.TrimSpace(string(raw)) |
| 139 | } |
| 140 | if logger != nil { |
| 141 | logger.Info("previews pair with CARLOS devbox", "domain", d.Domain) |
| 142 | } |
| 143 | return d |
| 144 | } |
| 145 | |
| 146 | var errDevboxCommand = errors.New("devbox command refused") |
| 147 | |
| 148 | // command runs one carlos devbox command from the fixed templates only: |
| 149 | // list; share --dir <a staging folder under this runner's state> eq-<task>; |
| 150 | // unshare eq-<task>. From an empty private directory, with a private HOME |
| 151 | // and nothing of the repository; no credential is involved. |
| 152 | func (d *DevboxOptions) command(ctx context.Context, verb string, args ...string) (string, error) { |
| 153 | switch { |
| 154 | case verb == "list" && len(args) == 0: |
| 155 | case verb == "share" && len(args) == 3 && args[0] == "--dir" && filepath.IsAbs(args[1]) && devboxTask.MatchString(args[2]): |
| 156 | case verb == "unshare" && len(args) == 1 && devboxTask.MatchString(args[0]): |
| 157 | default: |
| 158 | return "", errDevboxCommand |
| 159 | } |
| 160 | dir := filepath.Join(d.State, "run") |
| 161 | if err := os.MkdirAll(dir, 0o700); err != nil { |
| 162 | return "", err |
| 163 | } |
| 164 | argv := append([]string{"devbox", verb}, args...) |
| 165 | env := []string{"HOME=" + dir, "PATH=/usr/bin:/bin"} |
| 166 | cctx, cancel := context.WithTimeout(ctx, 2*time.Minute) |
| 167 | defer cancel() |
| 168 | if d.Run != nil { |
| 169 | return d.Run(cctx, dir, env, argv) |
| 170 | } |
| 171 | cmd := exec.CommandContext(cctx, d.Carlos, argv...) |
| 172 | cmd.Dir, cmd.Env = dir, env |
| 173 | return runCarlos(cmd) |
| 174 | } |
| 175 | |
| 176 | // carlosError is a carlos command that failed, with what carlos said on |
| 177 | // stderr (bounded). |
| 178 | type carlosError struct { |
| 179 | err error |
| 180 | words string |
| 181 | } |
| 182 | |
| 183 | func (c *carlosError) Error() string { return c.err.Error() + ": " + c.words } |
| 184 | func (c *carlosError) Unwrap() error { return c.err } |
| 185 | |
| 186 | // runCarlos runs cmd with stdout bounded at 64 KiB. carlos says why it |
| 187 | // refused on stderr, so on failure its words (the first 4 KiB) follow |
| 188 | // stdout in the text returned, where a caller looks for a known refusal, |
| 189 | // and the error carries them for the log. Words cut at the limit are |
| 190 | // never logged: redaction needs the whole text, and a secret cut short |
| 191 | // can slip past it. On success stdout is all. |
| 192 | func runCarlos(cmd *exec.Cmd) (string, error) { |
| 193 | var stderr bytes.Buffer |
| 194 | said := &limitWriter{w: &stderr, n: 4 << 10} |
| 195 | cmd.Stderr = said |
| 196 | out, clipped, err := boundedOutput(cmd, 64<<10) |
| 197 | if clipped && err == nil { |
| 198 | err = errors.New("carlos output too long") |
| 199 | } |
| 200 | if words := strings.TrimSpace(strings.ToValidUTF8(stderr.String(), "?")); err != nil && words != "" { |
| 201 | logged := words |
| 202 | if said.over { |
| 203 | logged = "(over 4 KiB on stderr, not logged)" |
| 204 | } |
| 205 | return string(out) + "\n" + words, &carlosError{err: err, words: logged} |
| 206 | } |
| 207 | return string(out), err |
| 208 | } |
| 209 | |
| 210 | var devboxTask = regexp.MustCompile(`^eq-[a-z0-9]{1,60}$`) |
| 211 | |
| 212 | // devboxRecord is what this runner shared for a task: the link's name and |
| 213 | // its URL, written before the share (intent) and completed after. |
| 214 | type devboxRecord struct { |
| 215 | Name string `json:"name"` |
| 216 | URL string `json:"url,omitempty"` |
| 217 | } |
| 218 | |
| 219 | func (d *DevboxOptions) record(task string, rec devboxRecord) error { |
| 220 | raw, _ := json.Marshal(rec) |
| 221 | return os.WriteFile(d.recordPath(task), raw, 0o600) |
| 222 | } |
| 223 | |
| 224 | func (d *DevboxOptions) recorded(task string) (devboxRecord, bool) { |
| 225 | var rec devboxRecord |
| 226 | raw, err := os.ReadFile(d.recordPath(task)) |
| 227 | return rec, err == nil && json.Unmarshal(raw, &rec) == nil && rec.Name == devboxName(task) |
| 228 | } |
| 229 | |
| 230 | // learn takes the domain from a link share printed for name, saved for the |
| 231 | // next start, and says so once (the hello carries it). |
| 232 | func (d *DevboxOptions) learn(url, name string) bool { |
| 233 | dom, ok := strings.CutPrefix(url, "https://"+name+".") |
| 234 | if !ok || !devboxDomain.MatchString(dom) || len(dom) > 253 { |
| 235 | return false |
| 236 | } |
| 237 | d.mu.Lock() |
| 238 | changed := d.Domain != dom |
| 239 | d.Domain = dom |
| 240 | d.mu.Unlock() |
| 241 | if changed { |
| 242 | os.WriteFile(filepath.Join(d.State, "domain"), []byte(dom+"\n"), 0o600) |
| 243 | if d.Learnt != nil { |
| 244 | d.Learnt() |
| 245 | } |
| 246 | } |
| 247 | return true |
| 248 | } |
| 249 | |
| 250 | // sharedURL is the link carlos printed for name: the one line that is |
| 251 | // exactly https://<name>.<domain>. |
| 252 | func sharedURL(out, name string) (string, bool) { |
| 253 | link := regexp.MustCompile(`^https://` + regexp.QuoteMeta(name) + `\.[a-z0-9-]+(\.[a-z0-9-]+)+$`) |
| 254 | for _, line := range strings.Split(ansi.ReplaceAllString(out, ""), "\n") { |
| 255 | if line = strings.TrimSuffix(strings.TrimSpace(line), "/"); link.MatchString(line) { |
| 256 | return line, true |
| 257 | } |
| 258 | } |
| 259 | return "", false |
| 260 | } |
| 261 | |
| 262 | // publishDevbox shares the export as eq-<task> on the paired devbox: one |
| 263 | // publish check, the intent recorded, one share (the same name replaces |
| 264 | // the previous candidate's copy in place), then the marker. The link is |
| 265 | // open to the whole tailnet: Equipo does not know the task creator's |
| 266 | // tailnet login, so it passes no --allow, as Paul's own shares do. |
| 267 | func (e *Engineer) publishDevbox(ctx context.Context, r stepRow, rep wire.StepReport, ex previewExport, mark previewMark, stage string, confirm func() error, stopped func(error) wire.StepReport) wire.StepReport { |
| 268 | d := e.Devbox |
| 269 | name := devboxName(r.TaskID) |
| 270 | if err := confirm(); err != nil { |
| 271 | return stopped(err) |
| 272 | } |
| 273 | if err := e.O.State.setStepPhase(context.WithoutCancel(ctx), r, phasePreviewPublishing, r.Base, r.Candidate); err != nil { |
| 274 | rep.State, rep.Reason, rep.Termination = wire.StepFailed, "preview_failed", true |
| 275 | return rep |
| 276 | } |
| 277 | if err := d.record(r.TaskID, devboxRecord{Name: name}); err != nil { |
| 278 | return e.previewDone(rep, r, ex, nil, false, "preview_failed") |
| 279 | } |
| 280 | out, err := d.command(ctx, "share", "--dir", stage, name) |
| 281 | if err != nil { |
| 282 | e.logDetail("preview share", err) |
| 283 | return e.previewDone(rep, r, ex, nil, false, previewPublishFailure(out)) |
| 284 | } |
| 285 | url, ok := sharedURL(out, name) |
| 286 | if !ok || !d.learn(url, name) { |
| 287 | return e.previewDone(rep, r, ex, nil, false, "preview_state") |
| 288 | } |
| 289 | d.record(r.TaskID, devboxRecord{Name: name, URL: url}) |
| 290 | served, why := e.previewServed(ctx, r, mark) |
| 291 | if served { |
| 292 | // devbox serves its own copy: the export can go (the marker stays |
| 293 | // for a restart's reconcile). |
| 294 | entries, _ := os.ReadDir(stage) |
| 295 | for _, en := range entries { |
| 296 | if en.Name() != previewMarker { |
| 297 | os.RemoveAll(filepath.Join(stage, en.Name())) |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | return e.previewDone(rep, r, ex, nil, served, why) |
| 302 | } |
| 303 | |
| 304 | // PreviewTaskEnded takes a task's devbox link down once the task is done, |
| 305 | // dropped or cancelled (the instance's ForgetTask): only a link this |
| 306 | // runner recorded sharing, by the fixed unshare template; the record goes |
| 307 | // once the link is gone. A Carloku temporary site expires on its own. |
| 308 | func (e *Engineer) PreviewTaskEnded(ctx context.Context, task string) { |
| 309 | d := e.Devbox |
| 310 | if d == nil || !regexp.MustCompile(`^[a-z0-9]{1,60}$`).MatchString(task) { |
| 311 | return |
| 312 | } |
| 313 | rec, ok := d.recorded(task) |
| 314 | if !ok { |
| 315 | return |
| 316 | } |
| 317 | out, err := d.command(ctx, "unshare", rec.Name) |
| 318 | if err != nil && !strings.Contains(out, "no link called "+rec.Name) { |
| 319 | e.logDetail("preview unshare", err) |
| 320 | return |
| 321 | } |
| 322 | os.Remove(d.recordPath(task)) |
| 323 | } |
| 324 | |