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 "bufio"
5 "context"
6 "crypto/sha256"
7 "encoding/hex"
8 "encoding/json"
9 "errors"
10 "log/slog"
11 "net/http"
12 "net/url"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "regexp"
17 "sort"
18 "strings"
19 "time"
20
21 "amadan.net/oficina/equipo/internal/runner"
22 "amadan.net/oficina/equipo/internal/wire"
23 "golang.org/x/sys/unix"
24)
25
26// Publishing a merged website to its confirmed place (oficina/equipo
27// discussion 11; places spec 2026-11-26, slice 1). The place (console
28// host, account sqid and name, app) and the mode come from the dispatch,
29// bound to the person's tap by their destination hash; this runner
30// deploys there and nowhere else, and never changes the mode. Every
31// command is one of five fixed templates, run by this runner's process,
32// never a model's sandbox, from an empty private directory that is also
33// HOME, with CARLOS_CONFIG naming an empty configuration of the runner's
34// own:
35//
36// carlos accounts list --console <o> (reach)
37// carlos apps list --account-id <sqid> --console <o> (taken)
38// carlos deploy --kind static --account-id <sqid> --console <o>
39// --app <app> --channel edge --timeout 5m --version <v> --no-prompt <export>
40// carlos services create --role deploy --app <app> --rungs edge
41// --account-id <sqid> --console <o> <name>
42//
43// The person's own login (their ~/.carlos/credentials) is used only for
44// the reach, a setup (the taken check, the deploy that creates the app,
45// the mint of its deploy key) and a mint (the existence check and the
46// mint), each behind its own final check. Every other deploy uses the
47// app's deploy key: CARLOS_SERVICE_TOKEN and CARLOS_CONSOLE in the
48// environment, the credentials file named absent. The key's secret is
49// read from the mint's output by this process, stored 0600 in the
50// runner's state, outside every sandbox mount, and never logged,
51// reported or put in argv.
52
53// The fixed parts of the deploy.
54const (
55 siteChannel = "edge"
56 siteTimeout = "5m"
57 // siteMarker is the file the runner adds beside the export and fetches
58 // back over https to confirm the site serves this export.
59 siteMarker = "equipo-site.json"
60)
61
62// Step phases of a publish attempt that may have changed CARLOS: after a
63// restart they only reconcile.
64const (
65 phaseSitePublishing = "site_publishing"
66 phaseSiteMinting = "site_minting"
67)
68
69// SiteOptions is CARLOS as the site host: the carlos binary, the person's
70// signed-in credential file ("" when none passes its checks: publishing
71// with held deploy keys still works), and this runner's state for sites.
72// Client and URL are seams for the tests (nil: a client that follows no
73// redirect, and the URL deploy printed).
74type SiteOptions struct {
75 Carlos string
76 Credentials string
77 State string
78 Client *http.Client
79 URL func(app string) string
80 // CLI is the carlos and its version (nil: one for Carlos).
81 CLI *carlosCLI
82}
83
84func (s *SiteOptions) Kind() string { return "carlos" }
85
86// App is the app a publish step names, when it is a site's.
87func (s *SiteOptions) App(app string) string {
88 if wire.ValidSiteApp(app) {
89 return app
90 }
91 return ""
92}
93
94// Origin is where app's marker is fetched: the URL its deploy printed in
95// this attempt, through the URL seam.
96func (s *SiteOptions) Origin(app string) string {
97 if s.URL != nil {
98 return s.URL(app)
99 }
100 return ""
101}
102
103func (s *SiteOptions) HTTP() *http.Client { return s.Client }
104
105var _ previewHost = (*SiteOptions)(nil)
106
107func (s *SiteOptions) cli() *carlosCLI {
108 if s.CLI == nil {
109 s.CLI = &carlosCLI{Bin: s.Carlos}
110 }
111 return s.CLI
112}
113
114// ProbeSite pairs the runner with CARLOS sites when carlos is found and
115// the runner has a state directory. The person's signed-in credential
116// (CARLOS_CREDENTIALS, else ~/.carlos/credentials) is used only when it
117// is this user's own regular file, mode 0600, outside every directory a
118// sandbox mounts. It runs no carlos command. nil when not.
119func ProbeSite(c runner.Config, logger *slog.Logger) *SiteOptions {
120 carlos := carlosLookup(c)
121 if carlos == "" || c.StateDir == "" {
122 return nil
123 }
124 s := &SiteOptions{Carlos: carlos, State: filepath.Join(c.StateDir, "site")}
125 if err := os.MkdirAll(s.State, 0o700); err != nil {
126 return nil
127 }
128 creds := os.Getenv("CARLOS_CREDENTIALS")
129 if creds == "" {
130 if home, err := os.UserHomeDir(); err == nil {
131 creds = filepath.Join(home, ".carlos", "credentials")
132 }
133 }
134 if err := siteCredential(c, creds); err == nil {
135 s.Credentials = creds
136 } else if logger != nil && !errors.Is(err, os.ErrNotExist) {
137 logger.Warn("site setup is off: the carlos credential was refused", "reason", err.Error())
138 }
139 // Deploy keys live under the state: never inside a sandbox mount.
140 place := c
141 place.PreviewCredentialPath = s.State
142 if previewCredentialPlace(place) != nil {
143 return nil
144 }
145 if logger != nil {
146 logger.Info("sites publish through carlos", "login", s.Credentials != "")
147 }
148 return s
149}
150
151// siteCredential checks a credential file without reading it: an
152// absolute path to a regular file (not a link), mode exactly 0600, owned
153// by this user, in no directory a sandbox mounts.
154func siteCredential(c runner.Config, file string) error {
155 if !filepath.IsAbs(file) || filepath.Clean(file) != file {
156 return errPreviewCredentialFile
157 }
158 var st unix.Stat_t
159 if err := unix.Lstat(file, &st); err != nil {
160 if errors.Is(err, unix.ENOENT) {
161 return os.ErrNotExist
162 }
163 return errPreviewCredentialFile
164 }
165 if st.Mode&unix.S_IFMT != unix.S_IFREG || st.Mode&0o7777 != 0o600 || int(st.Uid) != os.Getuid() {
166 return errPreviewCredentialFile
167 }
168 c.PreviewCredentialPath = file
169 return previewCredentialPlace(c)
170}
171
172var (
173 errSiteCommand = errors.New("site command refused")
174 siteVersion = regexp.MustCompile(`^s-[0-9a-f]{12}-[a-z0-9]{1,40}-[1-9][0-9]{0,8}$`)
175 siteStepID = regexp.MustCompile(`^s_([a-z0-9]{1,40})$`)
176)
177
178// siteTarget is a dispatch's destination, checked: every part of its
179// shape and hashing to its Destination.
180type siteTarget struct {
181 Console, Sqid, Name, App, Mode, DeployName, Destination string
182}
183
184func (t siteTarget) origin() string { return wire.ConsoleOrigin(t.Console) }
185
186// targetOf is the dispatch's checked destination, ok false when any part
187// is out of shape or the hash does not bind them.
188func targetOf(d *wire.PublishDispatch) (siteTarget, bool) {
189 if d == nil {
190 return siteTarget{}, false
191 }
192 t := siteTarget{Console: d.Console, Sqid: d.Account, Name: d.AccountName, App: d.App, Mode: d.Mode, DeployName: d.DeployName, Destination: d.Destination}
193 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) {
194 return siteTarget{}, false
195 }
196 switch t.Mode {
197 case wire.SitePublish:
198 return t, t.DeployName == ""
199 case wire.SiteSetup, wire.SiteMint:
200 return t, wire.ValidDeployName(t.DeployName)
201 }
202 return siteTarget{}, false
203}
204
205func cleanDir(dir string) bool {
206 return filepath.IsAbs(dir) && filepath.Clean(dir) == dir && dir != "/" && !strings.ContainsAny(dir, "\x00\r\n")
207}
208
209// siteDeployArgs is the deploy template.
210func siteDeployArgs(t siteTarget, version, dir string) ([]string, error) {
211 if !siteVersion.MatchString(version) || !cleanDir(dir) {
212 return nil, errSiteCommand
213 }
214 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
215}
216
217// siteListArgs is the read-only command that says whether a name is taken.
218func siteListArgs(t siteTarget) []string {
219 return []string{"apps", "list", "--account-id", t.Sqid, "--console", t.origin()}
220}
221
222// siteMintArgs is the mint template: an edge-only deploy key for the app.
223func siteMintArgs(t siteTarget) ([]string, error) {
224 if !wire.ValidDeployName(t.DeployName) {
225 return nil, errSiteCommand
226 }
227 return []string{"services", "create", "--role", "deploy", "--app", t.App, "--rungs", siteChannel, "--account-id", t.Sqid, "--console", t.origin(), t.DeployName}, nil
228}
229
230// siteVersionOf is the version a publish attempt deploys: the merged
231// commit's first twelve hex digits, the step and the attempt.
232func siteVersionOf(r stepRow) (string, bool) {
233 m := siteStepID.FindStringSubmatch(r.StepID)
234 if m == nil || !shaPattern.MatchString(r.CandidateSHA) || r.Attempt < 1 {
235 return "", false
236 }
237 v := "s-" + r.CandidateSHA[:12] + "-" + m[1] + "-" + itoa(r.Attempt)
238 return v, siteVersion.MatchString(v)
239}
240
241// runAs says whose authority a command runs with: the person's login, or
242// an app's deploy key.
243type runAs struct {
244 login bool
245 key *deployKey
246}
247
248// run runs one fixed command from an empty private directory that is also
249// HOME, with an empty configuration of the runner's own, no update check,
250// and either the person's credential or a deploy key, nothing else.
251func (s *SiteOptions) run(ctx context.Context, as runAs, args []string) (string, error) {
252 if as.login == (as.key != nil) || as.login && s.Credentials == "" {
253 return "", errSiteCommand
254 }
255 config := filepath.Join(s.State, "config", "carlos.json")
256 if err := os.MkdirAll(filepath.Dir(config), 0o700); err != nil {
257 return "", err
258 }
259 if err := os.WriteFile(config, []byte("{}\n"), 0o600); err != nil {
260 return "", err
261 }
262 run := filepath.Join(s.State, "run")
263 if err := os.RemoveAll(run); err != nil {
264 return "", err
265 }
266 if err := os.MkdirAll(run, 0o700); err != nil {
267 return "", err
268 }
269 cctx, cancel := context.WithTimeout(ctx, 7*time.Minute)
270 defer cancel()
271 cmd := exec.CommandContext(cctx, s.Carlos, args...)
272 cmd.Dir = run
273 cmd.Env = []string{"HOME=" + run, "PATH=/usr/bin:/bin", "CARLOS_CONFIG=" + config, "CARLOS_NO_UPDATE_CHECK=1"}
274 if as.login {
275 cmd.Env = append(cmd.Env, "CARLOS_CREDENTIALS="+s.Credentials)
276 } else {
277 cmd.Env = append(cmd.Env, "CARLOS_CREDENTIALS="+filepath.Join(run, "none"), "CARLOS_SERVICE_TOKEN="+as.key.Token, "CARLOS_CONSOLE="+wire.ConsoleOrigin(as.key.Console))
278 }
279 out, clipped, err := boundedOutput(cmd, 64<<10)
280 if clipped && err == nil {
281 err = errors.New("carlos output too long")
282 }
283 return string(out), err
284}
285
286// siteListed reads `carlos apps list` strictly: a "using" line, then
287// either "no apps in this account" or app lines (with or without the
288// header and the region column). present says whether app is listed; ok
289// false when the output is anything else.
290func siteListed(out, app string) (present, ok bool) {
291 sc := bufio.NewScanner(strings.NewReader(ansi.ReplaceAllString(out, "")))
292 var lines []string
293 for sc.Scan() {
294 if l := strings.TrimSpace(sc.Text()); l != "" {
295 lines = append(lines, l)
296 }
297 }
298 if len(lines) == 0 || !strings.HasPrefix(lines[0], "using ") {
299 return false, false
300 }
301 rest := lines[1:]
302 if len(rest) == 1 && rest[0] == "no apps in this account" {
303 return false, true
304 }
305 if len(rest) > 0 {
306 if f := strings.Fields(rest[0]); len(f) >= 2 && f[0] == "APP" && f[1] == "STATE" {
307 rest = rest[1:]
308 }
309 }
310 if len(rest) == 0 {
311 return false, false
312 }
313 for _, l := range rest {
314 f := strings.Fields(l)
315 if len(f) < 2 || !listedApp.MatchString(f[0]) || f[1] != "live" && f[1] != "trashed" {
316 return false, false
317 }
318 present = present || f[0] == app
319 }
320 return present, true
321}
322
323var listedApp = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`)
324
325// listed asks the account whether it holds app; ok false when the list
326// could not be read.
327func (s *SiteOptions) listed(ctx context.Context, t siteTarget) (present, ok bool) {
328 out, err := s.run(ctx, runAs{login: true}, siteListArgs(t))
329 if err != nil {
330 return false, false
331 }
332 return siteListed(out, t.App)
333}
334
335// siteURL is the app's address as deploy printed it: the first
336// https://<app>.<domain> it names.
337func siteURL(out, app string) (string, bool) {
338 m := regexp.MustCompile(`https://` + regexp.QuoteMeta(app) + `\.[a-z0-9-]+(\.[a-z0-9-]+)+`).FindString(ansi.ReplaceAllString(out, ""))
339 return m, m != "" && len(m) <= 200
340}
341
342// ---- this runner's site state ----------------------------------------------
343
344// deployKey is a deploy key this runner holds: where it was minted for, its
345// CARLOS name, the secret and its fingerprint.
346type deployKey struct {
347 Console string `json:"console"`
348 Account string `json:"account"`
349 App string `json:"app"`
350 Name string `json:"name"`
351 Token string `json:"token"`
352 Fingerprint string `json:"fingerprint"`
353 MintedAt time.Time `json:"minted_at"`
354}
355
356// destDir is a destination's folder under dir: console, sqid and app are
357// each checked, so none can climb out.
358func destDir(root, console, sqid string) (string, bool) {
359 if !wire.ValidConsoleHost(console) || !wire.ValidSqid(sqid) {
360 return "", false
361 }
362 return filepath.Join(root, console, sqid), true
363}
364
365func (s *SiteOptions) keyPath(t siteTarget) (string, bool) {
366 d, ok := destDir(filepath.Join(s.State, "keys"), t.Console, t.Sqid)
367 return filepath.Join(d, t.App+".json"), ok && wire.ValidSiteApp(t.App)
368}
369
370// lostPath is the intent of one mint, by its key's name: each stays until
371// a key of that name is held, so a credential whose answer was lost is
372// never hidden by a later one.
373func (s *SiteOptions) lostPath(t siteTarget) (string, bool) {
374 d, ok := destDir(filepath.Join(s.State, "keys"), t.Console, t.Sqid)
375 return filepath.Join(d, t.App+"."+t.DeployName+".lost"), ok && wire.ValidSiteApp(t.App) && wire.ValidDeployName(t.DeployName)
376}
377
378func (s *SiteOptions) createdPath(t siteTarget) (string, bool) {
379 d, ok := destDir(filepath.Join(s.State, "created"), t.Console, t.Sqid)
380 return filepath.Join(d, t.App+".json"), ok && wire.ValidSiteApp(t.App)
381}
382
383// key is the deploy key held for exactly this destination.
384func (s *SiteOptions) key(t siteTarget) (*deployKey, bool) {
385 p, ok := s.keyPath(t)
386 if !ok {
387 return nil, false
388 }
389 raw, err := os.ReadFile(p)
390 if err != nil {
391 return nil, false
392 }
393 var k deployKey
394 if json.Unmarshal(raw, &k) != nil || k.Token == "" {
395 return nil, false
396 }
397 return &k, true
398}
399
400// writeSecret writes raw to p, 0600 in 0700 folders, through a temp file
401// renamed into place, so a crash leaves the old file or the new, never a
402// part.
403func writeSecret(p string, raw []byte) error {
404 if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
405 return err
406 }
407 f, err := os.CreateTemp(filepath.Dir(p), ".tmp-*")
408 if err != nil {
409 return err
410 }
411 defer os.Remove(f.Name())
412 if err := f.Chmod(0o600); err != nil {
413 f.Close()
414 return err
415 }
416 if _, err := f.Write(raw); err != nil {
417 f.Close()
418 return err
419 }
420 if err := f.Sync(); err != nil {
421 f.Close()
422 return err
423 }
424 if err := f.Close(); err != nil {
425 return err
426 }
427 return os.Rename(f.Name(), p)
428}
429
430// created records that this runner's setup made the app at t: after its
431// deploy succeeded, or after one that failed when the account now lists
432// the app it had just found free. The one proof a mint accepts that the
433// app is Equipo's.
434func (s *SiteOptions) created(t siteTarget, task string) error {
435 p, ok := s.createdPath(t)
436 if !ok {
437 return errSiteCommand
438 }
439 raw, _ := json.Marshal(map[string]any{"console": t.Console, "account": t.Sqid, "app": t.App, "task": task, "at": time.Now().UTC()})
440 return writeSecret(p, raw)
441}
442
443func (s *SiteOptions) madeHere(t siteTarget) bool {
444 p, ok := s.createdPath(t)
445 if !ok {
446 return false
447 }
448 raw, err := os.ReadFile(p)
449 var rec struct{ Console, Account, App string }
450 return err == nil && json.Unmarshal(raw, &rec) == nil && rec.Console == t.Console && rec.Account == t.Sqid && rec.App == t.App
451}
452
453// mintToken is the one secret line a mint prints, and the line naming
454// what it minted.
455var (
456 mintToken = regexp.MustCompile(`^\s*CARLOS_SERVICE_TOKEN=([!-~]{16,512})\s*$`)
457 mintedLine = regexp.MustCompile(`^minted service:([^/\s]+)/(\S+) \(role deploy, app (\S+), rungs ([a-z, ]+)\)$`)
458)
459
460// mintedKey reads a mint's output: exactly one token line and the line
461// naming the name, app and edge only. The secret never leaves here but in
462// the key.
463func mintedKey(out string, t siteTarget) (string, bool) {
464 token, names := "", 0
465 okLine := false
466 for _, l := range strings.Split(ansi.ReplaceAllString(out, ""), "\n") {
467 if m := mintToken.FindStringSubmatch(l); m != nil {
468 token, names = m[1], names+1
469 }
470 if m := mintedLine.FindStringSubmatch(strings.TrimSpace(l)); m != nil {
471 okLine = okLine || m[1] == t.Sqid && m[2] == t.DeployName && m[3] == t.App && m[4] == siteChannel
472 }
473 }
474 return token, names == 1 && okLine
475}
476
477// mint asks CARLOS for the app's deploy key with the person's login,
478// once: the intent is recorded first (lost until the key is stored), the
479// secret stored before the intent goes. held false leaves it lost.
480func (s *SiteOptions) mint(ctx context.Context, t siteTarget) bool {
481 lost, ok := s.lostPath(t)
482 keyFile, ok2 := s.keyPath(t)
483 args, err := siteMintArgs(t)
484 if !ok || !ok2 || err != nil {
485 return false
486 }
487 intent, _ := json.Marshal(map[string]string{"name": t.DeployName})
488 if writeSecret(lost, intent) != nil {
489 return false
490 }
491 out, err := s.run(ctx, runAs{login: true}, args)
492 token, good := mintedKey(out, t)
493 if err != nil || !good {
494 return false
495 }
496 sum := sha256.Sum256([]byte(token))
497 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()})
498 if writeSecret(keyFile, raw) != nil {
499 return false
500 }
501 os.Remove(lost)
502 return true
503}
504
505// deploys are the keys this runner holds and the mints it lost, for the
506// hello: never a secret.
507func (s *SiteOptions) deploys() []wire.ReachDeploy {
508 out := []wire.ReachDeploy{}
509 root := filepath.Join(s.State, "keys")
510 consoles, _ := os.ReadDir(root)
511 for _, c := range consoles {
512 sqids, _ := os.ReadDir(filepath.Join(root, c.Name()))
513 for _, q := range sqids {
514 files, _ := os.ReadDir(filepath.Join(root, c.Name(), q.Name()))
515 for _, f := range files {
516 name := f.Name()
517 t := siteTarget{Console: c.Name(), Sqid: q.Name()}
518 switch {
519 case strings.HasSuffix(name, ".json"):
520 t.App = strings.TrimSuffix(name, ".json")
521 if k, ok := s.key(t); ok && k.Console == t.Console && k.Account == t.Sqid && k.App == t.App && wire.ValidDeployName(k.Name) {
522 out = append(out, wire.ReachDeploy{Console: t.Console, Account: t.Sqid, App: t.App, Name: k.Name, Fingerprint: k.Fingerprint})
523 }
524 case strings.HasSuffix(name, ".lost"):
525 app, keyName, _ := strings.Cut(strings.TrimSuffix(name, ".lost"), ".")
526 t.App = app
527 raw, err := os.ReadFile(filepath.Join(root, c.Name(), q.Name(), name))
528 var in struct{ Name string }
529 if err != nil || json.Unmarshal(raw, &in) != nil || in.Name != keyName {
530 continue
531 }
532 if k, ok := s.key(t); ok && k.Name == in.Name {
533 // Stored before the intent went (a stop between the
534 // two): the key is held, and the intent is spent.
535 os.Remove(filepath.Join(root, c.Name(), q.Name(), name))
536 continue
537 }
538 if wire.ValidSiteApp(t.App) && wire.ValidDeployName(in.Name) && wire.ValidConsoleHost(t.Console) && wire.ValidSqid(t.Sqid) {
539 out = append(out, wire.ReachDeploy{Console: t.Console, Account: t.Sqid, App: t.App, Name: in.Name, Lost: true})
540 }
541 }
542 }
543 }
544 }
545 sort.Slice(out, func(i, j int) bool {
546 a, b := out[i], out[j]
547 return a.Console+a.Account+a.App+a.Name < b.Console+b.Account+b.App+b.Name
548 })
549 if len(out) > wire.MaxReachDeploys {
550 out = out[:wire.MaxReachDeploys]
551 }
552 return out
553}
554
555// loginConsoles are the console hosts of the live entries in the
556// person's credential file, read by this process for their names only.
557func (s *SiteOptions) loginConsoles() []string {
558 if s.Credentials == "" {
559 return nil
560 }
561 raw, err := os.ReadFile(s.Credentials)
562 if err != nil || len(raw) > 1<<20 {
563 return nil
564 }
565 var f struct {
566 Credentials []struct {
567 Console string `json:"console"`
568 ExpiresAt time.Time `json:"expires_at"`
569 } `json:"credentials"`
570 }
571 err = json.Unmarshal(raw, &f)
572 clear(raw)
573 if err != nil {
574 return nil
575 }
576 var out []string
577 for _, c := range f.Credentials {
578 u, err := url.Parse(c.Console)
579 if err != nil || u.Scheme != "https" || u.User != nil || u.Port() != "" || u.Path != "" && u.Path != "/" || u.RawQuery != "" || !wire.ValidConsoleHost(u.Host) {
580 continue
581 }
582 if !c.ExpiresAt.IsZero() && time.Now().After(c.ExpiresAt) {
583 continue
584 }
585 if !containsString(out, u.Host) {
586 out = append(out, u.Host)
587 }
588 }
589 if len(out) > wire.MaxReachLogins {
590 out = out[:wire.MaxReachLogins]
591 }
592 return out
593}
594
595func containsString(list []string, s string) bool {
596 for _, v := range list {
597 if v == s {
598 return true
599 }
600 }
601 return false
602}
603
604// ownedAccounts reads `carlos accounts list`: its NAME SQID ROLE table,
605// the owner rows, each validated.
606func ownedAccounts(out string) []wire.ReachAccount {
607 sc := bufio.NewScanner(strings.NewReader(ansi.ReplaceAllString(out, "")))
608 header := false
609 seen := map[string]bool{}
610 accounts := []wire.ReachAccount{}
611 for sc.Scan() {
612 f := strings.Fields(sc.Text())
613 if len(f) == 0 {
614 continue
615 }
616 if !header {
617 header = len(f) == 3 && f[0] == "NAME" && f[1] == "SQID" && f[2] == "ROLE"
618 if !header {
619 return []wire.ReachAccount{}
620 }
621 continue
622 }
623 if len(f) != 3 || f[2] != "owner" || !wire.ValidAccountName(f[0]) || !wire.ValidSqid(f[1]) || seen[f[1]] {
624 continue
625 }
626 seen[f[1]] = true
627 accounts = append(accounts, wire.ReachAccount{Name: f[0], Sqid: f[1]})
628 if len(accounts) == wire.MaxReachAccounts {
629 break
630 }
631 }
632 return accounts
633}
634
635// Reach is what this runner's carlos can do now: the owned accounts on
636// each console its login reaches (one read-only list each, 20 seconds),
637// and the deploy keys it holds or lost. nil without a usable carlos.
638func (s *SiteOptions) Reach(ctx context.Context) *wire.Reach {
639 if s == nil || !s.cli().OK(ctx) {
640 return nil
641 }
642 r := &wire.Reach{Logins: []wire.ReachLogin{}, Deploys: s.deploys()}
643 for _, console := range s.loginConsoles() {
644 lctx, cancel := context.WithTimeout(ctx, 20*time.Second)
645 out, err := s.run(lctx, runAs{login: true}, []string{"accounts", "list", "--console", wire.ConsoleOrigin(console)})
646 cancel()
647 if err != nil {
648 continue
649 }
650 if accounts := ownedAccounts(out); len(accounts) > 0 {
651 r.Logins = append(r.Logins, wire.ReachLogin{Console: console, Accounts: accounts})
652 }
653 }
654 return r
655}
656
657// ErrPublishNotBuilt is the instance's refusal of a publish check whose
658// built report it has not applied yet.
659var ErrPublishNotBuilt = errors.New("publish not built yet")
660
661// Reasons a publish ends with that are its own.
662const (
663 reasonPublishSecrets = "publish_secrets"
664 reasonPublishScanner = "publish_scanner"
665 reasonPublishKeyMissing = "publish_key_missing"
666 reasonPublishMintFailed = "publish_mint_failed"
667 reasonPublishAppMissing = "publish_app_missing"
668 reasonPublishAppUnproven = "publish_app_unproven"
669)
670
671// publishSite runs a publish step in the mode the person's tap allowed:
672// the merged commit must be on the default branch; its site is exported
673// from git objects, scanned for secrets and reported built; then, each
674// behind its own final check for this export and destination, a setup's
675// taken check, deploy with the login and mint, a mint's existence check,
676// mint and deploy with the new key, or a publish's deploy with the held
677// key; then the marker over https says whether it is served.
678func (e *Engineer) publishSite(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport {
679 rep := judgeReport(r)
680 failed := func(reason string) wire.StepReport {
681 rep.State, rep.Reason, rep.Termination = wire.StepFailed, reason, true
682 return rep
683 }
684 site := e.Site
685 if site == nil || e.ConfirmPublish == nil || e.ConfirmMint == nil {
686 return failed("publish_off")
687 }
688 version, ok := siteVersionOf(r)
689 t, tok := targetOf(r.Publish)
690 if !tok || !validBranch(r.Publish.Into) || strings.HasPrefix(r.Publish.Into, "-") || !ok {
691 return failed("policy_rejected")
692 }
693 stage := filepath.Join(e.root(), stepKey(r), "site")
694 if r.Phase == phaseSitePublishing || r.Phase == phaseSiteMinting {
695 return e.siteReconcile(ctx, rep, r, t, version, stage)
696 }
697 if !site.cli().OK(ctx) {
698 return failed(wire.ReasonCarlosOutdated)
699 }
700 var key *deployKey
701 switch t.Mode {
702 case wire.SitePublish:
703 k, held := site.key(t)
704 if !held {
705 return failed(reasonPublishKeyMissing)
706 }
707 key = k
708 case wire.SiteSetup, wire.SiteMint:
709 if site.Credentials == "" {
710 return failed("publish_off")
711 }
712 }
713 tree, reason, err := e.judgeTree(ctx, r)
714 if err != nil {
715 rep.State, rep.Reason, rep.Termination = wire.StepFailed, reason, true
716 if reason == "withdrawn" || ctx.Err() != nil {
717 rep.State = wire.StepCancelled
718 }
719 return rep
720 }
721 defer os.RemoveAll(tree.GitDir)
722 defer os.RemoveAll(tree.Dir)
723 // The merged commit is on the default branch as this runner fetched it.
724 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 {
725 return failed("publish_not_merged")
726 }
727 cfg, err := readPreviewConfig(ctx, tree.Git, tree.GitDir, r.CandidateSHA)
728 if err != nil {
729 return failed("publish_config")
730 }
731 // The project's own files only: no Equipo _headers (a project's own
732 // _headers stays, and is scanned with the rest).
733 ex, err := exportStatic(ctx, tree.Git, tree.GitDir, r.CandidateSHA, cfg.Output, stage, "")
734 switch {
735 case errors.Is(err, errPreviewTooLarge):
736 return failed("publish_too_large")
737 case err != nil:
738 return failed("publish_config")
739 }
740 // The trusted secret scan, on exactly what would be sent: a finding
741 // or a scanner that cannot run refuses the publish.
742 switch e.scanPreview(ctx, stage) {
743 case "":
744 case "preview_secrets":
745 return failed(reasonPublishSecrets)
746 default:
747 return failed(reasonPublishScanner)
748 }
749 mark := previewMark{Task: r.TaskID, Candidate: r.CandidateSHA, Step: r.StepID, Attempt: r.Attempt, Digest: ex.Digest}
750 raw, _ := json.Marshal(mark)
751 if err := os.WriteFile(filepath.Join(stage, siteMarker), raw, 0o600); err != nil {
752 return failed("publish_failed")
753 }
754 rep.Publish = &wire.PublishResult{Phase: wire.PublishBuilt, Digest: ex.Digest, Files: ex.Files, Bytes: ex.Bytes}
755 progress(rep)
756 rep.Publish = nil
757 cancelled := func(err error) wire.StepReport {
758 rep.State, rep.Reason, rep.Termination = wire.StepCancelled, leaseReason(err), true
759 return rep
760 }
761 switch t.Mode {
762 case wire.SiteSetup:
763 // A name this runner has no proof of making here must be free in
764 // the account (another project's, another Equipo's, a person's
765 // own). Between this list and the deploy another app of the name
766 // could still appear: accepted (controller ruling, 2026-11-12);
767 // the six random characters make it impractical.
768 if !site.madeHere(t) {
769 present, ok := site.listed(ctx, t)
770 if !ok || present {
771 return failed("publish_app_taken")
772 }
773 }
774 if err := e.confirmSite(ctx, e.ConfirmPublish, r, ex.Digest, t.Destination); err != nil {
775 return cancelled(err)
776 }
777 done, deployed := e.siteDeploy(ctx, rep, r, t, runAs{login: true}, version, stage, ex, mark, func() {
778 if err := site.created(t, r.TaskID); err != nil {
779 e.log("site record", err)
780 }
781 })
782 if !deployed {
783 // A deploy that failed half way may have made the app: the
784 // name was free a moment ago, so an app there now is this
785 // deploy's (the accepted list and deploy race) and is recorded
786 // as made here, for a later mint. Anything else records
787 // nothing; attempted is never proven.
788 if present, ok := site.listed(context.WithoutCancel(ctx), t); ok && present {
789 if err := site.created(t, r.TaskID); err != nil {
790 e.log("site record", err)
791 }
792 }
793 return done
794 }
795 // Right after the app exists: its deploy key, behind its own check.
796 if err := e.confirmSite(ctx, e.ConfirmMint, r, ex.Digest, t.Destination); err == nil {
797 if e.O.State.setStepPhase(context.WithoutCancel(ctx), r, phaseSiteMinting, r.Base, r.Candidate) == nil {
798 done.Publish.DeployHeld = site.mint(ctx, t)
799 }
800 }
801 e.siteChanged()
802 return done
803 case wire.SiteMint:
804 if !site.madeHere(t) {
805 present, ok := site.listed(ctx, t)
806 switch {
807 case ok && !present:
808 return failed(reasonPublishAppMissing)
809 case ok:
810 return failed(reasonPublishAppUnproven)
811 }
812 return failed("publish_failed")
813 }
814 if err := e.confirmSite(ctx, e.ConfirmMint, r, ex.Digest, t.Destination); err != nil {
815 return cancelled(err)
816 }
817 if err := e.O.State.setStepPhase(context.WithoutCancel(ctx), r, phaseSiteMinting, r.Base, r.Candidate); err != nil {
818 return failed("publish_failed")
819 }
820 held := site.mint(ctx, t)
821 e.siteChanged()
822 if !held {
823 return failed(reasonPublishMintFailed)
824 }
825 k, _ := site.key(t)
826 key = k
827 }
828 if err := e.confirmSite(ctx, e.ConfirmPublish, r, ex.Digest, t.Destination); err != nil {
829 return cancelled(err)
830 }
831 done, _ := e.siteDeploy(ctx, rep, r, t, runAs{key: key}, version, stage, ex, mark, nil)
832 done.Publish.DeployHeld = true
833 return done
834}
835
836// siteChanged makes the next hello carry the runner's new reach.
837func (e *Engineer) siteChanged() {
838 if e.SiteChanged != nil {
839 e.SiteChanged()
840 }
841}
842
843// siteDeploy marks the attempt as one that may change CARLOS, deploys,
844// and says whether the marker answers. deployed reports the deploy
845// command succeeded.
846func (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) {
847 site := e.Site
848 if err := e.O.State.setStepPhase(context.WithoutCancel(ctx), r, phaseSitePublishing, r.Base, r.Candidate); err != nil {
849 rep.State, rep.Reason, rep.Termination = wire.StepFailed, "publish_failed", true
850 return rep, false
851 }
852 args, err := siteDeployArgs(t, version, stage)
853 out := ""
854 if err == nil {
855 out, err = site.run(ctx, as, args)
856 }
857 // CARLOS keeps its own copy: the export can go (the marker stays for
858 // a restart's reconcile).
859 if entries, rerr := os.ReadDir(stage); rerr == nil {
860 for _, en := range entries {
861 if en.Name() != siteMarker {
862 os.RemoveAll(filepath.Join(stage, en.Name()))
863 }
864 }
865 }
866 url, _ := siteURL(out, t.App)
867 if url != "" {
868 os.WriteFile(filepath.Join(filepath.Dir(stage), "site-url"), []byte(url), 0o600)
869 }
870 if err != nil {
871 e.log("site deploy", errors.New("carlos deploy failed"))
872 done := e.siteDone(rep, t.App, version, ex, url, false)
873 done.Reason = "publish_failed"
874 return done, false
875 }
876 if deployed != nil {
877 // Before anything slow: a stop while the marker is polled must not
878 // lose what the deploy proved.
879 deployed()
880 }
881 served := url != "" && e.markerServed(ctx, siteAt{site, url}, t.App, siteMarker, mark)
882 return e.siteDone(rep, t.App, version, ex, url, served), true
883}
884
885// siteReconcile settles an attempt that restarted after it may have
886// changed CARLOS: nothing is rebuilt, sent or minted again. The marker
887// over the recorded URL decides published or unconfirmed; a mint that had
888// not stored its key stays lost. A mint attempt that restarted before its
889// deploy ends failed: nothing of the site was sent.
890func (e *Engineer) siteReconcile(ctx context.Context, rep wire.StepReport, r stepRow, t siteTarget, version, stage string) wire.StepReport {
891 site := e.Site
892 _, held := site.key(t)
893 if r.Phase == phaseSiteMinting && t.Mode == wire.SiteMint {
894 rep.State, rep.Reason, rep.Termination = wire.StepFailed, reasonPublishMintFailed, true
895 return rep
896 }
897 var mark previewMark
898 raw, err := os.ReadFile(filepath.Join(stage, siteMarker))
899 if err != nil || json.Unmarshal(raw, &mark) != nil {
900 done := e.siteDone(rep, t.App, version, previewExport{}, "", false)
901 done.Publish.DeployHeld = held
902 return done
903 }
904 url := ""
905 if b, err := os.ReadFile(filepath.Join(filepath.Dir(stage), "site-url")); err == nil {
906 if u, ok := siteURL(string(b), t.App); ok {
907 url = u
908 }
909 }
910 served := url != "" && e.markerServed(context.WithoutCancel(ctx), siteAt{site, url}, t.App, siteMarker, mark)
911 if served && t.Mode == wire.SiteSetup && !site.madeHere(t) {
912 // This attempt's own marker answers from the app's address: the
913 // setup's deploy made it (a stop had come before the record).
914 if err := site.created(t, r.TaskID); err != nil {
915 e.log("site record", err)
916 }
917 }
918 done := e.siteDone(rep, t.App, version, previewExport{Digest: mark.Digest}, url, served)
919 done.Publish.DeployHeld = held
920 return done
921}
922
923// siteAt is the site host with the marker fetched from the URL this
924// attempt's deploy printed (the URL seam first, for the tests).
925type siteAt struct {
926 *SiteOptions
927 url string
928}
929
930func (s siteAt) Origin(app string) string {
931 if s.SiteOptions.URL != nil {
932 return s.SiteOptions.URL(app)
933 }
934 return strings.TrimSuffix(s.url, "/")
935}
936
937// confirmSite is the instance's decision right before a mint or a deploy,
938// for this export's digest and destination. The built report travels on
939// the outbox: a refusal for that alone is asked again, briefly.
940func (e *Engineer) confirmSite(ctx context.Context, check func(context.Context, string, int64, string, string) error, r stepRow, digest, destination string) error {
941 var err error
942 for i := 0; i < 10; i++ {
943 if err = check(ctx, r.StepID, r.Attempt, digest, destination); !errors.Is(err, ErrPublishNotBuilt) {
944 return err
945 }
946 select {
947 case <-ctx.Done():
948 return ctx.Err()
949 case <-time.After(previewBuiltWait):
950 }
951 }
952 return err
953}
954
955// siteDone ends the step: published when the marker answered with this
956// export over the URL deploy printed, else unconfirmed (never retried).
957func (e *Engineer) siteDone(rep wire.StepReport, app, version string, ex previewExport, url string, served bool) wire.StepReport {
958 rep.State, rep.Termination = wire.StepDone, true
959 rep.Publish = &wire.PublishResult{Phase: wire.PublishDone, App: app, Version: version, Digest: ex.Digest, Files: ex.Files, Bytes: ex.Bytes, Outcome: wire.PublishUnconfirmed}
960 if url != "" {
961 rep.Publish.URL = url + "/"
962 }
963 if served {
964 rep.Publish.Outcome = wire.PublishPublished
965 }
966 return rep
967}
968