mirror of
https://github.com/J3vb/OwnCord.git
synced 2026-09-03 03:50:00 +03:00
Fixes all 109 golangci-lint findings (106 contextcheck, 1 gocritic,
2 gosec) that accumulated after D2 wired dbgen (whose queries take ctx)
under ctx-less db.DB wrappers while CI lint was quota-dead. No nolint
comments added; every finding fixed by genuinely threading context.
- db: all 138 hand-written db.DB methods take ctx first; the dbCtx()
Background shim is deleted; raw Query/QueryRow/Exec/Begin use their
Context variants; the four redundant ctx-less passthroughs removed.
db.Auditor/WriteAudit gain ctx.
- Seams: permissions.Checker (DB iface, HasChannelPerm,
RequireChannelAccess) and the service.Store interface mirror the new
signatures (ws.EventStore and plugin.PluginStore already did).
- Callers: api/admin handlers use r.Context(); ws per-message paths use
the connection ctx via DispatchV2; hub loops and startup wiring use
context.Background(); service methods thread ctx where they have one
and Background where no ctx exists. Public service surface reached by
ctx-holding chains (PermissionService.HasChannelPerm/GetRoleForUser/
RequireChannelAccess, message/dm/block/invite/profile methods) is now
ctx-first.
- Detached (context.WithoutCancel) where cancellation would break an
invariant, found by a 3-lens adversarial review of the diff:
* voice-leave background retries (a dead webhook/connection ctx killed
retry 2 before it ran, leaving ghost capacity-holding voice rows)
* rollbackVoiceJoin's compensating delete (its trigger IS the cancel)
* post-2FA-change DeleteOtherSessions and logout DeleteSession (the
security tail of a committed change must not die with the request)
* all api/ws audit writes (a banned user could suppress their own
login_blocked_banned row by aborting the request mid-bcrypt)
* admin backup VACUUM INTO (an interrupt left a truncated .db that
the backup list presented as restorable)
* post-commit message/edit refetches (a committed message must still
fan out when the sender disconnects)
* hub settings-cache refresh (one dead connection could pin stale
values for the 30s TTL)
- gocritic rangeValCopy fixed (index iteration); gosec G306 excluded in
config with justification (generated source must stay world-readable)
instead of flipping genprotocol output to 0o600.
Verified: gofmt/vet, all four build-tag variants, full suite, deadlock
pass, full -race pass, golangci-lint 0 issues uncapped.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
179 lines
5.8 KiB
Go
179 lines
5.8 KiB
Go
package admin
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
|
|
"github.com/owncord/server/db"
|
|
"github.com/owncord/server/service"
|
|
)
|
|
|
|
// ─── User Handlers ───────────────────────────────────────────────────────────
|
|
|
|
func handleGetStats(database *db.DB, hub HubBroadcaster) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
stats, err := database.GetServerStats(r.Context())
|
|
if err != nil {
|
|
writeErr(w, http.StatusInternalServerError, "INTERNAL_ERROR", "failed to get stats")
|
|
return
|
|
}
|
|
if hub != nil {
|
|
stats.OnlineCount = hub.ClientCount()
|
|
}
|
|
writeJSON(w, http.StatusOK, stats)
|
|
}
|
|
}
|
|
|
|
func handleListUsers(database *db.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
limit := queryInt(r, "limit", 50, 1)
|
|
offset := queryInt(r, "offset", 0, 0)
|
|
|
|
users, err := database.ListAllUsers(r.Context(), limit, offset)
|
|
if err != nil {
|
|
writeErr(w, http.StatusInternalServerError, "INTERNAL_ERROR", "failed to list users")
|
|
return
|
|
}
|
|
|
|
safe := make([]adminUserResponse, len(users))
|
|
for i := range users {
|
|
safe[i] = toAdminUserResponse(users[i])
|
|
}
|
|
writeJSON(w, http.StatusOK, safe)
|
|
}
|
|
}
|
|
|
|
// patchUserRequest is the JSON body for PATCH /admin/api/users/{id}.
|
|
type patchUserRequest struct {
|
|
RoleID *int64 `json:"role_id"`
|
|
Banned *bool `json:"banned"`
|
|
BanReason *string `json:"ban_reason"`
|
|
}
|
|
|
|
// writeModerationErr maps ModerationService errors onto admin API responses.
|
|
func writeModerationErr(w http.ResponseWriter, err error) {
|
|
switch {
|
|
case errors.Is(err, service.ErrForbidden):
|
|
writeErr(w, http.StatusForbidden, "FORBIDDEN", err.Error())
|
|
case errors.Is(err, service.ErrNotFound):
|
|
writeErr(w, http.StatusNotFound, "NOT_FOUND", "user not found")
|
|
case errors.Is(err, service.ErrBadRequest):
|
|
writeErr(w, http.StatusBadRequest, "BAD_REQUEST", err.Error())
|
|
default:
|
|
writeErr(w, http.StatusInternalServerError, "INTERNAL_ERROR", "moderation action failed")
|
|
}
|
|
}
|
|
|
|
func handlePatchUser(database *db.DB, hub HubBroadcaster, permInvalidator PermissionInvalidator, mod *service.ModerationService) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, err := pathInt64(r, "id")
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadRequest, "BAD_REQUEST", "invalid user id")
|
|
return
|
|
}
|
|
|
|
var req patchUserRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeErr(w, http.StatusBadRequest, "BAD_REQUEST", "invalid request body")
|
|
return
|
|
}
|
|
|
|
user, err := database.GetUserByID(r.Context(), id)
|
|
if err != nil {
|
|
writeErr(w, http.StatusInternalServerError, "INTERNAL_ERROR", "failed to fetch user")
|
|
return
|
|
}
|
|
if user == nil {
|
|
writeErr(w, http.StatusNotFound, "NOT_FOUND", "user not found")
|
|
return
|
|
}
|
|
|
|
actor := actorFromContext(r)
|
|
|
|
// Prevent admins from modifying their own role or ban status, which
|
|
// could lock them out of the admin panel with no recovery path.
|
|
if id == actor {
|
|
writeErr(w, http.StatusBadRequest, "BAD_REQUEST", "cannot modify your own account via admin panel")
|
|
return
|
|
}
|
|
|
|
// Ban/unban first: it routes through ModerationService, which enforces
|
|
// BAN_MEMBERS + role hierarchy (the admin-auth perimeter alone does
|
|
// not — any admin-panel actor could previously ban the owner). The
|
|
// service also audits and refuses before the role change runs, so a
|
|
// rejected ban never leaves a half-applied PATCH behind.
|
|
if req.Banned != nil {
|
|
if mod == nil {
|
|
// Fail closed rather than fall back to an unchecked UPDATE.
|
|
writeErr(w, http.StatusInternalServerError, "INTERNAL_ERROR", "moderation service unavailable")
|
|
return
|
|
}
|
|
banReason := ""
|
|
if req.BanReason != nil {
|
|
banReason = *req.BanReason
|
|
}
|
|
var actionErr error
|
|
if *req.Banned {
|
|
actionErr = mod.BanUser(r.Context(), actor, id, banReason, nil)
|
|
} else {
|
|
actionErr = mod.UnbanUser(r.Context(), actor, id)
|
|
}
|
|
if actionErr != nil {
|
|
writeModerationErr(w, actionErr)
|
|
return
|
|
}
|
|
if *req.Banned && hub != nil {
|
|
hub.BroadcastMemberBan(id)
|
|
}
|
|
}
|
|
|
|
if req.RoleID != nil {
|
|
if _, err := database.ExecContext(r.Context(), `UPDATE users SET role_id = ? WHERE id = ?`, *req.RoleID, id); err != nil {
|
|
writeErr(w, http.StatusInternalServerError, "INTERNAL_ERROR", "failed to update role")
|
|
return
|
|
}
|
|
slog.Info("role changed", "actor_id", actor, "target_user", user.Username, "new_role_id", *req.RoleID)
|
|
if permInvalidator != nil {
|
|
permInvalidator.InvalidateUser(id)
|
|
}
|
|
db.WriteAudit(context.WithoutCancel(r.Context()), database, actor, "role_change", "user", id,
|
|
fmt.Sprintf("changed %s role to %d", user.Username, *req.RoleID))
|
|
if role, err := database.GetRoleByID(r.Context(), *req.RoleID); err == nil && role != nil {
|
|
if hub != nil {
|
|
hub.BroadcastMemberUpdate(id, role.Name)
|
|
}
|
|
}
|
|
}
|
|
|
|
updated, err := database.GetUserByID(r.Context(), id)
|
|
if err != nil {
|
|
writeErr(w, http.StatusInternalServerError, "INTERNAL_ERROR", "failed to fetch updated user")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, toAdminUserResponseFromUser(r.Context(), database, updated))
|
|
}
|
|
}
|
|
|
|
func handleForceLogout(database *db.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, err := pathInt64(r, "id")
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadRequest, "BAD_REQUEST", "invalid user id")
|
|
return
|
|
}
|
|
|
|
if err := database.ForceLogoutUser(r.Context(), id); err != nil {
|
|
writeErr(w, http.StatusInternalServerError, "INTERNAL_ERROR", "failed to logout user")
|
|
return
|
|
}
|
|
actor := actorFromContext(r)
|
|
slog.Info("force logout", "actor_id", actor, "target_user_id", id)
|
|
db.WriteAudit(context.WithoutCancel(r.Context()), database, actor, "force_logout", "user", id, "all sessions terminated")
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
}
|