Skip to content

Implement surgical security and robustness improvements - #264

Closed
RinZ27 wants to merge 1 commit into
rohitg00:mainfrom
RinZ27:security-robustness-improvements
Closed

RinZ27 wants to merge 1 commit into
rohitg00:mainfrom
RinZ27:security-robustness-improvements

Conversation

@RinZ27

@RinZ27 RinZ27 commented May 10, 2026 •

Copy link
Copy Markdown

Several architectural hardening measures have been implemented to improve the system's resilience against common exploit vectors. These changes focus on the internal viewer's proxy security and file system integrity during persistence operations.

Key updates:

  • Enforced secret-based authentication for the viewer's proxy server. It now strictly validates the Authorization header before relaying requests to the memory REST API, preventing unauthenticated memory manipulation.
  • Implemented symlink protection in snapshot.ts and claude-bridge.ts. Using O_NOFOLLOW during file creation ensures that memory exports and state snapshots cannot be redirected to overwrite sensitive system files.
  • Added credential masking for the engine URL in startup logs. This prevents potential leakage of authentication details when the engine URL contains embedded userInfo.
  • Sanitized log outputs in the viewer server to mitigate log injection risks by stripping newline characters from request paths before logging.

Summary by CodeRabbit

  • Security

    • Enforced Bearer-token checks across endpoints when a secret is set.
    • Engine URL logging is redacted to hide credentials.
    • Request paths are sanitized in error logs.
    • Improved timing-safe authorization comparisons.
  • Bug Fixes / Reliability

    • Safer on-disk writes for memory and snapshot files to reduce file-related risks.
  • Tests

    • Updated tests to cover the new file-write and auth behaviors.

Review Change Stack

@vercel

vercel Bot commented May 10, 2026

Copy link
Copy Markdown

@RinZ27 is attempting to deploy a commit to the rohitg00's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented May 10, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR hardens file write operations by replacing direct path-based writes with secure file descriptor patterns using openSync and restrictive POSIX flags. Server authentication enforces Bearer token validation, sensitive credentials are redacted from logs, and request paths are sanitized to prevent log injection attacks.

Changes

Security Hardening Across File Writes, Authentication, and Logging

Layer / File(s) Summary
Constant-time compare
src/auth.ts
timingSafeCompare now rejects differing lengths and compares raw bytes via Buffer + timingSafeEqual.
Secure File Write Pattern
src/functions/claude-bridge.ts, src/functions/snapshot.ts
fs imports expanded; memory and snapshot writes use openSync with O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, then writeFileSync(fd, ...) and closeSync(fd) in finally.
Viewer server auth & sanitization
src/viewer/server.ts
When secret is set, Authorization must use Bearer ; token is extracted and validated via timingSafeCompare; invalid requests return 401. Proxy error logging sanitizes CR/LF in pathnames.
MCP & Triggers Bearer parsing
src/mcp/server.ts, src/triggers/api.ts
Authorization header parsing updated to require "Bearer " and compare only the extracted token with timingSafeCompare (applied in middleware and endpoint checks).
Engine URL redaction
src/index.ts
Startup log masks credentials in config.engineUrl by replacing the substring between // and @ with *** when @ exists.
Test mock updates
test/claude-bridge.test.ts, test/snapshot.test.ts
node:fs Vitest mocks extended with constants, openSync, and closeSync; tests assert open/write/close calls using the fixed mock fd.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

A rabbit hops through files with care,
Opens doors with flags that never snare,
Tokens compared with steady paws,
URLs masked and paths kept fair,
Logs now rest — a tidy burrow’s air. 🐰✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.69% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Implement surgical security and robustness improvements' is generic and vague. While related to the changeset, it doesn't convey the primary changes such as authentication enforcement, symlink protection, or credential masking. Consider using a more specific title that highlights the main change, such as 'Add authentication, symlink protection, and credential masking' or similar.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (2)
test/snapshot.test.ts (1)

33-39: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Test mocks should include closeSync to verify resource cleanup.

Same issue as in test/claude-bridge.test.ts: the mock should include closeSync and verify it's called to ensure the file descriptor is properly released.

🧪 Enhanced mock with closeSync verification
 vi.mock("node:fs", () => ({
   existsSync: vi.fn().mockReturnValue(true),
   mkdirSync: vi.fn(),
   writeFileSync: vi.fn(),
   readFileSync: vi
     .fn()
     .mockReturnValue('{"version":"0.4.0","sessions":[],"memories":[]}'),
   constants: {
     O_WRONLY: 1,
     O_CREAT: 2,
     O_TRUNC: 4,
     O_NOFOLLOW: 8,
   },
   openSync: vi.fn().mockReturnValue(123),
+  closeSync: vi.fn(),
 }));

Then verify in the snapshot creation test:

