Files
m1saka 66abb76318 Fix audit findings: lock architecture, security, deployment hardening
Close all 14 findings from the codebase audit (1 high, 5 medium, 8 low):

- Locking: replace the global API and workspace mutexes with per-instance
  and per-user keyed locks (new internal/api/locks.go) so a slow restore,
  upgrade or transfer no longer blocks unrelated users or instances; move
  Docker I/O out of the build queue and invalidate concurrent image-index
  observations with a generation counter; serialize instance deletion
  behind in-flight creation.
- Security: equalize login timing for unknown usernames, periodically
  purge expired sessions/refresh tokens/lock rows, URL-encode orphan IDs
  in the frontend, upgrade vitest 3.x->5.x to clear 3 npm audit
  vulnerabilities (2 critical RCE).
- Deployment: add a -healthcheck mode probing /healthz (used by Dockerfile
  HEALTHCHECK and compose), make ADMIN_PASSWORD optional in compose with
  removal guidance after first start, exclude test scripts from the image,
  and cap panel resources (cpus: 2, pids_limit: 512).
- Reliability: check rows.Err() on admin listing loops, surface intent
  polling errors without sticking, disable close during in-flight create.

Verified: go build/vet, full go test -race -count=1 ./..., frontend
tsc build + 32 tests, npm audit 0, compose config, real-container
healthcheck.
2026-10-13 20:59:28 +08:00

64 lines
1.4 KiB
Go

package api
import (
"errors"
"git.misaka.ren/m1saka/dsh-web/internal/store"
"io/fs"
"os"
"strings"
)
// Call with the owner's user lock held through the write. Runtime writes remain soft-limited.
func (a *API) quotaGrowth(uid string, growth int64) error {
var u store.User
u.ID = uid
if err := a.s.DB.QueryRow("SELECT quota FROM users WHERE id=?", uid).Scan(&u.Quota); err != nil {
return err
}
used, err := a.userUsage(u)
if err != nil {
return err
}
if growth > 0 && (used > u.Quota || growth > u.Quota-used) {
return errors.New("quota exceeded")
}
return nil
}
func quotaTreeBytes(root *os.Root, name string) (int64, error) {
var total int64
entries := 0
err := fs.WalkDir(root.FS(), name, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
entries++
if entries > 100000 || strings.Count(p, "/") > 128 {
return errors.New("tree limit")
}
info, err := d.Info()
if err != nil {
return err
}
if info.Mode().IsRegular() {
if info.Size() > upgradeSnapshotLimit-total {
return errors.New("snapshot size limit")
}
total += info.Size()
}
return nil
})
return total, err
}
func (a *API) quotaSnapshot(uid string, root *os.Root, extra int64) (int64, error) {
size, err := quotaTreeBytes(root, "home")
if err != nil {
return 0, err
}
if err = a.quotaGrowth(uid, size+extra); err != nil {
return 0, err
}
return size, nil
}