Security improvements #393

Closed
opened 2026-10-21 05:49:39 +00:00 by jsheunis · 5 comments
Owner

Firstly, packages and dependencies need to be upgraded to take care of existing vulnerabilities. This has mostly been done in d31681bf1b

Then, additional measures are necessary, especially in the context of a multi-tenant-based approach. The core idea here is that the administrator of a shacl-vue deployment and the provider of a configuration are not the same people/entities. The administrator build, deploys, and serves a single shacl-vue instance, and multiple tenants can use this frontend while supplying their own configuration files, and then the UI will present differently for them. It makes sense that a tenant will configure the user-facing aspects of their UI/UX, but this opens up vulnerabilities. We need to heighten security in shacl-vue in order to prevent any number of possible attacks. And any newly introduced security-specific config options should remain under the sole control of the system administrator (see also: #392)

Investigating vulnerabilities

shacl-vue has several features that allow externally provided resources to be fetched, loaded into some format, and then interpreted/displayed inside the app:

  • content loading, allows the specification of arbitrary urls from which content will be fetched at app startup, and which is then stored in memory to be used somewhere in the app; no restrictions are currently placed on content type or origins or anything
  • front_page_content, for which the source is loaded via the content loading appproach mentioned above, is HTML that is rendered in a VueJS v-html tag. This basically injects arbitrary HTML dynamically into a div. This arbitrary HTML can also contain or link JS scripts.
  • Application inputs sources are the URLs via which the app's schema and data are loaded. The OWL (class_url) and SHACL (shapes_url) and RDF (data_url; hardly ever provided in our deployments, but operational nonetheless). The turtle at these URLs are fetched and put directly into an N3 store.
  • runtime plugins allow administrators of a shacl-vue deployment to include custom JS plugin code and custom VueJS components in the build process such that they become available to the deplopyment
  • some shacl-vue config options are urls for which the content isn't fetched but the url is used in e.g. an href or src tag

Things to protect against

  • XSS: cross-site scripting attacks. If v-html-injected html runs scripts that have malicious intent, or if a url containing executable javascript is fetched.
  • Unapproved sources: it is possible that the config specifies content to be fetched from an untrusted source
  • Undesired/malicious redirects: it is possible that the config specifies content to be fetched from an (untrusted) source, which redirects the browser to another (untrusted) source
  • Fetching large files unintentionally
  • Fetching content types that shouldn't be supported
  • Unintentionally sending credentials along with requests where the endpoint does not require it

Mechanisms of protection

  • Same origin policy: automatic in browsers
  • HTML sanitization: this takes incoming HTML and strips any unapproved tags/attributes from the content (e.g. <script>) in order to prevent unwanted scripts from running, i.e. preventing client-side XSS attacks.
  • Content security policy:
    • can restrict e.g. the types of resources that are allowed to be loaded by the app/site
    • restricts how scripts loaded by specific origins can interact with app (e.g. white/black listing)

Features to implement in shacl-vue

1. Content security policy

Useful options:

  • Fetch directives control locations from which certain resource types may be loaded
    • connect-src
    • default-src
    • more...

This can either be provided as an HTTP header in all responses from the server, or as content in the meta tag (with http-equiv attribute). The latter does not have access to all CSP features, but supports the useful ones for our use case.

Example:


<head>
  <meta charset="UTF-8" />

  <meta
    http-equiv="Content-Security-Policy"
    content="
      default-src 'self';
      script-src 'self';
      connect-src 'self'
        https://api.example.com
        https://content.example.com;
      img-src 'self' https://images.example.com;
      style-src 'self';
      object-src 'none';
      base-uri 'none';
      form-action 'self';
    "
  />

  <title>shacl-vue</title>
</head>

An important point regarding CSP specification and shacl-vue: should such options be specified via shacl-vue config? Or can they even? As far as I can figure out, this won't be possible because:

  1. The possible CSP info in the meta tag of index.html will be processed before the config file is even loaded, i.e. before
  2. Modifications to the content attribute, which would be necessary once the possible CSP options are read from config, aren't processed by the browser. I.e. this would be ignored, as if no CSP is specified.

This leaves two options:

  • CSP provided from server in http response headers
  • Meta-based CSP where the options are known+specified at build time

These can of course be combined, we are not forced to decide on a single orthogonal aproach. This suggests that it would be useful to support build-time (i.e. Vite environment variable based) specification of CSP options in shacl-vue (see issue: #392)

To implement:

Meta-based CSP where the options are known+specified at build time

we can use Vite ENV variables, either set explicitly in build runtime environment or provided via an env file. e.g. in a file env.production:

VITE_CSP_CONNECT_SRC="'self' https://api.example.com https://content.example.com"

and then this can be used in the Vue app:

<head>
  <meta charset="UTF-8" />

  <meta
    http-equiv="Content-Security-Policy"
    content="default-src 'self'; script-src 'self'; connect-src %VITE_CSP_CONNECT_SRC%"
  />

  <title>My Vue App</title>
</head>

2. Sanitization

We can use DOMPurify in a new component that will render sanitized html, via a computed ref. For example:

const sanitizedHtml = computed(() =>
  DOMPurify.sanitize(props.html, {
    USE_PROFILES: { html: true },
  })
)

Here we can consider just including html (as opposed to also allowing svg and mathml). But a wide range of configuration options are available: https://github.com/cure53/DOMPurify#can-i-configure-dompurify. We should decide how we want to approach this. An option is to allow and pass through all DOMPurify config options, i.e. make it configurable via shacl-vue. I don't think the shacl-vue config file is the correct home for this, because in the tenant setup that would allow individual tenants to specify how strict (or not) the sanitization should be, which would work against the reason for sanitizing in the first place. This means config during build time, i.e. the same approach as suggested above for specifying a content security policy.

3. Fetch restrictions

The idea here is to allow restriction of several aspects of content being fetched by shacl-vue. The CSP fetch directive can already control/limit (via allowlist) the origins from which content can be fetched, but does not help with restricting other apsects such as resource type and size, unintentional inclusion of credentials, redirect allowances, etc. All of this can be supported by updating the fetch calls inside shacl-vue, perhaps creating a new central fetch function that can be configured with these options. An illustrative example:

const url = 'some-remote-resource'
const kind = 'text'
const max_size = '10mb'
const max_time = '10000'
const redirect_option = 'error'
const creds = existing_creds | 'omit'
const response = await fetch(url, {
    method: 'GET',
    mode: 'cors',
    credentials: creds,
    redirect: redirect_option,
    signal: AbortSignal.timeout(max_time),
    headers: {
      Accept: {
        html: 'text/html',
        json: 'application/json',
        yaml: 'application/yaml, text/yaml, text/plain',
        text: 'text/plain',
      }[kind],
    },
})
  • credentials are explicitly omitted unless necessary to include
  • max time for request can be specified, and timeout happens after that
  • redirect can be allowed or not
  • max file size can be processed (and rejected) after fetching / or if possible after a head request
  • allowed resource type(s) can be specified

All of these, again, could be configured at app startup. While shacl-vue config is also possible, in the tenant approach this would work against the desired effect.

What's next?

Implementation!

Firstly, packages and dependencies need to be upgraded to take care of existing vulnerabilities. This has mostly been done in https://hub.psychoinformatics.de/orinoco/shacl-vue/commit/d31681bf1b91fbe6be9bd52cd9641cdda105a118 Then, additional measures are necessary, especially in the context of a multi-tenant-based approach. The core idea here is that the administrator of a `shacl-vue` deployment and the provider of a configuration are not the same people/entities. The administrator build, deploys, and serves a single `shacl-vue` instance, and multiple tenants can use this frontend while supplying their own configuration files, and then the UI will present differently for them. It makes sense that a tenant will configure the user-facing aspects of their UI/UX, but this opens up vulnerabilities. We need to heighten security in `shacl-vue` in order to prevent any number of possible [attacks](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks). And any newly introduced security-specific config options should remain under the sole control of the system administrator (see also: https://hub.psychoinformatics.de/orinoco/shacl-vue/issues/392) ## Investigating vulnerabilities `shacl-vue` has several features that allow externally provided resources to be fetched, loaded into some format, and then interpreted/displayed inside the app: - [content loading](https://shacl-vue.psychoinformatics.de/app-configuration.html#content), allows the specification of arbitrary urls from which content will be fetched at app startup, and which is then stored in memory to be used somewhere in the app; no restrictions are currently placed on content type or origins or anything - [`front_page_content`](https://shacl-vue.psychoinformatics.de/app-configuration.html#front-page-content), for which the source is loaded via the content loading appproach mentioned above, is HTML that is rendered in a VueJS `v-html` tag. This basically injects arbitrary HTML dynamically into a div. This arbitrary HTML can also contain or link JS scripts. - [Application inputs sources](https://shacl-vue.psychoinformatics.de/app-configuration.html#application-inputs-sources) are the URLs via which the app's schema and data are loaded. The OWL (`class_url`) and SHACL (`shapes_url`) and RDF (`data_url`; hardly ever provided in our deployments, but operational nonetheless). The turtle at these URLs are fetched and put directly into an N3 store. - [runtime plugins](https://shacl-vue.psychoinformatics.de/features-runtime-plugins.html) allow administrators of a `shacl-vue` deployment to include custom JS plugin code and custom VueJS components in the build process such that they become available to the deplopyment - some `shacl-vue` config options are urls for which the content isn't fetched but the url is used in e.g. an `href` or `src` tag ## Things to protect against - [XSS: cross-site scripting attacks](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/XSS). If `v-html`-injected html runs scripts that have malicious intent, or if a url containing executable javascript is fetched. - Unapproved sources: it is possible that the config specifies content to be fetched from an untrusted source - Undesired/malicious redirects: it is possible that the config specifies content to be fetched from an (untrusted) source, which redirects the browser to another (untrusted) source - Fetching large files unintentionally - Fetching content types that shouldn't be supported - Unintentionally sending credentials along with requests where the endpoint does not require it ## Mechanisms of protection - [Same origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Same-origin_policy): automatic in browsers - HTML sanitization: this takes incoming HTML and strips any unapproved tags/attributes from the content (e.g. `<script>`) in order to prevent unwanted scripts from running, i.e. preventing client-side XSS attacks. - Widely used JS library for sanitization: [DOMPurify](https://www.npmjs.com/package/dompurify) - See also: Trusted Types API: https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API - [Content security policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP): - can restrict e.g. the types of resources that are allowed to be loaded by the app/site - restricts how scripts loaded by specific origins can interact with app (e.g. white/black listing) ## Features to implement in `shacl-vue` ### 1. Content security policy Useful options: - [Fetch directives](https://developer.mozilla.org/en-US/docs/Glossary/Fetch_directive) control locations from which certain resource types may be loaded - `connect-src` - `default-src` - more... This can either be provided as an HTTP header in all responses from the server, or as `content` in the `meta` tag (with `http-equiv` attribute). The latter does not have access to all CSP features, but supports the useful ones for our use case. Example: ```html <head> <meta charset="UTF-8" /> <meta http-equiv="Content-Security-Policy" content=" default-src 'self'; script-src 'self'; connect-src 'self' https://api.example.com https://content.example.com; img-src 'self' https://images.example.com; style-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; " /> <title>shacl-vue</title> </head> ``` An important point regarding CSP specification and `shacl-vue`: should such options be specified via `shacl-vue` config? Or can they even? As far as I can figure out, this won't be possible because: 1. The possible CSP info in the meta tag of `index.html` will be processed before the config file is even loaded, i.e. before 2. Modifications to the `content` attribute, which would be necessary once the possible CSP options are read from config, aren't processed by the browser. I.e. this would be ignored, as if no CSP is specified. This leaves two options: - CSP provided from server in http response headers - Meta-based CSP where the options are known+specified at build time These can of course be combined, we are not forced to decide on a single orthogonal aproach. This suggests that it would be useful to support build-time (i.e. Vite environment variable based) specification of CSP options in `shacl-vue` (see issue: https://hub.psychoinformatics.de/orinoco/shacl-vue/issues/392) To implement: > Meta-based CSP where the options are known+specified at build time we can use Vite ENV variables, either set explicitly in build runtime environment or provided via an env file. e.g. in a file `env.production`: ``` VITE_CSP_CONNECT_SRC="'self' https://api.example.com https://content.example.com" ``` and then this can be used in the Vue app: ```html <head> <meta charset="UTF-8" /> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; connect-src %VITE_CSP_CONNECT_SRC%" /> <title>My Vue App</title> </head> ``` ### 2. Sanitization We can use DOMPurify in a new component that will render sanitized html, via a computed ref. For example: ```javascript= const sanitizedHtml = computed(() => DOMPurify.sanitize(props.html, { USE_PROFILES: { html: true }, }) ) ``` Here we can consider just including html (as opposed to also allowing svg and mathml). But a wide range of configuration options are available: https://github.com/cure53/DOMPurify#can-i-configure-dompurify. We should decide how we want to approach this. An option is to allow and pass through all DOMPurify config options, i.e. make it configurable via `shacl-vue`. I don't think the `shacl-vue` config file is the correct home for this, because in the tenant setup that would allow individual tenants to specify how strict (or not) the sanitization should be, which would work against the reason for sanitizing in the first place. This means config during build time, i.e. the same approach as suggested above for specifying a content security policy. ### 3. Fetch restrictions The idea here is to allow restriction of several aspects of content being fetched by `shacl-vue`. The CSP fetch directive can already control/limit (via allowlist) the origins from which content can be fetched, but does not help with restricting other apsects such as resource type and size, unintentional inclusion of credentials, redirect allowances, etc. All of this can be supported by updating the `fetch` calls inside `shacl-vue`, perhaps creating a new central `fetch` function that can be configured with these options. An illustrative example: ```javascript= const url = 'some-remote-resource' const kind = 'text' const max_size = '10mb' const max_time = '10000' const redirect_option = 'error' const creds = existing_creds | 'omit' const response = await fetch(url, { method: 'GET', mode: 'cors', credentials: creds, redirect: redirect_option, signal: AbortSignal.timeout(max_time), headers: { Accept: { html: 'text/html', json: 'application/json', yaml: 'application/yaml, text/yaml, text/plain', text: 'text/plain', }[kind], }, }) ``` - credentials are explicitly omitted unless necessary to include - max time for request can be specified, and timeout happens after that - redirect can be allowed or not - max file size can be processed (and rejected) after fetching / or if possible after a head request - allowed resource type(s) can be specified All of these, again, could be configured at app startup. While `shacl-vue` config is also possible, in the tenant approach this would work against the desired effect. ## What's next? Implementation!
Author
Owner

While working on:

We can use DOMPurify in a new component that will render sanitized html, via a computed ref. For example:

const sanitizedHtml = computed(() =>
  DOMPurify.sanitize(props.html, {
    USE_PROFILES: { html: true },
  })
)

I searched the app for all usage of v-html and saw several occurrences, e.g.:

<p v-html="formattedDescription" class="quote-description"></p>

<span v-for="(note, i) in fieldNotes">
    <em v-if="i == 0"><p v-html="addCodeTagsToText(note, 'Notes: <br/>* ')" class="quote-description"></p></em>
    <em v-else><p v-html="addCodeTagsToText(note, '* ')" class="quote-description"></p></em>
</span>

<div
    class="markdown-preview"
    v-html="renderedMarkdown"
/>

<span
    class="custom-svg"
    v-html="icon"
/>

<div class="markdown-preview" v-html="renderedMarkdown" />

So we actually need the component to be able to deal with rendering all these base tags while sanitizing the html, and also render these tags with the intended classes etc.

A different way to approach this would be to use a Vue custom directive. So we would introduce something like a v-html-sanitized tag instead of using the existing v-html tag. I need to read some more about how this would need to be built and declared and used...

After reading that:

Using custom directives on components is not recommended. Unexpected behaviour may occur when a component has multiple root nodes.

I decided against it, and rather just implemented the component. This is done in b1e269112c

While working on: > We can use DOMPurify in a new component that will render sanitized html, via a computed ref. For example: > ``` > const sanitizedHtml = computed(() => > DOMPurify.sanitize(props.html, { > USE_PROFILES: { html: true }, > }) > ) > ``` I searched the app for all usage of `v-html` and saw several occurrences, e.g.: ```html <p v-html="formattedDescription" class="quote-description"></p> <span v-for="(note, i) in fieldNotes"> <em v-if="i == 0"><p v-html="addCodeTagsToText(note, 'Notes: <br/>* ')" class="quote-description"></p></em> <em v-else><p v-html="addCodeTagsToText(note, '* ')" class="quote-description"></p></em> </span> <div class="markdown-preview" v-html="renderedMarkdown" /> <span class="custom-svg" v-html="icon" /> <div class="markdown-preview" v-html="renderedMarkdown" /> ``` So we actually need the component to be able to deal with rendering all these base tags while sanitizing the html, and also render these tags with the intended classes etc. A different way to approach this would be to use a [Vue custom directive](https://vuejs.org/guide/reusability/custom-directives.html). So we would introduce something like a `v-html-sanitized` tag instead of using the existing `v-html` tag. I need to read some more about how this would need to be built and declared and used... After reading that: > Using custom directives on components is not recommended. Unexpected behaviour may occur when a component has multiple root nodes. I decided against it, and rather just implemented the component. This is done in https://hub.psychoinformatics.de/orinoco/shacl-vue/commit/b1e269112c2d910662728e628522705174a24e5e
Author
Owner

Next step is CSP. An implementation is fairly straightforward: we need to load the build config (already supported), then check if any CSP options are defined, then parse these into the format that they are needed in in the index.html.

Example config:

CSP_CONTENT:
  connect-src:
    - "'self'"
    - https://hub.psychoinformatics.de
    - https://cerebra.fz-juelich.de
    - https://concepts.datalad.org

Example format:

  <meta
    http-equiv="Content-Security-Policy"
    content="connect-src 'self' https://cerebra.fz-juelich.de https://concepts.datalad.org;"
  />

We can do the parsing as follows:

function serializeCsp(csp) {
    return Object.entries(csp).map(([directive, sources]) => `${directive} ${sources.join(' ')};`).join(' ');
}

const buildConfig = loadBuildConfig();
buildConfig.CSP_CONTENT = buildConfig.CSP_CONTENT ? serializeCsp(buildConfig.CSP_CONTENT) : '';

and then use it in index.html:

        <meta
            http-equiv="Content-Security-Policy"
            content="%CSP_CONTENT%"
        />

if CSP_CONTENT is an empty string, no CSP is enforced by the browser, so the default is as expected.

Next step is CSP. An implementation is fairly straightforward: we need to load the build config (already supported), then check if any CSP options are defined, then parse these into the format that they are needed in in the `index.html`. Example config: ```yaml CSP_CONTENT: connect-src: - "'self'" - https://hub.psychoinformatics.de - https://cerebra.fz-juelich.de - https://concepts.datalad.org ``` Example format: ```html <meta http-equiv="Content-Security-Policy" content="connect-src 'self' https://cerebra.fz-juelich.de https://concepts.datalad.org;" /> ``` We can do the parsing as follows: ```js function serializeCsp(csp) { return Object.entries(csp).map(([directive, sources]) => `${directive} ${sources.join(' ')};`).join(' '); } const buildConfig = loadBuildConfig(); buildConfig.CSP_CONTENT = buildConfig.CSP_CONTENT ? serializeCsp(buildConfig.CSP_CONTENT) : ''; ``` and then use it in `index.html`: ```html <meta http-equiv="Content-Security-Policy" content="%CSP_CONTENT%" /> ``` if `CSP_CONTENT` is an empty string, no CSP is enforced by the browser, so the default is as expected.
Author
Owner

Basic CSP configuration support is now provided in bb69bd46d8

Now the question becomes: how should we construct allowlists for this, and which directives should we use. And should we rather approach it conservatively or liberally? E.g. if one specifies the default-src directive as 'self', it will say to the browser: you can only fetch resources for this page from the same domain that the site is hosted on. Then adding specific domains under more specific directives, e.g. image-src or font-src would individually and systematically open the gate for more sources. This would be the conservative route, and one would have to identify all possible trusted sources of content (fonts, images, text content, more). On the liberal side, one could exclude a directive setting to basically allow everything; and then pivot on specific directives that one might want to control (e.g. connect-src that controls scripts).

Basic CSP configuration support is now provided in https://hub.psychoinformatics.de/orinoco/shacl-vue/commit/bb69bd46d827ebf07b753a0d4c9760c417e730f3 Now the question becomes: how should we construct allowlists for this, and which directives should we use. And should we rather approach it conservatively or liberally? E.g. if one specifies the `default-src` directive as `'self'`, it will say to the browser: you can only fetch resources for this page from the same domain that the site is hosted on. Then adding specific domains under more specific directives, e.g. `image-src` or `font-src` would individually and systematically open the gate for more sources. This would be the conservative route, and one would have to identify all possible trusted sources of content (fonts, images, text content, more). On the liberal side, one could exclude a directive setting to basically allow everything; and then pivot on specific directives that one might want to control (e.g. `connect-src` that controls scripts).
Author
Owner

While working a general "secure fetch" wrapper, which is intended to:

  • set an explicit mode (basically always cors)
  • handle credential setting explicitly (basically always 'omit'; our important credentials are handled via auth headers)
  • specify how to handle redirects (we could conservatively always error, but this could exclude legitimate origins)
  • abort the request after a specified timeout (via signal; do we actually want this? is it useful for security? what is a sensible timeout value?)
  • set allowed accept headers
  • limit response content size
  • validate response types

I find myself questioning to what extent some of these features are really helpful i.t.o. improving security when looking at the complexity it introduces because of difficulty deciding on sensible values.

My feeling is that the following could be useful:

  • mode: 'cors'
  • credentials: 'omit'
  • checking requested file type against allowed accept headers, and validating the response file type against the same

I am not so sure about the rest...

This is what I currently have:

const MAX_BYTES = import.meta.env.FETCH.MAX_BYTES || 1_000_000;
const TIMEOUT_MS = import.meta.env.FETCH.TIMEOUT_MS || 10_000;
const CONTENT_TYPES = import.meta.env.FETCH.CONTENT_TYPES || {
    json: [
        'application/json',
        'application/problem+json',
    ],
    html: [
        'text/html',
    ],
    yaml: [
        'application/yaml',
        'application/x-yaml',
        'text/yaml',
        'text/plain',
    ],
    text: [
        'text/plain',
    ],
    rdf: [
        'application/ld+json', // JSON-LD
        'application/rdf+xml', // RDF/XML
        'text/turtle', // Turtle
        'application/n-triples', // N-Triples
        'application/trig', // TriG
    ]
};

export async function secureFetch(
    url,
    kind,
    {
        maxBytes = MAX_BYTES,
        timeoutMs = TIMEOUT_MS,
        signal,
        ...fetchOptions
    } = {},
) {
    const acceptedTypes = CONTENT_TYPES[kind];

    if (!acceptedTypes) {
        throw new Error(`Unsupported content kind: ${kind}`);
    }

    const headers = new Headers(fetchOptions.headers || {});
    headers.set('Accept', acceptedTypes.join(', '));

    const response = await fetch(url, {
        ...fetchOptions,
        mode: 'cors',
        credentials: 'omit',
        signal: signal
            ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)])
            : AbortSignal.timeout(timeoutMs),
        headers,
    });

    if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
    }

    const contentType = (
        response.headers.get('content-type') ?? ''
    ).split(';')[0].trim().toLowerCase();

    if (!acceptedTypes.includes(contentType)) {
        throw new Error(`Unexpected content type: ${contentType}`);
    }

    const declaredLength = response.headers.get('content-length')
    if (declaredLength !== null) {
        const length = Number(declaredLength)
        if (!Number.isFinite(length) || length < 0) {
            // throw new Error('Invalid Content-Length')
        } else if (length > maxBytes) {
            throw new Error('Response too large')
        } else {
            // 
        }
    }

    return response;
}

