feat: define P2 host workspace command contract

This commit is contained in:
2026-08-11 00:24:31 +02:00
parent 38c8398bc1
commit ccaf8c1be0
12 changed files with 808 additions and 1 deletions
@@ -3,6 +3,7 @@
package safeio
import (
"io/fs"
"os"
"path/filepath"
"strings"
@@ -94,3 +95,48 @@ func closeWindowsHandles(handles []windows.Handle) {
windows.CloseHandle(handle)
}
}
func writeCanonicalExclusive(path string, contents []byte, mode fs.FileMode) error {
if err := ValidateCanonicalPath(path); err != nil || len(contents) > 16<<20 || mode.Perm() == 0 || mode.Perm()&0o077 != 0 {
return ErrUnsafeFile
}
h, err := windows.CreateFile(windows.StringToUTF16Ptr(path), windows.GENERIC_WRITE, 0, nil, windows.CREATE_NEW, windows.FILE_ATTRIBUTE_NORMAL|windows.FILE_FLAG_OPEN_REPARSE_POINT, 0)
if err != nil {
return ErrUnsafeFile
}
f := os.NewFile(uintptr(h), "thothctl-safeio-output")
if f == nil {
windows.CloseHandle(h)
return ErrUnsafeFile
}
defer f.Close()
if _, err := f.Write(contents); err != nil {
return ErrUnsafeFile
}
return f.Sync()
}
func validateCanonicalOutputPath(path string) error {
if err := ValidateCanonicalPath(path); err != nil {
return err
}
volume := filepath.VolumeName(path)
root := volume + string(filepath.Separator)
components := strings.Split(strings.TrimPrefix(path, root), string(filepath.Separator))
if volume == "" || len(components) < 2 || components[0] == "" {
return ErrUnsafeFile
}
current := root
for _, component := range components[:len(components)-1] {
current = filepath.Join(current, component)
h, err := openWindowsComponent(current, true)
if err != nil {
return ErrUnsafeFile
}
windows.CloseHandle(h)
}
if _, err := os.Lstat(filepath.Join(current, components[len(components)-1])); err == nil || !os.IsNotExist(err) {
return ErrUnsafeFile
}
return nil
}