Browse Source
Sanitized HTML in AI Assistant content, applied the AI chat requests rate limit and sorted alarms by severity prioritypull/16888/head
committed by
GitHub
75 changed files with 1069 additions and 266 deletions
@ -0,0 +1,75 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
package org.thingsboard.server.common.data.permission; |
||||
|
|
||||
|
import org.junit.jupiter.api.Test; |
||||
|
|
||||
|
import java.util.Collections; |
||||
|
import java.util.HashMap; |
||||
|
import java.util.HashSet; |
||||
|
import java.util.Map; |
||||
|
import java.util.Set; |
||||
|
|
||||
|
import static org.assertj.core.api.Assertions.assertThat; |
||||
|
|
||||
|
class MergedUserPermissionsTest { |
||||
|
|
||||
|
@Test |
||||
|
void shouldAllowEverythingExceptAi_whenTheRoleAllowsAll() { |
||||
|
MergedUserPermissions permissions = new MergedUserPermissions(Map.of(Resource.ALL, Set.of(Operation.ALL)), Collections.emptyMap()); |
||||
|
|
||||
|
assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isTrue(); |
||||
|
assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue(); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
void shouldAllowEverythingExceptAi_whenAllIsAllowedAndTheAiResourcesAreExcluded() { |
||||
|
MergedUserPermissions permissions = new MergedUserPermissions(expandedExceptAi(Operation.ALL), Collections.emptyMap()); |
||||
|
|
||||
|
assertThat(permissions.hasGenericPermission(Resource.ALL, Operation.ALL)).isFalse(); |
||||
|
assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isTrue(); |
||||
|
assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue(); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
void shouldNotAllowEverything_whenAnotherResourceIsExcluded() { |
||||
|
Map<Resource, Set<Operation>> generic = expandedExceptAi(Operation.ALL); |
||||
|
generic.get(Resource.DEVICE).remove(Operation.WRITE); |
||||
|
|
||||
|
MergedUserPermissions permissions = new MergedUserPermissions(generic, Collections.emptyMap()); |
||||
|
|
||||
|
assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isFalse(); |
||||
|
assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue(); |
||||
|
} |
||||
|
|
||||
|
@Test |
||||
|
void shouldAllowReadOnly_whenReadIsAllowedOnEverythingExceptAi() { |
||||
|
MergedUserPermissions permissions = new MergedUserPermissions(expandedExceptAi(Operation.READ), Collections.emptyMap()); |
||||
|
|
||||
|
assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue(); |
||||
|
assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isFalse(); |
||||
|
} |
||||
|
|
||||
|
static Map<Resource, Set<Operation>> expandedExceptAi(Operation allowed) { |
||||
|
Map<Resource, Set<Operation>> generic = new HashMap<>(); |
||||
|
for (Resource resource : Resource.values()) { |
||||
|
Set<Operation> valid = Resource.operationsByResource.get(resource); |
||||
|
if (resource == Resource.ALL || MergedUserPermissions.AI_RESOURCES.contains(resource) || valid == null) { |
||||
|
continue; |
||||
|
} |
||||
|
Set<Operation> operations = new HashSet<>(valid); |
||||
|
if (allowed == Operation.ALL) { |
||||
|
if (operations.size() > 1) { |
||||
|
operations.remove(Operation.ALL); |
||||
|
} |
||||
|
} else { |
||||
|
operations.retainAll(Set.of(allowed)); |
||||
|
} |
||||
|
if (!operations.isEmpty()) { |
||||
|
generic.put(resource, operations); |
||||
|
} |
||||
|
} |
||||
|
return generic; |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,7 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
||||
|
// SPDX-License-Identifier: BUSL-1.1 |
||||
|
|
||||
|
// Widths at which the AI chat drops secondary text. The chat head's narrow width used by the |
||||
|
// component code is AI_NARROW_HEAD_WIDTH in ai-breakpoints.ts. |
||||
|
$ai-head-status-hidden-below: 400px; |
||||
|
$ai-composer-auto-label-max: 400px; |
||||
@ -0,0 +1,5 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
|
||||
|
// The chat head is narrow below this width (px); the CSS breakpoints of the AI chat are in _ai-breakpoints.scss.
|
||||
|
export const AI_NARROW_HEAD_WIDTH = 500; |
||||
@ -0,0 +1,172 @@ |
|||||
|
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
||||
|
// SPDX-License-Identifier: BUSL-1.1
|
||||
|
import DOMPurify, { UponSanitizeAttributeHookEvent } from 'dompurify'; |
||||
|
|
||||
|
const ALLOWED_TAGS = [ |
||||
|
'a', 'abbr', 'b', 'bdi', 'bdo', 'blockquote', 'br', 'button', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', |
||||
|
'details', 'dfn', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', |
||||
|
'input', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'small', 'span', 'strong', |
||||
|
'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time', 'tr', 'u', 'ul', 'var', 'wbr' |
||||
|
]; |
||||
|
|
||||
|
const ALLOWED_ATTR = [ |
||||
|
'abbr', 'align', 'alt', 'checked', 'cite', 'class', 'colspan', 'datetime', 'dir', 'disabled', 'headers', 'height', 'href', |
||||
|
'id', 'lang', 'ngnonbindable', 'onclick', 'open', 'rel', 'reversed', 'rowspan', 'scope', 'span', 'src', 'start', 'style', 'tabindex', |
||||
|
'target', 'title', 'type', 'valign', 'width' |
||||
|
]; |
||||
|
|
||||
|
const COPY_CODE_CLICK = /^markdownCopyCode\(\d+\)$/; |
||||
|
|
||||
|
const COPY_CODE_ID = /^(codeWrapper|copyCodeId)\d+$/; |
||||
|
|
||||
|
const SAFE_DATA_IMAGE = /^data:image\/(png|jpe?g|gif|webp|bmp);/i; |
||||
|
|
||||
|
const ALLOWED_STYLE_PROPERTIES = new Set([ |
||||
|
'background-color', 'border', 'border-bottom', 'border-collapse', 'border-color', 'border-left', 'border-radius', |
||||
|
'border-right', 'border-spacing', 'border-style', 'border-top', 'border-width', 'color', 'display', 'font-family', |
||||
|
'font-size', 'font-style', 'font-variant', 'font-weight', 'height', 'letter-spacing', 'line-height', 'list-style-type', |
||||
|
'margin', 'margin-bottom', 'margin-left', 'margin-right', 'margin-top', 'max-height', 'max-width', 'min-height', |
||||
|
'min-width', 'opacity', 'overflow', 'overflow-wrap', 'padding', 'padding-bottom', 'padding-left', 'padding-right', |
||||
|
'padding-top', 'table-layout', 'text-align', 'text-decoration', 'text-decoration-color', 'text-decoration-line', |
||||
|
'text-decoration-style', 'text-indent', 'text-transform', 'vertical-align', 'white-space', 'width', 'word-break' |
||||
|
]); |
||||
|
|
||||
|
const ALLOWED_STYLE_FUNCTIONS = new Set(['rgb', 'rgba', 'hsl', 'hsla', 'calc', 'min', 'max', 'clamp']); |
||||
|
|
||||
|
let purifier: ReturnType<typeof DOMPurify> | null = null; |
||||
|
|
||||
|
/** |
||||
|
* Sanitizes HTML that is not trusted, such as AI content, for rendering with innerHTML. Only an allowlist of elements |
||||
|
* and attributes is kept: scripts, event handlers, SVG, forms and frames are dropped, and ids only stay on the copy-code |
||||
|
* markup of the markdown renderer. Images load only from this origin or from inline image data; an image from another |
||||
|
* host becomes a link to it, so nothing is fetched until the person opens it. Styles keep only text and box properties |
||||
|
* with plain values. |
||||
|
*/ |
||||
|
export function sanitizeMarkdownHtml(html: string): string { |
||||
|
const body = getPurifier().sanitize(html, { |
||||
|
ALLOWED_TAGS, |
||||
|
ALLOWED_ATTR, |
||||
|
ALLOW_DATA_ATTR: true, |
||||
|
ALLOW_ARIA_ATTR: true, |
||||
|
RETURN_DOM: true |
||||
|
}) as HTMLElement; |
||||
|
postProcess(body); |
||||
|
return body.innerHTML; |
||||
|
} |
||||
|
|
||||
|
function getPurifier(): ReturnType<typeof DOMPurify> { |
||||
|
if (!purifier) { |
||||
|
purifier = DOMPurify(window); |
||||
|
purifier.addHook('uponSanitizeAttribute', sanitizeAttribute); |
||||
|
} |
||||
|
return purifier; |
||||
|
} |
||||
|
|
||||
|
function sanitizeAttribute(node: Element, data: UponSanitizeAttributeHookEvent): void { |
||||
|
const value = data.attrValue ?? ''; |
||||
|
switch (data.attrName) { |
||||
|
case 'onclick': |
||||
|
if (COPY_CODE_CLICK.test(value.trim()) && node.classList.contains('code-wrapper')) { |
||||
|
data.forceKeepAttr = true; |
||||
|
} else { |
||||
|
data.keepAttr = false; |
||||
|
} |
||||
|
break; |
||||
|
case 'id': |
||||
|
if (!COPY_CODE_ID.test(value)) { |
||||
|
data.keepAttr = false; |
||||
|
} |
||||
|
break; |
||||
|
case 'style': |
||||
|
data.attrValue = sanitizeStyle(value); |
||||
|
if (!data.attrValue) { |
||||
|
data.keepAttr = false; |
||||
|
} |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function postProcess(root: HTMLElement): void { |
||||
|
root.querySelectorAll('img').forEach(img => { |
||||
|
if (!isSafeImageSource(img.getAttribute('src'))) { |
||||
|
replaceExternalImage(img); |
||||
|
} |
||||
|
}); |
||||
|
root.querySelectorAll('button').forEach(button => { |
||||
|
if (!isCopyCodeButton(button)) { |
||||
|
button.replaceWith(...Array.from(button.childNodes)); |
||||
|
} |
||||
|
}); |
||||
|
root.querySelectorAll('input').forEach(input => { |
||||
|
if (input.getAttribute('type') !== 'checkbox' || !input.hasAttribute('disabled')) { |
||||
|
input.remove(); |
||||
|
} |
||||
|
}); |
||||
|
root.querySelectorAll('a[target]').forEach(link => link.setAttribute('rel', 'noopener noreferrer')); |
||||
|
} |
||||
|
|
||||
|
function isSafeImageSource(src: string | null): boolean { |
||||
|
const value = src?.trim(); |
||||
|
if (!value) { |
||||
|
return false; |
||||
|
} |
||||
|
if (value.toLowerCase().startsWith('data:')) { |
||||
|
return SAFE_DATA_IMAGE.test(value); |
||||
|
} |
||||
|
try { |
||||
|
return new URL(value, window.location.href).origin === window.location.origin; |
||||
|
} catch { |
||||
|
return false; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function replaceExternalImage(img: HTMLImageElement): void { |
||||
|
let href: URL | null = null; |
||||
|
try { |
||||
|
href = new URL(img.getAttribute('src')?.trim() ?? '', window.location.href); |
||||
|
} catch { |
||||
|
href = null; |
||||
|
} |
||||
|
if (!href || !/^https?:$/.test(href.protocol) || href.origin === window.location.origin) { |
||||
|
img.remove(); |
||||
|
return; |
||||
|
} |
||||
|
const link = img.ownerDocument.createElement('a'); |
||||
|
link.setAttribute('href', href.href); |
||||
|
link.setAttribute('target', '_blank'); |
||||
|
link.setAttribute('rel', 'noopener noreferrer'); |
||||
|
link.textContent = img.getAttribute('alt')?.trim() || img.getAttribute('title')?.trim() || href.host; |
||||
|
img.replaceWith(link); |
||||
|
} |
||||
|
|
||||
|
function isCopyCodeButton(button: HTMLButtonElement): boolean { |
||||
|
const wrapper = button.parentElement; |
||||
|
return button.classList.contains('clipboard-btn') && !!wrapper?.classList.contains('code-wrapper') && |
||||
|
COPY_CODE_CLICK.test(wrapper.getAttribute('onclick')?.trim() ?? ''); |
||||
|
} |
||||
|
|
||||
|
function sanitizeStyle(style: string): string { |
||||
|
const declarations = style.split(';').map(declaration => declaration.trim()).filter(declaration => declaration); |
||||
|
const kept = declarations.filter(declaration => { |
||||
|
const colon = declaration.indexOf(':'); |
||||
|
if (colon <= 0) { |
||||
|
return false; |
||||
|
} |
||||
|
const property = declaration.substring(0, colon).trim().toLowerCase(); |
||||
|
const value = declaration.substring(colon + 1).trim().toLowerCase(); |
||||
|
return ALLOWED_STYLE_PROPERTIES.has(property) && isSafeStyleValue(property, value); |
||||
|
}); |
||||
|
return kept.length === declarations.length ? style : kept.join('; '); |
||||
|
} |
||||
|
|
||||
|
function isSafeStyleValue(property: string, value: string): boolean { |
||||
|
if (!value || /[\\@<>"']|\/\*|url|expression|image|attr\s*\(/.test(value)) { |
||||
|
return false; |
||||
|
} |
||||
|
for (const call of value.matchAll(/([a-z-]+)\s*\(/g)) { |
||||
|
if (!ALLOWED_STYLE_FUNCTIONS.has(call[1])) { |
||||
|
return false; |
||||
|
} |
||||
|
} |
||||
|
return !(property.startsWith('margin') && value.includes('-')); |
||||
|
} |
||||
Loading…
Reference in new issue