Skip to content

fix: harden MCP security boundaries - #444

Merged
mohanagy merged 1 commit into
nextfrom
issue-426-mcp-security-hardening
May 31, 2026
Merged

mohanagy merged 1 commit into
nextfrom
issue-426-mcp-security-hardening

Conversation

@mohanagy

@mohanagy mohanagy commented May 31, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • add a checked-in MCP threat model plus explicit local trust-boundary guidance in README/SECURITY/install templates
  • harden share-safe sanitization so compare/review-compare redact credential-like env values, auth headers, URL userinfo, and secret-bearing query params
  • add release SBOM/provenance guidance and lock the new security contract with focused regressions

Test Plan

  • npm run test:run -- tests/unit/share-safe-artifacts.test.ts tests/unit/security.test.ts tests/unit/install-docs.test.ts tests/unit/install-templates.test.ts tests/unit/release-docs.test.ts tests/unit/mcp-threat-model-doc.test.ts tests/unit/compare.test.ts
  • npm run typecheck
  • npm run build
  • CI=1 npm run test:run
  • npm pack --dry-run

Closes #426

Summary by CodeRabbit

  • Documentation

    • Added comprehensive security threat model documentation clarifying local trust boundaries.
    • Enhanced README and security policy with guidance on treating MCP installations and profiles as trust boundaries.
    • Updated release procedures to include SBOM generation and npm provenance attestations.
  • New Features

    • Improved credential and secret redaction in shareable artifacts.
    • Added path validation to prevent directory traversal escapes.
  • Tests

    • Added verification tests for security guidance and threat model documentation.
    • Enhanced security validation tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented May 31, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR implements the MCP security threat model and supply-chain hardening roadmap. It adds comprehensive threat documentation, hardens credential/secret redaction in share-safe artifacts, updates user-facing guidance, and validates both through extensive tests.

Changes

MCP Security Threat Model and Artifact Hardening

Layer / File(s) Summary
Security threat model and documentation
docs/security/mcp-threat-model.md, README.md, SECURITY.md, docs/release.md
New mcp-threat-model.md document defines trust boundaries, enumerates threats (prompt injection, path traversal, tool poisoning, share-safe leakage, secret exposure, supply-chain drift), and references mitigations. SECURITY.md adds a "Local MCP trust boundary" policy section clarifying local-first is not automatic safety. README.md adds trust-boundary paragraphs and a security-boundary note. docs/release.md adds SBOM generation (npm sbom --sbom-format cyclonedx) and npm provenance attestation (--provenance) to release steps.
Credential redaction and share-safe sanitization
src/shared/share-safe-artifacts.ts, src/infrastructure/review-compare.ts
sanitizeShareSafeText now detects and redacts credential-like key/value patterns and Authorization headers before masking URLs; URL parsing redacts username/password and sensitive query parameters. rewriteShareSafeStderr removes the intermediate redactCredentialLikeText call and delegates directly to the consolidated sanitizer.
Installation template trust-boundary guidance
src/infrastructure/install-skill-templates.ts
commonOverview() adds a guidance message instructing users to treat local MCP servers, hooks, plugins, and AGENTS profiles as trust boundaries and to enable them only for trusted repositories/runtimes, preferring least-privilege modes.
Test coverage for threat model, redaction, and documentation
tests/unit/mcp-threat-model-doc.test.ts, tests/unit/install-docs.test.ts, tests/unit/install-templates.test.ts, tests/unit/release-docs.test.ts, tests/unit/share-safe-artifacts.test.ts, tests/unit/security.test.ts
New mcp-threat-model-doc.test.ts validates threat model document structure and keywords. Updated install-docs.test.ts and install-templates.test.ts verify trust-boundary guidance in README and skill templates. Updated release-docs.test.ts checks for SBOM and provenance commands. New share-safe-artifacts.test.ts suite tests credential/token redaction, URL secret masking, and resilience to malformed encodings. New validateGraphPath test in security.test.ts verifies symlink-based path-traversal rejection.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

The changes span security documentation, credential-redaction logic with medium complexity, user-facing guidance updates, and comprehensive test validation. The credential redaction logic is the most intricate portion, combining URL parsing, pattern matching, and sentinel-based redaction normalization. Most changes are well-scoped documentation and testing additions with consistent patterns across files, though the redaction helpers require careful review to ensure coverage of credential variants.

Possibly related PRs

  • mohanagy/madar#333: Related template generation and guidance changes in src/infrastructure/install-skill-templates.ts; this PR extends similar guidance surface with trust-boundary messaging.

Poem

