fix(im): make presigned URL flow diagnosable end-to-end
When IM image rendering breaks, operators previously had no log line to correlate against the IM platform's fetch attempt. Add observability hooks on both ends and unblock HEAD probes so common IM previews work at all. - log rewriteStorageURLs success/failure/no-op with the full signed URL (operators can copy it from logs and verify public reachability) - log presigned handler 4xx with client_ip + UA + tenant_id + file_path so failures correlate against IM platform fetch logs; use the request context so trace IDs are preserved - accept HEAD on /api/v1/files/presigned: IM platforms (Feishu, Slack etc.) probe with HEAD before GET when rendering image previews, and a 401 there is enough to break the inline image even when the GET would have succeeded - add Admin-only GET /api/v1/files/presigned-preview that returns the exact URL an IM channel would embed for the calling tenant, for self-service verification without sending a real IM message - clarify APP_EXTERNAL_URL and MINIO_ENDPOINT public-reachability rules in .env.example; misconfigured endpoints are the most common cause of "image broken in IM" reports
This commit is contained in:
+18
-1
@@ -81,15 +81,32 @@ var storageSchemeRe = regexp.MustCompile(`\b(local|minio|s3|cos|tos|oss)://[^\s)
|
||||
// rewriteStorageURLs replaces all provider:// URLs in content with HTTP URLs
|
||||
// obtained from fileService.GetFileURL. URLs that are already HTTP or cannot
|
||||
// be resolved are left unchanged.
|
||||
//
|
||||
// Logging policy:
|
||||
// - Successful rewrite logs at INFO with the full signed URL so operators
|
||||
// can copy it out of logs and verify public reachability directly. The
|
||||
// trade-off: anyone with log access can use a signed URL until it
|
||||
// expires (WeKnora 2h, MinIO 24h). Acceptable for diagnosability.
|
||||
// - Failure or no-op rewrite logs at WARN. The no-op case typically means
|
||||
// APP_EXTERNAL_URL is not configured for the local backend, which is
|
||||
// the most common cause of "image broken in IM" reports.
|
||||
func rewriteStorageURLs(ctx context.Context, content string, fileSvc interfaces.FileService) string {
|
||||
if fileSvc == nil {
|
||||
return content
|
||||
}
|
||||
return storageSchemeRe.ReplaceAllStringFunc(content, func(match string) string {
|
||||
httpURL, err := fileSvc.GetFileURL(ctx, match)
|
||||
if err != nil || httpURL == match {
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[IM] rewriteStorageURLs failed: src=%s err=%v", match, err)
|
||||
return match
|
||||
}
|
||||
if httpURL == match {
|
||||
logger.Warnf(ctx,
|
||||
"[IM] rewriteStorageURLs no-op (URL unchanged; for local storage set APP_EXTERNAL_URL): src=%s",
|
||||
match)
|
||||
return match
|
||||
}
|
||||
logger.Infof(ctx, "[IM] rewriteStorageURLs: src=%s dst=%s", match, httpURL)
|
||||
return httpURL
|
||||
})
|
||||
}
|
||||
|
||||
@@ -29,7 +29,10 @@ var noAuthAPI = map[string][]string{
|
||||
"/api/v1/auth/oidc/url": {"GET"},
|
||||
"/api/v1/auth/oidc/callback": {"GET"},
|
||||
"/api/v1/auth/refresh": {"POST"},
|
||||
"/api/v1/files/presigned": {"GET"},
|
||||
// IM platforms (Feishu, Slack, etc.) commonly issue a HEAD request
|
||||
// before GET to validate Content-Type / Content-Length when rendering
|
||||
// image previews — both verbs must be allowed for image links to work.
|
||||
"/api/v1/files/presigned": {"GET", "HEAD"},
|
||||
}
|
||||
|
||||
// 检查请求是否在无需认证的API列表中
|
||||
|
||||
+139
-18
@@ -138,6 +138,9 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
// Presigned file access: no auth required, signature-verified.
|
||||
servePresignedFiles(r, params.TenantService)
|
||||
|
||||
// Diagnostic preview of presigned URLs (Admin only, behind auth middleware).
|
||||
servePresignedPreview(r, params.Config)
|
||||
|
||||
// 添加OpenTelemetry追踪中间件
|
||||
// r.Use(middleware.TracingMiddleware())
|
||||
|
||||
@@ -1289,8 +1292,17 @@ func serveFiles(r getRouteRegistrar, globalFileService interfaces.FileService) {
|
||||
// servePresignedFiles serves files via HMAC-signed URLs without requiring authentication.
|
||||
// This is used by IM channels to serve images that are embedded in bot replies.
|
||||
//
|
||||
// Route:
|
||||
// - /api/v1/files/presigned?file_path=<provider://...>&tenant_id=<id>&expires=<unix>&sig=<hmac>
|
||||
// Routes:
|
||||
// - GET /api/v1/files/presigned?file_path=<provider://...>&tenant_id=<id>&expires=<unix>&sig=<hmac>
|
||||
// - HEAD /api/v1/files/presigned?... (IM platforms issue HEAD first to validate
|
||||
// Content-Type / Content-Length before rendering image previews; HEAD must
|
||||
// succeed or the inline image renders as broken)
|
||||
//
|
||||
// Failure paths log client IP + User-Agent + (truncated) file_path so operators
|
||||
// can correlate an IM platform's fetch against the upstream signing log line.
|
||||
// Without this it is otherwise impossible to tell whether a "broken image" is
|
||||
// caused by an expired signature, a stale URL cached by the platform, the
|
||||
// platform's IP being blocked, or the URL simply never reaching us.
|
||||
func servePresignedFiles(r *gin.Engine, tenantService interfaces.TenantService) {
|
||||
baseDir := os.Getenv("LOCAL_STORAGE_BASE_DIR")
|
||||
if baseDir == "" {
|
||||
@@ -1298,57 +1310,72 @@ func servePresignedFiles(r *gin.Engine, tenantService interfaces.TenantService)
|
||||
}
|
||||
absDir, _ := filepath.Abs(baseDir)
|
||||
|
||||
r.GET("/api/v1/files/presigned", func(c *gin.Context) {
|
||||
handler := presignedFileHandler(tenantService, absDir)
|
||||
r.GET("/api/v1/files/presigned", handler)
|
||||
r.HEAD("/api/v1/files/presigned", handler)
|
||||
}
|
||||
|
||||
// presignedFileHandler returns the shared Gin handler used by both GET and HEAD.
|
||||
// For HEAD requests it returns the same status + headers but does not stream
|
||||
// the body — this is enough for IM platforms to validate the URL while saving
|
||||
// us a full read of the backing object.
|
||||
func presignedFileHandler(tenantService interfaces.TenantService, absDir string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
clientIP := c.ClientIP()
|
||||
userAgent := c.Request.UserAgent()
|
||||
|
||||
filePath := strings.TrimSpace(c.Query("file_path"))
|
||||
tenantIDStr := strings.TrimSpace(c.Query("tenant_id"))
|
||||
expiresStr := strings.TrimSpace(c.Query("expires"))
|
||||
sig := strings.TrimSpace(c.Query("sig"))
|
||||
|
||||
if filePath == "" || tenantIDStr == "" || expiresStr == "" || sig == "" {
|
||||
logger.Warnf(ctx, "[Router] /files/presigned missing params: client_ip=%s ua=%q file_path=%q tenant_id=%q expires=%q has_sig=%v",
|
||||
clientIP, userAgent, filePath, tenantIDStr, expiresStr, sig != "")
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "missing required parameters"})
|
||||
return
|
||||
}
|
||||
if strings.Contains(filePath, "..") {
|
||||
logger.Warnf(ctx, "[Router] /files/presigned rejected path traversal: client_ip=%s file_path=%q", clientIP, filePath)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid file path"})
|
||||
return
|
||||
}
|
||||
|
||||
tenantID, err := strconv.ParseUint(tenantIDStr, 10, 64)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Router] /files/presigned invalid tenant_id: client_ip=%s tenant_id=%q err=%v", clientIP, tenantIDStr, err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid tenant_id"})
|
||||
return
|
||||
}
|
||||
|
||||
// Verify HMAC signature and expiry.
|
||||
// Verify HMAC signature and expiry. Logged at Warn because every 403
|
||||
// here is a signal worth investigating: either the URL was tampered
|
||||
// with, the IM platform cached an expired URL, or SYSTEM_AES_KEY was
|
||||
// rotated without invalidating in-flight links.
|
||||
if !secutils.VerifyFileURLSig(filePath, tenantID, expiresStr, sig) {
|
||||
logger.Warnf(ctx, "[Router] /files/presigned sig invalid or expired: client_ip=%s ua=%q tenant_id=%d file_path=%q expires=%s",
|
||||
clientIP, userAgent, tenantID, filePath, expiresStr)
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "invalid or expired signature"})
|
||||
return
|
||||
}
|
||||
|
||||
// Resolve the file service for this tenant.
|
||||
provider := types.ParseProviderScheme(filePath)
|
||||
tenant, err := tenantService.GetTenantByID(c.Request.Context(), tenantID)
|
||||
tenant, err := tenantService.GetTenantByID(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(context.Background(), "[Router] /files/presigned tenant lookup failed: tenant_id=%d err=%v", tenantID, err)
|
||||
logger.Warnf(ctx, "[Router] /files/presigned tenant lookup failed: client_ip=%s tenant_id=%d err=%v", clientIP, tenantID, err)
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
fileSvc, resolvedProvider, err := filesvc.NewFileServiceFromStorageConfig(provider, tenant.StorageEngineConfig, absDir)
|
||||
if err != nil {
|
||||
logger.Warnf(context.Background(), "[Router] /files/presigned resolve file service failed: tenant_id=%d provider=%s err=%v", tenantID, provider, err)
|
||||
logger.Warnf(ctx, "[Router] /files/presigned resolve file service failed: client_ip=%s tenant_id=%d provider=%s err=%v",
|
||||
clientIP, tenantID, provider, err)
|
||||
c.Status(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
reader, err := fileSvc.GetFile(c.Request.Context(), filePath)
|
||||
if err != nil {
|
||||
logger.Warnf(context.Background(), "[Router] /files/presigned get file failed: tenant_id=%d provider=%s path=%q err=%v", tenantID, resolvedProvider, filePath, err)
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
ext := filepath.Ext(filePath)
|
||||
contentType := "application/octet-stream"
|
||||
switch strings.ToLower(ext) {
|
||||
@@ -1368,13 +1395,107 @@ func servePresignedFiles(r *gin.Engine, tenantService interfaces.TenantService)
|
||||
contentType = "application/pdf"
|
||||
}
|
||||
|
||||
// HEAD short-circuits the body read. We still need to confirm the
|
||||
// object exists, but we use a 0-byte content length and skip io.Copy.
|
||||
// Skipping GetFile entirely for HEAD would risk reporting 200 for a
|
||||
// signed URL that no longer points at a real object; that mismatch
|
||||
// would make subsequent GETs from the same client mysteriously fail.
|
||||
reader, err := fileSvc.GetFile(ctx, filePath)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Router] /files/presigned get file failed: client_ip=%s tenant_id=%d provider=%s path=%q err=%v",
|
||||
clientIP, tenantID, resolvedProvider, filePath, err)
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
c.Header("Content-Type", contentType)
|
||||
c.Header("Cache-Control", "public, max-age=86400")
|
||||
if c.Request.Method == http.MethodHead {
|
||||
c.Status(http.StatusOK)
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusOK)
|
||||
if _, err := io.Copy(c.Writer, reader); err != nil {
|
||||
logger.Warnf(context.Background(), "[Router] /files/presigned write response failed: %v", err)
|
||||
logger.Warnf(ctx, "[Router] /files/presigned write response failed: client_ip=%s tenant_id=%d err=%v", clientIP, tenantID, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// servePresignedPreview registers an Admin-only diagnostic endpoint that
|
||||
// returns the presigned HTTP URL that *would be* generated for a given
|
||||
// storage path by the calling tenant's current storage config — exactly the
|
||||
// URL an IM channel would embed in a reply. Operators can paste the result
|
||||
// into a 4G/mobile browser to verify public reachability without having to
|
||||
// send a real message through an IM bot.
|
||||
//
|
||||
// Route:
|
||||
// - GET /api/v1/files/presigned-preview?file_path=<provider://...>
|
||||
func servePresignedPreview(r *gin.Engine, cfg *config.Config) {
|
||||
baseDir := os.Getenv("LOCAL_STORAGE_BASE_DIR")
|
||||
if baseDir == "" {
|
||||
baseDir = "/data/files"
|
||||
}
|
||||
absDir, _ := filepath.Abs(baseDir)
|
||||
|
||||
r.GET("/api/v1/files/presigned-preview",
|
||||
middleware.RequireRole(types.TenantRoleAdmin, cfg),
|
||||
func(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
filePath := strings.TrimSpace(c.Query("file_path"))
|
||||
if filePath == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "missing required parameter: file_path"})
|
||||
return
|
||||
}
|
||||
if strings.Contains(filePath, "..") {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid file path"})
|
||||
return
|
||||
}
|
||||
|
||||
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
if tenant == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: tenant context missing"})
|
||||
return
|
||||
}
|
||||
|
||||
provider := types.ParseProviderScheme(filePath)
|
||||
fileSvc, resolvedProvider, err := filesvc.NewFileServiceFromStorageConfig(provider, tenant.StorageEngineConfig, absDir)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": err.Error(),
|
||||
"provider": provider,
|
||||
"hint": "tenant storage config is missing or incomplete for this provider",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
httpURL, err := fileSvc.GetFileURL(ctx, filePath)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": err.Error(),
|
||||
"provider": resolvedProvider,
|
||||
"hint": "GetFileURL failed; for local storage this usually means APP_EXTERNAL_URL is unset",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Detect the "no-op" case where local storage falls back to the
|
||||
// provider:// path because APP_EXTERNAL_URL is missing. Surfacing
|
||||
// this explicitly is the whole point of the endpoint.
|
||||
rewritten := httpURL != filePath
|
||||
hint := ""
|
||||
if !rewritten {
|
||||
hint = "URL unchanged; for local storage set APP_EXTERNAL_URL to enable presigned HTTP URLs"
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"file_path": filePath,
|
||||
"provider": resolvedProvider,
|
||||
"url": httpURL,
|
||||
"rewritten": rewritten,
|
||||
"hint": hint,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// RegisterDataSourceRoutes 注册数据源相关的路由
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
||||
// stubTenantService is a minimal stub of interfaces.TenantService that only
|
||||
// implements GetTenantByID. Every other method panics — those code paths
|
||||
// must not be exercised by presigned routes; the panic surfaces test bugs
|
||||
// instead of silently returning zero values.
|
||||
type stubTenantService struct {
|
||||
get func(ctx context.Context, id uint64) (*types.Tenant, error)
|
||||
}
|
||||
|
||||
var _ interfaces.TenantService = (*stubTenantService)(nil)
|
||||
|
||||
func (s *stubTenantService) GetTenantByID(ctx context.Context, id uint64) (*types.Tenant, error) {
|
||||
if s.get == nil {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
return s.get(ctx, id)
|
||||
}
|
||||
|
||||
func (s *stubTenantService) CreateTenant(context.Context, *types.Tenant) (*types.Tenant, error) {
|
||||
panic("unexpected")
|
||||
}
|
||||
|
||||
func (s *stubTenantService) GetTenantsByIDs(context.Context, []uint64) (map[uint64]*types.Tenant, error) {
|
||||
panic("unexpected")
|
||||
}
|
||||
func (s *stubTenantService) ListTenants(context.Context) ([]*types.Tenant, error) {
|
||||
panic("unexpected")
|
||||
}
|
||||
|
||||
func (s *stubTenantService) UpdateTenant(context.Context, *types.Tenant) (*types.Tenant, error) {
|
||||
panic("unexpected")
|
||||
}
|
||||
func (s *stubTenantService) DeleteTenant(context.Context, uint64) error { panic("unexpected") }
|
||||
func (s *stubTenantService) UpdateAPIKey(context.Context, uint64) (string, error) {
|
||||
panic("unexpected")
|
||||
}
|
||||
func (s *stubTenantService) ExtractTenantIDFromAPIKey(string) (uint64, error) { panic("unexpected") }
|
||||
func (s *stubTenantService) ListAllTenants(context.Context) ([]*types.Tenant, error) {
|
||||
panic("unexpected")
|
||||
}
|
||||
func (s *stubTenantService) BulkSetStorageQuota(context.Context, int64) (int64, error) {
|
||||
panic("unexpected")
|
||||
}
|
||||
|
||||
func (s *stubTenantService) SearchTenants(context.Context, string, uint64, int, int) ([]*types.Tenant, int64, error) {
|
||||
panic("unexpected")
|
||||
}
|
||||
|
||||
func (s *stubTenantService) GetTenantByIDForUser(context.Context, uint64, string) (*types.Tenant, error) {
|
||||
panic("unexpected")
|
||||
}
|
||||
|
||||
func (s *stubTenantService) GetWeKnoraCloudCredentials(context.Context) *types.WeKnoraCloudCredentials {
|
||||
panic("unexpected")
|
||||
}
|
||||
|
||||
// setupPresignedTestServer wires presignedFileHandler with a real local file
|
||||
// service rooted at a temp dir, returning the engine, baseDir, and the
|
||||
// presigned URL generator helper.
|
||||
func setupPresignedTestServer(t *testing.T) (engine *gin.Engine, baseDir string, signURL func(filePath string, tenantID uint64, ttl time.Duration) string) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
t.Setenv("SYSTEM_AES_KEY", "weknora-test-aes-key-32bytes!!!")
|
||||
|
||||
baseDir = t.TempDir()
|
||||
|
||||
tenant := &types.Tenant{
|
||||
ID: 1,
|
||||
StorageEngineConfig: &types.StorageEngineConfig{
|
||||
DefaultProvider: "local",
|
||||
Local: &types.LocalEngineConfig{},
|
||||
},
|
||||
}
|
||||
stubTS := &stubTenantService{
|
||||
get: func(_ context.Context, id uint64) (*types.Tenant, error) {
|
||||
if id == tenant.ID {
|
||||
return tenant, nil
|
||||
}
|
||||
return nil, os.ErrNotExist
|
||||
},
|
||||
}
|
||||
|
||||
engine = gin.New()
|
||||
handler := presignedFileHandler(stubTS, baseDir)
|
||||
engine.GET("/api/v1/files/presigned", handler)
|
||||
engine.HEAD("/api/v1/files/presigned", handler)
|
||||
|
||||
signURL = func(filePath string, tenantID uint64, ttl time.Duration) string {
|
||||
signed, err := secutils.SignFileURL("https://weknora.example.com", filePath, tenantID, ttl)
|
||||
if err != nil {
|
||||
t.Fatalf("SignFileURL: %v", err)
|
||||
}
|
||||
// Re-parse so we only keep the query part: the test server is on
|
||||
// a different host than the canonical signing baseURL.
|
||||
u, _ := url.Parse(signed)
|
||||
return "/api/v1/files/presigned?" + u.RawQuery
|
||||
}
|
||||
|
||||
return engine, baseDir, signURL
|
||||
}
|
||||
|
||||
// writeTestFile creates baseDir/<relPath> with the given content and returns
|
||||
// the matching `local://<relPath>` storage path.
|
||||
func writeTestFile(t *testing.T, baseDir, relPath, content string) string {
|
||||
t.Helper()
|
||||
full := filepath.Join(baseDir, filepath.FromSlash(relPath))
|
||||
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
|
||||
t.Fatalf("MkdirAll: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(full, []byte(content), 0o644); err != nil {
|
||||
t.Fatalf("WriteFile: %v", err)
|
||||
}
|
||||
return "local://" + relPath
|
||||
}
|
||||
|
||||
func TestPresignedFile_HEAD_Returns200WithoutBody(t *testing.T) {
|
||||
engine, baseDir, signURL := setupPresignedTestServer(t)
|
||||
storagePath := writeTestFile(t, baseDir, "1/img.png", "PNG-BYTES")
|
||||
|
||||
req := httptest.NewRequest(http.MethodHead, signURL(storagePath, 1, time.Hour), nil)
|
||||
w := httptest.NewRecorder()
|
||||
engine.ServeHTTP(w, req)
|
||||
|
||||
if got, want := w.Code, http.StatusOK; got != want {
|
||||
t.Fatalf("status = %d, want %d (body=%q)", got, want, w.Body.String())
|
||||
}
|
||||
if got := w.Header().Get("Content-Type"); got != "image/png" {
|
||||
t.Fatalf("Content-Type = %q, want image/png", got)
|
||||
}
|
||||
// HEAD must not stream the body — protects backing storage from a
|
||||
// full read on every IM preview probe.
|
||||
if w.Body.Len() != 0 {
|
||||
t.Fatalf("HEAD response body should be empty, got %d bytes", w.Body.Len())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPresignedFile_GET_ReturnsContent(t *testing.T) {
|
||||
engine, baseDir, signURL := setupPresignedTestServer(t)
|
||||
storagePath := writeTestFile(t, baseDir, "1/img.png", "PNG-BYTES")
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, signURL(storagePath, 1, time.Hour), nil)
|
||||
w := httptest.NewRecorder()
|
||||
engine.ServeHTTP(w, req)
|
||||
|
||||
if got, want := w.Code, http.StatusOK; got != want {
|
||||
t.Fatalf("status = %d, want %d", got, want)
|
||||
}
|
||||
if got := w.Body.String(); got != "PNG-BYTES" {
|
||||
t.Fatalf("body = %q, want %q", got, "PNG-BYTES")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPresignedFile_InvalidSig_403(t *testing.T) {
|
||||
engine, _, _ := setupPresignedTestServer(t)
|
||||
|
||||
// Hand-craft a URL with a tampered signature.
|
||||
q := url.Values{}
|
||||
q.Set("file_path", "local://1/img.png")
|
||||
q.Set("tenant_id", "1")
|
||||
q.Set("expires", strconv.FormatInt(time.Now().Add(time.Hour).Unix(), 10))
|
||||
q.Set("sig", "deadbeefdeadbeef")
|
||||
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
t.Run(method, func(t *testing.T) {
|
||||
req := httptest.NewRequest(method, "/api/v1/files/presigned?"+q.Encode(), nil)
|
||||
w := httptest.NewRecorder()
|
||||
engine.ServeHTTP(w, req)
|
||||
if got, want := w.Code, http.StatusForbidden; got != want {
|
||||
t.Fatalf("status = %d, want %d", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPresignedFile_MissingParams_400(t *testing.T) {
|
||||
engine, _, _ := setupPresignedTestServer(t)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/files/presigned?file_path=local%3A%2F%2F1%2Fimg.png", nil)
|
||||
w := httptest.NewRecorder()
|
||||
engine.ServeHTTP(w, req)
|
||||
if got, want := w.Code, http.StatusBadRequest; got != want {
|
||||
t.Fatalf("status = %d, want %d", got, want)
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "missing required parameters") {
|
||||
t.Fatalf("body = %q, want missing-params error", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPresignedFile_MissingFile_404(t *testing.T) {
|
||||
engine, _, signURL := setupPresignedTestServer(t)
|
||||
|
||||
// A legitimately signed URL pointing at a file that does not exist.
|
||||
req := httptest.NewRequest(http.MethodGet, signURL("local://1/nope.png", 1, time.Hour), nil)
|
||||
w := httptest.NewRecorder()
|
||||
engine.ServeHTTP(w, req)
|
||||
if got, want := w.Code, http.StatusNotFound; got != want {
|
||||
t.Fatalf("status = %d, want %d", got, want)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user