| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "crypto/sha256" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "hash" |
| 13 | "io" |
| 14 | "log/slog" |
| 15 | "net/http" |
| 16 | "os" |
| 17 | "os/exec" |
| 18 | "path" |
| 19 | "path/filepath" |
| 20 | "regexp" |
| 21 | "sort" |
| 22 | "strconv" |
| 23 | "strings" |
| 24 | "time" |
| 25 | |
| 26 | "amadan.net/oficina/equipo/internal/runner" |
| 27 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 28 | "amadan.net/oficina/equipo/internal/wire" |
| 29 | "golang.org/x/sys/unix" |
| 30 | ) |
| 31 | |
| 32 | // PreviewOptions is what a preview step publishes with: the carlos binary |
| 33 | // and the Carloku service credential (token, console, account and the |
| 34 | // account's platform domain), read from a 0600 file, never mounted into a |
| 35 | // namespace. Run and URL are seams for the tests. |
| 36 | type PreviewOptions struct { |
| 37 | Carlos string `json:"carlos"` |
| 38 | Token string `json:"token"` |
| 39 | Console string `json:"console"` |
| 40 | Account string `json:"account"` |
| 41 | Domain string `json:"domain"` |
| 42 | // Run runs one carlos command (nil: exec). Client fetches the marker |
| 43 | // (nil: one that follows no redirect). URL is the app's origin (nil: |
| 44 | // https://<app>.<Domain>). |
| 45 | Run func(ctx context.Context, dir string, env []string, args []string) (string, error) `json:"-"` |
| 46 | Client *http.Client `json:"-"` |
| 47 | URL func(app string) string `json:"-"` |
| 48 | } |
| 49 | |
| 50 | // previewOptions loads the preview credential when one is configured, |
| 51 | // and only from a place no sandbox mounts. A file that is refused leaves |
| 52 | // previews off, said once in the log without its content. |
| 53 | func previewOptions(c runner.Config, logger *slog.Logger) *PreviewOptions { |
| 54 | if c.PreviewCredentialPath == "" { |
| 55 | return nil |
| 56 | } |
| 57 | o, err := LoadPreviewOptions(c.PreviewCredentialPath) |
| 58 | if err == nil { |
| 59 | err = previewCredentialPlace(c) |
| 60 | } |
| 61 | if err != nil { |
| 62 | if logger != nil { |
| 63 | logger.Warn("previews are off: the preview credential file was refused", "reason", err.Error()) |
| 64 | } |
| 65 | return nil |
| 66 | } |
| 67 | return o |
| 68 | } |
| 69 | |
| 70 | // Errors of the preview credential, fixed words only: never the file's |
| 71 | // content, a key it holds or the decoder's message. |
| 72 | var ( |
| 73 | errPreviewCredentialFile = errors.New("preview credential must be a regular file, not a link, mode 0600, owned by this user") |
| 74 | errPreviewCredentialShape = errors.New("preview credential file is not the expected JSON") |
| 75 | errPreviewCredentialPlace = errors.New("preview credential file is inside a directory sandboxes mount") |
| 76 | ) |
| 77 | |
| 78 | // previewCredentialPlace refuses a credential file that sits inside any |
| 79 | // directory a step's sandbox mounts or works in. |
| 80 | func previewCredentialPlace(c runner.Config) error { |
| 81 | file, err := filepath.EvalSymlinks(c.PreviewCredentialPath) |
| 82 | if err != nil { |
| 83 | return errPreviewCredentialFile |
| 84 | } |
| 85 | for _, root := range []string{c.WorkspaceRoot, c.ScratchRoot, filepath.Join(c.StateDir, "steps"), c.GoRoot, c.ModuleCache, homeModuleCache()} { |
| 86 | if root == "" { |
| 87 | continue |
| 88 | } |
| 89 | real, err := filepath.EvalSymlinks(root) |
| 90 | if err != nil { |
| 91 | real = filepath.Clean(root) |
| 92 | } |
| 93 | if rel, err := filepath.Rel(real, file); err == nil && rel != ".." && !strings.HasPrefix(rel, "../") { |
| 94 | return errPreviewCredentialPlace |
| 95 | } |
| 96 | } |
| 97 | return nil |
| 98 | } |
| 99 | |
| 100 | var previewDomain = regexp.MustCompile(`^[a-z0-9-]+(\.[a-z0-9-]+)+$`) |
| 101 | |
| 102 | // LoadPreviewOptions reads the preview credential file: a regular file, |
| 103 | // not a link (refused before and while opening), mode exactly 0600, owned |
| 104 | // by this user, at most 8 KiB, every field present, the carlos binary an |
| 105 | // absolute path. Its errors never carry its content. |
| 106 | func LoadPreviewOptions(file string) (*PreviewOptions, error) { |
| 107 | if info, err := os.Lstat(file); err != nil || !info.Mode().IsRegular() { |
| 108 | return nil, errPreviewCredentialFile |
| 109 | } |
| 110 | fd, err := unix.Open(file, unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| 111 | if err != nil { |
| 112 | return nil, errPreviewCredentialFile |
| 113 | } |
| 114 | f := os.NewFile(uintptr(fd), file) |
| 115 | defer f.Close() |
| 116 | var st unix.Stat_t |
| 117 | if unix.Fstat(fd, &st) != nil || st.Mode&unix.S_IFMT != unix.S_IFREG || st.Mode&0o7777 != 0o600 || int(st.Uid) != os.Getuid() { |
| 118 | return nil, errPreviewCredentialFile |
| 119 | } |
| 120 | raw, err := io.ReadAll(io.LimitReader(f, 8<<10+1)) |
| 121 | if err != nil || len(raw) > 8<<10 { |
| 122 | return nil, errPreviewCredentialShape |
| 123 | } |
| 124 | var o PreviewOptions |
| 125 | d := json.NewDecoder(bytes.NewReader(raw)) |
| 126 | d.DisallowUnknownFields() |
| 127 | if d.Decode(&o) != nil || d.More() { |
| 128 | return nil, errPreviewCredentialShape |
| 129 | } |
| 130 | if !filepath.IsAbs(o.Carlos) || o.Token == "" || strings.ContainsAny(o.Token, "\r\n") || !strings.HasPrefix(o.Console, "https://") || o.Account == "" || !previewDomain.MatchString(o.Domain) { |
| 131 | return nil, errPreviewCredentialShape |
| 132 | } |
| 133 | return &o, nil |
| 134 | } |
| 135 | |
| 136 | // Preview bounds (spec §1.3). |
| 137 | const ( |
| 138 | previewConfigPath = "release/preview.json" |
| 139 | previewMarker = "equipo-preview.json" |
| 140 | previewMaxConfig = 4 << 10 |
| 141 | previewMaxFiles = 2000 |
| 142 | previewMaxFile = 10 << 20 |
| 143 | previewMaxBytes = 50 << 20 |
| 144 | previewTTL = "7d" |
| 145 | ) |
| 146 | |
| 147 | // phasePreviewPublishing marks a preview attempt that may have changed |
| 148 | // Carloku: after a restart it only reconciles (the marker), never sends. |
| 149 | const phasePreviewPublishing = "preview_publishing" |
| 150 | |
| 151 | // Paced for the tests. |
| 152 | var ( |
| 153 | previewVerifyFor = 2 * time.Minute |
| 154 | previewVerifyEvery = 5 * time.Second |
| 155 | previewBuiltWait = time.Second |
| 156 | ) |
| 157 | |
| 158 | var errPreviewConfig = errors.New("preview config refused") |
| 159 | var errPreviewTooLarge = errors.New("preview too large") |
| 160 | |
| 161 | type previewConfig struct { |
| 162 | Output string `json:"output"` |
| 163 | } |
| 164 | |
| 165 | // gitRead runs git on the private git directory only (no work tree, no |
| 166 | // hooks, no configuration of the person's). |
| 167 | func gitRead(ctx context.Context, git, gitDir string, limit int, args ...string) ([]byte, error) { |
| 168 | cmd := exec.CommandContext(ctx, git, append([]string{"--git-dir=" + gitDir, "-c", "core.quotePath=false"}, args...)...) |
| 169 | env := workspace.GitEnvironment() |
| 170 | env["HOME"] = "/nonexistent" |
| 171 | for k, v := range env { |
| 172 | cmd.Env = append(cmd.Env, k+"="+v) |
| 173 | } |
| 174 | out, clipped, err := boundedOutput(cmd, limit) |
| 175 | if err != nil { |
| 176 | return nil, err |
| 177 | } |
| 178 | if clipped { |
| 179 | return nil, errPreviewTooLarge |
| 180 | } |
| 181 | return out, nil |
| 182 | } |
| 183 | |
| 184 | // readPreviewConfig reads release/preview.json from the candidate's git |
| 185 | // objects: a blob of at most 4 KiB, strictly {"output": <clean path>}. |
| 186 | func readPreviewConfig(ctx context.Context, git, gitDir, sha string) (previewConfig, error) { |
| 187 | ls, err := gitRead(ctx, git, gitDir, 4096, "ls-tree", "-l", sha, "--", previewConfigPath) |
| 188 | if err != nil || len(ls) == 0 { |
| 189 | return previewConfig{}, errPreviewConfig |
| 190 | } |
| 191 | f := strings.Fields(string(ls)) |
| 192 | if len(f) < 5 || f[0] != "100644" && f[0] != "100755" || f[1] != "blob" { |
| 193 | return previewConfig{}, errPreviewConfig |
| 194 | } |
| 195 | if n, err := strconv.Atoi(f[3]); err != nil || n > previewMaxConfig { |
| 196 | return previewConfig{}, errPreviewConfig |
| 197 | } |
| 198 | raw, err := gitRead(ctx, git, gitDir, previewMaxConfig+1, "cat-file", "blob", f[2]) |
| 199 | if err != nil { |
| 200 | return previewConfig{}, errPreviewConfig |
| 201 | } |
| 202 | return parsePreviewConfig(raw) |
| 203 | } |
| 204 | |
| 205 | // parsePreviewConfig is release/preview.json's content rule, wherever it |
| 206 | // was read from: at most 4 KiB, strictly {"output": <clean path>}. |
| 207 | func parsePreviewConfig(raw []byte) (previewConfig, error) { |
| 208 | if len(raw) > previewMaxConfig { |
| 209 | return previewConfig{}, errPreviewConfig |
| 210 | } |
| 211 | var c previewConfig |
| 212 | d := json.NewDecoder(bytes.NewReader(raw)) |
| 213 | d.DisallowUnknownFields() |
| 214 | if d.Decode(&c) != nil || d.More() || !cleanPreviewPath(c.Output) { |
| 215 | return previewConfig{}, errPreviewConfig |
| 216 | } |
| 217 | return c, nil |
| 218 | } |
| 219 | |
| 220 | // cleanPreviewPath: relative, already clean, no part starting with a dot. |
| 221 | func cleanPreviewPath(p string) bool { |
| 222 | if p == "" || path.IsAbs(p) || path.Clean(p) != p || strings.ContainsAny(p, "\\\x00\r\n") { |
| 223 | return false |
| 224 | } |
| 225 | for _, part := range strings.Split(p, "/") { |
| 226 | if part == "" || strings.HasPrefix(part, ".") { |
| 227 | return false |
| 228 | } |
| 229 | } |
| 230 | return true |
| 231 | } |
| 232 | |
| 233 | // hasPreview is Review's scheduling evidence: the candidate holds a |
| 234 | // release/preview.json this version can use. |
| 235 | func hasPreview(ctx context.Context, git, gitDir, sha string) bool { |
| 236 | _, err := readPreviewConfig(ctx, git, gitDir, sha) |
| 237 | return err == nil |
| 238 | } |
| 239 | |
| 240 | type previewExport struct { |
| 241 | Digest string |
| 242 | Files int |
| 243 | Bytes int64 |
| 244 | } |
| 245 | |
| 246 | // exportPreview writes the output directory's blobs, read from git |
| 247 | // objects only, into stage (fresh, private): regular files only, every |
| 248 | // path clean, within the caps, which are checked against the listing |
| 249 | // before any read and again while copying. The digest is SHA-256 over the |
| 250 | // sorted "<path> <sha256>" lines. |
| 251 | func exportPreview(ctx context.Context, git, gitDir, sha, output, stage, origin string) (previewExport, error) { |
| 252 | return exportStatic(ctx, git, gitDir, sha, output, stage, previewHeaders(origin)) |
| 253 | } |
| 254 | |
| 255 | func exportStatic(ctx context.Context, git, gitDir, sha, output, stage, headers string) (previewExport, error) { |
| 256 | ls, err := gitRead(ctx, git, gitDir, 4<<20, "ls-tree", "-r", "-l", "-z", sha, "--", output+"/") |
| 257 | if err != nil { |
| 258 | return previewExport{}, errPreviewTooLarge |
| 259 | } |
| 260 | type entry struct { |
| 261 | rel, object string |
| 262 | size int64 |
| 263 | } |
| 264 | var entries []entry |
| 265 | budget := newSiteBudget(headers) |
| 266 | for _, rec := range bytes.Split(bytes.TrimRight(ls, "\x00"), []byte{0}) { |
| 267 | if len(rec) == 0 { |
| 268 | continue |
| 269 | } |
| 270 | meta, name, ok := strings.Cut(string(rec), "\t") |
| 271 | f := strings.Fields(meta) |
| 272 | if !ok || len(f) != 4 || !strings.HasPrefix(name, output+"/") { |
| 273 | return previewExport{}, errPreviewConfig |
| 274 | } |
| 275 | if f[0] != "100644" && f[0] != "100755" || f[1] != "blob" { |
| 276 | // A symlink, a submodule: never followed. |
| 277 | return previewExport{}, errPreviewConfig |
| 278 | } |
| 279 | rel := strings.TrimPrefix(name, output+"/") |
| 280 | skip, err := siteEntry(rel, headers) |
| 281 | if err != nil { |
| 282 | return previewExport{}, err |
| 283 | } |
| 284 | if skip { |
| 285 | continue |
| 286 | } |
| 287 | size, err := strconv.ParseInt(f[3], 10, 64) |
| 288 | if err != nil { |
| 289 | return previewExport{}, errPreviewTooLarge |
| 290 | } |
| 291 | if err := budget.add(size); err != nil { |
| 292 | return previewExport{}, err |
| 293 | } |
| 294 | entries = append(entries, entry{rel, f[2], size}) |
| 295 | } |
| 296 | if len(entries) == 0 { |
| 297 | return previewExport{}, errPreviewConfig |
| 298 | } |
| 299 | st, err := openSiteStage(stage) |
| 300 | if err != nil { |
| 301 | return previewExport{}, err |
| 302 | } |
| 303 | defer st.close() |
| 304 | if headers != "" { |
| 305 | entries = append(entries, entry{rel: "_headers", size: int64(len(headers))}) |
| 306 | } |
| 307 | sort.Slice(entries, func(i, j int) bool { return entries[i].rel < entries[j].rel }) |
| 308 | for _, e := range entries { |
| 309 | var blob []byte |
| 310 | if headers != "" && e.rel == "_headers" { |
| 311 | blob = []byte(headers) |
| 312 | } else { |
| 313 | blob, err = gitRead(ctx, git, gitDir, previewMaxFile, "cat-file", "blob", e.object) |
| 314 | if err != nil || int64(len(blob)) != e.size { |
| 315 | return previewExport{}, errPreviewTooLarge |
| 316 | } |
| 317 | } |
| 318 | if err := st.put(e.rel, blob); err != nil { |
| 319 | return previewExport{}, err |
| 320 | } |
| 321 | } |
| 322 | return previewExport{Digest: st.digest(), Files: len(entries), Bytes: budget.bytes}, nil |
| 323 | } |
| 324 | |
| 325 | // siteEntry is the rule for one path inside the output directory, |
| 326 | // relative to it: clean, no part starting with a dot, not a marker's |
| 327 | // name. skip: the tree's own _headers, replaced by the runner's. |
| 328 | func siteEntry(rel, headers string) (skip bool, err error) { |
| 329 | if !cleanPreviewPath(rel) || rel == previewMarker || rel == siteMarker { |
| 330 | return false, errPreviewConfig |
| 331 | } |
| 332 | return headers != "" && rel == "_headers", nil |
| 333 | } |
| 334 | |
| 335 | // siteBudget counts an export against the caps: files, bytes, and each |
| 336 | // file's size. The runner's _headers counts from the start. |
| 337 | type siteBudget struct { |
| 338 | files int |
| 339 | bytes int64 |
| 340 | } |
| 341 | |
| 342 | func newSiteBudget(headers string) siteBudget { |
| 343 | b := siteBudget{bytes: int64(len(headers))} |
| 344 | if headers != "" { |
| 345 | b.files = 1 |
| 346 | } |
| 347 | return b |
| 348 | } |
| 349 | |
| 350 | func (b *siteBudget) add(size int64) error { |
| 351 | if size < 0 || size > previewMaxFile { |
| 352 | return errPreviewTooLarge |
| 353 | } |
| 354 | b.bytes += size |
| 355 | b.files++ |
| 356 | if b.files > previewMaxFiles || b.bytes > previewMaxBytes { |
| 357 | return errPreviewTooLarge |
| 358 | } |
| 359 | return nil |
| 360 | } |
| 361 | |
| 362 | // siteStage is an export's stage: fresh and private, each file created |
| 363 | // once (never over another), the digest SHA-256 over the "<path> |
| 364 | // <sha256>" lines in the order put (sorted by the caller). |
| 365 | type siteStage struct { |
| 366 | root *os.Root |
| 367 | sum hash.Hash |
| 368 | } |
| 369 | |
| 370 | // openSiteStage empties stage and makes it again, 0700. |
| 371 | func openSiteStage(stage string) (*siteStage, error) { |
| 372 | if err := os.RemoveAll(stage); err != nil { |
| 373 | return nil, err |
| 374 | } |
| 375 | if err := os.MkdirAll(stage, 0o700); err != nil { |
| 376 | return nil, err |
| 377 | } |
| 378 | root, err := os.OpenRoot(stage) |
| 379 | if err != nil { |
| 380 | return nil, err |
| 381 | } |
| 382 | return &siteStage{root: root, sum: sha256.New()}, nil |
| 383 | } |
| 384 | |
| 385 | func (s *siteStage) put(rel string, blob []byte) error { |
| 386 | if dir := path.Dir(rel); dir != "." { |
| 387 | if err := s.root.MkdirAll(dir, 0o700); err != nil { |
| 388 | return err |
| 389 | } |
| 390 | } |
| 391 | fh, err := s.root.OpenFile(rel, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) |
| 392 | if err != nil { |
| 393 | return err |
| 394 | } |
| 395 | _, werr := fh.Write(blob) |
| 396 | if cerr := fh.Close(); werr != nil || cerr != nil { |
| 397 | return errors.Join(werr, cerr) |
| 398 | } |
| 399 | h := sha256.Sum256(blob) |
| 400 | fmt.Fprintf(s.sum, "%s %s\n", rel, hex.EncodeToString(h[:])) |
| 401 | return nil |
| 402 | } |
| 403 | |
| 404 | func (s *siteStage) digest() string { return hex.EncodeToString(s.sum.Sum(nil)) } |
| 405 | |
| 406 | func (s *siteStage) close() { s.root.Close() } |
| 407 | |
| 408 | // previewMark is the marker the runner adds beside the export (outside |
| 409 | // its digest) and fetches back to confirm what is served. |
| 410 | type previewMark struct { |
| 411 | Security string `json:"security,omitempty"` |
| 412 | Task string `json:"task"` |
| 413 | Candidate string `json:"candidate"` |
| 414 | Step string `json:"step"` |
| 415 | Attempt int64 `json:"attempt"` |
| 416 | Digest string `json:"digest"` |
| 417 | } |
| 418 | |
| 419 | func previewApp(task string) string { return "tmp-" + task } |
| 420 | |
| 421 | func (o *PreviewOptions) origin(app string) string { |
| 422 | if o.URL != nil { |
| 423 | return o.URL(app) |
| 424 | } |
| 425 | return "https://" + app + "." + o.Domain |
| 426 | } |
| 427 | |
| 428 | // carlos runs one fixed command with the credential in its environment |
| 429 | // only, from an empty private directory with a private HOME, so nothing of |
| 430 | // the repository or the person's own configuration is read. |
| 431 | func (e *Engineer) carlos(ctx context.Context, r stepRow, args ...string) (string, error) { |
| 432 | o := e.Preview |
| 433 | dir := filepath.Join(e.root(), stepKey(r), "carlos") |
| 434 | if err := os.MkdirAll(dir, 0o700); err != nil { |
| 435 | return "", err |
| 436 | } |
| 437 | // The flags go before any positional argument: carlos stops reading |
| 438 | // flags at the first one. |
| 439 | n := 1 |
| 440 | if args[0] == "apps" { |
| 441 | n = 2 |
| 442 | } |
| 443 | args = append(append(append([]string{}, args[:n]...), "--account", o.Account, "--console", o.Console), args[n:]...) |
| 444 | env := []string{"CARLOS_SERVICE_TOKEN=" + o.Token, "HOME=" + dir, "PATH=/usr/bin:/bin"} |
| 445 | cctx, cancel := context.WithTimeout(ctx, 5*time.Minute) |
| 446 | defer cancel() |
| 447 | if o.Run != nil { |
| 448 | return o.Run(cctx, dir, env, args) |
| 449 | } |
| 450 | cmd := exec.CommandContext(cctx, o.Carlos, args...) |
| 451 | cmd.Dir, cmd.Env = dir, env |
| 452 | return runCarlos(cmd) |
| 453 | } |
| 454 | |
| 455 | // The app's state as `carlos apps list` prints it. |
| 456 | const ( |
| 457 | appMissing = "missing" |
| 458 | appLive = "live" |
| 459 | appKept = "kept" |
| 460 | appTrashed = "trashed" |
| 461 | ) |
| 462 | |
| 463 | // ansi is a terminal colour sequence carlos may print around a line. |
| 464 | var ansi = regexp.MustCompile(`\x1b\[[0-9;]*m`) |
| 465 | |
| 466 | func appState(list, app string) (string, bool) { |
| 467 | list = ansi.ReplaceAllString(list, "") |
| 468 | sc := bufio.NewScanner(strings.NewReader(list)) |
| 469 | header := false |
| 470 | for sc.Scan() { |
| 471 | if strings.TrimSpace(sc.Text()) == "no apps in this account" { |
| 472 | // An account with no apps at all: listed, and empty. |
| 473 | header = true |
| 474 | continue |
| 475 | } |
| 476 | f := strings.Fields(sc.Text()) |
| 477 | if len(f) >= 2 && f[0] == "APP" && f[1] == "STATE" { |
| 478 | header = true |
| 479 | continue |
| 480 | } |
| 481 | if len(f) < 2 || f[0] != app { |
| 482 | continue |
| 483 | } |
| 484 | switch { |
| 485 | case f[1] == "trashed": |
| 486 | return appTrashed, true |
| 487 | case f[1] == "live" && strings.Contains(sc.Text(), "expires in"): |
| 488 | return appLive, true |
| 489 | case f[1] == "live": |
| 490 | return appKept, true |
| 491 | } |
| 492 | return "", false |
| 493 | } |
| 494 | if !header { |
| 495 | return "", false |
| 496 | } |
| 497 | return appMissing, true |
| 498 | } |
| 499 | |
| 500 | var trashAt = regexp.MustCompile(`moves to the Trash .*?, at (\d{4}-\d{2}-\d{2} \d{2}:\d{2}) UTC`) |
| 501 | |
| 502 | func expiryIn(out string) *time.Time { |
| 503 | m := trashAt.FindStringSubmatch(out) |
| 504 | if m == nil { |
| 505 | return nil |
| 506 | } |
| 507 | t, err := time.Parse("2006-01-02 15:04", m[1]) |
| 508 | if err != nil { |
| 509 | return nil |
| 510 | } |
| 511 | return &t |
| 512 | } |
| 513 | |
| 514 | func onlyChannel(out string) (string, bool) { |
| 515 | var names []string |
| 516 | for _, line := range strings.Split(out, "\n") { |
| 517 | f := strings.Fields(line) |
| 518 | if len(f) == 0 || f[0] == "CHANNEL" || strings.HasPrefix(line, "using ") { |
| 519 | continue |
| 520 | } |
| 521 | names = append(names, f[0]) |
| 522 | } |
| 523 | if len(names) != 1 || !regexp.MustCompile(`^[a-z][a-z0-9/-]*$`).MatchString(names[0]) { |
| 524 | return "", false |
| 525 | } |
| 526 | return names[0], true |
| 527 | } |
| 528 | |
| 529 | // preview runs a preview step (spec §1): export the approved candidate's |
| 530 | // output from git objects, report it built, then each Carloku mutation |
| 531 | // behind its own publish check, then confirm what is served. |
| 532 | func (e *Engineer) preview(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport { |
| 533 | rep := judgeReport(r) |
| 534 | failed := func(reason string) wire.StepReport { |
| 535 | rep.State, rep.Reason, rep.Termination = wire.StepFailed, reason, true |
| 536 | return rep |
| 537 | } |
| 538 | host := e.activePreviewHost() |
| 539 | if host == nil || e.ConfirmPreview == nil { |
| 540 | return failed("preview_failed") |
| 541 | } |
| 542 | stage := filepath.Join(e.root(), stepKey(r), "preview") |
| 543 | if r.Phase == phasePreviewPublishing { |
| 544 | // After a restart: nothing is rebuilt or sent; the marker decides. |
| 545 | var mark previewMark |
| 546 | raw, err := os.ReadFile(filepath.Join(stage, previewMarker)) |
| 547 | if err != nil || json.Unmarshal(raw, &mark) != nil { |
| 548 | return e.previewDone(rep, r, previewExport{}, nil, false) |
| 549 | } |
| 550 | if mark.Security != previewSecurityStamp(e.O.Runner.Origin) { |
| 551 | return e.previewDone(rep, r, previewExport{Digest: mark.Digest}, nil, false) |
| 552 | } |
| 553 | // Even when the step was cancelled meanwhile: the marker says what |
| 554 | // is served, within its own bounded window. |
| 555 | served, why := e.previewServed(context.WithoutCancel(ctx), r, mark) |
| 556 | return e.previewDone(rep, r, previewExport{Digest: mark.Digest}, nil, served, why) |
| 557 | } |
| 558 | // A carlos too old for the preview's headers refuses now, before |
| 559 | // anything is built (it would fail obscurely at the deploy). |
| 560 | if !e.previewCarlosOK(ctx) { |
| 561 | return failed(wire.ReasonCarlosOutdated) |
| 562 | } |
| 563 | tree, reason, err := e.judgeTree(ctx, r) |
| 564 | if err != nil { |
| 565 | rep.State, rep.Reason, rep.Termination = wire.StepFailed, reason, true |
| 566 | if reason == "withdrawn" || ctx.Err() != nil { |
| 567 | rep.State = wire.StepCancelled |
| 568 | } |
| 569 | return rep |
| 570 | } |
| 571 | defer os.RemoveAll(tree.GitDir) |
| 572 | defer os.RemoveAll(tree.Dir) |
| 573 | cfg, err := readPreviewConfig(ctx, tree.Git, tree.GitDir, r.CandidateSHA) |
| 574 | if err != nil { |
| 575 | return failed("preview_config") |
| 576 | } |
| 577 | ex, err := exportPreview(ctx, tree.Git, tree.GitDir, r.CandidateSHA, cfg.Output, stage, e.O.Runner.Origin) |
| 578 | switch { |
| 579 | case errors.Is(err, errPreviewTooLarge): |
| 580 | return failed("preview_too_large") |
| 581 | case err != nil: |
| 582 | return failed("preview_config") |
| 583 | } |
| 584 | if reason := e.scanPreview(ctx, stage); reason != "" { |
| 585 | return failed(reason) |
| 586 | } |
| 587 | if r.PreviewUnsafeDigest != "" { |
| 588 | if r.PreviewUnsafeDigest != ex.Digest { |
| 589 | return failed("withdrawn") |
| 590 | } |
| 591 | if err := os.Remove(filepath.Join(stage, "_headers")); err != nil { |
| 592 | return failed("preview_failed") |
| 593 | } |
| 594 | } |
| 595 | mark := previewMark{Security: previewSecurityStamp(e.O.Runner.Origin), Task: r.TaskID, Candidate: r.CandidateSHA, Step: r.StepID, Attempt: r.Attempt, Digest: ex.Digest} |
| 596 | raw, _ := json.Marshal(mark) |
| 597 | if err := os.WriteFile(filepath.Join(stage, previewMarker), raw, 0o600); err != nil { |
| 598 | return failed("preview_failed") |
| 599 | } |
| 600 | rep.Preview = &wire.PreviewResult{Phase: wire.PreviewBuilt, Digest: ex.Digest, Files: ex.Files, Bytes: ex.Bytes} |
| 601 | progress(rep) |
| 602 | rep.Preview = nil |
| 603 | |
| 604 | app := previewApp(r.TaskID) |
| 605 | confirm := func() error { |
| 606 | // The built report travels on the outbox: the instance may not have |
| 607 | // it yet, so a refusal for that alone is asked again, briefly. |
| 608 | var err error |
| 609 | for i := 0; i < 10; i++ { |
| 610 | if err = e.ConfirmPreview(ctx, r.StepID, r.Attempt, ex.Digest); !errors.Is(err, ErrPreviewNotBuilt) { |
| 611 | return err |
| 612 | } |
| 613 | select { |
| 614 | case <-ctx.Done(): |
| 615 | return ctx.Err() |
| 616 | case <-time.After(previewBuiltWait): |
| 617 | } |
| 618 | } |
| 619 | return err |
| 620 | } |
| 621 | stopped := func(err error) wire.StepReport { |
| 622 | rep.State, rep.Reason, rep.Termination = wire.StepCancelled, leaseReason(err), true |
| 623 | return rep |
| 624 | } |
| 625 | if host.Kind() == wire.PreviewHostDevbox { |
| 626 | return e.publishDevbox(ctx, r, rep, ex, mark, stage, confirm, stopped) |
| 627 | } |
| 628 | list, err := e.carlos(ctx, r, "apps", "list") |
| 629 | state, ok := appState(list, app) |
| 630 | if err != nil || !ok { |
| 631 | return failed("preview_state") |
| 632 | } |
| 633 | switch state { |
| 634 | case appTrashed: |
| 635 | return failed("preview_expired") |
| 636 | case appKept: |
| 637 | return failed("preview_state") |
| 638 | } |
| 639 | if err := confirm(); err != nil { |
| 640 | return stopped(err) |
| 641 | } |
| 642 | // From here Carloku may change: a restart only reconciles. |
| 643 | if err := e.O.State.setStepPhase(context.WithoutCancel(ctx), r, phasePreviewPublishing, r.Base, r.Candidate); err != nil { |
| 644 | return failed("preview_failed") |
| 645 | } |
| 646 | var expires *time.Time |
| 647 | if state == appMissing { |
| 648 | hold := filepath.Join(e.root(), stepKey(r), "placeholder") |
| 649 | os.RemoveAll(hold) |
| 650 | if err := os.MkdirAll(hold, 0o700); err != nil { |
| 651 | return failed("preview_failed") |
| 652 | } |
| 653 | if err := os.WriteFile(filepath.Join(hold, "_headers"), []byte(previewHeaders(e.O.Runner.Origin)), 0o600); err != nil { |
| 654 | return failed("preview_failed") |
| 655 | } |
| 656 | if r.PreviewUnsafeDigest != "" { |
| 657 | _ = os.Remove(filepath.Join(hold, "_headers")) |
| 658 | } |
| 659 | os.WriteFile(filepath.Join(hold, "index.html"), []byte("<!doctype html><meta charset=\"utf-8\"><title>Preview</title>\n"), 0o600) |
| 660 | out, err := e.carlos(ctx, r, "deploy", "--temporary", "--ttl", previewTTL, "--app", r.TaskID, "--kind", "static", "--version", "p0-"+r.StepID+"-"+itoa(r.Attempt), "--no-prompt", hold) |
| 661 | if err != nil { |
| 662 | if strings.Contains(out, "temporary apps, the most it can hold") { |
| 663 | // Refused at Carloku's cap: nothing was created. |
| 664 | return failed("preview_cap") |
| 665 | } |
| 666 | return e.previewDone(rep, r, ex, nil, false, previewPublishFailure(out)) |
| 667 | } |
| 668 | expires = expiryIn(out) |
| 669 | } else { |
| 670 | out, err := e.carlos(ctx, r, "apps", "ttl", "--app", app, previewTTL) |
| 671 | if err != nil { |
| 672 | return e.previewDone(rep, r, ex, nil, false, "preview_failed") |
| 673 | } |
| 674 | expires = expiryIn(out) |
| 675 | } |
| 676 | if err := confirm(); err != nil { |
| 677 | return stopped(err) |
| 678 | } |
| 679 | version := "p-" + r.StepID + "-" + itoa(r.Attempt) |
| 680 | if out, err := e.carlos(ctx, r, "ship", "--app", app, "--kind", "static", "--version", version, "--no-prompt", stage); err != nil { |
| 681 | return e.previewDone(rep, r, ex, nil, false, previewPublishFailure(out)) |
| 682 | } |
| 683 | chans, err := e.carlos(ctx, r, "channels", "--app", app) |
| 684 | channel, ok := onlyChannel(chans) |
| 685 | if err != nil || !ok { |
| 686 | return e.previewDone(rep, r, ex, nil, false, "preview_state") |
| 687 | } |
| 688 | if err := confirm(); err != nil { |
| 689 | return stopped(err) |
| 690 | } |
| 691 | if _, err := e.carlos(ctx, r, "promote", "--app", app, "--no-prompt", version, channel); err != nil { |
| 692 | return e.previewDone(rep, r, ex, nil, false, "preview_failed") |
| 693 | } |
| 694 | served, why := e.previewServed(ctx, r, mark) |
| 695 | rep2 := e.previewDone(rep, r, ex, expires, served, why) |
| 696 | rep2.Preview.Version = version |
| 697 | return rep2 |
| 698 | } |
| 699 | |
| 700 | // previewDone ends the step: deployed when the marker answered with this |
| 701 | // export, else unconfirmed (never retried); a reason means it failed |
| 702 | // after Carloku may have changed, which the step says as unconfirmed too. |
| 703 | func (e *Engineer) previewDone(rep wire.StepReport, r stepRow, ex previewExport, expires *time.Time, served bool, reason ...string) wire.StepReport { |
| 704 | host := e.activePreviewHost() |
| 705 | app := host.App(r.TaskID) |
| 706 | rep.State, rep.Termination = wire.StepDone, true |
| 707 | rep.Preview = &wire.PreviewResult{Phase: wire.PreviewDone, App: app, Digest: ex.Digest, Files: ex.Files, Bytes: ex.Bytes, Outcome: wire.PreviewUnconfirmed} |
| 708 | if len(reason) > 0 { |
| 709 | rep.Reason = reason[0] |
| 710 | } |
| 711 | if served { |
| 712 | rep.Preview.Unsafe = r.PreviewUnsafeDigest != "" |
| 713 | rep.Preview.Outcome, rep.Preview.URL, rep.Preview.ExpiresAt = wire.PreviewDeployed, host.Origin(app)+"/", expires |
| 714 | } |
| 715 | return rep |
| 716 | } |
| 717 | |
| 718 | // previewServed fetches the marker from the task's preview app. |
| 719 | func (e *Engineer) previewServed(ctx context.Context, r stepRow, want previewMark) (bool, string) { |
| 720 | host := e.activePreviewHost() |
| 721 | return e.markerStatus(ctx, host, host.App(r.TaskID), previewMarker, want, r.PreviewUnsafeDigest == want.Digest && want.Digest != "") |
| 722 | } |
| 723 | |
| 724 | // markerServed fetches marker from app's origin on host, following no |
| 725 | // redirect and sending no credential, until it names exactly this export |
| 726 | // or the window ends. |
| 727 | func (e *Engineer) markerServed(ctx context.Context, host previewHost, app, marker string, want previewMark) bool { |
| 728 | ok, _ := e.markerStatus(ctx, host, app, marker, want, false) |
| 729 | return ok |
| 730 | } |
| 731 | func (e *Engineer) markerStatus(ctx context.Context, host previewHost, app, marker string, want previewMark, unsafe bool) (bool, string) { |
| 732 | client := host.HTTP() |
| 733 | if client == nil { |
| 734 | client = &http.Client{Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| 735 | } |
| 736 | copyClient := *client |
| 737 | copyClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } |
| 738 | client = ©Client |
| 739 | origin := host.Origin(app) |
| 740 | if origin == "" { |
| 741 | return false, "" |
| 742 | } |
| 743 | url := origin + "/" + marker |
| 744 | deadline := time.Now().Add(previewVerifyFor) |
| 745 | for { |
| 746 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| 747 | if err != nil { |
| 748 | return false, "" |
| 749 | } |
| 750 | if res, err := client.Do(req); err == nil { |
| 751 | raw, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10)) |
| 752 | res.Body.Close() |
| 753 | var got previewMark |
| 754 | if res.StatusCode == http.StatusOK && json.Unmarshal(raw, &got) == nil && got == want { |
| 755 | if marker == previewMarker && !unsafe && (len(res.Header.Values("Content-Security-Policy")) != 1 || res.Header.Get("Content-Security-Policy") != previewCSP(e.O.Runner.Origin)) { |
| 756 | return false, "preview_header_missing" |
| 757 | } |
| 758 | return true, "" |
| 759 | } |
| 760 | } |
| 761 | if time.Now().After(deadline) { |
| 762 | return false, "" |
| 763 | } |
| 764 | select { |
| 765 | case <-ctx.Done(): |
| 766 | return false, "" |
| 767 | case <-time.After(previewVerifyEvery): |
| 768 | } |
| 769 | } |
| 770 | } |
| 771 | |
| 772 | // ErrPreviewNotBuilt is the instance's refusal of a publish check whose |
| 773 | // built report it has not applied yet. |
| 774 | var ErrPreviewNotBuilt = errors.New("preview not built yet") |
| 775 | |