Policies
A policy is anything that implements Policy: a function from an AccessRequest to an AccessResponse whose access is Granted or Denied. The DSL in codes.laurence.warden.policy builds the common ones.
Expressions
An expression compares one attribute of the request with a value or with another attribute. Exp.subject(path), Exp.action(path), Exp.resource(path) and Exp.environment(path) start one, and an infix operator finishes it.
Comparison operators
equalTo works on any value. The ordering operators need values that are Comparable with each other:
val comparisonPolicies: List<Policy> =
listOf(
Exp.subject("name") equalTo "Ada",
Exp.subject("age") greaterThan 17,
Exp.subject("age") greaterThanEqual 18,
Exp.resource("sizeInBytes") lessThan 1_000_000,
Exp.resource("sizeInBytes") lessThanEqual 999_999,
)
Collection operators
isIn tests a single attribute against a collection. contains, containsAll and containsAny test a collection attribute:
val collectionPolicies: List<Policy> =
listOf(
// The attribute is a single value and the operand is a collection.
Exp.action("type") isIn listOf("MODIFY", "DELETE"),
// The attribute is a collection.
Exp.subject("roles") contains "Author",
Exp.subject("roles") containsAll listOf("Author", "Reviewer"),
Exp.subject("roles") containsAny listOf("Author", "Admin"),
)
Attributes on the right
The right-hand side is a literal unless it is a reference. subjectVal, actionVal, resourceVal and environmentVal refer to attributes of the request, so two parts of the request can be compared with each other. Exp.value puts a literal on the left:
val operandPolicies: List<Policy> =
listOf(
// Compare two attributes of the request with each other.
Exp.subject("id") equalTo resourceVal("authorId"),
Exp.subject("roles") contains resourceVal("requiredRole"),
// A plain value on the left, an attribute on the right.
Exp.value("production") equalTo environmentVal("stage"),
)
Inside an allOf or anyOf block, resource("authorId") on the right-hand side would add a second expression to the block rather than refer to the attribute. Always use the ...Val functions for references.
Nested attributes
A path has one or more segments. Each segment after the first steps into a nested map:
/** Attributes nest. Each extra path segment steps into a nested map. */
val nestedPathPolicy: Policy = Exp.subject("profile", "address", "country") equalTo "ZA"
Missing attributes and wrong types
A path that does not resolve, because an attribute is absent or an intermediate value is not a map, evaluates to Denied. Policies can therefore be written for attributes that are only sometimes present.
An attribute that is present but has the wrong shape is a programming error. contains on a value that is not a collection, or greaterThan between values that cannot be compared, throws BadExpressionException:
class PolicyOperatorsTest {
@Test
fun `every comparison and collection operator grants for a matching request`() {
val request =
AccessRequest(
subject =
mapOf(
"name" to "Ada",
"age" to 18,
"roles" to listOf("Author", "Reviewer"),
"id" to "ada",
),
action = mapOf("type" to "MODIFY"),
resource =
mapOf("sizeInBytes" to 999_999, "authorId" to "ada", "requiredRole" to "Author"),
environment = mapOf("stage" to "production"),
)
val all = AllOf(comparisonPolicies + collectionPolicies + operandPolicies)
assertThat(all.checkAuthorized(request).access).isEqualTo(Access.Granted())
}
@Test
fun `nested paths step into nested maps`() {
val request =
AccessRequest(subject = mapOf("profile" to mapOf("address" to mapOf("country" to "ZA"))))
assertThat(nestedPathPolicy.checkAuthorized(request).access).isEqualTo(Access.Granted())
}
@Test
fun `a missing attribute is denied, not an error`() {
val request =
AccessRequest(subject = mapOf("profile" to mapOf("address" to emptyMap<String, Any?>())))
assertThat(nestedPathPolicy.checkAuthorized(request).access).isEqualTo(Access.Denied())
}
@Test
fun `an operand of the wrong type is an error`() {
val policy = Exp.subject("roles") contains "Author"
val request = AccessRequest(subject = mapOf("roles" to "Author"))
assertFailsWith<BadExpressionException> { policy.checkAuthorized(request) }
}
@Test
fun `member policies evaluate each member of a collection attribute`() {
val request =
AccessRequest(
subject = mapOf("id" to "ada"),
action = mapOf("type" to "MODIFY"),
resource =
mapOf(
"collaborators" to
listOf(
mapOf("id" to "bob", "role" to "viewer", "verified" to true),
mapOf("id" to "ada", "role" to "editor", "verified" to false),
)),
)
assertThat(collaboratorMayEdit.checkAuthorized(request).access).isEqualTo(Access.Granted())
assertThat(allCollaboratorsVerified.checkAuthorized(request).access).isEqualTo(Access.Denied())
}
@Test
fun `a hand-written policy can explain its denial`() {
val response =
BusinessHoursPolicy().checkAuthorized(AccessRequest(environment = mapOf("hour" to 22)))
assertThat(response.access)
.isEqualTo(Access.Denied(mapOf("reason" to "Outside business hours")))
}
}
Boolean policies
allOf is granted when every nested policy is granted, anyOf when at least one is. Both are denied when empty. not inverts a policy:
val allOfPolicy: Policy = allOf {
resource("type") equalTo "Article"
action("type") equalTo "READ"
}
val anyOfPolicy: Policy = anyOf {
subject("roles") contains "Admin"
subject("id") equalTo resourceVal("authorId")
}
val notPolicy: Policy = not(Exp.subject("suspended") equalTo true)
Inside a block, subject(...), action(...), resource(...) and environment(...) add an expression to the block. Blocks nest, and notAllOf and notAnyOf add a negated block. add adds any Policy, including your own:
/** Boolean policies nest, and `notAnyOf` / `notAllOf` negate a nested group in place. */
val nestedBooleanPolicy: Policy = allOf {
resource("type") equalTo "Article"
anyOf {
subject("roles") contains "Admin"
subject("id") equalTo resourceVal("authorId")
}
notAnyOf {
subject("suspended") equalTo true
resource("locked") equalTo true
}
}
Policies over the members of a collection
When an attribute is a collection of maps, forAnyMember and forAllMembers evaluate expressions against each member. Inside the block, attribute(path) refers to the member, and the ...Val references still refer to the request:
/** Granted when at least one collaborator is this user and holds the editor role. */
val collaboratorMayEdit: Policy = allOf {
action("type") equalTo "MODIFY"
resource("collaborators") forAnyMember
{
attribute("id") equalTo subjectVal("id")
attribute("role") equalTo "editor"
}
}
/** Granted when every collaborator has been verified. An empty collection is granted. */
val allCollaboratorsVerified: Policy =
Exp.resource("collaborators") forAllMembers { attribute("verified") equalTo true }
forAnyMember is denied for an empty collection. forAllMembers is granted for one. Both are denied when the attribute is missing or is not a collection of maps.
Writing a policy
Implement Policy when a rule does not fit the DSL. The response carries properties that explain the outcome; an enforcement point puts those of a denial into the NotAuthorizedException:
/**
* A hand-written policy. It reads the hour from the environment and explains a denial through the
* properties of the [Access].
*/
class BusinessHoursPolicy(private val opensAt: Int = 9, private val closesAt: Int = 17) : Policy {
override fun checkAuthorized(accessRequest: AccessRequest): AccessResponse {
val hour =
accessRequest.environment["hour"] as? Int
?: return AccessResponse(
Access.Denied(mapOf("reason" to "The request carries no hour")), accessRequest)
return if (hour in opensAt until closesAt) {
AccessResponse(Access.Granted(), accessRequest)
} else {
AccessResponse(Access.Denied(mapOf("reason" to "Outside business hours")), accessRequest)
}
}
}
Policies are evaluated on every request, so keep them free of I/O. Attributes that must be looked up belong in an information point, described in Decision and enforcement.
14 November 2026