package containment import ( "context" "encoding/hex" "encoding/json" "errors" "fmt" "os" "path/filepath" "strconv" "strings" "time" "amadan.net/oficina/equipo/internal/runner/provider" "golang.org/x/sys/unix" ) type Record struct { ID, AttemptKey, BootID, NamespaceID, ManifestHash string EgressHash, PolicyHash string ParentPID int ParentTicks uint64 HostPID int StartTicks uint64 } type Proof struct { Record Record Exit provider.Exit Verified bool } var errIdentity = errors.New("namespace_identity_unproven") var errNamespaceExited = errors.New("namespace_exited") func bootID() (string, error) { b, e := os.ReadFile("/proc/sys/kernel/random/boot_id") return strings.TrimSpace(string(b)), e } func identity(pid int) (uint64, string, error) { b, e := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) if e != nil { return 0, "", e } end := strings.LastIndexByte(string(b), ')') if end < 0 { return 0, "", errIdentity } fields := strings.Fields(string(b)[end+1:]) if len(fields) < 20 { return 0, "", errIdentity } ticks, e := strconv.ParseUint(fields[19], 10, 64) if e != nil { return 0, "", e } ns, e := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", pid)) return ticks, ns, e } func exactPID(r Record) (int, error) { fd, e := pidfdOpen(r.HostPID) if e == unix.ESRCH { return -1, errNamespaceExited } if e != nil { return -1, e } ticks, ns, e := identity(r.HostPID) if errors.Is(e, os.ErrNotExist) || (e == nil && (ticks != r.StartTicks || ns != r.NamespaceID)) { unix.Close(fd) return -1, errNamespaceExited } if e != nil { unix.Close(fd) return -1, errIdentity } // Check exit before /proc status: an exiting init may already have lost it. polls := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} n, e := pollFD(polls, 0) if e == nil && n > 0 && polls[0].Revents&unix.POLLIN != 0 { unix.Close(fd) return -1, errNamespaceExited } if e != nil || n != 0 { unix.Close(fd) return -1, errIdentity } // Recovery must identify namespace init, not merely a matching process. hostNS, hostErr := os.Readlink("/proc/self/ns/pid") status, statusErr := os.ReadFile(fmt.Sprintf("/proc/%d/status", r.HostPID)) init := false for _, line := range strings.Split(string(status), "\n") { if strings.HasPrefix(line, "NSpid:") { fields := strings.Fields(line) init = len(fields) > 2 && fields[len(fields)-1] == "1" } } if hostErr != nil || statusErr != nil || ns == hostNS || !init { unix.Close(fd) return -1, errIdentity } return fd, nil } func waitPID(ctx context.Context, fd int) error { for { if e := ctx.Err(); e != nil { return e } polls := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} n, e := unix.Poll(polls, 25) if e == unix.EINTR { continue } if e != nil { return e } if n > 0 { if polls[0].Revents&unix.POLLIN == 0 { return errIdentity } return nil } } } func (m *Manager) persist(r Record) error { return durableJSON(m.cfg.ScratchRoot, r.ID+".json", r) } func durableJSON(root, name string, v any) error { data, e := json.Marshal(v) if e != nil { return e } f, e := os.CreateTemp(root, ".journal-") if e != nil { return e } tmp := f.Name() defer os.Remove(tmp) if _, e = f.Write(data); e == nil { e = f.Sync() } closeErr := f.Close() if e != nil { return e } if closeErr != nil { return closeErr } if e = os.Rename(tmp, filepath.Join(root, name)); e != nil { return e } d, e := os.Open(root) if e != nil { return e } defer d.Close() return d.Sync() } // Recover never enumerates host processes. Once the saved init identity is // absent, the kernel has finished killing its namespace. Its outcome is unknown. func (m *Manager) Recover(ctx context.Context, r Record) (Proof, error) { proof := Proof{Record: r, Exit: provider.Exit{Code: -1}} _, idErr := hex.DecodeString(r.ID) if len(r.ID) != 32 || idErr != nil || strings.ContainsAny(r.ID, "/.\\") || r.AttemptKey == "" || r.BootID == "" || r.ManifestHash == "" || r.PolicyHash == "" { return proof, errIdentity } boot, e := bootID() if e != nil { return proof, e } if boot != r.BootID { proof.Verified = true proof.Exit.ObservedAt = time.Now().UTC() return m.finishRecovery(proof) } if r.HostPID == 0 && r.StartTicks == 0 && r.NamespaceID == "" { stored, err := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".json")) var durable Record if err != nil || json.Unmarshal(stored, &durable) != nil || durable != r || r.PolicyHash == "" { return proof, errIdentity } if b, err := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json")); err == nil { var prior Proof if json.Unmarshal(b, &prior) != nil || !prior.Verified || prior.Record != r || prior.Exit.ObservedAt.IsZero() { return proof, errIdentity } return m.finishRecovery(prior) } else if !errors.Is(err, os.ErrNotExist) { return proof, err } // Release is written only after the init identity is durable. An // intent-only namespace cannot have launched the harness. Old records // lack parent identity; their release pipe is already closed at restart. if r.ParentPID > 0 { fd, err := pidfdOpen(r.ParentPID) if err == nil { defer unix.Close(fd) ticks, _, identityErr := identity(r.ParentPID) if identityErr == nil && ticks == r.ParentTicks { if err = waitPID(ctx, fd); err != nil { return proof, err } } else if identityErr != nil && !errors.Is(identityErr, os.ErrNotExist) { return proof, errIdentity } } else if err != unix.ESRCH { return proof, err } } proof.Verified = true proof.Exit.ObservedAt = time.Now().UTC() if err := durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", proof); err != nil { return Proof{Record: r}, err } return m.finishRecovery(proof) } nsID, nsErr := strconv.ParseUint(strings.TrimSuffix(strings.TrimPrefix(r.NamespaceID, "pid:["), "]"), 10, 64) if r.HostPID <= 0 || r.StartTicks == 0 || nsErr != nil || nsID == 0 || r.NamespaceID != fmt.Sprintf("pid:[%d]", nsID) { return proof, errIdentity } saved, readErr := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json")) if readErr == nil { var prior Proof if json.Unmarshal(saved, &prior) != nil || !prior.Verified || prior.Record != r || prior.Exit.ObservedAt.IsZero() { return proof, errIdentity } return m.finishRecovery(prior) } if !errors.Is(readErr, os.ErrNotExist) { return proof, readErr } stored, readErr := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".json")) var durable Record if readErr != nil || json.Unmarshal(stored, &durable) != nil || durable != r { return proof, errIdentity } fd, e := exactPID(r) if errors.Is(e, errNamespaceExited) { proof.Verified = true proof.Exit.ObservedAt = time.Now().UTC() if e = durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", proof); e != nil { proof.Verified = false return proof, e } return m.finishRecovery(proof) } if e != nil { return proof, errIdentity } defer unix.Close(fd) if e = pidfdSignal(fd, unix.SIGKILL); e != nil && e != unix.ESRCH { return proof, e } if e = waitPID(ctx, fd); e != nil { return proof, e } proof.Verified = true proof.Exit = provider.Exit{Code: -1, Signal: int(unix.SIGKILL), ObservedAt: time.Now().UTC()} if e = durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", proof); e != nil { proof.Verified = false return proof, e } return m.finishRecovery(proof) } // Scratch has the durable launch ID. Cleanup cannot undo an observed exit. func (m *Manager) finishRecovery(proof Proof) (Proof, error) { return proof, removeScratch(filepath.Join(m.cfg.ScratchRoot, "attempt-"+proof.Record.ID)) } func removeScratch(dir string) error { // Namespace members are gone before this walk. WalkDir does not follow // symlinks, including the root, so only owned scratch directories change. err := filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error { if errors.Is(err, os.ErrNotExist) { return nil } if err != nil { return err } if d.IsDir() { return os.Chmod(path, 0700) } return nil }) if err == nil { err = os.RemoveAll(dir) } if err != nil { return fmt.Errorf("namespace_scratch_cleanup: %w", err) } return nil } // Records returns only durable namespace identities, never a host process scan. func (m *Manager) Records(ctx context.Context) ([]Record, error) { entries, err := os.ReadDir(m.cfg.ScratchRoot) if err != nil { return nil, err } var records []Record for _, entry := range entries { if err = ctx.Err(); err != nil { return nil, err } name := entry.Name() if len(name) != 37 || !strings.HasSuffix(name, ".json") { continue } b, e := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, name)) if e != nil { return nil, e } var r Record if json.Unmarshal(b, &r) != nil || r.ID+".json" != name { return nil, errIdentity } records = append(records, r) } return records, nil } // RecoverUnstarted covers the crash between the runner's journal intent and // the namespace record. Start cannot fork until that record is durable. func (m *Manager) RecoverUnstarted(ctx context.Context, r Record) (Proof, error) { if r.HostPID != 0 || r.StartTicks != 0 || r.NamespaceID != "" { return Proof{Record: r}, errIdentity } if _, err := os.Lstat(filepath.Join(m.cfg.ScratchRoot, r.ID+".json")); !errors.Is(err, os.ErrNotExist) { return Proof{Record: r}, errIdentity } if len(r.ID) != 32 || strings.ContainsAny(r.ID, "/.\\") { return Proof{Record: r}, errIdentity } if err := m.persist(r); err != nil { return Proof{Record: r}, err } return m.Recover(ctx, r) } // Forget removes only an already verified, exited namespace's durable records. func (m *Manager) Forget(ctx context.Context, r Record) error { proof, err := m.Recover(ctx, r) if err != nil { return err } if !proof.Verified { return errIdentity } for _, suffix := range []string{".json", ".exit.json"} { if err = os.Remove(filepath.Join(m.cfg.ScratchRoot, r.ID+suffix)); err != nil && !errors.Is(err, os.ErrNotExist) { return err } } m.mu.Lock() delete(m.processes, r.ID) m.mu.Unlock() return nil }