package thin import ( "bytes" "context" "encoding/json" "errors" "log/slog" "net/http" "os" "os/exec" "path/filepath" "regexp" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/wire" ) // Equipo is designed to pair with a CARLOS preview host. A preview host is // an adapter behind one interface: where an approved candidate's export // is published, under which app name, and where its marker is fetched. // CARLOS devbox (links on the tailnet) and Carloku temporary sites are // the two adapters; devbox wins when both are there. type previewHost interface { Kind() string App(task string) string // Origin is where the app's marker is fetched, "" when not known. Origin(app string) string HTTP() *http.Client } func (o *PreviewOptions) Kind() string { return wire.PreviewHostCarlokuTemp } func (o *PreviewOptions) App(task string) string { return previewApp(task) } func (o *PreviewOptions) Origin(app string) string { return o.origin(app) } func (o *PreviewOptions) HTTP() *http.Client { return o.Client } func (o *PreviewOptions) host() *wire.PreviewHost { return &wire.PreviewHost{Kind: o.Kind(), Domain: o.Domain} } func (d *DevboxOptions) Kind() string { return wire.PreviewHostDevbox } func (d *DevboxOptions) App(task string) string { return devboxName(task) } func (d *DevboxOptions) HTTP() *http.Client { return d.Client } func devboxName(task string) string { return "eq-" + task } func (d *DevboxOptions) host() *wire.PreviewHost { return &wire.PreviewHost{Kind: d.Kind(), Domain: d.domainNow()} } func (d *DevboxOptions) domainNow() string { d.mu.Lock(); defer d.mu.Unlock(); return d.Domain } func (d *DevboxOptions) recordPath(task string) string { return filepath.Join(d.State, task+".json") } // activePreviewHost is the paired host previews use: devbox first. func (e *Engineer) activePreviewHost() previewHost { switch { case e.Devbox != nil: return e.Devbox case e.Preview != nil: return e.Preview } return nil } // PreviewHostOf is the host a runner reports in its hello: devbox when // usable, else Carloku temporary sites with a credential, else none. func PreviewHostOf(d *DevboxOptions, p *PreviewOptions) func() *wire.PreviewHost { return func() *wire.PreviewHost { switch { case d != nil: return d.host() case p != nil: return p.host() } return nil } } // DevboxOptions is CARLOS devbox as a preview host: the carlos binary, run // by this runner's process outside every namespace (devbox needs AF_UNIX // to reach its registrar), and the domain links live under, learnt from a // share. State holds one record per task this runner shared. type DevboxOptions struct { Carlos string State string // Run and Client are seams for the tests (nil: exec, and a client // that follows no redirect). Learnt is called once the domain is known. Run func(ctx context.Context, dir string, env []string, args []string) (string, error) Client *http.Client Learnt func() mu sync.Mutex Domain string } // Origin is the app's link: https://., "" until a share told // the domain. func (d *DevboxOptions) Origin(app string) string { if dom := d.domainNow(); dom != "" { return "https://" + app + "." + dom } return "" } var devboxDomain = regexp.MustCompile(`^[a-z0-9-]+(\.[a-z0-9-]+)+$`) // ProbeDevbox pairs the runner with CARLOS devbox when its configuration // selects devbox (the default) and its carlos can list links for this // user (`carlos devbox // list` answers): the binary from EQUIPO_CARLOS_PATH, else PATH, else // ~/.local/bin. nil when not. func ProbeDevbox(c runner.Config, logger *slog.Logger, run func(ctx context.Context, dir string, env []string, args []string) (string, error)) *DevboxOptions { if c.PreviewHost != wire.PreviewHostDevbox { return nil } carlos := c.CarlosPath if carlos == "" { if p, err := exec.LookPath("carlos"); err == nil { carlos = p } else if home, err := os.UserHomeDir(); err == nil { carlos = filepath.Join(home, ".local", "bin", "carlos") } } if !filepath.IsAbs(carlos) || c.StateDir == "" { return nil } if info, err := os.Stat(carlos); err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 { return nil } d := &DevboxOptions{Carlos: carlos, State: filepath.Join(c.StateDir, "devbox"), Run: run} if err := os.MkdirAll(d.State, 0o700); err != nil { return nil } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if _, err := d.command(ctx, "list"); err != nil { return nil } if raw, err := os.ReadFile(filepath.Join(d.State, "domain")); err == nil && devboxDomain.MatchString(strings.TrimSpace(string(raw))) { d.Domain = strings.TrimSpace(string(raw)) } if logger != nil { logger.Info("previews pair with CARLOS devbox", "domain", d.Domain) } return d } var errDevboxCommand = errors.New("devbox command refused") // command runs one carlos devbox command from the fixed templates only: // list; share --dir eq-; // unshare eq-. From an empty private directory, with a private HOME // and nothing of the repository; no credential is involved. func (d *DevboxOptions) command(ctx context.Context, verb string, args ...string) (string, error) { switch { case verb == "list" && len(args) == 0: case verb == "share" && len(args) == 3 && args[0] == "--dir" && filepath.IsAbs(args[1]) && devboxTask.MatchString(args[2]): case verb == "unshare" && len(args) == 1 && devboxTask.MatchString(args[0]): default: return "", errDevboxCommand } dir := filepath.Join(d.State, "run") if err := os.MkdirAll(dir, 0o700); err != nil { return "", err } argv := append([]string{"devbox", verb}, args...) env := []string{"HOME=" + dir, "PATH=/usr/bin:/bin"} cctx, cancel := context.WithTimeout(ctx, 2*time.Minute) defer cancel() if d.Run != nil { return d.Run(cctx, dir, env, argv) } cmd := exec.CommandContext(cctx, d.Carlos, argv...) cmd.Dir, cmd.Env = dir, env return runCarlos(cmd) } // carlosError is a carlos command that failed, with what carlos said on // stderr (bounded). type carlosError struct { err error words string } func (c *carlosError) Error() string { return c.err.Error() + ": " + c.words } func (c *carlosError) Unwrap() error { return c.err } // runCarlos runs cmd with stdout bounded at 64 KiB. carlos says why it // refused on stderr, so on failure its words (the first 4 KiB) follow // stdout in the text returned, where a caller looks for a known refusal, // and the error carries them for the log. Words cut at the limit are // never logged: redaction needs the whole text, and a secret cut short // can slip past it. On success stdout is all. func runCarlos(cmd *exec.Cmd) (string, error) { var stderr bytes.Buffer said := &limitWriter{w: &stderr, n: 4 << 10} cmd.Stderr = said out, clipped, err := boundedOutput(cmd, 64<<10) if clipped && err == nil { err = errors.New("carlos output too long") } if words := strings.TrimSpace(strings.ToValidUTF8(stderr.String(), "?")); err != nil && words != "" { logged := words if said.over { logged = "(over 4 KiB on stderr, not logged)" } return string(out) + "\n" + words, &carlosError{err: err, words: logged} } return string(out), err } var devboxTask = regexp.MustCompile(`^eq-[a-z0-9]{1,60}$`) // devboxRecord is what this runner shared for a task: the link's name and // its URL, written before the share (intent) and completed after. type devboxRecord struct { Name string `json:"name"` URL string `json:"url,omitempty"` } func (d *DevboxOptions) record(task string, rec devboxRecord) error { raw, _ := json.Marshal(rec) return os.WriteFile(d.recordPath(task), raw, 0o600) } func (d *DevboxOptions) recorded(task string) (devboxRecord, bool) { var rec devboxRecord raw, err := os.ReadFile(d.recordPath(task)) return rec, err == nil && json.Unmarshal(raw, &rec) == nil && rec.Name == devboxName(task) } // learn takes the domain from a link share printed for name, saved for the // next start, and says so once (the hello carries it). func (d *DevboxOptions) learn(url, name string) bool { dom, ok := strings.CutPrefix(url, "https://"+name+".") if !ok || !devboxDomain.MatchString(dom) || len(dom) > 253 { return false } d.mu.Lock() changed := d.Domain != dom d.Domain = dom d.mu.Unlock() if changed { os.WriteFile(filepath.Join(d.State, "domain"), []byte(dom+"\n"), 0o600) if d.Learnt != nil { d.Learnt() } } return true } // sharedURL is the link carlos printed for name: the one line that is // exactly https://.. func sharedURL(out, name string) (string, bool) { link := regexp.MustCompile(`^https://` + regexp.QuoteMeta(name) + `\.[a-z0-9-]+(\.[a-z0-9-]+)+$`) for _, line := range strings.Split(ansi.ReplaceAllString(out, ""), "\n") { if line = strings.TrimSuffix(strings.TrimSpace(line), "/"); link.MatchString(line) { return line, true } } return "", false } // publishDevbox shares the export as eq- on the paired devbox: one // publish check, the intent recorded, one share (the same name replaces // the previous candidate's copy in place), then the marker. The link is // open to the whole tailnet: Equipo does not know the task creator's // tailnet login, so it passes no --allow, as Paul's own shares do. 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 { d := e.Devbox name := devboxName(r.TaskID) if err := confirm(); err != nil { return stopped(err) } if err := e.O.State.setStepPhase(context.WithoutCancel(ctx), r, phasePreviewPublishing, r.Base, r.Candidate); err != nil { rep.State, rep.Reason, rep.Termination = wire.StepFailed, "preview_failed", true return rep } if err := d.record(r.TaskID, devboxRecord{Name: name}); err != nil { return e.previewDone(rep, r, ex, nil, false, "preview_failed") } out, err := d.command(ctx, "share", "--dir", stage, name) if err != nil { e.logDetail("preview share", err) return e.previewDone(rep, r, ex, nil, false, previewPublishFailure(out)) } url, ok := sharedURL(out, name) if !ok || !d.learn(url, name) { return e.previewDone(rep, r, ex, nil, false, "preview_state") } d.record(r.TaskID, devboxRecord{Name: name, URL: url}) served, why := e.previewServed(ctx, r, mark) if served { // devbox serves its own copy: the export can go (the marker stays // for a restart's reconcile). entries, _ := os.ReadDir(stage) for _, en := range entries { if en.Name() != previewMarker { os.RemoveAll(filepath.Join(stage, en.Name())) } } } return e.previewDone(rep, r, ex, nil, served, why) } // PreviewTaskEnded takes a task's devbox link down once the task is done, // dropped or cancelled (the instance's ForgetTask): only a link this // runner recorded sharing, by the fixed unshare template; the record goes // once the link is gone. A Carloku temporary site expires on its own. func (e *Engineer) PreviewTaskEnded(ctx context.Context, task string) { d := e.Devbox if d == nil || !regexp.MustCompile(`^[a-z0-9]{1,60}$`).MatchString(task) { return } rec, ok := d.recorded(task) if !ok { return } out, err := d.command(ctx, "unshare", rec.Name) if err != nil && !strings.Contains(out, "no link called "+rec.Name) { e.logDetail("preview unshare", err) return } os.Remove(d.recordPath(task)) }