mirror of
https://github.com/J3vb/OwnCord.git
synced 2026-09-03 03:50:00 +03:00
* feat(auth): add revocable API tokens (bot/service auth) Add long-lived, revocable API tokens so headless clients (the introspection MCP tool, bots, CI) can authenticate without a password. Presented as "Authorization: Bearer <token>", a token authenticates as a specific user, inheriting that user's role and permissions. - migration 018 + dedicated api_tokens table (kept separate from sessions so bulk logout and the per-user session cap never touch these); only the SHA-256 hash is stored, raw token shown once at creation - auth.ResolveTokenHash: one shared bearer resolver that both AuthMiddleware and adminAuthMiddleware now call. Sessions are matched first so existing login behavior is unchanged; API tokens are a fallback only on session miss. A DB outage is returned wrapped, never mistaken for a bad token. - `server token create|list|revoke` CLI: mints directly against the DB with no HTTP and no login — the password-free bootstrap path - tests: resolver (8 cases incl. outage-not-fallthrough), db queries (6), api middleware integration (valid + revoked token) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(tools): add owncord-introspect MCP server A local MCP dev tool that lets Claude Code introspect a running OwnCord instance: read its logs, query any REST endpoint, and tail the desktop client's log file. It is a thin wrapper over the existing API plus the client log — no new product surface. - tools/mcp-introspect/index.mjs (Node/ESM, one dep: @modelcontextprotocol/sdk) exposes api_request (full read-write passthrough), server_logs (admin SSE ring-buffer stream), client_logs (reads the desktop log file) - authenticates with an API token (OWNCORD_API_TOKEN); pins the self-signed cert and skips hostname checks (the cert has no SAN) - registered in .mcp.json (secret-free ${OWNCORD_API_TOKEN}) - un-ignore tools/mcp-introspect/ so this shared dev tool is committed, while tools/livekit-server.exe and node_modules stay ignored - docs/mcp-introspect.md: how it works, tool reference, setup, troubleshooting Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(dependencies): update and add various crate versions in Cargo.lock * feat(admin): manage API tokens from the admin panel Add Owner-gated HTTP endpoints and a UI card to create, list, and revoke API tokens from the web admin panel. Previously only the `server token` CLI could manage them, which requires shell access to the host. - POST|GET|DELETE /admin/api/tokens in admin/handlers_tokens.go, wired in admin/api.go. All three are Owner-only (ownerOnlyMiddleware, like backups/updates): an HTTP token-mint endpoint is a network-reachable credential-minting surface, and API tokens deliberately survive password change + bulk logout, so a hijacked admin session must not mint one. - Reuses the same db.*APIToken calls as the CLI; create sources the actor from request context (audits who clicked, not the bound user); the raw token is returned once in the 201 body, never stored. - Add json tags to db.APITokenListItem for snake_case wire consistency. - Admin panel: "API Tokens" nav item + create modal, show-once reveal, revoke confirm in admin/static/index.html. - Tests: 7 in admin/api_test.go (+api_tokens table in the in-memory schema). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * refactor: modernize to Go 1.26 idioms + enable modernize linter Apply `golangci-lint modernize` autofixes across the server and enable the linter in .golangci.yml so these stop re-accumulating (they built up only because modernize was never in the config). Production code: slices.Contains for hand-rolled membership loops (api router, ws origin, db/account, plugin manifest); strings.SplitSeq for allocation-free line/segment iteration (db/migrate, updater, livekit_proxy); strings.Cut (config); fmt.Appendf (dm_handler); min() (event_pruner); any (ws client). Tests: range-over-int, t.Context(), WaitGroup.Go, slices.Sort, maps.Copy, new(expr), interface{}->any. - plugin/manifest.go parent-traversal check applied by hand: modernize skipped it (two conflicting rewrites); used the slices.Contains form. - Removed the now-dead ptr() test helper after newexpr inlined its callers. - Dropped dangling sort imports left by the sort.Slice->slices.Sort rewrite. No behavior change. All four tag variants build, full test suite is green, and golangci-lint (with modernize enabled) reports 0 issues. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
333 lines
9.6 KiB
Go
333 lines
9.6 KiB
Go
package db_test
|
|
|
|
import (
|
|
"encoding/json"
|
|
"testing"
|
|
|
|
"github.com/owncord/server/db"
|
|
)
|
|
|
|
// ─── Role JSON round-trip ────────────────────────────────────────────────────
|
|
|
|
func TestRole_JSONRoundTrip(t *testing.T) {
|
|
color := "#ff0000"
|
|
original := db.Role{
|
|
ID: 1,
|
|
Name: "admin",
|
|
Color: &color,
|
|
Permissions: 0x40000000,
|
|
Position: 100,
|
|
IsDefault: false,
|
|
}
|
|
|
|
data, err := json.Marshal(original)
|
|
if err != nil {
|
|
t.Fatalf("Marshal: %v", err)
|
|
}
|
|
|
|
var decoded db.Role
|
|
if err := json.Unmarshal(data, &decoded); err != nil {
|
|
t.Fatalf("Unmarshal: %v", err)
|
|
}
|
|
|
|
if decoded.ID != original.ID {
|
|
t.Errorf("ID = %d, want %d", decoded.ID, original.ID)
|
|
}
|
|
if decoded.Name != original.Name {
|
|
t.Errorf("Name = %q, want %q", decoded.Name, original.Name)
|
|
}
|
|
if decoded.Color == nil || *decoded.Color != color {
|
|
t.Errorf("Color = %v, want %q", decoded.Color, color)
|
|
}
|
|
if decoded.Permissions != original.Permissions {
|
|
t.Errorf("Permissions = %d, want %d", decoded.Permissions, original.Permissions)
|
|
}
|
|
if decoded.Position != original.Position {
|
|
t.Errorf("Position = %d, want %d", decoded.Position, original.Position)
|
|
}
|
|
if decoded.IsDefault != original.IsDefault {
|
|
t.Errorf("IsDefault = %v, want %v", decoded.IsDefault, original.IsDefault)
|
|
}
|
|
}
|
|
|
|
func TestRole_JSONKeys(t *testing.T) {
|
|
role := db.Role{ID: 1, Name: "member", Permissions: 3, Position: 1, IsDefault: true}
|
|
data, _ := json.Marshal(role)
|
|
|
|
var raw map[string]json.RawMessage
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
t.Fatalf("Unmarshal to map: %v", err)
|
|
}
|
|
|
|
expectedKeys := []string{"id", "name", "color", "permissions", "position", "is_default"}
|
|
for _, k := range expectedKeys {
|
|
if _, ok := raw[k]; !ok {
|
|
t.Errorf("missing JSON key %q", k)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRole_NilColor(t *testing.T) {
|
|
role := db.Role{ID: 1, Name: "member"}
|
|
data, _ := json.Marshal(role)
|
|
|
|
var raw map[string]any
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
t.Fatalf("Unmarshal: %v", err)
|
|
}
|
|
|
|
if raw["color"] != nil {
|
|
t.Errorf("nil Color should serialize as null, got %v", raw["color"])
|
|
}
|
|
}
|
|
|
|
// ─── Channel JSON round-trip ─────────────────────────────────────────────────
|
|
|
|
func TestChannel_JSONRoundTrip(t *testing.T) {
|
|
quality := "high"
|
|
threshold := 10
|
|
original := db.Channel{
|
|
ID: 42,
|
|
Name: "general",
|
|
Type: "text",
|
|
Category: "Main",
|
|
Topic: "General chat",
|
|
Position: 0,
|
|
SlowMode: 5,
|
|
Archived: false,
|
|
CreatedAt: "2026-01-01T00:00:00Z",
|
|
VoiceMaxUsers: 25,
|
|
VoiceQuality: &quality,
|
|
MixingThreshold: &threshold,
|
|
VoiceMaxVideo: 4,
|
|
}
|
|
|
|
data, err := json.Marshal(original)
|
|
if err != nil {
|
|
t.Fatalf("Marshal: %v", err)
|
|
}
|
|
|
|
var decoded db.Channel
|
|
if err := json.Unmarshal(data, &decoded); err != nil {
|
|
t.Fatalf("Unmarshal: %v", err)
|
|
}
|
|
|
|
if decoded.ID != original.ID || decoded.Name != original.Name {
|
|
t.Errorf("basic fields mismatch: got ID=%d Name=%q", decoded.ID, decoded.Name)
|
|
}
|
|
if decoded.VoiceQuality == nil || *decoded.VoiceQuality != quality {
|
|
t.Errorf("VoiceQuality = %v, want %q", decoded.VoiceQuality, quality)
|
|
}
|
|
if decoded.MixingThreshold == nil || *decoded.MixingThreshold != threshold {
|
|
t.Errorf("MixingThreshold = %v, want %d", decoded.MixingThreshold, threshold)
|
|
}
|
|
}
|
|
|
|
func TestChannel_OmitEmptyFields(t *testing.T) {
|
|
ch := db.Channel{ID: 1, Name: "voice-1", Type: "voice"}
|
|
data, _ := json.Marshal(ch)
|
|
|
|
var raw map[string]json.RawMessage
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
t.Fatalf("Unmarshal: %v", err)
|
|
}
|
|
|
|
// voice_quality and mixing_threshold have omitempty — should be absent when nil.
|
|
if _, ok := raw["voice_quality"]; ok {
|
|
t.Error("nil VoiceQuality should be omitted")
|
|
}
|
|
if _, ok := raw["mixing_threshold"]; ok {
|
|
t.Error("nil MixingThreshold should be omitted")
|
|
}
|
|
}
|
|
|
|
// ─── VoiceState JSON ─────────────────────────────────────────────────────────
|
|
|
|
func TestVoiceState_JoinedAtOmittedFromJSON(t *testing.T) {
|
|
vs := db.VoiceState{
|
|
UserID: 1,
|
|
ChannelID: 2,
|
|
Username: "alice",
|
|
JoinedAt: "2026-01-01T00:00:00Z",
|
|
}
|
|
|
|
data, _ := json.Marshal(vs)
|
|
var raw map[string]json.RawMessage
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
t.Fatalf("Unmarshal: %v", err)
|
|
}
|
|
|
|
if _, ok := raw["JoinedAt"]; ok {
|
|
t.Error("JoinedAt has json:\"-\" tag and should not appear in JSON output")
|
|
}
|
|
if _, ok := raw["joined_at"]; ok {
|
|
t.Error("JoinedAt should not appear under any key in JSON output")
|
|
}
|
|
}
|
|
|
|
func TestVoiceState_BoolDefaults(t *testing.T) {
|
|
vs := db.VoiceState{UserID: 1, ChannelID: 2, Username: "bob"}
|
|
data, _ := json.Marshal(vs)
|
|
|
|
var decoded db.VoiceState
|
|
if err := json.Unmarshal(data, &decoded); err != nil {
|
|
t.Fatalf("Unmarshal: %v", err)
|
|
}
|
|
|
|
if decoded.Muted || decoded.Deafened || decoded.Speaking || decoded.Camera || decoded.Screenshare {
|
|
t.Error("zero-value VoiceState bools should all be false")
|
|
}
|
|
}
|
|
|
|
// ─── MessageAPIResponse JSON ─────────────────────────────────────────────────
|
|
|
|
func TestMessageAPIResponse_JSONKeys(t *testing.T) {
|
|
resp := db.MessageAPIResponse{
|
|
ID: 1,
|
|
ChannelID: 2,
|
|
User: db.UserPublic{ID: 3, Username: "alice"},
|
|
Content: "hello",
|
|
Attachments: []db.AttachmentInfo{},
|
|
Reactions: []db.ReactionInfo{},
|
|
Timestamp: "2026-01-01T00:00:00Z",
|
|
}
|
|
|
|
data, _ := json.Marshal(resp)
|
|
var raw map[string]json.RawMessage
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
t.Fatalf("Unmarshal: %v", err)
|
|
}
|
|
|
|
required := []string{
|
|
"id", "channel_id", "user", "content", "reply_to",
|
|
"attachments", "reactions", "pinned", "edited_at", "deleted", "timestamp",
|
|
}
|
|
for _, k := range required {
|
|
if _, ok := raw[k]; !ok {
|
|
t.Errorf("missing required JSON key %q", k)
|
|
}
|
|
}
|
|
}
|
|
|
|
// ─── AttachmentInfo omitempty ─────────────────────────────────────────────────
|
|
|
|
func TestAttachmentInfo_OmitsNilDimensions(t *testing.T) {
|
|
att := db.AttachmentInfo{
|
|
ID: "abc", Filename: "doc.pdf", Size: 1024, Mime: "application/pdf", URL: "/files/abc",
|
|
}
|
|
data, _ := json.Marshal(att)
|
|
|
|
var raw map[string]json.RawMessage
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
t.Fatalf("Unmarshal: %v", err)
|
|
}
|
|
|
|
if _, ok := raw["width"]; ok {
|
|
t.Error("nil Width should be omitted")
|
|
}
|
|
if _, ok := raw["height"]; ok {
|
|
t.Error("nil Height should be omitted")
|
|
}
|
|
}
|
|
|
|
func TestAttachmentInfo_IncludesDimensions(t *testing.T) {
|
|
w, h := 1920, 1080
|
|
att := db.AttachmentInfo{
|
|
ID: "abc", Filename: "img.png", Size: 2048, Mime: "image/png",
|
|
URL: "/files/abc", Width: &w, Height: &h,
|
|
}
|
|
data, _ := json.Marshal(att)
|
|
|
|
var raw map[string]json.RawMessage
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
t.Fatalf("Unmarshal: %v", err)
|
|
}
|
|
|
|
if _, ok := raw["width"]; !ok {
|
|
t.Error("non-nil Width should be present")
|
|
}
|
|
if _, ok := raw["height"]; !ok {
|
|
t.Error("non-nil Height should be present")
|
|
}
|
|
}
|
|
|
|
// ─── UserPublic omitempty ────────────────────────────────────────────────────
|
|
|
|
func TestUserPublic_OmitsNilAvatar(t *testing.T) {
|
|
u := db.UserPublic{ID: 1, Username: "alice"}
|
|
data, _ := json.Marshal(u)
|
|
|
|
var raw map[string]json.RawMessage
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
t.Fatalf("Unmarshal: %v", err)
|
|
}
|
|
|
|
if _, ok := raw["avatar"]; ok {
|
|
t.Error("nil Avatar should be omitted")
|
|
}
|
|
}
|
|
|
|
func TestUserPublic_IncludesAvatar(t *testing.T) {
|
|
av := "avatar.png"
|
|
u := db.UserPublic{ID: 1, Username: "alice", Avatar: &av}
|
|
data, _ := json.Marshal(u)
|
|
|
|
var raw map[string]json.RawMessage
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
t.Fatalf("Unmarshal: %v", err)
|
|
}
|
|
|
|
if _, ok := raw["avatar"]; !ok {
|
|
t.Error("non-nil Avatar should be present")
|
|
}
|
|
}
|
|
|
|
// ─── ServerStats JSON ────────────────────────────────────────────────────────
|
|
|
|
func TestServerStats_JSONRoundTrip(t *testing.T) {
|
|
original := db.ServerStats{
|
|
UserCount: 150,
|
|
MessageCount: 50000,
|
|
ChannelCount: 20,
|
|
InviteCount: 5,
|
|
DBSizeBytes: 1048576,
|
|
OnlineCount: 42,
|
|
}
|
|
|
|
data, err := json.Marshal(original)
|
|
if err != nil {
|
|
t.Fatalf("Marshal: %v", err)
|
|
}
|
|
|
|
var decoded db.ServerStats
|
|
if err := json.Unmarshal(data, &decoded); err != nil {
|
|
t.Fatalf("Unmarshal: %v", err)
|
|
}
|
|
|
|
if decoded != original {
|
|
t.Errorf("round-trip mismatch:\n got %+v\n want %+v", decoded, original)
|
|
}
|
|
}
|
|
|
|
// ─── AuditEntry JSON ─────────────────────────────────────────────────────────
|
|
|
|
func TestAuditEntry_JSONKeys(t *testing.T) {
|
|
entry := db.AuditEntry{
|
|
ID: 1, ActorID: 2, ActorName: "admin", Action: "ban_user",
|
|
TargetType: "user", TargetID: 3, Detail: "reason", CreatedAt: "2026-01-01",
|
|
}
|
|
|
|
data, _ := json.Marshal(entry)
|
|
var raw map[string]json.RawMessage
|
|
if err := json.Unmarshal(data, &raw); err != nil {
|
|
t.Fatalf("Unmarshal: %v", err)
|
|
}
|
|
|
|
required := []string{"id", "actor_id", "actor_name", "action", "target_type", "target_id", "detail", "created_at"}
|
|
for _, k := range required {
|
|
if _, ok := raw[k]; !ok {
|
|
t.Errorf("missing JSON key %q", k)
|
|
}
|
|
}
|
|
}
|