Files
Kelx/fs-reviewed-mutations.go
2026-11-30 16:32:37 +00:00

62 lines
1.7 KiB
Go

package main
import (
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"os"
)
type fsWriteRequest struct {
Path string `json:"path"`
Server string `json:"server"`
Content string `json:"content"`
Encoding string `json:"encoding"`
Mode string `json:"mode"`
ExpectedSHA256 string `json:"expectedSha256"`
EditorBaseHash string `json:"editorBaseSha256"`
}
type fsDeleteRequest struct {
Path string `json:"path"`
Server string `json:"server"`
IsDir bool `json:"isDir"`
ExpectedSHA256 string `json:"expectedSha256"`
}
const maxReviewedFileBytes = 16_000
func (body fsWriteRequest) expectedFileHash() (string, int64) {
if body.ExpectedSHA256 != "" {
return body.ExpectedSHA256, maxReviewedFileBytes
}
return body.EditorBaseHash, maxEditorRead
}
// adpanel:agent-action-review - match the reviewed bytes at the node while the write scope is locked.
func matchReviewedFile(root *safeRoot, rel, expected string) bool {
return matchFileHash(root, rel, expected, maxReviewedFileBytes)
}
func matchFileHash(root *safeRoot, rel, expected string, maxBytes int64) bool {
if len(expected) != sha256.Size*2 {
return false
}
file, info, err := safeOpenRegularAt(root, rel, os.O_RDONLY|openNoFollow, 0)
if err != nil {
return false
}
defer file.Close()
if info.Size() > maxBytes {
return false
}
hash := sha256.New()
size, err := io.Copy(hash, io.LimitReader(file, maxBytes+1))
return err == nil && size <= maxBytes && hex.EncodeToString(hash.Sum(nil)) == expected
}
func refuseChangedReviewedFile(w http.ResponseWriter) {
jsonWrite(w, http.StatusConflict, map[string]any{"ok": false, "error": "file changed on disk", "code": "file_changed_on_disk"})
}