diff --git a/docs/content/4.plugins/1.built-in/security.md b/docs/content/4.plugins/1.built-in/security.md index 0fd339f8..c5e5a6c7 100644 --- a/docs/content/4.plugins/1.built-in/security.md +++ b/docs/content/4.plugins/1.built-in/security.md @@ -111,11 +111,11 @@ Framework renderers (Vue, React, Svelte, Angular) never forward `innerHTML`, `da Renderers hand bound props to components, and Vue treats a plain object with a `template`, `render`, `ssrRender`, `setup`, `extends` or `mixins` key as a component definition, one with `__v_isVNode` as a ready-made element, and one with `__isTeleport`, `__isSuspense` or `__isKeepAlive` as a built-in component. Its template can then run during server rendering, or the element skips tag filtering. These values are always dropped: -- `as` and `is` (and their bindings) that are not strings, since they name the element or component to render: Vue mounts an array as a component, and React throws on one. Strings must be a plain tag or component name, since Vue's server renderer writes anything else (`img src=x onerror=…`) into the opening tag, and can't name a tag that runs code (`script`, `style`, `iframe`, `object`, `embed`, …). `tag` is often a data prop, so only objects are dropped there. +- `as` and `is` that are not strings, since they name the element or component to render: Vue mounts an array as a component, and React throws on one. Strings must be a plain tag or component name, since Vue's server renderer writes anything else (`img src=x onerror=…`) into the opening tag, and can't name a tag that runs code (`script`, `style`, `iframe`, `object`, `embed`, …). The security plugin also strips every binding to them; see [`allowedTags`](#allowedtags). `tag` is often a data prop, so only objects are dropped there. - Any object or array with one of those keys at any depth, such as `:icon='{"extends": {"template": "..."}}'` or `:icon='{"__v_isVNode": true, "type": "script"}'`. - An `__v_isVNode` attribute on the element itself, bound or not. Vue would otherwise render the element's attributes as a ready-made element. -Data props keep working, for example `:items='[{"label": "a"}]'`. The Vue renderer also only resolves `as` to a component when it is a string. Frontmatter is checked for component options only, so data such as `tag: [vue, nuxt]` stays; a binding that passes a frontmatter array or object to `as` or `is`, or an object to `tag`, is still dropped. +Data props keep working, for example `:items='[{"label": "a"}]'`. The Vue renderer also only resolves `as` to a component when it is a string. Frontmatter is checked for component options only, so data such as `tag: [vue, nuxt]` stays; a binding to `as` or `is` is always dropped, and one that passes an object to `tag` is too. ::warning Rendering untrusted markdown (chat messages, LLM output, user comments) is only safe with this plugin enabled. The renderers apply a minimum floor to bound props, but the plugin is the full policy: it also removes the values from the document tree. Keep `security()` enabled for untrusted input. @@ -232,9 +232,13 @@ security({ }) ``` -The `as` and `is` props (which make framework renderers resolve a different component than the element's own tag) are held to the same filters: a value naming a blocked or not-allowed tag, or `object`, is stripped, and the element falls back to its own tag. +The `as` and `is` props (which make framework renderers resolve a different component than the element's own tag) are treated as the element's tag. An element whose `as` or `is` names a blocked or not-allowed tag is removed, or passed to [`tagFallback`](#tagfallback), just like an element with that tag. Its own tag must pass the filters too, since renderers fall back to it when no component matches the `as` value. Props are validated for the named tag, so `as="object"` drops them all. -Their bindings are checked too. A JSON binding (`:as='"section"'`) is checked decoded, as renderers decode it. A dot-path binding (`:as="frontmatter.tag"`) only resolves at render time, after every check, so it is always stripped. +An `as` or `is` value must be a literal string made only of letters, digits, `_` and `-`, such as `as="my-card"`. Any other value is stripped, along with every binding that could set one, since a bound value is only known at render time, after every check: + +- `:as`, `v-bind:as`, `:is` and `v-bind:is`, even with a JSON string (`:as='"section"'`) +- prefixed or differently cased names that the renderers don't read as `as` or `is`, such as `AS` or `.is` +- an object binding (`v-bind`, `v-bind:` or `:`) whose object has an `as` or `is` key, or comes from render-time data (`v-bind="frontmatter.props"`) ### `tagFallback` diff --git a/packages/comark/src/plugins/security.ts b/packages/comark/src/plugins/security.ts index 4cf34035..f59eb03b 100644 --- a/packages/comark/src/plugins/security.ts +++ b/packages/comark/src/plugins/security.ts @@ -1,13 +1,7 @@ import type { ElementNode, Node } from 'comark' import { defineComarkPlugin } from 'comark' import { visitAsync } from 'comark/utils' -import { - createTagFilter, - isTagSelector, - isUnsafeTagSelector, - sanitizeData, - validateProps, -} from '../internal/sanitize.ts' +import { isTagSelector, sanitizeData, unsafeTags, validateProps } from '../internal/sanitize.ts' import type { PropsValidationOptions } from '../internal/sanitize.ts' interface SecurityOptions extends PropsValidationOptions { @@ -36,6 +30,27 @@ interface SecurityOptions extends PropsValidationOptions { frontmatter?: boolean } +/** A tag name an `as` or `is` value may name: letters, digits, `_` and `-` only. */ +const RE_TAG_NAME = /^[\w-]+$/ + +/** Whether `key` binds an object of props at once: `v-bind`, `v-bind:` or `:`. */ +function isObjectBinding(key: string): boolean { + return key === ':' || key === 'v-bind' || key === 'v-bind:' +} + +/** Whether an object binding can set `as` or `is`: it holds one, or only render-time data decides. */ +function bindsTagSelector(value: unknown): boolean { + if (typeof value === 'string') { + try { + value = JSON.parse(value) + } catch { + return true + } + } + if (typeof value !== 'object' || value === null) return false + return Object.keys(value).some(isTagSelector) +} + export default defineComarkPlugin((options: SecurityOptions = {}) => { const { blockedTags = [], @@ -51,7 +66,6 @@ export default defineComarkPlugin((options: SecurityOptions = {}) => { const dropSet = new Set(blockedTags.map((t) => t.toLowerCase())) const allowSet = new Set(allowedTags.map((t) => t.toLowerCase())) - const isFilteredTag = createTagFilter(blockedTags, allowedTags) const propsOptions: PropsValidationOptions = { allowedLinkPrefixes, @@ -69,10 +83,27 @@ export default defineComarkPlugin((options: SecurityOptions = {}) => { (node) => typeof node !== 'string' && node[0] !== null, async (node) => { const element = node as ElementNode - const tagName = element[0].toLowerCase() - const isBlocked = dropSet.has(tagName) - const isNotAllowed = allowSet.size > 0 && !allowSet.has(tagName) + // `as` and `is` change the tag renderers create, so the element is checked as each tag it names: + // otherwise `[x]{as="AdminPanel"}` bypasses the tag filters. Its own tag is checked too, as + // renderers fall back to it when no component matches the `as` value. + const tagNames = [element[0].toLowerCase()] + for (const key of Object.keys(element[1])) { + const value = element[1][key] + const isLiteral = key === 'as' || key === 'is' + if (isLiteral && typeof value === 'string' && RE_TAG_NAME.test(value)) { + tagNames.push(value.toLowerCase()) + continue + } + if (!isLiteral && !isTagSelector(key) && !(isObjectBinding(key) && bindsTagSelector(value))) continue + // A bound selector (`:as`, `v-bind:is`, `v-bind="{ as }"`) names its tag only at render + // time, after every check, and a non-string or malformed one names no valid tag. + console.warn(`[comark/plugins/security] removing unsafe attribute: ${key}="${value}"`) + delete element[1][key] + } + + const isBlocked = tagNames.some((tag) => dropSet.has(tag)) + const isNotAllowed = allowSet.size > 0 && tagNames.some((tag) => !allowSet.has(tag)) if (isNotAllowed || isBlocked) { if (typeof tagFallback === 'function') { @@ -83,22 +114,14 @@ export default defineComarkPlugin((options: SecurityOptions = {}) => { return false } - // `as` and `is` make renderers resolve a different component than the element's own tag. - // Hold them, bindings included, to the same tag filters: otherwise `[x]{as="AdminPanel"}` bypasses them. - for (const key of Object.keys(element[1])) { - if (isTagSelector(key) && isUnsafeTagSelector(key, element[1][key], isFilteredTag)) { - console.warn(`[comark/plugins/security] removing unsafe attribute: ${key}="${element[1][key]}"`) - delete element[1][key] - } - } - const keys = Object.keys(element[1]) /** * If the element has any props, validate them */ if (keys.length) { - element[1] = validateProps(element[0], element[1], propsOptions) + const type = tagNames.find((tag) => unsafeTags.includes(tag)) ?? tagNames[0] + element[1] = validateProps(type, element[1], propsOptions) } } ) diff --git a/packages/comark/test/plugins/security.test.ts b/packages/comark/test/plugins/security.test.ts index f328b66e..8f2d993a 100644 --- a/packages/comark/test/plugins/security.test.ts +++ b/packages/comark/test/plugins/security.test.ts @@ -627,22 +627,34 @@ describe('security plugin — allowedTags', () => { }) describe('security plugin — as prop', () => { - it('strips as pointing at a blocked tag', async () => { - const tree = makeTree([['span', { as: 'script' }, 'x']]) + it('removes an element whose as names a blocked tag', async () => { + const tree = makeTree([ + ['span', { as: 'Script' }, 'x'], + ['p', {}, 'safe'], + ]) await runPlugin(tree, { blockedTags: ['script'] }) - const el = tree.nodes[0] as [string, any] - expect(el[0]).toBe('span') - expect(el[1].as).toBeUndefined() + expect(tree.nodes).toEqual([['p', {}, 'safe']]) }) - it('strips as pointing at a tag outside allowedTags', async () => { + it('removes an element whose as names a tag outside allowedTags', async () => { const tree = makeTree([['span', { as: 'AdminPanel' }, 'x']]) await runPlugin(tree, { allowedTags: ['span'] }) - const el = tree.nodes[0] as [string, any] - expect(el[1].as).toBeUndefined() + expect(tree.nodes).toEqual([]) }) - it('keeps as when the resolved tag is allowed', async () => { + it('passes the element to tagFallback when as names a blocked tag', async () => { + const tree = makeTree([['span', { as: 'AdminPanel' }, 'x']]) + await runPlugin(tree, { blockedTags: ['adminpanel'], tagFallback: (e) => textContent(e) }) + expect(tree.nodes).toEqual(['x']) + }) + + it('still checks the element tag, which renderers fall back to', async () => { + const tree = makeTree([['iframe', { as: 'Badge' }]]) + await runPlugin(tree, { blockedTags: ['iframe'] }) + expect(tree.nodes).toEqual([]) + }) + + it('keeps as when the element and the named tag are allowed', async () => { const tree = makeTree([['span', { as: 'Badge' }, 'x']]) await runPlugin(tree, { allowedTags: ['span', 'badge'] }) const el = tree.nodes[0] as [string, any] @@ -656,32 +668,56 @@ describe('security plugin — as prop', () => { expect(el[1].as).toBe('Badge') }) - it('strips is like as', async () => { + it('checks is like as', async () => { const tree = makeTree([['span', { is: 'script' }, 'x']]) await runPlugin(tree, { blockedTags: ['script'] }) - const el = tree.nodes[0] as [string, any] - expect(el[1].is).toBeUndefined() + expect(tree.nodes).toEqual([]) }) - it('checks a JSON binding decoded, as renderers decode it', async () => { - const tree = makeTree([['span', { ':as': '"script"', ':is': '"section"' }, 'x']]) - await runPlugin(tree, { blockedTags: ['script'] }) - const el = tree.nodes[0] as [string, any] - expect(el[1]).toEqual({ ':is': '"section"' }) + it('strips every bound as or is, even one naming an allowed tag', async () => { + const tree = makeTree([ + ['span', { ':as': '"section"', 'v-bind:is': '"section"' }, 'x'], + ['span', { ':as': 'frontmatter.tag', 'v-bind:as': 'props.tag' }, 'x'], + ]) + await runPlugin(tree) + expect((tree.nodes[0] as [string, any])[1]).toEqual({}) + expect((tree.nodes[1] as [string, any])[1]).toEqual({}) }) - it('strips a binding resolved from data at render time, as no check can follow it', async () => { - const tree = makeTree([['span', { ':as': 'frontmatter.tag', 'v-bind:is': 'props.tag' }, 'x']]) + it('strips an object binding that can set as or is, and keeps one that cannot', async () => { + const tree = makeTree([ + ['span', { 'v-bind': '{"as":"AdminPanel"}' }, 'x'], + ['span', { ':': { is: 'AdminPanel' } }, 'x'], + ['span', { 'v-bind': 'frontmatter.props' }, 'x'], + ['span', { 'v-bind': '{"title":"ok"}' }, 'x'], + ]) await runPlugin(tree) - const el = tree.nodes[0] as [string, any] - expect(el[1]).toEqual({}) + expect(tree.nodes.map((node) => (node as [string, any])[1])).toEqual([{}, {}, {}, { 'v-bind': '{"title":"ok"}' }]) }) - it("strips as naming object, whose props were checked against the element's own tag", async () => { + it('strips an as or is that is not a plain tag name', async () => { + const tree = makeTree([ + ['span', { as: 'my component' }, 'x'], + ['span', { as: '