// SPDX-License-Identifier: AGPL-3.0-or-later
package httpapi
import (
"context"
"io"
"mime"
"net/http"
"time"
"docwell/server/internal/access"
"docwell/server/internal/auth"
"docwell/server/internal/directory"
)
// AttachmentService is the part of directory.Service that handles page files.
type AttachmentService interface {
UploadAttachment(ctx context.Context, c access.Caller, pageID, filename string, file io.Reader) (directory.Attachment, error)
ListAttachments(ctx context.Context, c access.Caller, pageID string) ([]directory.Attachment, error)
DeleteAttachment(ctx context.Context, c access.Caller, id string) error
OpenAttachment(ctx context.Context, c access.Caller, id string, header http.Header) (directory.FileDownload, error)
}
// inlineTypes are shown in the browser; everything else downloads, so a
// stored HTML file can never run script on the API's origin. SVG is shown
// (drawings are stored as SVG): in an
it never runs script, and opened
// directly the response's CSP (no script source, sandbox) stops any.
var inlineTypes = map[string]bool{
"image/png": true, "image/jpeg": true, "image/gif": true, "image/webp": true, "image/avif": true, "image/svg+xml": true,
"application/pdf": true, "video/mp4": true, "video/webm": true, "audio/mpeg": true, "audio/ogg": true,
}
func (a *api) fileRoutes(mux *routeMux, maxUpload int64) {
mux.HandleFunc("GET /api/v1/pages/{id}/attachments", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
list, err := a.dir.ListAttachments(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, list, err)
}))
mux.HandleFunc("POST /api/v1/pages/{id}/attachments", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxUpload+1<<20)
mr, err := r.MultipartReader()
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "expected multipart/form-data"})
return
}
for {
part, err := mr.NextPart()
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "no file part"})
return
}
if part.FormName() != "file" {
_ = part.Close()
continue
}
att, err := a.dir.UploadAttachment(r.Context(), caller(r), r.PathValue("id"), part.FileName(), part)
_ = part.Close()
a.respondStatus(w, http.StatusCreated, att, err)
return
}
}))
mux.HandleFunc("DELETE /api/v1/attachments/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
a.respondNoContent(w, a.dir.DeleteAttachment(r.Context(), caller(r), r.PathValue("id")))
}))
mux.HandleFunc("POST /api/v1/files/token", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
u, _ := CurrentUser(r.Context())
token, exp := a.files.Issue(u.ID)
writeJSON(w, http.StatusOK, map[string]string{"token": token, "expires": exp.UTC().Format(time.RFC3339)})
}))
// Files load with the session token or, for
tags and links, ?token=.
mux.HandleFunc("GET /api/v1/files/{id}", func(w http.ResponseWriter, r *http.Request) {
u, err := a.fileUser(r)
if err != nil {
a.writeError(w, err)
return
}
f, err := a.dir.OpenAttachment(r.Context(), u.Caller(), r.PathValue("id"), r.Header)
if err != nil {
a.writeError(w, err)
return
}
serveFile(w, f)
})
}
// fileUser identifies a download's user from the bearer token or a file token.
func (a *api) fileUser(r *http.Request) (auth.User, error) {
if t := auth.BearerToken(r); t != "" {
return a.auth.Verify(r.Context(), t)
}
if a.files == nil {
return auth.User{}, auth.ErrUnauthorized
}
id, err := a.files.Parse(r.URL.Query().Get("token"))
if err != nil {
return auth.User{}, err
}
return a.auth.UserByID(r.Context(), id)
}
func serveFile(w http.ResponseWriter, f directory.FileDownload) {
defer f.Body.Close()
h := w.Header()
for _, k := range []string{"Content-Length", "Content-Range", "Accept-Ranges", "ETag", "Last-Modified"} {
if v := f.Header.Get(k); v != "" {
h.Set(k, v)
}
}
disposition := "attachment"
contentType := "application/octet-stream"
if inlineTypes[f.Mime] {
disposition, contentType = "inline", f.Mime
}
h.Set("Content-Type", contentType)
h.Set("Content-Disposition", mime.FormatMediaType(disposition, map[string]string{"filename": f.Name}))
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Content-Security-Policy", "default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox")
h.Set("Cache-Control", "private, max-age=3600")
w.WriteHeader(f.StatusCode)
_, _ = io.Copy(w, f.Body)
}