Process Untrusted HTML Safely in Python

To restrict untrusted HTML in Python, create a Configuration, add the required Sandbox flags to configuration.security, and pass that configuration to HTMLDocument when loading the source. Apply the restrictions before the document is created.

Aspose.HTML for Python via .NET sandbox flags control selected capabilities of an HTML document during loading and processing. They can block script execution, image loading, form submission, plugins, navigation, and other browser-like behavior.

Use these restrictions when an application processes HTML from users, external systems, email content, scraped pages, or another source that is not fully controlled. Aspose.HTML sandboxing is a document-processing control, not an operating-system security boundary. It should complement normal process, file-system, and network protections rather than replace them.

Configure HTML Sandbox Restrictions

Set one or more flags through the security property of a Configuration instance. The same configured instance must then be passed to the HTMLDocument constructor.

The reusable workflow is:

  1. Create a Configuration instance.
  2. Add the required Sandbox flags to configuration.security.
  3. Load the HTML source with the configured environment.
  4. Process, render, or convert the document while the restrictions are active.

Combine restrictions with the bitwise OR operator when several capabilities must be blocked:

1configuration.security |= ah.Sandbox.SCRIPTS | ah.Sandbox.IMAGES

Apply the flags before creating HTMLDocument; changing the configuration after loading does not retroactively change how the source was processed.

Disable JavaScript Execution

Use Sandbox.SCRIPTS when scripts from the HTML source must not execute. This is useful for static conversion workflows that do not depend on JavaScript-generated content.

The following example loads an HTML file with scripts disabled and converts the resulting document to PDF:

  1. Create a Configuration instance.
  2. Add Sandbox.SCRIPTS to its security settings.
  3. Load the HTML source with that configuration.
  4. Convert or render the restricted document.
 1# Disable JavaScript when converting HTML to PDF in Python
 2
 3import os
 4import aspose.html as ah
 5import aspose.html.converters as conv
 6import aspose.html.saving as sav
 7
 8# Prepare input and output paths
 9data_dir = "data"
10output_dir = "output"
11os.makedirs(output_dir, exist_ok=True)
12html_path = os.path.join(data_dir, "document-with-scripts.html")
13output_pdf = os.path.join(output_dir, "document-sandbox.pdf")
14
15# Block scripts and convert HTML to PDF
16with ah.Configuration() as config:
17    config.security |= ah.Sandbox.SCRIPTS
18
19    with ah.HTMLDocument(html_path, config) as doc:
20        conv.Converter.convert_html(doc, sav.PdfSaveOptions(), output_pdf)

Because script execution is blocked during loading, content that normally appears only after JavaScript runs will not be generated. Static HTML and CSS can still be processed.

Disable Image Loading

Use Sandbox.IMAGES when the document should be processed without loading image resources. The restriction applies to image loading generally, including images referenced by HTML or CSS; it is not limited to remote URLs.

The example creates HTML containing a CSS background image, loads it with image loading disabled, and converts the document to PDF:

  1. Prepare or obtain HTML that references image resources.
  2. Create a Configuration and add Sandbox.IMAGES to its security settings.
  3. Load the HTML source with the restricted configuration.
  4. Convert or render the document without loading the blocked images.
 1# Block external images when converting HTML to PDF in Python
 2
 3import os
 4import aspose.html as ah
 5import aspose.html.converters as conv
 6import aspose.html.saving as sav
 7
 8# Prepare output paths
 9output_dir = "output"
10os.makedirs(output_dir, exist_ok=True)
11html_path = os.path.join(output_dir, "sandboxing.html")
12output_pdf = os.path.join(output_dir, "sandboxing-out.pdf")
13
14# Define HTML that references an external image
15code = (
16    "<span style=\"background-image:url('https://docs.aspose.com/html/images/work/lioness.jpg')\">"
17    "Hello, World!!</span> <script>document.write('Have a nice day!');</script>"
18)
19
20# Save the source HTML file
21with open(html_path, "w", encoding="utf-8") as file:
22    file.write(code)
23
24# Block image loading and convert HTML to PDF
25with ah.Configuration() as configuration:
26    configuration.security |= ah.Sandbox.IMAGES
27
28    with ah.HTMLDocument(html_path, configuration) as document:
29        conv.Converter.convert_html(document, sav.PdfSaveOptions(), output_pdf)

The resulting document keeps the processable HTML and text content, but image resources are not loaded. The script in this sample is not blocked because only Sandbox.IMAGES is set; combine flags when both images and scripts must be restricted.

Choose Sandbox Flags

The Sandbox enumeration is a flag set, so a configuration can use one restriction or combine several. Choose only the capabilities that the workflow needs to block.

FlagRestricted capability
Sandbox.NONENo sandbox restriction is applied.
Sandbox.NAVIGATIONNavigation of other browsing contexts.
Sandbox.AUXILIARY_NAVIGATIONCreation of auxiliary browsing contexts, such as popups.
Sandbox.TOP_LEVEL_NAVIGATIONNavigation or closing of the top-level browsing context.
Sandbox.PLUGINSPlugin instantiation through plugin-related content.
Sandbox.ORIGINSame-origin access by forcing content into a unique origin.
Sandbox.FORMSForm submission.
Sandbox.POINTER_LOCKUse of the Pointer Lock API.
Sandbox.SCRIPTSScript execution.
Sandbox.AUTOMATIC_FEATURESAutomatically triggered features, such as autoplay or autofocus.
Sandbox.FULLSCREENRequests to enter fullscreen mode.
Sandbox.DOCUMENT_DOMAINChanges to the effective script origin through document.domain.
Sandbox.IMAGESImage loading.

Common Sandboxing Issues

IssueCause and recommended action
Scripts still affect the outputThe document was loaded before Sandbox.SCRIPTS was applied, or a different Configuration instance was passed to HTMLDocument. Configure security first and reuse the same instance.
JavaScript-generated content is missingBlocking scripts also blocks content created by those scripts. Allow scripts when the required page content depends on JavaScript and the source is trusted.
Images still appearVerify that Sandbox.IMAGES was applied before loading and that the visible content is actually an image resource rather than CSS color, text, or vector markup.
More behavior is blocked than expectedToo many flags were combined. Begin with the narrowest restriction and add another flag only when required.
Only particular URLs should be blockedSandbox flags restrict broad capability categories. Apply request-level rules in the application’s network layer when URL-specific control is required.
Sandboxing is treated as complete isolationSandbox flags do not isolate the Python process, operating system, file system, or network environment. Use ordinary application security controls as well.

FAQ

How do I disable JavaScript when converting HTML in Python?

Add Sandbox.SCRIPTS to configuration.security before creating the HTMLDocument, then convert or render the document loaded with that configuration.

Does Sandbox.IMAGES block only external images?

No. Sandbox.IMAGES disables image loading as a capability. It is not limited to images downloaded from remote URLs.

Can I combine several sandbox restrictions?

Yes. Combine flags with the bitwise OR operator, for example ah.Sandbox.SCRIPTS | ah.Sandbox.IMAGES, and add the result to configuration.security.

Does Aspose.HTML sandboxing make untrusted HTML completely safe?

No. It restricts selected document capabilities inside Aspose.HTML. Continue to use appropriate process isolation, file permissions, network policies, input validation, and other application security measures.

Related Articles

Other Platforms