* HH-438: close upload and remote URL attack surfaces * HH-438: use valid PNG in direct upload test * HH-438: align PostgreSQL upload staging schema * HH-438: run upload migrations before PostgreSQL E2E --------- Co-authored-by: Rogee <rogee@ipao.vip>
292 lines
9.1 KiB
Go
292 lines
9.1 KiB
Go
package v1
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/gochat/gochat/internal/auth"
|
|
"github.com/gochat/gochat/internal/service"
|
|
"github.com/gochat/gochat/pkg/response"
|
|
)
|
|
|
|
// UploadHandler handles file upload endpoints (account-level + widget direct + account direct).
|
|
type UploadHandler struct {
|
|
svc *service.UploadService
|
|
jwtSvc *auth.JWTService
|
|
}
|
|
|
|
// WithAccessAuth enables authenticated serving of local private uploads.
|
|
func (h *UploadHandler) WithAccessAuth(jwtSvc *auth.JWTService) *UploadHandler {
|
|
h.jwtSvc = jwtSvc
|
|
return h
|
|
}
|
|
|
|
// NewUploadHandler creates a new UploadHandler.
|
|
func NewUploadHandler(svc *service.UploadService) *UploadHandler {
|
|
return &UploadHandler{svc: svc}
|
|
}
|
|
|
|
// Upload handles POST /api/v1/accounts/:id/upload — account-level file upload.
|
|
// Reference: Chatwoot api/v1/accounts/:account_id/upload
|
|
func (h *UploadHandler) Upload(c *gin.Context) {
|
|
h.limitBody(c)
|
|
accountID := getAccountID(c)
|
|
if accountID == 0 {
|
|
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "account_id is required")
|
|
return
|
|
}
|
|
|
|
var result *service.UploadResponse
|
|
var svcErr error
|
|
if strings.Contains(c.GetHeader("Content-Type"), "application/json") {
|
|
var req struct {
|
|
ExternalURL string `json:"external_url"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.ExternalURL) == "" {
|
|
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "missing input"})
|
|
return
|
|
}
|
|
result, svcErr = h.svc.AccountUploadFromURL(c.Request.Context(), accountID, strings.TrimSpace(req.ExternalURL))
|
|
} else {
|
|
fileHeader, err := c.FormFile("attachment")
|
|
if err != nil {
|
|
fileHeader, err = c.FormFile("file")
|
|
}
|
|
if err != nil {
|
|
status := http.StatusUnprocessableEntity
|
|
if isUploadBodyTooLarge(err) {
|
|
status = http.StatusRequestEntityTooLarge
|
|
}
|
|
c.JSON(status, gin.H{"error": "missing input"})
|
|
return
|
|
}
|
|
result, svcErr = h.svc.AccountUpload(c.Request.Context(), accountID, service.AccountUploadRequest{
|
|
FileHeader: fileHeader,
|
|
})
|
|
}
|
|
if svcErr != nil {
|
|
status := http.StatusUnprocessableEntity
|
|
if errors.Is(svcErr, gorm.ErrRecordNotFound) {
|
|
status = http.StatusNotFound
|
|
}
|
|
c.JSON(status, gin.H{"error": svcErr.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"file_url": result.FileURL,
|
|
"blob_id": result.UploadUUID,
|
|
"blob_key": result.UploadUUID,
|
|
})
|
|
}
|
|
|
|
// DirectUpload handles POST /api/v1/widget/direct_uploads — widget direct file upload.
|
|
// Reference: Chatwoot POST /widget/direct_uploads
|
|
func (h *UploadHandler) DirectUpload(c *gin.Context) {
|
|
h.limitBody(c)
|
|
if strings.Contains(c.GetHeader("Content-Type"), "application/json") {
|
|
var req service.ActiveStorageDirectUploadRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "invalid direct upload metadata")
|
|
return
|
|
}
|
|
req.WebsiteToken = c.Query("website_token")
|
|
req.AuthToken = c.GetHeader("X-Auth-Token")
|
|
result, svcErr := h.svc.CreateWidgetDirectUpload(c.Request.Context(), req)
|
|
if svcErr != nil {
|
|
handleServiceError(c, svcErr)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, result)
|
|
return
|
|
}
|
|
|
|
fileHeader, err := c.FormFile("file")
|
|
if err != nil {
|
|
if isUploadBodyTooLarge(err) {
|
|
c.AbortWithStatusJSON(http.StatusRequestEntityTooLarge, gin.H{"error": "upload body is too large"})
|
|
} else {
|
|
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "file is required")
|
|
}
|
|
return
|
|
}
|
|
|
|
result, svcErr := h.svc.WidgetDirectUpload(c.Request.Context(), service.WidgetDirectUploadRequest{
|
|
WebsiteToken: c.Query("website_token"),
|
|
AuthToken: c.GetHeader("X-Auth-Token"),
|
|
FileHeader: fileHeader,
|
|
})
|
|
if svcErr != nil {
|
|
handleServiceError(c, svcErr)
|
|
return
|
|
}
|
|
|
|
response.OK(c, result)
|
|
}
|
|
|
|
func (h *UploadHandler) CompleteWidgetDirectUpload(c *gin.Context) {
|
|
h.limitBody(c)
|
|
result, svcErr := h.svc.CompleteWidgetDirectUpload(c.Request.Context(), c.Param("upload_uuid"), c.Request.Body, c.Query("token"))
|
|
if svcErr != nil {
|
|
handleServiceError(c, svcErr)
|
|
return
|
|
}
|
|
response.OK(c, result)
|
|
}
|
|
|
|
// AccountDirectUpload handles POST /api/v1/accounts/:id/direct_uploads — account-level staged upload.
|
|
// Returns a blob/UUID for later attachment to messages.
|
|
// Reference: Chatwoot POST /api/v1/accounts/:account_id/direct_uploads
|
|
func (h *UploadHandler) AccountDirectUpload(c *gin.Context) {
|
|
h.limitBody(c)
|
|
accountID := getAccountID(c)
|
|
if accountID == 0 {
|
|
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "account_id is required")
|
|
return
|
|
}
|
|
|
|
fileHeader, err := c.FormFile("file")
|
|
if err != nil {
|
|
if isUploadBodyTooLarge(err) {
|
|
c.AbortWithStatusJSON(http.StatusRequestEntityTooLarge, gin.H{"error": "upload body is too large"})
|
|
} else {
|
|
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "file is required")
|
|
}
|
|
return
|
|
}
|
|
|
|
result, svcErr := h.svc.AccountDirectUpload(c.Request.Context(), accountID, service.AccountDirectUploadRequest{
|
|
FileHeader: fileHeader,
|
|
})
|
|
if svcErr != nil {
|
|
handleServiceError(c, svcErr)
|
|
return
|
|
}
|
|
|
|
response.OK(c, result)
|
|
}
|
|
|
|
// ConversationDirectUpload handles Chatwoot's nested conversation direct upload
|
|
// endpoint used by the reused dashboard message composer.
|
|
// Reference: POST /api/v1/accounts/:account_id/conversations/:conversation_id/direct_uploads
|
|
func (h *UploadHandler) ConversationDirectUpload(c *gin.Context) {
|
|
h.limitBody(c)
|
|
accountID := getAccountID(c)
|
|
if accountID == 0 {
|
|
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "account_id is required")
|
|
return
|
|
}
|
|
conversationID, err := parseUintParam(c, "conversation_id")
|
|
if err != nil || conversationID == 0 {
|
|
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid conversation_id")
|
|
return
|
|
}
|
|
|
|
if !strings.Contains(c.GetHeader("Content-Type"), "application/json") {
|
|
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "invalid direct upload metadata")
|
|
return
|
|
}
|
|
|
|
var req service.ActiveStorageDirectUploadRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "invalid direct upload metadata")
|
|
return
|
|
}
|
|
result, svcErr := h.svc.CreateConversationDirectUpload(c.Request.Context(), accountID, conversationID, req)
|
|
if svcErr != nil {
|
|
handleServiceError(c, svcErr)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, result)
|
|
}
|
|
|
|
func (h *UploadHandler) CompleteConversationDirectUpload(c *gin.Context) {
|
|
h.limitBody(c)
|
|
accountID := getAccountID(c)
|
|
if accountID == 0 {
|
|
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "account_id is required")
|
|
return
|
|
}
|
|
conversationID, err := parseUintParam(c, "conversation_id")
|
|
if err != nil || conversationID == 0 {
|
|
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid conversation_id")
|
|
return
|
|
}
|
|
|
|
result, svcErr := h.svc.CompleteConversationDirectUpload(c.Request.Context(), accountID, conversationID, c.Param("upload_uuid"), c.Request.Body)
|
|
if svcErr != nil {
|
|
handleServiceError(c, svcErr)
|
|
return
|
|
}
|
|
response.OK(c, result)
|
|
}
|
|
|
|
// ServeUpload replaces the public StaticFS route with account/widget-session
|
|
// authorization. Deliberately return 404 for every denied lookup to avoid an
|
|
// attachment existence oracle across tenants.
|
|
func (h *UploadHandler) ServeUpload(c *gin.Context) {
|
|
fileURL := "/uploads/" + strings.TrimPrefix(c.Param("filepath"), "/")
|
|
fullPath, ok := h.svc.ResolveAuthorizedUpload(c.Request.Context(), fileURL, h.dashboardAccountID(c), widgetAccessToken(c))
|
|
if !ok {
|
|
c.Status(http.StatusNotFound)
|
|
return
|
|
}
|
|
c.Header("Cache-Control", "private, no-store")
|
|
c.Header("Content-Security-Policy", "sandbox")
|
|
c.Header("X-Content-Type-Options", "nosniff")
|
|
c.File(fullPath)
|
|
}
|
|
|
|
func (h *UploadHandler) limitBody(c *gin.Context) {
|
|
if c.Request.Body != nil {
|
|
limit := int64(21 << 20)
|
|
if h.svc != nil {
|
|
limit = h.svc.MaxRequestBodySize()
|
|
}
|
|
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, limit)
|
|
}
|
|
}
|
|
|
|
func (h *UploadHandler) dashboardAccountID(c *gin.Context) uint {
|
|
if h.jwtSvc == nil {
|
|
return 0
|
|
}
|
|
token := strings.TrimSpace(c.GetHeader("access-token"))
|
|
if authorization := c.GetHeader("Authorization"); strings.HasPrefix(authorization, "Bearer ") {
|
|
token = strings.TrimPrefix(authorization, "Bearer ")
|
|
}
|
|
if token == "" {
|
|
if cookie, err := c.Cookie("cw_d_session_info"); err == nil {
|
|
var session map[string]any
|
|
if json.Unmarshal([]byte(cookie), &session) == nil {
|
|
token, _ = session["access-token"].(string)
|
|
}
|
|
}
|
|
}
|
|
claims, err := h.jwtSvc.ValidateAccessToken(token)
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
return claims.AccountID
|
|
}
|
|
|
|
func widgetAccessToken(c *gin.Context) string {
|
|
for _, token := range []string{c.GetHeader("X-Widget-Token"), c.GetHeader("X-Auth-Token")} {
|
|
if token != "" {
|
|
return token
|
|
}
|
|
}
|
|
token, _ := c.Cookie("cw_conversation")
|
|
return token
|
|
}
|
|
|
|
func isUploadBodyTooLarge(err error) bool {
|
|
var maxBytesError *http.MaxBytesError
|
|
return errors.As(err, &maxBytesError) || strings.Contains(strings.ToLower(err.Error()), "request body too large")
|
|
}
|