Skip to content

Commit 8c47476

Browse files
committed
fix: preserve literal input and static asset boundaries
Escape project names before building hand-test patterns, compare transport identifiers as literal tokens, preserve boundaries when extracting prose and XML facts, and require canonical containment for smoke static assets. Add regression coverage for metacharacters, dollar identifiers, markup joining, traversal, symlinks, and malformed URL encoding. Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
1 parent 72c3604 commit 8c47476

12 files changed

Lines changed: 150 additions & 21 deletions

‎graph-ui/src/architecture/container-topology.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,3 +343,9 @@ describe('Spring service connection evidence', () => {
343343
expect(links(result)).toEqual([]);
344344
});
345345
});
346+
347+
it.each(['$endpoint', 'endpoint$'])('tracks a literal identifier through a transport wrapper: %s', parameter => {
348+
const compose = 'services:\n web:\n build: ./web\n api:\n image: example/api\n';
349+
const source = `function load(${parameter}) { return fetch(${parameter}); }\nload("http://api:8080/items");`;
350+
expect(links(buildContainerTopology([project(compose, { 'web/client.js': source })]))).toEqual(['web>api:http']);
351+
});

‎graph-ui/src/architecture/container-topology.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,12 @@ function networkCall(name: string): boolean {
300300
|| /^(?:requests|http|https|axios|urllib\.request|urllib3|grpc|redis|psycopg2?|pymysql|mysql|amqp|amqplib|net|socket|ConnectionMultiplexer|Dns)\./i.test(name)
301301
&& /(?:get|post|put|patch|delete|request|urlopen|dial|newclient|connect|connectasync|createclient|createconnection|insecure_channel|secure_channel|gethostentry(?:async)?)$/i.test(name);
302302
}
303-
const wordIn = (code: string, name: string): boolean => new RegExp(`\\b${name.replace(/[$]/g, '\\$&')}\\b`).test(code);
303+
function wordIn(code: string, name: string): boolean {
304+
for (const [identifier] of code.matchAll(/[A-Za-z_$][\w$]*/g)) {
305+
if (identifier === name) return true;
306+
}
307+
return false;
308+
}
304309
interface Wrapper { parameter: number; hint: string }
305310
/** Bounded local argument propagation to known transport APIs, not a function-name dictionary. */
306311
function connectionWrappers(code: string, calls: Call[]): Map<string, Wrapper> {

‎graph-ui/src/architecture/repository-guide.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,10 @@ it('follows only actual call edges across components and retains their evidence'
6464
expect(paths[0].edges[0]).toBe(map.evidence[0]);
6565
expect(entryRoutes(graph.nodes[2], map.evidence)).toEqual([]);
6666
});
67+
68+
it('keeps token boundaries when dropping markup from repository prose', () => {
69+
const quote = sourceQuote('README.md', 'This repository provides useful source browsing and <<script>script> examples for developers.');
70+
expect(quote?.text).not.toContain('<script>');
71+
expect(sourceQuote('README.md', 'This repository provides useful source<b>browsing</b> for developers.')?.text)
72+
.toBe('This repository provides useful source browsing for developers.');
73+
});

‎graph-ui/src/architecture/repository-guide.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ export function sourceCandidates(area: RepositoryArea): string[] {
4141
}
4242

4343
function plainMarkdown(text: string): string {
44-
return text.replace(/!\[[^\]]*\]\([^)]*\)/g, '').replace(/\[([^\]]+)\]\([^)]*\)/g, '$1').replace(/[*_`]/g, '').replace(/<[^>]*>/g, '').trim();
44+
return text.replace(/!\[[^\]]*\]\([^)]*\)/g, '').replace(/\[([^\]]+)\]\([^)]*\)/g, '$1').replace(/[*_`]/g, '').replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
4545
}
4646

4747
/** Quote only repository-authored prose, never infer a responsibility from an identifier. */

‎graph-ui/src/browser-ai/file-facts.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,3 +102,10 @@ describe('facts read from a configuration or text file (K12)', () => {
102102
expect(readerFacts(reader('manage.py', 'import os\n'))).toEqual([]);
103103
});
104104
});
105+
106+
// Removing a comment must not create a root tag that was absent from the input.
107+
it('does not join XML markup across removed declarations or comments', () => {
108+
expect(fileFactLines('pom.xml', '<<!-- ignored -->fake/><project/>')).toContain('Root element: `<project>`.');
109+
expect(fileFactLines('pom.xml', '<<?meta?>fake/><project/>')).toContain('Root element: `<project>`.');
110+
expect(fileFactLines('pom.xml', '<!-- <hidden/> --><project/>')).toContain('Root element: `<project>`.');
111+
});

