package wire import ( "encoding/json" "path" "strings" "unicode" "unicode/utf8" ) const ( ChangeFileAdded = "added" ChangeFileModified = "modified" ChangeFileDeleted = "deleted" ChangeFileRenamed = "renamed" ) // ChangeFiles is presentation only. Merge authority consumes ChangeFacts, // independently measured by Review, never these Engineering measurements. type ChangeFiles struct { Base string `json:"base"` SHA string `json:"sha"` Files int `json:"files"` Additions int `json:"additions"` Deletions int `json:"deletions"` Binary int `json:"binary"` Entries []ChangedFile `json:"entries"` Truncated bool `json:"truncated"` } type ChangedFile struct { Path string `json:"path"` OldPath string `json:"old_path,omitempty"` Status string `json:"status"` Additions int `json:"additions"` Deletions int `json:"deletions"` Binary bool `json:"binary"` } // MaxChangeFilesBytes leaves room for the rest of a bounded StepReport. const MaxChangeFilesBytes = 96 << 10 func ValidChangePath(s string) bool { return s != "" && len(s) <= 4096 && utf8.ValidString(s) && !strings.HasPrefix(s, "/") && s != "." && s != ".." && !strings.HasPrefix(s, "../") && path.Clean(s) == s && !strings.ContainsAny(s, "\\") && strings.IndexFunc(s, unsafeChangePathRune) < 0 } // Keep in sync with native ThinChangeFiles.path and the shared path fixture. // Other format characters (for example ZWJ in emoji names) are valid. func unsafeChangePathRune(r rune) bool { return unicode.IsControl(r) || r == 0x061c || r == 0x200e || r == 0x200f || r >= 0x202a && r <= 0x202e || r >= 0x2066 && r <= 0x2069 } func ValidChangeFiles(f *ChangeFiles) bool { if f == nil || f.Entries == nil || f.Base != "" && len(f.Base) != 40 || len(f.SHA) != 40 || strings.Trim(f.Base+f.SHA, "0123456789abcdef") != "" || f.Files < 0 || f.Additions < 0 || f.Deletions < 0 || f.Binary < 0 || f.Binary > f.Files || len(f.Entries) > MaxChangeEntries || len(f.Entries) > f.Files || f.Truncated != (len(f.Entries) < f.Files) { return false } a, d, b := 0, 0, 0 seen := map[string]bool{} for _, e := range f.Entries { if !ValidChangePath(e.Path) || seen[e.Path] || e.Additions < 0 || e.Deletions < 0 { return false } seen[e.Path] = true switch e.Status { case ChangeFileAdded, ChangeFileModified, ChangeFileDeleted: if e.OldPath != "" { return false } case ChangeFileRenamed: if !ValidChangePath(e.OldPath) || e.OldPath == e.Path { return false } default: return false } // Subtraction checks also prevent integer overflow. if e.Additions > f.Additions-a || e.Deletions > f.Deletions-d { return false } a += e.Additions d += e.Deletions if e.Binary { b++ if e.Additions != 0 || e.Deletions != 0 { return false } } } if b > f.Binary || !f.Truncated && (a != f.Additions || d != f.Deletions || b != f.Binary) { return false } raw, err := json.Marshal(f) return err == nil && len(raw) <= MaxChangeFilesBytes }