feat: auto-resolve MinIO file URLs in API responses

Presign minio:// references on outbound /api/v1 JSON so clients get usable URLs from resource GETs without calling the refresh endpoint.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Yared Yemane 2026-07-03 06:37:10 -07:00
parent 180448d688
commit f457589f4a
6 changed files with 368 additions and 44 deletions

View File

@ -0,0 +1,134 @@
package fileurls
import (
"context"
"fmt"
"net/url"
"strings"
"time"
)
const defaultPresignedExpiry = time.Hour
// URLProvider generates presigned download URLs for MinIO object keys.
type URLProvider interface {
GetURL(ctx context.Context, objectKey string, expiry time.Duration) (string, error)
BucketName() string
}
// Resolver converts stored file references to presigned download URLs.
type Resolver struct {
provider URLProvider
}
func New(provider URLProvider) *Resolver {
return &Resolver{provider: provider}
}
// Resolve converts minio:// references, object keys, and stale presigned URLs to fresh presigned URLs.
// Static paths and unrelated HTTPS URLs are returned unchanged.
func (r *Resolver) Resolve(ctx context.Context, reference string) string {
if r == nil || r.provider == nil {
return reference
}
ref := strings.TrimSpace(reference)
if ref == "" || strings.HasPrefix(ref, "/static/") {
return reference
}
if !NeedsResolution(ref) {
return reference
}
key, err := ExtractObjectKey(ref, r.provider.BucketName())
if err != nil {
return reference
}
freshURL, err := r.provider.GetURL(ctx, key, defaultPresignedExpiry)
if err != nil {
return reference
}
return freshURL
}
// NeedsResolution reports whether a stored value should be presigned on outbound API responses.
func NeedsResolution(reference string) bool {
ref := strings.TrimSpace(reference)
if ref == "" || strings.HasPrefix(ref, "/static/") {
return false
}
if strings.HasPrefix(ref, "minio://") {
return true
}
if strings.HasPrefix(ref, "http://") || strings.HasPrefix(ref, "https://") {
return isPresignedS3URL(ref)
}
return isKnownObjectKey(ref)
}
// ExtractObjectKey parses minio:// URIs, presigned URLs, and raw object keys.
func ExtractObjectKey(reference, bucketName string) (string, error) {
ref := strings.TrimSpace(reference)
if ref == "" {
return "", fmt.Errorf("reference is required")
}
if strings.HasPrefix(ref, "minio://") {
key := strings.TrimPrefix(ref, "minio://")
if key == "" {
return "", fmt.Errorf("invalid minio reference")
}
return key, nil
}
if strings.HasPrefix(ref, "http://") || strings.HasPrefix(ref, "https://") {
u, err := url.Parse(ref)
if err != nil || u.Host == "" {
return "", fmt.Errorf("invalid file URL")
}
objectPath := strings.TrimPrefix(u.Path, "/")
if objectPath == "" {
return "", fmt.Errorf("invalid file URL")
}
bucket := strings.TrimSpace(bucketName)
if bucket != "" {
prefix := bucket + "/"
if strings.HasPrefix(objectPath, prefix) {
objectPath = strings.TrimPrefix(objectPath, prefix)
}
}
if objectPath == "" {
return "", fmt.Errorf("invalid file URL")
}
return objectPath, nil
}
if isKnownObjectKey(ref) {
return ref, nil
}
if !strings.Contains(ref, "://") && !strings.HasPrefix(ref, "/") {
return ref, nil
}
return "", fmt.Errorf("unsupported file reference")
}
func isPresignedS3URL(raw string) bool {
u, err := url.Parse(raw)
if err != nil || u.Host == "" {
return false
}
q := u.Query()
return q.Has("X-Amz-Algorithm") || q.Has("X-Amz-Signature")
}
func isKnownObjectKey(key string) bool {
knownPrefixes := []string{
"image/",
"audio/",
"pdf/",
"profile_pictures/",
"notification_images/",
"audio_answers/",
}
for _, prefix := range knownPrefixes {
if strings.HasPrefix(key, prefix) {
return true
}
}
return false
}

View File

