Merge branch 'worktree-agent-ae487572986d7a387' into integrate/chat-ntfy-attachments

This commit is contained in:
2026-10-30 21:05:32 +00:00
18 changed files with 1397 additions and 29 deletions
+3
View File
@@ -215,6 +215,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
case protocol.ChatShellOutput:
handleChatShellOutput(ctx, request, broker, registry, write)
return true
case protocol.ChatAttachmentImage:
handleChatAttachmentImage(request, broker, write)
return true
}
return false
}
+136
View File
@@ -0,0 +1,136 @@
package server
import (
"encoding/base64"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"os"
"path/filepath"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// maxChatAttachmentImageBytes bounds one chat_attachment_image reply. The
// bytes travel base64-encoded in a single websocket frame that the server must
// write within its per-frame deadline, and clients serialize requests, so a
// preview stays well below the 100 MiB upload limit.
const maxChatAttachmentImageBytes = 4 << 20
// errChatAttachmentGone is the reply for a stored file that was collected by
// retention or never existed; clients show it as "no longer available".
var errChatAttachmentGone = errors.New("image is no longer available")
// chatAttachmentImageTypes are the sniffed types a client can draw. SVG and
// anything unrecognised stay a plain file row.
var chatAttachmentImageTypes = map[string]bool{
"image/png": true,
"image/jpeg": true,
"image/gif": true,
"image/webp": true,
"image/bmp": true,
}
// handleChatAttachmentImage returns one image file the operator attached, so a
// transcript can draw it after a reload. Only regular files directly inside the
// private attachment store are readable; anything else is refused before it is
// opened.
func handleChatAttachmentImage(request protocol.Message, broker chatBroker, write func(protocol.Message) error) {
fail := func(message string) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: message})
}
if broker == nil {
fail("chat is not configured on this server")
return
}
query := request.ChatAttachmentImageRequest
if query == nil || query.URI == "" {
fail("a chat_attachment_image_request with a uri is required")
return
}
data, mime, err := readChatAttachmentImage(query.URI)
if err != nil {
fail(err.Error())
return
}
_ = write(protocol.Message{Type: protocol.ChatAttachmentImage, ID: request.ID, ChatAttachmentImage: &protocol.ChatAttachmentImageContent{
URI: query.URI,
Mime: mime,
Size: int64(len(data)),
Data: base64.StdEncoding.EncodeToString(data),
}})
}
// readChatAttachmentImage resolves a file:// URI to one regular file in the
// attachment store and returns its bytes and sniffed image type.
func readChatAttachmentImage(uri string) ([]byte, string, error) {
notStored := errors.New("not a stored chat attachment")
u, err := url.Parse(uri)
if err != nil || u.Scheme != "file" || u.Host != "" || u.User != nil || u.Opaque != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" {
return nil, "", notStored
}
path := u.Path
if !filepath.IsAbs(path) || filepath.Clean(path) != path {
return nil, "", notStored
}
dir, err := chatAttachmentDir()
if err != nil {
return nil, "", err
}
name := filepath.Base(path)
if filepath.Dir(path) != dir || name == "." || name == ".." || name == string(filepath.Separator) {
return nil, "", notStored
}
dirInfo, err := os.Lstat(dir)
if errors.Is(err, fs.ErrNotExist) {
return nil, "", errChatAttachmentGone
}
if err != nil || !dirInfo.IsDir() {
return nil, "", errors.New("attachment storage must be a directory, not a symlink")
}
root, err := os.OpenRoot(dir)
if err != nil {
return nil, "", err
}
defer root.Close()
if actual, err := root.Stat("."); err != nil || !os.SameFile(dirInfo, actual) {
return nil, "", errors.New("chat attachment storage changed while opening")
}
info, err := root.Lstat(name)
if errors.Is(err, fs.ErrNotExist) {
return nil, "", errChatAttachmentGone
}
if err != nil || !info.Mode().IsRegular() {
return nil, "", notStored
}
if info.Size() > maxChatAttachmentImageBytes {
return nil, "", fmt.Errorf("image is too large to preview (over %d MiB)", maxChatAttachmentImageBytes>>20)
}
file, err := root.Open(name)
if errors.Is(err, fs.ErrNotExist) {
return nil, "", errChatAttachmentGone
}
if err != nil {
return nil, "", notStored
}
defer file.Close()
opened, err := file.Stat()
if err != nil || !os.SameFile(info, opened) || !opened.Mode().IsRegular() {
return nil, "", errors.New("attachment changed while opening")
}
data, err := io.ReadAll(io.LimitReader(file, maxChatAttachmentImageBytes+1))
if err != nil {
return nil, "", fmt.Errorf("read attachment: %w", err)
}
if len(data) > maxChatAttachmentImageBytes {
return nil, "", fmt.Errorf("image is too large to preview (over %d MiB)", maxChatAttachmentImageBytes>>20)
}
mime := http.DetectContentType(data)
if !chatAttachmentImageTypes[mime] {
return nil, "", errors.New("attachment is not a previewable image")
}
return data, mime, nil
}
@@ -0,0 +1,149 @@
package server
import (
"context"
"encoding/base64"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// pngHeader is enough for content sniffing to report image/png.
var pngHeader = []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00")
func attachmentImageStore(t *testing.T) string {
t.Helper()
dir := filepath.Join(t.TempDir(), "uploads")
if err := os.Mkdir(dir, 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("PIPELINES_CHAT_ATTACHMENT_DIR", dir)
return dir
}
func fileURI(path string) string { return (&url.URL{Scheme: "file", Path: path}).String() }
func requestAttachmentImage(t *testing.T, uri string) protocol.Message {
t.Helper()
var reply protocol.Message
request := protocol.Message{Type: protocol.ChatAttachmentImage, ID: "img-1", ChatAttachmentImageRequest: &protocol.ChatAttachmentImageRequest{URI: uri}}
handled := handleChat(context.Background(), request, &fakeChat{}, nil, nil, "conn-test", func(message protocol.Message) error {
reply = message
return nil
})
if !handled {
t.Fatal("chat_attachment_image was not dispatched")
}
if reply.ID != "img-1" {
t.Fatalf("reply id = %q", reply.ID)
}
return reply
}
func TestChatAttachmentImageServesStoredImage(t *testing.T) {
dir := attachmentImageStore(t)
path := filepath.Join(dir, "up-0123456789abcdef0123456789abcdef-shot one.png")
if err := os.WriteFile(path, pngHeader, 0o600); err != nil {
t.Fatal(err)
}
reply := requestAttachmentImage(t, fileURI(path))
if reply.Type != protocol.ChatAttachmentImage || reply.ChatAttachmentImage == nil {
t.Fatalf("reply = %+v", reply)
}
got := reply.ChatAttachmentImage
data, err := base64.StdEncoding.DecodeString(got.Data)
if err != nil || string(data) != string(pngHeader) {
t.Fatalf("data = %q err=%v", data, err)
}
if got.Mime != "image/png" || got.Size != int64(len(pngHeader)) || got.URI != fileURI(path) {
t.Fatalf("content = %+v", got)
}
}
func TestChatAttachmentImageRefusesOutsideAndUnsafeReferences(t *testing.T) {
dir := attachmentImageStore(t)
outside := filepath.Join(filepath.Dir(dir), "secret.png")
if err := os.WriteFile(outside, pngHeader, 0o600); err != nil {
t.Fatal(err)
}
nested := filepath.Join(dir, "nested")
if err := os.Mkdir(nested, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(nested, "inner.png"), pngHeader, 0o600); err != nil {
t.Fatal(err)
}
link := filepath.Join(dir, "link.png")
if err := os.Symlink(outside, link); err != nil {
t.Fatal(err)
}
text := filepath.Join(dir, "notes.txt")
if err := os.WriteFile(text, []byte("plain text, not an image"), 0o600); err != nil {
t.Fatal(err)
}
cases := map[string]string{
"outside": fileURI(outside),
"traversal": "file://" + dir + "/../secret.png",
"encoded": "file://" + dir + "/%2e%2e/secret.png",
"nested": fileURI(filepath.Join(nested, "inner.png")),
"symlink": fileURI(link),
"directory": fileURI(nested),
"store itself": fileURI(dir),
"relative": "file:secret.png",
"remote host": "file://example.com" + outside,
"http": "https://example.com/a.png",
"data": "data:image/png;base64,AAAA",
"query": fileURI(outside) + "?x=1",
"not an image": fileURI(text),
"plain path": outside,
"fragment": fileURI(outside) + "#top",
}
for name, uri := range cases {
t.Run(name, func(t *testing.T) {
reply := requestAttachmentImage(t, uri)
if reply.Type != protocol.Error || reply.ChatAttachmentImage != nil {
t.Fatalf("%s was served: %+v", uri, reply)
}
})
}
}
func TestChatAttachmentImageMissingAndOversize(t *testing.T) {
dir := attachmentImageStore(t)
missing := requestAttachmentImage(t, fileURI(filepath.Join(dir, "up-gone.png")))
if missing.Type != protocol.Error || !strings.Contains(missing.Error, "no longer available") {
t.Fatalf("missing = %+v", missing)
}
large := filepath.Join(dir, "large.png")
body := append(append([]byte{}, pngHeader...), make([]byte, maxChatAttachmentImageBytes)...)
if err := os.WriteFile(large, body, 0o600); err != nil {
t.Fatal(err)
}
oversize := requestAttachmentImage(t, fileURI(large))
if oversize.Type != protocol.Error || !strings.Contains(oversize.Error, "too large") {
t.Fatalf("oversize = %+v", oversize)
}
if err := os.RemoveAll(dir); err != nil {
t.Fatal(err)
}
gone := requestAttachmentImage(t, fileURI(filepath.Join(dir, "up-any.png")))
if gone.Type != protocol.Error || !strings.Contains(gone.Error, "no longer available") {
t.Fatalf("store gone = %+v", gone)
}
}
func TestChatAttachmentImageRequiresRequestBody(t *testing.T) {
attachmentImageStore(t)
var reply protocol.Message
handleChat(context.Background(), protocol.Message{Type: protocol.ChatAttachmentImage, ID: "x"}, &fakeChat{}, nil, nil, "c", func(m protocol.Message) error {
reply = m
return nil
})
if reply.Type != protocol.Error {
t.Fatalf("reply = %+v", reply)
}
}
+16 -7
View File
@@ -190,22 +190,31 @@ func safeChatAttachmentName(value string) string {
return name
}
// openChatAttachmentStore opens the private attachment directory, collects
// unleased files past retention and reports what the rest occupy. The caller
// holds chatAttachmentStore and closes the root.
func openChatAttachmentStore() (*os.Root, string, int64, int, error) {
// chatAttachmentDir is the configured attachment store directory: an absolute,
// cleaned path that may not exist yet.
func chatAttachmentDir() (string, error) {
dir := os.Getenv("PIPELINES_CHAT_ATTACHMENT_DIR")
if dir == "" {
home, err := os.UserHomeDir()
if err != nil {
return nil, "", 0, 0, err
return "", err
}
dir = filepath.Join(home, ".pipelines-chat-attachments")
}
if !filepath.IsAbs(dir) {
return nil, "", 0, 0, fmt.Errorf("chat attachment storage must be an absolute path")
return "", fmt.Errorf("chat attachment storage must be an absolute path")
}
return filepath.Clean(dir), nil
}
// openChatAttachmentStore opens the private attachment directory, collects
// unleased files past retention and reports what the rest occupy. The caller
// holds chatAttachmentStore and closes the root.
func openChatAttachmentStore() (*os.Root, string, int64, int, error) {
dir, err := chatAttachmentDir()
if err != nil {
return nil, "", 0, 0, err
}
dir = filepath.Clean(dir)
if err := os.Mkdir(dir, 0o700); err != nil && !os.IsExist(err) {
return nil, "", 0, 0, fmt.Errorf("prepare attachment directory: %w", err)
}