+import { closeSync } from "node:fs";
+
 it("snapshot-create serializes state and returns meta", async () => {
   const result = (await sdk.trigger("mem::snapshot-create", {
     message: "Test snapshot",
   })) as { success: boolean; snapshot: SnapshotMeta };

   expect(result.success).toBe(true);
+  expect(closeSync).toHaveBeenCalledWith(123);
   // ... rest of test
 });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/snapshot.test.ts` around lines 33 - 39, Add a mock for closeSync
alongside openSync in the test's fs mock (the constants object and openSync mock
already present) and update the snapshot creation test to assert that the mocked
closeSync was called to verify the file descriptor was released; specifically,
add a vi.fn() mock named closeSync where openSync is mocked and then add an
expectation like expect(closeSync).toHaveBeenCalled() in the relevant snapshot
creation test to ensure resource cleanup is verified.
src/functions/snapshot.ts (1)

78-84: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

File descriptor leak: missing closeSync after write.

Identical to the issue in claude-bridge.ts, the file descriptor from openSync is never closed, causing a resource leak on every mem::snapshot-create invocation.

🔒 Proposed fix with explicit close
+import { existsSync, mkdirSync, writeFileSync, readFileSync, constants, openSync, closeSync } from "node:fs";
 const stateContent = JSON.stringify(state, null, 2);
 const statePath = join(snapshotDir, "state.json");
 const fd = openSync(
   statePath,
   constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW,
 );
-writeFileSync(fd, stateContent, "utf-8");
+try {
+  writeFileSync(fd, stateContent, "utf-8");
+} finally {
+  closeSync(fd);
+}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/functions/snapshot.ts` around lines 78 - 84, The state file descriptor
opened via openSync (fd) is never closed, causing a leak; update the snapshot
creation in src/functions/snapshot.ts (around stateContent/statePath/fd) to
ensure the descriptor is closed after writing (e.g., wrap the writeFileSync call
in a try/finally and call closeSync(fd) in the finally, or avoid openSync
entirely and write directly to statePath), so fd is always closed even on
errors.
🧹 Nitpick comments (1)
src/viewer/server.ts (1)

108-114: 💤 Low value

Consider extracting the token before comparison.

While the current implementation works, it compares the entire Authorization header including the Bearer prefix. Standard practice is to validate the scheme separately, then extract and compare just the token. This makes the validation more robust against whitespace variations.

