| 1 | package engine |
| 2 | |
| 3 | import ( |
| 4 | "crypto/sha256" |
| 5 | "encoding/hex" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "io/fs" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "regexp" |
| 13 | "sort" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | ) |
| 17 | |
| 18 | // SentinelFilename names the file Ensure writes inside the cache directory |
| 19 | // after a successful extraction. Its contents are compared to the requested |
| 20 | // version; a match short-circuits re-extraction on subsequent calls. |
| 21 | const SentinelFilename = ".version" |
| 22 | |
| 23 | // DigestFilename records the SHA-256 manifest digest of the embedded engine |
| 24 | // tree so reuse verifies content integrity rather than trusting a bare version. |
| 25 | const DigestFilename = ".sha256" |
| 26 | |
| 27 | // cacheSubdir namespaces our cache under the OS user cache directory so |
| 28 | // multiple printing-press-style bundles can coexist. |
| 29 | const cacheSubdir = "last30days-pp-mcp" |
| 30 | |
| 31 | // CacheEnvOverride lets users redirect the cache directory when the default |
| 32 | // OS cache location is read-only (locked-down corp images, ephemeral CI |
| 33 | // containers). Pointed at by extract errors via the documented escape hatch. |
| 34 | const CacheEnvOverride = "LAST30DAYS_CACHE_DIR" |
| 35 | |
| 36 | var validVersionRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$`) |
| 37 | |
| 38 | var windowsReservedNames = map[string]struct{}{ |
| 39 | "CON": {}, "PRN": {}, "AUX": {}, "NUL": {}, |
| 40 | "COM1": {}, "COM2": {}, "COM3": {}, "COM4": {}, "COM5": {}, "COM6": {}, "COM7": {}, "COM8": {}, "COM9": {}, |
| 41 | "LPT1": {}, "LPT2": {}, "LPT3": {}, "LPT4": {}, "LPT5": {}, "LPT6": {}, "LPT7": {}, "LPT8": {}, "LPT9": {}, |
| 42 | } |
| 43 | |
| 44 | func validateVersion(version string) error { |
| 45 | if version == "" { |
| 46 | return errors.New("engine: version is required") |
| 47 | } |
| 48 | if !validVersionRe.MatchString(version) { |
| 49 | return fmt.Errorf("engine: invalid version %q", version) |
| 50 | } |
| 51 | if strings.HasSuffix(version, ".") || strings.Contains(version, "..") { |
| 52 | return fmt.Errorf("engine: invalid version %q", version) |
| 53 | } |
| 54 | stem := strings.ToUpper(strings.SplitN(version, ".", 2)[0]) |
| 55 | if _, reserved := windowsReservedNames[stem]; reserved { |
| 56 | return fmt.Errorf("engine: reserved version name %q", version) |
| 57 | } |
| 58 | return nil |
| 59 | } |
| 60 | |
| 61 | // Ensure extracts src into a user-scoped cache directory under baseDir and |
| 62 | // returns the cache path. If the sentinel and content digest already match src |
| 63 | // and directory ownership/permissions are safe, the directory is reused without |
| 64 | // rewriting. version must be a safe single path segment. |
| 65 | // |
| 66 | // Extraction writes to a unique sibling directory and publishes it under a |
| 67 | // filesystem lock so another process cannot remove a completed cache. Concurrent |
| 68 | // callers within the same process share one attempt through a per-cache-dir |
| 69 | // call, and every call validates the cached tree first: a long-lived process |
| 70 | // that finds its cache deleted or corrupted rebuilds it instead of using it. |
| 71 | func Ensure(src fs.FS, baseDir, version string) (string, error) { |
| 72 | if err := validateVersion(version); err != nil { |
| 73 | return "", err |
| 74 | } |
| 75 | parent := cacheParentDir(baseDir) |
| 76 | cacheDir := filepath.Join(parent, version) |
| 77 | if filepath.Dir(cacheDir) != parent || filepath.Base(cacheDir) != version { |
| 78 | return "", fmt.Errorf("engine: cache path escaped parent for version %q", version) |
| 79 | } |
| 80 | |
| 81 | call := getCacheCall(cacheDir) |
| 82 | call.mu.Lock() |
| 83 | live := call.live |
| 84 | owns := live == nil |
| 85 | if owns { |
| 86 | live = &liveAttempt{done: make(chan struct{})} |
| 87 | call.live = live |
| 88 | } |
| 89 | call.mu.Unlock() |
| 90 | |
| 91 | if owns { |
| 92 | live.err = ensureLocked(src, cacheDir, version) |
| 93 | call.mu.Lock() |
| 94 | call.live = nil |
| 95 | call.mu.Unlock() |
| 96 | close(live.done) |
| 97 | } else { |
| 98 | <-live.done |
| 99 | } |
| 100 | if live.err != nil { |
| 101 | return "", live.err |
| 102 | } |
| 103 | return cacheDir, nil |
| 104 | } |
| 105 | |
| 106 | // EnsureUserCache wraps Ensure with the OS user cache dir (or the |
| 107 | // LAST30DAYS_CACHE_DIR override) as base. Production callers use this; tests |
| 108 | // use Ensure with an explicit temp dir. |
| 109 | func EnsureUserCache(src fs.FS, version string) (string, error) { |
| 110 | if override := os.Getenv(CacheEnvOverride); override != "" { |
| 111 | return Ensure(src, override, version) |
| 112 | } |
| 113 | base, err := os.UserCacheDir() |
| 114 | if err != nil { |
| 115 | return "", fmt.Errorf("engine: resolve user cache dir (set %s to override): %w", CacheEnvOverride, err) |
| 116 | } |
| 117 | return Ensure(src, base, version) |
| 118 | } |
| 119 | |
| 120 | func manifestDigest(files map[string][32]byte) string { |
| 121 | paths := make([]string, 0, len(files)) |
| 122 | for p := range files { |
| 123 | paths = append(paths, p) |
| 124 | } |
| 125 | sort.Strings(paths) |
| 126 | manifest := sha256.New() |
| 127 | for _, p := range paths { |
| 128 | sum := files[p] |
| 129 | _, _ = fmt.Fprintf(manifest, "%s\x00%x\n", p, sum) |
| 130 | } |
| 131 | return hex.EncodeToString(manifest.Sum(nil)) |
| 132 | } |
| 133 | |
| 134 | func computeSourceManifest(src fs.FS) (string, map[string][32]byte, error) { |
| 135 | files := map[string][32]byte{} |
| 136 | err := fs.WalkDir(src, ".", func(path string, d fs.DirEntry, walkErr error) error { |
| 137 | if walkErr != nil { |
| 138 | return walkErr |
| 139 | } |
| 140 | if path == "." || d.IsDir() { |
| 141 | return nil |
| 142 | } |
| 143 | in, err := src.Open(path) |
| 144 | if err != nil { |
| 145 | return fmt.Errorf("engine: open %s: %w", path, err) |
| 146 | } |
| 147 | h := sha256.New() |
| 148 | _, copyErr := io.Copy(h, in) |
| 149 | closeErr := in.Close() |
| 150 | if copyErr != nil { |
| 151 | return fmt.Errorf("engine: hash %s: %w", path, copyErr) |
| 152 | } |
| 153 | if closeErr != nil { |
| 154 | return fmt.Errorf("engine: close %s: %w", path, closeErr) |
| 155 | } |
| 156 | var sum [32]byte |
| 157 | copy(sum[:], h.Sum(nil)) |
| 158 | files[path] = sum |
| 159 | return nil |
| 160 | }) |
| 161 | if err != nil { |
| 162 | return "", nil, err |
| 163 | } |
| 164 | return manifestDigest(files), files, nil |
| 165 | } |
| 166 | |
| 167 | func verifyCachedTree(src fs.FS, cacheDir, version string) bool { |
| 168 | if err := verifyPrivateDir(filepath.Dir(cacheDir)); err != nil { |
| 169 | return false |
| 170 | } |
| 171 | if err := verifyPrivateDir(cacheDir); err != nil { |
| 172 | return false |
| 173 | } |
| 174 | if !sentinelMatches(cacheDir, version) { |
| 175 | return false |
| 176 | } |
| 177 | expectedDigest, expectedFiles, err := computeSourceManifest(src) |
| 178 | if err != nil { |
| 179 | return false |
| 180 | } |
| 181 | return cacheReady(cacheDir, version, expectedDigest, expectedFiles) |
| 182 | } |
| 183 | |
| 184 | func ensureLocked(src fs.FS, cacheDir, version string) error { |
| 185 | if verifyCachedTree(src, cacheDir, version) { |
| 186 | if lock, err := openPublicationLock(cacheDir, false); err == nil && lock != nil { |
| 187 | _ = reclaimCacheStages(cacheDir) |
| 188 | _ = lock.Close() |
| 189 | } |
| 190 | return nil |
| 191 | } |
| 192 | parent := filepath.Dir(cacheDir) |
| 193 | if err := ensurePrivateParentDir(parent); err != nil { |
| 194 | return fmt.Errorf("engine: unsafe cache parent (%s, set %s to override): %w", parent, CacheEnvOverride, err) |
| 195 | } |
| 196 | tmpDir, owner, err := prepareCacheStage(src, cacheDir, version) |
| 197 | if err != nil { |
| 198 | return err |
| 199 | } |
| 200 | if tmpDir == "" { |
| 201 | return nil |
| 202 | } |
| 203 | defer func() { |
| 204 | _ = owner.Close() |
| 205 | _ = os.RemoveAll(tmpDir) |
| 206 | _ = os.Remove(owner.Name()) |
| 207 | }() |
| 208 | expectedDigest, expectedFiles, err := extractAll(src, tmpDir) |
| 209 | if err != nil { |
| 210 | return err |
| 211 | } |
| 212 | sentinel := filepath.Join(tmpDir, SentinelFilename) |
| 213 | if err := os.WriteFile(sentinel, []byte(version), 0o600); err != nil { |
| 214 | return fmt.Errorf("engine: write sentinel: %w", err) |
| 215 | } |
| 216 | digestPath := filepath.Join(tmpDir, DigestFilename) |
| 217 | if err := os.WriteFile(digestPath, []byte(expectedDigest), 0o600); err != nil { |
| 218 | return fmt.Errorf("engine: write digest: %w", err) |
| 219 | } |
| 220 | lock, err := openPublicationLock(cacheDir, true) |
| 221 | if err != nil { |
| 222 | return fmt.Errorf("engine: lock cache publication: %w", err) |
| 223 | } |
| 224 | defer func() { _ = lock.Close() }() |
| 225 | // Keep the lock file in place: unlinking it can give concurrent publishers |
| 226 | // different lock inodes. Closing the descriptor releases the lock. |
| 227 | if err := verifyPrivateDir(parent); err != nil { |
| 228 | return fmt.Errorf("engine: unsafe cache parent: %w", err) |
| 229 | } |
| 230 | if cacheReady(cacheDir, version, expectedDigest, expectedFiles) { |
| 231 | return nil |
| 232 | } |
| 233 | if _, err := os.Lstat(cacheDir); err == nil { |
| 234 | if err := verifyPrivateDir(cacheDir); err != nil { |
| 235 | return fmt.Errorf("engine: unsafe existing cache dir: %w", err) |
| 236 | } |
| 237 | } else if !errors.Is(err, os.ErrNotExist) { |
| 238 | return fmt.Errorf("engine: stat old cache: %w", err) |
| 239 | } |
| 240 | if err := os.RemoveAll(cacheDir); err != nil { |
| 241 | return fmt.Errorf("engine: clean old cache: %w", err) |
| 242 | } |
| 243 | if err := os.Rename(tmpDir, cacheDir); err != nil { |
| 244 | return fmt.Errorf("engine: promote tmp cache: %w", err) |
| 245 | } |
| 246 | return nil |
| 247 | } |
| 248 | |
| 249 | func readRegularNoFollow(path string) ([]byte, error) { |
| 250 | f, err := openNoFollowFile(path, os.O_RDONLY, 0) |
| 251 | if err != nil { |
| 252 | return nil, err |
| 253 | } |
| 254 | defer func() { _ = f.Close() }() |
| 255 | return io.ReadAll(io.LimitReader(f, 4096)) |
| 256 | } |
| 257 | |
| 258 | func sentinelMatches(cacheDir, version string) bool { |
| 259 | data, err := readRegularNoFollow(filepath.Join(cacheDir, SentinelFilename)) |
| 260 | if err != nil { |
| 261 | return false |
| 262 | } |
| 263 | return string(data) == version |
| 264 | } |
| 265 | |
| 266 | func cacheReady(cacheDir, version, expectedDigest string, expectedFiles map[string][32]byte) bool { |
| 267 | if err := verifyPrivateDir(filepath.Dir(cacheDir)); err != nil { |
| 268 | return false |
| 269 | } |
| 270 | if err := verifyPrivateDir(cacheDir); err != nil { |
| 271 | return false |
| 272 | } |
| 273 | if !sentinelMatches(cacheDir, version) { |
| 274 | return false |
| 275 | } |
| 276 | digestBytes, err := readRegularNoFollow(filepath.Join(cacheDir, DigestFilename)) |
| 277 | if err != nil || string(digestBytes) != expectedDigest { |
| 278 | return false |
| 279 | } |
| 280 | root, err := os.OpenRoot(cacheDir) |
| 281 | if err != nil { |
| 282 | return false |
| 283 | } |
| 284 | defer func() { _ = root.Close() }() |
| 285 | for relPath, wantSum := range expectedFiles { |
| 286 | nativeRel := filepath.FromSlash(relPath) |
| 287 | f, err := openRootRegularNoFollow(root, cacheDir, nativeRel) |
| 288 | if err != nil { |
| 289 | return false |
| 290 | } |
| 291 | h := sha256.New() |
| 292 | _, copyErr := io.Copy(h, f) |
| 293 | _ = f.Close() |
| 294 | if copyErr != nil { |
| 295 | return false |
| 296 | } |
| 297 | var gotSum [32]byte |
| 298 | copy(gotSum[:], h.Sum(nil)) |
| 299 | if gotSum != wantSum { |
| 300 | return false |
| 301 | } |
| 302 | } |
| 303 | return verifyCachedTreeEntries(cacheDir, root, expectedFiles) |
| 304 | } |
| 305 | |
| 306 | var blockedExtraCacheExts = map[string]struct{}{ |
| 307 | ".py": {}, |
| 308 | ".pyc": {}, |
| 309 | ".pyo": {}, |
| 310 | ".pyw": {}, |
| 311 | ".pth": {}, |
| 312 | ".so": {}, |
| 313 | ".pyd": {}, |
| 314 | ".dll": {}, |
| 315 | ".dylib": {}, |
| 316 | ".egg": {}, |
| 317 | ".whl": {}, |
| 318 | } |
| 319 | |
| 320 | func verifyCachedTreeEntries(cacheDir string, root *os.Root, expectedFiles map[string][32]byte) bool { |
| 321 | errUnexpected := errors.New("unexpected cache entry") |
| 322 | err := fs.WalkDir(root.FS(), ".", func(relPath string, d fs.DirEntry, walkErr error) error { |
| 323 | if walkErr != nil { |
| 324 | return walkErr |
| 325 | } |
| 326 | if relPath == "." { |
| 327 | return nil |
| 328 | } |
| 329 | if d.Type()&fs.ModeSymlink != 0 { |
| 330 | return errUnexpected |
| 331 | } |
| 332 | fullPath := filepath.Join(cacheDir, filepath.FromSlash(relPath)) |
| 333 | if d.IsDir() { |
| 334 | if pathHasSegment(relPath, "__pycache__") { |
| 335 | return errUnexpected |
| 336 | } |
| 337 | return verifyPrivateDir(fullPath) |
| 338 | } |
| 339 | info, err := d.Info() |
| 340 | if err != nil { |
| 341 | return err |
| 342 | } |
| 343 | if err := verifyOwnedRegularFile(info, fullPath); err != nil { |
| 344 | return err |
| 345 | } |
| 346 | if relPath == SentinelFilename || relPath == DigestFilename { |
| 347 | return nil |
| 348 | } |
| 349 | if _, ok := expectedFiles[relPath]; ok { |
| 350 | return nil |
| 351 | } |
| 352 | if pathHasSegment(relPath, "__pycache__") { |
| 353 | return errUnexpected |
| 354 | } |
| 355 | ext := strings.ToLower(filepath.Ext(relPath)) |
| 356 | if _, blocked := blockedExtraCacheExts[ext]; blocked { |
| 357 | return errUnexpected |
| 358 | } |
| 359 | return nil |
| 360 | }) |
| 361 | return err == nil |
| 362 | } |
| 363 | |
| 364 | func pathHasSegment(slashPath, target string) bool { |
| 365 | for _, seg := range strings.Split(slashPath, "/") { |
| 366 | if seg == target { |
| 367 | return true |
| 368 | } |
| 369 | } |
| 370 | return false |
| 371 | } |
| 372 | |
| 373 | func extractAll(src fs.FS, dst string) (string, map[string][32]byte, error) { |
| 374 | root, err := os.OpenRoot(dst) |
| 375 | if err != nil { |
| 376 | return "", nil, fmt.Errorf("engine: open staging root: %w", err) |
| 377 | } |
| 378 | defer func() { _ = root.Close() }() |
| 379 | files := map[string][32]byte{} |
| 380 | err = fs.WalkDir(src, ".", func(path string, d fs.DirEntry, err error) error { |
| 381 | if err != nil { |
| 382 | return err |
| 383 | } |
| 384 | if path == "." { |
| 385 | return nil |
| 386 | } |
| 387 | rel := filepath.FromSlash(path) |
| 388 | if d.IsDir() { |
| 389 | return root.MkdirAll(rel, 0o700) |
| 390 | } |
| 391 | sum, err := copyEmbeddedFile(src, root, path, rel) |
| 392 | if err != nil { |
| 393 | return err |
| 394 | } |
| 395 | files[path] = sum |
| 396 | return nil |
| 397 | }) |
| 398 | if err != nil { |
| 399 | return "", nil, err |
| 400 | } |
| 401 | return manifestDigest(files), files, nil |
| 402 | } |
| 403 | |
| 404 | func copyEmbeddedFile(src fs.FS, root *os.Root, srcPath, relDst string) ([32]byte, error) { |
| 405 | var sum [32]byte |
| 406 | in, err := src.Open(srcPath) |
| 407 | if err != nil { |
| 408 | return sum, fmt.Errorf("engine: open %s: %w", srcPath, err) |
| 409 | } |
| 410 | defer func() { _ = in.Close() }() |
| 411 | if dir := filepath.Dir(relDst); dir != "." { |
| 412 | if err := root.MkdirAll(dir, 0o700); err != nil { |
| 413 | return sum, fmt.Errorf("engine: ensure parent of %s: %w", relDst, err) |
| 414 | } |
| 415 | } |
| 416 | out, err := root.OpenFile(relDst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) |
| 417 | if err != nil { |
| 418 | return sum, fmt.Errorf("engine: create %s: %w", relDst, err) |
| 419 | } |
| 420 | defer func() { _ = out.Close() }() |
| 421 | h := sha256.New() |
| 422 | if _, err := io.Copy(io.MultiWriter(out, h), in); err != nil { |
| 423 | return sum, fmt.Errorf("engine: write %s: %w", relDst, err) |
| 424 | } |
| 425 | copy(sum[:], h.Sum(nil)) |
| 426 | return sum, nil |
| 427 | } |
| 428 | |
| 429 | // cacheCall groups the Ensure calls racing on one cache directory. A caller |
| 430 | // either runs the attempt or waits for the one already in flight, so N |
| 431 | // goroutines on a cold cache pay one extraction. The attempt is forgotten as |
| 432 | // soon as it finishes, so the next call validates the tree again. |
| 433 | type cacheCall struct { |
| 434 | mu sync.Mutex |
| 435 | live *liveAttempt |
| 436 | } |
| 437 | |
| 438 | type liveAttempt struct { |
| 439 | done chan struct{} |
| 440 | err error |
| 441 | } |
| 442 | |
| 443 | var ( |
| 444 | cacheCallsMu sync.Mutex |
| 445 | cacheCalls = map[string]*cacheCall{} |
| 446 | ) |
| 447 | |
| 448 | func getCacheCall(cacheDir string) *cacheCall { |
| 449 | cacheCallsMu.Lock() |
| 450 | defer cacheCallsMu.Unlock() |
| 451 | if c, ok := cacheCalls[cacheDir]; ok { |
| 452 | return c |
| 453 | } |
| 454 | c := &cacheCall{} |
| 455 | cacheCalls[cacheDir] = c |
| 456 | return c |
| 457 | } |
| 458 |