🐰 A rabbit hops through secrets masked,
Credentials redacted, boundaries tasked,
With SBOM checks and provenance signed,
MCP's threat model—now well-designed. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: harden MCP security boundaries' accurately summarizes the main change—hardening security around MCP trust boundaries with threat modeling and credential redaction.
Description check ✅ Passed The PR description covers the summary of changes, documents the test plan with executed commands, and references the closed issue. All required sections are present and complete.
Linked Issues check ✅ Passed All key objectives from issue #426 are met: threat model document added, SBOM/provenance guidance in release docs, share-safe credential redaction implemented, MCP boundary tests added, and trust boundary guidance in public docs.
Out of Scope Changes check ✅ Passed All changes are directly related to MCP security hardening objectives. Documentation updates, threat model, credential redaction, and release guidance are all within scope of issue #426.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch issue-426-mcp-security-hardening

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
tests/unit/share-safe-artifacts.test.ts (1)

22-26: ⚡ Quick win

Add regression cases for apikey and x-api-key assignment redaction

Please extend this test to include those common credential-like forms so the sanitizer contract is locked against regressions.

✅ Suggested test extension
-  it('redacts credential-like environment assignments and bearer tokens', () => {
-    const text = 'MADAR_TOKEN=abc123 Authorization: Bearer super-secret-value'
+  it('redacts credential-like environment assignments and bearer tokens', () => {
+    const text = 'MADAR_TOKEN=abc123 apikey=def456 x-api-key=ghi789 Authorization: Bearer super-secret-value'

-    expect(sanitizeShareSafeText(text, ROOTS)).toBe('MADAR_TOKEN=[REDACTED] Authorization: Bearer [REDACTED]')
+    expect(sanitizeShareSafeText(text, ROOTS)).toBe(
+      'MADAR_TOKEN=[REDACTED] apikey=[REDACTED] x-api-key=[REDACTED] Authorization: Bearer [REDACTED]',
+    )
   })
🤖 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 `@tests/unit/share-safe-artifacts.test.ts` around lines 22 - 26, Update the
test case that asserts sanitizeShareSafeText behavior (the "redacts
credential-like environment assignments and bearer tokens" spec) to also cover
assignment forms "apikey=..." and "x-api-key=..." so the sanitizer contract
prevents regressions; modify the test using the same INPUT/ROOTS setup and add
expectations like expect(sanitizeShareSafeText('apikey=secret123',
ROOTS)).toBe('apikey=[REDACTED]') and
expect(sanitizeShareSafeText('x-api-key=anotherSecret',
ROOTS)).toBe('x-api-key=[REDACTED]') (or combine them into one string alongside
existing tokens) referencing the sanitizeShareSafeText function and ROOTS
constant so the new assertions run with existing cases.
🤖 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/shared/share-safe-artifacts.ts`:
- Around line 46-57: The credential redaction misses names like "apikey" and
hyphenated keys (e.g. "x-api-key") because SENSITIVE_CREDENTIAL_NAME_PATTERN
doesn't include "apikey" and the name capture in redactCredentialLikeText only
allows underscores (uses ([A-Z0-9_]+)). Update SENSITIVE_CREDENTIAL_NAME_PATTERN
to include "apikey" and allow hyphens inside names (e.g. use a pattern that
permits [A-Z0-9-] around the sensitive tokens), and change the name capture in
redactCredentialLikeText from ([A-Z0-9_]+) to ([A-Z0-9_-]+) so hyphenated keys
are recognized; keep using isSensitiveCredentialName to test the normalized name
after these changes.

---

Nitpick comments:
In `@tests/unit/share-safe-artifacts.test.ts`:
- Around line 22-26: Update the test case that asserts sanitizeShareSafeText
behavior (the "redacts credential-like environment assignments and bearer
tokens" spec) to also cover assignment forms "apikey=..." and "x-api-key=..." so
the sanitizer contract prevents regressions; modify the test using the same
INPUT/ROOTS setup and add expectations like
expect(sanitizeShareSafeText('apikey=secret123',
ROOTS)).toBe('apikey=[REDACTED]') and
expect(sanitizeShareSafeText('x-api-key=anotherSecret',
ROOTS)).toBe('x-api-key=[REDACTED]') (or combine them into one string alongside
existing tokens) referencing the sanitizeShareSafeText function and ROOTS
constant so the new assertions run with existing cases.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 82503574-d2c2-4215-88f1-197d3c257a8e

📥 Commits

Reviewing files that changed from the base of the PR and between 9c7dca5 and aa44b5d.

📒 Files selected for processing (13)
  • README.md
  • SECURITY.md
  • docs/release.md
  • docs/security/mcp-threat-model.md
  • src/infrastructure/install-skill-templates.ts
  • src/infrastructure/review-compare.ts
  • src/shared/share-safe-artifacts.ts
  • tests/unit/install-docs.test.ts
  • tests/unit/install-templates.test.ts
  • tests/unit/mcp-threat-model-doc.test.ts
  • tests/unit/release-docs.test.ts
  • tests/unit/security.test.ts
  • tests/unit/share-safe-artifacts.test.ts

Comment on lines +46 to +57
const SENSITIVE_CREDENTIAL_NAME_PATTERN = /(?:^|[_-])(token|key|secret|password|pass|auth|authorization|signature|sig)(?:[_-]|$)/i
const REDACTION_SENTINEL = 'MADAR_SHARE_SAFE_REDACTED'

function isSensitiveCredentialName(name: string): boolean {
const normalized = name.trim().toLowerCase().replace(/\[\]$/, '')
return SENSITIVE_CREDENTIAL_NAME_PATTERN.test(normalized)
}

function redactCredentialLikeText(text: string): string {
return text
.replaceAll(/(^|[\s([{])([A-Z0-9_]+)=([^\s]+)/gim, (match, prefix: string, name: string) =>
isSensitiveCredentialName(name) ? `${prefix}${name}=[REDACTED]` : match,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Credential matcher misses common apikey / hyphenated key forms

Line 46 and Line 56 together can leave secrets unredacted for common shapes like apikey=... and x-api-key=..., because separator matching is too strict and - is excluded from parsed key names.

🔧 Proposed fix
-const SENSITIVE_CREDENTIAL_NAME_PATTERN = /(?:^|[_-])(token|key|secret|password|pass|auth|authorization|signature|sig)(?:[_-]|$)/i
+const SENSITIVE_CREDENTIAL_NAME_PATTERN =
+  /(?:^|[_-])(token|api[_-]?key|key|secret|password|pass|auth|authorization|signature|sig)(?:[_-]|$)/i

 function isSensitiveCredentialName(name: string): boolean {
-  const normalized = name.trim().toLowerCase().replace(/\[\]$/, '')
+  const normalized = name
+    .trim()
+    .replace(/\[\]$/, '')
+    .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
+    .toLowerCase()
   return SENSITIVE_CREDENTIAL_NAME_PATTERN.test(normalized)
 }

 function redactCredentialLikeText(text: string): string {
   return text
-    .replaceAll(/(^|[\s([{])([A-Z0-9_]+)=([^\s]+)/gim, (match, prefix: string, name: string) =>
+    .replaceAll(/(^|[\s([{])([A-Z0-9_-]+)=([^\s]+)/gim, (match, prefix: string, name: string) =>
       isSensitiveCredentialName(name) ? `${prefix}${name}=[REDACTED]` : match,
     )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const SENSITIVE_CREDENTIAL_NAME_PATTERN = /(?:^|[_-])(token|key|secret|password|pass|auth|authorization|signature|sig)(?:[_-]|$)/i
const REDACTION_SENTINEL = 'MADAR_SHARE_SAFE_REDACTED'
function isSensitiveCredentialName(name: string): boolean {
const normalized = name.trim().toLowerCase().replace(/\[\]$/, '')
return SENSITIVE_CREDENTIAL_NAME_PATTERN.test(normalized)
}
function redactCredentialLikeText(text: string): string {
return text
.replaceAll(/(^|[\s([{])([A-Z0-9_]+)=([^\s]+)/gim, (match, prefix: string, name: string) =>
isSensitiveCredentialName(name) ? `${prefix}${name}=[REDACTED]` : match,
const SENSITIVE_CREDENTIAL_NAME_PATTERN =
/(?:^|[_-])(token|api[_-]?key|key|secret|password|pass|auth|authorization|signature|sig)(?:[_-]|$)/i
const REDACTION_SENTINEL = 'MADAR_SHARE_SAFE_REDACTED'
function isSensitiveCredentialName(name: string): boolean {
const normalized = name
.trim()
.replace(/\[\]$/, '')
.replace(/([a-z0-9])([A-Z])/g, '$1_$2')
.toLowerCase()
return SENSITIVE_CREDENTIAL_NAME_PATTERN.test(normalized)
}
function redactCredentialLikeText(text: string): string {
return text
.replaceAll(/(^|[\s([{])([A-Z0-9_-]+)=([^\s]+)/gim, (match, prefix: string, name: string) =>
isSensitiveCredentialName(name) ? `${prefix}${name}=[REDACTED]` : match,
🤖 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/shared/share-safe-artifacts.ts` around lines 46 - 57, The credential
redaction misses names like "apikey" and hyphenated keys (e.g. "x-api-key")
because SENSITIVE_CREDENTIAL_NAME_PATTERN doesn't include "apikey" and the name
capture in redactCredentialLikeText only allows underscores (uses ([A-Z0-9_]+)).
Update SENSITIVE_CREDENTIAL_NAME_PATTERN to include "apikey" and allow hyphens
inside names (e.g. use a pattern that permits [A-Z0-9-] around the sensitive
tokens), and change the name capture in redactCredentialLikeText from
([A-Z0-9_]+) to ([A-Z0-9_-]+) so hyphenated keys are recognized; keep using
isSensitiveCredentialName to test the normalized name after these changes.

@mohanagy
mohanagy merged commit 423d60a into next May 31, 2026
7 checks passed
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.

1 participant