Warden Help

Ktor

Warden keeps authorization rules out of the HTTP layer, but the HTTP layer has one authorization concern of its own: no route should be left open by accident. The warden-ktor3 plugin makes every route fail with 403 unless it was authorized through an EnforcementPointKtor or explicitly left open. The artifact is named after the Ktor major version it targets; the package is codes.laurence.warden.ktor regardless of the Ktor version.

dependencies { implementation("codes.laurence.warden:warden-core:0.5.0") implementation("codes.laurence.warden:warden-ktor3:0.5.0") }

How it works

EnforcementPointKtor is an EnforcementPoint that also marks the current call as enforced when it grants access. It wraps any enforcement point, or builds one from a decision point or from policies, so your services take it in place of EnforcementPointDefault.

The Warden plugin inspects every response. A response with a 2xx or 101 status whose call was neither marked as enforced nor left open is replaced by 403 Not Authorized: EnforcementPoint not enforced. Other statuses pass through, since something else already stopped the request. OPTIONS requests are never checked.

The enforcement point can only mark a call it can see. Routes must therefore be declared inside a warded block, which carries the call to the enforcement point through the coroutine context. A route outside any warded block is refused even when it calls the enforcement point.

Install

class NotAuthenticatedException : Exception("Not Authenticated") /** Authentication is not Warden's concern. This sample trusts a header. */ fun ApplicationCall.currentUser(users: Map<String, User>): User = users[request.header("X-User")] ?: throw NotAuthenticatedException() fun Application.blogModule(users: Map<String, User>, articles: ArticleStore) { val enforcementPoint = EnforcementPointKtor(articlePolicies) val service = ArticleService(articles, enforcementPoint) install(WebSockets) install(Warden) { routePriorityStack = listOf( // The first matching entry wins. Health checks are open for GET only. WardenRoute("/health", WardenRouteBehaviour.IGNORE, setOf(HttpMethod.Get)), // Everything else is enforced, which is also the default when nothing matches. WardenRoute("/.*", WardenRouteBehaviour.ENFORCE), ) } install(StatusPages) { exception<NotAuthorizedException> { call, _ -> call.respondText("Not Authorized", status = HttpStatusCode.Forbidden) } exception<NotAuthenticatedException> { call, _ -> call.respondText("Not Authenticated", status = HttpStatusCode.Unauthorized) } exception<NoSuchElementException> { call, _ -> call.respond(HttpStatusCode.NotFound) } } routing { // Open through the plugin configuration above. get("/health") { call.respondText("ok") } // Open through an inline block. unwarded { get("/about") { call.respondText("A blog guarded by Warden") } } warded { route("/articles") { get { val user = call.currentUser(users) val titles = service.listArticles(user).map { it.title } call.respondText(titles.joinToString("\n")) } get("/{id}") { val user = call.currentUser(users) val article = service.readArticle(user, call.parameters["id"]!!) call.respondText(article.title) } delete("/{id}") { val user = call.currentUser(users) service.deleteArticle(user, call.parameters["id"]!!) call.respond(HttpStatusCode.NoContent) } } // Nothing here calls the enforcement point, so Warden answers 403 instead of the text. get("/drafts") { call.respondText("Unpublished drafts") } // A websocket cannot be refused once it is open, so authorization runs before the upgrade. route("/feed") { beforeEach({ val user = call.currentUser(users) enforcementPoint.enforceAuthorization( AccessRequest( subject = user.atts(), action = ArticleAction.READ.atts(), resource = ArticleType.atts(), )) }) { webSocket { for (article in articles.all()) { outgoing.send(Frame.Text(article.title)) } } } } } } }

Three things happen in blogModule:

  • install(Warden) with a routePriorityStack. The first WardenRoute whose regular expression matches the request URI and whose methods include the request method decides whether the route is enforced or ignored. A request that matches nothing is enforced. The ENFORCE entry above is therefore redundant, and shows how to carve exceptions out of an ignored prefix.

  • install(StatusPages) maps NotAuthorizedException to 403. Without it Ktor answers 500. The status is yours to choose, as is what the denial's properties reveal.

  • routing declares the guarded routes inside warded, and the open ones outside it.

Leaving routes open

Two ways, both shown above: match the route in routePriorityStack with IGNORE, or declare it in an unwarded block. unwarded blocks can be nested inside warded ones, so a public corner of a private API stays next to it.

Websockets

Once a websocket is open there is no response to replace, so authorization has to happen before the upgrade. A beforeEach block runs for every route declared inside it, before the handler. Put the enforcement there, and the handshake fails for a denied request:

class KtorAppTest { private val users = mapOf( "ada" to User(id = "ada", roles = listOf("Author")), "bob" to User(id = "bob", roles = emptyList()), ) private val articles = listOf(Article(id = "a1", title = "Warden", authorId = "ada")) @Test fun `a route that enforces authorization responds normally`() = testApplication { application { blogModule(users, ArticleStore(articles)) } val response = client.get("/articles/a1") { header("X-User", "bob") } assertThat(response.status).isEqualTo(HttpStatusCode.OK) assertThat(response.bodyAsText()).isEqualTo("Warden") } @Test fun `a denied request gets the status from StatusPages`() = testApplication { application { blogModule(users, ArticleStore(articles)) } val response = client.delete("/articles/a1") { header("X-User", "bob") } assertThat(response.status).isEqualTo(HttpStatusCode.Forbidden) assertThat(response.bodyAsText()).isEqualTo("Not Authorized") } @Test fun `a route that forgets to enforce authorization is refused by the plugin`() = testApplication { application { blogModule(users, ArticleStore(articles)) } val response = client.get("/drafts") { header("X-User", "ada") } assertThat(response.status).isEqualTo(HttpStatusCode.Forbidden) assertThat(response.bodyAsText()).isEqualTo("Not Authorized: EnforcementPoint not enforced") } @Test fun `routes left open respond without authorization`() = testApplication { application { blogModule(users, ArticleStore(articles)) } assertThat(client.get("/health").status).isEqualTo(HttpStatusCode.OK) assertThat(client.get("/about").status).isEqualTo(HttpStatusCode.OK) } @Test fun `a websocket is authorized before the upgrade`() = testApplication { application { blogModule(users, ArticleStore(articles)) } val client = createClient { install(WebSockets) } client.webSocket("/feed", { header("X-User", "bob") }) { assertThat((incoming.receive() as Frame.Text).readText()).isEqualTo("Warden") } try { client.webSocket("/feed") {} fail("The handshake should fail without a user") } catch (_: Exception) {} } }

The /feed route in blogModule is authorized this way. beforeEach works for ordinary routes too, when several share a check.

What the plugin does not do

Authentication. The sample reads a header; a real application resolves the user with Ktor's authentication plugin and builds the subject from the principal. Warden only decides what that subject may do.

14 November 2026