Files
OwnCord/Server/auth/resolve_test.go
T
J3vbandClaude Opus 4.8 58005c9c6f feat(auth): revocable API tokens, introspect MCP server, and a Go 1.26 idiom pass (#1266)
* 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>
2026-07-29 13:25:46 +02:00

161 lines
4.8 KiB
Go

package auth_test
import (
"context"
"errors"
"testing"
"time"
"github.com/owncord/server/auth"
"github.com/owncord/server/db"
)
// fakeStore is a hand-rolled tokenStore so the security-critical resolution
// logic is tested without a real database. It satisfies the (unexported)
// tokenStore interface structurally when passed to auth.ResolveTokenHash.
type fakeStore struct {
sess *db.Session
sessErr error
apiTok *db.APIToken
apiErr error
user *db.User
userErr error
role *db.Role
roleErr error
apiCalled bool // set when the API-token fallback is consulted
}
func (f *fakeStore) GetSessionByTokenHash(_ context.Context, _ string) (*db.Session, error) {
return f.sess, f.sessErr
}
func (f *fakeStore) GetActiveAPIToken(_ context.Context, _ string) (*db.APIToken, error) {
f.apiCalled = true
return f.apiTok, f.apiErr
}
func (f *fakeStore) GetUserByID(_ context.Context, _ int64) (*db.User, error) {
return f.user, f.userErr
}
func (f *fakeStore) GetRoleByID(_ context.Context, _ int64) (*db.Role, error) {
return f.role, f.roleErr
}
func future() string { return time.Now().Add(time.Hour).UTC().Format("2006-01-02T15:04:05Z") }
func past() string { return time.Now().Add(-time.Hour).UTC().Format("2006-01-02T15:04:05Z") }
func TestResolveTokenHash(t *testing.T) {
dbErr := errors.New("db down")
user := &db.User{ID: 7, RoleID: 3}
role := &db.Role{ID: 3}
tests := []struct {
name string
store *fakeStore
wantErr error // nil = success; dbErr = wrapped (non-sentinel) DB error; else a sentinel
wantUser bool
wantSessionNil bool // only checked on success
wantAPICalled bool
}{
{
name: "valid session resolves without consulting api tokens",
store: &fakeStore{sess: &db.Session{UserID: 7, ExpiresAt: future()}, user: user, role: role},
wantErr: nil,
wantUser: true,
},
{
name: "expired session returns ErrTokenExpired",
store: &fakeStore{sess: &db.Session{UserID: 7, ExpiresAt: past()}},
wantErr: auth.ErrTokenExpired,
},
{
name: "session miss falls through to active api token",
store: &fakeStore{sess: nil, apiTok: &db.APIToken{UserID: 7}, user: user, role: role},
wantErr: nil,
wantUser: true,
wantSessionNil: true,
wantAPICalled: true,
},
{
name: "no session and no active api token is ErrTokenNotFound",
store: &fakeStore{sess: nil, apiTok: nil},
wantErr: auth.ErrTokenNotFound,
wantAPICalled: true,
},
{
name: "api-token user missing is ErrUserNotFound",
store: &fakeStore{sess: nil, apiTok: &db.APIToken{UserID: 7}, user: nil},
wantErr: auth.ErrUserNotFound,
wantAPICalled: true,
},
{
name: "missing role is ErrRoleNotFound",
store: &fakeStore{sess: &db.Session{UserID: 7, ExpiresAt: future()}, user: user, role: nil},
wantErr: auth.ErrRoleNotFound,
},
{
name: "db error on session lookup does not fall through to api tokens",
store: &fakeStore{sessErr: dbErr},
wantErr: dbErr,
// wantAPICalled stays false: an outage must never be treated as a session miss.
},
{
name: "db error on api-token lookup is surfaced, not swallowed",
store: &fakeStore{sess: nil, apiErr: dbErr},
wantErr: dbErr,
wantAPICalled: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
u, gotRole, sess, err := auth.ResolveTokenHash(context.Background(), tc.store, "hash")
switch {
case tc.wantErr == nil:
if err != nil {
t.Fatalf("want success, got error %v", err)
}
if gotRole == nil {
t.Fatal("want role on success, got nil")
}
if tc.wantSessionNil && sess != nil {
t.Fatalf("want nil session for api-token principal, got %+v", sess)
}
if !tc.wantSessionNil && sess == nil {
t.Fatal("want session for session principal, got nil")
}
case errors.Is(tc.wantErr, dbErr):
if !errors.Is(err, dbErr) {
t.Fatalf("want wrapped db error, got %v", err)
}
// A DB outage must never masquerade as a sentinel outcome.
for _, s := range []error{auth.ErrTokenNotFound, auth.ErrTokenExpired, auth.ErrUserNotFound, auth.ErrRoleNotFound} {
if errors.Is(err, s) {
t.Fatalf("db error must not be sentinel %v", s)
}
}
default:
if !errors.Is(err, tc.wantErr) {
t.Fatalf("want %v, got %v", tc.wantErr, err)
}
}
if errors.Is(err, auth.ErrTokenExpired) && sess == nil {
t.Fatal("expired session must be returned so the caller can clean it up")
}
if tc.wantUser && u == nil {
t.Fatal("want user, got nil")
}
if !tc.wantUser && u != nil {
t.Fatalf("want nil user, got %+v", u)
}
if tc.store.apiCalled != tc.wantAPICalled {
t.Fatalf("api-token fallback called = %v, want %v", tc.store.apiCalled, tc.wantAPICalled)
}
})
}
}