package thin import ( "bufio" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "log/slog" "net/http" "net/url" "os" "os/exec" "path/filepath" "regexp" "sort" "strings" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/wire" "golang.org/x/sys/unix" ) // Publishing a merged website to its confirmed place (oficina/equipo // discussion 11; places spec 2026-11-26, slice 1). The place (console // host, account sqid and name, app) and the mode come from the dispatch, // bound to the person's tap by their destination hash; this runner // deploys there and nowhere else, and never changes the mode. Every // command is one of five fixed templates, run by this runner's process, // never a model's sandbox, from an empty private directory that is also // HOME, with CARLOS_CONFIG naming an empty configuration of the runner's // own: // // carlos accounts list --console (reach) // carlos apps list --account-id --console (taken) // carlos deploy --kind static --account-id --console // --app --channel edge --timeout 5m --version --no-prompt // carlos services create --role deploy --app --rungs edge // --account-id --console // // The person's own login (their ~/.carlos/credentials) is used only for // the reach, a setup (the taken check, the deploy that creates the app, // the mint of its deploy key) and a mint (the existence check and the // mint), each behind its own final check. Every other deploy uses the // app's deploy key: CARLOS_SERVICE_TOKEN and CARLOS_CONSOLE in the // environment, the credentials file named absent. The key's secret is // read from the mint's output by this process, stored 0600 in the // runner's state, outside every sandbox mount, and never logged, // reported or put in argv. // The fixed parts of the deploy. const ( siteChannel = "edge" siteTimeout = "5m" // siteMarker is the file the runner adds beside the export and fetches // back over https to confirm the site serves this export. siteMarker = "equipo-site.json" ) // Step phases of a publish attempt that may have changed CARLOS: after a // restart they only reconcile. const ( phaseSitePublishing = "site_publishing" phaseSiteMinting = "site_minting" ) // SiteOptions is CARLOS as the site host: the carlos binary, the person's // signed-in credential file ("" when none passes its checks: publishing // with held deploy keys still works), and this runner's state for sites. // Client and URL are seams for the tests (nil: a client that follows no // redirect, and the URL deploy printed). type SiteOptions struct { Carlos string Credentials string State string Client *http.Client URL func(app string) string // CLI is the carlos and its version (nil: one for Carlos). CLI *carlosCLI } func (s *SiteOptions) Kind() string { return "carlos" } // App is the app a publish step names, when it is a site's. func (s *SiteOptions) App(app string) string { if wire.ValidSiteApp(app) { return app } return "" } // Origin is where app's marker is fetched: the URL its deploy printed in // this attempt, through the URL seam. func (s *SiteOptions) Origin(app string) string { if s.URL != nil { return s.URL(app) } return "" } func (s *SiteOptions) HTTP() *http.Client { return s.Client } var _ previewHost = (*SiteOptions)(nil) func (s *SiteOptions) cli() *carlosCLI { if s.CLI == nil { s.CLI = &carlosCLI{Bin: s.Carlos} } return s.CLI } // ProbeSite pairs the runner with CARLOS sites when carlos is found and // the runner has a state directory. The person's signed-in credential // (CARLOS_CREDENTIALS, else ~/.carlos/credentials) is used only when it // is this user's own regular file, mode 0600, outside every directory a // sandbox mounts. It runs no carlos command. nil when not. func ProbeSite(c runner.Config, logger *slog.Logger) *SiteOptions { carlos := carlosLookup(c) if carlos == "" || c.StateDir == "" { return nil } s := &SiteOptions{Carlos: carlos, State: filepath.Join(c.StateDir, "site")} if err := os.MkdirAll(s.State, 0o700); err != nil { return nil } creds := os.Getenv("CARLOS_CREDENTIALS") if creds == "" { if home, err := os.UserHomeDir(); err == nil { creds = filepath.Join(home, ".carlos", "credentials") } } if err := siteCredential(c, creds); err == nil { s.Credentials = creds } else if logger != nil && !errors.Is(err, os.ErrNotExist) { logger.Warn("site setup is off: the carlos credential was refused", "reason", err.Error()) } // Deploy keys live under the state: never inside a sandbox mount. place := c place.PreviewCredentialPath = s.State if previewCredentialPlace(place) != nil { return nil } if logger != nil { logger.Info("sites publish through carlos", "login", s.Credentials != "") } return s } // siteCredential checks a credential file without reading it: an // absolute path to a regular file (not a link), mode exactly 0600, owned // by this user, in no directory a sandbox mounts. func siteCredential(c runner.Config, file string) error { if !filepath.IsAbs(file) || filepath.Clean(file) != file { return errPreviewCredentialFile } var st unix.Stat_t if err := unix.Lstat(file, &st); err != nil { if errors.Is(err, unix.ENOENT) { return os.ErrNotExist } return errPreviewCredentialFile } if st.Mode&unix.S_IFMT != unix.S_IFREG || st.Mode&0o7777 != 0o600 || int(st.Uid) != os.Getuid() { return errPreviewCredentialFile } c.PreviewCredentialPath = file return previewCredentialPlace(c) } var ( errSiteCommand = errors.New("site command refused") siteVersion = regexp.MustCompile(`^s-[0-9a-f]{12}-[a-z0-9]{1,40}-[1-9][0-9]{0,8}$`) siteStepID = regexp.MustCompile(`^s_([a-z0-9]{1,40})$`) ) // siteTarget is a dispatch's destination, checked: every part of its // shape and hashing to its Destination. type siteTarget struct { Console, Sqid, Name, App, Mode, DeployName, Destination string } func (t siteTarget) origin() string { return wire.ConsoleOrigin(t.Console) } // targetOf is the dispatch's checked destination, ok false when any part // is out of shape or the hash does not bind them. func targetOf(d *wire.PublishDispatch) (siteTarget, bool) { if d == nil { return siteTarget{}, false } t := siteTarget{Console: d.Console, Sqid: d.Account, Name: d.AccountName, App: d.App, Mode: d.Mode, DeployName: d.DeployName, Destination: d.Destination} if !wire.ValidConsoleHost(t.Console) || !wire.ValidSqid(t.Sqid) || !wire.ValidAccountName(t.Name) || !wire.ValidSiteApp(t.App) || t.Destination != wire.SiteDestination(t.Console, t.Sqid, t.Name, t.App) { return siteTarget{}, false } switch t.Mode { case wire.SitePublish: return t, t.DeployName == "" case wire.SiteSetup, wire.SiteMint: return t, wire.ValidDeployName(t.DeployName) } return siteTarget{}, false } func cleanDir(dir string) bool { return filepath.IsAbs(dir) && filepath.Clean(dir) == dir && dir != "/" && !strings.ContainsAny(dir, "\x00\r\n") } // siteDeployArgs is the deploy template. func siteDeployArgs(t siteTarget, version, dir string) ([]string, error) { if !siteVersion.MatchString(version) || !cleanDir(dir) { return nil, errSiteCommand } return []string{"deploy", "--kind", "static", "--account-id", t.Sqid, "--console", t.origin(), "--app", t.App, "--channel", siteChannel, "--timeout", siteTimeout, "--version", version, "--no-prompt", dir}, nil } // siteListArgs is the read-only command that says whether a name is taken. func siteListArgs(t siteTarget) []string { return []string{"apps", "list", "--account-id", t.Sqid, "--console", t.origin()} } // siteMintArgs is the mint template: an edge-only deploy key for the app. func siteMintArgs(t siteTarget) ([]string, error) { if !wire.ValidDeployName(t.DeployName) { return nil, errSiteCommand } return []string{"services", "create", "--role", "deploy", "--app", t.App, "--rungs", siteChannel, "--account-id", t.Sqid, "--console", t.origin(), t.DeployName}, nil } // siteVersionOf is the version a publish attempt deploys: the merged // commit's first twelve hex digits, the step and the attempt. func siteVersionOf(r stepRow) (string, bool) { m := siteStepID.FindStringSubmatch(r.StepID) if m == nil || !shaPattern.MatchString(r.CandidateSHA) || r.Attempt < 1 { return "", false } v := "s-" + r.CandidateSHA[:12] + "-" + m[1] + "-" + itoa(r.Attempt) return v, siteVersion.MatchString(v) } // runAs says whose authority a command runs with: the person's login, or // an app's deploy key. type runAs struct { login bool key *deployKey } // run runs one fixed command from an empty private directory that is also // HOME, with an empty configuration of the runner's own, no update check, // and either the person's credential or a deploy key, nothing else. func (s *SiteOptions) run(ctx context.Context, as runAs, args []string) (string, error) { if as.login == (as.key != nil) || as.login && s.Credentials == "" { return "", errSiteCommand } config := filepath.Join(s.State, "config", "carlos.json") if err := os.MkdirAll(filepath.Dir(config), 0o700); err != nil { return "", err } if err := os.WriteFile(config, []byte("{}\n"), 0o600); err != nil { return "", err } run := filepath.Join(s.State, "run") if err := os.RemoveAll(run); err != nil { return "", err } if err := os.MkdirAll(run, 0o700); err != nil { return "", err } cctx, cancel := context.WithTimeout(ctx, 7*time.Minute) defer cancel() cmd := exec.CommandContext(cctx, s.Carlos, args...) cmd.Dir = run cmd.Env = []string{"HOME=" + run, "PATH=/usr/bin:/bin", "CARLOS_CONFIG=" + config, "CARLOS_NO_UPDATE_CHECK=1"} if as.login { cmd.Env = append(cmd.Env, "CARLOS_CREDENTIALS="+s.Credentials) } else { cmd.Env = append(cmd.Env, "CARLOS_CREDENTIALS="+filepath.Join(run, "none"), "CARLOS_SERVICE_TOKEN="+as.key.Token, "CARLOS_CONSOLE="+wire.ConsoleOrigin(as.key.Console)) } out, clipped, err := boundedOutput(cmd, 64<<10) if clipped && err == nil { err = errors.New("carlos output too long") } return string(out), err } // siteListed reads `carlos apps list` strictly: a "using" line, then // either "no apps in this account" or app lines (with or without the // header and the region column). present says whether app is listed; ok // false when the output is anything else. func siteListed(out, app string) (present, ok bool) { sc := bufio.NewScanner(strings.NewReader(ansi.ReplaceAllString(out, ""))) var lines []string for sc.Scan() { if l := strings.TrimSpace(sc.Text()); l != "" { lines = append(lines, l) } } if len(lines) == 0 || !strings.HasPrefix(lines[0], "using ") { return false, false } rest := lines[1:] if len(rest) == 1 && rest[0] == "no apps in this account" { return false, true } if len(rest) > 0 { if f := strings.Fields(rest[0]); len(f) >= 2 && f[0] == "APP" && f[1] == "STATE" { rest = rest[1:] } } if len(rest) == 0 { return false, false } for _, l := range rest { f := strings.Fields(l) if len(f) < 2 || !listedApp.MatchString(f[0]) || f[1] != "live" && f[1] != "trashed" { return false, false } present = present || f[0] == app } return present, true } var listedApp = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`) // listed asks the account whether it holds app; ok false when the list // could not be read. func (s *SiteOptions) listed(ctx context.Context, t siteTarget) (present, ok bool) { out, err := s.run(ctx, runAs{login: true}, siteListArgs(t)) if err != nil { return false, false } return siteListed(out, t.App) } // siteURL is the app's address as deploy printed it: the first // https://. it names. func siteURL(out, app string) (string, bool) { m := regexp.MustCompile(`https://` + regexp.QuoteMeta(app) + `\.[a-z0-9-]+(\.[a-z0-9-]+)+`).FindString(ansi.ReplaceAllString(out, "")) return m, m != "" && len(m) <= 200 } // ---- this runner's site state ---------------------------------------------- // deployKey is a deploy key this runner holds: where it was minted for, its // CARLOS name, the secret and its fingerprint. type deployKey struct { Console string `json:"console"` Account string `json:"account"` App string `json:"app"` Name string `json:"name"` Token string `json:"token"` Fingerprint string `json:"fingerprint"` MintedAt time.Time `json:"minted_at"` } // destDir is a destination's folder under dir: console, sqid and app are // each checked, so none can climb out. func destDir(root, console, sqid string) (string, bool) { if !wire.ValidConsoleHost(console) || !wire.ValidSqid(sqid) { return "", false } return filepath.Join(root, console, sqid), true } func (s *SiteOptions) keyPath(t siteTarget) (string, bool) { d, ok := destDir(filepath.Join(s.State, "keys"), t.Console, t.Sqid) return filepath.Join(d, t.App+".json"), ok && wire.ValidSiteApp(t.App) } // lostPath is the intent of one mint, by its key's name: each stays until // a key of that name is held, so a credential whose answer was lost is // never hidden by a later one. func (s *SiteOptions) lostPath(t siteTarget) (string, bool) { d, ok := destDir(filepath.Join(s.State, "keys"), t.Console, t.Sqid) return filepath.Join(d, t.App+"."+t.DeployName+".lost"), ok && wire.ValidSiteApp(t.App) && wire.ValidDeployName(t.DeployName) } func (s *SiteOptions) createdPath(t siteTarget) (string, bool) { d, ok := destDir(filepath.Join(s.State, "created"), t.Console, t.Sqid) return filepath.Join(d, t.App+".json"), ok && wire.ValidSiteApp(t.App) } // key is the deploy key held for exactly this destination. func (s *SiteOptions) key(t siteTarget) (*deployKey, bool) { p, ok := s.keyPath(t) if !ok { return nil, false } raw, err := os.ReadFile(p) if err != nil { return nil, false } var k deployKey if json.Unmarshal(raw, &k) != nil || k.Token == "" { return nil, false } return &k, true } // writeSecret writes raw to p, 0600 in 0700 folders, through a temp file // renamed into place, so a crash leaves the old file or the new, never a // part. func writeSecret(p string, raw []byte) error { if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { return err } f, err := os.CreateTemp(filepath.Dir(p), ".tmp-*") if err != nil { return err } defer os.Remove(f.Name()) if err := f.Chmod(0o600); err != nil { f.Close() return err } if _, err := f.Write(raw); err != nil { f.Close() return err } if err := f.Sync(); err != nil { f.Close() return err } if err := f.Close(); err != nil { return err } return os.Rename(f.Name(), p) } // created records that this runner's setup made the app at t: after its // deploy succeeded, or after one that failed when the account now lists // the app it had just found free. The one proof a mint accepts that the // app is Equipo's. func (s *SiteOptions) created(t siteTarget, task string) error { p, ok := s.createdPath(t) if !ok { return errSiteCommand } raw, _ := json.Marshal(map[string]any{"console": t.Console, "account": t.Sqid, "app": t.App, "task": task, "at": time.Now().UTC()}) return writeSecret(p, raw) } func (s *SiteOptions) madeHere(t siteTarget) bool { p, ok := s.createdPath(t) if !ok { return false } raw, err := os.ReadFile(p) var rec struct{ Console, Account, App string } return err == nil && json.Unmarshal(raw, &rec) == nil && rec.Console == t.Console && rec.Account == t.Sqid && rec.App == t.App } // mintToken is the one secret line a mint prints, and the line naming // what it minted. var ( mintToken = regexp.MustCompile(`^\s*CARLOS_SERVICE_TOKEN=([!-~]{16,512})\s*$`) mintedLine = regexp.MustCompile(`^minted service:([^/\s]+)/(\S+) \(role deploy, app (\S+), rungs ([a-z, ]+)\)$`) ) // mintedKey reads a mint's output: exactly one token line and the line // naming the name, app and edge only. The secret never leaves here but in // the key. func mintedKey(out string, t siteTarget) (string, bool) { token, names := "", 0 okLine := false for _, l := range strings.Split(ansi.ReplaceAllString(out, ""), "\n") { if m := mintToken.FindStringSubmatch(l); m != nil { token, names = m[1], names+1 } if m := mintedLine.FindStringSubmatch(strings.TrimSpace(l)); m != nil { okLine = okLine || m[1] == t.Sqid && m[2] == t.DeployName && m[3] == t.App && m[4] == siteChannel } } return token, names == 1 && okLine } // mint asks CARLOS for the app's deploy key with the person's login, // once: the intent is recorded first (lost until the key is stored), the // secret stored before the intent goes. held false leaves it lost. func (s *SiteOptions) mint(ctx context.Context, t siteTarget) bool { lost, ok := s.lostPath(t) keyFile, ok2 := s.keyPath(t) args, err := siteMintArgs(t) if !ok || !ok2 || err != nil { return false } intent, _ := json.Marshal(map[string]string{"name": t.DeployName}) if writeSecret(lost, intent) != nil { return false } out, err := s.run(ctx, runAs{login: true}, args) token, good := mintedKey(out, t) if err != nil || !good { return false } sum := sha256.Sum256([]byte(token)) raw, _ := json.Marshal(deployKey{Console: t.Console, Account: t.Sqid, App: t.App, Name: t.DeployName, Token: token, Fingerprint: hex.EncodeToString(sum[:])[:16], MintedAt: time.Now().UTC()}) if writeSecret(keyFile, raw) != nil { return false } os.Remove(lost) return true } // deploys are the keys this runner holds and the mints it lost, for the // hello: never a secret. func (s *SiteOptions) deploys() []wire.ReachDeploy { out := []wire.ReachDeploy{} root := filepath.Join(s.State, "keys") consoles, _ := os.ReadDir(root) for _, c := range consoles { sqids, _ := os.ReadDir(filepath.Join(root, c.Name())) for _, q := range sqids { files, _ := os.ReadDir(filepath.Join(root, c.Name(), q.Name())) for _, f := range files { name := f.Name() t := siteTarget{Console: c.Name(), Sqid: q.Name()} switch { case strings.HasSuffix(name, ".json"): t.App = strings.TrimSuffix(name, ".json") if k, ok := s.key(t); ok && k.Console == t.Console && k.Account == t.Sqid && k.App == t.App && wire.ValidDeployName(k.Name) { out = append(out, wire.ReachDeploy{Console: t.Console, Account: t.Sqid, App: t.App, Name: k.Name, Fingerprint: k.Fingerprint}) } case strings.HasSuffix(name, ".lost"): app, keyName, _ := strings.Cut(strings.TrimSuffix(name, ".lost"), ".") t.App = app raw, err := os.ReadFile(filepath.Join(root, c.Name(), q.Name(), name)) var in struct{ Name string } if err != nil || json.Unmarshal(raw, &in) != nil || in.Name != keyName { continue } if k, ok := s.key(t); ok && k.Name == in.Name { // Stored before the intent went (a stop between the // two): the key is held, and the intent is spent. os.Remove(filepath.Join(root, c.Name(), q.Name(), name)) continue } if wire.ValidSiteApp(t.App) && wire.ValidDeployName(in.Name) && wire.ValidConsoleHost(t.Console) && wire.ValidSqid(t.Sqid) { out = append(out, wire.ReachDeploy{Console: t.Console, Account: t.Sqid, App: t.App, Name: in.Name, Lost: true}) } } } } } sort.Slice(out, func(i, j int) bool { a, b := out[i], out[j] return a.Console+a.Account+a.App+a.Name < b.Console+b.Account+b.App+b.Name }) if len(out) > wire.MaxReachDeploys { out = out[:wire.MaxReachDeploys] } return out } // loginConsoles are the console hosts of the live entries in the // person's credential file, read by this process for their names only. func (s *SiteOptions) loginConsoles() []string { if s.Credentials == "" { return nil } raw, err := os.ReadFile(s.Credentials) if err != nil || len(raw) > 1<<20 { return nil } var f struct { Credentials []struct { Console string `json:"console"` ExpiresAt time.Time `json:"expires_at"` } `json:"credentials"` } err = json.Unmarshal(raw, &f) clear(raw) if err != nil { return nil } var out []string for _, c := range f.Credentials { u, err := url.Parse(c.Console) if err != nil || u.Scheme != "https" || u.User != nil || u.Port() != "" || u.Path != "" && u.Path != "/" || u.RawQuery != "" || !wire.ValidConsoleHost(u.Host) { continue } if !c.ExpiresAt.IsZero() && time.Now().After(c.ExpiresAt) { continue } if !containsString(out, u.Host) { out = append(out, u.Host) } } if len(out) > wire.MaxReachLogins { out = out[:wire.MaxReachLogins] } return out } func containsString(list []string, s string) bool { for _, v := range list { if v == s { return true } } return false } // ownedAccounts reads `carlos accounts list`: its NAME SQID ROLE table, // the owner rows, each validated. func ownedAccounts(out string) []wire.ReachAccount { sc := bufio.NewScanner(strings.NewReader(ansi.ReplaceAllString(out, ""))) header := false seen := map[string]bool{} accounts := []wire.ReachAccount{} for sc.Scan() { f := strings.Fields(sc.Text()) if len(f) == 0 { continue } if !header { header = len(f) == 3 && f[0] == "NAME" && f[1] == "SQID" && f[2] == "ROLE" if !header { return []wire.ReachAccount{} } continue } if len(f) != 3 || f[2] != "owner" || !wire.ValidAccountName(f[0]) || !wire.ValidSqid(f[1]) || seen[f[1]] { continue } seen[f[1]] = true accounts = append(accounts, wire.ReachAccount{Name: f[0], Sqid: f[1]}) if len(accounts) == wire.MaxReachAccounts { break } } return accounts } // Reach is what this runner's carlos can do now: the owned accounts on // each console its login reaches (one read-only list each, 20 seconds), // and the deploy keys it holds or lost. nil without a usable carlos. func (s *SiteOptions) Reach(ctx context.Context) *wire.Reach { if s == nil || !s.cli().OK(ctx) { return nil } r := &wire.Reach{Logins: []wire.ReachLogin{}, Deploys: s.deploys()} for _, console := range s.loginConsoles() { lctx, cancel := context.WithTimeout(ctx, 20*time.Second) out, err := s.run(lctx, runAs{login: true}, []string{"accounts", "list", "--console", wire.ConsoleOrigin(console)}) cancel() if err != nil { continue } if accounts := ownedAccounts(out); len(accounts) > 0 { r.Logins = append(r.Logins, wire.ReachLogin{Console: console, Accounts: accounts}) } } return r } // ErrPublishNotBuilt is the instance's refusal of a publish check whose // built report it has not applied yet. var ErrPublishNotBuilt = errors.New("publish not built yet") // Reasons a publish ends with that are its own. const ( reasonPublishSecrets = "publish_secrets" reasonPublishScanner = "publish_scanner" reasonPublishKeyMissing = "publish_key_missing" reasonPublishMintFailed = "publish_mint_failed" reasonPublishAppMissing = "publish_app_missing" reasonPublishAppUnproven = "publish_app_unproven" ) // publishSite runs a publish step in the mode the person's tap allowed: // the merged commit must be on the default branch; its site is exported // from git objects, scanned for secrets and reported built; then, each // behind its own final check for this export and destination, a setup's // taken check, deploy with the login and mint, a mint's existence check, // mint and deploy with the new key, or a publish's deploy with the held // key; then the marker over https says whether it is served. func (e *Engineer) publishSite(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport { rep := judgeReport(r) failed := func(reason string) wire.StepReport { rep.State, rep.Reason, rep.Termination = wire.StepFailed, reason, true return rep } site := e.Site if site == nil || e.ConfirmPublish == nil || e.ConfirmMint == nil { return failed("publish_off") } version, ok := siteVersionOf(r) t, tok := targetOf(r.Publish) if !tok || !validBranch(r.Publish.Into) || strings.HasPrefix(r.Publish.Into, "-") || !ok { return failed("policy_rejected") } stage := filepath.Join(e.root(), stepKey(r), "site") if r.Phase == phaseSitePublishing || r.Phase == phaseSiteMinting { return e.siteReconcile(ctx, rep, r, t, version, stage) } if !site.cli().OK(ctx) { return failed(wire.ReasonCarlosOutdated) } var key *deployKey switch t.Mode { case wire.SitePublish: k, held := site.key(t) if !held { return failed(reasonPublishKeyMissing) } key = k case wire.SiteSetup, wire.SiteMint: if site.Credentials == "" { return failed("publish_off") } } tree, reason, err := e.judgeTree(ctx, r) if err != nil { rep.State, rep.Reason, rep.Termination = wire.StepFailed, reason, true if reason == "withdrawn" || ctx.Err() != nil { rep.State = wire.StepCancelled } return rep } defer os.RemoveAll(tree.GitDir) defer os.RemoveAll(tree.Dir) // The merged commit is on the default branch as this runner fetched it. if _, err := gitRead(ctx, tree.Git, e.Clones.Path(r.Repo), 4096, "merge-base", "--is-ancestor", "--end-of-options", r.CandidateSHA, "refs/heads/"+r.Publish.Into); err != nil { return failed("publish_not_merged") } cfg, err := readPreviewConfig(ctx, tree.Git, tree.GitDir, r.CandidateSHA) if err != nil { return failed("publish_config") } // The project's own files only: no Equipo _headers (a project's own // _headers stays, and is scanned with the rest). ex, err := exportStatic(ctx, tree.Git, tree.GitDir, r.CandidateSHA, cfg.Output, stage, "") switch { case errors.Is(err, errPreviewTooLarge): return failed("publish_too_large") case err != nil: return failed("publish_config") } // The trusted secret scan, on exactly what would be sent: a finding // or a scanner that cannot run refuses the publish. switch e.scanPreview(ctx, stage) { case "": case "preview_secrets": return failed(reasonPublishSecrets) default: return failed(reasonPublishScanner) } mark := previewMark{Task: r.TaskID, Candidate: r.CandidateSHA, Step: r.StepID, Attempt: r.Attempt, Digest: ex.Digest} raw, _ := json.Marshal(mark) if err := os.WriteFile(filepath.Join(stage, siteMarker), raw, 0o600); err != nil { return failed("publish_failed") } rep.Publish = &wire.PublishResult{Phase: wire.PublishBuilt, Digest: ex.Digest, Files: ex.Files, Bytes: ex.Bytes} progress(rep) rep.Publish = nil cancelled := func(err error) wire.StepReport { rep.State, rep.Reason, rep.Termination = wire.StepCancelled, leaseReason(err), true return rep } switch t.Mode { case wire.SiteSetup: // A name this runner has no proof of making here must be free in // the account (another project's, another Equipo's, a person's // own). Between this list and the deploy another app of the name // could still appear: accepted (controller ruling, 2026-11-12); // the six random characters make it impractical. if !site.madeHere(t) { present, ok := site.listed(ctx, t) if !ok || present { return failed("publish_app_taken") } } if err := e.confirmSite(ctx, e.ConfirmPublish, r, ex.Digest, t.Destination); err != nil { return cancelled(err) } done, deployed := e.siteDeploy(ctx, rep, r, t, runAs{login: true}, version, stage, ex, mark, func() { if err := site.created(t, r.TaskID); err != nil { e.log("site record", err) } }) if !deployed { // A deploy that failed half way may have made the app: the // name was free a moment ago, so an app there now is this // deploy's (the accepted list and deploy race) and is recorded // as made here, for a later mint. Anything else records // nothing; attempted is never proven. if present, ok := site.listed(context.WithoutCancel(ctx), t); ok && present { if err := site.created(t, r.TaskID); err != nil { e.log("site record", err) } } return done } // Right after the app exists: its deploy key, behind its own check. if err := e.confirmSite(ctx, e.ConfirmMint, r, ex.Digest, t.Destination); err == nil { if e.O.State.setStepPhase(context.WithoutCancel(ctx), r, phaseSiteMinting, r.Base, r.Candidate) == nil { done.Publish.DeployHeld = site.mint(ctx, t) } } e.siteChanged() return done case wire.SiteMint: if !site.madeHere(t) { present, ok := site.listed(ctx, t) switch { case ok && !present: return failed(reasonPublishAppMissing) case ok: return failed(reasonPublishAppUnproven) } return failed("publish_failed") } if err := e.confirmSite(ctx, e.ConfirmMint, r, ex.Digest, t.Destination); err != nil { return cancelled(err) } if err := e.O.State.setStepPhase(context.WithoutCancel(ctx), r, phaseSiteMinting, r.Base, r.Candidate); err != nil { return failed("publish_failed") } held := site.mint(ctx, t) e.siteChanged() if !held { return failed(reasonPublishMintFailed) } k, _ := site.key(t) key = k } if err := e.confirmSite(ctx, e.ConfirmPublish, r, ex.Digest, t.Destination); err != nil { return cancelled(err) } done, _ := e.siteDeploy(ctx, rep, r, t, runAs{key: key}, version, stage, ex, mark, nil) done.Publish.DeployHeld = true return done } // siteChanged makes the next hello carry the runner's new reach. func (e *Engineer) siteChanged() { if e.SiteChanged != nil { e.SiteChanged() } } // siteDeploy marks the attempt as one that may change CARLOS, deploys, // and says whether the marker answers. deployed reports the deploy // command succeeded. func (e *Engineer) siteDeploy(ctx context.Context, rep wire.StepReport, r stepRow, t siteTarget, as runAs, version, stage string, ex previewExport, mark previewMark, deployed func()) (wire.StepReport, bool) { site := e.Site if err := e.O.State.setStepPhase(context.WithoutCancel(ctx), r, phaseSitePublishing, r.Base, r.Candidate); err != nil { rep.State, rep.Reason, rep.Termination = wire.StepFailed, "publish_failed", true return rep, false } args, err := siteDeployArgs(t, version, stage) out := "" if err == nil { out, err = site.run(ctx, as, args) } // CARLOS keeps its own copy: the export can go (the marker stays for // a restart's reconcile). if entries, rerr := os.ReadDir(stage); rerr == nil { for _, en := range entries { if en.Name() != siteMarker { os.RemoveAll(filepath.Join(stage, en.Name())) } } } url, _ := siteURL(out, t.App) if url != "" { os.WriteFile(filepath.Join(filepath.Dir(stage), "site-url"), []byte(url), 0o600) } if err != nil { e.log("site deploy", errors.New("carlos deploy failed")) done := e.siteDone(rep, t.App, version, ex, url, false) done.Reason = "publish_failed" return done, false } if deployed != nil { // Before anything slow: a stop while the marker is polled must not // lose what the deploy proved. deployed() } served := url != "" && e.markerServed(ctx, siteAt{site, url}, t.App, siteMarker, mark) return e.siteDone(rep, t.App, version, ex, url, served), true } // siteReconcile settles an attempt that restarted after it may have // changed CARLOS: nothing is rebuilt, sent or minted again. The marker // over the recorded URL decides published or unconfirmed; a mint that had // not stored its key stays lost. A mint attempt that restarted before its // deploy ends failed: nothing of the site was sent. func (e *Engineer) siteReconcile(ctx context.Context, rep wire.StepReport, r stepRow, t siteTarget, version, stage string) wire.StepReport { site := e.Site _, held := site.key(t) if r.Phase == phaseSiteMinting && t.Mode == wire.SiteMint { rep.State, rep.Reason, rep.Termination = wire.StepFailed, reasonPublishMintFailed, true return rep } var mark previewMark raw, err := os.ReadFile(filepath.Join(stage, siteMarker)) if err != nil || json.Unmarshal(raw, &mark) != nil { done := e.siteDone(rep, t.App, version, previewExport{}, "", false) done.Publish.DeployHeld = held return done } url := "" if b, err := os.ReadFile(filepath.Join(filepath.Dir(stage), "site-url")); err == nil { if u, ok := siteURL(string(b), t.App); ok { url = u } } served := url != "" && e.markerServed(context.WithoutCancel(ctx), siteAt{site, url}, t.App, siteMarker, mark) if served && t.Mode == wire.SiteSetup && !site.madeHere(t) { // This attempt's own marker answers from the app's address: the // setup's deploy made it (a stop had come before the record). if err := site.created(t, r.TaskID); err != nil { e.log("site record", err) } } done := e.siteDone(rep, t.App, version, previewExport{Digest: mark.Digest}, url, served) done.Publish.DeployHeld = held return done } // siteAt is the site host with the marker fetched from the URL this // attempt's deploy printed (the URL seam first, for the tests). type siteAt struct { *SiteOptions url string } func (s siteAt) Origin(app string) string { if s.SiteOptions.URL != nil { return s.SiteOptions.URL(app) } return strings.TrimSuffix(s.url, "/") } // confirmSite is the instance's decision right before a mint or a deploy, // for this export's digest and destination. The built report travels on // the outbox: a refusal for that alone is asked again, briefly. func (e *Engineer) confirmSite(ctx context.Context, check func(context.Context, string, int64, string, string) error, r stepRow, digest, destination string) error { var err error for i := 0; i < 10; i++ { if err = check(ctx, r.StepID, r.Attempt, digest, destination); !errors.Is(err, ErrPublishNotBuilt) { return err } select { case <-ctx.Done(): return ctx.Err() case <-time.After(previewBuiltWait): } } return err } // siteDone ends the step: published when the marker answered with this // export over the URL deploy printed, else unconfirmed (never retried). func (e *Engineer) siteDone(rep wire.StepReport, app, version string, ex previewExport, url string, served bool) wire.StepReport { rep.State, rep.Termination = wire.StepDone, true rep.Publish = &wire.PublishResult{Phase: wire.PublishDone, App: app, Version: version, Digest: ex.Digest, Files: ex.Files, Bytes: ex.Bytes, Outcome: wire.PublishUnconfirmed} if url != "" { rep.Publish.URL = url + "/" } if served { rep.Publish.Outcome = wire.PublishPublished } return rep }