Files
OwnCord/Server/admin/handlers_roles_test.go
T
Claude 7a4e5dc357 refactor: rename the Go module to github.com/J3vb/OwnCord/Server (RL-13)
`Server/go.mod` declared `github.com/owncord/server` while the public
repository is `github.com/J3vb/OwnCord`. Nothing resolves that path — there is
no `owncord` GitHub org and no vanity-import host serving go-import metadata
for it — so every import line in the tree named a location that does not
exist. It compiles because a main module's own path is never fetched, which is
exactly why it went unnoticed.

The obvious fix — an AST-aware import rewriter (`gomvpkg`, `go mod edit`) —
is wrong here, and provably so. Six of the 722 occurrences are not imports at
all: `api/main_test.go:20` (a goleak `IgnoreTopFunction` pattern),
`telemetry/metrics.go:17-19` (three OTel instrumentation-scope names),
`invariants/syncutil_locks.go:73` (a diagnostic message), and
`invariants/syncutil_locks_test.go:56` (an import line inside a raw-string Go
fixture). An import rewriter touches none of them, and the compiler cannot
see any of them either.

Done as one scripted substitution over `git ls-files`, anchored on the full
`github.com/owncord/server` string. The anchor matters: `owncord-server` is a
different identifier — the OTel `service.name` (`config/config.go`,
`telemetry/telemetry_otel.go`) and the GHCR image name
(`.github/workflows/release.yml`, `docker-compose.yml`) — and a looser pattern
would have moved it. It is untouched: 10 occurrences across 9 files, before
and after.

350 files, 728 insertions, 728 deletions. 722 occurrences in 344 Go files,
plus `go.mod:1`, the `sed` at `Makefile:67`, `Server/CLAUDE.md:3`,
`docs/architecture/server.md:5`, and the ledger pair
(`findings-ledger.json:3758` plus a `render-ledger.mjs` re-render of
`FINDINGS.md`). Zero in any workflow, zero in the Dockerfile, zero in
`Server/.golangci.yml` (no `local-prefixes`, `gci`, `importas` or `depguard`
rule keys on the module path, so import grouping is not configured anywhere).

The plan's blast-radius estimate missed one thing, and it is the one that
would have gone red: **gofmt**. `J` (0x4A) sorts before every lowercase
letter, so in the 36 files where a module-local import shares a contiguous
group with a third-party one, the module's imports must move above
`github.com/go-chi/...`. `gofmt -l` was clean before the substitution and
listed exactly 36 files after it; `gofmt -w` on those 36 restores it to
clean. `gofmt` is an enforced gate — the `formatters` block in
`Server/.golangci.yml`, which is S-05 — so a substitution-only commit fails
Lint.

Verified: both directions, and the line accounting is exact. Every added line
in this diff contains the new module path (728) and every removed line
contains the old one (728); the count of changed lines containing neither is
**zero**, so the gofmt re-sort moved module-path lines only and touched no
third-party import. The residual check
(`git ls-files -z | xargs -0 grep -n 'github\.com/owncord/server'`) returns
exactly two hits, both deliberately out of scope: the RL-13 row in
`docs/audit-2026-08-23-repository-layout.md` and the measurement row in this
phase's own plan. The compiler-invisible half was proven by reverting *only*
`api/main_test.go:20` to the old path on the otherwise-renamed tree:
`go build ./...` and `go vet ./api/` both still pass — they see nothing wrong
— while `go test ./api/` FAILS, because the runtime function name now carries
the new path and goleak stops ignoring `ws.(*Hub).Run.func1`. Restoring the
line makes it pass. `go.sum` is byte-identical (no `go mod tidy` was run and
none was needed). All four build-tag variants compile; `go vet ./...`,
`go vet -tags otel,wazero ./...` and `go vet -tags deadlock ./...` pass;
`go test -race ./...` is 16/16 packages green; `go test -tags deadlock ./...`
passes; the tag-gated `./plugin/...` (wazero) and `./telemetry/...` (otel)
runs pass. `golangci-lint` v2.11.3 — the pinned CI version, rebuilt locally
against Go 1.26 because the packaged binary cannot load a 1.26 config —
reports **0 issues**. `go run ./cmd/genprotocol` leaves
`git diff --exit-code ws/message_types.go ../Client/src/lib/protocolTypes.ts`
clean, so the rename does not reach the generated protocol constants.
`npx prettier --check .` and `node .superpowers/render-ledger.mjs --check`
pass.

