Skip to content

Security

The HTML library has built-in multi-layer security protection. All configuration is centralized in the Config security fields. This page covers security-related APIs; for a conceptual overview, see Security Overview.

Security Configuration Fields

FieldTypeDefaultSecurity Purpose
EnableSanitizationbooltrueContent sanitization: removes dangerous tags, event attributes, and malicious protocols
MaxInputSizeint52428800 (50MB)Input size limit, prevents memory exhaustion
MaxDepthint500DOM nesting depth limit, prevents recursion bombs
ProcessingTimeouttime.Duration30sPer-document processing timeout, prevents infinite processing
AllowedBaseDirstring""File operation directory sandbox, prevents path traversal
AuditAuditConfigDefaultAuditConfig()Security audit configuration (see Audit System)

Risk of Disabling Sanitization

EnableSanitization is enabled by default. Only disable for fully trusted input. Disabling causes HTML to be parsed as-is, potentially leading to XSS risks.

Content Sanitization

When enabled (default), the following cleaning is applied automatically:

Protection LayerBehavior
Dangerous tagsRemoves <script>, <style>, <iframe>, <object>, <embed>, etc.
Event attributesRemoves all on* attributes (onclick, onerror, etc.)
Dangerous protocolsBlocks javascript:, vbscript:
Data URLsOnly allows data:image/*, data:font/*, data:application/pdf

Blocked content is recorded through the audit system (requires audit to be enabled).

Path Security

AllowedBaseDir Sandbox

Restricts file operations (ExtractFromFile, etc.) to a specified directory and its subdirectories:

go
cfg := html.DefaultConfig()
cfg.AllowedBaseDir = "/var/www/html"

p, err := html.New(cfg)
if err != nil {
    log.Fatal(err)
}
defer p.Close()

// ✅ Allowed: file inside directory
result, err := p.ExtractFromFile("/var/www/html/page.html")

// ❌ Rejected: file outside directory
_, err = p.ExtractFromFile("/etc/passwd")

Once set, file paths must be inside AllowedBaseDir to be readable. Cross-platform support:

  • Unix: Resolves symbolic links (symlinks), preventing escape via links
  • Windows: Resolves junctions and symbolic links

Empty (default) means no restriction — suitable for trusted input scenarios.

Path Traversal Detection

Automatically detects and blocks path traversal attempts (e.g., ../../../etc/passwd), returning a *FileError:

go
_, err := html.ExtractFromFile("../../../etc/passwd")
// err contains "path traversal detected" information

FileError.SafePath

File errors automatically sanitize path information to prevent filesystem structure leakage:

go
type FileError struct {
    Op      string
    Path    string
    FileErr error
}

func (e *FileError) Error() string        // Outputs truncated path (filename only)
func (e *FileError) SafePath() string     // Returns filename only
func (e *FileError) MarshalJSON() ([]byte, error) // Automatically sanitizes on JSON serialization
go
_, err := html.ExtractFromFile("/var/www/secret/config.html")
if err != nil {
    var fileErr *html.FileError
    if errors.As(err, &fileErr) {
        fmt.Println(fileErr.SafePath()) // Output: config.html (no path)
    }
}

TIP

Both FileError.Error() and SafePath() return truncated safe paths (filename only), preventing path leakage. For internal debugging, access the Path field directly.

Security Preset

HighSecurityConfig

A preset configuration for high-security environments, tightening all limits and enabling comprehensive audit:

go
func HighSecurityConfig() Config

Security field overrides compared to DefaultConfig():

FieldDefaultHigh Security
MaxInputSize52428800 (50MB)10485760 (10MB)
MaxDepth500100
ProcessingTimeout30s10s
WorkerPoolSize42
AuditDefaultAuditConfig()HighSecurityAuditConfig()
go
cfg := html.HighSecurityConfig()
p, err := html.New(cfg)
if err != nil {
    log.Fatal(err)
}
defer p.Close()
ErrorTrigger Condition
ErrInputTooLargeInput exceeds MaxInputSize
ErrMaxDepthExceededDOM depth exceeds MaxDepth
ErrProcessingTimeoutProcessing exceeds ProcessingTimeout
ErrInvalidFilePathFile path validation failed (including path traversal)
ErrInternalPanicInternal panic recovered

INFO

For complete error type definitions (InputError, ConfigError, FileError) and errors.Is/errors.As usage, see Constants & Errors.

Panic Recovery

All extraction operations have built-in panic recovery. Even if an unexpected panic occurs during processing, it returns ErrInternalPanic instead of crashing the service:

go
result, err := html.Extract(maliciousData)
if err != nil {
    if errors.Is(err, html.ErrInternalPanic) {
        // Input may have triggered an internal bug
        log.Printf("panic recovered: %v", err)
    }
}