Search code examples
javascripthtml5-canvascorsfrontendsame-origin-policy

Why is crossorigin attribute necessary to load images into a canvas and render it?


When loading an Image via setting the src attribute to the URL into a Canvas and trying to call toDataURL() on the canvas, this will only be allowed when the crossorigin attribute is set before loading the Image.

Why is this though? If the image has the proper Allow-Access-Control-Origin header. Is it because the Origin attribute is not used when loading an Image via a URL (i.e. the Origin header is only included when the crossorigin attribute is set)?


Solution

  • Being that images are commonly used to load arbitrary user-defined content, and image data just opens up another vector that could be for example used to hide executable code that can be decoded later to bypass XSS filters. And ImageData and OffscreenCanvas can be passed across frames and to workers.
    And there really aren't any valid use cases for allowing arbitrary image data from an element be retrieved without it being explicitly requested for, with a simple attribute. (Especially when it can just be rendered)
    I think the question should be, why should it be allowed by default?

    Not to mention the overhead of keeping a paper-trail for cors whitelisted (untainted) resources, when you can just have them blacklisted by default.


    Basically tells the browser whether it should use a CORS request, and what headers to expect. Specifically whether to send and expect credentials.

    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-crossorigin

    crossorigin Indicates if the fetching of the image must be done using CORS. CORS-enabled images can be reused in the element without being "tainted." Allowed values:

    anonymous A cross-origin request (i.e., with Origin HTTP header) is performed, but no credentials are sent (i.e., no cookie, X.509 certificate, or HTTP Basic authentication). If the server does not give credentials to the origin site (by not setting the Access-Control-Allow-Origin HTTP header), the image will be tainted and its usage restricted.

    use-credentials A cross-origin request (i.e., with the Origin HTTP header) performed along with credentials sent (i.e., a cookie, certificate, or HTTP Basic authentication). If the server does not give credentials to the origin site (through the Access-Control-Allow-Credentials HTTP header), the image will be tainted and its usage restricted.

    If the attribute is not present, the resource is fetched without a CORS request (i.e., without sending the Origin HTTP header), preventing its non-tainted usage in elements. If an invalid value, it is handled as if the anonymous value was used. See CORS settings attributes for additional information.