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

@@ -93,6 +93,10 @@ absolute-path, inline, symlink, and byte-limit scenarios remain protected.
## Stage 3: Make Restricted Acquisition Cooperatively Cancellable ## Stage 3: Make Restricted Acquisition Cooperatively Cancellable
**Status: complete.** Acquisition checks cancellation around filesystem reads,
rejects non-regular files, and retains streaming size enforcement. Controlled
reader, directory, Linux FIFO, and real-engine HTTP cancellation tests pass.
**Finding:** 1, including its regression protection. **Finding:** 1, including its regression protection.
**Files:** the HTTP artifact reader/tests; a Linux-specific FIFO test file if **Files:** the HTTP artifact reader/tests; a Linux-specific FIFO test file if
needed, and focused handler integration coverage. needed, and focused handler integration coverage.

View File

@@ -60,7 +60,7 @@ func (r *restrictedArtifactReader) Read(ctx context.Context, ref promptkit.Artif
case promptkit.ArtifactRefInline: case promptkit.ArtifactRefInline:
return readInlineArtifact(ref) return readInlineArtifact(ref)
case promptkit.ArtifactRefFile: case promptkit.ArtifactRefFile:
return r.readFileArtifact(ref) return r.readFileArtifact(ctx, ref)
default: default:
return nil, fmt.Errorf("unsupported artifact reference type %q", ref.Type) return nil, fmt.Errorf("unsupported artifact reference type %q", ref.Type)
} }
@@ -81,7 +81,7 @@ func readInlineArtifact(ref promptkit.ArtifactRef) (*promptkit.Artifact, error)
}, nil }, nil
} }
func (r *restrictedArtifactReader) readFileArtifact(ref promptkit.ArtifactRef) (*promptkit.Artifact, error) { func (r *restrictedArtifactReader) readFileArtifact(ctx context.Context, ref promptkit.ArtifactRef) (*promptkit.Artifact, error) {
if ref.URI == "" { if ref.URI == "" {
return nil, errors.New("file artifact path is required") return nil, errors.New("file artifact path is required")
} }
@@ -93,7 +93,7 @@ func (r *restrictedArtifactReader) readFileArtifact(ref promptkit.ArtifactRef) (
if err != nil { if err != nil {
return nil, err return nil, err
} }
return readArtifactFile(path, r.maxBytes) return readArtifactFile(ctx, path, r.maxBytes)
} }
// resolveLexicalPath checks cleaned path containment without resolving symlinks. // resolveLexicalPath checks cleaned path containment without resolving symlinks.
@@ -120,49 +120,97 @@ func (r *restrictedArtifactReader) resolveLexicalPath(rawPath string) (string, e
return absCandidate, nil return absCandidate, nil
} }
func readArtifactFile(path string, maxBytes int64) (*promptkit.Artifact, error) { func readArtifactFile(ctx context.Context, path string, maxBytes int64) (*promptkit.Artifact, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
info, err := os.Stat(path)
if err != nil {
return nil, fmt.Errorf("failed to stat file %s: %w", path, err)
}
if !info.Mode().IsRegular() {
return nil, fmt.Errorf("file %s is not a regular file", path)
}
if err := ctx.Err(); err != nil {
return nil, err
}
file, err := os.Open(path) file, err := os.Open(path)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to read file %s: %w", path, err) return nil, fmt.Errorf("failed to read file %s: %w", path, err)
} }
defer file.Close() defer file.Close()
info, err := file.Stat() info, err = file.Stat()
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to stat file %s: %w", path, err) return nil, fmt.Errorf("failed to stat file %s: %w", path, err)
} }
if !info.Mode().IsRegular() {
return nil, fmt.Errorf("file %s is not a regular file", path)
}
if maxBytes > 0 && info.Size() > maxBytes { if maxBytes > 0 && info.Size() > maxBytes {
return nil, ErrFileTooLarge return nil, ErrFileTooLarge
} }
var reader io.Reader = file body, err := readArtifactBody(ctx, file, maxBytes)
if maxBytes > 0 {
readLimit := maxBytes
if readLimit < math.MaxInt64 {
readLimit++ // Read one extra byte to detect an oversized file.
}
reader = io.LimitReader(file, readLimit)
}
body, err := io.ReadAll(reader)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to read file %s: %w", path, err) return nil, fmt.Errorf("failed to read file %s: %w", path, err)
} }
if maxBytes > 0 && int64(len(body)) > maxBytes {
return nil, ErrFileTooLarge
}
contentType := mime.TypeByExtension(filepath.Ext(path)) contentType := mime.TypeByExtension(filepath.Ext(path))
if contentType == "" { if contentType == "" {
contentType = fallbackArtifactContentType contentType = fallbackArtifactContentType
} }
return &promptkit.Artifact{ artifact := &promptkit.Artifact{
Name: filepath.Base(path), Name: filepath.Base(path),
ContentType: contentType, ContentType: contentType,
Body: body, Body: body,
URI: path, URI: path,
Size: int64(len(body)), Size: int64(len(body)),
Hash: artifactHash(body), Hash: artifactHash(body),
}, nil }
if err := ctx.Err(); err != nil {
return nil, err
}
return artifact, nil
}
type contextReader struct {
ctx context.Context
reader io.Reader
}
func (r contextReader) Read(p []byte) (int, error) {
if err := r.ctx.Err(); err != nil {
return 0, err
}
n, err := r.reader.Read(p)
if ctxErr := r.ctx.Err(); ctxErr != nil {
return n, ctxErr
}
return n, err
}
func readArtifactBody(ctx context.Context, source io.Reader, maxBytes int64) ([]byte, error) {
var reader io.Reader = contextReader{ctx: ctx, reader: source}
if maxBytes > 0 {
readLimit := maxBytes
if readLimit < math.MaxInt64 {
readLimit++ // Read one extra byte to detect an oversized file.
}
reader = io.LimitReader(reader, readLimit)
}
body, err := io.ReadAll(reader)
if err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
if maxBytes > 0 && int64(len(body)) > maxBytes {
return nil, ErrFileTooLarge
}
return body, nil
} }
func artifactHash(body []byte) string { func artifactHash(body []byte) string {

View File

@@ -0,0 +1,56 @@
package httpadapter
import (
"context"
"path/filepath"
"syscall"
"testing"
"time"
"go.maximumdirect.net/promptkit"
)
func TestRestrictedArtifactReaderRejectsFIFO(t *testing.T) {
root := t.TempDir()
path := filepath.Join(root, "pipe")
if err := syscall.Mkfifo(path, 0o600); err != nil {
t.Fatal(err)
}
reader, err := NewRestrictedArtifactReader(root, 0)
if err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() {
_, err := reader.Read(context.Background(), promptkit.File("pipe"))
done <- err
}()
select {
case err := <-done:
if err == nil {
t.Fatal("expected FIFO rejection")
}
return
case <-time.After(time.Second):
}
// Release an old blocking FIFO open before joining the worker.
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
fd, err := syscall.Open(path, syscall.O_WRONLY|syscall.O_NONBLOCK, 0)
if err == nil {
_ = syscall.Close(fd)
break
}
select {
case <-done:
t.Fatal("FIFO read did not reject promptly")
case <-time.After(10 * time.Millisecond):
}
}
select {
case <-done:
t.Fatal("FIFO read did not reject promptly")
case <-time.After(time.Second):
t.Fatal("FIFO reader could not be released")
}
}

View File

@@ -3,6 +3,7 @@ package httpadapter
import ( import (
"context" "context"
"errors" "errors"
"io"
"math" "math"
"mime" "mime"
"os" "os"
@@ -13,6 +14,38 @@ import (
"go.maximumdirect.net/promptkit" "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) { func TestRestrictedArtifactReaderReturnsDetachedBodies(t *testing.T) {
root := t.TempDir() root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, "input.txt"), []byte("original"), 0o644); err != nil { if err := os.WriteFile(filepath.Join(root, "input.txt"), []byte("original"), 0o644); err != nil {

View File

@@ -28,6 +28,49 @@ type fakeRunner struct {
type runnerFunc func(context.Context, promptkit.RunRequest) (*promptkit.RunResult, error) type runnerFunc func(context.Context, promptkit.RunRequest) (*promptkit.RunResult, error)
type cancelingArtifactReader struct {
cancel context.CancelFunc
reader promptkit.ArtifactReader
}
func (r cancelingArtifactReader) Read(ctx context.Context, ref promptkit.ArtifactRef) (*promptkit.Artifact, error) {
r.cancel()
return r.reader.Read(ctx, ref)
}
func TestHandlerCancellationDuringRestrictedArtifactAcquisition(t *testing.T) {
root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, "input.txt"), []byte("input"), 0o644); err != nil {
t.Fatal(err)
}
reader, err := NewRestrictedArtifactReader(root, 0)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
client := &blockingLLMClient{started: make(chan struct{}, 1), release: make(chan struct{})}
close(client.release)
engine := newHandlerEngineWithOptions(t, promptkit.WithArtifactReader(cancelingArtifactReader{cancel: cancel, reader: reader}), promptkit.WithLLMClient(client))
var runErr error
h := NewHandler(runnerFunc(func(ctx context.Context, req promptkit.RunRequest) (*promptkit.RunResult, error) {
result, err := engine.Run(ctx, req)
runErr = err
return result, err
}))
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequestWithContext(ctx, http.MethodPost, "/v1/runs", strings.NewReader(`{"prompt_id":"p","inputs":{"input":{"type":"file","uri":"input.txt"}}}`)))
assertHTTPErrorCode(t, w, http.StatusRequestTimeout, "request_canceled")
if !errors.Is(runErr, context.Canceled) {
t.Fatalf("engine lost cancellation identity: %v", runErr)
}
select {
case <-client.started:
t.Fatal("provider was dispatched after cancellation")
default:
}
}
func (run runnerFunc) Run(ctx context.Context, req promptkit.RunRequest) (*promptkit.RunResult, error) { func (run runnerFunc) Run(ctx context.Context, req promptkit.RunRequest) (*promptkit.RunResult, error) {
return run(ctx, req) return run(ctx, req)
} }