Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Log onAuthenticate rejections to the structured log (#3381)
Andrew Mikofalvyf0a7b08e5ecf
diff --git a/.changeset/auth-rejection-structured-log.md b/.changeset/auth-rejection-structured-log.mdnew file mode 100644index 000000000..a450e9fef--- /dev/null+++ b/.changeset/auth-rejection-structured-log.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++When the server refuses a document's realtime connection, it now writes a timestamped line to the diagnostic log saying why. Previously those refusals went only to an untimestamped stderr file, so a bug report from a workspace where every document had gone unreachable carried no record of the refusal that caused it and the cause could only be guessed at. The new line names the reason plus the claimed and current value that disagreed, which is what turns that guess into an answer. Nothing about which connections are accepted or refused changed.diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.tsindex bf370cab7..718e05fb7 100644--- a/packages/server/src/server-factory.test.ts+++ b/packages/server/src/server-factory.test.ts@@ -2258,6 +2258,154 @@ describe("createServer() — onAuthenticate rejects 'branch-mismatch'", () => {});});+// ---------------------------------------------------------------------------+// A rejection thrown out of onAuthenticate refuses a document's WebSocket+// connection. Without a structured record it surfaces only as untimestamped+// Hocuspocus stderr, which cannot be bound to the session it wedged — so the+// warn line is the diagnostic surface, not a nicety.+// ---------------------------------------------------------------------------+describe('createServer() — onAuthenticate rejections reach the structured log', () => {+ let tmpDir: string;+ let logCapture: ReturnType<typeof captureAllLoggers>;++ beforeEach(async () => {+ tmpDir = await mkdtemp(join(tmpdir(), 'ok-auth-log-'));+ // Must precede createServer(): the factory resolves its logger once, at+ // construction time.+ logCapture = captureAllLoggers();+ });+ afterEach(async () => {+ loggerFactory.reset();+ await rm(tmpDir, { recursive: true, force: true });+ });++ function getAuthExtension(server: Awaited<ReturnType<typeof createServer>>): {+ onAuthenticate: (payload: unknown) => Promise<void>;+ } {+ const ext = server.hocuspocus.configuration.extensions.find(+ (e) => (e as { __kind?: string }).__kind === 'principal-auth',+ ) as { onAuthenticate: (payload: unknown) => Promise<void> } | undefined;+ if (!ext) throw new Error('expected principalAuthExtension on hocuspocus.configuration');+ return ext;+ }++ test('branch-mismatch rejection emits a warn carrying claimed and current branch', async () => {+ const server = createServer({ contentDir: tmpDir, projectDir: tmpDir, quiet: true });+ try {+ await server.ready;+ const authExt = getAuthExtension(server);++ await expect(+ authExt.onAuthenticate({+ token: JSON.stringify({ principalId: 'p-1', expectedBranch: 'feature' }),+ context: {},+ documentName: 'notes/alpha',+ }),+ ).rejects.toMatchObject({ reason: 'branch-mismatch' });++ const warns = logCapture.getCalls('warn', '[auth-rejection]');+ expect(warns).toHaveLength(1);+ expect(warns[0]?.msg).toBe('[auth-rejection] branch-mismatch');+ expect(warns[0]?.payload).toMatchObject({+ reason: 'branch-mismatch',+ docName: 'notes/alpha',+ claimedBranch: 'feature',+ currentBranch: 'main',+ });+ } finally {+ await server.destroy();+ }+ });++ test('server-instance-mismatch rejection emits a warn carrying both instance ids', async () => {+ const server = createServer({ contentDir: tmpDir, projectDir: tmpDir, quiet: true });+ try {+ await server.ready;+ const authExt = getAuthExtension(server);++ await expect(+ authExt.onAuthenticate({+ token: JSON.stringify({+ principalId: 'p-1',+ expectedServerInstanceId: 'stale-instance-from-prior-process',+ }),+ context: {},+ documentName: 'notes/beta',+ }),+ ).rejects.toMatchObject({ reason: 'server-instance-mismatch' });++ const warns = logCapture.getCalls('warn', '[auth-rejection]');+ expect(warns).toHaveLength(1);+ expect(warns[0]?.msg).toBe('[auth-rejection] server-instance-mismatch');+ expect(warns[0]?.payload).toMatchObject({+ reason: 'server-instance-mismatch',+ docName: 'notes/beta',+ claimedServerInstanceId: 'stale-instance-from-prior-process',+ currentServerInstanceId: server.serverInstanceId,+ });+ } finally {+ await server.destroy();+ }+ });++ test('an accepted connection emits no rejection warn', async () => {+ const server = createServer({ contentDir: tmpDir, projectDir: tmpDir, quiet: true });+ try {+ await server.ready;+ const authExt = getAuthExtension(server);++ await authExt.onAuthenticate({+ token: JSON.stringify({+ principalId: 'p-1',+ tabSessionId: 's-1',+ expectedBranch: 'main',+ expectedServerInstanceId: server.serverInstanceId,+ }),+ context: {},+ documentName: 'notes/gamma',+ });++ expect(logCapture.getCalls('warn', '[auth-rejection]')).toHaveLength(0);+ } finally {+ await server.destroy();+ }+ });++ test('config-doc admission denial emits a warn naming which gate fired', async () => {+ const server = createServer({ contentDir: tmpDir, projectDir: tmpDir, quiet: true });+ try {+ await server.ready;+ const guard = server.hocuspocus.configuration.extensions.find(+ (e) => (e as { __kind?: string }).__kind === 'config-doc-admission-guard',+ ) as { onAuthenticate: (payload: unknown) => Promise<void> } | undefined;+ if (!guard) throw new Error('expected configDocAdmissionGuard on hocuspocus.configuration');++ await expect(+ guard.onAuthenticate({+ token: undefined,+ context: {},+ documentName: '__config__/project',+ request: { socket: { remoteAddress: '203.0.113.7' }, headers: { host: 'evil.test' } },+ }),+ ).rejects.toThrow(/config-doc admission requires loopback peer/);++ const warns = logCapture.getCalls('warn', '[auth-rejection]');+ expect(warns).toHaveLength(1);+ expect(warns[0]?.payload).toMatchObject({+ reason: 'config-doc-admission-denied',+ docName: '__config__/project',+ check: 'peer',+ });+ // The offending peer address stays out of the structured fields — the+ // thrown message already carries it, and the log record is the+ // low-cardinality surface.+ expect(warns[0]?.payload).not.toHaveProperty('peer');+ } finally {+ await server.destroy();+ }+ });+});+// ---------------------------------------------------------------------------// Config-doc admission guard. The synthetic `__config__/project` and// `__user__/config.yml` Y.Docs are pre-materialized at boot and remaindiff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex 04741f7f6..9df004b89 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -61,7 +61,11 @@ import { AgentSessionManager } from './agent-sessions.ts';import { type CommentDocHooks, createApiExtension, isSafeDocName } from './api-extension.ts';import { assetReferencesChanged } from './asset-references.ts';import { seedBasenameIndex, seedSingleDirBasenameIndex } from './asset-walk.ts';-import { HocuspocusAuthRejection, parseHocuspocusAuthToken } from './auth-token-schema.ts';+import {+ HocuspocusAuthRejection,+ type HocuspocusAuthRejectionReason,+ parseHocuspocusAuthToken,+} from './auth-token-schema.ts';import { shellEscape } from './bash/shell-escape.ts';import { bootElapsedMs, recordBootPhase, setBootField } from './boot-timings.ts';import {@@ -1619,6 +1623,27 @@ export function createServer(options: ServerOptions): ServerInstance {});hocuspocus.configuration.extensions.push(liveDerivedIndexExtension);+ // A throw out of `onAuthenticate` refuses one document's WebSocket+ // connection, but Hocuspocus surfaces it only as untimestamped stderr —+ // nothing lands in the structured log, so a rejection that wedges a+ // workspace cannot afterwards be bound to the session it wedged. Emit the+ // record ourselves, immediately before each throw. Purely observational:+ // no rejection decision reads this path.+ //+ // Cardinality: `reason` is the bounded rejection vocabulary and `docName`+ // is pre-normalized. The claimed-vs-current pairs are client-supplied but+ // ride only on the rejection path, which is rare by construction and is+ // exactly the evidence a diagnosis needs. Raw peer addresses and Host+ // headers stay out — the thrown message already carries them.+ type AuthRejectionLogReason = HocuspocusAuthRejectionReason | 'config-doc-admission-denied';+ function logAuthRejection(+ reason: AuthRejectionLogReason,+ documentName: string | undefined,+ detail: Record<string, unknown> = {},+ ): void {+ log.warn({ reason, docName: documentName, ...detail }, `[auth-rejection] ${reason}`);+ }+// Browser tabs supply { principalId, tabSessionId } via the auth token.// onAuthenticate parses the JSON token and hoists identity into connection// context so persistence.resolveWriterFromOrigin sees source:'connection'@@ -1659,6 +1684,10 @@ export function createServer(options: ServerOptions): ServerInstance {// are accepted unconditionally for backward compat.const claimed = parsed?.expectedServerInstanceId;if (typeof claimed === 'string' && claimed.length > 0 && claimed !== serverInstanceId) {+ logAuthRejection('server-instance-mismatch', payload.documentName, {+ claimedServerInstanceId: claimed,+ currentServerInstanceId: serverInstanceId,+ });throw new HocuspocusAuthRejection('server-instance-mismatch',`server instance mismatch: client claimed ${claimed}, this server is ${serverInstanceId}`,@@ -1682,6 +1711,10 @@ export function createServer(options: ServerOptions): ServerInstance {claimedBranch.length > 0 &&claimedBranch !== currentBranch) {+ logAuthRejection('branch-mismatch', payload.documentName, {+ claimedBranch,+ currentBranch,+ });throw new HocuspocusAuthRejection('branch-mismatch',`branch mismatch: client claimed ${claimedBranch}, server is on ${currentBranch}`,@@ -1774,6 +1807,7 @@ export function createServer(options: ServerOptions): ServerInstance {};const peer = req.socket?.remoteAddress;if (peer !== undefined && !isLoopbackAddress(peer)) {+ logAuthRejection('config-doc-admission-denied', payload.documentName, { check: 'peer' });throw new Error(`config-doc admission requires loopback peer (peer=${peer}, doc=${payload.documentName})`,);@@ -1793,6 +1827,7 @@ export function createServer(options: ServerOptions): ServerInstance {options.remotePublicHost !== undefined &&hostHeaderMatchesPublicHost(host, options.remotePublicHost);if (!isAllowedWorkspaceHostHeader(host) && !remoteHostOk) {+ logAuthRejection('config-doc-admission-denied', payload.documentName, { check: 'host' });throw new Error(`config-doc admission requires a loopback or remote Host header (host=${host ?? '<absent>'}, doc=${payload.documentName})`,);