Files
OwnCord/Server/admin/handlers_channel_perms.go
T
J3vbandClaude Fable 5 6afa9e974c refactor(server): thread context.Context through the db layer and all callers
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>
2026-07-23 17:03:52 +02:00

163 lines
5.3 KiB
Go

package admin
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"github.com/owncord/server/db"
"github.com/owncord/server/permissions"
)
// ─── Channel Permission Override Handlers ────────────────────────────────────
//
// These endpoints manage per-role allow/deny permission overrides on a
// channel (the channel_overrides table). Denying ReadMessages hides the
// channel from a role entirely ("private channel"); the read side is already
// enforced by ListVisibleChannels, the WS ready payload, and the per-message
// permission checks.
// getPermChannel loads the channel for an override request and writes the
// appropriate error response when it is missing or a DM. Returns nil when a
// response has already been written.
func getPermChannel(database *db.DB, w http.ResponseWriter, r *http.Request) *db.Channel {
id, err := pathInt64(r, "id")
if err != nil {
writeErr(w, http.StatusBadRequest, "BAD_REQUEST", "invalid channel id")
return nil
}
ch, err := database.GetChannel(r.Context(), id)
if err != nil {
writeErr(w, http.StatusInternalServerError, "INTERNAL_ERROR", "failed to fetch channel")
return nil
}
if ch == nil {
writeErr(w, http.StatusNotFound, "NOT_FOUND", "channel not found")
return nil
}
if ch.Type == "dm" {
writeErr(w, http.StatusBadRequest, "INVALID_INPUT", "DM channels do not support permission overrides")
return nil
}
return ch
}
// channelPermissionsResponse is the JSON shape for GET .../permissions.
type channelPermissionsResponse struct {
ChannelID int64 `json:"channel_id"`
Roles []db.ChannelRoleOverride `json:"roles"`
}
func handleGetChannelPermissions(database *db.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ch := getPermChannel(database, w, r)
if ch == nil {
return
}
overrides, err := database.ListChannelRoleOverrides(r.Context(), ch.ID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "INTERNAL_ERROR", "failed to list channel permissions")
return
}
writeJSON(w, http.StatusOK, channelPermissionsResponse{ChannelID: ch.ID, Roles: overrides})
}
}
// putChannelPermissionRequest is the JSON body for PUT .../permissions/{roleId}.
type putChannelPermissionRequest struct {
Allow int64 `json:"allow"`
Deny int64 `json:"deny"`
}
func handlePutChannelPermission(database *db.DB, hub HubBroadcaster, permInvalidator PermissionInvalidator) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ch := getPermChannel(database, w, r)
if ch == nil {
return
}
roleID, err := pathInt64(r, "roleId")
if err != nil {
writeErr(w, http.StatusBadRequest, "BAD_REQUEST", "invalid role id")
return
}
role, err := database.GetRoleByID(r.Context(), roleID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "INTERNAL_ERROR", "failed to fetch role")
return
}
if role == nil {
writeErr(w, http.StatusNotFound, "NOT_FOUND", "role not found")
return
}
var req putChannelPermissionRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, "BAD_REQUEST", "invalid request body")
return
}
// Drop unknown bits so garbage input cannot persist undefined perms.
allow := req.Allow & permissions.AllPerms
deny := req.Deny & permissions.AllPerms
if err := database.UpsertChannelOverride(r.Context(), ch.ID, roleID, allow, deny); err != nil {
writeErr(w, http.StatusInternalServerError, "INTERNAL_ERROR", "failed to save channel permission")
return
}
actor := actorFromContext(r)
slog.Info("channel permissions updated", "actor_id", actor, "channel_id", ch.ID,
"role_id", roleID, "allow", allow, "deny", deny)
db.WriteAudit(context.WithoutCancel(r.Context()), database, actor, "channel_perms_update", "channel", ch.ID,
fmt.Sprintf("set overrides for role %s on #%s (allow=%#x deny=%#x)", role.Name, ch.Name, allow, deny))
if permInvalidator != nil {
permInvalidator.InvalidateAll()
}
if hub != nil {
hub.RefreshChannelVisibility(ch)
}
writeJSON(w, http.StatusOK, db.ChannelRoleOverride{
RoleID: role.ID,
RoleName: role.Name,
Position: role.Position,
Permissions: role.Permissions,
Allow: allow,
Deny: deny,
})
}
}
func handleDeleteChannelPermission(database *db.DB, hub HubBroadcaster, permInvalidator PermissionInvalidator) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ch := getPermChannel(database, w, r)
if ch == nil {
return
}
roleID, err := pathInt64(r, "roleId")
if err != nil {
writeErr(w, http.StatusBadRequest, "BAD_REQUEST", "invalid role id")
return
}
if err := database.DeleteChannelOverride(r.Context(), ch.ID, roleID); err != nil {
writeErr(w, http.StatusInternalServerError, "INTERNAL_ERROR", "failed to delete channel permission")
return
}
actor := actorFromContext(r)
slog.Info("channel permissions cleared", "actor_id", actor, "channel_id", ch.ID, "role_id", roleID)
db.WriteAudit(context.WithoutCancel(r.Context()), database, actor, "channel_perms_clear", "channel", ch.ID,
fmt.Sprintf("cleared overrides for role %d on #%s", roleID, ch.Name))
if permInvalidator != nil {
permInvalidator.InvalidateAll()
}
if hub != nil {
hub.RefreshChannelVisibility(ch)
}
w.WriteHeader(http.StatusNoContent)
}
}