feat(backend): file-scoped content tokens for media URLs
Opening an original by URL (?access_token=) baked in the 15-minute access token, so a long video opened in a new tab stopped streaming once that token expired mid-playback: the access token can't be refreshed in an already-opened tab, and its next Range request 401'd. Add a content token: a signed, single-file capability (typ=content, fid claim) with its own longer TTL (CONTENT_TOKEN_TTL, default 6h) and — crucially — no session id, so it survives refresh rotation and outlives the short access TTL. POST /files/:id/content-token mints one after the same view-ACL check content serving does; GET /files/:id/content now runs under content-aware auth that accepts either a normal access token or a content token scoped to that file. View permission is still enforced against the token's user, so the token only changes when a file may be read by URL, never which files. It's a bearer capability for that one file until expiry, hence the bounded, configurable TTL. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -22,13 +22,14 @@ import (
|
||||
type FileHandler struct {
|
||||
fileSvc *service.FileService
|
||||
tagSvc *service.TagService
|
||||
authSvc *service.AuthService
|
||||
maxUploadBytes int64
|
||||
}
|
||||
|
||||
// NewFileHandler creates a FileHandler. maxUploadBytes caps the size of an
|
||||
// uploaded or replacement file.
|
||||
func NewFileHandler(fileSvc *service.FileService, tagSvc *service.TagService, maxUploadBytes int64) *FileHandler {
|
||||
return &FileHandler{fileSvc: fileSvc, tagSvc: tagSvc, maxUploadBytes: maxUploadBytes}
|
||||
// uploaded or replacement file. authSvc mints content tokens for media URLs.
|
||||
func NewFileHandler(fileSvc *service.FileService, tagSvc *service.TagService, authSvc *service.AuthService, maxUploadBytes int64) *FileHandler {
|
||||
return &FileHandler{fileSvc: fileSvc, tagSvc: tagSvc, authSvc: authSvc, maxUploadBytes: maxUploadBytes}
|
||||
}
|
||||
|
||||
// formFileLimited reads the "file" multipart field while bounding how many bytes
|
||||
@@ -383,6 +384,38 @@ func (h *FileHandler) SoftDelete(c *gin.Context) {
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// POST /files/:id/content-token
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// CreateContentToken mints a short-lived, single-file capability token the
|
||||
// client can put in a content URL's access_token query parameter to open or
|
||||
// stream the original by link (e.g. a long video in a new tab) without the URL
|
||||
// dying when the 15-minute access token expires. It first enforces view
|
||||
// permission via fileSvc.Get, so a token is only issued for a file the caller
|
||||
// may actually read.
|
||||
func (h *FileHandler) CreateContentToken(c *gin.Context) {
|
||||
id, ok := parseFileID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// Authorize (and confirm existence) the same way content serving does.
|
||||
if _, err := h.fileSvc.Get(c.Request.Context(), id); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
userID, isAdmin, _ := domain.UserFromContext(c.Request.Context())
|
||||
token, expiresIn, err := h.authSvc.GenerateContentToken(id.String(), userID, isAdmin)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"token": token, "expires_in": expiresIn})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GET /files/:id/content
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"tanabata/backend/internal/domain"
|
||||
"tanabata/backend/internal/service"
|
||||
@@ -50,6 +51,55 @@ func (m *AuthMiddleware) Handle() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// HandleContent authenticates a file-content GET, accepting either a normal
|
||||
// access token or a content token scoped (by its fid claim) to the :id in the
|
||||
// path. The content token is what keeps a long media stream playing after the
|
||||
// short access token would have expired. View permission is still enforced in
|
||||
// the handler against the resolved user, so a content token only widens *when*
|
||||
// a file may be read by URL, never *which* files.
|
||||
func (m *AuthMiddleware) HandleContent() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
token := bearerToken(c)
|
||||
if token == "" {
|
||||
contentUnauthorized(c)
|
||||
return
|
||||
}
|
||||
|
||||
// A regular access token grants access to everything as usual.
|
||||
if claims, err := m.authSvc.ValidateAccessToken(c.Request.Context(), token); err == nil {
|
||||
ctx := domain.WithUser(c.Request.Context(), claims.UserID, claims.IsAdmin, claims.SessionID)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// Otherwise accept a content token minted for exactly this file. Normalise
|
||||
// the path id to canonical form so it matches the minted fid claim.
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
contentUnauthorized(c)
|
||||
return
|
||||
}
|
||||
claims, err := m.authSvc.ValidateContentToken(token, id.String())
|
||||
if err != nil {
|
||||
contentUnauthorized(c)
|
||||
return
|
||||
}
|
||||
// A content token carries no session (sid 0); it is session-independent.
|
||||
ctx := domain.WithUser(c.Request.Context(), claims.UserID, claims.IsAdmin, claims.SessionID)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func contentUnauthorized(c *gin.Context) {
|
||||
c.JSON(http.StatusUnauthorized, errorBody{
|
||||
Code: domain.ErrUnauthorized.Code(),
|
||||
Message: "invalid or expired token",
|
||||
})
|
||||
c.Abort()
|
||||
}
|
||||
|
||||
// bearerToken extracts the access token from the Authorization header. As a
|
||||
// fallback it accepts an ?access_token= query parameter, but only for GET
|
||||
// requests — this lets the browser open media (e.g. /files/{id}/content) via a
|
||||
|
||||
@@ -91,8 +91,9 @@ func NewRouter(
|
||||
files.PATCH("/:id", fileHandler.UpdateMeta)
|
||||
files.DELETE("/:id", fileHandler.SoftDelete)
|
||||
|
||||
files.GET("/:id/content", fileHandler.GetContent)
|
||||
files.PUT("/:id/content", fileHandler.ReplaceContent)
|
||||
// Mints a content token (strict auth) for the GET /:id/content route below.
|
||||
files.POST("/:id/content-token", fileHandler.CreateContentToken)
|
||||
files.GET("/:id/thumbnail", fileHandler.GetThumbnail)
|
||||
files.GET("/:id/preview", fileHandler.GetPreview)
|
||||
files.POST("/:id/views", fileHandler.RecordView)
|
||||
@@ -106,6 +107,15 @@ func NewRouter(
|
||||
files.DELETE("/:id/tags/:tag_id", tagHandler.FileRemoveTag)
|
||||
}
|
||||
|
||||
// Serving an original is the one read that can outlive a 15-minute access
|
||||
// token — a long video streams via repeated Range requests over many minutes.
|
||||
// So this route alone also accepts a file-scoped content token (see
|
||||
// HandleContent), letting the media URL stay valid for the whole playback.
|
||||
media := v1.Group("/files", auth.HandleContent())
|
||||
{
|
||||
media.GET("/:id/content", fileHandler.GetContent)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Tags (all require auth)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package handler
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestNewRouterRegisters builds the router with typed-nil dependencies to assert
|
||||
// route registration itself succeeds. Gin panics on a route conflict (e.g. a
|
||||
// duplicated method+path or an inconsistent wildcard name) during registration,
|
||||
// before any handler runs — so this catches such mistakes without a database.
|
||||
// Handlers are never invoked here; method values on nil pointers are fine.
|
||||
func TestNewRouterRegisters(t *testing.T) {
|
||||
r, err := NewRouter(
|
||||
(*AuthMiddleware)(nil), (*AuthHandler)(nil),
|
||||
(*FileHandler)(nil), (*TagHandler)(nil), (*CategoryHandler)(nil), (*PoolHandler)(nil),
|
||||
(*UserHandler)(nil), (*ACLHandler)(nil), (*AuditHandler)(nil),
|
||||
"", nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter: %v", err)
|
||||
}
|
||||
if r == nil {
|
||||
t.Fatal("NewRouter returned nil engine")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user