Not included: `docs/audit-2026-08-23-repository-layout.md` and
`docs/plans/b1-repository-foundation-2026-08-25.md` keep the old path — they
are the audit row and the measurement that motivated this change, and
rewriting them would erase the record of what was measured. They are why the
residual check needs a two-path allowance rather than being empty; that
allowance is stated above rather than hidden in a pathspec.
`telemetry/metrics.go:19` declares `scopeVoice` for a `Server/voice` package
that does not exist; the substitution carried the dead path forward verbatim
as `github.com/J3vb/OwnCord/Server/voice` rather than fixing it, because
correcting a real observability bug inside a mechanical rename would hide it
in a 350-file diff. It needs its own item. No `go.work`, no second module,
and no vanity-import host was set up — the new path resolves against the real
repository, but nothing imports this module as a library, so `go get`
reachability was not exercised either way.

Refs RL-13, L-12
2026-08-26 20:23:49 +00:00

449 lines
17 KiB
Go

package admin_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/J3vb/OwnCord/Server/admin"
"github.com/J3vb/OwnCord/Server/auth"
"github.com/J3vb/OwnCord/Server/db"
"github.com/J3vb/OwnCord/Server/permissions"
)
// The admin test schema seeds Owner (id 1, pos 100, ADMINISTRATOR), Admin
// (id 2, pos 80, everything but ADMINISTRATOR) and Member (id 3, pos 40,
// is_default). createAdminUser signs in as the Owner.
// newRolesHandler wires the full admin API with a mock hub and a recording
// permission invalidator, and returns them alongside an Owner bearer token.
func newRolesHandler(t *testing.T, database *db.DB) (http.Handler, *mockHub, *mockPermInvalidator, string) {
t.Helper()
hub := &mockHub{}
inv := &mockPermInvalidator{}
handler := admin.NewAdminAPI(database, "1.0.0", hub, nil, nil, nil, inv,
newTestModService(database), newTestRoleService(database))
return handler, hub, inv, createAdminUser(t, database)
}
// createUserWithRole creates a user holding an existing roleID and returns a
// bearer token for them. (perm_gates_test.go's createRoleUser also upserts the
// role; these tests want the schema's seeded roles left exactly as they are.)
func createUserWithRole(t *testing.T, database *db.DB, username string, roleID int) string {
t.Helper()
uid, err := database.CreateUser(context.Background(), username, "$2a$12$placeholder", roleID)
if err != nil {
t.Fatalf("CreateUser %s: %v", username, err)
}
token := "test-token-" + username + "-" + t.Name()
if _, err := database.CreateSession(context.Background(), uid, auth.HashToken(token), "test", "127.0.0.1"); err != nil {
t.Fatalf("CreateSession %s: %v", username, err)
}
return token
}
// doRequestRaw sends a request with a raw (possibly malformed) body, which
// doRequest cannot express because it marshals its body argument.
func doRequestRaw(t *testing.T, handler http.Handler, method, path, token, body string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
return w
}
// decodeRole unmarshals a role response body.
func decodeRole(t *testing.T, body []byte) db.Role {
t.Helper()
var role db.Role
if err := json.Unmarshal(body, &role); err != nil {
t.Fatalf("unmarshal role: %v (body %s)", err, body)
}
return role
}
// ─── POST /roles ─────────────────────────────────────────────────────────────
func TestAdminAPI_CreateRole_OK(t *testing.T) {
database := openAdminTestDB(t)
handler, hub, _, token := newRolesHandler(t, database)
w := doRequest(t, handler, http.MethodPost, "/roles", token, map[string]any{
"name": "Helper",
"color": "#12ab34",
"permissions": permissions.ReadMessages | permissions.SendMessages,
"position": 50,
})
if w.Code != http.StatusCreated {
t.Fatalf("status = %d, want 201; body: %s", w.Code, w.Body.String())
}
role := decodeRole(t, w.Body.Bytes())
if role.Name != "Helper" || role.Position != 50 {
t.Errorf("role = %+v", role)
}
if role.Color == nil || *role.Color != "#12AB34" {
t.Errorf("color = %v, want #12AB34", role.Color)
}
// Every mutation ships the new list to connected clients.
if len(hub.rolesUpdates) != 1 {
t.Fatalf("BroadcastRolesUpdate called %d times, want 1", len(hub.rolesUpdates))
}
if len(hub.rolesUpdates[0]) != 4 {
t.Errorf("broadcast carried %d roles, want the full list of 4", len(hub.rolesUpdates[0]))
}
// A new role has no members, so nothing changed visibility.
if hub.allVisibilityRefreshes != 0 {
t.Errorf("RefreshAllChannelVisibility called %d times on create, want 0", hub.allVisibilityRefreshes)
}
}
func TestAdminAPI_CreateRole_DuplicateNameIsBadRequest(t *testing.T) {
database := openAdminTestDB(t)
handler, _, _, token := newRolesHandler(t, database)
w := doRequest(t, handler, http.MethodPost, "/roles", token, map[string]any{"name": "mEmBeR"})
if w.Code != http.StatusBadRequest {
t.Errorf("status = %d, want 400; body: %s", w.Code, w.Body.String())
}
}
func TestAdminAPI_Roles_RequireManageRoles(t *testing.T) {
database := openAdminTestDB(t)
handler, _, _, _ := newRolesHandler(t, database)
// A role inside the admin perimeter but without MANAGE_ROLES.
if _, err := database.ExecContext(context.Background(),
`INSERT INTO roles (id, name, permissions, position, is_default) VALUES (9, 'Janitor', ?, 50, 0)`,
permissions.ManageChannels,
); err != nil {
t.Fatalf("seed role: %v", err)
}
token := createUserWithRole(t, database, "janitor", 9)
for _, tc := range []struct {
method, path string
body any
}{
{http.MethodGet, "/roles", nil},
{http.MethodPost, "/roles", map[string]any{"name": "x"}},
{http.MethodPatch, "/roles/3", map[string]any{"name": "x"}},
{http.MethodPatch, "/roles/reorder", map[string]any{"role_ids": []int64{3}}},
{http.MethodDelete, "/roles/3", nil},
} {
w := doRequest(t, handler, tc.method, tc.path, token, tc.body)
if w.Code != http.StatusForbidden {
t.Errorf("%s %s: status = %d, want 403; body: %s", tc.method, tc.path, w.Code, w.Body.String())
}
}
}
func TestAdminAPI_Roles_Unauthenticated(t *testing.T) {
database := openAdminTestDB(t)
handler, _, _, _ := newRolesHandler(t, database)
if w := doRequest(t, handler, http.MethodGet, "/roles", "", nil); w.Code != http.StatusUnauthorized {
t.Errorf("status = %d, want 401", w.Code)
}
}
func TestAdminAPI_Roles_ServiceUnavailableFailsClosed(t *testing.T) {
database := openAdminTestDB(t)
// nil RoleService: the routes must refuse rather than fall through to an
// unchecked write.
handler := admin.NewAdminAPI(database, "1.0.0", &mockHub{}, nil, nil, nil, nil,
newTestModService(database), nil)
token := createAdminUser(t, database)
for _, tc := range []struct {
method, path string
body any
}{
{http.MethodGet, "/roles", nil},
{http.MethodPost, "/roles", map[string]any{"name": "x"}},
{http.MethodPatch, "/roles/3", map[string]any{"name": "x"}},
{http.MethodPatch, "/roles/reorder", map[string]any{"role_ids": []int64{3}}},
{http.MethodDelete, "/roles/3", nil},
} {
w := doRequest(t, handler, tc.method, tc.path, token, tc.body)
if w.Code != http.StatusInternalServerError {
t.Errorf("%s %s: status = %d, want 500", tc.method, tc.path, w.Code)
}
}
}
// ─── GET /roles ──────────────────────────────────────────────────────────────
func TestAdminAPI_ListRoles_CarriesMemberCounts(t *testing.T) {
database := openAdminTestDB(t)
handler, _, _, token := newRolesHandler(t, database)
createUserWithRole(t, database, "member1", 3)
createUserWithRole(t, database, "member2", 3)
w := doRequest(t, handler, http.MethodGet, "/roles", token, nil)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body: %s", w.Code, w.Body.String())
}
var list []struct {
ID int64 `json:"id"`
Position int `json:"position"`
MemberCount int `json:"member_count"`
}
if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if len(list) != 3 {
t.Fatalf("got %d roles, want 3", len(list))
}
if list[0].Position < list[len(list)-1].Position {
t.Error("roles are not ordered by position descending")
}
counts := map[int64]int{}
for _, r := range list {
counts[r.ID] = r.MemberCount
}
if counts[3] != 2 {
t.Errorf("member count = %d, want 2", counts[3])
}
if counts[1] != 1 {
t.Errorf("owner count = %d, want 1 (the acting admin)", counts[1])
}
}
// ─── PATCH /roles/{id} ───────────────────────────────────────────────────────
func TestAdminAPI_PatchRole_PermissionChangeInvalidatesAndResyncs(t *testing.T) {
database := openAdminTestDB(t)
handler, hub, inv, token := newRolesHandler(t, database)
createUserWithRole(t, database, "member1", 3)
w := doRequest(t, handler, http.MethodPatch, "/roles/3", token, map[string]any{
"permissions": permissions.ReadMessages,
})
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body: %s", w.Code, w.Body.String())
}
// The one member of role 3 has their cached mask dropped …
if len(inv.invalidateUserIDs) != 1 || inv.invalidateUserIDs[0] == 0 {
t.Errorf("InvalidateUser calls = %v, want the single role member", inv.invalidateUserIDs)
}
// … and every channel's audience is recomputed, because READ_MESSAGES moved.
if hub.allVisibilityRefreshes != 1 {
t.Errorf("RefreshAllChannelVisibility called %d times, want 1", hub.allVisibilityRefreshes)
}
if len(hub.rolesUpdates) != 1 {
t.Errorf("roles_update broadcasts = %d, want 1", len(hub.rolesUpdates))
}
}
func TestAdminAPI_PatchRole_RenameOnlySkipsResync(t *testing.T) {
database := openAdminTestDB(t)
handler, hub, inv, token := newRolesHandler(t, database)
w := doRequest(t, handler, http.MethodPatch, "/roles/3", token, map[string]any{"name": "Regulars"})
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body: %s", w.Code, w.Body.String())
}
if decodeRole(t, w.Body.Bytes()).Name != "Regulars" {
t.Errorf("name not applied: %s", w.Body.String())
}
if hub.allVisibilityRefreshes != 0 {
t.Errorf("RefreshAllChannelVisibility called %d times for a rename, want 0", hub.allVisibilityRefreshes)
}
if len(inv.invalidateUserIDs) != 0 {
t.Errorf("InvalidateUser called %v for a rename, want none", inv.invalidateUserIDs)
}
if len(hub.rolesUpdates) != 1 {
t.Errorf("roles_update broadcasts = %d, want 1 — the name is in the client's role list", len(hub.rolesUpdates))
}
}
func TestAdminAPI_PatchRole_HierarchyDenied(t *testing.T) {
database := openAdminTestDB(t)
handler, _, _, _ := newRolesHandler(t, database)
adminToken := createUserWithRole(t, database, "admin2", 2)
// The Admin actor (80) may not edit the Owner role (100) …
w := doRequest(t, handler, http.MethodPatch, "/roles/1", adminToken, map[string]any{"name": "Pwned"})
if w.Code != http.StatusForbidden {
t.Errorf("edit owner role: status = %d, want 403; body: %s", w.Code, w.Body.String())
}
// … nor their own.
w = doRequest(t, handler, http.MethodPatch, "/roles/2", adminToken, map[string]any{"name": "Superadmin"})
if w.Code != http.StatusForbidden {
t.Errorf("edit own role: status = %d, want 403", w.Code)
}
// … nor push a role up to their own rank.
w = doRequest(t, handler, http.MethodPatch, "/roles/3", adminToken, map[string]any{"position": 80})
if w.Code != http.StatusForbidden {
t.Errorf("promote role to own rank: status = %d, want 403", w.Code)
}
}
func TestAdminAPI_PatchRole_InvalidIDAndBody(t *testing.T) {
database := openAdminTestDB(t)
handler, _, _, token := newRolesHandler(t, database)
if w := doRequest(t, handler, http.MethodPatch, "/roles/abc", token, map[string]any{}); w.Code != http.StatusBadRequest {
t.Errorf("non-numeric id: status = %d, want 400", w.Code)
}
if w := doRequest(t, handler, http.MethodPatch, "/roles/999", token, map[string]any{"name": "x"}); w.Code != http.StatusNotFound {
t.Errorf("missing role: status = %d, want 404", w.Code)
}
req := doRequestRaw(t, handler, http.MethodPatch, "/roles/3", token, "{not json")
if req.Code != http.StatusBadRequest {
t.Errorf("malformed body: status = %d, want 400", req.Code)
}
}
// ─── DELETE /roles/{id} ──────────────────────────────────────────────────────
func TestAdminAPI_DeleteRole_ReassignsAndBroadcasts(t *testing.T) {
database := openAdminTestDB(t)
handler, hub, inv, token := newRolesHandler(t, database)
ctx := context.Background()
w := doRequest(t, handler, http.MethodPost, "/roles", token, map[string]any{
"name": "Contractor", "position": 50,
})
if w.Code != http.StatusCreated {
t.Fatalf("create: %d %s", w.Code, w.Body.String())
}
created := decodeRole(t, w.Body.Bytes())
uid, err := database.CreateUser(ctx, "contractor", "$2a$12$placeholder", int(created.ID))
if err != nil {
t.Fatalf("CreateUser: %v", err)
}
hub.rolesUpdates = nil
w = doRequest(t, handler, http.MethodDelete, "/roles/"+itoa(created.ID), token, nil)
if w.Code != http.StatusNoContent {
t.Fatalf("delete: status = %d, want 204; body: %s", w.Code, w.Body.String())
}
user, err := database.GetUserByID(ctx, uid)
if err != nil || user == nil {
t.Fatalf("GetUserByID: %v", err)
}
if user.RoleID != 3 {
t.Errorf("member role after delete = %d, want the default role 3", user.RoleID)
}
if len(inv.invalidateUserIDs) == 0 {
t.Error("reassigned member's cached permissions were not invalidated")
}
if len(hub.memberUpdates) != 1 || hub.memberUpdates[0].userID != uid {
t.Errorf("member_update broadcasts = %+v, want one for the reassigned member", hub.memberUpdates)
}
if hub.memberUpdates[0].roleName != "Member" {
t.Errorf("member_update role = %q, want the default role's name", hub.memberUpdates[0].roleName)
}
if hub.allVisibilityRefreshes != 1 {
t.Errorf("RefreshAllChannelVisibility called %d times, want 1", hub.allVisibilityRefreshes)
}
if len(hub.rolesUpdates) != 1 {
t.Errorf("roles_update broadcasts = %d, want 1", len(hub.rolesUpdates))
}
}
func TestAdminAPI_DeleteRole_OwnerAndDefaultRefused(t *testing.T) {
database := openAdminTestDB(t)
handler, _, _, token := newRolesHandler(t, database)
// Nothing outranks the Owner role, so the hierarchy check refuses first.
if w := doRequest(t, handler, http.MethodDelete, "/roles/1", token, nil); w.Code != http.StatusForbidden {
t.Errorf("delete owner role: status = %d, want 403; body: %s", w.Code, w.Body.String())
}
// The default role clears the hierarchy check and is stopped by is_default.
w := doRequest(t, handler, http.MethodDelete, "/roles/3", token, nil)
if w.Code != http.StatusBadRequest {
t.Errorf("delete default role: status = %d, want 400; body: %s", w.Code, w.Body.String())
}
if role, _ := database.GetRoleByID(context.Background(), 3); role == nil {
t.Fatal("the default role was deleted")
}
}
// ─── PATCH /roles/reorder ────────────────────────────────────────────────────
func TestAdminAPI_ReorderRoles_NormalizesAndBroadcasts(t *testing.T) {
database := openAdminTestDB(t)
handler, hub, inv, token := newRolesHandler(t, database)
w := doRequest(t, handler, http.MethodPatch, "/roles/reorder", token, map[string]any{
"role_ids": []int64{3, 2},
})
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body: %s", w.Code, w.Body.String())
}
var list []db.Role
if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil {
t.Fatalf("unmarshal: %v", err)
}
positions := map[int64]int{}
for _, r := range list {
positions[r.ID] = r.Position
}
if positions[3] != 2 || positions[2] != 1 {
t.Errorf("positions = %v, want role 3 above role 2 (2 and 1)", positions)
}
if positions[1] != 100 {
t.Errorf("owner position = %d, want it untouched at 100", positions[1])
}
// Positions feed the hierarchy checks, so the cached role snapshots go.
if inv.invalidateAllN == 0 {
t.Error("InvalidateAll was not called after a reorder")
}
if len(hub.rolesUpdates) != 1 {
t.Errorf("roles_update broadcasts = %d, want 1", len(hub.rolesUpdates))
}
// "reorder" must not be parsed as a role id by the {id} route.
if hub.allVisibilityRefreshes != 0 {
t.Errorf("RefreshAllChannelVisibility called %d times for a reorder, want 0", hub.allVisibilityRefreshes)
}
}
// ─── broadcast fan-out must survive request cancellation ────────────────────
// TestBroadcastRoles_SurvivesCanceledRequestContext pins OC-0170:
// broadcastRoles re-reads the role list with r.Context() AFTER the mutation
// (create/update/delete/reorder) has already committed. If the admin's
// request is aborted (tab closed, deadline fired) in that window, the re-read
// must not ride the same now-canceled context, or the roles_update broadcast
// is silently skipped and every connected client keeps the stale role list.
// This mirrors OC-0139's fix for broadcastEmojiSet in api/emoji_handler.go
// and the analogous fix for broadcastDMOpen in api/dm_handler.go.
func TestBroadcastRoles_SurvivesCanceledRequestContext(t *testing.T) {
database := openAdminTestDB(t)
hub := &mockHub{}
ctx, cancel := context.WithCancel(context.Background())
cancel() // the request was already aborted by the time the commit lands
admin.BroadcastRolesForTest(ctx, database, hub)
if len(hub.rolesUpdates) != 1 {
t.Fatalf("roles_update broadcasts = %d, want 1 (fan-out must survive a canceled request context)", len(hub.rolesUpdates))
}
if len(hub.rolesUpdates[0]) != 3 {
t.Errorf("broadcast carried %d roles, want the seeded 3", len(hub.rolesUpdates[0]))
}
}
func TestAdminAPI_ReorderRoles_PartialListRefused(t *testing.T) {
database := openAdminTestDB(t)
handler, hub, _, token := newRolesHandler(t, database)
w := doRequest(t, handler, http.MethodPatch, "/roles/reorder", token, map[string]any{
"role_ids": []int64{3},
})
if w.Code != http.StatusBadRequest {
t.Errorf("status = %d, want 400; body: %s", w.Code, w.Body.String())
}
if len(hub.rolesUpdates) != 0 {
t.Error("a refused reorder must not broadcast")
}
}