Files
OwnCord/Server/admin/handlers_channel_perms.go
T
Claude 685f226a59 feat(server,admin): private channels via per-role permission overrides
The read side of channel visibility was already complete — channel_overrides
rows deny ReadMessages and every list/focus/send/voice path enforces them —
but nothing could write those rows. Add the missing write path and UI:

- db: UpsertChannelOverride / DeleteChannelOverride / ListChannelRoleOverrides
  (roles LEFT JOIN overrides so the UI gets everything in one call)
- admin API: GET/PUT/DELETE /admin/api/channels/{id}/permissions[/{roleId}]
  with unknown permission bits masked via the new permissions.AllPerms,
  audit logging, and immediate permission-cache invalidation
- ws: Hub.RefreshChannelVisibility sends targeted channel_create /
  channel_delete to connected clients after an override change, unsubscribes
  hidden clients from the channel topic, and clears their focus. Sent outside
  the sequenced replay path on purpose: a replayed channel_delete would be
  filtered by the post-change allowed-channel set, inverting its audience.
- admin panel: per-channel Access modal (lock icon) with per-role
  "Can access" checkboxes; unchecking writes deny = ReadMessages|ConnectVoice

Known limits (follow-ups): users offline during a revoke keep a stale
sidebar entry until their next fresh connect (server still denies access),
and users already in a voice channel are not kicked when it goes private.

Closes #93

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LwtnpHAoSFr1ZibQgQkNQK
2026-07-19 10:50:11 +00:00

162 lines
5.2 KiB
Go

package admin
import (
"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(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(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(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(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)
_ = database.LogAudit(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(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)
_ = database.LogAudit(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)
}
}