package pp import ( "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "io" "os" "knowledge-governance/internal/governance" ) type RecoveryReport struct { Recovered int VerifiedBytes int64 } const LegacyMaxBytes int64 = 50 * 1024 * 1024 type manifestDocument struct { Results []manifestItem `json:"results"` } type manifestItem struct { URL string `json:"url"` LocalPath string `json:"local_path"` Bytes int64 `json:"bytes"` SHA256 string `json:"sha256"` Status string `json:"status"` SourceIDs []string `json:"source_ids"` } func RecoverMissingSHA256(snapshot Snapshot, reader io.Reader) (Snapshot, RecoveryReport, error) { var manifest manifestDocument if err := json.NewDecoder(reader).Decode(&manifest); err != nil { return Snapshot{}, RecoveryReport{}, fmt.Errorf("decode download manifest: %w", err) } bySourceHash := make(map[string]manifestItem, len(manifest.Results)) for _, item := range manifest.Results { digest := sha256.Sum256([]byte(item.URL)) bySourceHash[hex.EncodeToString(digest[:])] = item } result := snapshot result.Items = append([]Item(nil), snapshot.Items...) report := RecoveryReport{} for index := range result.Items { item := &result.Items[index] if item.SHA256 != "" { continue } artifact, ok := bySourceHash[item.SourceURLHash] if !ok { return Snapshot{}, RecoveryReport{}, fmt.Errorf("missing manifest artifact for source hash %s", item.SourceURLHash) } if !governance.ValidSHA256(artifact.SHA256) { return Snapshot{}, RecoveryReport{}, fmt.Errorf("manifest artifact has invalid SHA-256 for source hash %s", item.SourceURLHash) } if artifact.Bytes != item.Bytes { return Snapshot{}, RecoveryReport{}, fmt.Errorf("manifest size differs from ledger for source hash %s", item.SourceURLHash) } if artifact.Bytes > LegacyMaxBytes { return Snapshot{}, RecoveryReport{}, fmt.Errorf("manifest artifact exceeds the legacy 50 MiB limit for source hash %s", item.SourceURLHash) } file, err := os.Open(artifact.LocalPath) if err != nil { return Snapshot{}, RecoveryReport{}, fmt.Errorf("open manifest artifact for source hash %s: %w", item.SourceURLHash, err) } digest := sha256.New() bytesRead, copyErr := io.Copy(digest, file) closeErr := file.Close() if copyErr != nil { return Snapshot{}, RecoveryReport{}, fmt.Errorf("hash manifest artifact for source hash %s: %w", item.SourceURLHash, copyErr) } if closeErr != nil { return Snapshot{}, RecoveryReport{}, fmt.Errorf("close manifest artifact for source hash %s: %w", item.SourceURLHash, closeErr) } if bytesRead != artifact.Bytes { return Snapshot{}, RecoveryReport{}, fmt.Errorf("manifest artifact size mismatch for source hash %s", item.SourceURLHash) } actual := hex.EncodeToString(digest.Sum(nil)) if actual != artifact.SHA256 { return Snapshot{}, RecoveryReport{}, fmt.Errorf("manifest artifact SHA-256 mismatch for source hash %s", item.SourceURLHash) } item.SHA256 = actual report.Recovered++ report.VerifiedBytes += bytesRead } return result, report, nil }