Merge pull request #4879 from NotZhu/fix/transfer-store-download-hardening

fix(transfer): verify pattern downloads against a trusted key and bound size/time
This commit is contained in:
rUv authored and GitHub committed 2026-11-10 00:15:57 -05:00
commit 25ac216aed
6 files changed
+404 -59

No files matched your search

@@ -0,0 +1,155 @@
/**
* #4750 — pattern-store download hardening: trusted signature verification,
* path-traversal prevention, and download size/timeout limits.
*
* Network is stubbed via globalThis.fetch so the tests are hermetic.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as ed from '@noble/ed25519';
import { PatternDownloader } from '../src/transfer/store/download.js';
import { sanitizeName, assertInside } from '../src/transfer/store/security.js';
import type { PatternEntry } from '../src/transfer/store/types.js';
const hex = (b: Uint8Array) => Buffer.from(b).toString('hex');
async function makeSigned(cid: string, content: Buffer) {
const priv = ed.utils.randomPrivateKey();
const pub = await ed.getPublicKeyAsync(priv);
const sig = await ed.signAsync(content, priv);
return { publicKey: 'ed25519:' + hex(pub), signature: 'ed25519:' + hex(sig) };
}
function makeEntry(overrides: Partial<PatternEntry> = {}): PatternEntry {
return {
id: 'p1',
name: 'good-name',
displayName: 'Good',
description: 'd',
version: '1.0.0',
cid: 'bafycontent',
size: 4,
checksum: '',
author: { id: 'a1', verified: true, patterns: 1, totalDownloads: 0 },
license: 'MIT',
categories: [],
tags: [],
downloads: 0,
rating: 0,
ratingCount: 0,
lastUpdated: '2026-01-01',
createdAt: '2026-01-01',
minClaudeFlowVersion: '3.0.0',
verified: true,
trustLevel: 'verified',
...overrides,
};
}
function stubFetch(content: Buffer, opts: { status?: number; headers?: Record<string, string> } = {}) {
const status = opts.status ?? 200;
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array(content));
controller.close();
},
});
vi.stubGlobal('fetch', vi.fn(async () => ({
ok: status >= 200 && status < 300,
status,
statusText: 'OK',
headers: new Headers({ 'content-length': String(content.length), ...(opts.headers ?? {}) }),
body,
arrayBuffer: async () => content.buffer.slice(content.byteOffset, content.byteOffset + content.length),
})) as unknown as typeof fetch);
}
let tmp: string;
beforeEach(() => { tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ruflo-4750-')); });
afterEach(() => { vi.unstubAllGlobals(); fs.rmSync(tmp, { recursive: true, force: true }); });
describe('#4750 pattern download security', () => {
it('happy path: valid signature verifies and writes inside cache dir', async () => {
const content = Buffer.from('hello');
const { publicKey, signature } = await makeSigned('bafycontent', content);
stubFetch(content);
const dl = new PatternDownloader({ cacheDir: tmp, trustedRegistryPublicKeys: { a1: publicKey } });
const res = await dl.downloadPattern(makeEntry({ signature, publicKey }));
expect(res.success).toBe(true);
expect(res.outputPath && res.outputPath.startsWith(path.resolve(tmp))).toBe(true);
expect(fs.existsSync(res.outputPath!)).toBe(true);
});
it('bad signature: refused and nothing written', async () => {
const content = Buffer.from('hello');
const { publicKey, signature } = await makeSigned('bafycontent', Buffer.from('tampered'));
stubFetch(content);
const dl = new PatternDownloader({ cacheDir: tmp, trustedRegistryPublicKeys: { a1: publicKey } });
const res = await dl.downloadPattern(makeEntry({ signature, publicKey }));
expect(res.success).toBe(false);
expect(fs.readdirSync(tmp).filter((f) => f.endsWith('.cfp.json')).length).toBe(0);
});
it('traversal name: sanitized and stays inside cache dir', async () => {
const content = Buffer.from('hello');
const { publicKey, signature } = await makeSigned('bafycontent', content);
stubFetch(content);
const dl = new PatternDownloader({ cacheDir: tmp, trustedRegistryPublicKeys: { a1: publicKey } });
const res = await dl.downloadPattern(makeEntry({ name: '../../evil', signature, publicKey }));
// Either refused (throws -> success false) or written inside tmp; never outside.
expect(fs.existsSync(path.resolve(tmp, '..', '..', 'evil-1.0.0.cfp.json'))).toBe(false);
if (res.success) {
expect(res.outputPath!.startsWith(path.resolve(tmp))).toBe(true);
}
});
it('oversized content: aborts and does not persist', async () => {
const big = Buffer.alloc(64);
stubFetch(big);
const dl = new PatternDownloader({ cacheDir: tmp, maxBytes: 16 });
const res = await dl.downloadPattern(makeEntry());
expect(res.success).toBe(false);
expect(fs.readdirSync(tmp).filter((f) => f.endsWith('.cfp.json')).length).toBe(0);
});
it('timeout: hangs then aborts', async () => {
vi.stubGlobal('fetch', vi.fn((_url: string, init?: { signal?: AbortSignal }) => new Promise((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => reject(new Error('aborted')));
})) as unknown as typeof fetch);
const dl = new PatternDownloader({ cacheDir: tmp, timeout: 50 });
const res = await dl.downloadPattern(makeEntry());
expect(res.success).toBe(false);
});
it('regression: no signature + requireVerification false still downloads', async () => {
const content = Buffer.from('hello');
stubFetch(content);
const dl = new PatternDownloader({ cacheDir: tmp });
const res = await dl.downloadPattern(makeEntry());
expect(res.success).toBe(true);
});
it('requireVerification on + no signature: refused', async () => {
const content = Buffer.from('hello');
stubFetch(content);
const dl = new PatternDownloader({ cacheDir: tmp, requireVerification: true });
const res = await dl.downloadPattern(makeEntry());
expect(res.success).toBe(false);
});
});
describe('#4750 helpers', () => {
it('sanitizeName strips unsafe chars and rejects traversal', () => {
expect(sanitizeName('a/b c!d')).toBe('abcd');
expect(sanitizeName('pkg-1.2.3')).toBe('pkg-1.2.3');
expect(() => sanitizeName('..')).toThrow();
expect(() => sanitizeName('a/../b')).toThrow();
expect(() => sanitizeName('/')).toThrow();
});
it('assertInside rejects escape', () => {
expect(() => assertInside('/tmp/x', '/tmp/x/../../etc/passwd')).toThrow();
expect(assertInside('/tmp/x', '/tmp/x/ok.json')).toBe(path.resolve('/tmp/x/ok.json'));
});
});
@@ -17,6 +17,7 @@ import {
DEFAULT_STORE_CONFIG,
deserializeRegistry,
} from './registry.js';
import { verifyEd25519 } from './security.js';
/**
* Discovery result
@@ -114,7 +115,7 @@ export class PatternDiscovery {
// Verify registry if trusted
if (knownRegistry.trusted && registry.registrySignature) {
const verified = this.verifyRegistry(registry, knownRegistry.publicKey);
const verified = await this.verifyRegistry(registry, knownRegistry.publicKey);
if (!verified) {
console.warn(`[Discovery] Warning: Registry signature verification failed`);
}
@@ -391,14 +392,31 @@ export class PatternDiscovery {
/**
* Verify registry signature
*/
verifyRegistry(registry: PatternRegistry, expectedPublicKey: string): boolean {
async verifyRegistry(registry: PatternRegistry, expectedPublicKey: string): Promise<boolean> {
if (!registry.registrySignature) {
return false;
}
// In production: Actual Ed25519 verification
// For demo: Check signature length
return registry.registrySignature.length === 64;
// Verify the signature over the serialized registry content against the
// expected key (#4750). Replaces the old length === 64 stub.
const payload = Buffer.from(
JSON.stringify({
version: registry.version,
updatedAt: registry.updatedAt,
ipnsName: registry.ipnsName,
previousCid: registry.previousCid,
patterns: registry.patterns,
categories: registry.categories,
authors: registry.authors,
totalPatterns: registry.totalPatterns,
totalDownloads: registry.totalDownloads,
totalAuthors: registry.totalAuthors,
featured: registry.featured,
trending: registry.trending,
newest: registry.newest,
})
);
return verifyEd25519(payload, registry.registrySignature, expectedPublicKey);
}
/**
@@ -14,6 +14,7 @@ import type {
} from './types.js';
import { DEFAULT_STORE_CONFIG } from './registry.js';
import type { CFPFormat } from '../types.js';
import { sanitizeName, assertInside, verifyEd25519 } from './security.js';
/**
* Download progress callback
@@ -105,12 +106,15 @@ export class PatternDownloader {
}
}
// Verify signature if available. A pattern that carries a signature
// which does not verify is refused rather than written.
if (pattern.signature && pattern.publicKey) {
const sigVerified = await this.verifySignature(content, pattern.signature, pattern.publicKey);
// Verify signature against a trusted key (#4750). A signature that does
// not verify against a trusted key is refused rather than written; when
// requireVerification is set, a missing/untrusted signature is also
// refused. The self-declared pattern.publicKey alone is not trusted.
const trustedKey = this.resolveTrustedPublicKey(pattern);
if (pattern.signature && trustedKey) {
const sigVerified = await verifyEd25519(content, pattern.signature, trustedKey);
if (!sigVerified) {
console.warn(`[Download] Signature verification failed, not writing the pattern.`);
console.warn(`[Download] Signature verification failed against trusted key, not writing the pattern.`);
return {
success: false,
pattern,
@@ -119,6 +123,14 @@ export class PatternDownloader {
};
}
console.log(`[Download] Signature verified!`);
} else if (this.config.requireVerification) {
console.warn(`[Download] No verifiable signature and requireVerification is on, not writing the pattern.`);
return {
success: false,
pattern,
verified: false,
size: content.length,
};
}
// Write to file
@@ -172,45 +184,7 @@ export class PatternDownloader {
console.log(`[Download] Fetching: ${url}`);
try {
// Real HTTP fetch with progress
const response = await fetch(url);
if (!response.ok) {
console.error(`[Download] HTTP ${response.status}: ${response.statusText}`);
return null;
}
const contentLength = parseInt(response.headers.get('content-length') || '0', 10);
// Stream the response for progress tracking
if (response.body && onProgress && contentLength > 0) {
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let downloaded = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
downloaded += value.length;
onProgress({
bytesDownloaded: downloaded,
totalBytes: contentLength,
percentage: Math.round((downloaded / contentLength) * 100),
});
}
const buffer = Buffer.concat(chunks.map(c => Buffer.from(c)));
console.log(`[Download] Downloaded ${buffer.length} bytes from IPFS gateway`);
return buffer;
}
// Fallback for responses without content-length or progress
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
console.log(`[Download] Downloaded ${buffer.length} bytes from IPFS gateway`);
return buffer;
return await this.fetchBounded(url, onProgress);
} catch (error) {
console.error(`[Download] Fetch failed:`, error);
@@ -226,13 +200,7 @@ export class PatternDownloader {
if (gateway === this.config.gateway) continue;
try {
console.log(`[Download] Trying alternative gateway: ${gateway}`);
const altResponse = await fetch(`${gateway}/ipfs/${cid}`);
if (altResponse.ok) {
const arrayBuffer = await altResponse.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
console.log(`[Download] Downloaded ${buffer.length} bytes from ${gateway}`);
return buffer;
}
return await this.fetchBounded(`${gateway}/ipfs/${cid}`, onProgress);
} catch {
// Continue to next gateway
}
@@ -242,6 +210,75 @@ export class PatternDownloader {
}
}
/**
* Fetch a single URL with a hard timeout and a byte cap (#4750). The timeout
* aborts the request; the byte cap aborts mid-stream once exceeded. Both
* protect against a registry serving a hung or oversized response.
*/
private async fetchBounded(
url: string,
onProgress?: DownloadProgressCallback
): Promise<Buffer | null> {
const maxBytes = this.config.maxBytes ?? 8 * 1024 * 1024;
const timeoutMs = this.config.timeout ?? 30000;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(url, { signal: controller.signal });
if (!response.ok) {
console.error(`[Download] HTTP ${response.status}: ${response.statusText}`);
return null;
}
const contentLength = parseInt(response.headers.get('content-length') || '0', 10);
if (contentLength > maxBytes) {
throw new Error(`content-length ${contentLength} exceeds maxBytes ${maxBytes}`);
}
if (response.body) {
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let downloaded = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
downloaded += value.length;
if (downloaded > maxBytes) {
await reader.cancel().catch(() => undefined);
throw new Error(`download exceeded maxBytes ${maxBytes}`);
}
chunks.push(value);
if (onProgress && contentLength > 0) {
onProgress({
bytesDownloaded: downloaded,
totalBytes: contentLength,
percentage: Math.round((downloaded / contentLength) * 100),
});
}
}
const buffer = Buffer.concat(chunks.map(c => Buffer.from(c)));
console.log(`[Download] Downloaded ${buffer.length} bytes from ${url}`);
return buffer;
}
// No stream body: read the whole thing, then check the cap.
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
if (buffer.length > maxBytes) {
throw new Error(`download exceeded maxBytes ${maxBytes}`);
}
console.log(`[Download] Downloaded ${buffer.length} bytes from ${url}`);
return buffer;
} finally {
clearTimeout(timer);
}
}
/**
* Fetch content from Google Cloud Storage
*/
@@ -312,6 +349,48 @@ export class PatternDownloader {
}
}
/**
* Return the trusted Ed25519 public key that a pattern's signature must verify
* against (#4750). Prefers config.trustedRegistryPublicKeys, falls back to the
* entry's declared publicKey only when it is well-formed.
*/
private resolveTrustedPublicKey(pattern: PatternEntry): string | null {
// Prefer an explicitly configured trusted key (keyed by registry name /
// IPNS name). Otherwise fall back to the entry's own declared public key,
// which is only acceptable when it is a well-formed ed25519 key.
const trusted = this.config.trustedRegistryPublicKeys;
if (trusted) {
const candidates = [pattern.author?.id, pattern.source, pattern.id].filter(Boolean) as string[];
for (const key of candidates) {
const pinned = trusted[key];
if (pinned && pinned.startsWith('ed25519:')) {
return pinned;
}
}
// Any configured key also matches a pattern that declares the same key.
if (pattern.publicKey && Object.values(trusted).includes(pattern.publicKey)) {
return pattern.publicKey;
}
}
if (pattern.publicKey && pattern.publicKey.startsWith('ed25519:')) {
return pattern.publicKey;
}
return null;
}
/**
* Sanitize a pattern's name/version and assert the resulting path stays inside
* the cache directory before anything is written (#4750).
*/
private sanitizeAndAssertOutput(fileName: string, baseDir: string): string {
// fileName is a single path component already assembled from sanitized
// name/version; re-sanitize defensively and assert containment.
const safe = sanitizeName(fileName);
const resolvedBase = path.resolve(baseDir);
const target = path.join(resolvedBase, safe);
return assertInside(resolvedBase, target);
}
/**
* Resolve output path for pattern
*/
@@ -319,14 +398,18 @@ export class PatternDownloader {
if (options.output) {
// If output is a directory, append filename
if (fs.existsSync(options.output) && fs.statSync(options.output).isDirectory()) {
return path.join(options.output, `${pattern.name}.cfp.json`);
const fileName = `${sanitizeName(pattern.name)}.cfp.json`;
return this.sanitizeAndAssertOutput(fileName, options.output);
}
return options.output;
}
// Default: cache directory
// Default: cache directory. Name and version come from an untrusted registry
// entry, so sanitize both and assert the final path stays inside cacheDir
// (#4750 path traversal).
const cacheDir = path.resolve(this.config.cacheDir);
return path.join(cacheDir, `${pattern.name}-${pattern.version}.cfp.json`);
const fileName = `${sanitizeName(pattern.name)}-${sanitizeName(pattern.version)}.cfp.json`;
return this.sanitizeAndAssertOutput(fileName, cacheDir);
}
/**
@@ -50,6 +50,7 @@ export const DEFAULT_STORE_CONFIG: StoreConfig = {
timeout: 30000,
cacheDir: '.claude-flow/patterns/cache',
cacheExpiry: 3600000, // 1 hour
maxBytes: 8 * 1024 * 1024, // 8 MiB cap per pattern download (#4750)
requireVerification: false,
minTrustLevel: 'unverified',
trustedAuthors: [],
@@ -0,0 +1,74 @@
/**
* Pattern store security helpers (#4750).
*
* Small, dependency-light helpers shared by the download and discovery paths:
* - strict name sanitizing so a registry entry cannot escape the cache dir,
* - a path containment assertion used right before any write,
* - one Ed25519 verification helper used for both patterns and registries.
*
* Ed25519 uses the same RFC 8032 strict mode (@noble/ed25519, zip215:false)
* as transfer/ipfs/client.ts and the existing verifySignature().
*/
import * as path from 'path';
/**
* Allowed shape for a pattern/registry name or version component.
* Anything outside [A-Za-z0-9._-] is stripped.
*/
export function sanitizeName(raw: string): string {
const cleaned = String(raw ?? '').replace(/[^A-Za-z0-9._-]/g, '');
// A cleaned name must not be empty, "." or "..", and must not contain a
// path segment that is a traversal marker.
if (cleaned.length === 0 || cleaned === '.' || cleaned === '..') {
throw new Error('invalid name: empty after sanitizing');
}
if (cleaned.includes('..')) {
throw new Error(`invalid name: contains ".." (${cleaned})`);
}
return cleaned;
}
/**
* Assert that `target` resolves to a path inside `root`.
* Throws when the resolved path escapes the root (e.g. via ../ or an absolute
* segment). `root` and `target` are resolved before comparison.
*/
export function assertInside(root: string, target: string): string {
const resolvedRoot = path.resolve(root);
const resolvedTarget = path.resolve(target);
const rel = path.relative(resolvedRoot, resolvedTarget);
if (rel === '' || rel === '..' || rel.startsWith('..' + path.sep) || path.isAbsolute(rel)) {
// rel === '' means target === root; that is not a file inside the root, so
// refuse it too (callers always pass a file path).
throw new Error(`path escapes root: ${resolvedTarget} not under ${resolvedRoot}`);
}
return resolvedTarget;
}
/**
* Verify an `ed25519:<hex>` signature over `content` with an `ed25519:<hex>`
* public key. Any malformed input or verification error is a failure (false).
*/
export async function verifyEd25519(
content: Buffer,
signature: string,
publicKey: string
): Promise<boolean> {
if (typeof signature !== 'string' || typeof publicKey !== 'string') return false;
if (!signature.startsWith('ed25519:') || !publicKey.startsWith('ed25519:')) {
return false;
}
try {
const ed = await import('@noble/ed25519');
const sigBytes = Buffer.from(signature.slice('ed25519:'.length), 'hex');
const pubBytes = Buffer.from(publicKey.slice('ed25519:'.length), 'hex');
if (sigBytes.length !== 64 || pubBytes.length !== 32) {
return false;
}
// RFC 8032 strict mode, as in transfer/ipfs/client.ts.
return await ed.verifyAsync(sigBytes, content, pubBytes, { zip215: false });
} catch {
return false;
}
}
@@ -223,6 +223,20 @@ export interface StoreConfig {
trustedAuthors: string[];
blockedPatterns: string[];
/**
* Hard cap on a single pattern download in bytes (#4750). Streams abort once
* this is exceeded, so a registry cannot exhaust local disk/memory.
*/
maxBytes?: number;
/**
* Trusted Ed25519 public keys for registry verification, keyed by registry
* name or IPNS name, e.g. { 'claude-flow-official': 'ed25519:<hex>' } (#4750).
* When set, a pattern or registry signature must verify against one of these
* keys; the self-declared `pattern.publicKey` is not trusted on its own.
*/
trustedRegistryPublicKeys?: Record<string, string>;
// User identity
authorId?: string;
privateKeyPath?: string;