Make restricted artifact reads cooperatively cancellable

This commit is contained in:
2026-11-25 17:28:16 +00:00
parent 3f5b2958cb
commit e74061d5a0
5 changed files with 203 additions and 19 deletions

View File

@@ -3,6 +3,7 @@ package httpadapter
import (
"context"
"errors"
"io"
"math"
"mime"
"os"
@@ -13,6 +14,38 @@ import (
"go.maximumdirect.net/promptkit"
)
type cancelingBodyReader struct {
cancel context.CancelFunc
err error
}
func (r cancelingBodyReader) Read(p []byte) (int, error) {
r.cancel()
return copy(p, "data"), r.err
}
func TestArtifactBodyReadHonorsCancellation(t *testing.T) {
for _, readErr := range []error{nil, io.EOF} {
ctx, cancel := context.WithCancel(context.Background())
body, err := readArtifactBody(ctx, cancelingBodyReader{cancel: cancel, err: readErr}, 4)
if !errors.Is(err, context.Canceled) || body != nil {
t.Errorf("read error %v: body=%q, err=%v", readErr, body, err)
}
}
}
func TestRestrictedArtifactReaderRejectsDirectory(t *testing.T) {
root := t.TempDir()
reader, err := NewRestrictedArtifactReader(root, 0)
if err != nil {
t.Fatal(err)
}
artifact, err := reader.Read(context.Background(), promptkit.File("."))
if err == nil || artifact != nil {
t.Fatalf("expected directory rejection, got %#v, %v", artifact, err)
}
}
func TestRestrictedArtifactReaderReturnsDetachedBodies(t *testing.T) {
root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, "input.txt"), []byte("original"), 0o644); err != nil {