perf(files): 优化私有文件鉴权与高成本查询隔离
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
package filekey
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const objectEndpointSuffix = "/files/object"
|
||||
|
||||
// Canonical returns the stored object key for current and legacy file URLs.
|
||||
func Canonical(raw string) string {
|
||||
value := strings.TrimSpace(strings.Trim(raw, `"'`))
|
||||
if value == "" || strings.Contains(value, "..") {
|
||||
return ""
|
||||
}
|
||||
|
||||
if parsed, err := url.Parse(value); err == nil {
|
||||
if key := parsed.Query().Get("key"); key != "" && strings.HasSuffix(parsed.Path, objectEndpointSuffix) {
|
||||
return normalizeKey(key)
|
||||
}
|
||||
if parsed.Scheme != "" || parsed.Host != "" {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
if index := strings.Index(value, "?key="); index >= 0 {
|
||||
query, err := url.ParseQuery(value[index+1:])
|
||||
if err == nil && query.Get("key") != "" {
|
||||
return normalizeKey(query.Get("key"))
|
||||
}
|
||||
}
|
||||
return normalizeKey(value)
|
||||
}
|
||||
|
||||
func normalizeKey(raw string) string {
|
||||
key := strings.TrimSpace(raw)
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
decoded, err := url.QueryUnescape(key)
|
||||
if err != nil || decoded == key {
|
||||
break
|
||||
}
|
||||
key = decoded
|
||||
}
|
||||
key = strings.TrimLeft(strings.TrimSpace(key), "/")
|
||||
if key == "" || strings.Contains(key, "..") {
|
||||
return ""
|
||||
}
|
||||
for _, suffix := range []string{".medium.jpg", ".thumb.jpg"} {
|
||||
if strings.HasSuffix(key, suffix) {
|
||||
return strings.TrimSuffix(key, suffix)
|
||||
}
|
||||
}
|
||||
return key
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package filekey
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCanonical(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"listing/2026/11/a.webp": "listing/2026/11/a.webp",
|
||||
"/api/files/object?key=listing%2F2026%2F11%2Fa.webp": "listing/2026/11/a.webp",
|
||||
"/api/admin/files/object?key=listing/2026/11/a.webp": "listing/2026/11/a.webp",
|
||||
"/api/files/object?key=listing%2F2026%2F11%2Fa.webp.medium.jpg": "listing/2026/11/a.webp",
|
||||
"https://example.com/external.png": "",
|
||||
"../secret": "",
|
||||
}
|
||||
for raw, want := range tests {
|
||||
t.Run(raw, func(t *testing.T) {
|
||||
if got := Canonical(raw); got != want {
|
||||
t.Fatalf("Canonical(%q) = %q, want %q", raw, got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user