max total storage usage implemented!

code may be a bit messy but....

also implemented a storage usage stat (that can be toggled in .env) that
shows on the home page, you can also enable the total limit to show as
well

eventually i need to implement clearing old unfinished uploads both on
startup, admin actions, and cleaning up on upload failure
This commit is contained in:
2026-12-05 16:24:57 -05:00
parent a1ebd905df
commit c5636c9160
8 changed files with 269 additions and 87 deletions
+42 -21
View File
@@ -2,7 +2,6 @@ package config
import (
"fmt"
"log"
"net/netip"
"os"
"slices"
@@ -16,12 +15,16 @@ type Config struct {
UploadDir string
MaxPasteBytes int64
MaxFileBytes int64
MaxStorageUsage int64
Expiries []Expiry
NormalizeMIMETypes bool
BannedMIMETypes []string
PoWDifficulty int
ReportOptions []string
DisplayStorageUsage bool
DisplayStorageLimit bool
DatabasePath string
// public host like "https://bin.zip", NOT the address minbin listens on
Host string
@@ -34,25 +37,21 @@ type Config struct {
func LoadConfig() (Config, error) {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
return Config{}, fmt.Errorf("failed to load .env: %w", err)
}
pasteSizeSetting := envOrDefault("MINIBIN_MAX_PASTE_KIB", "1024")
maxPasteKiB, err := strconv.ParseInt(pasteSizeSetting, 10, 64)
maxPasteKiB, err := envKibAsBytes("MINIBIN_MAX_PASTE_KIB", "1024", 1)
if err != nil {
return Config{}, fmt.Errorf("failed to parse MINIBIN_MAX_PASTE_KIB: %w", err)
}
if maxPasteKiB <= 0 {
return Config{}, fmt.Errorf("MINIBIN_MAX_PASTE_KIB must be greater than 0")
return Config{}, err
}
fileSizeSetting := envOrDefault("MINIBIN_MAX_FILE_KIB", "1024")
maxFileKiB, err := strconv.ParseInt(fileSizeSetting, 10, 64)
maxFileKiB, err := envKibAsBytes("MINIBIN_MAX_FILE_KIB", "1024", 1)
if err != nil {
return Config{}, fmt.Errorf("failed to parse MINIBIN_MAX_FILE_KIB: %w", err)
return Config{}, err
}
if maxFileKiB <= 0 {
return Config{}, fmt.Errorf("MINIBIN_MAX_FILE_KIB must be greater than 0")
maxStorageUsageKiB, err := envKibAsBytes("MINIBIN_MAX_STORAGE_USAGE_KIB", "0", 0)
if err != nil {
return Config{}, err
}
expiriesSetting := envOrDefault("MINIBIN_EXPIRIES", "1h,12h,1d,7d,2w,1mo,6mo,1y,5y,0")
@@ -72,9 +71,6 @@ func LoadConfig() (Config, error) {
}
reportOptionsSetting := envOrDefault("MINIBIN_REPORT_OPTIONS", "Malware (including links),CSAM/CSEM,Copyright Infringement,Fraud")
reportOptions := strings.Split(reportOptionsSetting, ",")
if len(reportOptions) == 0 {
return Config{}, fmt.Errorf("no valid report options set")
}
ipAddressSource := envOrDefault("MINIBIN_IP_ADDRESS_SOURCE", "remote")
if !slices.Contains([]string{"remote", "cloudflare", "xff"}, ipAddressSource) {
return Config{}, fmt.Errorf("%s is not a valid MINIBIN_IP_ADDRESS_SOURCE option", ipAddressSource)
@@ -105,23 +101,32 @@ func LoadConfig() (Config, error) {
}
}
return Config{
config := Config{
UploadDir: envOrDefault("MINIBIN_UPLOAD_DIR", "uploads"),
MaxPasteBytes: maxPasteKiB * 1024,
MaxFileBytes: maxFileKiB * 1024,
MaxPasteBytes: maxPasteKiB,
MaxFileBytes: maxFileKiB,
MaxStorageUsage: maxStorageUsageKiB,
Expiries: expiries,
NormalizeMIMETypes: envOrDefault("MINIBIN_NORMALIZE_MIME_TYPES", "true") == "true",
NormalizeMIMETypes: envAsBool("MINIBIN_NORMALIZE_MIME_TYPES", "true"),
BannedMIMETypes: strings.Split(envOrDefault("MINIBIN_BANNED_MIME_TYPES", ""), ","),
PoWDifficulty: powDifficulty,
ReportOptions: reportOptions,
DisplayStorageUsage: envAsBool("MINIBIN_STATS_DISPLAY_STORAGE_USAGE", "false"),
DisplayStorageLimit: envAsBool("MINIBIN_STATS_DISPLAY_STORAGE_LIMIT", "false"),
DatabasePath: envOrDefault("MINIBIN_DATABASE_PATH", "minibin.sqlite"),
Host: envOrDefault("MINIBIN_HOST", "http://localhost:8080"),
Addr: envOrDefault("MINIBIN_ADDR", "localhost:8080"),
IPAdressSource: ipAddressSource,
TrustedProxies: trustedProxies,
BannedClientASNs: bannedAsns,
}, nil
}
if !config.DisplayStorageUsage && config.DisplayStorageLimit {
return Config{}, fmt.Errorf("MINIBIN_STATS_DISPLAY_STORAGE_LIMIT must be enabled when MINIBIN_STATS_DISPLAY_STORAGE_USAGE is enabled")
}
return config, nil
}
func envOrDefault(key, fallback string) string {
@@ -131,3 +136,19 @@ func envOrDefault(key, fallback string) string {
}
return value
}
func envKibAsBytes(key, fallback string, minKiB int64) (int64, error) {
setting := envOrDefault(key, fallback)
value, err := strconv.ParseInt(setting, 10, 64)
if err != nil {
return 0, fmt.Errorf("parse %s: %w", key, err)
}
if value < minKiB {
return 0, fmt.Errorf("%s cannot be less than %v", key, minKiB)
}
return value * 1024, nil
}
func envAsBool(key, fallback string) bool {
return strings.ToLower(envOrDefault(key, fallback)) == "true"
}
+89 -5
View File
@@ -15,17 +15,26 @@ const (
ContentPaste
)
type UploadState uint8
const (
Complete UploadState = iota
Pending
Deleting
)
type Upload struct {
ID string `gorm:"column:id;primaryKey" json:"id"`
Type ContentType `gorm:"column:type;not null;default:0;type:integer" json:"type"`
Filename string `gorm:"column:filename;not null" json:"-"`
MIMEType string `gorm:"column:mime_type;not null" json:"mime_type"`
Size int64 `gorm:"column:size;not null" json:"size"`
SHA256 []byte `gorm:"column:sha256;type:blob;notnull;index" json:"-"`
SHA256 []byte `gorm:"column:sha256;type:blob;index" json:"-"`
CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime" json:"created_at"`
ExpiresAt *int64 `gorm:"column:expires_at;index" json:"expires_at"` // null means no expiration
LastAccessedAt int64 `gorm:"column:last_accessed_at;not null;autoCreateTime;index" json:"last_accessed_at"`
DeleteToken string `gorm:"column:delete_token;not null" json:"-"`
State UploadState `gorm:"column:state;not null;default:0;type:integer;index" json:"-"`
}
type Report struct {
@@ -36,6 +45,13 @@ type Report struct {
CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime"`
}
type Stat struct {
Key string `gorm:"column:key;primaryKey"`
Value int64 `gorm:"column:value"`
}
var ErrStorageQuotaExceeded = errors.New("storage quota exceeded")
func InitDatabase(path string) (*gorm.DB, error) {
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{TranslateError: true})
if err != nil {
@@ -60,7 +76,7 @@ func InitDatabase(path string) (*gorm.DB, error) {
return nil, fmt.Errorf("set synchronous normal: %w", err)
}
if err := db.AutoMigrate(&Upload{}, &Report{}); err != nil {
if err := db.AutoMigrate(&Upload{}, &Report{}, &Stat{}); err != nil {
migrationErr := fmt.Errorf("migrate database: %w", err)
return nil, errors.Join(migrationErr, sqlDB.Close())
}
@@ -68,8 +84,44 @@ func InitDatabase(path string) (*gorm.DB, error) {
return db, nil
}
func InsertUpload(db *gorm.DB, upload *Upload) error {
return db.Create(upload).Error
func ReserveUpload(db *gorm.DB, upload *Upload, maxStorageUsage int64) (int64, error) {
var usedBytes int64
err := db.Transaction(func(tx *gorm.DB) error {
query := tx.Model(&Stat{}).Where(`"Key" = ?`, "quota_usage")
if maxStorageUsage > 0 {
query = query.Where("value <= ?", maxStorageUsage-upload.Size)
}
result := query.UpdateColumn("value", gorm.Expr("value + ?", upload.Size))
if result.Error != nil {
return result.Error
}
var stat Stat
if err := tx.Where(`"key" =?`, "quota_usage").Take(&stat).Error; err != nil {
return fmt.Errorf("read quota usage: %w", err)
}
usedBytes = stat.Value
if result.RowsAffected == 0 {
return fmt.Errorf("reserve upload: %w", ErrStorageQuotaExceeded)
}
upload.State = Pending
return tx.Create(upload).Error
})
if err != nil && !errors.Is(err, ErrStorageQuotaExceeded) {
return 0, err
}
return usedBytes, err
}
func CompleteUpload(db *gorm.DB, upload *Upload) error {
if upload.SHA256 == nil {
return fmt.Errorf("sha256 hash required")
}
return db.Model(&Upload{}).Where("id = ? AND state = ?", upload.ID, Pending).
Updates(map[string]any{
"sha256": upload.SHA256,
"state": Complete,
}).Error
}
func InsertReport(db *gorm.DB, report *Report) error {
@@ -78,8 +130,40 @@ func InsertReport(db *gorm.DB, report *Report) error {
func GetUploadById(db *gorm.DB, id string) (*Upload, error) {
var upload Upload
if err := db.First(&upload, "id = ?", id).Error; err != nil {
// will only find uploads whose upload state is complete
if err := db.First(&upload, "id = ? AND state = ?", id, Complete).Error; err != nil {
return nil, err
}
return &upload, nil
}
func EnsureQuotaUsage(db *gorm.DB) error {
var stat Stat
result := db.Where(`"key" = ?`, "quota_usage").Limit(1).Find(&stat)
if result.Error != nil {
return result.Error
} else if result.RowsAffected == 0 {
return rebuildQuotaUsage(db)
}
return nil
}
func GetQuotaUsage(db *gorm.DB) (int64, error) {
var stat Stat
if err := db.First(&stat, `"key" = ?`, "quota_usage").Error; err != nil {
return 0, err
}
return stat.Value, nil
}
func rebuildQuotaUsage(db *gorm.DB) error {
return db.Transaction(func(tx *gorm.DB) error {
var total int64
if err := tx.Model(&Upload{}).Select("COALESCE(SUM(size),0)").Scan(&total).Error; err != nil {
return err
}
return tx.Exec(`
INSERT INTO stats ("key", value) values (?,?)
ON CONFLICT ("key") DO UPDATE SET value = excluded.value`, "quota_usage", total).Error
})
}
+19 -19
View File
@@ -11,6 +11,7 @@ import (
"os"
"path/filepath"
"strings"
"sync/atomic"
"git.whoswhip.dev/whoswhip/minibin/internal/config"
"github.com/dustin/go-humanize"
@@ -20,16 +21,7 @@ type Pages struct {
Templates *template.Template
Qts []string
Placeholders []string
}
type HomePageData struct {
Expiries []config.Expiry
Qt string
PastePlaceholder string
FileMaxSize string
FileMaxSizeBytes int64
PasteMaxSize string
PasteMaxSizeBytes int64
QuotaUsage *atomic.Int64
}
func (pages *Pages) Render(w http.ResponseWriter, name string, data any) {
@@ -68,7 +60,7 @@ func GetRandomQt(qts []string) string {
return ""
}
func LoadPages() (*Pages, error) {
func LoadPages(usage *atomic.Int64) (*Pages, error) {
templates, err := template.New("").Funcs(template.FuncMap{
"hasPrefix": strings.HasPrefix,
}).ParseGlob("web/templates/*.html")
@@ -79,6 +71,7 @@ func LoadPages() (*Pages, error) {
pages := &Pages{
Templates: templates,
Placeholders: []string{"cmon, paste something already!"},
QuotaUsage: usage,
}
qtFiles, err := os.ReadDir("qts")
@@ -110,17 +103,24 @@ func LoadPages() (*Pages, error) {
func HomeHandler(pages *Pages, cfg config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
data := HomePageData{
Expiries: cfg.Expiries,
FileMaxSize: humanize.Bytes(uint64(cfg.MaxFileBytes)),
FileMaxSizeBytes: cfg.MaxFileBytes,
PasteMaxSize: humanize.Bytes(uint64(cfg.MaxPasteBytes)),
PasteMaxSizeBytes: cfg.MaxPasteBytes,
Qt: GetRandomQt(pages.Qts),
data := map[string]any{
"Expiries": cfg.Expiries,
"FileMaxSize": humanize.Bytes(uint64(cfg.MaxFileBytes)),
"FileMaxSizeBytes": cfg.MaxFileBytes,
"PasteMaxSize": humanize.Bytes(uint64(cfg.MaxPasteBytes)),
"PasteMaxSizeBytes": cfg.MaxPasteBytes,
"Qt": GetRandomQt(pages.Qts),
}
if len(pages.Placeholders) > 0 {
data.PastePlaceholder = pages.Placeholders[rand.IntN(len(pages.Placeholders))]
data["PastePlaceholder"] = pages.Placeholders[rand.IntN(len(pages.Placeholders))]
}
if cfg.DisplayStorageLimit {
data["StorageLimit"] = humanize.Bytes(uint64(cfg.MaxStorageUsage))
}
if cfg.DisplayStorageUsage {
data["StorageUsage"] = humanize.Bytes(uint64(pages.QuotaUsage.Load()))
}
pages.Render(w, "home.html", data)
+59 -36
View File
@@ -15,6 +15,7 @@ import (
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
"unicode/utf8"
@@ -31,6 +32,7 @@ type UploadInput struct {
Filename string
MIMEType string
Type database.ContentType
Size int64
}
type UploadResponse struct {
database.Upload
@@ -109,6 +111,7 @@ func UploadHandler(db *gorm.DB, cfg config.Config, p *pages.Pages) http.HandlerF
input.Reader = file
input.Filename = header.Filename
input.Type = database.ContentFile
input.Size = header.Size
case "text/plain", "application/x-www-form-urlencoded": // paste uploads
r.Body = http.MaxBytesReader(w, r.Body, cfg.MaxPasteBytes)
var content string
@@ -145,6 +148,7 @@ func UploadHandler(db *gorm.DB, cfg config.Config, p *pages.Pages) http.HandlerF
Filename: "paste.txt",
MIMEType: "text/plain; charset=utf-8",
Type: database.ContentPaste,
Size: int64(len(content)),
}
default:
p.HTTPError(w, r, "unsupported Content-Type", http.StatusUnsupportedMediaType)
@@ -181,39 +185,6 @@ func UploadHandler(db *gorm.DB, cfg config.Config, p *pages.Pages) http.HandlerF
return
}
dest, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
log.Println("create file:", err)
p.HTTPError(w, r, "faield to save upload", http.StatusInternalServerError)
return
}
saved := false
defer func() {
dest.Close()
if !saved {
if err := os.Remove(path); err != nil {
log.Printf("remove incomplete upload %s: %v", id, err)
}
}
}()
hasher := sha256.New()
size, err := io.Copy(io.MultiWriter(dest, hasher), input.Reader)
if err != nil {
if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
p.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge)
return
}
log.Println("write file:", err)
p.HTTPError(w, r, "faield to write upload", http.StatusInternalServerError)
return
}
if err := dest.Close(); err != nil {
log.Println("close file:", err)
p.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError)
return
}
createdAt := time.Now().UTC().Unix()
expires, err := selected.ExpiresFrom(time.Now().UTC())
if err != nil {
@@ -243,14 +214,59 @@ func UploadHandler(db *gorm.DB, cfg config.Config, p *pages.Pages) http.HandlerF
Type: input.Type,
Filename: input.Filename,
MIMEType: input.MIMEType,
Size: size,
SHA256: hasher.Sum(nil),
Size: input.Size,
CreatedAt: createdAt,
ExpiresAt: expiresAt,
LastAccessedAt: createdAt,
DeleteToken: rand.Text(),
}
err = database.InsertUpload(db, &upload)
usedBytes, err := database.ReserveUpload(db, &upload, cfg.MaxStorageUsage)
if err != nil {
if errors.Is(err, database.ErrStorageQuotaExceeded) {
p.HTTPError(w, r, "storage capacity reached", http.StatusInsufficientStorage)
return
}
log.Println("reserve upload:", err)
p.HTTPError(w, r, "failed to reserve upload", http.StatusInternalServerError)
return
}
dest, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
log.Println("create file:", err)
p.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError)
return
}
saved := false
defer func() {
dest.Close()
if !saved {
if err := os.Remove(path); err != nil {
log.Printf("remove incomplete upload %s: %v", id, err)
}
}
}()
hasher := sha256.New()
_, err = io.Copy(io.MultiWriter(dest, hasher), input.Reader)
if err != nil {
if _, ok := errors.AsType[*http.MaxBytesError](err); ok {
p.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge)
return
}
log.Println("write file:", err)
p.HTTPError(w, r, "faield to write upload", http.StatusInternalServerError)
return
}
if err := dest.Close(); err != nil {
log.Println("close file:", err)
p.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError)
return
}
upload.SHA256 = hasher.Sum(nil)
err = database.CompleteUpload(db, &upload)
if err != nil {
log.Println("save upload:", err)
p.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError)
@@ -266,6 +282,13 @@ func UploadHandler(db *gorm.DB, cfg config.Config, p *pages.Pages) http.HandlerF
Qt: pages.GetRandomQt(p.Qts),
}
if cfg.DisplayStorageUsage {
w.Header().Set("X-Storage-Usage", strconv.FormatInt(usedBytes, 10))
}
if cfg.DisplayStorageLimit {
w.Header().Set("X-Storage-Limit", strconv.FormatInt(cfg.MaxStorageUsage, 10))
}
switch returnType {
// html & maybe xml? cant think of other return types
case "html":