‎graph-ui/src/browser-ai/file-facts.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,8 +130,12 @@ function patternFacts(text: string): string[] {
130130
}
131131

132132
function xmlFacts(text: string): string[] {
133-
const root = /<([A-Za-z_][\w:.-]*)[\s>/]/.exec(text.replace(/<\?[\s\S]*?\?>|<!--[\s\S]*?-->|<![^>]*>/g, ''));
134-
return root ? [words.root(quote(`<${root[1]}>`))] : [];
133+
// Skip markup in the original input: deleting it could join fragments into a new tag.
134+
const tokens = /<\?[\s\S]*?(?:\?>|$)|<!--[\s\S]*?(?:-->|$)|<![^>]*>|<([A-Za-z_][\w:.-]*)[\s>/]/g;
135+
for (const match of text.matchAll(tokens)) {
136+
if (match[1]) return [words.root(quote(`<${match[1]}>`))];
137+
}
138+
return [];
135139
}
136140

137141
/** The structure of the text, by the kind its name gives. */
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { afterEach, expect, it } from 'vitest';
2+
import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync } from 'node:fs';
3+
import { tmpdir } from 'node:os';
4+
import { join } from 'node:path';
5+
import { Writable } from 'node:stream';
6+
import { literalPattern } from './literal-pattern.mjs';
7+
import { serveStaticAsset } from './smoke-static-assets.mjs';
8+
9+
const temporary = [];
10+
afterEach(() => { for (const path of temporary.splice(0)) rmSync(path, { recursive: true, force: true }); });
11+
12+
it.each(['a.b', 'a+b', '(a+)+$', '[project]', 'a\\b'])('treats a project name as literal text: %s', name => {
13+
const pattern = literalPattern(name, { start: true, end: true });
14+
expect(pattern.test(name)).toBe(true);
15+
expect(pattern.test(`prefix${name}`)).toBe(false);
16+
expect(pattern.test(`${name}suffix`)).toBe(false);
17+
});
18+
19+
it('does not expand project-name wildcards', () => {
20+
expect(literalPattern('a.b', { start: true, end: true }).test('axb')).toBe(false);
21+
});
22+
23+
function fixture() {
24+
const root = mkdtempSync(join(tmpdir(), 'cbm-static-assets-')); temporary.push(root);
25+
mkdirSync(join(root, 'spike')); mkdirSync(join(root, 'node_modules')); mkdirSync(join(root, 'spike-extra'));
26+
writeFileSync(join(root, 'spike', 'index.html'), 'fixture');
27+
writeFileSync(join(root, 'outside.txt'), 'outside-root');
28+
writeFileSync(join(root, 'spike-extra', 'outside.txt'), 'sibling-root');
29+
return root;
30+
}
31+
function request(root, url) {
32+
return new Promise((resolve, reject) => {
33+
const chunks = []; let status;
34+
const response = new Writable({ write(chunk, encoding, done) { chunks.push(Buffer.from(chunk)); done(); } });
35+
response.writeHead = code => { status = code; };
36+
response.on('error', reject);
37+
response.on('finish', () => resolve({ status, body: Buffer.concat(chunks).toString() }));
38+
try { serveStaticAsset(root, { url }, response); } catch (error) { reject(error); }
39+
});
40+
}
41+
42+
it('serves an allowed static fixture and rejects traversal and sibling prefixes', async () => {
43+
const root = fixture();
44+
expect(await request(root, '/spike/index.html')).toEqual({ status: 200, body: 'fixture' });
45+
expect((await request(root, '/spike/../outside.txt')).status).toBe(404);
46+
expect((await request(root, '/spike/%2e%2e/outside.txt')).status).toBe(404);
47+
expect((await request(root, '/spike-extra/outside.txt')).status).toBe(404);
48+
});
49+
50+
it('rejects a symlink escaping an allowed static root', async () => {
51+
const root = fixture();
52+
symlinkSync(join(root, 'outside.txt'), join(root, 'spike', 'escape.txt'));
53+
expect((await request(root, '/spike/escape.txt')).status).toBe(404);
54+
});
55+
56+
it('returns not found for malformed URL encoding instead of throwing', async () => {
57+
expect((await request(fixture(), '/spike/%zz')).status).toBe(404);
58+
});
59+
60+
it('allows a symlink whose real target stays inside the static root', async () => {
61+
const root = fixture();
62+
symlinkSync(join(root, 'spike', 'index.html'), join(root, 'spike', 'alias.html'));
63+
expect(await request(root, '/spike/alias.html')).toEqual({ status: 200, body: 'fixture' });
64+
});

