mirror of
https://github.com/J3vb/OwnCord.git
synced 2026-09-03 03:50:00 +03:00
* refactor(ws): split handleVoiceJoin into cohesive join-stage helpers handleVoiceJoin was 130 statements / cyclomatic 59 / nestif 11, breaking all three complexity budgets at once. Split along the stage boundaries the doc comment already described: precheck, leave-current, persist, restore moderator flags, grant token, complete. The publish-permission derivation becomes its own helper because it is the one branch-heavy block inside the token grant. Pure move: every statement is preserved verbatim. The only edits are bare `return`s becoming the typed returns of their new helper, `c.userID` becoming the `userID` parameter inside voiceJoinPublishPerms, and voiceJoinComplete re-reading `ch.VoiceMaxUsers` instead of receiving it — `ch` is never mutated, so the value is identical. Verified by normalising both revisions of the region to sorted, comment- and whitespace-stripped statements and diffing: the only deltas are the ones listed above. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor: collapse the three duplicated sibling pairs dupl flagged three pairs of adjacent near-identical functions. Each pair is now one parameterised implementation plus two thin, still-greppable wrappers. - ws/voice_controls.go: handleVoiceMuteV2 / handleVoiceDeafenV2 share voiceSelfToggleV2; handleVoiceCameraV2 / handleVoiceScreenshareV2 share voiceStreamToggleV2. Camera and screenshare drawing from one voice_max_video budget (OC-0023) was a bug caused by exactly this duplication drifting, so one body is the point, not a side effect. - db/mention_queries.go: ListMentionTargetsByRoles / ListMentionTargetsByUserIDs share listMentionTargets. The matched column is a closed named type (mentionTargetColumn) rather than a bare string, so the value interpolated into the SELECT cannot become caller-supplied. Behaviour is unchanged: every rate-limit key, error code, error string, slog message and slog key is preserved verbatim, including the two "failed to update <kind> state" messages, which are now assembled the same way enableVideoSlot already assembled them. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor(api): extract readEmojiUpload from handleCreateEmoji handleCreateEmoji was 101 lines against a 100-line budget. The upload-bytes stage — pull the file out of the parsed form, cap its size, sniff its MIME type and sniff its dimensions — is the one self-contained block in it, and it already wrote its own refusals, so it moves out whole as readEmojiUpload. The permission-before-parse ordering the doc comment calls out is unchanged; so is every error string. file.Close() now runs when the helper returns rather than when the handler does, which is strictly earlier and unobservable: the bytes are already copied into raw and nothing else touches the handle. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor: extract one cohesive block from three single-budget offenders Each of these was over exactly one budget, so each gets exactly one extraction rather than a restructure: - api/totp_handler.go handleVerifyTOTP (102 lines / 100): the block that resolves the user behind the partial-auth challenge and decrypts their TOTP secret becomes totpChallengeSecret. The ban-inside-the-partial-window check moves with it. - service/message_reactions.go handleReaction (cyclop 21 / 20): the whole authorisation chain — channel lookup, archived gate, DM participant and block checks, non-DM permission check — becomes reactionAudience, which also returns the DM fan-out audience it already resolved. Check order is unchanged and load-bearing. - db/admin_queries.go BackupToSafe (cyclop 21 / 20): the character allowlist loop and the SQL-comment rejection become validateBackupPathChars. That loop alone was most of the branch count. No error string, no check and no ordering changed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor(plugin): split InstallFromZip into staged install helpers 104 statements / cyclomatic 44 / nestif 12. Split along the stages the code already had: installZipExtract (the per-entry write loop, with installZipEntryDest holding the mode/symlink/zip-slip guard chain and installZipWriteEntry the size-capped copy), installZipStagedManifest, installZipPromote, and installZipReactivate for the :399 nested block. Every zip-slip, symlink, entry-mode and uncompressed-size check is preserved in the same order relative to the writes it guards. The 19 inline `cleanup(); return` sites collapse to 4 in the orchestrator, one per stage, because each helper now returns an error instead of unwinding itself — the staging directory is still removed on exactly the same set of failures. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor(api): split newWAFMiddleware into engine build and per-phase helpers 184 lines / cyclomatic 38, and the request-body block at :382 was the worst nested site in the tree at nestif 17. Engine construction moves out of the closure (wafInlineEngine, wafCRSEngine — the Coraza directive string is lifted verbatim), and each request phase becomes its own helper: wafInlineRequestHeaders, wafCRSRequestHeaders (including the Host/Transfer-Encoding re-add for CRS 920280), wafFeedCRSBody and wafInspectRequestBody, which is the old :382 block. The three `handleWAFInterruption(w, it); return` sites inside the body block become one: the helper now returns the interruption and the orchestrator handles it. No statement runs between the two points on either side, so the verdict is honoured identically — in particular a CRS body interruption still returns without replacing r.Body. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor(service): split SendMessage and lift EditMessage's access check SendMessage was 79 statements / cyclomatic 35 with an 11-deep nested attachment block at :101; EditMessage was one point over cyclop. SendMessage becomes sendMessagePrecheck (permission and DM-block gates, content sanitisation), sendMessageLinkAttachments (the :101 block: attachment ownership, claim and link) and sendMessageDMSideEffects. EditMessage gets editMessageCheckAccess and nothing else — one budget over earns one extraction. The sanitizeContent fixpoint and the attachment ownership check are unchanged, as is the order of every gate. The DM side effects run behind `isDM && !s.sendMessageDMSideEffects(...)`, so a non-DM never enters them; inside, only the GetDMParticipantIDs failure returns false, matching the one error the original early-returned on. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor(admin): split handlePatchUser into per-field apply helpers 106 lines / cyclomatic 29, with the ban block at :154 nested 9 deep. Each optional field of the partial edit becomes its own helper — patchUserPrecheck, patchUserAuthorizeRole, patchUserApplyBan (the :154 block, including the session disconnect and the broadcast) and patchUserApplyRole. Each returns a bool meaning "keep going"; none of them writes a success response, so the single response site in the orchestrator is unchanged. Field application order, the permission-cache invalidation on a role change and the disconnect-and-broadcast on a ban are all preserved, as are the three fail-closed `mod == nil` guards, which now sit at the top of their own helper and still fire on exactly the same conditions. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor(admin): split handleSetup into first-run setup stages 143 lines / cyclomatic 30, with the optional-wizard block at :219 sitting exactly on the nestif threshold. Split into the stages the endpoint already had: request gating (rate limit and origin check, which run before any auth exists on a fresh server), owner account creation, and the wizard application that was the :219 block. Every gate in front of the handler is a security control on an unauthenticated endpoint; none moved relative to the work it protects. setup_wizard.go is untouched. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor: split run() into named bootstrap and shutdown steps 131 statements / cyclomatic 57, with the executable-path fallback at :126 nested 9 deep. The five anonymous `defer func(){...}()` blocks become named functions — telemetryStop, runClosePlugins, runStopEventPersistence, runStopAuditWriter, maintenanceStop — and the bootstrap stages move out likewise. Every defer is still registered in run() itself, at the same point in the sequence, so the LIFO teardown order is unchanged; that order is documented in the surrounding comments and is load-bearing (the audit-writer stop must follow database.Close's registration, the event-persistence stop must precede it). runStopEventPersistence is now registered unconditionally with a nil persister meaning "disabled", where the old code registered its defer inside the enabled branch — a no-op occupying that slot cannot change the relative order of the others. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor(ws): split handleReconnect into resume stages 77 statements / cyclomatic 41, plus the replay block at :199 and, in handleFreshConnect, the voice-state restore at :622. handleReconnect becomes reconnectPrecheck, reconnectSelectReplay (with reconnectVetColdTail for the cold-tier gap check), reconnectRegister and reconnectWriteReplay. handleFreshConnect's stale-voice cleanup moves to its own helper, where the `if h.livekit != nil` wrapper becomes a guard clause — that block was the tail of its scope, so returning early and falling off the end are the same. The parts that carry the invariants are moved verbatim: reconnectRegister still takes h.seqMu, still calls registerNow inside that same critical section (BUG-123 / OC-0206), still unlocks on every exit, and still emits the "full" tier counter and telemetry on each of its three re-check failures. handleReconnect's two-boolean contract is unchanged — the collapsed `return false, false` sites are all fall-through-to-full-ready, and the single `return true, false` is still the handshake-write-failure path whose teardown already ran (OC-0051). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * docs(server): fold in the adversarial review of the complexity refactors Eleven skeptic passes over the refactor commits on this branch found no blocker and no major — behaviour is preserved throughout. They did find comment and accuracy defects worth correcting: - db/mention_queries.go: the mentionTargetColumn rationale claimed the named type made the interpolated column "only ever one of the two constants". A Go named type is not closed, so that is a convention the type makes visible, not one it enforces. Reworded, gosec justification included. - ws/voice_controls.go: the dupl collapse generalised away three specifics — that a server deafen is the moderator's to lift (now on the serverDeafen field), the concrete voice_states.camera / voice_states.screenshare column names, and the half of the OC-0023 rationale about neither stream kind hiding from the other's count. All three restored. - ws/voice_join.go: `maxUsers := ch.VoiceMaxUsers` had been hoisted to the top of voiceJoinComplete, moving a read across the tail supersession guard. The read is inert, but it was the one statement in that commit whose position relative to a security guard changed; it now sits at its use, as before. - ws/*_test.go: three test comments cited voice_join.go line numbers that the split invalidated. They now cite the helper by name instead. - service/message_reactions.go: reactionAudience's doc claimed to enforce "every gate on reacting"; it enforces the channel-scoped ones, and the doc now says which gates stay with the caller. - api/emoji_handler.go: the readEmojiUpload call reused the outer `ok` from the auth check by assignment; it gets its own readOK. - admin/setup_handler.go: a moved comment kept a "the response above" deictic that no longer had a response above it. No behaviour change. Build, vet, full tests and -race on five packages green. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor(ws): clear the remaining complexity budgets across the hub Eight files, thirteen findings. Each function is split at the stages it already had; no branch is reordered, merged or inverted. - handlers.go handleMessage (cyclop 28, 88 stmts): session re-check, frame decode and result application become handleMessageSessionRecheck, handleMessageDecode and handleMessageApply. The V2 constructor lookup -> DispatchV2 -> Result resolution order is untouched. - serve_ready.go buildReady (cyclop 26, 61 stmts): the per-section fetches split out, readyChannelPayloads among them. Every visibility predicate is preserved verbatim — this is the payload that decides what a client may see. - serve_pumps.go writePump (cyclop 31): writePumpWrite, writePumpDeliver, writePumpDrainChannel and writePumpDrainAndClose. Every channel receive stays in the same select statement, so scheduling is unchanged. - hub_sweep.go sweepStaleVoiceStates (cyclop 22, 56 stmts): the staleness predicate, the hub-lock ordering and the position of the race hook are all as they were — handleVoiceJoin's BUG-088 ordering depends on them. - hub_broadcast.go channelReadAudienceImpl and RefreshChannelVisibility (cyclop 22 each, 57 stmts): channelReadAudienceDM and refreshChannelVisibilityCanSend. The audience predicate is the OC-0090 group-DM leak surface, so it is extracted, never simplified. - livekit_webhook.go (nestif 13 and 14): webhookJoinedEnforceVoiceState, webhookLeftCleanupClient and webhookLeftFinishLeave. DB delete still precedes broadcast on every path. - livekit_download.go EnsureLiveKitBinary (52 stmts): one extraction, ensureLiveKitStageBinary, keeping every archive path check intact. - voice_moderation.go (nestif 8): voiceModDeafenRollback. The persisted server_muted flag remains the authority. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor(api): clear the remaining complexity budgets across the HTTP layer - router.go NewRouter (cyclop 28, 84 stmts): split by wiring concern into routerTOTPKey, routerHealthDeps, routerMiddleware, routerUploadRoutes, routerPluginWiring, routerVoiceRoutes and routerMetricsRoutes. Middleware ORDER is a security property (auth before handler, WAF before body parse, rate limit before work) and is unchanged; the returned cleanup func still closes over and releases everything it did before. - auth_handler.go handleRegister (133 lines) and handleLogin (cyclop 21, 152 lines): registerPolicyGate, registerReadRequest, loginReadRequest and loginAuthenticate. The always-compare posture, every rate-limit key, every counter reset and the ban-check-versus-password-compare order are all preserved — including loginUserFailureThreshold staying unscaled by scaledAuthLimit, which is deliberate and commented. - upload_handler.go handleServeFile (cyclop 31, 128 lines): serveFileResolve and serveFileAuthorize. Every header this sets — Content-Disposition included, which is what stops a stored file being served as active content — is still set with the same value in the same circumstances. - profile_handler.go handleUploadAvatar (120 lines): avatarUploadReadImage, mirroring readEmojiUpload in shape but with the avatar caps and MIME set. The two deliberately do not share a helper. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor: clear the last complexity budgets in db and admin - db/account.go DeleteAccount (cyclop 28, 55 stmts): grouped by subsystem into deleteAccountAdminGuard, deleteAccountDMChannels and deleteAccountCloseDMChannels, each taking the same transaction. The transaction boundary, the delete ORDER (which foreign keys depend on) and the rollback path are unchanged. - admin/logstream.go handleLogStream (cyclop 24): logStreamAuthorize. Flush cadence, heartbeat and disconnect detection untouched. - admin/setup_wizard.go validateWizard (cyclop 23): grouped by section into wizardValidateIdentity, wizardValidateNetwork and wizardValidateMedia. Every message and bound is unchanged — this is the first input-validation boundary on a fresh server, before any auth exists. With this the tree is at zero: golangci-lint run reports 0 issues against the budgets set in #1384 (funlen 100/50, cyclop 20, nestif 8, dupl 150), with no //nolint and no exclusion added anywhere. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
475 lines
17 KiB
Go
475 lines
17 KiB
Go
package api
|
||
|
||
import (
|
||
"database/sql"
|
||
"errors"
|
||
"image"
|
||
_ "image/gif"
|
||
_ "image/jpeg"
|
||
_ "image/png"
|
||
"io"
|
||
"log/slog"
|
||
"mime"
|
||
"net/http"
|
||
"path/filepath"
|
||
"strings"
|
||
"time"
|
||
"unicode"
|
||
"unicode/utf8"
|
||
|
||
"github.com/go-chi/chi/v5"
|
||
"github.com/google/uuid"
|
||
"github.com/owncord/server/auth"
|
||
"github.com/owncord/server/db"
|
||
"github.com/owncord/server/permissions"
|
||
"github.com/owncord/server/service"
|
||
"github.com/owncord/server/storage"
|
||
)
|
||
|
||
// uploadResponse is the JSON shape returned by POST /api/v1/uploads.
|
||
type uploadResponse struct {
|
||
ID string `json:"id"`
|
||
Filename string `json:"filename"`
|
||
Size int64 `json:"size"`
|
||
Mime string `json:"mime"`
|
||
URL string `json:"url"`
|
||
Width *int `json:"width,omitempty"`
|
||
Height *int `json:"height,omitempty"`
|
||
}
|
||
|
||
// sanitizeUploadFilename cleans an upload filename: strips control and
|
||
// invisible formatting characters, removes path separators, and truncates to a
|
||
// safe length.
|
||
func sanitizeUploadFilename(name string) string {
|
||
// Strip path components — use only the base name.
|
||
name = filepath.Base(name)
|
||
// filepath.Base only understands the *server* OS's separator, so a
|
||
// backslash survives on a Linux server and is then a path separator on the
|
||
// victim's Windows client, where the name is pre-filled into a save dialog.
|
||
if i := strings.LastIndexByte(name, '\\'); i >= 0 {
|
||
name = name[i+1:]
|
||
}
|
||
// Remove control characters, invisible formatting characters, and any
|
||
// residual forward slash.
|
||
var sb strings.Builder
|
||
for _, r := range name {
|
||
// unicode.Cf covers the bidi overrides (U+202A–U+202E, U+2066–U+2069):
|
||
// invisible characters that reorder how the name renders, so an
|
||
// attachment can display a harmless-looking extension to every other
|
||
// member of the channel while really being an executable script — and
|
||
// the same string is what the native save dialog pre-fills. This is the
|
||
// rule auth.ValidateUsername already applies to usernames.
|
||
//
|
||
// A forward slash is dropped too: filepath.Base("/") returns "/" (root
|
||
// is its own basename), so an upload literally named "/" would otherwise
|
||
// slip through the reserved-name check below with a path separator
|
||
// intact. Any residual '/' is unsafe as a basename, so strip it here.
|
||
if unicode.IsControl(r) || unicode.In(r, unicode.Cf) || r == '/' {
|
||
continue
|
||
}
|
||
sb.WriteRune(r)
|
||
}
|
||
name = strings.TrimSpace(sb.String())
|
||
// Truncate to the filesystem limit. Slicing by byte offset can land in the
|
||
// middle of a multibyte rune, so trim back to the last full rune to keep the
|
||
// result valid UTF-8 (an invalid name misbehaves in JSON encoding, on disk,
|
||
// and in the client's download-name handling).
|
||
if len(name) > maxUploadFilenameLength {
|
||
name = name[:maxUploadFilenameLength]
|
||
for len(name) > 0 && !utf8.ValidString(name) {
|
||
name = name[:len(name)-1]
|
||
}
|
||
}
|
||
if name == "" || name == "." || name == ".." {
|
||
name = "unnamed"
|
||
}
|
||
return name
|
||
}
|
||
|
||
// isUnsafeInlineMIME returns true for MIME types that could execute active
|
||
// content (scripts, markup) if served inline under the OwnCord origin.
|
||
func isUnsafeInlineMIME(mimeType string) bool {
|
||
// Normalize: take the base type before any parameters (e.g. "text/html; charset=utf-8").
|
||
base := strings.SplitN(mimeType, ";", 2)[0]
|
||
base = strings.TrimSpace(strings.ToLower(base))
|
||
switch base {
|
||
case "text/html", "application/xhtml+xml",
|
||
"image/svg+xml", "text/xml", "application/xml",
|
||
"application/pdf",
|
||
"text/xsl", "text/xslt":
|
||
return true
|
||
}
|
||
return false
|
||
}
|
||
|
||
// safeStorageErrorMessage maps a storage.Save error to a client-safe
|
||
// "upload rejected" body. Full detail always goes to slog.Warn at the call
|
||
// site — this only decides what crosses the HTTP boundary. storage.Save's
|
||
// failure messages are built with fmt.Errorf("... %s", dst) / %w around
|
||
// path-bearing OS errors (creating the file, syncing it, or the destination
|
||
// resolving outside the storage dir), so echoing them verbatim hands any
|
||
// authenticated user the server's absolute storage layout the moment a save
|
||
// fails (disk full, permission change, read-only mount). The two validation
|
||
// failures below are the only ones that never embed a path, so they're the
|
||
// only ones whose detail is forwarded.
|
||
func safeStorageErrorMessage(err error) string {
|
||
msg := err.Error()
|
||
switch {
|
||
case strings.HasPrefix(msg, "blocked file type:"),
|
||
strings.HasPrefix(msg, "file exceeds maximum size"):
|
||
return "upload rejected: " + msg
|
||
default:
|
||
return "upload rejected"
|
||
}
|
||
}
|
||
|
||
// writeStorageSaveError maps a storage.Save failure onto the right HTTP
|
||
// class: server-side filesystem failures (storage.ErrIO — disk full,
|
||
// permissions, read-only mount) become 507 so they are distinguishable from
|
||
// bad uploads in any status dashboard; everything else stays the client's
|
||
// 400. Detail never crosses the HTTP boundary either way (path leakage —
|
||
// see safeStorageErrorMessage).
|
||
func writeStorageSaveError(w http.ResponseWriter, saveErr error, what string) {
|
||
if errors.Is(saveErr, storage.ErrIO) {
|
||
slog.Error(what+" failed: server storage error", "error", saveErr)
|
||
writeJSON(w, http.StatusInsufficientStorage, errorResponse{
|
||
Error: "STORAGE_ERROR",
|
||
Message: "upload failed: server storage error",
|
||
})
|
||
return
|
||
}
|
||
slog.Warn(what+" rejected", "error", saveErr)
|
||
writeJSON(w, http.StatusBadRequest, errorResponse{
|
||
Error: "BAD_REQUEST",
|
||
Message: safeStorageErrorMessage(saveErr),
|
||
})
|
||
}
|
||
|
||
// MountUploadRoutes registers upload and file-serving endpoints.
|
||
// allowedOrigins controls the Access-Control-Allow-Origin header on served files.
|
||
//
|
||
// permSvc MUST be non-nil — handleServeFile dereferences it to enforce
|
||
// per-channel ACLs on every file download. A nil permSvc would panic for
|
||
// any authenticated file request, so we fail fast at mount time rather
|
||
// than let the first user hit a 500.
|
||
func MountUploadRoutes(r chi.Router, database *db.DB, store FileStore, limiter *auth.RateLimiter, allowedOrigins []string, permSvc *service.PermissionService) {
|
||
if permSvc == nil {
|
||
panic("api: MountUploadRoutes requires a non-nil PermissionService")
|
||
}
|
||
// Upload requires authentication and a higher body size limit (100 MB).
|
||
r.With(
|
||
AuthMiddleware(database),
|
||
MaxBodySize(uploadMaxBodySize),
|
||
).Post("/api/v1/uploads", handleUpload(database, store, limiter))
|
||
// File serving requires authentication for channel-level access control.
|
||
r.With(AuthMiddleware(database)).Get("/api/v1/files/{id}", handleServeFile(database, store, allowedOrigins, permSvc))
|
||
}
|
||
|
||
func handleUpload(database *db.DB, store FileStore, limiter *auth.RateLimiter) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
// BUG-131: Per-user upload rate limit to prevent disk exhaustion.
|
||
user, ok := r.Context().Value(UserKey).(*db.User)
|
||
if ok && user != nil {
|
||
uploadKey := auth.Key("upload", user.ID)
|
||
if !limiter.Allow(uploadKey, uploadRateLimitPerMinute, time.Minute) {
|
||
writeJSON(w, http.StatusTooManyRequests, errorResponse{
|
||
Error: "RATE_LIMITED",
|
||
Message: "upload rate limit exceeded, try again later",
|
||
})
|
||
return
|
||
}
|
||
}
|
||
|
||
// Limit request body size to prevent abuse.
|
||
r.Body = http.MaxBytesReader(w, r.Body, uploadMaxBodySize)
|
||
|
||
// Parse multipart form — 10 MB in memory, rest on disk.
|
||
if err := r.ParseMultipartForm(multipartMemoryLimit); err != nil {
|
||
writeJSON(w, http.StatusBadRequest, errorResponse{
|
||
Error: "BAD_REQUEST",
|
||
Message: "invalid multipart form",
|
||
})
|
||
return
|
||
}
|
||
|
||
file, header, err := r.FormFile("file")
|
||
if err != nil {
|
||
writeJSON(w, http.StatusBadRequest, errorResponse{
|
||
Error: "BAD_REQUEST",
|
||
Message: "missing file field",
|
||
})
|
||
return
|
||
}
|
||
defer file.Close() //nolint:errcheck
|
||
|
||
// Generate UUID for storage.
|
||
fileID := uuid.New().String()
|
||
|
||
// Detect MIME type from actual file bytes (never trust client header).
|
||
var sniffBuf [512]byte
|
||
n, readErr := file.Read(sniffBuf[:])
|
||
if readErr != nil && !errors.Is(readErr, io.EOF) && !errors.Is(readErr, io.ErrUnexpectedEOF) {
|
||
writeJSON(w, http.StatusBadRequest, errorResponse{
|
||
Error: "BAD_REQUEST",
|
||
Message: "failed to read uploaded file",
|
||
})
|
||
return
|
||
}
|
||
detectedMime := http.DetectContentType(sniffBuf[:n])
|
||
// Seek back so the full content is available for storage.
|
||
if _, seekErr := file.Seek(0, 0); seekErr != nil {
|
||
writeJSON(w, http.StatusInternalServerError, errorResponse{
|
||
Error: "INTERNAL_ERROR",
|
||
Message: "failed to process uploaded file",
|
||
})
|
||
return
|
||
}
|
||
mime := detectedMime
|
||
|
||
// Store file on disk (validates file type via magic bytes).
|
||
writtenBytes, saveErr := store.Save(fileID, file)
|
||
if saveErr != nil {
|
||
writeStorageSaveError(w, saveErr, "file upload")
|
||
return
|
||
}
|
||
|
||
// Extract image dimensions if the file is an image.
|
||
var width, height *int
|
||
if strings.HasPrefix(mime, "image/") {
|
||
f, openErr := store.Open(fileID)
|
||
if openErr == nil {
|
||
cfg, _, decErr := image.DecodeConfig(f)
|
||
f.Close() //nolint:errcheck
|
||
if decErr == nil {
|
||
w2, h2 := cfg.Width, cfg.Height
|
||
width = &w2
|
||
height = &h2
|
||
} else {
|
||
slog.Warn("failed to decode image dimensions", "id", fileID, "error", decErr)
|
||
}
|
||
}
|
||
}
|
||
|
||
// Insert attachment record in DB (unlinked — message_id is NULL).
|
||
user, _ = r.Context().Value(UserKey).(*db.User)
|
||
safeFilename := sanitizeUploadFilename(header.Filename)
|
||
if err := database.CreateAttachment(r.Context(), fileID, user.ID, safeFilename, fileID, mime, writtenBytes, width, height); err != nil {
|
||
// Clean up stored file on DB failure.
|
||
_ = store.Delete(fileID)
|
||
slog.Error("failed to create attachment record", "error", err)
|
||
writeJSON(w, http.StatusInternalServerError, errorResponse{
|
||
Error: "INTERNAL_ERROR",
|
||
Message: "failed to save attachment",
|
||
})
|
||
return
|
||
}
|
||
|
||
slog.Info("file uploaded", "id", fileID, "filename", safeFilename, "size", writtenBytes, "mime", mime)
|
||
|
||
writeJSON(w, http.StatusCreated, uploadResponse{
|
||
ID: fileID,
|
||
Filename: safeFilename,
|
||
Size: writtenBytes,
|
||
Mime: mime,
|
||
URL: "/api/v1/files/" + fileID,
|
||
Width: width,
|
||
Height: height,
|
||
})
|
||
}
|
||
}
|
||
|
||
func handleServeFile(database *db.DB, store FileStore, allowedOrigins []string, permSvc *service.PermissionService) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
fileID := chi.URLParam(r, "id")
|
||
if fileID == "" {
|
||
http.NotFound(w, r)
|
||
return
|
||
}
|
||
|
||
aa := serveFileResolve(w, r, database, fileID)
|
||
if aa == nil {
|
||
return
|
||
}
|
||
|
||
if !serveFileAuthorize(w, r, database, permSvc, aa, fileID) {
|
||
return
|
||
}
|
||
|
||
// Open file from storage.
|
||
f, err := store.Open(aa.StoredAs)
|
||
if err != nil {
|
||
http.NotFound(w, r)
|
||
return
|
||
}
|
||
defer f.Close() //nolint:errcheck
|
||
|
||
// Set headers before ServeContent to ensure correct MIME type.
|
||
w.Header().Set("Content-Type", aa.MimeType)
|
||
// BUG-118: Force download for MIME types that could execute content
|
||
// under the OwnCord origin (HTML, SVG, XML, PDF).
|
||
disposition := "inline"
|
||
if isUnsafeInlineMIME(aa.MimeType) {
|
||
disposition = "attachment"
|
||
}
|
||
w.Header().Set("Content-Disposition", mime.FormatMediaType(disposition, map[string]string{"filename": aa.Filename}))
|
||
// These downloads are access-controlled, so they must never be stored by
|
||
// shared/proxy caches (info-leak). Mark private and force revalidation.
|
||
// W3-4: no-cache forces revalidation on every use, so a max-age is dead
|
||
// weight alongside it — private + no-cache expresses the intent exactly.
|
||
w.Header().Set("Cache-Control", "private, no-cache")
|
||
// The Access-Control-Allow-Origin header below reflects the request
|
||
// Origin, so responses vary by Origin and must not be cross-served.
|
||
w.Header().Set("Vary", "Origin")
|
||
// CORS: allow webview to read the response body using configured origins.
|
||
if origin := r.Header.Get("Origin"); origin != "" {
|
||
for _, allowed := range allowedOrigins {
|
||
if allowed == "*" || strings.EqualFold(allowed, origin) {
|
||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||
w.Header().Set("Access-Control-Expose-Headers", "Content-Type, Content-Length")
|
||
break
|
||
}
|
||
}
|
||
}
|
||
|
||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||
|
||
// Use the actual file modification time so If-Modified-Since works correctly.
|
||
var modTime time.Time
|
||
if info, statErr := f.Stat(); statErr == nil {
|
||
modTime = info.ModTime()
|
||
}
|
||
http.ServeContent(w, r, aa.Filename, modTime, f)
|
||
}
|
||
}
|
||
|
||
// serveFileResolve looks up the attachment behind {id} and applies the checks
|
||
// that make a file unservable regardless of who is asking. It returns nil once
|
||
// it has written the response, so the caller only has to return.
|
||
func serveFileResolve(w http.ResponseWriter, r *http.Request, database *db.DB, fileID string) *db.AttachmentAccess {
|
||
// Look up attachment metadata with channel context.
|
||
aa, err := database.GetAttachmentWithChannel(r.Context(), fileID)
|
||
if err != nil {
|
||
slog.Error("failed to look up attachment", "id", fileID, "error", err)
|
||
writeJSON(w, http.StatusInternalServerError, errorResponse{
|
||
Error: "INTERNAL_ERROR",
|
||
Message: "internal server error",
|
||
})
|
||
return nil
|
||
}
|
||
if aa == nil {
|
||
http.NotFound(w, r)
|
||
return nil
|
||
}
|
||
|
||
// A soft-deleted message's attachments must stop being servable the
|
||
// moment the message is deleted — the client shows a tombstone, but
|
||
// without this check the file stays reachable by URL forever (no
|
||
// sweep can ever reclaim a linked row either, since the only reaper
|
||
// requires message_id IS NULL). Checked before the ACL branch so it
|
||
// also covers admins, matching the tombstone applying to everyone.
|
||
//
|
||
// Queried directly rather than through database.GetMessage: that
|
||
// wrapper's SELECT list carries every message column, and the
|
||
// `deleted` flag is the only one this check needs.
|
||
if aa.MessageID != nil {
|
||
var deleted bool
|
||
deletedErr := database.QueryRowContext(r.Context(),
|
||
`SELECT deleted FROM messages WHERE id = ?`, *aa.MessageID).Scan(&deleted)
|
||
switch {
|
||
case errors.Is(deletedErr, sql.ErrNoRows):
|
||
// No message row — leave ACL to decide (unlinked-shaped by now).
|
||
case deletedErr != nil:
|
||
slog.Error("failed to look up message for attachment", "id", fileID, "error", deletedErr)
|
||
writeJSON(w, http.StatusInternalServerError, errorResponse{
|
||
Error: "INTERNAL_ERROR",
|
||
Message: "internal server error",
|
||
})
|
||
return nil
|
||
case deleted:
|
||
http.NotFound(w, r)
|
||
return nil
|
||
}
|
||
}
|
||
|
||
return aa
|
||
}
|
||
|
||
// serveFileAuthorize decides whether the caller may read aa. It returns false
|
||
// once it has written the response, so the caller only has to return.
|
||
func serveFileAuthorize(w http.ResponseWriter, r *http.Request, database *db.DB, permSvc *service.PermissionService, aa *db.AttachmentAccess, fileID string) bool {
|
||
user, _ := r.Context().Value(UserKey).(*db.User)
|
||
role, _ := r.Context().Value(RoleKey).(*db.Role)
|
||
|
||
// ── Access control ──────────────────────────────────────────────
|
||
isAdmin := role != nil && permissions.HasAdmin(role.Permissions)
|
||
|
||
// DM participation is required of everyone, including admins — this
|
||
// matches every other DM read gate in the codebase (requireChannelRead,
|
||
// PermissionService.RequireChannelAccess, checkSendPermission), none of
|
||
// which have an admin bypass. Checked ahead of the `!isAdmin` block so
|
||
// the admin bypass below cannot skip it.
|
||
if aa.ChannelID != nil && aa.ChannelType == "dm" {
|
||
if user == nil {
|
||
writeJSON(w, http.StatusForbidden, errorResponse{
|
||
Error: "FORBIDDEN",
|
||
Message: "you do not have access to this file",
|
||
})
|
||
return false
|
||
}
|
||
ok, dmErr := database.IsDMParticipant(r.Context(), user.ID, *aa.ChannelID)
|
||
if dmErr != nil || !ok {
|
||
writeJSON(w, http.StatusForbidden, errorResponse{
|
||
Error: "FORBIDDEN",
|
||
Message: "you do not have access to this file",
|
||
})
|
||
return false
|
||
}
|
||
}
|
||
|
||
if !isAdmin {
|
||
if aa.ChannelID == nil {
|
||
// An unlinked attachment that some user's avatar points at is
|
||
// readable by every authenticated user: an avatar has to be
|
||
// visible to the people who see the messages it sits next to.
|
||
// The check is by the exact URL the column stores, so the file
|
||
// stops being public the instant the avatar is replaced.
|
||
isAvatar, avatarErr := database.IsAvatarFileURL(r.Context(), service.AvatarFileURL(fileID))
|
||
if avatarErr != nil {
|
||
slog.Error("failed to check avatar file", "id", fileID, "error", avatarErr)
|
||
}
|
||
switch {
|
||
case isAvatar:
|
||
// Public while in use — fall through to serving.
|
||
// Unlinked attachment — only the uploader may access.
|
||
// M-2: Legacy rows (NULL uploader_id) are now denied rather than
|
||
// served to any authenticated user.
|
||
case aa.UploaderID == nil:
|
||
slog.Warn("legacy attachment access denied (NULL uploader_id)", "id", fileID)
|
||
writeJSON(w, http.StatusForbidden, errorResponse{
|
||
Error: "FORBIDDEN",
|
||
Message: "you do not have access to this file",
|
||
})
|
||
return false
|
||
case user == nil || *aa.UploaderID != user.ID:
|
||
writeJSON(w, http.StatusForbidden, errorResponse{
|
||
Error: "FORBIDDEN",
|
||
Message: "you do not have access to this file",
|
||
})
|
||
return false
|
||
}
|
||
} else if aa.ChannelType != "dm" {
|
||
// Linked attachment in a guild channel — check channel
|
||
// permissions. The DM case is handled unconditionally above.
|
||
if user == nil || !permSvc.HasChannelPerm(r.Context(), user.ID, *aa.ChannelID, permissions.ReadMessages) {
|
||
writeJSON(w, http.StatusForbidden, errorResponse{
|
||
Error: "FORBIDDEN",
|
||
Message: "you do not have access to this file",
|
||
})
|
||
return false
|
||
}
|
||
}
|
||
}
|
||
|
||
return true
|
||
}
|