@ -0,0 +1,79 @@
package fileurls
import (
"context"
"strings"
"testing"
"time"
)
type stubURLProvider struct {
bucket string
url string
key string
}
func (s *stubURLProvider) GetURL(_ context.Context, objectKey string, _ time.Duration) (string, error) {
s.key = objectKey
return s.url, nil
}
func (s *stubURLProvider) BucketName() string { return s.bucket }
func TestNeedsResolution(t *testing.T) {
tests := []struct {
in string
want bool
}{
{"minio://image/a.png", true},
{"image/a.png", true},
{"/static/profile_pictures/x.jpg", false},
{"https://player.vimeo.com/video/1", false},
{"https://cdn.example.com/audio.mp3", false},
{"https://minio.example.com/bucket/image/a.png?X-Amz-Algorithm=AWS4-HMAC-SHA256", true},
{"", false},
}
for _, tc := range tests {
if got := NeedsResolution(tc.in); got != tc.want {
t.Fatalf("NeedsResolution(%q) = %v, want %v", tc.in, got, tc.want)
}
}
}
func TestResolveMinIOReference(t *testing.T) {
provider := &stubURLProvider{
bucket: "yimaru",
url: "https://minio.example.com/yimaru/image/a.png?sig=1",
}
r := New(provider)
got := r.Resolve(context.Background(), "minio://image/a.png")
if got != provider.url {
t.Fatalf("expected presigned url, got %q", got)
}
if provider.key != "image/a.png" {
t.Fatalf("expected object key image/a.png, got %q", provider.key)
}
}
func TestResolveInJSON(t *testing.T) {
provider := &stubURLProvider{
bucket: "yimaru",
url: "https://minio.example.com/yimaru/image/a.png?sig=1",
}
r := New(provider)
raw := []byte(`{"data":{"profile_picture_url":"minio://image/a.png","reference":"minio://image/a.png","video_url":"https://player.vimeo.com/video/1"}}`)
out, ok := r.ResolveInJSON(context.Background(), raw)
if !ok {
t.Fatal("expected json resolution")
}
body := string(out)
if !strings.Contains(body, provider.url) {
t.Fatalf("expected resolved profile url in %s", body)
}
if !strings.Contains(body, `"reference":"minio://image/a.png"`) {
t.Fatalf("reference should stay canonical in %s", body)
}
if !strings.Contains(body, `"video_url":"https://player.vimeo.com/video/1"`) {
t.Fatalf("video_url should be unchanged in %s", body)
}
}

View File

@ -0,0 +1,116 @@
package fileurls
import (
"context"
"strings"
"github.com/bytedance/sonic"
)
var resolveFieldKeys = map[string]struct{}{
"profile_picture_url": {},
"profile_picture": {},
"image_url": {},
"thumbnail": {},
"thumbnail_url": {},
"voice_prompt": {},
"sample_answer_voice_prompt": {},
"audio_url": {},
"banner_image": {},
"image": {},
"icon": {},
"url": {},
"value": {},
}
var skipFieldKeys = map[string]struct{}{
"reference": {},
"object_key": {},
"upload_url": {},
"payment_url": {},
"checkout_url": {},
"callback_url": {},
"return_url": {},
"cancel_url": {},
"success_url": {},
"error_url": {},
"notify_url": {},
"notification_url": {},
"notificationUrl": {},
"embed_url": {},
"store_url": {},
"intro_video_url": {},
"video_url": {},
"link": {},
"vimeo_id": {},
"previewUrl": {},
"preview_url": {},
}
func shouldResolveField(fieldKey, value string) bool {
if _, skip := skipFieldKeys[fieldKey]; skip {
return false
}
if _, ok := resolveFieldKeys[fieldKey]; !ok {
return false
}
return NeedsResolution(value)
}
// ResolveInJSON walks a decoded JSON value and presigns known file-reference fields.
func (r *Resolver) ResolveInJSON(ctx context.Context, raw []byte) ([]byte, bool) {
if r == nil || r.provider == nil || len(raw) == 0 {
return raw, false
}
var root interface{}
if err := sonic.Unmarshal(raw, &root); err != nil {
return raw, false
}
resolved := resolveValue(ctx, r, root, "")
out, err := sonic.Marshal(resolved)
if err != nil {
return raw, false
}
return out, true
}
func resolveValue(ctx context.Context, r *Resolver, value interface{}, fieldKey string) interface{} {
switch typed := value.(type) {
case map[string]interface{}:
out := make(map[string]interface{}, len(typed))
for k, child := range typed {
out[k] = resolveValue(ctx, r, child, k)
}
return out
case []interface{}:
out := make([]interface{}, len(typed))
for i, child := range typed {
out[i] = resolveValue(ctx, r, child, fieldKey)
}
return out
case string:
if shouldResolveField(fieldKey, typed) {
return r.Resolve(ctx, typed)
}
return typed
default:
return value
}
}
// ResolvePtr returns a pointer to a resolved URL when the input is non-nil and resolvable.
func (r *Resolver) ResolvePtr(ctx context.Context, ref *string) *string {
if ref == nil {
return nil
}
trimmed := strings.TrimSpace(*ref)
if trimmed == "" {
return ref
}
resolved := r.Resolve(ctx, trimmed)
if resolved == trimmed {
return ref
}
out := resolved
return &out
}

