Fix security issues, bugs, and convoluted code across the stack
Security: - Token revocation. User gains a TokenVersion counter embedded in both tokens as a "tv" claim; AuthenticateToken rejects a token whose version no longer matches the row. Logout bumps it, so logging out now kills outstanding tokens rather than only clearing cookies. Costs one primary-key SELECT per authenticated request, which is the price of having revocation at all. - Spotify OAuth CSRF. The fixed SPOTIFY_AUTH_STATE constant is replaced by a per-request one-shot nonce, verified and consumed on callback. - Private chat attachments. Attachments on private messages are written to /backend/uploads/private/ and served at /uploads/private/, gated by the same nginx auth_request admin check used for /hasura/ and /notes/. Private uploads are rejected from non-admin callers. - The icecast admin UI (/radio/admin/) is behind the admin gate; listener traffic is untouched. - Store caches are mutex-guarded, so -race is clean. Bugs: - The email pipeline no longer drops emails permanently on transient failure. Failures record an attempt counter and are retried up to 3 times; the fetch window rewinds to the oldest retryable email's ReceivedAt, without which a retry could never re-fetch it. - Rowing duplicate detection distinguishes ErrRecordNotFound from a real DB error, so a transient failure no longer causes a duplicate insert plus a paid Claude call. - DeletePost propagates its delete error instead of reporting success. - RecentlyPlayed populates the cache it reads. - main.go exits non-zero if r.Run fails, so a port conflict is visible. - Python: the scan truncation flag is set on every deadline path; timed_out is reported by the worker rather than inferred from the clock; date validation uses Europe/London rather than server-local time. - Vue: Time.vue and Radio.vue intervals are cleared on unmount; Feed.vue guards a missing author; Timer.vue gets an explicit state machine and compares total elapsed seconds; Elle.vue's comma-operator call and per-frame console.log are fixed. Simplification: - One TTLCache replaces three near-identical cache implementations, with the differing eviction rules as explicit parameters. - run_scan's transport index no longer uses one object as both ordering record and live output; its three phases are separate functions. - _price_hotels submits all work to a single pool, so the nested-executor deadlock hazard is gone by construction. - The NDJSON event generators share one implementation. - IMAP FETCH responses pair each line with its literal in the type, so callers no longer hand-skip alternate entries. - Shared helpers for slice-of-pointers, markdown fences and auth cookies. - Vue: useHotelSearch, createMirrorStore, useRotation, useCreateForm, useLinkAttrs, ListWidget and LinkTableItems replace duplicated blocks. - nginx dev config's duplicated :80/:443 bodies share one partial. Infra: certbot passes --deploy-hook touching a sentinel that nginx's watcher reloads on, so renewed certs are served without a restart, and the watcher also removes the manual restart after first issuance. db is gated on service_healthy, autoheal is pinned, and the unused envsubst entries are dropped. Verified: go build/vet, npx vite build, py_compile, docker compose config for both overlays, bash -n on all scripts, and an envsubst render of every nginx template (no leftover placeholders, runtime vars preserved, braces balanced). Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
@@ -10,11 +10,17 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// Attachment upload for the chat. Files land in a directory that nginx serves
|
||||
// directly at /uploads/, so anything written here is publicly reachable by
|
||||
// URL — which is why the extension and content checks below matter.
|
||||
// Attachment upload for the chat.
|
||||
//
|
||||
// Files land in one of two directories. /backend/uploads/ is served by nginx
|
||||
// at /uploads/ with no authentication, so anything written there is publicly
|
||||
// reachable by URL — which is why the extension and content checks below
|
||||
// matter. /backend/uploads/private/ holds attachments for private (admin-only)
|
||||
// messages and is served at /uploads/private/ behind an nginx auth_request
|
||||
// gate; only an admin may upload there.
|
||||
|
||||
// allowedExtensions is the upload allow-list, keyed by lower-cased extension.
|
||||
var allowedExtensions = map[string]bool{
|
||||
@@ -36,10 +42,28 @@ var extensionToMIMEPrefix = map[string]string{
|
||||
".pdf": "application/pdf", ".txt": "text/",
|
||||
}
|
||||
|
||||
// publicUploadDir and privateUploadDir are the two destinations; the private
|
||||
// one is created on demand because nothing else guarantees it exists.
|
||||
const (
|
||||
publicUploadDir = "/backend/uploads/"
|
||||
privateUploadDir = "/backend/uploads/private/"
|
||||
)
|
||||
|
||||
// UploadMessageFile backs POST /messages/upload (login required) and returns
|
||||
// the public URL of the stored file, which the client then sends over the
|
||||
// WebSocket as a message's fileUrl.
|
||||
// the URL of the stored file, which the client then sends over the WebSocket
|
||||
// as a message's fileUrl.
|
||||
//
|
||||
// The multipart form takes an optional "private" field: "true" stores the file
|
||||
// under /uploads/private/ for use as a private message's attachment. That is
|
||||
// admin-only, because private messages themselves are — an attachment URL
|
||||
// leaking out is the same disclosure as the message leaking out.
|
||||
func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
private := ctx.PostForm("private") == "true"
|
||||
if private && !requestIsAdmin(ctx) {
|
||||
ctx.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
||||
return
|
||||
}
|
||||
|
||||
file, err := ctx.FormFile("file")
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
|
||||
@@ -94,7 +118,18 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
}
|
||||
filename := hex.EncodeToString(b) + ext
|
||||
|
||||
uploadDir := "/backend/uploads/"
|
||||
uploadDir := publicUploadDir
|
||||
urlPrefix := "/uploads/"
|
||||
if private {
|
||||
uploadDir = privateUploadDir
|
||||
urlPrefix = "/uploads/private/"
|
||||
// 0755 so nginx (a different user) can traverse the directory to
|
||||
// serve the files once its auth_request gate has approved.
|
||||
if err := os.MkdirAll(uploadDir, 0755); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
|
||||
return
|
||||
}
|
||||
}
|
||||
dest := filepath.Join(uploadDir, filename)
|
||||
|
||||
// Reopened rather than rewound: the earlier handle was closed after
|
||||
@@ -119,5 +154,25 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"url": "/uploads/" + filename})
|
||||
ctx.JSON(http.StatusOK, gin.H{"url": urlPrefix + filename})
|
||||
}
|
||||
|
||||
// requestIsAdmin reports whether the caller's access token carries admin=true.
|
||||
//
|
||||
// This route sits in the `protected` group, which runs AuthMiddlewear but not
|
||||
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
|
||||
// public attachments — so the admin check is made here from the same
|
||||
// "userClaims" value AdminMiddleware would have read.
|
||||
func requestIsAdmin(ctx *gin.Context) bool {
|
||||
claims, exists := ctx.Get("userClaims")
|
||||
if !exists {
|
||||
return false
|
||||
}
|
||||
mapClaims, ok := claims.(*jwt.MapClaims)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
admin, ok := (*mapClaims)["admin"].(bool)
|
||||
|
||||
return ok && admin
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user