| 1 | package runnersetup |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "io" |
| 11 | "net/http" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "runtime" |
| 15 | "strings" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/release" |
| 19 | "golang.org/x/sys/unix" |
| 20 | ) |
| 21 | |
| 22 | type InstallOptions struct { |
| 23 | Release, Root, InstanceOrigin string |
| 24 | EnableService bool |
| 25 | } |
| 26 | type InstallResult struct { |
| 27 | Version, BinaryPath, ServicePath, State string |
| 28 | Missing []string |
| 29 | LingeringEnabled bool |
| 30 | } |
| 31 | |
| 32 | var errUnavailable = errors.New("runner.install.unavailable") |
| 33 | |
| 34 | type installHost struct { |
| 35 | scannerPin string |
| 36 | renderer release.RendererAsset |
| 37 | manifest release.Manifest |
| 38 | home, goos, goarch string |
| 39 | fetch func(context.Context, string, int64) ([]byte, error) |
| 40 | // fetchRenderer downloads the renderer archive at url into a new |
| 41 | // private file in scratch, at most size+1 bytes, and returns it open |
| 42 | // at its start (fetchRendererArchive). |
| 43 | fetchRenderer func(ctx context.Context, url string, size int64, scratch string) (*os.File, error) |
| 44 | preflight func(context.Context, string, release.InstallManifest) []string |
| 45 | service func(context.Context, string) error |
| 46 | lingering func(context.Context) (bool, error) |
| 47 | serviceAvailable func(context.Context) bool |
| 48 | } |
| 49 | |
| 50 | func InstallUser(ctx context.Context, opts InstallOptions) (InstallResult, error) { |
| 51 | home, err := os.UserHomeDir() |
| 52 | if err != nil { |
| 53 | return InstallResult{State: "unavailable", Missing: []string{"runner.install.destination"}}, errUnavailable |
| 54 | } |
| 55 | renderer, _ := release.LinkedRendererAsset() |
| 56 | return installUser(ctx, opts, installHost{scannerPin: release.GitleaksSHA256(), renderer: renderer, manifest: release.BuildManifest(), home: home, goos: runtime.GOOS, goarch: runtime.GOARCH, fetch: fetchRelease, fetchRenderer: fetchRendererArchive, preflight: containmentPreflight, service: enableService, lingering: readLingering, serviceAvailable: userServiceAvailable}) |
| 57 | } |
| 58 | func installUser(ctx context.Context, o InstallOptions, h installHost) (r InstallResult, err error) { |
| 59 | r = InstallResult{Version: o.Release, State: "unavailable"} |
| 60 | fail := func(key string) (InstallResult, error) { r.Missing = []string{key}; return r, errUnavailable } |
| 61 | if h.goos != "linux" || h.goarch != "amd64" { |
| 62 | return fail("runner.install.platform") |
| 63 | } |
| 64 | if !release.InstallOrigin(o.InstanceOrigin) || !release.ValidInstallVersion(o.Release) { |
| 65 | return fail("runner.install.release") |
| 66 | } |
| 67 | if !within(h.home, o.Root) || o.Root == h.home || !privateDirectory(o.Root) { |
| 68 | return fail("runner.install.destination") |
| 69 | } |
| 70 | lock, e := os.OpenFile(filepath.Join(o.Root, "install.lock"), os.O_CREATE|os.O_RDWR|unix.O_NOFOLLOW, 0600) |
| 71 | if e != nil { |
| 72 | return fail("runner.install.destination") |
| 73 | } |
| 74 | defer lock.Close() |
| 75 | if unix.Flock(int(lock.Fd()), unix.LOCK_EX|unix.LOCK_NB) != nil { |
| 76 | return fail("runner.install.busy") |
| 77 | } |
| 78 | defer unix.Flock(int(lock.Fd()), unix.LOCK_UN) |
| 79 | base := o.InstanceOrigin + "/releases/" + o.Release + "/" |
| 80 | raw, e := h.fetch(ctx, base+"install-manifest.json", 1<<20) |
| 81 | if e != nil { |
| 82 | return fail("runner.install.release") |
| 83 | } |
| 84 | var m release.InstallManifest |
| 85 | if json.Unmarshal(raw, &m) != nil || m.Validate(o.Release) != nil { |
| 86 | return fail("runner.install.release") |
| 87 | } |
| 88 | // Each attempt owns exactly one private scratch directory. TMPDIR wins |
| 89 | // when set; otherwise the user's cache directory keeps it on disk, since |
| 90 | // /tmp may be a shared RAM disk. |
| 91 | scratchRoot := os.Getenv("TMPDIR") |
| 92 | if scratchRoot == "" { |
| 93 | cache, ce := os.UserCacheDir() |
| 94 | if ce != nil { |
| 95 | return fail("runner.install.scratch") |
| 96 | } |
| 97 | scratchRoot = filepath.Join(cache, "equipo", "install") |
| 98 | if os.MkdirAll(scratchRoot, 0o700) != nil { |
| 99 | return fail("runner.install.scratch") |
| 100 | } |
| 101 | } |
| 102 | scratch, e := os.MkdirTemp(scratchRoot, "equipo-install-") |
| 103 | if e != nil { |
| 104 | return fail("runner.install.scratch") |
| 105 | } |
| 106 | defer os.RemoveAll(scratch) |
| 107 | binary, e := h.fetch(ctx, base+"equipo-runner", 128<<20) |
| 108 | if e != nil { |
| 109 | return fail("runner.install.release") |
| 110 | } |
| 111 | sum := sha256.Sum256(binary) |
| 112 | if hex.EncodeToString(sum[:]) != m.RunnerSHA256 { |
| 113 | return fail("runner.install.checksum") |
| 114 | } |
| 115 | candidate := filepath.Join(scratch, "equipo-runner") |
| 116 | if os.WriteFile(candidate, binary, 0700) != nil { |
| 117 | return fail("runner.install.destination") |
| 118 | } |
| 119 | if missing := h.preflight(ctx, candidate, m); len(missing) > 0 { |
| 120 | r.Missing = missing |
| 121 | return r, errUnavailable |
| 122 | } |
| 123 | if !h.serviceAvailable(ctx) { |
| 124 | return fail("runner.install.service") |
| 125 | } |
| 126 | linger, e := h.lingering(ctx) |
| 127 | if e != nil { |
| 128 | return fail("runner.install.lingering") |
| 129 | } |
| 130 | r.LingeringEnabled = linger |
| 131 | helper, e := h.fetch(ctx, base+"equipo-tool-proxy", 128<<20) |
| 132 | if e != nil { |
| 133 | return fail("runner.install.release") |
| 134 | } |
| 135 | helperHash := sha256.Sum256(helper) |
| 136 | if m.Release.ToolProxySHA256() == "" || hex.EncodeToString(helperHash[:]) != m.Release.ToolProxySHA256() || hex.EncodeToString(helperHash[:]) != h.manifest.ToolProxySHA256() { |
| 137 | return fail("runner.install.checksum") |
| 138 | } |
| 139 | scanner, e := h.fetch(ctx, base+"gitleaks", 128<<20) |
| 140 | scannerHash := sha256.Sum256(scanner) |
| 141 | scannerPin := hex.EncodeToString(scannerHash[:]) |
| 142 | if e != nil || h.scannerPin == "" || scannerPin != h.scannerPin || scannerPin != m.Targets[release.TargetLinux].GitleaksSHA256 { |
| 143 | return fail("runner.install.checksum") |
| 144 | } |
| 145 | dir := filepath.Join(o.Root, "releases", o.Release) |
| 146 | // The page renderer, beside the runner. The archive this runner |
| 147 | // installs is linked into it (release.LinkedRendererAsset): its tree |
| 148 | // pin, digest, size and forge tag, which the release's manifest must |
| 149 | // repeat. A tree already there that verifies (the second run, after |
| 150 | // enrolment) is kept; one an earlier release here has is copied; |
| 151 | // otherwise the archive is fetched from the forge, never from the |
| 152 | // instance, and checked whole before anything is unpacked. |
| 153 | asset, linux := h.renderer, m.Targets[release.TargetLinux] |
| 154 | if !asset.Valid() || asset.Pin != linux.RendererSHA256 || asset.SHA256 != linux.RendererArchiveSHA256 || asset.Size != linux.RendererArchiveSize { |
| 155 | return fail("runner.install.checksum") |
| 156 | } |
| 157 | var archive *os.File |
| 158 | reuse := "" |
| 159 | if release.VerifyRenderer(release.RendererTree(dir, asset.Pin), asset.Pin) != nil { |
| 160 | if reuse = earlierTree(o.Root, o.Release, asset.Pin); reuse == "" { |
| 161 | if archive, e = h.fetchRenderer(ctx, asset.URL(), asset.Size, scratch); e != nil { |
| 162 | return fail("runner.install.release") |
| 163 | } |
| 164 | defer archive.Close() |
| 165 | if !archiveMatches(archive, asset) { |
| 166 | return fail("runner.install.checksum") |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | if !privateDirectory(dir) { |
| 171 | return fail("runner.install.destination") |
| 172 | } |
| 173 | // Unpacked (or copied) and verified before any of the runner's files |
| 174 | // is written. |
| 175 | if archive != nil || reuse != "" { |
| 176 | if archive != nil { |
| 177 | _, e = release.InstallRenderer(dir, archive, asset.Pin) |
| 178 | } else { |
| 179 | _, e = release.CopyRenderer(dir, reuse, asset.Pin) |
| 180 | } |
| 181 | if e != nil { |
| 182 | var mismatch *release.RendererError |
| 183 | if errors.As(e, &mismatch) { |
| 184 | return fail("runner.install.checksum") |
| 185 | } |
| 186 | return fail("runner.install.destination") |
| 187 | } |
| 188 | } |
| 189 | r.BinaryPath = filepath.Join(dir, "equipo-runner") |
| 190 | if e = writeOwned(r.BinaryPath, binary, 0700); e != nil { |
| 191 | return fail("runner.install.destination") |
| 192 | } |
| 193 | if e = writeOwned(filepath.Join(dir, "equipo-tool-proxy"), helper, 0700); e != nil { |
| 194 | return fail("runner.install.destination") |
| 195 | } |
| 196 | if e = writeOwned(filepath.Join(dir, "gitleaks"), scanner, 0700); e != nil { |
| 197 | return fail("runner.install.destination") |
| 198 | } |
| 199 | r.ServicePath = filepath.Join(o.Root, "equipo-runner.service") |
| 200 | unit := serviceUnit(r.BinaryPath, filepath.Join(o.Root, "runner.env")) |
| 201 | if e = writeOwned(r.ServicePath, []byte(unit), 0600); e != nil { |
| 202 | return fail("runner.install.destination") |
| 203 | } |
| 204 | if o.EnableService { |
| 205 | marker := filepath.Join(o.Root, "service-enabled.json") |
| 206 | identity, _ := json.Marshal([]string{o.InstanceOrigin, o.Release, m.RunnerSHA256}) |
| 207 | old, readErr := os.ReadFile(marker) |
| 208 | if readErr != nil && !os.IsNotExist(readErr) { |
| 209 | return fail("runner.install.service") |
| 210 | } |
| 211 | if string(old) != string(identity) { |
| 212 | if h.service(ctx, r.ServicePath) != nil { |
| 213 | return fail("runner.install.service") |
| 214 | } |
| 215 | if e = writeOwned(marker, identity, 0600); e != nil { |
| 216 | return fail("runner.install.service") |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | r.State = "installed" |
| 221 | if !r.LingeringEnabled { |
| 222 | r.State = "stops_at_logout" |
| 223 | } |
| 224 | return r, nil |
| 225 | } |
| 226 | func within(home, path string) bool { |
| 227 | if !filepath.IsAbs(path) || filepath.Clean(path) != path { |
| 228 | return false |
| 229 | } |
| 230 | rel, e := filepath.Rel(home, path) |
| 231 | return e == nil && rel != ".." && !strings.HasPrefix(rel, "../") |
| 232 | } |
| 233 | func privateDirectory(path string) bool { |
| 234 | // Reject symlinks in existing ancestors before creating anything. |
| 235 | for p := path; p != "/"; p = filepath.Dir(p) { |
| 236 | i, e := os.Lstat(p) |
| 237 | if os.IsNotExist(e) { |
| 238 | continue |
| 239 | } |
| 240 | if e != nil || !i.IsDir() || i.Mode()&os.ModeSymlink != 0 { |
| 241 | return false |
| 242 | } |
| 243 | } |
| 244 | if os.MkdirAll(path, 0700) != nil { |
| 245 | return false |
| 246 | } |
| 247 | i, e := os.Stat(path) |
| 248 | if e != nil || i.Mode().Perm() != 0700 { |
| 249 | return false |
| 250 | } |
| 251 | var stat unix.Stat_t |
| 252 | return unix.Stat(path, &stat) == nil && stat.Uid == uint32(os.Geteuid()) && unix.Access(path, unix.W_OK) == nil |
| 253 | } |
| 254 | |
| 255 | const installOwnership = "user.equipo.installer.sha256" |
| 256 | |
| 257 | // InstallerOwns reports whether the installer may replace path: it does |
| 258 | // not exist, or it is this user's regular file, exactly as the installer |
| 259 | // last wrote it (its ownership marker matches). A file edited by hand, |
| 260 | // or not the installer's, is never replaced. |
| 261 | func InstallerOwns(path string) bool { |
| 262 | _, err := ownedContent(path) |
| 263 | return err == nil || os.IsNotExist(err) |
| 264 | } |
| 265 | |
| 266 | // ownedContent is the content of a file the installer wrote and still |
| 267 | // owns; an error (errUnavailable when it is not the installer's) else. |
| 268 | func ownedContent(path string) ([]byte, error) { |
| 269 | i, e := os.Lstat(path) |
| 270 | if e != nil { |
| 271 | return nil, e |
| 272 | } |
| 273 | if !i.Mode().IsRegular() { |
| 274 | return nil, errUnavailable |
| 275 | } |
| 276 | var stat unix.Stat_t |
| 277 | if unix.Lstat(path, &stat) != nil || stat.Uid != uint32(os.Geteuid()) { |
| 278 | return nil, errUnavailable |
| 279 | } |
| 280 | old, e := os.ReadFile(path) |
| 281 | if e != nil { |
| 282 | return nil, e |
| 283 | } |
| 284 | marker := make([]byte, 64) |
| 285 | n, e := unix.Getxattr(path, installOwnership, marker) |
| 286 | sum := sha256.Sum256(old) |
| 287 | if e != nil || n != 64 || string(marker) != hex.EncodeToString(sum[:]) { |
| 288 | return nil, errUnavailable |
| 289 | } |
| 290 | return old, nil |
| 291 | } |
| 292 | |
| 293 | func writeOwned(path string, data []byte, mode os.FileMode) error { |
| 294 | replace := false |
| 295 | if i, e := os.Lstat(path); e == nil { |
| 296 | old, e := ownedContent(path) |
| 297 | if e != nil { |
| 298 | return e |
| 299 | } |
| 300 | if string(old) == string(data) && i.Mode().Perm() == mode { |
| 301 | return nil |
| 302 | } |
| 303 | replace = true |
| 304 | } else if !os.IsNotExist(e) { |
| 305 | return e |
| 306 | } |
| 307 | f, e := os.CreateTemp(filepath.Dir(path), ".install-write-") |
| 308 | if e != nil { |
| 309 | return e |
| 310 | } |
| 311 | defer os.Remove(f.Name()) |
| 312 | defer f.Close() |
| 313 | if e = f.Chmod(mode); e != nil { |
| 314 | return e |
| 315 | } |
| 316 | if _, e = f.Write(data); e != nil { |
| 317 | return e |
| 318 | } |
| 319 | sum := sha256.Sum256(data) |
| 320 | if e = unix.Fsetxattr(int(f.Fd()), installOwnership, []byte(hex.EncodeToString(sum[:])), 0); e != nil { |
| 321 | return e |
| 322 | } |
| 323 | if e = f.Sync(); e != nil { |
| 324 | return e |
| 325 | } |
| 326 | if e = f.Close(); e != nil { |
| 327 | return e |
| 328 | } |
| 329 | if replace { |
| 330 | e = os.Rename(f.Name(), path) |
| 331 | } else { |
| 332 | e = os.Link(f.Name(), path) |
| 333 | } |
| 334 | if e != nil { |
| 335 | return e |
| 336 | } |
| 337 | dir, e := os.Open(filepath.Dir(path)) |
| 338 | if e != nil { |
| 339 | return e |
| 340 | } |
| 341 | defer dir.Close() |
| 342 | return dir.Sync() |
| 343 | } |
| 344 | func fetchRelease(ctx context.Context, url string, limit int64) ([]byte, error) { |
| 345 | c := http.Client{Timeout: 2 * time.Minute, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| 346 | req, e := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| 347 | if e != nil { |
| 348 | return nil, e |
| 349 | } |
| 350 | resp, e := c.Do(req) |
| 351 | if e != nil { |
| 352 | return nil, e |
| 353 | } |
| 354 | defer resp.Body.Close() |
| 355 | if resp.StatusCode != http.StatusOK { |
| 356 | return nil, errUnavailable |
| 357 | } |
| 358 | // One buffer of the announced size (the renderer is about 230 MB). |
| 359 | var buf bytes.Buffer |
| 360 | if resp.ContentLength > 0 && resp.ContentLength <= limit { |
| 361 | buf.Grow(int(resp.ContentLength) + 1) |
| 362 | } |
| 363 | _, e = buf.ReadFrom(io.LimitReader(resp.Body, limit+1)) |
| 364 | b := buf.Bytes() |
| 365 | if e != nil || int64(len(b)) > limit { |
| 366 | return nil, errUnavailable |
| 367 | } |
| 368 | return b, nil |
| 369 | } |
| 370 | |
| 371 | // earlierTree is a renderer tree for pin that verifies in another release |
| 372 | // directory under root (an earlier install's), or "". At most a few |
| 373 | // release directories are looked at. |
| 374 | func earlierTree(root, version, pin string) string { |
| 375 | entries, err := os.ReadDir(filepath.Join(root, "releases")) |
| 376 | if err != nil { |
| 377 | return "" |
| 378 | } |
| 379 | for i, d := range entries { |
| 380 | if i >= 32 { |
| 381 | break |
| 382 | } |
| 383 | name := d.Name() |
| 384 | if name == version || !d.IsDir() || !release.ValidInstallVersion(name) { |
| 385 | continue |
| 386 | } |
| 387 | tree := release.RendererTree(filepath.Join(root, "releases", name), pin) |
| 388 | if info, err := os.Lstat(tree); err == nil && info.IsDir() && release.VerifyRenderer(tree, pin) == nil { |
| 389 | return tree |
| 390 | } |
| 391 | } |
| 392 | return "" |
| 393 | } |
| 394 | |
| 395 | // archiveMatches: f holds exactly the asset's size in bytes, with its |
| 396 | // SHA-256, and the archive's MANIFEST is its tree pin. f is left at its |
| 397 | // start. |
| 398 | func archiveMatches(f *os.File, a release.RendererAsset) bool { |
| 399 | if _, err := f.Seek(0, io.SeekStart); err != nil { |
| 400 | return false |
| 401 | } |
| 402 | h := sha256.New() |
| 403 | n, err := io.Copy(h, io.LimitReader(f, a.Size+1)) |
| 404 | if err != nil || n != a.Size || hex.EncodeToString(h.Sum(nil)) != a.SHA256 { |
| 405 | return false |
| 406 | } |
| 407 | if _, err := f.Seek(0, io.SeekStart); err != nil { |
| 408 | return false |
| 409 | } |
| 410 | pin, err := release.RendererArchivePin(f) |
| 411 | if err != nil || pin != a.Pin { |
| 412 | return false |
| 413 | } |
| 414 | _, err = f.Seek(0, io.SeekStart) |
| 415 | return err == nil |
| 416 | } |
| 417 | |
| 418 | // Bounds on the renderer download: it may take long on a slow link, but |
| 419 | // not stall. rendererTransport is nil (the default) but in tests. |
| 420 | var ( |
| 421 | rendererDownloadMax = 30 * time.Minute |
| 422 | rendererDownloadStall = 2 * time.Minute |
| 423 | rendererTransport http.RoundTripper |
| 424 | ) |
| 425 | |
| 426 | // fetchRendererArchive downloads the archive at url (the forge's fixed |
| 427 | // address) into a new private file in scratch. The forge answers with a |
| 428 | // redirect to its storage: exactly one is followed, and only to an https |
| 429 | // URL without credentials. The body is read at most to size+1 bytes, and |
| 430 | // a download that makes no progress for rendererDownloadStall, or runs |
| 431 | // past rendererDownloadMax, is abandoned. A failure removes the file. |
| 432 | func fetchRendererArchive(ctx context.Context, url string, size int64, scratch string) (_ *os.File, err error) { |
| 433 | ctx, cancel := context.WithTimeout(ctx, rendererDownloadMax) |
| 434 | defer cancel() |
| 435 | c := http.Client{Transport: rendererTransport, CheckRedirect: func(req *http.Request, via []*http.Request) error { |
| 436 | if len(via) > 1 || req.URL.Scheme != "https" || req.URL.User != nil || req.URL.Host == "" { |
| 437 | return errUnavailable |
| 438 | } |
| 439 | return nil |
| 440 | }} |
| 441 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| 442 | if err != nil { |
| 443 | return nil, err |
| 444 | } |
| 445 | // The stall bound covers the wait for each response's headers too. |
| 446 | stall := time.AfterFunc(rendererDownloadStall, cancel) |
| 447 | defer stall.Stop() |
| 448 | resp, err := c.Do(req) |
| 449 | if err != nil { |
| 450 | return nil, err |
| 451 | } |
| 452 | defer resp.Body.Close() |
| 453 | if resp.StatusCode != http.StatusOK { |
| 454 | return nil, errUnavailable |
| 455 | } |
| 456 | f, err := os.CreateTemp(scratch, "renderer-*.tar.gz") |
| 457 | if err != nil { |
| 458 | return nil, err |
| 459 | } |
| 460 | defer func() { |
| 461 | if err != nil { |
| 462 | f.Close() |
| 463 | os.Remove(f.Name()) |
| 464 | } |
| 465 | }() |
| 466 | stall.Reset(rendererDownloadStall) |
| 467 | n, err := io.Copy(f, progress{io.LimitReader(resp.Body, size+1), func() { stall.Reset(rendererDownloadStall) }}) |
| 468 | if err != nil { |
| 469 | return nil, err |
| 470 | } |
| 471 | if n != size { |
| 472 | return nil, errUnavailable |
| 473 | } |
| 474 | if _, err = f.Seek(0, io.SeekStart); err != nil { |
| 475 | return nil, err |
| 476 | } |
| 477 | return f, nil |
| 478 | } |
| 479 | |
| 480 | // progress calls moved after every read that returned bytes. |
| 481 | type progress struct { |
| 482 | r io.Reader |
| 483 | moved func() |
| 484 | } |
| 485 | |
| 486 | func (p progress) Read(b []byte) (int, error) { |
| 487 | n, err := p.r.Read(b) |
| 488 | if n > 0 { |
| 489 | p.moved() |
| 490 | } |
| 491 | return n, err |
| 492 | } |
| 493 | |