|
| 1 | +// Package contenthash provides deterministic SHA-256 content hashing for |
| 2 | +// package integrity verification. |
| 3 | +package contenthash |
| 4 | + |
| 5 | +import ( |
| 6 | + "crypto/sha256" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "os" |
| 10 | + "path/filepath" |
| 11 | + "sort" |
| 12 | +) |
| 13 | + |
| 14 | +const ( |
| 15 | + // MarkerFilename is the cache-pin marker excluded from package hashes. |
| 16 | + MarkerFilename = ".apm-pin" |
| 17 | +) |
| 18 | + |
| 19 | +var excludedDirs = map[string]bool{ |
| 20 | + ".git": true, |
| 21 | + "__pycache__": true, |
| 22 | +} |
| 23 | + |
| 24 | +// emptyHash is the well-known hash for an empty or missing package. |
| 25 | +var emptyHash = "sha256:" + func() string { |
| 26 | + h := sha256.Sum256([]byte{}) |
| 27 | + return fmt.Sprintf("%x", h) |
| 28 | +}() |
| 29 | + |
| 30 | +// ComputePackageHash computes a deterministic SHA-256 hash of a package's |
| 31 | +// file tree. The hash is computed over sorted file paths and their contents, |
| 32 | +// making it independent of filesystem ordering and metadata. |
| 33 | +// |
| 34 | +// Returns a hash string in format "sha256:<hex_digest>". |
| 35 | +func ComputePackageHash(packagePath string) (string, error) { |
| 36 | + info, err := os.Lstat(packagePath) |
| 37 | + if err != nil || !info.IsDir() { |
| 38 | + return emptyHash, nil |
| 39 | + } |
| 40 | + |
| 41 | + var relFiles []string |
| 42 | + err = filepath.WalkDir(packagePath, func(path string, d os.DirEntry, err error) error { |
| 43 | + if err != nil { |
| 44 | + return err |
| 45 | + } |
| 46 | + // Skip symlinks |
| 47 | + if d.Type()&os.ModeSymlink != 0 { |
| 48 | + return nil |
| 49 | + } |
| 50 | + rel, relErr := filepath.Rel(packagePath, path) |
| 51 | + if relErr != nil { |
| 52 | + return relErr |
| 53 | + } |
| 54 | + if rel == "." { |
| 55 | + return nil |
| 56 | + } |
| 57 | + // Skip excluded directories |
| 58 | + parts := splitPath(rel) |
| 59 | + for _, part := range parts { |
| 60 | + if excludedDirs[part] { |
| 61 | + if d.IsDir() { |
| 62 | + return filepath.SkipDir |
| 63 | + } |
| 64 | + return nil |
| 65 | + } |
| 66 | + } |
| 67 | + if d.IsDir() { |
| 68 | + return nil |
| 69 | + } |
| 70 | + // Exclude root-level marker files |
| 71 | + if len(parts) == 1 && parts[0] == MarkerFilename { |
| 72 | + return nil |
| 73 | + } |
| 74 | + relFiles = append(relFiles, filepath.ToSlash(rel)) |
| 75 | + return nil |
| 76 | + }) |
| 77 | + if err != nil { |
| 78 | + return "", fmt.Errorf("contenthash: walking %s: %w", packagePath, err) |
| 79 | + } |
| 80 | + |
| 81 | + if len(relFiles) == 0 { |
| 82 | + return emptyHash, nil |
| 83 | + } |
| 84 | + |
| 85 | + sort.Strings(relFiles) |
| 86 | + |
| 87 | + h := sha256.New() |
| 88 | + for _, rel := range relFiles { |
| 89 | + h.Write([]byte(rel)) |
| 90 | + f, openErr := os.Open(filepath.Join(packagePath, filepath.FromSlash(rel))) |
| 91 | + if openErr != nil { |
| 92 | + return "", fmt.Errorf("contenthash: opening %s: %w", rel, openErr) |
| 93 | + } |
| 94 | + _, copyErr := io.Copy(h, f) |
| 95 | + f.Close() |
| 96 | + if copyErr != nil { |
| 97 | + return "", fmt.Errorf("contenthash: reading %s: %w", rel, copyErr) |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + return fmt.Sprintf("sha256:%x", h.Sum(nil)), nil |
| 102 | +} |
| 103 | + |
| 104 | +// ComputeFileHash computes SHA-256 of a single file's contents. |
| 105 | +// Returns "sha256:<hex_digest>". Returns the empty-content hash when the |
| 106 | +// path does not exist or is not a regular file. |
| 107 | +func ComputeFileHash(filePath string) (string, error) { |
| 108 | + info, err := os.Lstat(filePath) |
| 109 | + if err != nil { |
| 110 | + return emptyHash, nil |
| 111 | + } |
| 112 | + if !info.Mode().IsRegular() { |
| 113 | + return emptyHash, nil |
| 114 | + } |
| 115 | + f, err := os.Open(filePath) |
| 116 | + if err != nil { |
| 117 | + return emptyHash, nil |
| 118 | + } |
| 119 | + defer f.Close() |
| 120 | + h := sha256.New() |
| 121 | + if _, err = io.Copy(h, f); err != nil { |
| 122 | + return "", fmt.Errorf("contenthash: reading %s: %w", filePath, err) |
| 123 | + } |
| 124 | + return fmt.Sprintf("sha256:%x", h.Sum(nil)), nil |
| 125 | +} |
| 126 | + |
| 127 | +// VerifyPackageHash verifies a package's content matches the expected hash. |
| 128 | +// Returns true if hash matches. |
| 129 | +func VerifyPackageHash(packagePath, expectedHash string) (bool, error) { |
| 130 | + actual, err := ComputePackageHash(packagePath) |
| 131 | + if err != nil { |
| 132 | + return false, err |
| 133 | + } |
| 134 | + return actual == expectedHash, nil |
| 135 | +} |
| 136 | + |
| 137 | +// splitPath splits a slash-separated relative path into its components. |
| 138 | +func splitPath(p string) []string { |
| 139 | + s := filepath.ToSlash(p) |
| 140 | + var parts []string |
| 141 | + start := 0 |
| 142 | + for i := 0; i <= len(s); i++ { |
| 143 | + if i == len(s) || s[i] == '/' { |
| 144 | + if seg := s[start:i]; seg != "" && seg != "." { |
| 145 | + parts = append(parts, seg) |
| 146 | + } |
| 147 | + start = i + 1 |
| 148 | + } |
| 149 | + } |
| 150 | + return parts |
| 151 | +} |
0 commit comments