Searching through the code for instances of fetch-GET, i found the following places where the wrapper would need to be used:

  1. configuration.js composable: fetching the config file (we know this will be in JSON or YAML format)
  2. configuration.js composable: fetching content at URLs provided via config file (here we are not sure what file type it is, although we could try to derive it from the extension in the URL)
  3. useData.js composable: fetching data from dumpthings (here we know this will be in TTL or JSON format - the latter when paginated)
  4. Indirectly: in the useClasses.js and useShapes.js composables, we use loadRDF which is a method defined in shacl-tulip, which in turn uses a modified fetch (import fetch from '@rdfjs/fetch-lite'). Here we know that the source files would be some RDF format, we currently restrict it to 'text/turtle'
While working a general "secure fetch" wrapper, which is intended to: - set an explicit `mode` (basically always `cors`) - handle credential setting explicitly (basically always 'omit'; our important credentials are handled via auth headers) - specify how to handle `redirect`s (we could conservatively always `error`, but this could exclude legitimate origins) - abort the request after a specified timeout (via `signal`; do we actually want this? is it useful for security? what is a sensible timeout value?) - set allowed accept headers - limit response content size - validate response types I find myself questioning to what extent some of these features are really helpful i.t.o. improving security when looking at the complexity it introduces because of difficulty deciding on sensible values. My feeling is that the following could be useful: - `mode: 'cors'` - `credentials: 'omit'` - checking requested file type against allowed accept headers, and validating the response file type against the same I am not so sure about the rest... This is what I currently have: ```javascript const MAX_BYTES = import.meta.env.FETCH.MAX_BYTES || 1_000_000; const TIMEOUT_MS = import.meta.env.FETCH.TIMEOUT_MS || 10_000; const CONTENT_TYPES = import.meta.env.FETCH.CONTENT_TYPES || { json: [ 'application/json', 'application/problem+json', ], html: [ 'text/html', ], yaml: [ 'application/yaml', 'application/x-yaml', 'text/yaml', 'text/plain', ], text: [ 'text/plain', ], rdf: [ 'application/ld+json', // JSON-LD 'application/rdf+xml', // RDF/XML 'text/turtle', // Turtle 'application/n-triples', // N-Triples 'application/trig', // TriG ] }; export async function secureFetch( url, kind, { maxBytes = MAX_BYTES, timeoutMs = TIMEOUT_MS, signal, ...fetchOptions } = {}, ) { const acceptedTypes = CONTENT_TYPES[kind]; if (!acceptedTypes) { throw new Error(`Unsupported content kind: ${kind}`); } const headers = new Headers(fetchOptions.headers || {}); headers.set('Accept', acceptedTypes.join(', ')); const response = await fetch(url, { ...fetchOptions, mode: 'cors', credentials: 'omit', signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs), headers, }); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } const contentType = ( response.headers.get('content-type') ?? '' ).split(';')[0].trim().toLowerCase(); if (!acceptedTypes.includes(contentType)) { throw new Error(`Unexpected content type: ${contentType}`); } const declaredLength = response.headers.get('content-length') if (declaredLength !== null) { const length = Number(declaredLength) if (!Number.isFinite(length) || length < 0) { // throw new Error('Invalid Content-Length') } else if (length > maxBytes) { throw new Error('Response too large') } else { // } } return response; } ``` Searching through the code for instances of `fetch`-`GET`, i found the following places where the wrapper would need to be used: 1. `configuration.js` composable: [fetching the config file](https://hub.psychoinformatics.de/orinoco/shacl-vue/src/commit/6a12a32f533c9cd300851234137a4eba39c54f14/src/composables/configuration.js#L178) (we know this will be in JSON or YAML format) 2. `configuration.js` composable: [fetching content at URLs provided via config file](https://hub.psychoinformatics.de/orinoco/shacl-vue/src/commit/6a12a32f533c9cd300851234137a4eba39c54f14/src/composables/configuration.js#L289) (here we are not sure what file type it is, although we could try to derive it from the extension in the URL) 3. `useData.js` composable: [fetching data from `dumpthings`](https://hub.psychoinformatics.de/orinoco/shacl-vue/src/commit/6a12a32f533c9cd300851234137a4eba39c54f14/src/composables/useData.js#L274) (here we know this will be in TTL or JSON format - the latter when paginated) 4. Indirectly: in the `useClasses.js` and `useShapes.js` composables, we use `loadRDF` which is a method defined in `shacl-tulip`, which in turn uses a modified `fetch` (`import fetch from '@rdfjs/fetch-lite'`). Here we know that the source files would be some RDF format, we currently restrict it to `'text/turtle'`
Author
Owner

Added in #394

Added in https://hub.psychoinformatics.de/orinoco/shacl-vue/pulls/394
Sign in to join this conversation.
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
orinoco/shacl-vue#393
No description provided.