♻️ More flexible token validation
 if (secret) {
   const auth = req.headers["authorization"];
-  if (typeof auth !== "string" || !timingSafeCompare(auth, `Bearer ${secret}`)) {
+  const expectedScheme = "Bearer ";
+  if (
+    typeof auth !== "string" ||
+    !auth.startsWith(expectedScheme) ||
+    !timingSafeCompare(auth.slice(expectedScheme.length).trim(), secret)
+  ) {
     json(res, 401, { error: "unauthorized" }, req);
     return;
   }
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/viewer/server.ts` around lines 108 - 114, Extract and validate the Bearer
token separately before calling timingSafeCompare: read
req.headers["authorization"] into a variable, verify it's a string and starts
with the "Bearer " scheme (handle casing/whitespace by trimming and using
.startsWith or splitting on whitespace), extract the token portion (everything
after "Bearer "), then call timingSafeCompare(token, secret); if checks fail
call json(res, 401, { error: "unauthorized" }, req) and return. This change
should be applied in the same block that currently references secret,
req.headers["authorization"], timingSafeCompare, and json.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/functions/claude-bridge.ts`:
- Around line 142-146: The code opens a file descriptor with openSync (using
constants.O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW) and calls writeFileSync(fd,
md, "utf-8") but never closes the descriptor; import closeSync from node:fs and
change the write to ensure the fd is always closed by wrapping the writeFileSync
call in a try/finally (or equivalent) that calls closeSync(fd) in the finally
block; update the imports and ensure the logic around config.memoryFilePath,
openSync, writeFileSync and closeSync is adjusted accordingly to prevent file
descriptor leaks.

In `@test/claude-bridge.test.ts`:
- Around line 12-18: Add a mocked closeSync alongside the existing openSync and
constants in the test's fs mock (e.g., add closeSync: vi.fn()), keep
openSync.mockReturnValue(123) as-is, and update the sync write test to assert
closeSync was called (for example
expect(mockFs.closeSync).toHaveBeenCalledWith(123) or
expect(mockFs.closeSync).toHaveBeenCalled()). This ensures the implementation
calls closeSync after writes and the test will catch file descriptor leaks.

---

Duplicate comments:
In `@src/functions/snapshot.ts`:
- Around line 78-84: The state file descriptor opened via openSync (fd) is never
closed, causing a leak; update the snapshot creation in
src/functions/snapshot.ts (around stateContent/statePath/fd) to ensure the
descriptor is closed after writing (e.g., wrap the writeFileSync call in a
try/finally and call closeSync(fd) in the finally, or avoid openSync entirely
and write directly to statePath), so fd is always closed even on errors.

In `@test/snapshot.test.ts`:
- Around line 33-39: Add a mock for closeSync alongside openSync in the test's
fs mock (the constants object and openSync mock already present) and update the
snapshot creation test to assert that the mocked closeSync was called to verify
the file descriptor was released; specifically, add a vi.fn() mock named
closeSync where openSync is mocked and then add an expectation like
expect(closeSync).toHaveBeenCalled() in the relevant snapshot creation test to
ensure resource cleanup is verified.

---

Nitpick comments:
In `@src/viewer/server.ts`:
- Around line 108-114: Extract and validate the Bearer token separately before
calling timingSafeCompare: read req.headers["authorization"] into a variable,
verify it's a string and starts with the "Bearer " scheme (handle
casing/whitespace by trimming and using .startsWith or splitting on whitespace),
extract the token portion (everything after "Bearer "), then call
timingSafeCompare(token, secret); if checks fail call json(res, 401, { error:
"unauthorized" }, req) and return. This change should be applied in the same
block that currently references secret, req.headers["authorization"],
timingSafeCompare, and json.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9245273f-0c61-41c9-8ba0-3a00505f63c4

📥 Commits

Reviewing files that changed from the base of the PR and between 0322da8 and f2b76b7.

📒 Files selected for processing (6)
  • src/functions/claude-bridge.ts
  • src/functions/snapshot.ts
  • src/index.ts
  • src/viewer/server.ts
  • test/claude-bridge.test.ts
  • test/snapshot.test.ts

Comment thread src/functions/claude-bridge.ts Resolved
Comment thread test/claude-bridge.test.ts Resolved
@RinZ27
RinZ27 force-pushed the security-robustness-improvements branch from f2b76b7 to 7ef3afd Compare May 10, 2026 05:53

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/auth.ts`:
- Around line 6-10: In timingSafeCompare, create the buffers from the input
strings first (e.g., Buffer.from(a) and Buffer.from(b)), then compare their byte
lengths (bufA.length and bufB.length) and return false if they differ before
calling timingSafeEqual; update the function (timingSafeCompare) to check buffer
byte lengths rather than JavaScript string lengths so timingSafeEqual cannot
throw for differing byte-length inputs.

In `@src/mcp/server.ts`:
- Around line 54-58: The Bearer scheme check in the MCP auth path uses a
case-sensitive startsWith("Bearer ") which rejects valid variants; update the
logic that builds and checks prefix to compare the auth-scheme
case-insensitively (e.g., lowercasing the scheme portion of auth before
matching) and then perform timingSafeCompare on the token part (use auth.slice
after the scheme delimiter). Replace the local prefix/check in src/mcp/server.ts
(references: prefix, auth, timingSafeCompare) to call/reuse the existing
scheme/token parsing helper used by the REST auth path so both paths share the
same case-insensitive parsing behavior.

In `@src/triggers/api.ts`:
- Around line 39-43: The auth parsing is too strict: update checkAuth() to split
the Authorization header on whitespace (e.g., auth.trim().split(/\s+/)), verify
there are at least two parts, compare the scheme case-insensitively
(scheme.toLowerCase() === "bearer"), and then perform timingSafeCompare on the
rest joined as the token; apply the same change to the middleware handler that
currently uses prefix = "Bearer " so both places accept any case and multiple
spaces between scheme and credentials.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 56c2fd5e-6e7f-4eca-8b75-d988428737fb

📥 Commits

Reviewing files that changed from the base of the PR and between f2b76b7 and 7ef3afd.

📒 Files selected for processing (9)
  • src/auth.ts
  • src/functions/claude-bridge.ts
  • src/functions/snapshot.ts
  • src/index.ts
  • src/mcp/server.ts
  • src/triggers/api.ts
  • src/viewer/server.ts
  • test/claude-bridge.test.ts
  • test/snapshot.test.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/functions/claude-bridge.ts
  • test/claude-bridge.test.ts
  • test/snapshot.test.ts
  • src/functions/snapshot.ts
  • src/viewer/server.ts
  • src/index.ts

Comment thread src/auth.ts Resolved
Comment thread src/mcp/server.ts Resolved
Comment thread src/triggers/api.ts Resolved
@RinZ27
RinZ27 force-pushed the security-robustness-improvements branch from 7ef3afd to 663e25a Compare May 10, 2026 06:01

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/triggers/api.ts (1)

39-40: ⚡ Quick win

Consider stricter RFC 7235 compliance for Bearer token parsing.

The regex /^bearer\s+(.+)$/i is more permissive than RFC 7235/9110 requires. While it correctly handles case-insensitivity and multiple spaces (addressing the prior review), it deviates from the spec in two ways:

  1. \s+ matches any whitespace (tabs, form-feeds, etc.), but RFC 7235 specifies 1*SP (one or more ASCII space characters, U+0020 only)
  2. .+ accepts any token content, including embedded spaces, but RFC 7235 token68 allows only [A-Za-z0-9\-._~+/=]

While not a security risk (malformed tokens won't match the secret and will be rejected), adopting the helper function from the previous review would improve RFC compliance and fail fast on malformed input:

📋 Recommended refactor aligned with past review
+function extractBearerToken(auth: unknown): string | null {
+  if (typeof auth !== "string") return null;
+  const parts = auth.trim().split(/ +/);
+  if (parts.length !== 2 || parts[0].toLowerCase() !== "bearer") return null;
+  return parts[1];
+}
+
 function checkAuth(
   req: ApiRequest,
   secret: string | undefined,
 ): Response | null {
   if (!secret) return null;
   const auth = req.headers?.["authorization"] || req.headers?.["Authorization"];
-  const match = typeof auth === "string" ? auth.match(/^bearer\s+(.+)$/i) : null;
-  if (!match || !timingSafeCompare(match[1], secret)) {
+  const token = extractBearerToken(auth);
+  if (!token || !timingSafeCompare(token, secret)) {
     return { status_code: 401, body: { error: "unauthorized" } };
   }
   return null;
 }

Note: Changed split(/\s+/) to split(/ +/) to strictly match ASCII spaces per RFC 7235. The parts.length !== 2 check ensures tokens with embedded spaces are rejected.

Also applies to: 127-128

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/triggers/api.ts` around lines 39 - 40, The current bearer parsing uses a
permissive regex (/^bearer\s+(.+)$/i) that allows non-ASCII spaces and tokens
with embedded spaces; replace it with an RFC‑7235/token68 compliant parse: split
the Authorization header on a single-space delimiter (use split(/ +/) or
equivalent that matches ASCII SP only), verify there are exactly two parts and
the scheme equals "Bearer" (case-insensitive), then validate the token against
token68 characters (allowed set [A-Za-z0-9\-._~+/=]) before calling
timingSafeCompare(matchToken, secret); implement this as a small helper (e.g.,
parseBearerToken or validateToken68) and use it in place of the current match
variable logic so malformed headers fail fast.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/triggers/api.ts`:
- Around line 39-40: The current bearer parsing uses a permissive regex
(/^bearer\s+(.+)$/i) that allows non-ASCII spaces and tokens with embedded
spaces; replace it with an RFC‑7235/token68 compliant parse: split the
Authorization header on a single-space delimiter (use split(/ +/) or equivalent
that matches ASCII SP only), verify there are exactly two parts and the scheme
equals "Bearer" (case-insensitive), then validate the token against token68
characters (allowed set [A-Za-z0-9\-._~+/=]) before calling
timingSafeCompare(matchToken, secret); implement this as a small helper (e.g.,
parseBearerToken or validateToken68) and use it in place of the current match
variable logic so malformed headers fail fast.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c3f8a15c-d623-4a8b-ae5a-d98769f51427

📥 Commits

Reviewing files that changed from the base of the PR and between 7ef3afd and 663e25a.

📒 Files selected for processing (9)
  • src/auth.ts
  • src/functions/claude-bridge.ts
  • src/functions/snapshot.ts
  • src/index.ts
  • src/mcp/server.ts
  • src/triggers/api.ts
  • src/viewer/server.ts
  • test/claude-bridge.test.ts
  • test/snapshot.test.ts
✅ Files skipped from review due to trivial changes (1)
  • test/claude-bridge.test.ts
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/index.ts
  • src/functions/claude-bridge.ts
  • src/functions/snapshot.ts
  • src/mcp/server.ts
  • src/viewer/server.ts
  • test/snapshot.test.ts
  • src/auth.ts

possiblyneal pushed a commit to possiblyneal/agentmemory-sqlite that referenced this pull request Oct 4, 2026
…gets

Both used plain writeFileSync. Write a temp file in the same directory
(exclusive create) and rename over the target, and refuse a target that
is a symlink. Ref rohitg00#264.

Generated-By: Claude Sonnet 5.5
@rohitg00

rohitg00 commented Nov 9, 2026

Copy link
Copy Markdown
Owner

Closing: main has O_NOFOLLOW writes in the Claude bridge and path guard, and Bearer auth on the viewer. Thanks for the contribution.

@rohitg00 rohitg00 closed this Nov 9, 2026
@RinZ27
RinZ27 deleted the security-robustness-improvements branch November 15, 2026 03:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants