| 1 | package containment |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/hex" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 16 | "golang.org/x/sys/unix" |
| 17 | ) |
| 18 | |
| 19 | type Record struct { |
| 20 | ID, AttemptKey, BootID, NamespaceID, ManifestHash string |
| 21 | EgressHash, PolicyHash string |
| 22 | ParentPID int |
| 23 | ParentTicks uint64 |
| 24 | HostPID int |
| 25 | StartTicks uint64 |
| 26 | } |
| 27 | type Proof struct { |
| 28 | Record Record |
| 29 | Exit provider.Exit |
| 30 | Verified bool |
| 31 | } |
| 32 | |
| 33 | var errIdentity = errors.New("namespace_identity_unproven") |
| 34 | var errNamespaceExited = errors.New("namespace_exited") |
| 35 | |
| 36 | func bootID() (string, error) { |
| 37 | b, e := os.ReadFile("/proc/sys/kernel/random/boot_id") |
| 38 | return strings.TrimSpace(string(b)), e |
| 39 | } |
| 40 | func identity(pid int) (uint64, string, error) { |
| 41 | b, e := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) |
| 42 | if e != nil { |
| 43 | return 0, "", e |
| 44 | } |
| 45 | end := strings.LastIndexByte(string(b), ')') |
| 46 | if end < 0 { |
| 47 | return 0, "", errIdentity |
| 48 | } |
| 49 | fields := strings.Fields(string(b)[end+1:]) |
| 50 | if len(fields) < 20 { |
| 51 | return 0, "", errIdentity |
| 52 | } |
| 53 | ticks, e := strconv.ParseUint(fields[19], 10, 64) |
| 54 | if e != nil { |
| 55 | return 0, "", e |
| 56 | } |
| 57 | ns, e := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", pid)) |
| 58 | return ticks, ns, e |
| 59 | } |
| 60 | func exactPID(r Record) (int, error) { |
| 61 | fd, e := pidfdOpen(r.HostPID) |
| 62 | if e == unix.ESRCH { |
| 63 | return -1, errNamespaceExited |
| 64 | } |
| 65 | if e != nil { |
| 66 | return -1, e |
| 67 | } |
| 68 | ticks, ns, e := identity(r.HostPID) |
| 69 | if errors.Is(e, os.ErrNotExist) || (e == nil && (ticks != r.StartTicks || ns != r.NamespaceID)) { |
| 70 | unix.Close(fd) |
| 71 | return -1, errNamespaceExited |
| 72 | } |
| 73 | if e != nil { |
| 74 | unix.Close(fd) |
| 75 | return -1, errIdentity |
| 76 | } |
| 77 | // Check exit before /proc status: an exiting init may already have lost it. |
| 78 | polls := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} |
| 79 | n, e := pollFD(polls, 0) |
| 80 | if e == nil && n > 0 && polls[0].Revents&unix.POLLIN != 0 { |
| 81 | unix.Close(fd) |
| 82 | return -1, errNamespaceExited |
| 83 | } |
| 84 | if e != nil || n != 0 { |
| 85 | unix.Close(fd) |
| 86 | return -1, errIdentity |
| 87 | } |
| 88 | // Recovery must identify namespace init, not merely a matching process. |
| 89 | hostNS, hostErr := os.Readlink("/proc/self/ns/pid") |
| 90 | status, statusErr := os.ReadFile(fmt.Sprintf("/proc/%d/status", r.HostPID)) |
| 91 | init := false |
| 92 | for _, line := range strings.Split(string(status), "\n") { |
| 93 | if strings.HasPrefix(line, "NSpid:") { |
| 94 | fields := strings.Fields(line) |
| 95 | init = len(fields) > 2 && fields[len(fields)-1] == "1" |
| 96 | } |
| 97 | } |
| 98 | if hostErr != nil || statusErr != nil || ns == hostNS || !init { |
| 99 | unix.Close(fd) |
| 100 | return -1, errIdentity |
| 101 | } |
| 102 | return fd, nil |
| 103 | } |
| 104 | func waitPID(ctx context.Context, fd int) error { |
| 105 | for { |
| 106 | if e := ctx.Err(); e != nil { |
| 107 | return e |
| 108 | } |
| 109 | polls := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} |
| 110 | n, e := unix.Poll(polls, 25) |
| 111 | if e == unix.EINTR { |
| 112 | continue |
| 113 | } |
| 114 | if e != nil { |
| 115 | return e |
| 116 | } |
| 117 | if n > 0 { |
| 118 | if polls[0].Revents&unix.POLLIN == 0 { |
| 119 | return errIdentity |
| 120 | } |
| 121 | return nil |
| 122 | } |
| 123 | } |
| 124 | } |
| 125 | func (m *Manager) persist(r Record) error { return durableJSON(m.cfg.ScratchRoot, r.ID+".json", r) } |
| 126 | func durableJSON(root, name string, v any) error { |
| 127 | data, e := json.Marshal(v) |
| 128 | if e != nil { |
| 129 | return e |
| 130 | } |
| 131 | f, e := os.CreateTemp(root, ".journal-") |
| 132 | if e != nil { |
| 133 | return e |
| 134 | } |
| 135 | tmp := f.Name() |
| 136 | defer os.Remove(tmp) |
| 137 | if _, e = f.Write(data); e == nil { |
| 138 | e = f.Sync() |
| 139 | } |
| 140 | closeErr := f.Close() |
| 141 | if e != nil { |
| 142 | return e |
| 143 | } |
| 144 | if closeErr != nil { |
| 145 | return closeErr |
| 146 | } |
| 147 | if e = os.Rename(tmp, filepath.Join(root, name)); e != nil { |
| 148 | return e |
| 149 | } |
| 150 | d, e := os.Open(root) |
| 151 | if e != nil { |
| 152 | return e |
| 153 | } |
| 154 | defer d.Close() |
| 155 | return d.Sync() |
| 156 | } |
| 157 | |
| 158 | // Recover never enumerates host processes. Once the saved init identity is |
| 159 | // absent, the kernel has finished killing its namespace. Its outcome is unknown. |
| 160 | func (m *Manager) Recover(ctx context.Context, r Record) (Proof, error) { |
| 161 | proof := Proof{Record: r, Exit: provider.Exit{Code: -1}} |
| 162 | _, idErr := hex.DecodeString(r.ID) |
| 163 | if len(r.ID) != 32 || idErr != nil || strings.ContainsAny(r.ID, "/.\\") || r.AttemptKey == "" || r.BootID == "" || r.ManifestHash == "" || r.PolicyHash == "" { |
| 164 | return proof, errIdentity |
| 165 | } |
| 166 | boot, e := bootID() |
| 167 | if e != nil { |
| 168 | return proof, e |
| 169 | } |
| 170 | if boot != r.BootID { |
| 171 | proof.Verified = true |
| 172 | proof.Exit.ObservedAt = time.Now().UTC() |
| 173 | return m.finishRecovery(proof) |
| 174 | } |
| 175 | if r.HostPID == 0 && r.StartTicks == 0 && r.NamespaceID == "" { |
| 176 | stored, err := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".json")) |
| 177 | var durable Record |
| 178 | if err != nil || json.Unmarshal(stored, &durable) != nil || durable != r || r.PolicyHash == "" { |
| 179 | return proof, errIdentity |
| 180 | } |
| 181 | if b, err := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json")); err == nil { |
| 182 | var prior Proof |
| 183 | if json.Unmarshal(b, &prior) != nil || !prior.Verified || prior.Record != r || prior.Exit.ObservedAt.IsZero() { |
| 184 | return proof, errIdentity |
| 185 | } |
| 186 | return m.finishRecovery(prior) |
| 187 | } else if !errors.Is(err, os.ErrNotExist) { |
| 188 | return proof, err |
| 189 | } |
| 190 | // Release is written only after the init identity is durable. An |
| 191 | // intent-only namespace cannot have launched the harness. Old records |
| 192 | // lack parent identity; their release pipe is already closed at restart. |
| 193 | if r.ParentPID > 0 { |
| 194 | fd, err := pidfdOpen(r.ParentPID) |
| 195 | if err == nil { |
| 196 | defer unix.Close(fd) |
| 197 | ticks, _, identityErr := identity(r.ParentPID) |
| 198 | if identityErr == nil && ticks == r.ParentTicks { |
| 199 | if err = waitPID(ctx, fd); err != nil { |
| 200 | return proof, err |
| 201 | } |
| 202 | } else if identityErr != nil && !errors.Is(identityErr, os.ErrNotExist) { |
| 203 | return proof, errIdentity |
| 204 | } |
| 205 | } else if err != unix.ESRCH { |
| 206 | return proof, err |
| 207 | } |
| 208 | } |
| 209 | proof.Verified = true |
| 210 | proof.Exit.ObservedAt = time.Now().UTC() |
| 211 | if err := durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", proof); err != nil { |
| 212 | return Proof{Record: r}, err |
| 213 | } |
| 214 | return m.finishRecovery(proof) |
| 215 | } |
| 216 | nsID, nsErr := strconv.ParseUint(strings.TrimSuffix(strings.TrimPrefix(r.NamespaceID, "pid:["), "]"), 10, 64) |
| 217 | if r.HostPID <= 0 || r.StartTicks == 0 || nsErr != nil || nsID == 0 || r.NamespaceID != fmt.Sprintf("pid:[%d]", nsID) { |
| 218 | return proof, errIdentity |
| 219 | } |
| 220 | saved, readErr := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json")) |
| 221 | if readErr == nil { |
| 222 | var prior Proof |
| 223 | if json.Unmarshal(saved, &prior) != nil || !prior.Verified || prior.Record != r || prior.Exit.ObservedAt.IsZero() { |
| 224 | return proof, errIdentity |
| 225 | } |
| 226 | return m.finishRecovery(prior) |
| 227 | } |
| 228 | if !errors.Is(readErr, os.ErrNotExist) { |
| 229 | return proof, readErr |
| 230 | } |
| 231 | stored, readErr := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".json")) |
| 232 | var durable Record |
| 233 | if readErr != nil || json.Unmarshal(stored, &durable) != nil || durable != r { |
| 234 | return proof, errIdentity |
| 235 | } |
| 236 | fd, e := exactPID(r) |
| 237 | if errors.Is(e, errNamespaceExited) { |
| 238 | proof.Verified = true |
| 239 | proof.Exit.ObservedAt = time.Now().UTC() |
| 240 | if e = durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", proof); e != nil { |
| 241 | proof.Verified = false |
| 242 | return proof, e |
| 243 | } |
| 244 | return m.finishRecovery(proof) |
| 245 | } |
| 246 | if e != nil { |
| 247 | return proof, errIdentity |
| 248 | } |
| 249 | defer unix.Close(fd) |
| 250 | if e = pidfdSignal(fd, unix.SIGKILL); e != nil && e != unix.ESRCH { |
| 251 | return proof, e |
| 252 | } |
| 253 | if e = waitPID(ctx, fd); e != nil { |
| 254 | return proof, e |
| 255 | } |
| 256 | proof.Verified = true |
| 257 | proof.Exit = provider.Exit{Code: -1, Signal: int(unix.SIGKILL), ObservedAt: time.Now().UTC()} |
| 258 | if e = durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", proof); e != nil { |
| 259 | proof.Verified = false |
| 260 | return proof, e |
| 261 | } |
| 262 | return m.finishRecovery(proof) |
| 263 | } |
| 264 | |
| 265 | // Scratch has the durable launch ID. Cleanup cannot undo an observed exit. |
| 266 | func (m *Manager) finishRecovery(proof Proof) (Proof, error) { |
| 267 | return proof, removeScratch(filepath.Join(m.cfg.ScratchRoot, "attempt-"+proof.Record.ID)) |
| 268 | } |
| 269 | |
| 270 | func removeScratch(dir string) error { |
| 271 | // Namespace members are gone before this walk. WalkDir does not follow |
| 272 | // symlinks, including the root, so only owned scratch directories change. |
| 273 | err := filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error { |
| 274 | if errors.Is(err, os.ErrNotExist) { |
| 275 | return nil |
| 276 | } |
| 277 | if err != nil { |
| 278 | return err |
| 279 | } |
| 280 | if d.IsDir() { |
| 281 | return os.Chmod(path, 0700) |
| 282 | } |
| 283 | return nil |
| 284 | }) |
| 285 | if err == nil { |
| 286 | err = os.RemoveAll(dir) |
| 287 | } |
| 288 | if err != nil { |
| 289 | return fmt.Errorf("namespace_scratch_cleanup: %w", err) |
| 290 | } |
| 291 | return nil |
| 292 | } |
| 293 | |
| 294 | // Records returns only durable namespace identities, never a host process scan. |
| 295 | func (m *Manager) Records(ctx context.Context) ([]Record, error) { |
| 296 | entries, err := os.ReadDir(m.cfg.ScratchRoot) |
| 297 | if err != nil { |
| 298 | return nil, err |
| 299 | } |
| 300 | var records []Record |
| 301 | for _, entry := range entries { |
| 302 | if err = ctx.Err(); err != nil { |
| 303 | return nil, err |
| 304 | } |
| 305 | name := entry.Name() |
| 306 | if len(name) != 37 || !strings.HasSuffix(name, ".json") { |
| 307 | continue |
| 308 | } |
| 309 | b, e := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, name)) |
| 310 | if e != nil { |
| 311 | return nil, e |
| 312 | } |
| 313 | var r Record |
| 314 | if json.Unmarshal(b, &r) != nil || r.ID+".json" != name { |
| 315 | return nil, errIdentity |
| 316 | } |
| 317 | records = append(records, r) |
| 318 | } |
| 319 | return records, nil |
| 320 | } |
| 321 | |
| 322 | // RecoverUnstarted covers the crash between the runner's journal intent and |
| 323 | // the namespace record. Start cannot fork until that record is durable. |
| 324 | func (m *Manager) RecoverUnstarted(ctx context.Context, r Record) (Proof, error) { |
| 325 | if r.HostPID != 0 || r.StartTicks != 0 || r.NamespaceID != "" { |
| 326 | return Proof{Record: r}, errIdentity |
| 327 | } |
| 328 | if _, err := os.Lstat(filepath.Join(m.cfg.ScratchRoot, r.ID+".json")); !errors.Is(err, os.ErrNotExist) { |
| 329 | return Proof{Record: r}, errIdentity |
| 330 | } |
| 331 | if len(r.ID) != 32 || strings.ContainsAny(r.ID, "/.\\") { |
| 332 | return Proof{Record: r}, errIdentity |
| 333 | } |
| 334 | if err := m.persist(r); err != nil { |
| 335 | return Proof{Record: r}, err |
| 336 | } |
| 337 | return m.Recover(ctx, r) |
| 338 | } |
| 339 | |
| 340 | // Forget removes only an already verified, exited namespace's durable records. |
| 341 | func (m *Manager) Forget(ctx context.Context, r Record) error { |
| 342 | proof, err := m.Recover(ctx, r) |
| 343 | if err != nil { |
| 344 | return err |
| 345 | } |
| 346 | if !proof.Verified { |
| 347 | return errIdentity |
| 348 | } |
| 349 | for _, suffix := range []string{".json", ".exit.json"} { |
| 350 | if err = os.Remove(filepath.Join(m.cfg.ScratchRoot, r.ID+suffix)); err != nil && !errors.Is(err, os.ErrNotExist) { |
| 351 | return err |
| 352 | } |
| 353 | } |
| 354 | m.mu.Lock() |
| 355 | delete(m.processes, r.ID) |
| 356 | m.mu.Unlock() |
| 357 | return nil |
| 358 | } |
| 359 | |