fetch_ml/internal/worker/artifacts.go
Jeremie Fraeys 92aab06d76
feat(security): implement comprehensive security hardening phases 1-5,7
Implements defense-in-depth security for HIPAA and multi-tenant requirements:

**Phase 1 - File Ingestion Security:**
- SecurePathValidator with symlink resolution and path boundary enforcement
  in internal/fileutil/secure.go
- Magic bytes validation for ML artifacts (safetensors, GGUF, HDF5, numpy)
  in internal/fileutil/filetype.go
- Dangerous extension blocking (.pt, .pkl, .exe, .sh, .zip)
- Upload limits (10GB size, 100MB/s rate, 10 uploads/min)

**Phase 2 - Sandbox Hardening:**
- ApplySecurityDefaults() with secure-by-default principle
  - network_mode: none, read_only_root: true, no_new_privileges: true
  - drop_all_caps: true, user_ns: true, run_as_uid/gid: 1000
- PodmanSecurityConfig and BuildSecurityArgs() in internal/container/podman.go
- BuildPodmanCommand now accepts full security configuration
- Container executor passes SandboxConfig to Podman command builder
- configs/seccomp/default-hardened.json blocks dangerous syscalls
  (ptrace, mount, reboot, kexec_load, open_by_handle_at)

**Phase 3 - Secrets Management:**
- expandSecrets() for environment variable expansion using ${VAR} syntax
- validateNoPlaintextSecrets() with entropy-based detection
- Pattern matching for AWS, GitHub, GitLab, OpenAI, Stripe tokens
- Shannon entropy calculation (>4 bits/char triggers detection)
- Secrets expanded during LoadConfig() before validation

**Phase 5 - HIPAA Audit Logging:**
- Tamper-evident chain hashing with SHA-256 in internal/audit/audit.go
- Event struct extended with PrevHash, EventHash, SequenceNum
- File access event types: EventFileRead, EventFileWrite, EventFileDelete
- LogFileAccess() helper for HIPAA compliance
- VerifyChain() function for tamper detection

**Supporting Changes:**
- Add DeleteJob() and DeleteJobsByPrefix() to storage package
- Integrate SecurePathValidator in artifact scanning
2026-02-23 18:00:33 -05:00

124 lines
2.8 KiB
Go

package worker
import (
"fmt"
"io/fs"
"path/filepath"
"sort"
"strings"
"time"
"github.com/jfraeys/fetch_ml/internal/fileutil"
"github.com/jfraeys/fetch_ml/internal/manifest"
)
func scanArtifacts(runDir string, includeAll bool) (*manifest.Artifacts, error) {
runDir = strings.TrimSpace(runDir)
if runDir == "" {
return nil, fmt.Errorf("run dir is empty")
}
// Validate and canonicalize the runDir before any operations
validator := fileutil.NewSecurePathValidator(runDir)
validatedRunDir, err := validator.ValidatePath("")
if err != nil {
return nil, fmt.Errorf("invalid run directory: %w", err)
}
var files []manifest.ArtifactFile
var total int64
now := time.Now().UTC()
err = filepath.WalkDir(validatedRunDir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if path == validatedRunDir {
return nil
}
// Security: Validate each path is still within runDir
// This catches any symlink escapes or path traversal attempts during walk
rel, err := filepath.Rel(validatedRunDir, path)
if err != nil {
return fmt.Errorf("path escape detected during artifact scan: %w", err)
}
rel = filepath.ToSlash(rel)
// Check for path traversal patterns in the relative path
if strings.Contains(rel, "..") {
return fmt.Errorf("path traversal attempt detected: %s", rel)
}
// Standard exclusions (always apply)
if rel == manifestFilename {
return nil
}
if strings.HasSuffix(rel, "/"+manifestFilename) {
return nil
}
// Optional exclusions (skipped when includeAll is true)
if !includeAll {
if rel == "code" || strings.HasPrefix(rel, "code/") {
if d.IsDir() {
return fs.SkipDir
}
return nil
}
if rel == "snapshot" || strings.HasPrefix(rel, "snapshot/") {
if d.IsDir() {
return fs.SkipDir
}
return nil
}
if strings.HasSuffix(rel, ".log") {
return nil
}
if d.Type()&fs.ModeSymlink != 0 {
// Skip symlinks - they could point outside the directory
return nil
}
}
if d.IsDir() {
return nil
}
info, err := d.Info()
if err != nil {
return err
}
files = append(files, manifest.ArtifactFile{
Path: rel,
SizeBytes: info.Size(),
Modified: info.ModTime().UTC(),
})
total += info.Size()
return nil
})
if err != nil {
return nil, err
}
sort.Slice(files, func(i, j int) bool {
return files[i].Path < files[j].Path
})
return &manifest.Artifacts{
DiscoveryTime: now,
Files: files,
TotalSizeBytes: total,
}, nil
}
const manifestFilename = "run_manifest.json"
// ScanArtifacts is an exported wrapper for testing/benchmarking.
// When includeAll is false, excludes code/, snapshot/, *.log files, and symlinks.
func ScanArtifacts(runDir string, includeAll bool) (*manifest.Artifacts, error) {
return scanArtifacts(runDir, includeAll)
}