page on failure

This commit is contained in:
2026-11-20 21:57:06 -05:00
parent 6650d0d1c2
commit 123e47596b
5 changed files with 62 additions and 48 deletions
+42 -42
View File
@@ -52,7 +52,7 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost && r.Method != http.MethodPut { if r.Method != http.MethodPost && r.Method != http.MethodPut {
w.Header().Set("Allow", "POST,PUT") w.Header().Set("Allow", "POST,PUT")
http.Error(w, "invalid method", http.StatusMethodNotAllowed) pages.HTTPError(w, r, "invalid method", http.StatusMethodNotAllowed)
return return
} }
@@ -64,7 +64,7 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc {
if r.Method == http.MethodPost || r.Header.Get("Content-Type") != "" { if r.Method == http.MethodPost || r.Header.Get("Content-Type") != "" {
mediaType, _, err = mime.ParseMediaType(r.Header.Get("Content-Type")) mediaType, _, err = mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil { if err != nil {
http.Error(w, "failed to find or parse Content-Type", http.StatusBadRequest) pages.HTTPError(w, r, "failed to find or parse Content-Type", http.StatusBadRequest)
return return
} }
} }
@@ -84,11 +84,11 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc {
} }
if err != nil { if err != nil {
if _, ok := errors.AsType[*http.MaxBytesError](err); ok { if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
http.Error(w, "upload too large", http.StatusRequestEntityTooLarge) pages.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge)
return return
} }
http.Error(w, "invalid file", http.StatusBadRequest) pages.HTTPError(w, r, "invalid file", http.StatusBadRequest)
return return
} }
defer file.Close() defer file.Close()
@@ -96,11 +96,11 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc {
input.MIMEType, err = detectMimeType(file) input.MIMEType, err = detectMimeType(file)
if err != nil { if err != nil {
log.Println("detect file mime type:", err) log.Println("detect file mime type:", err)
http.Error(w, "failed to detect mime type", http.StatusInternalServerError) pages.HTTPError(w, r, "failed to detect mime type", http.StatusInternalServerError)
return return
} }
if slices.Contains(cfg.BannedMIMETypes, input.MIMEType) { if slices.Contains(cfg.BannedMIMETypes, input.MIMEType) {
http.Error(w, "content type not allowed", http.StatusBadRequest) pages.HTTPError(w, r, "content type not allowed", http.StatusBadRequest)
return return
} }
input.Reader = file input.Reader = file
@@ -110,7 +110,7 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc {
r.Body = http.MaxBytesReader(w, r.Body, cfg.MaxPasteBytes) r.Body = http.MaxBytesReader(w, r.Body, cfg.MaxPasteBytes)
var content string var content string
if mediaType == "application/x-www-form-urlencoded" { if mediaType == "application/x-www-form-urlencoded" {
err := r.ParseForm() err = r.ParseForm()
if err == nil { if err == nil {
content = r.PostForm.Get("content") content = r.PostForm.Get("content")
} }
@@ -124,16 +124,16 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc {
if err != nil { if err != nil {
if _, ok := errors.AsType[*http.MaxBytesError](err); ok { if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
http.Error(w, "upload too large", http.StatusRequestEntityTooLarge) pages.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge)
return return
} }
http.Error(w, "invalid paste upload", http.StatusBadRequest) pages.HTTPError(w, r, "invalid paste upload", http.StatusBadRequest)
return return
} }
if strings.TrimSpace(content) == "" { if strings.TrimSpace(content) == "" {
http.Error(w, "paste cannot be empty", http.StatusBadRequest) pages.HTTPError(w, r, "paste cannot be empty", http.StatusBadRequest)
return return
} }
@@ -144,7 +144,7 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc {
Type: ContentPaste, Type: ContentPaste,
} }
default: default:
http.Error(w, "unsupported Content-Type", http.StatusUnsupportedMediaType) pages.HTTPError(w, r, "unsupported Content-Type", http.StatusUnsupportedMediaType)
return return
} }
@@ -158,7 +158,7 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc {
selected, found := findExpiry(cfg.Expiries, expLabel) selected, found := findExpiry(cfg.Expiries, expLabel)
if !found { if !found {
http.Error(w, "invalid expiry", http.StatusBadRequest) pages.HTTPError(w, r, "invalid expiry", http.StatusBadRequest)
return return
} }
@@ -174,14 +174,14 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc {
path := getStoragePath(cfg.UploadDir, id) path := getStoragePath(cfg.UploadDir, id)
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
log.Println("create directories:", err) log.Println("create directories:", err)
http.Error(w, "failed to save upload", http.StatusInternalServerError) pages.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError)
return return
} }
dest, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) dest, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil { if err != nil {
log.Println("create file:", err) log.Println("create file:", err)
http.Error(w, "faield to save upload", http.StatusInternalServerError) pages.HTTPError(w, r, "faield to save upload", http.StatusInternalServerError)
return return
} }
@@ -199,23 +199,23 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc {
size, err := io.Copy(io.MultiWriter(dest, hasher), input.Reader) size, err := io.Copy(io.MultiWriter(dest, hasher), input.Reader)
if err != nil { if err != nil {
if _, ok := errors.AsType[*http.MaxBytesError](err); ok { if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
http.Error(w, "upload too large", http.StatusRequestEntityTooLarge) pages.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge)
return return
} }
log.Println("write file:", err) log.Println("write file:", err)
http.Error(w, "faield to write upload", http.StatusInternalServerError) pages.HTTPError(w, r, "faield to write upload", http.StatusInternalServerError)
return return
} }
if err := dest.Close(); err != nil { if err := dest.Close(); err != nil {
log.Println("close file:", err) log.Println("close file:", err)
http.Error(w, "failed to save upload", http.StatusInternalServerError) pages.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError)
return return
} }
createdAt := time.Now().UTC().Unix() createdAt := time.Now().UTC().Unix()
expires, err := selected.ExpiresFrom(time.Now().UTC()) expires, err := selected.ExpiresFrom(time.Now().UTC())
if err != nil { if err != nil {
log.Println("calc expiry:", err) // im just using slang log.Println("calc expiry:", err) // im just using slang
http.Error(w, "internal server error", http.StatusInternalServerError) pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
return return
} }
@@ -250,7 +250,7 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc {
err = insertUpload(db, &upload) err = insertUpload(db, &upload)
if err != nil { if err != nil {
log.Println("save upload:", err) log.Println("save upload:", err)
http.Error(w, "failed to save upload", http.StatusInternalServerError) pages.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError)
return return
} }
saved = true saved = true
@@ -280,12 +280,12 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc {
} }
} }
func contentHandler(db *gorm.DB, cfg Config, tracker *AccessTracker) http.HandlerFunc { func contentHandler(db *gorm.DB, cfg Config, tracker *AccessTracker, pages *Pages) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
id, _, _ := strings.Cut(r.PathValue("id"), ".") // remove any extension via strings.Cut id, _, _ := strings.Cut(r.PathValue("id"), ".") // remove any extension via strings.Cut
if !validPasteId(id) { if !validPasteId(id) {
http.NotFound(w, r) pages.HTTPError(w, r, "upload not found", 404)
return return
} }
@@ -293,28 +293,28 @@ func contentHandler(db *gorm.DB, cfg Config, tracker *AccessTracker) http.Handle
upload, err := getUploadById(db.WithContext(r.Context()), id) upload, err := getUploadById(db.WithContext(r.Context()), id)
if err != nil { if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
http.NotFound(w, r) pages.HTTPError(w, r, "upload not found", 404)
return return
} }
log.Println("get upload:", err) log.Println("get upload:", err)
http.Error(w, "internal server error", http.StatusInternalServerError) pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
return return
} }
now := time.Now().UTC().Unix() now := time.Now().UTC().Unix()
if upload.ExpiresAt != nil && now >= *upload.ExpiresAt { if upload.ExpiresAt != nil && now >= *upload.ExpiresAt {
http.NotFound(w, r) pages.HTTPError(w, r, "upload not found", 404)
return return
} }
file, err := os.Open(path) file, err := os.Open(path)
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
http.NotFound(w, r) pages.HTTPError(w, r, "upload not found", 404)
return return
} }
log.Println("get upload file:", err) log.Println("get upload file:", err)
http.Error(w, "internal server error", http.StatusInternalServerError) pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
return return
} }
@@ -346,23 +346,23 @@ func contentHandler(db *gorm.DB, cfg Config, tracker *AccessTracker) http.Handle
} }
} }
func contentInfoHandler(db *gorm.DB, tracker *AccessTracker) http.HandlerFunc { func contentInfoHandler(db *gorm.DB, tracker *AccessTracker, pages *Pages) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
id, _, _ := strings.Cut(r.PathValue("id"), ".") // remove any extension via strings.Cut id, _, _ := strings.Cut(r.PathValue("id"), ".") // remove any extension via strings.Cut
if !validPasteId(id) { if !validPasteId(id) {
http.NotFound(w, r) pages.HTTPError(w, r, "upload not found", 404)
return return
} }
upload, err := getUploadById(db, id) upload, err := getUploadById(db, id)
if err != nil { if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
http.NotFound(w, r) pages.HTTPError(w, r, "upload not found", 404)
return return
} }
log.Println("get upload:", err) log.Println("get upload:", err)
http.Error(w, "internal server error", http.StatusInternalServerError) pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
return return
} }
@@ -378,11 +378,11 @@ func contentInfoHandler(db *gorm.DB, tracker *AccessTracker) http.HandlerFunc {
} }
} }
func deleteHandler(db *gorm.DB, cfg Config) http.HandlerFunc { func deleteHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id") id := r.PathValue("id")
if !validPasteId(id) { if !validPasteId(id) {
http.NotFound(w, r) pages.HTTPError(w, r, "upload not found", 404)
return return
} }
redirect := r.URL.Query().Get("redirect") == "true" redirect := r.URL.Query().Get("redirect") == "true"
@@ -395,7 +395,7 @@ func deleteHandler(db *gorm.DB, cfg Config) http.HandlerFunc {
var found bool var found bool
scheme, token, found = strings.Cut(bearer, " ") scheme, token, found = strings.Cut(bearer, " ")
if !found || scheme != "Bearer" { if !found || scheme != "Bearer" {
http.Error(w, "invalid token", http.StatusBadRequest) pages.HTTPError(w, r, "invalid token", http.StatusBadRequest)
return return
} }
case http.MethodPost: case http.MethodPost:
@@ -406,33 +406,33 @@ func deleteHandler(db *gorm.DB, cfg Config) http.HandlerFunc {
upload, err := getUploadById(db.WithContext(r.Context()), id) upload, err := getUploadById(db.WithContext(r.Context()), id)
if err != nil { if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
http.NotFound(w, r) pages.HTTPError(w, r, "upload not found", 404)
return return
} }
log.Println("get upload:", err) log.Println("get upload:", err)
http.Error(w, "internal server error", http.StatusInternalServerError) pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
return return
} }
if token == "" || subtle.ConstantTimeCompare([]byte(upload.DeleteToken), []byte(token)) != 1 { if token == "" || subtle.ConstantTimeCompare([]byte(upload.DeleteToken), []byte(token)) != 1 {
http.Error(w, "invalid token", http.StatusBadRequest) pages.HTTPError(w, r, "invalid token", http.StatusBadRequest)
return return
} }
// continue to delete from database IF the file doesnt exist on disk // continue to delete from database IF the file doesnt exist on disk
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
log.Println("remove upload file:", err) log.Println("remove upload file:", err)
http.Error(w, "internal server error", http.StatusInternalServerError) pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
return return
} }
if err := db.WithContext(r.Context()).Delete(upload).Error; err != nil { if err := db.WithContext(r.Context()).Delete(upload).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
http.NotFound(w, r) pages.HTTPError(w, r, "upload not found", 404)
return return
} }
log.Println("remove upload file:", err) log.Println("remove upload file:", err)
http.Error(w, "internal server error", http.StatusInternalServerError) pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
return return
} }
@@ -448,7 +448,7 @@ func deleteHandler(db *gorm.DB, cfg Config) http.HandlerFunc {
func reportUploadHandler(db *gorm.DB, cfg Config, pages *Pages, cStore *ChallengeStore) http.HandlerFunc { func reportUploadHandler(db *gorm.DB, cfg Config, pages *Pages, cStore *ChallengeStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil { if err := r.ParseForm(); err != nil {
http.Error(w, "Invalid form data", http.StatusBadRequest) pages.HTTPError(w, r, "Invalid form data", http.StatusBadRequest)
return return
} }
@@ -485,7 +485,7 @@ func reportUploadHandler(db *gorm.DB, cfg Config, pages *Pages, cStore *Challeng
return return
} }
if err != nil && clientError { if err != nil && clientError {
http.Error(w, err.Error(), http.StatusBadRequest) pages.HTTPError(w, r, err.Error(), http.StatusBadRequest)
return return
} }
@@ -503,7 +503,7 @@ func reportUploadHandler(db *gorm.DB, cfg Config, pages *Pages, cStore *Challeng
} }
log.Println("failed to insert report:", err) log.Println("failed to insert report:", err)
http.Error(w, "internal server error", http.StatusInternalServerError) pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError)
return return
} }
+13
View File
@@ -152,3 +152,16 @@ func reportPageHandler(pages *Pages, store *ChallengeStore, cfg Config) http.Han
}) })
} }
} }
func (pages *Pages) HTTPError(w http.ResponseWriter, r *http.Request, message string, status int) {
if strings.Contains(r.Header.Get("Accept"), "text/html") {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
_ = pages.Templates.ExecuteTemplate(w, "result.html", map[string]any{
"Title": status,
"Message": message,
})
return
}
http.Error(w, message, status)
}
+2 -2
View File
@@ -26,8 +26,8 @@ goals:
- [ ] size based expiry - [ ] size based expiry
- exclusions if below a certain size (like 5mb) - exclusions if below a certain size (like 5mb)
- [x] delete content endpoints - [x] delete content endpoints
- [ ] return a page for nojs clients, such as on delete or upload - [x] return a page for nojs clients, such as on delete or upload
- need to return one on failures as well 💔💔💔 - [x] need to return one on failures as well 💔💔💔
- [ ] max total storage usage - [ ] max total storage usage
- [x] normalize mime types (like html) - [x] normalize mime types (like html)
- converts specific mime types to text/plain to prevent rendering - converts specific mime types to text/plain to prevent rendering
+4 -4
View File
@@ -23,13 +23,13 @@ func newRouter(db *gorm.DB, cfg Config, pages *Pages, tracker *AccessTracker, cS
mux.HandleFunc("GET /report", reportPageHandler(pages, cStore, cfg)) mux.HandleFunc("GET /report", reportPageHandler(pages, cStore, cfg))
mux.HandleFunc("POST /report", reportUploadHandler(db, cfg, pages, cStore)) mux.HandleFunc("POST /report", reportUploadHandler(db, cfg, pages, cStore))
uploads := http.NewServeMux() uploads := http.NewServeMux()
uploads.HandleFunc("GET /{id}", contentHandler(db, cfg, tracker)) uploads.HandleFunc("GET /{id}", contentHandler(db, cfg, tracker, pages))
uploads.HandleFunc("GET /{id}/info", contentInfoHandler(db, tracker)) uploads.HandleFunc("GET /{id}/info", contentInfoHandler(db, tracker, pages))
mux.Handle("/", uploads) mux.Handle("/", uploads)
mux.HandleFunc("POST /upload", uploadHandler(db, cfg, pages)) mux.HandleFunc("POST /upload", uploadHandler(db, cfg, pages))
mux.HandleFunc("PUT /upload", uploadHandler(db, cfg, pages)) mux.HandleFunc("PUT /upload", uploadHandler(db, cfg, pages))
mux.HandleFunc("DELETE /{id}", deleteHandler(db, cfg)) mux.HandleFunc("DELETE /{id}", deleteHandler(db, cfg, pages))
mux.HandleFunc("POST /{id}/delete", deleteHandler(db, cfg)) mux.HandleFunc("POST /{id}/delete", deleteHandler(db, cfg, pages))
mux.HandleFunc("GET /health", health) mux.HandleFunc("GET /health", health)
return mux return mux
} }
+1
View File
@@ -218,6 +218,7 @@ img,
video, video,
audio { audio {
max-width: 100%; max-width: 100%;
max-height: 80dvh;
} }
.upload-links { .upload-links {