feat: publish outbound answer images to private OSS

This commit is contained in:
姚章浩
2026-08-13 12:34:39 +08:00
parent 74c9af9944
commit 9363d10e44
16 changed files with 794 additions and 13 deletions
+64
View File
@@ -0,0 +1,64 @@
package outboundimage
import (
"bytes"
"context"
"errors"
"strings"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
type AliyunOSSStore struct {
client *oss.Client
bucket string
}
func NewAliyunOSSStore(endpoint, region, accessKeyID, accessKeySecret, bucket string) (*AliyunOSSStore, error) {
endpoint = strings.TrimSpace(endpoint)
region = strings.TrimSpace(region)
accessKeyID = strings.TrimSpace(accessKeyID)
accessKeySecret = strings.TrimSpace(accessKeySecret)
bucket = strings.TrimSpace(bucket)
if endpoint == "" || region == "" || accessKeyID == "" || accessKeySecret == "" || bucket == "" {
return nil, errors.New("outbound image: OSS endpoint, region, credentials, and bucket are required")
}
provider := credentials.NewStaticCredentialsProvider(accessKeyID, accessKeySecret, "")
config := oss.LoadDefaultConfig().
WithCredentialsProvider(provider).
WithRegion(region).
WithEndpoint(endpoint)
return &AliyunOSSStore{client: oss.NewClient(config), bucket: bucket}, nil
}
func (s *AliyunOSSStore) Put(ctx context.Context, key string, data []byte, contentType string) error {
if s == nil || s.client == nil || strings.TrimSpace(key) == "" || len(data) == 0 {
return errors.New("outbound image: invalid OSS put request")
}
_, err := s.client.PutObject(ctx, &oss.PutObjectRequest{
Bucket: oss.Ptr(s.bucket),
Key: oss.Ptr(key),
Body: bytes.NewReader(data),
ContentType: oss.Ptr(contentType),
})
if err != nil {
return errors.New("outbound image: OSS put failed")
}
return nil
}
func (s *AliyunOSSStore) PresignGet(ctx context.Context, key string, ttl time.Duration) (string, error) {
if s == nil || s.client == nil || strings.TrimSpace(key) == "" || ttl <= 0 {
return "", errors.New("outbound image: invalid OSS presign request")
}
result, err := s.client.Presign(ctx, &oss.GetObjectRequest{
Bucket: oss.Ptr(s.bucket),
Key: oss.Ptr(key),
}, oss.PresignExpires(ttl))
if err != nil {
return "", errors.New("outbound image: OSS presign failed")
}
return result.URL, nil
}
+65
View File
@@ -0,0 +1,65 @@
package outboundimage
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"path"
"strings"
"time"
)
type ObjectStore interface {
Put(ctx context.Context, key string, data []byte, contentType string) error
PresignGet(ctx context.Context, key string, ttl time.Duration) (string, error)
}
type HashPublisher struct {
store ObjectStore
prefix string
ttl time.Duration
}
func NewHashPublisher(store ObjectStore, prefix string, ttl time.Duration) *HashPublisher {
return &HashPublisher{store: store, prefix: strings.Trim(strings.TrimSpace(prefix), "/"), ttl: ttl}
}
func (p *HashPublisher) Publish(ctx context.Context, data []byte, contentType string) (string, error) {
if p == nil || p.store == nil || len(data) == 0 || p.prefix == "" || p.ttl <= 0 {
return "", errors.New("outbound image: invalid publisher configuration")
}
extension := imageExtension(contentType)
if extension == "" {
return "", errors.New("outbound image: unsupported image content type")
}
sum := sha256.Sum256(data)
digest := hex.EncodeToString(sum[:])
key := path.Join(p.prefix, digest[:2], digest+extension)
if err := p.store.Put(ctx, key, data, contentType); err != nil {
return "", errors.New("outbound image: publish object failed")
}
signedURL, err := p.store.PresignGet(ctx, key, p.ttl)
if err != nil {
return "", errors.New("outbound image: sign object URL failed")
}
if !strings.HasPrefix(strings.TrimSpace(signedURL), "https://") {
return "", errors.New("outbound image: signed object URL must use HTTPS")
}
return signedURL, nil
}
func imageExtension(contentType string) string {
switch strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0])) {
case "image/jpeg", "image/jpg":
return ".jpg"
case "image/png":
return ".png"
case "image/webp":
return ".webp"
case "image/gif":
return ".gif"
default:
return ""
}
}
+55
View File
@@ -0,0 +1,55 @@
package outboundimage
import (
"context"
"strings"
"testing"
"time"
)
type fakeObjectStore struct {
key string
data []byte
contentType string
ttl time.Duration
}
func (s *fakeObjectStore) Put(_ context.Context, key string, data []byte, contentType string) error {
s.key = key
s.data = append([]byte(nil), data...)
s.contentType = contentType
return nil
}
func (s *fakeObjectStore) PresignGet(_ context.Context, key string, ttl time.Duration) (string, error) {
s.ttl = ttl
return "https://private-oss.example/" + key + "?signature=short", nil
}
func TestHashPublisherUsesDeterministicTemporaryKeyAndTwoHourHTTPSURL(t *testing.T) {
store := &fakeObjectStore{}
publisher := NewHashPublisher(store, "dobotai/im-images", 2*time.Hour)
first, err := publisher.Publish(context.Background(), []byte("same-image"), "image/jpeg")
if err != nil {
t.Fatal(err)
}
firstKey := store.key
second, err := publisher.Publish(context.Background(), []byte("same-image"), "image/jpeg")
if err != nil {
t.Fatal(err)
}
if first != second || firstKey != store.key {
t.Fatalf("publish is not deterministic: url1=%q url2=%q key1=%q key2=%q", first, second, firstKey, store.key)
}
if !strings.HasPrefix(store.key, "dobotai/im-images/") || !strings.HasSuffix(store.key, ".jpg") {
t.Fatalf("key=%q", store.key)
}
if strings.Contains(store.key, "same-image") {
t.Fatalf("key leaks content: %q", store.key)
}
if store.ttl != 2*time.Hour || !strings.HasPrefix(first, "https://") {
t.Fatalf("ttl=%s url=%q", store.ttl, first)
}
}
+65
View File
@@ -0,0 +1,65 @@
package outboundimage
import (
"context"
"regexp"
"strings"
)
var resourceMarkdownImageRE = regexp.MustCompile(`!\[[^\]]*\]\((resource://[0-9A-Za-z_-]+)\)`)
type Fetcher interface {
Fetch(ctx context.Context, reference string) ([]byte, string, error)
}
type Publisher interface {
Publish(ctx context.Context, data []byte, contentType string) (string, error)
}
type Rewriter struct {
fetcher Fetcher
publisher Publisher
maxImages int
}
func NewRewriter(fetcher Fetcher, publisher Publisher, maxImages int) *Rewriter {
return &Rewriter{fetcher: fetcher, publisher: publisher, maxImages: maxImages}
}
func (r *Rewriter) Rewrite(ctx context.Context, markdown string) string {
if r == nil || r.fetcher == nil || r.publisher == nil || r.maxImages <= 0 {
return resourceMarkdownImageRE.ReplaceAllString(markdown, "")
}
urls := map[string]string{}
attempted := 0
return resourceMarkdownImageRE.ReplaceAllStringFunc(markdown, func(image string) string {
match := resourceMarkdownImageRE.FindStringSubmatch(image)
if len(match) != 2 {
return ""
}
reference := match[1]
if signedURL, ok := urls[reference]; ok {
if signedURL == "" {
return ""
}
return strings.Replace(image, reference, signedURL, 1)
}
if attempted >= r.maxImages {
urls[reference] = ""
return ""
}
attempted++
data, contentType, err := r.fetcher.Fetch(ctx, reference)
if err != nil {
urls[reference] = ""
return ""
}
signedURL, err := r.publisher.Publish(ctx, data, contentType)
if err != nil || !strings.HasPrefix(signedURL, "https://") {
urls[reference] = ""
return ""
}
urls[reference] = signedURL
return strings.Replace(image, reference, signedURL, 1)
})
}
+78
View File
@@ -0,0 +1,78 @@
package outboundimage
import (
"context"
"errors"
"strings"
"testing"
)
type fakeFetcher struct {
calls map[string]int
fail map[string]bool
}
func (f *fakeFetcher) Fetch(_ context.Context, ref string) ([]byte, string, error) {
if f.calls == nil {
f.calls = map[string]int{}
}
f.calls[ref]++
if f.fail[ref] {
return nil, "", errors.New("fetch failed")
}
return []byte("image:" + ref), "image/png", nil
}
type fakePublisher struct {
calls int
}
func (p *fakePublisher) Publish(_ context.Context, data []byte, contentType string) (string, error) {
p.calls++
if contentType != "image/png" || len(data) == 0 {
return "", errors.New("bad image")
}
return "https://img.example/" + string(rune('0'+p.calls)) + ".png?sig=short", nil
}
func TestRewriteMarkdownResourceImagesDeduplicatesAndPreservesOtherURLs(t *testing.T) {
fetcher := &fakeFetcher{}
publisher := &fakePublisher{}
r := NewRewriter(fetcher, publisher, 5)
input := "步骤一\n![图1](resource://AbCdEfGhIjKlMnOpQrStUv)\n重复\n![图1重复](resource://AbCdEfGhIjKlMnOpQrStUv)\n外部\n![官网](https://example.com/a.png)"
got := r.Rewrite(context.Background(), input)
if strings.Contains(got, "resource://") {
t.Fatalf("resource reference remained: %s", got)
}
if strings.Count(got, "https://img.example/1.png?sig=short") != 2 {
t.Fatalf("deduplicated signed URL count mismatch: %s", got)
}
if !strings.Contains(got, "![官网](https://example.com/a.png)") {
t.Fatalf("ordinary HTTPS image changed: %s", got)
}
if fetcher.calls["resource://AbCdEfGhIjKlMnOpQrStUv"] != 1 || publisher.calls != 1 {
t.Fatalf("calls fetch=%v publish=%d", fetcher.calls, publisher.calls)
}
}
func TestRewriteMarkdownResourceImagesDropsFailuresAndImagesBeyondLimit(t *testing.T) {
failed := "resource://FailedRefAbCdEfGhIjKlMn"
fetcher := &fakeFetcher{fail: map[string]bool{failed: true}}
publisher := &fakePublisher{}
r := NewRewriter(fetcher, publisher, 3)
input := "保留正文\n![坏图](" + failed + ")\n![一](resource://FirstRefAbCdEfGhIjKlMnO)\n![二](resource://SecondRefAbCdEfGhIjKlMn)\n![三](resource://ThirdRefAbCdEfGhIjKlMnO)"
got := r.Rewrite(context.Background(), input)
if !strings.Contains(got, "保留正文") {
t.Fatalf("text was lost: %s", got)
}
if strings.Contains(got, "resource://") || strings.Contains(got, "坏图") || strings.Contains(got, "![三]") {
t.Fatalf("broken or over-limit image remained: %s", got)
}
if publisher.calls != 2 {
t.Fatalf("publisher calls=%d, want 2", publisher.calls)
}
}
+80
View File
@@ -0,0 +1,80 @@
package outboundimage
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type WeKnoraFetcher struct {
baseURL *url.URL
apiKey string
client *http.Client
maxBytes int64
}
func NewWeKnoraFetcher(baseURL, apiKey string, client *http.Client, maxBytes int64) (*WeKnoraFetcher, error) {
parsed, err := url.Parse(strings.TrimRight(strings.TrimSpace(baseURL), "/"))
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
return nil, errors.New("outbound image: invalid WeKnora base URL")
}
if strings.TrimSpace(apiKey) == "" {
return nil, errors.New("outbound image: WeKnora API key is required")
}
if maxBytes <= 0 {
return nil, errors.New("outbound image: positive max bytes is required")
}
if client == nil {
client = &http.Client{Timeout: 30 * time.Second}
}
return &WeKnoraFetcher{baseURL: parsed, apiKey: apiKey, client: client, maxBytes: maxBytes}, nil
}
func (f *WeKnoraFetcher) Fetch(ctx context.Context, reference string) ([]byte, string, error) {
if !strings.HasPrefix(reference, "resource://") || !resourceMarkdownImageRE.MatchString("![]("+reference+")") {
return nil, "", errors.New("outbound image: unsupported resource reference")
}
u := *f.baseURL
u.Path = "/files"
u.RawPath = ""
query := u.Query()
query.Set("file_path", reference)
u.RawQuery = query.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return nil, "", errors.New("outbound image: create WeKnora request failed")
}
req.Header.Set("X-API-Key", f.apiKey)
resp, err := f.client.Do(req)
if err != nil {
return nil, "", fmt.Errorf("outbound image: WeKnora request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
return nil, "", fmt.Errorf("outbound image: WeKnora HTTP %d", resp.StatusCode)
}
contentType := strings.TrimSpace(strings.Split(resp.Header.Get("Content-Type"), ";")[0])
if !strings.HasPrefix(contentType, "image/") {
return nil, "", errors.New("outbound image: WeKnora response is not an image")
}
if length := strings.TrimSpace(resp.Header.Get("Content-Length")); length != "" {
if n, convErr := strconv.ParseInt(length, 10, 64); convErr == nil && n > f.maxBytes {
return nil, "", errors.New("outbound image: WeKnora image exceeds size limit")
}
}
data, err := io.ReadAll(io.LimitReader(resp.Body, f.maxBytes+1))
if err != nil {
return nil, "", errors.New("outbound image: read WeKnora response failed")
}
if int64(len(data)) == 0 || int64(len(data)) > f.maxBytes {
return nil, "", errors.New("outbound image: WeKnora image exceeds size limit")
}
return data, contentType, nil
}
@@ -0,0 +1,77 @@
package outboundimage
import (
"context"
"io"
"net/http"
"net/http/httptest"
"testing"
)
func TestWeKnoraFetcherDownloadsAuthenticatedResourceImage(t *testing.T) {
var called bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
called = true
if req.URL.Path != "/files" {
t.Fatalf("path=%q", req.URL.Path)
}
if got := req.URL.Query().Get("file_path"); got != "resource://AbCdEfGhIjKlMnOpQrStUv" {
t.Fatalf("file_path=%q", got)
}
if got := req.Header.Get("X-API-Key"); got != "secret-test-key" {
t.Fatalf("api key header=%q", got)
}
w.Header().Set("Content-Type", "image/jpeg")
w.Header().Set("Content-Length", "4")
_, _ = io.WriteString(w, "JPEG")
}))
defer server.Close()
fetcher, err := NewWeKnoraFetcher(server.URL+"/api/v1", "secret-test-key", server.Client(), 10<<20)
if err != nil {
t.Fatal(err)
}
data, contentType, err := fetcher.Fetch(context.Background(), "resource://AbCdEfGhIjKlMnOpQrStUv")
if err != nil {
t.Fatal(err)
}
if !called || string(data) != "JPEG" || contentType != "image/jpeg" {
t.Fatalf("called=%t data=%q type=%q", called, data, contentType)
}
}
func TestWeKnoraFetcherRejectsUnsafeReferenceNonImageAndOversize(t *testing.T) {
t.Run("unsafe reference", func(t *testing.T) {
fetcher, err := NewWeKnoraFetcher("https://weknora.example", "key", http.DefaultClient, 4)
if err != nil {
t.Fatal(err)
}
if _, _, err := fetcher.Fetch(context.Background(), "https://evil.example/a.png"); err == nil {
t.Fatal("expected unsafe reference rejection")
}
})
for _, tc := range []struct {
name string
contentType string
body string
}{
{name: "non image", contentType: "text/plain", body: "TEXT"},
{name: "oversize", contentType: "image/png", body: "12345"},
} {
t.Run(tc.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", tc.contentType)
_, _ = io.WriteString(w, tc.body)
}))
defer server.Close()
fetcher, err := NewWeKnoraFetcher(server.URL, "key", server.Client(), 4)
if err != nil {
t.Fatal(err)
}
if _, _, err := fetcher.Fetch(context.Background(), "resource://AbCdEfGhIjKlMnOpQrStUv"); err == nil {
t.Fatal("expected response rejection")
}
})
}
}