View File

@ -4,13 +4,13 @@ import (
dbgen "Yimaru-Backend/gen/db"
"Yimaru-Backend/internal/domain"
minioservice "Yimaru-Backend/internal/services/minio"
"Yimaru-Backend/internal/web_server/fileurls"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
"strconv"
"strings"
@ -64,18 +64,10 @@ type refreshFileURLReq struct {
}
// resolveFileURL converts a stored file path to a usable URL.
// If the path starts with "minio://", it generates a presigned URL.
// If the path is a MinIO reference, it generates a presigned URL.
// Otherwise it returns the path as-is (e.g. "/static/...").
func (h *Handler) resolveFileURL(c *fiber.Ctx, storedPath string) string {
if h.minioSvc == nil || !strings.HasPrefix(storedPath, "minio://") {
return storedPath
}
objectKey := strings.TrimPrefix(storedPath, "minio://")
url, err := h.minioSvc.GetURL(c.Context(), objectKey, 1*time.Hour)
if err != nil {
return storedPath
}
return url
return fileurls.New(h.minioSvc).Resolve(c.Context(), storedPath)
}
// GetFileURL resolves a MinIO object key to a presigned download URL.
@ -115,39 +107,11 @@ func (h *Handler) GetFileURL(c *fiber.Ctx) error {
}
func (h *Handler) extractObjectKeyFromReference(reference string) (string, error) {
ref := strings.TrimSpace(reference)
if ref == "" {
return "", fmt.Errorf("reference is required")
bucket := ""
if h.minioSvc != nil {
bucket = h.minioSvc.BucketName()
}
if strings.HasPrefix(ref, "minio://") {
key := strings.TrimPrefix(ref, "minio://")
if key == "" {
return "", fmt.Errorf("invalid minio reference")
}
return key, nil
}
u, err := url.Parse(ref)
if err == nil && u.Scheme != "" && u.Host != "" {
path := strings.TrimPrefix(u.Path, "/")
if path == "" {
return "", fmt.Errorf("invalid file URL")
}
bucket := strings.TrimSpace(h.minioSvc.BucketName())
if bucket != "" {
prefix := bucket + "/"
if strings.HasPrefix(path, prefix) {
path = strings.TrimPrefix(path, prefix)
}
}
if path == "" {
return "", fmt.Errorf("invalid file URL")
}
return path, nil
}
return ref, nil
return fileurls.ExtractObjectKey(reference, bucket)
}
// RefreshFileURL generates a new presigned URL from an object key, minio:// URI, or stale presigned URL.

View File

@ -3,7 +3,9 @@ package httpserver
import (
"Yimaru-Backend/internal/domain"
examprepsvc "Yimaru-Backend/internal/services/examprep"
"Yimaru-Backend/internal/web_server/fileurls"
jwtutil "Yimaru-Backend/internal/web_server/jwt"
"bytes"
"context"
"errors"
"fmt"
@ -634,3 +636,32 @@ func (a *App) TenantAuthMiddleware(c *fiber.Ctx) error {
return c.Next()
}
// resolveFileURLsMiddleware presigns MinIO file references in successful JSON API responses.
func (a *App) resolveFileURLsMiddleware(c *fiber.Ctx) error {
if err := c.Next(); err != nil {
return err
}
if a.minioSvc == nil {
return nil
}
status := c.Response().StatusCode()
if status < fiber.StatusOK || status >= 300 {
return nil
}
contentType := string(c.Response().Header.ContentType())
if !strings.Contains(contentType, "application/json") {
return nil
}
body := c.Response().Body()
if len(body) == 0 {
return nil
}
resolver := fileurls.New(a.minioSvc)
resolved, ok := resolver.ResolveInJSON(c.Context(), body)
if !ok || bytes.Equal(resolved, body) {
return nil
}
c.Response().SetBodyRaw(resolved)
return nil
}

View File

@ -67,7 +67,7 @@ func (a *App) initAppRoutes() {
})
// Groups
groupV1 := a.fiber.Group("/api/v1")
groupV1 := a.fiber.Group("/api/v1", a.resolveFileURLsMiddleware)
// Serve static files (profile pictures, etc.)
a.fiber.Static("/static", "./static")