navid/veinsforge / f01606a53246ae5f33eacb77fbb8d149679fce25958bb46523525556482c27d6 / internal/web/attachments.go
attachments.go
← internal/web · 5654 bytes · raw · download
package web
import (
"io"
"mime"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"veinsforge/internal/auth"
"veinsforge/internal/data"
)
func (s *Server) handleAttachmentUpload(w http.ResponseWriter, r *http.Request) {
repo, perms, ok := s.repoFromPath(w, r)
if !ok {
return
}
u := s.requireUser(w, r)
if u == nil {
return
}
if !perms.CanView || repo.Archived {
s.renderError(w, r, http.StatusForbidden, "Cannot attach files here.")
return
}
subjectType := r.FormValue("subject_type")
subjectID, ok := parseID(r.FormValue("subject_id"))
if !ok || (subjectType != "issue" && subjectType != "pull") {
s.renderError(w, r, http.StatusBadRequest, "Invalid attachment target.")
return
}
if subjectType == "issue" {
issue, err := s.data.GetIssueByID(r.Context(), subjectID)
if err != nil || issue.RepoID != repo.ID {
s.renderError(w, r, http.StatusNotFound, "Issue not found.")
return
}
} else {
pull, err := s.data.GetPullByID(r.Context(), subjectID)
if err != nil || pull.RepoID != repo.ID {
s.renderError(w, r, http.StatusNotFound, "Pull request not found.")
return
}
}
file, header, err := r.FormFile("file")
if err != nil {
redirect(w, r, repoURL(repo), "", "Choose a file to upload.")
return
}
defer file.Close()
dataBytes, err := io.ReadAll(io.LimitReader(file, s.cfg.MaxUploadBytes+1))
if err != nil || int64(len(dataBytes)) > s.cfg.MaxUploadBytes {
redirect(w, r, repoURL(repo), "", "Attachment is too large.")
return
}
if len(dataBytes) == 0 {
redirect(w, r, repoURL(repo), "", "Attachment is empty.")
return
}
filename := sanitizeFilename(header.Filename)
if filename == "" {
filename = "attachment"
}
mimeType := http.DetectContentType(dataBytes[:minInt(len(dataBytes), 512)])
ext := filepath.Ext(filename)
if strings.EqualFold(ext, ".svg") || strings.Contains(strings.ToLower(mimeType), "svg") || strings.Contains(strings.ToLower(mimeType), "html") {
mimeType = "application/octet-stream"
}
id, err := auth.RandomToken(18)
if err != nil {
redirect(w, r, repoURL(repo), "", "Could not store the attachment.")
return
}
stored := id
if safeExt := cleanExt(ext); safeExt != "" {
stored += safeExt
}
dir := filepath.Join(s.cfg.AttachmentDir, strconv.FormatInt(repo.ID, 10))
if err := os.MkdirAll(dir, 0o700); err != nil {
redirect(w, r, repoURL(repo), "", "Could not store the attachment.")
return
}
if err := os.WriteFile(filepath.Join(dir, stored), dataBytes, 0o600); err != nil {
redirect(w, r, repoURL(repo), "", "Could not store the attachment.")
return
}
att := &data.Attachment{
ID: id, RepoID: repo.ID, UploaderID: u.ID, SubjectType: subjectType, SubjectID: subjectID,
Filename: filename, StoredName: stored, MIME: mimeType, Size: int64(len(dataBytes)),
}
if err := s.data.CreateAttachment(r.Context(), att); err != nil {
_ = os.Remove(filepath.Join(dir, stored))
redirect(w, r, repoURL(repo), "", "Could not save the attachment record.")
return
}
s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "attachment.create", repo.OwnerName+"/"+repo.Name+" "+filename, r.UserAgent())
target := repoURL(repo) + "/issues"
if subjectType == "pull" {
target = repoURL(repo) + "/pulls"
}
// Redirect back to the concrete subject.
if subjectType == "issue" {
if issue, err := s.data.GetIssueByID(r.Context(), subjectID); err == nil {
target = issueURL(repo, issue.Number)
}
} else {
if pull, err := s.data.GetPullByID(r.Context(), subjectID); err == nil {
target = pullURL(repo, pull.Number)
}
}
redirect(w, r, target, "Attachment uploaded.", "")
}
func (s *Server) attachmentGet(w http.ResponseWriter, r *http.Request) {
att, err := s.data.GetAttachment(r.Context(), r.PathValue("id"))
if err != nil {
http.NotFound(w, r)
return
}
repo, err := s.data.GetRepoByID(r.Context(), att.RepoID)
if err != nil {
http.NotFound(w, r)
return
}
perms, err := s.data.Permissions(r.Context(), repo, userFrom(r))
if err != nil || !perms.CanView {
http.NotFound(w, r)
return
}
file := filepath.Join(s.cfg.AttachmentDir, strconv.FormatInt(repo.ID, 10), filepath.Base(att.StoredName))
f, err := os.Open(file)
if err != nil {
http.NotFound(w, r)
return
}
defer f.Close()
stat, err := f.Stat()
if err != nil {
http.NotFound(w, r)
return
}
name := sanitizeFilename(att.Filename)
if name == "" {
name = "attachment"
}
mimeType := att.MIME
disposition := "attachment"
if isSafeImage(mimeType) {
disposition = "inline"
} else if !strings.HasPrefix(mimeType, "text/") && mimeType != "application/pdf" {
mimeType = "application/octet-stream"
}
w.Header().Set("Content-Type", mimeType)
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Disposition", mime.FormatMediaType(disposition, map[string]string{"filename": name}))
w.Header().Set("Cache-Control", "private, max-age=300")
http.ServeContent(w, r, name, stat.ModTime(), f)
}
func sanitizeFilename(name string) string {
name = filepath.Base(strings.ReplaceAll(name, "\\", "/"))
name = strings.Map(func(r rune) rune {
if r < 32 || r == 127 || r == '"' || r == '\'' || r == '\n' || r == '\r' {
return -1
}
return r
}, name)
name = strings.TrimSpace(name)
if len(name) > 200 {
name = name[:200]
}
if name == "." || name == ".." {
return ""
}
return name
}
func cleanExt(ext string) string {
if len(ext) < 2 || len(ext) > 12 {
return ""
}
ext = strings.ToLower(ext)
for _, r := range ext[1:] {
if (r < 'a' || r > 'z') && (r < '0' || r > '9') {
return ""
}
}
return ext
}
func minInt(a, b int) int {
if a < b {
return a
}
return b
}