fix: append parsed nodes when loading initial HTML into the Lexical editor

EditorShell's ingest called $generateNodesFromDOM but discarded the
returned nodes, so stored content never appeared in the WYSIWYG editor
in edit mode (the E2E edit test only checked title/points and missed it).
The parsed nodes are now appended to the root (kept empty-paragraph
default when nothing parses).

Hardening tests added while auditing the M6 test checklist:
- E2E: edit view asserts the stored body renders in the editor; new
  hostile-HTML test loads <script> tags, onerror/onload handlers and
  javascript: links through the real editor and asserts none survive
  into the contenteditable and nothing executes.
- E2E/unit: create button is disabled while the request is in flight.
- Backend: SQL metacharacters in the search term behave as literal
  text and leave the table intact.

Milestone doc updated: QA checklist items now cite their tests, plus a
QA-findings note for the ingest bug.
This commit is contained in:
Daniel Samson committed 2026-10-30 21:58:23 +00:00
1 parent b440809548
commit e62fad4a10
5 files changed
+104 -3

No files matched your search

+17
View File
@@ -176,6 +176,23 @@ class TestListItems:
assert none["items"] == []
assert none["total"] == 0
def test_search_with_sql_metacharacters_is_treated_as_text(self, client, session) -> None:
"""Search input is a parameterized substring filter, never raw SQL."""
_make_user(session, "root", is_admin=True)
_seed_items(session, 5)
headers = _headers(session, "root")
attack = "1=1' OR '1'='1"
resp = client.get(BASE, params={"search": attack}, headers=headers)
assert resp.status_code == 200
body = resp.json()
assert body["items"] == []
assert body["total"] == 0
# The table is intact after the "attack".
intact = client.get(BASE, headers=headers).json()
assert intact["total"] == 5
@pytest.mark.parametrize("order, expected_first", [("asc", "Story 00"), ("desc", "Story 04")])
def test_sort_by_title(self, client, session, order, expected_first) -> None:
_make_user(session, "root", is_admin=True)
+42
View File
@@ -341,6 +341,8 @@ test.describe('admin area (M6)', () => {
await expect(page.getByRole('heading', { level: 1, name: /edit item/i })).toBeVisible();
await expect(page.getByLabel(/^Title/)).toHaveValue('Breaking: local cat discovers keyboard');
await expect(page.getByLabel('Points')).toHaveValue('42');
// The stored body loads into the WYSIWYG editor.
await expect(page.getByLabel('Item content')).toContainText('Amazing news.');
await page.getByLabel(/^Title/).fill('Breaking: local cat becomes famous');
await page.getByRole('button', { name: /save changes/i }).click();
@@ -405,4 +407,44 @@ test.describe('admin area (M6)', () => {
// (Still one page for 3 items — assert the selector round-trips.)
await expect(page.getByLabel('Rows per page')).toHaveValue('10');
});
test('editor sanitizes hostile stored HTML (no scripts or handlers survive)', async ({
page,
}) => {
const { store } = mockAdminApi(page);
await seedToken(page, ADMIN_TOKEN);
// Simulate a hostile item body persisted by the backend.
store[0].content = [
'<p>Safe <strong>text</strong></p>',
'<script>alert(1)</script>',
'<img src="x" onerror="alert(1)"/>',
'<svg onload="alert(1)"></svg>',
'<a href="javascript:alert(1)">click</a>',
].join('');
const dialogs: string[] = [];
const pageErrors: string[] = [];
page.on('dialog', (dialog) => {
dialogs.push(dialog.message());
void dialog.dismiss();
});
page.on('pageerror', (error) => pageErrors.push(error.message));
await page.goto('/admin/items/1/edit');
const editable = page.getByLabel('Item content');
await expect(editable).toContainText('Safe');
const html = await editable.evaluate((el) => el.innerHTML);
expect(html).not.toContain('<script');
expect(html).not.toContain('onerror');
expect(html).not.toContain('onload');
expect(html).not.toContain('javascript:');
// The legitimate content survives the round trip.
expect(html).toContain('<strong');
// Nothing executed in the page.
expect(dialogs).toHaveLength(0);
expect(pageErrors).toHaveLength(0);
});
});
+9 -1
View File
@@ -149,13 +149,21 @@ function EditorShell({ initialHtml, onChange, placeholder }: EditorShellProps) {
const [editor] = useLexicalComposerContext();
// Load the initial HTML once (empty string -> the default empty paragraph).
// $generateNodesFromDOM returns the parsed nodes without attaching them,
// so they must be appended to the root manually. Non-whitelisted markup
// (scripts, event handlers, unknown elements) is dropped by the parser,
// which also acts as the XSS boundary for stored content.
useEffect(() => {
if (!initialHtml) return;
const doc = document.implementation.createHTMLDocument('');
doc.body.innerHTML = initialHtml;
editor.update(
() => {
$generateNodesFromDOM(editor, doc);
const nodes = $generateNodesFromDOM(editor, doc);
if (nodes.length === 0) return; // keep the default empty paragraph
const root = $getRoot();
root.clear();
root.append(...nodes);
},
{ discrete: true },
);
@@ -179,6 +179,28 @@ describe('EditItemPage (create)', () => {
);
});
it('disables the create button while the request is in flight', async () => {
let resolveCreate!: (value: AdminItem) => void;
vi.mocked(adminCreateItem).mockReturnValueOnce(
new Promise<AdminItem>((resolve) => {
resolveCreate = resolve;
}),
);
renderAt('/admin/items/new');
await screen.findByTestId('lexical-stub');
fireEvent.change(screen.getByLabelText(/^Title/), {
target: { value: 'Pending' },
});
screen.getByRole('button', { name: /create item/i }).click();
const button = screen.getByRole('button', { name: /create item/i });
await waitFor(() => expect(button).toBeDisabled());
resolveCreate({ ...ITEM, id: 99, title: 'Pending' });
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
});
it('shows the backend error when the create request fails', async () => {
vi.mocked(adminCreateItem).mockRejectedValue(
new ApiError(422, 'Validation failed', 'validation_error'),
+14 -2
View File
@@ -302,6 +302,18 @@ Implementation notes (deviations from the prompt sketch, matching project conven
- Rate limiting is implemented in-memory (1000 req/60s per admin; 429 on breach)
rather than a placeholder.
QA findings from M6 (all fixed):
- The editor's `initialHtml` ingest called `$generateNodesFromDOM` but
discarded the returned nodes, so stored content never appeared in the
WYSIWYG editor in edit mode. Fixed by appending the parsed nodes to the
root; covered by the E2E edit + hostile-HTML tests.
- XSS: the E2E hostile-HTML test loads `<script>`, `onerror`/`onload`
handlers and `javascript:` links through the real editor and asserts
none of it survives into the contenteditable (nothing executes).
- SQL injection: the backend search test feeds `1=1' OR '1'='1` as a
search term and asserts literal-substring behaviour plus table integrity.
## Technical Details
### Database Schema Update
@@ -574,8 +586,8 @@ export function DeleteConfirmation({ itemId, itemName, onConfirm, onCancel }: De
- [x] Direct URL access to /api/v1/admin/items → 403 for non-admins
- [x] Token tampering doesn't bypass admin check (JWT signature validation)
- [x] Rate limiting active (in-memory, 1000 req/60s per admin → 429)
- [x] Input sanitization prevents SQL injection (SQLAlchemy parameterized queries)
- [x] XSS prevention in Lexical editor output (HTML round-trips through Lexical's node model, which drops non-whitelisted markup; content is only rendered inside the admin editor)
- [x] Input sanitization prevents SQL injection (SQLAlchemy parameterized queries; verified by `test_search_with_sql_metacharacters_is_treated_as_text`)
- [x] XSS prevention in Lexical editor output (verified by the E2E hostile-HTML test: scripts, event handlers and `javascript:` links are stripped by the node-model round trip and nothing executes)
### Performance Considerations
- Search with 10,000 items: <2 seconds response time