Files
Anya Tokugawa b90aef79d0
Build and publish container images / images (push) Successful in 11m37s
Release container images / release (push) Successful in 22s
feat: add browser upload queue and trusted sessions with bounded projections
2026-11-08 20:27:04 +09:00

149 lines
4.5 KiB
Go

package server
import (
"database/sql"
"errors"
"io"
"mime"
"net/http"
"path/filepath"
"strings"
"pageswiki/internal/store"
)
const maxWebUploadBytes = int64(256 << 20)
func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
s.renderWithContext(w, r, "upload.gohtml", map[string]any{
"Title": translate(
s.getLocale(s.domainUUIDForRequest(r)),
"upload.title",
),
"NavItems": resolveNavItems(
s.getSystemNavItems(s.domainUUIDForRequest(r)),
NavContext{},
),
"SuggestedPath": r.URL.Query().Get("path"),
})
return
}
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxWebUploadBytes+(1<<20))
if err := r.ParseMultipartForm(32 << 20); err != nil {
http.Error(w, err.Error(), http.StatusRequestEntityTooLarge)
return
}
defer r.MultipartForm.RemoveAll()
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, "file is required", http.StatusBadRequest)
return
}
defer file.Close()
payload, err := io.ReadAll(io.LimitReader(file, maxWebUploadBytes+1))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if int64(len(payload)) > maxWebUploadBytes {
http.Error(w, "file is too large", http.StatusRequestEntityTooLarge)
return
}
originalName := filepath.Base(strings.TrimSpace(header.Filename))
if originalName == "." || originalName == "/" || originalName == "" {
http.Error(w, "invalid filename", http.StatusBadRequest)
return
}
targetPath := strings.TrimSpace(r.FormValue("path"))
if targetPath == "" {
targetPath = "/" + originalName
} else if strings.HasSuffix(targetPath, "/") {
targetPath += originalName
}
if !strings.HasPrefix(targetPath, "/") {
targetPath = "/" + targetPath
}
domainUUID := s.domainUUIDForRequest(r)
mode, _ := s.store.GetConfigInDomain(domainUUID, "authorization_mode")
var principal *store.Principal
if mode == "enforcing" {
var authErr error
principal, authErr = s.store.PrincipalForSession(domainUUID, s.authTokenFromRequest(r))
if authErr != nil || s.store.Authorize(store.AuthorizationRequest{DomainUUID: domainUUID, PrincipalUUID: principal.UUID, Capability: "upload", TargetType: "path", TargetID: targetPath}) != nil {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
}
objectUUID, err := s.store.ResolvePathInDomain(domainUUID, targetPath)
createOnly := r.Header.Get("If-None-Match") == "*"
if err == nil && createOnly {
http.Error(w, "file already exists", http.StatusPreconditionFailed)
return
}
if err == nil && mode == "enforcing" {
// upload and write-once grants never overwrite an existing object.
if s.store.Authorize(store.AuthorizationRequest{DomainUUID: domainUUID, PrincipalUUID: principal.UUID, Capability: "write", TargetType: "path", TargetID: targetPath}) != nil {
http.Error(w, "existing files cannot be overwritten", http.StatusForbidden)
return
}
}
if errors.Is(err, sql.ErrNoRows) {
objectUUID, err = s.store.CreatePageAtPathInDomain(domainUUID, targetPath)
if err != nil && createOnly {
// A concurrent creator wins; never turn this into an overwrite.
if _, resolveErr := s.store.ResolvePathInDomain(domainUUID, targetPath); resolveErr == nil {
http.Error(w, "file already exists", http.StatusPreconditionFailed)
return
}
}
}
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
contentType := strings.TrimSpace(header.Header.Get("Content-Type"))
if mediaType, _, parseErr := mime.ParseMediaType(contentType); parseErr != nil ||
mediaType == "application/octet-stream" {
detected := detectRevisionText(payload, originalName)
if detected.ContentType != "" {
contentType = detected.ContentType
}
}
if contentType == "" {
contentType = "application/octet-stream"
}
language := s.campusForDomain(s.domainForRequest(r)).DefaultLang
if strings.TrimSpace(language) == "" {
language = "und"
}
revision, err := s.store.SaveRevisionContent(
objectUUID,
payload,
"web upload: "+originalName,
language,
contentType,
originalName,
)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if strings.Contains(r.Header.Get("Accept"), "application/json") {
w.Header().Set("Cache-Control", "private, no-store")
writeEventJSON(w, http.StatusCreated, map[string]string{"path": targetPath, "object_uuid": objectUUID, "revision_uuid": revision.UUID})
return
}
http.Redirect(w, r, targetPath, http.StatusSeeOther)
}