Hardening

Besides CORS, the security module provides a few concerns that harden a web application against common transport-level issues. All three are added automatically by defaults() (with preventSniffing off), or can be added together via harden() (which also enables preventSniffing by default). They are extensions of the host in the package org.genhttp.modules.security.

Kotlin
val app = Layout.create()

Host.create()
    .handler(app)
    .harden()
    .run()

Each of them can be switched off with a flag, e.g. harden(preventSniffing = false).

Secure Upgrade

secureUpgrade redirects insecure (HTTP) requests to their HTTPS equivalent. SecureUpgrade.Force always redirects; SecureUpgrade.Allow only does so if the client requests it via the Upgrade-Insecure-Requests header; SecureUpgrade.None disables the concern. Requests are only redirected if the server provides a secure endpoint.

Kotlin
val app = Layout.create()

Host.create()
    .handler(app)
    .secureUpgrade(SecureUpgrade.Force)
    .run()

Strict Transport

strictTransport sends a Strict-Transport-Security header with the responses to secure requests, instructing browsers to only ever contact your server via HTTPS for the given duration. harden() and defaults() configure it with a 365 day policy that includes subdomains and requests preload list inclusion.

Kotlin
import org.genhttp.engine.internal.Host

import org.genhttp.modules.layouting.*
import org.genhttp.modules.security.*
import org.genhttp.modules.security.providers.StrictTransportPolicy

import kotlin.time.Duration.Companion.days

suspend fun main() {
    val app = Layout.create()

    val policy = StrictTransportPolicy(365.days, includeSubdomains = true, preload = true)

    Host.create()
        .handler(app)
        .strictTransport(policy)
        .run()
}

Prevent Sniffing

preventSniffing sends X-Content-Type-Options: nosniff, instructing browsers to trust the Content-Type header of a response instead of guessing the MIME type from its content.

Kotlin
val app = Layout.create()

Host.create()
    .handler(app)
    .preventSniffing()
    .run()