feat(dingtalk): stabilize multimodal answer workflows
This commit is contained in:
@@ -4,8 +4,8 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
|
||||
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
|
||||
@@ -49,16 +49,31 @@ func (s *AliyunOSSStore) Put(ctx context.Context, key string, data []byte, conte
|
||||
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")
|
||||
func (s *AliyunOSSStore) Get(ctx context.Context, key string, maxBytes int64) ([]byte, string, error) {
|
||||
if s == nil || s.client == nil || strings.TrimSpace(key) == "" || maxBytes <= 0 {
|
||||
return nil, "", errors.New("outbound image: invalid OSS get request")
|
||||
}
|
||||
result, err := s.client.Presign(ctx, &oss.GetObjectRequest{
|
||||
result, err := s.client.GetObject(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 nil, "", errors.New("outbound image: OSS get failed")
|
||||
}
|
||||
return result.URL, nil
|
||||
defer result.Body.Close()
|
||||
if result.ContentLength > maxBytes {
|
||||
return nil, "", errors.New("outbound image: OSS object exceeds size limit")
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(result.Body, maxBytes+1))
|
||||
if err != nil {
|
||||
return nil, "", errors.New("outbound image: OSS read failed")
|
||||
}
|
||||
if int64(len(data)) > maxBytes {
|
||||
return nil, "", errors.New("outbound image: OSS object exceeds size limit")
|
||||
}
|
||||
contentType := ""
|
||||
if result.ContentType != nil {
|
||||
contentType = strings.TrimSpace(*result.ContentType)
|
||||
}
|
||||
return data, contentType, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package outboundimage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
|
||||
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
|
||||
)
|
||||
|
||||
func TestAliyunOSSStoreGetReturnsBoundedImageBytesAndMIME(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet || r.URL.Path != "/private-bucket/dobotai/im-images/id" {
|
||||
t.Fatalf("method=%s path=%s", r.Method, r.URL.Path)
|
||||
}
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
w.Header().Set("Content-Length", "4")
|
||||
_, _ = w.Write([]byte("PNG!"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
config := oss.LoadDefaultConfig().
|
||||
WithCredentialsProvider(credentials.NewStaticCredentialsProvider("test-id", "test-secret", "")).
|
||||
WithRegion("cn-test").
|
||||
WithEndpoint(server.URL).
|
||||
WithUsePathStyle(true)
|
||||
store := &AliyunOSSStore{client: oss.NewClient(config), bucket: "private-bucket"}
|
||||
|
||||
data, contentType, err := store.Get(context.Background(), "dobotai/im-images/id", 4)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(data) != "PNG!" || contentType != "image/png" {
|
||||
t.Fatalf("data=%q contentType=%q", data, contentType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliyunOSSStoreGetRejectsOversizedObjects(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
w.Header().Set("Content-Length", "5")
|
||||
_, _ = w.Write([]byte("PNG!!"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
config := oss.LoadDefaultConfig().
|
||||
WithCredentialsProvider(credentials.NewStaticCredentialsProvider("test-id", "test-secret", "")).
|
||||
WithRegion("cn-test").
|
||||
WithEndpoint(server.URL).
|
||||
WithUsePathStyle(true)
|
||||
store := &AliyunOSSStore{client: oss.NewClient(config), bucket: "private-bucket"}
|
||||
|
||||
if _, _, err := store.Get(context.Background(), "dobotai/im-images/id", 4); err == nil {
|
||||
t.Fatal("expected oversized object error")
|
||||
}
|
||||
}
|
||||
@@ -5,48 +5,57 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ObjectStore interface {
|
||||
var stableImageIDRE = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`)
|
||||
|
||||
type ObjectWriter 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
|
||||
type StableHashPublisher struct {
|
||||
store ObjectWriter
|
||||
prefix string
|
||||
publicBaseURL string
|
||||
}
|
||||
|
||||
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")
|
||||
func NewStableHashPublisher(store ObjectWriter, prefix, publicBaseURL string) (*StableHashPublisher, error) {
|
||||
prefix = strings.Trim(strings.TrimSpace(prefix), "/")
|
||||
publicBaseURL = strings.TrimRight(strings.TrimSpace(publicBaseURL), "/")
|
||||
parsed, err := url.Parse(publicBaseURL)
|
||||
if store == nil || prefix == "" || err != nil || parsed.Scheme != "https" || parsed.Host == "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" {
|
||||
return nil, errors.New("outbound image: invalid stable publisher configuration")
|
||||
}
|
||||
extension := imageExtension(contentType)
|
||||
if extension == "" {
|
||||
return &StableHashPublisher{
|
||||
store: store,
|
||||
prefix: prefix,
|
||||
publicBaseURL: publicBaseURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *StableHashPublisher) Publish(ctx context.Context, data []byte, contentType string) (string, error) {
|
||||
if p == nil || p.store == nil || len(data) == 0 || p.prefix == "" || p.publicBaseURL == "" {
|
||||
return "", errors.New("outbound image: invalid stable publisher configuration")
|
||||
}
|
||||
if imageExtension(contentType) == "" {
|
||||
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)
|
||||
idBytes := sum[:16]
|
||||
idBytes[6] = (idBytes[6] & 0x0f) | 0x50
|
||||
idBytes[8] = (idBytes[8] & 0x3f) | 0x80
|
||||
idHex := hex.EncodeToString(idBytes)
|
||||
id := fmt.Sprintf("%s-%s-%s-%s-%s", idHex[:8], idHex[8:12], idHex[12:16], idHex[16:20], idHex[20:])
|
||||
key := path.Join(p.prefix, id)
|
||||
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
|
||||
return p.publicBaseURL + "/" + id, nil
|
||||
}
|
||||
|
||||
func imageExtension(contentType string) string {
|
||||
|
||||
@@ -4,14 +4,12 @@ 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 {
|
||||
@@ -21,14 +19,16 @@ func (s *fakeObjectStore) Put(_ context.Context, key string, data []byte, conten
|
||||
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) {
|
||||
func TestStableHashPublisherUsesDeterministicUUIDURLWithoutPresigning(t *testing.T) {
|
||||
store := &fakeObjectStore{}
|
||||
publisher := NewHashPublisher(store, "dobotai/im-images", 2*time.Hour)
|
||||
publisher, err := NewStableHashPublisher(
|
||||
store,
|
||||
"dobotai/im-images",
|
||||
"https://weknora-api-test.dobot.cn/dingtalk/i",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
first, err := publisher.Publish(context.Background(), []byte("same-image"), "image/jpeg")
|
||||
if err != nil {
|
||||
@@ -43,13 +43,48 @@ func TestHashPublisherUsesDeterministicTemporaryKeyAndTwoHourHTTPSURL(t *testing
|
||||
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)
|
||||
|
||||
wantURLPrefix := "https://weknora-api-test.dobot.cn/dingtalk/i/"
|
||||
if !strings.HasPrefix(first, wantURLPrefix) {
|
||||
t.Fatalf("url=%q", first)
|
||||
}
|
||||
if strings.Contains(store.key, "same-image") {
|
||||
t.Fatalf("key leaks content: %q", store.key)
|
||||
id := strings.TrimPrefix(first, wantURLPrefix)
|
||||
if !stableImageIDRE.MatchString(id) {
|
||||
t.Fatalf("stable image id=%q", id)
|
||||
}
|
||||
if store.ttl != 2*time.Hour || !strings.HasPrefix(first, "https://") {
|
||||
t.Fatalf("ttl=%s url=%q", store.ttl, first)
|
||||
if store.key != "dobotai/im-images/"+id {
|
||||
t.Fatalf("key=%q id=%q", store.key, id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStableHashPublisherRejectsUnsafeConfigurationAndNonImages(t *testing.T) {
|
||||
store := &fakeObjectStore{}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
store ObjectWriter
|
||||
prefix string
|
||||
baseURL string
|
||||
}{
|
||||
{name: "nil store", prefix: "dobotai/im-images", baseURL: "https://img.example/i"},
|
||||
{name: "empty prefix", store: store, baseURL: "https://img.example/i"},
|
||||
{name: "http base", store: store, prefix: "dobotai/im-images", baseURL: "http://img.example/i"},
|
||||
{name: "query base", store: store, prefix: "dobotai/im-images", baseURL: "https://img.example/i?token=secret"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if _, err := NewStableHashPublisher(test.store, test.prefix, test.baseURL); err == nil {
|
||||
t.Fatal("expected configuration error")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
publisher, err := NewStableHashPublisher(store, "dobotai/im-images", "https://img.example/i")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := publisher.Publish(context.Background(), nil, "image/png"); err == nil {
|
||||
t.Fatal("expected empty image error")
|
||||
}
|
||||
if _, err := publisher.Publish(context.Background(), []byte("text"), "text/plain"); err == nil {
|
||||
t.Fatal("expected non-image error")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,29 @@ package outboundimage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/url"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var resourceMarkdownImageRE = regexp.MustCompile(`!\[[^\]]*\]\((resource://[0-9A-Za-z_-]+)\)`)
|
||||
var (
|
||||
resourceMarkdownImageRE = regexp.MustCompile(`!\[[^\]]*\]\((resource://[0-9A-Za-z_-]+)(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|\([^\)\r\n]*\)))?\)`)
|
||||
resourceHTMLDoubleImageRE = regexp.MustCompile(`(?i)<img\b[^>]*\bsrc\s*=\s*"(resource://[0-9A-Za-z_-]+)"[^>]*>`)
|
||||
resourceHTMLSingleImageRE = regexp.MustCompile(`(?i)<img\b[^>]*\bsrc\s*=\s*'(resource://[0-9A-Za-z_-]+)'[^>]*>`)
|
||||
resourceHTMLUnsafeImageRE = regexp.MustCompile(`(?i)<img\b[^>]*resource://[0-9A-Za-z_-]+[^>]*>`)
|
||||
markdownImageRE = regexp.MustCompile(`!\[[^\]]*\]\(([^\s)]+)(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|\([^\)\r\n]*\)))?\)`)
|
||||
incompleteMarkdownImageRE = regexp.MustCompile(`!\[[^\]\r\n]*\]\([^\)\r\n]*$`)
|
||||
htmlImageRE = regexp.MustCompile(`(?i)<img\b[^>]*>`)
|
||||
incompleteHTMLImageRE = regexp.MustCompile(`(?i)<img\b[^>]*$`)
|
||||
htmlDoubleSrcRE = regexp.MustCompile(`(?i)\bsrc\s*=\s*"([^"]+)"`)
|
||||
htmlSingleSrcRE = regexp.MustCompile(`(?i)\bsrc\s*=\s*'([^']+)'`)
|
||||
htmlDoubleAltRE = regexp.MustCompile(`(?i)\balt\s*=\s*"([^"]*)"`)
|
||||
htmlSingleAltRE = regexp.MustCompile(`(?i)\balt\s*=\s*'([^']*)'`)
|
||||
resourceReferenceRE = regexp.MustCompile(`resource://[0-9A-Za-z_-]+`)
|
||||
dataImageReferenceRE = regexp.MustCompile(`(?i)data:image[^\s]*`)
|
||||
)
|
||||
|
||||
type Fetcher interface {
|
||||
Fetch(ctx context.Context, reference string) ([]byte, string, error)
|
||||
@@ -28,21 +46,15 @@ func NewRewriter(fetcher Fetcher, publisher Publisher, maxImages int) *Rewriter
|
||||
|
||||
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, "")
|
||||
markdown = normalizePublicHTMLImages(stripResourceImages(markdown))
|
||||
markdown = resourceReferenceRE.ReplaceAllString(resourceHTMLUnsafeImageRE.ReplaceAllString(markdown, ""), "")
|
||||
return sanitizePublicMarkdownImages(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)
|
||||
resolve := func(reference string) string {
|
||||
if publishedURL, ok := urls[reference]; ok {
|
||||
return publishedURL
|
||||
}
|
||||
if attempted >= r.maxImages {
|
||||
urls[reference] = ""
|
||||
@@ -54,12 +66,147 @@ func (r *Rewriter) Rewrite(ctx context.Context, markdown string) string {
|
||||
urls[reference] = ""
|
||||
return ""
|
||||
}
|
||||
signedURL, err := r.publisher.Publish(ctx, data, contentType)
|
||||
if err != nil || !strings.HasPrefix(signedURL, "https://") {
|
||||
publishedURL, err := r.publisher.Publish(ctx, data, contentType)
|
||||
if err != nil || !strings.HasPrefix(publishedURL, "https://") {
|
||||
urls[reference] = ""
|
||||
return ""
|
||||
}
|
||||
urls[reference] = signedURL
|
||||
return strings.Replace(image, reference, signedURL, 1)
|
||||
urls[reference] = publishedURL
|
||||
return publishedURL
|
||||
}
|
||||
|
||||
markdown = resourceMarkdownImageRE.ReplaceAllStringFunc(markdown, func(image string) string {
|
||||
match := resourceMarkdownImageRE.FindStringSubmatch(image)
|
||||
if len(match) != 2 {
|
||||
return ""
|
||||
}
|
||||
reference := match[1]
|
||||
publishedURL := resolve(reference)
|
||||
if publishedURL == "" {
|
||||
return ""
|
||||
}
|
||||
return strings.Replace(image, reference, publishedURL, 1)
|
||||
})
|
||||
markdown = rewriteHTMLImages(markdown, resourceHTMLDoubleImageRE, resolve)
|
||||
markdown = rewriteHTMLImages(markdown, resourceHTMLSingleImageRE, resolve)
|
||||
markdown = normalizePublicHTMLImages(markdown)
|
||||
markdown = resourceReferenceRE.ReplaceAllString(resourceHTMLUnsafeImageRE.ReplaceAllString(markdown, ""), "")
|
||||
return sanitizePublicMarkdownImages(markdown)
|
||||
}
|
||||
|
||||
func sanitizePublicMarkdownImages(markdown string) string {
|
||||
markdown = markdownImageRE.ReplaceAllStringFunc(markdown, func(image string) string {
|
||||
match := markdownImageRE.FindStringSubmatch(image)
|
||||
if len(match) != 2 || !isSafePublicImageURL(match[1]) {
|
||||
return ""
|
||||
}
|
||||
if isKnownDocumentURL(match[1]) {
|
||||
return strings.TrimPrefix(image, "!")
|
||||
}
|
||||
return image
|
||||
})
|
||||
markdown = incompleteMarkdownImageRE.ReplaceAllString(markdown, "")
|
||||
markdown = incompleteHTMLImageRE.ReplaceAllString(markdown, "")
|
||||
return dataImageReferenceRE.ReplaceAllString(markdown, "")
|
||||
}
|
||||
|
||||
func isKnownDocumentURL(raw string) bool {
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
switch strings.ToLower(path.Ext(u.Path)) {
|
||||
case ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
|
||||
".csv", ".txt", ".zip", ".rar", ".7z":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func rewriteHTMLImages(content string, pattern *regexp.Regexp, resolve func(string) string) string {
|
||||
return pattern.ReplaceAllStringFunc(content, func(image string) string {
|
||||
match := pattern.FindStringSubmatch(image)
|
||||
if len(match) != 2 {
|
||||
return ""
|
||||
}
|
||||
publishedURL := resolve(match[1])
|
||||
if publishedURL == "" {
|
||||
return ""
|
||||
}
|
||||
alt := "图片"
|
||||
for _, pattern := range []*regexp.Regexp{htmlDoubleAltRE, htmlSingleAltRE} {
|
||||
if altMatch := pattern.FindStringSubmatch(image); len(altMatch) == 2 && strings.TrimSpace(altMatch[1]) != "" {
|
||||
alt = strings.ReplaceAll(strings.TrimSpace(altMatch[1]), "]", `\]`)
|
||||
break
|
||||
}
|
||||
}
|
||||
return ""
|
||||
})
|
||||
}
|
||||
|
||||
func normalizePublicHTMLImages(content string) string {
|
||||
return htmlImageRE.ReplaceAllStringFunc(content, func(image string) string {
|
||||
source := ""
|
||||
for _, pattern := range []*regexp.Regexp{htmlDoubleSrcRE, htmlSingleSrcRE} {
|
||||
if match := pattern.FindStringSubmatch(image); len(match) == 2 {
|
||||
source = strings.TrimSpace(match[1])
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isSafePublicImageURL(source) {
|
||||
return ""
|
||||
}
|
||||
return ""
|
||||
})
|
||||
}
|
||||
|
||||
func imageAlt(image string) string {
|
||||
for _, pattern := range []*regexp.Regexp{htmlDoubleAltRE, htmlSingleAltRE} {
|
||||
if match := pattern.FindStringSubmatch(image); len(match) == 2 && strings.TrimSpace(match[1]) != "" {
|
||||
return strings.ReplaceAll(strings.TrimSpace(match[1]), "]", `\]`)
|
||||
}
|
||||
}
|
||||
return "图片"
|
||||
}
|
||||
|
||||
func isSafePublicImageURL(raw string) bool {
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil {
|
||||
return false
|
||||
}
|
||||
hostname := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".")
|
||||
if hostname == "" || hostname == "localhost" || strings.HasSuffix(hostname, ".localhost") || strings.HasSuffix(hostname, ".local") || strings.HasSuffix(hostname, ".internal") {
|
||||
return false
|
||||
}
|
||||
if port := u.Port(); port != "" && port != "443" {
|
||||
return false
|
||||
}
|
||||
if ip := net.ParseIP(hostname); ip != nil {
|
||||
if !ip.IsGlobalUnicast() || ip.IsPrivate() {
|
||||
return false
|
||||
}
|
||||
} else if !strings.Contains(hostname, ".") {
|
||||
return false
|
||||
}
|
||||
for key := range u.Query() {
|
||||
normalized := strings.ToLower(key)
|
||||
if strings.Contains(normalized, "signature") || normalized == "ossaccesskeyid" || strings.Contains(normalized, "credential") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func stripResourceImages(content string) string {
|
||||
content = resourceMarkdownImageRE.ReplaceAllString(content, "")
|
||||
content = resourceHTMLDoubleImageRE.ReplaceAllString(content, "")
|
||||
content = resourceHTMLSingleImageRE.ReplaceAllString(content, "")
|
||||
return resourceHTMLUnsafeImageRE.ReplaceAllString(content, "")
|
||||
}
|
||||
|
||||
func (r *Rewriter) SanitizePartial(content string) string {
|
||||
content = resourceReferenceRE.ReplaceAllString(stripResourceImages(content), "")
|
||||
content = normalizePublicHTMLImages(content)
|
||||
return sanitizePublicMarkdownImages(content)
|
||||
}
|
||||
|
||||
@@ -76,3 +76,302 @@ func TestRewriteMarkdownResourceImagesDropsFailuresAndImagesBeyondLimit(t *testi
|
||||
t.Fatalf("publisher calls=%d, want 2", publisher.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewriteHTMLResourceImagesAsDingTalkMarkdown(t *testing.T) {
|
||||
resource := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
fetcher := &fakeFetcher{}
|
||||
publisher := &fakePublisher{}
|
||||
r := NewRewriter(fetcher, publisher, 5)
|
||||
input := "前文\n<img alt=\"步骤图\" width=\"100\" src=\"" + resource + "\"/>\n" +
|
||||
"重复\n<img src='" + resource + "' class='diagram'>\n后文"
|
||||
|
||||
got := r.Rewrite(context.Background(), input)
|
||||
|
||||
if strings.Contains(got, "resource://") || strings.Contains(strings.ToLower(got), "<img") {
|
||||
t.Fatalf("internal HTML image remained: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "") {
|
||||
t.Fatalf("alt image not normalized: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "") {
|
||||
t.Fatalf("default-alt image not normalized: %s", got)
|
||||
}
|
||||
if fetcher.calls[resource] != 1 || publisher.calls != 1 {
|
||||
t.Fatalf("calls fetch=%v publish=%d", fetcher.calls, publisher.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizePartialRemovesInternalImageNodesAndBareReferences(t *testing.T) {
|
||||
r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5)
|
||||
input := "正文\n\n" +
|
||||
"<img alt='图' src='resource://SecondRefAbCdEfGhIjKlMn'>\n" +
|
||||
"内部引用 resource://BareRefAbCdEfGhIjKlMn"
|
||||
|
||||
got := r.SanitizePartial(input)
|
||||
|
||||
if strings.Contains(got, "resource://") || strings.Contains(strings.ToLower(got), "<img") {
|
||||
t.Fatalf("partial content leaked an internal image: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "正文") || !strings.Contains(got, "内部引用") {
|
||||
t.Fatalf("partial text was lost: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewriteFailsClosedOnUnquotedHTMLAndBareResourceReferences(t *testing.T) {
|
||||
fetcher := &fakeFetcher{}
|
||||
r := NewRewriter(fetcher, &fakePublisher{}, 5)
|
||||
input := "正文\n<img src=resource://UnsafeRefAbCdEfGhIjKlMn>\n内部引用 resource://BareRefAbCdEfGhIjKlMn"
|
||||
|
||||
got := r.Rewrite(context.Background(), input)
|
||||
|
||||
if strings.Contains(got, "resource://") || strings.Contains(strings.ToLower(got), "<img") {
|
||||
t.Fatalf("final content leaked an internal reference: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "正文") || !strings.Contains(got, "内部引用") {
|
||||
t.Fatalf("final text was lost: %s", got)
|
||||
}
|
||||
if len(fetcher.calls) != 0 {
|
||||
t.Fatalf("unsafe references must not be fetched: %v", fetcher.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewriteRemovesUnsafeImageLocatorsAndSignedURLs(t *testing.T) {
|
||||
r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5)
|
||||
input := strings.Join([]string{
|
||||
"正文",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
}, "\n")
|
||||
|
||||
got := r.Rewrite(context.Background(), input)
|
||||
|
||||
for _, forbidden := range []string{"local://", "oss://", "127.0.0.1", "x-oss-signature"} {
|
||||
if strings.Contains(strings.ToLower(got), forbidden) {
|
||||
t.Fatalf("final content retained %q: %s", forbidden, got)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(got, "") {
|
||||
t.Fatalf("public HTTPS image was removed: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewriteNormalizesPublicHTMLImageAsDingTalkMarkdown(t *testing.T) {
|
||||
r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5)
|
||||
input := `<img class="diagram" src="https://example.com/a.png" alt="公网图" width="100">`
|
||||
|
||||
got := r.Rewrite(context.Background(), input)
|
||||
|
||||
if got != "" {
|
||||
t.Fatalf("normalized public HTML image=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewriteRemovesDataImageWithOptionalTitle(t *testing.T) {
|
||||
r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5)
|
||||
input := "正文\n\n后文"
|
||||
|
||||
got := r.Rewrite(context.Background(), input)
|
||||
|
||||
if strings.Contains(got, "data:image") || strings.Contains(got, "占位图") {
|
||||
t.Fatalf("final content retained a data image: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "正文") || !strings.Contains(got, "后文") {
|
||||
t.Fatalf("surrounding text was lost: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizePartialRemovesDataImageWithOptionalTitle(t *testing.T) {
|
||||
r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5)
|
||||
input := "正文\n\n后文"
|
||||
|
||||
got := r.SanitizePartial(input)
|
||||
|
||||
if strings.Contains(got, "data:image") || strings.Contains(got, "占位图") {
|
||||
t.Fatalf("partial content retained a data image: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "正文") || !strings.Contains(got, "后文") {
|
||||
t.Fatalf("surrounding text was lost: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewritePublishesResourceImageWithOptionalTitle(t *testing.T) {
|
||||
resource := "resource://AbCdEfGhIjKlMnOpQrStUv"
|
||||
fetcher := &fakeFetcher{}
|
||||
publisher := &fakePublisher{}
|
||||
r := NewRewriter(fetcher, publisher, 5)
|
||||
input := ""
|
||||
|
||||
got := r.Rewrite(context.Background(), input)
|
||||
|
||||
if got != "" {
|
||||
t.Fatalf("resource image with title=%q", got)
|
||||
}
|
||||
if fetcher.calls[resource] != 1 || publisher.calls != 1 {
|
||||
t.Fatalf("calls fetch=%v publish=%d", fetcher.calls, publisher.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizePartialRemovesDataHTMLImage(t *testing.T) {
|
||||
r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5)
|
||||
input := `正文<img alt="占位图" src="data:image/png;base64,iVBORw0KGgo=">后文`
|
||||
|
||||
got := r.SanitizePartial(input)
|
||||
|
||||
if strings.Contains(got, "data:image") || strings.Contains(strings.ToLower(got), "<img") {
|
||||
t.Fatalf("partial content retained a data HTML image: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "正文") || !strings.Contains(got, "后文") {
|
||||
t.Fatalf("surrounding text was lost: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewritePreservesPublicHTTPSImageWithOptionalTitle(t *testing.T) {
|
||||
r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5)
|
||||
input := ``
|
||||
|
||||
if got := r.Rewrite(context.Background(), input); got != input {
|
||||
t.Fatalf("final public HTTPS image=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizePartialPreservesPublicHTTPSImageWithOptionalTitle(t *testing.T) {
|
||||
r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5)
|
||||
input := ``
|
||||
|
||||
if got := r.SanitizePartial(input); got != input {
|
||||
t.Fatalf("partial public HTTPS image=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizePartialRemovesIncompleteDataMarkdownImage(t *testing.T) {
|
||||
r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5)
|
||||
input := "正文\n
|
||||
|
||||
if strings.Contains(got, "data:image") || strings.Contains(got, "占位图") {
|
||||
t.Fatalf("partial content retained an incomplete data image: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "正文") {
|
||||
t.Fatalf("surrounding text was lost: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizePartialRemovesIncompleteDataHTMLImage(t *testing.T) {
|
||||
r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5)
|
||||
input := `正文<img alt="占位图" src="data:image/png;base64,iVBORw0K`
|
||||
|
||||
got := r.SanitizePartial(input)
|
||||
|
||||
if strings.Contains(got, "data:image") || strings.Contains(strings.ToLower(got), "<img") {
|
||||
t.Fatalf("partial content retained an incomplete data HTML image: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "正文") {
|
||||
t.Fatalf("surrounding text was lost: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewriteRemovesBareDataImageReference(t *testing.T) {
|
||||
r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5)
|
||||
input := "正文 data:image/png;base64,iVBORw0KGgo= 后文"
|
||||
|
||||
got := r.Rewrite(context.Background(), input)
|
||||
|
||||
if strings.Contains(got, "data:image") {
|
||||
t.Fatalf("final content retained a bare data image: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "正文") || !strings.Contains(got, "后文") {
|
||||
t.Fatalf("surrounding text was lost: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewriteRemovesIncompleteDataMarkdownImage(t *testing.T) {
|
||||
r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5)
|
||||
input := "正文\n, input)
|
||||
|
||||
if strings.Contains(got, "data:image") || strings.Contains(got, "占位图") || strings.Contains(got, " 后文`
|
||||
|
||||
got := r.Rewrite(context.Background(), input)
|
||||
|
||||
if strings.Contains(got, "data:image") || strings.Contains(got, "占位图") {
|
||||
t.Fatalf("fail-closed rewrite retained a data image: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "正文") || !strings.Contains(got, "后文") {
|
||||
t.Fatalf("surrounding text was lost: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewriteDowngradesPDFImageToDocumentLink(t *testing.T) {
|
||||
r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5)
|
||||
input := ``
|
||||
want := `[机械臂示教与应用课件](https://sales-edu.example/06%20robot-teaching.PDF?tenant=demo "课件")`
|
||||
|
||||
if got := r.Rewrite(context.Background(), input); got != want {
|
||||
t.Fatalf("PDF image rewrite=%q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinalAndPartialDowngradeKnownDocumentImages(t *testing.T) {
|
||||
r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5)
|
||||
for _, extension := range []string{
|
||||
".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
|
||||
".csv", ".txt", ".zip", ".rar", ".7z",
|
||||
} {
|
||||
t.Run(extension, func(t *testing.T) {
|
||||
url := "https://docs.example/manual" + extension + "?tenant=demo"
|
||||
input := ""
|
||||
want := "[资料](" + url + ")"
|
||||
|
||||
if got := r.Rewrite(context.Background(), input); got != want {
|
||||
t.Fatalf("final rewrite=%q, want %q", got, want)
|
||||
}
|
||||
if got := r.SanitizePartial(input); got != want {
|
||||
t.Fatalf("partial rewrite=%q, want %q", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
html := `<img src="https://docs.example/manual.xlsx" alt="参数表">`
|
||||
if got, want := r.Rewrite(context.Background(), html), `[参数表](https://docs.example/manual.xlsx)`; got != want {
|
||||
t.Fatalf("HTML document image rewrite=%q, want %q", got, want)
|
||||
}
|
||||
if got, want := r.SanitizePartial(html), `[参数表](https://docs.example/manual.xlsx)`; got != want {
|
||||
t.Fatalf("partial HTML document image rewrite=%q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocumentImageDowngradePreservesImageAndLinkContracts(t *testing.T) {
|
||||
r := NewRewriter(&fakeFetcher{}, &fakePublisher{}, 5)
|
||||
input := strings.Join([]string{
|
||||
``,
|
||||
`[已有PDF链接](https://docs.example/manual.pdf)`,
|
||||
``,
|
||||
}, "\n")
|
||||
|
||||
got := r.Rewrite(context.Background(), input)
|
||||
|
||||
if !strings.Contains(got, ``) {
|
||||
t.Fatalf("extensionless stable image changed: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, `[已有PDF链接](https://docs.example/manual.pdf)`) {
|
||||
t.Fatalf("existing document link changed: %s", got)
|
||||
}
|
||||
if strings.Contains(got, "127.0.0.1") || strings.Contains(got, "危险PDF") {
|
||||
t.Fatalf("unsafe document image became a link: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package outboundimage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type ObjectReader interface {
|
||||
Get(ctx context.Context, key string, maxBytes int64) ([]byte, string, error)
|
||||
}
|
||||
|
||||
func NewStableImageHandler(reader ObjectReader, objectPrefix, routePrefix string, maxBytes int64) (http.Handler, error) {
|
||||
objectPrefix = strings.Trim(strings.TrimSpace(objectPrefix), "/")
|
||||
routePrefix = "/" + strings.Trim(strings.TrimSpace(routePrefix), "/") + "/"
|
||||
if reader == nil || objectPrefix == "" || maxBytes <= 0 {
|
||||
return nil, errors.New("outbound image: invalid stable image handler configuration")
|
||||
}
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
w.Header().Set("Allow", "GET, HEAD")
|
||||
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
id := strings.TrimPrefix(r.URL.Path, routePrefix)
|
||||
if r.URL.Path == id || strings.Contains(id, "/") || !stableImageIDRE.MatchString(id) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
data, contentType, err := reader.Get(r.Context(), path.Join(objectPrefix, id), maxBytes)
|
||||
if err != nil || len(data) == 0 || imageExtension(contentType) == "" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", strings.TrimSpace(strings.Split(contentType, ";")[0]))
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
|
||||
w.Header().Set("Cache-Control", "public, max-age=86400, immutable")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if r.Method == http.MethodHead {
|
||||
return
|
||||
}
|
||||
_, _ = w.Write(data)
|
||||
}), nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package outboundimage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeImageReader struct {
|
||||
key string
|
||||
maxBytes int64
|
||||
data []byte
|
||||
contentType string
|
||||
err error
|
||||
}
|
||||
|
||||
func (r *fakeImageReader) Get(_ context.Context, key string, maxBytes int64) ([]byte, string, error) {
|
||||
r.key = key
|
||||
r.maxBytes = maxBytes
|
||||
return append([]byte(nil), r.data...), r.contentType, r.err
|
||||
}
|
||||
|
||||
func TestStableImageHandlerReturnsImageBytesDirectly(t *testing.T) {
|
||||
const id = "ca13f02b-58b6-5f8f-a80d-b41873a97425"
|
||||
reader := &fakeImageReader{data: []byte("JPEG"), contentType: "image/jpeg"}
|
||||
handler, err := NewStableImageHandler(reader, "dobotai/im-images", "/dingtalk/i/", 10<<20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/dingtalk/i/"+id, nil))
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d", recorder.Code)
|
||||
}
|
||||
if recorder.Header().Get("Location") != "" {
|
||||
t.Fatalf("stable image endpoint must not redirect: location=%q", recorder.Header().Get("Location"))
|
||||
}
|
||||
if recorder.Header().Get("Content-Type") != "image/jpeg" {
|
||||
t.Fatalf("content-type=%q", recorder.Header().Get("Content-Type"))
|
||||
}
|
||||
if recorder.Body.String() != "JPEG" {
|
||||
t.Fatalf("body=%q", recorder.Body.String())
|
||||
}
|
||||
if reader.key != "dobotai/im-images/"+id || reader.maxBytes != 10<<20 {
|
||||
t.Fatalf("key=%q maxBytes=%d", reader.key, reader.maxBytes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStableImageHandlerAllowsHeadWithoutBody(t *testing.T) {
|
||||
const id = "ca13f02b-58b6-5f8f-a80d-b41873a97425"
|
||||
reader := &fakeImageReader{data: []byte("JPEG"), contentType: "image/jpeg"}
|
||||
handler, err := NewStableImageHandler(reader, "dobotai/im-images", "/dingtalk/i/", 10<<20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodHead, "/dingtalk/i/"+id, nil))
|
||||
|
||||
if recorder.Code != http.StatusOK || recorder.Body.Len() != 0 {
|
||||
t.Fatalf("status=%d body=%q", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if recorder.Header().Get("Content-Length") != "4" {
|
||||
t.Fatalf("content-length=%q", recorder.Header().Get("Content-Length"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStableImageHandlerRejectsPostAndInvalidIDsWithoutReadingOSS(t *testing.T) {
|
||||
reader := &fakeImageReader{data: []byte("JPEG"), contentType: "image/jpeg"}
|
||||
handler, err := NewStableImageHandler(reader, "dobotai/im-images", "/dingtalk/i/", 10<<20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
post := httptest.NewRecorder()
|
||||
handler.ServeHTTP(post, httptest.NewRequest(http.MethodPost, "/dingtalk/i/ca13f02b-58b6-5f8f-a80d-b41873a97425", nil))
|
||||
if post.Code != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("post status=%d", post.Code)
|
||||
}
|
||||
invalid := httptest.NewRecorder()
|
||||
handler.ServeHTTP(invalid, httptest.NewRequest(http.MethodGet, "/dingtalk/i/../../secret", nil))
|
||||
if invalid.Code != http.StatusNotFound {
|
||||
t.Fatalf("invalid status=%d", invalid.Code)
|
||||
}
|
||||
if reader.key != "" {
|
||||
t.Fatalf("invalid requests reached OSS key=%q", reader.key)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user