‎graph-ui/tools/handtest-fixes-chat.mjs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
* access to Hugging Face), to switch the project while the download runs; the cache is full again after it.
2323
*/
2424

25+
import { literalPattern } from './literal-pattern.mjs';
2526
import { chromium } from 'playwright';
2627
import { mkdir, writeFile } from 'node:fs/promises';
2728
import { join, resolve } from 'node:path';
@@ -843,7 +844,7 @@ const activeWorkspace = (page) => page.locator('[data-workspace-tab][aria-select
843844
const sameText = (left, right) => left.replace(/\d[\d,.:]*/g, '#').replace(/\s+/g, ' ') === right.replace(/\d[\d,.:]*/g, '#').replace(/\s+/g, ' ');
844845
async function switchTo(page, project) {
845846
await page.locator('.atlas-project-switcher summary').first().click();
846-
await page.locator('.atlas-project-picker button', { has: page.locator('.atlas-project-result-name', { hasText: new RegExp(`^${project}`) }) }).first().click();
847+
await page.locator('.atlas-project-picker button', { has: page.locator('.atlas-project-result-name', { hasText: literalPattern(project, { start: true }) }) }).first().click();
847848
}
848849

849850
const pageState = (page) => page.evaluate(() => ({ id: window.__probePage, origin: performance.timeOrigin, workers: window.__probeModelWorkers }));
@@ -1064,7 +1065,7 @@ async function k24(page) {
10641065
const downloads = modelRequests.length - requestsBefore;
10651066
await save('K24', 'legs.json', legs);
10661067
const legOk = (leg) => leg.samePage && leg.workspace.before === leg.workspace.after && leg.modelWorkersCreated === 0 && leg.prepares === 0 && leg.lamp.every((frame) => /Agent active/.test(frame.label ?? ''))
1067-
&& new RegExp(leg.to).test(leg.project ?? '') && leg.requestsNamingOldProject.length === 0 && leg.views.length === K24_VIEWS.length && leg.views.every((view) => !view.stale && !view.unexpected.length) && leg.galaxySameAsFresh
1068+
&& literalPattern(leg.to).test(leg.project ?? '') && leg.requestsNamingOldProject.length === 0 && leg.views.length === K24_VIEWS.length && leg.views.every((view) => !view.stale && !view.unexpected.length) && leg.galaxySameAsFresh
10681069
&& (leg.to !== CONTROL || leg.chatHasOldTurn === false) && (leg.to !== PROJECT || leg.how !== 'switcher' || leg.chatKeptOwnTurn === true);
10691070
check('K24', 'A project switch stays in the page: the model stays loaded (no reload, no new worker, lamp active), every workspace shows only the new project and the Galaxy its graph, no request names the old one; Back/Forward the same, all views checked',
10701071
loaded && downloads === 0 && legs.every(legOk),

‎graph-ui/tools/handtest-fixes-k27.mjs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
* wird im Browser beantwortet und navigator.sendBeacon bleibt in der Seite.
3232
*/
3333

34+
import { literalPattern } from './literal-pattern.mjs';
3435
import { chromium } from 'playwright';
3536
import { mkdir, writeFile } from 'node:fs/promises';
3637
import { join, resolve } from 'node:path';
@@ -460,7 +461,7 @@ try {
460461

461462
// Projektwechsel nach cbm: frischer Verlauf
462463
await page.locator('.atlas-shell details summary', { hasText: PROJECT }).first().click();
463-
const entry = page.locator('.atlas-project-results button', { has: page.locator('.atlas-project-result-name', { hasText: new RegExp(`^${CONTROL}$`) }) }).first();
464+
const entry = page.locator('.atlas-project-results button', { has: page.locator('.atlas-project-result-name', { hasText: literalPattern(CONTROL, { start: true, end: true }) }) }).first();
464465
await entry.waitFor({ timeout: 20000 });
465466
await entry.click();
466467
const fresh = { position: '1/1', back: { disabled: true, title: 'Nothing to go back to yet' }, forward: { disabled: true, title: 'Nothing to go forward to' }, recent: [] };

‎graph-ui/tools/literal-pattern.mjs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
/** Build a pattern for literal text with optional start/end anchoring. */
2+
export function literalPattern(value, { start = false, end = false } = {}) {
3+
const escaped = value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
4+
return new RegExp(`${start ? '^' : ''}${escaped}${end ? '$' : ''}`);
5+
}

0 commit comments

Comments
 (0)