Authorization with Cedar
Decide each call with a Cedar policy set in one Guard that serves HTTP and RPC, with the action declared by #[meta].
Authentication says who is calling, and authorization says whether they may do this. Cedar keeps the second question in a policy set, away from handler code. One guard reads the principal and the action the handler declares, asks Cedar, and refuses on a deny.
This recipe compiled and ran against cedar-policy 4.15.0 with ulo 0.1.0-alpha.3. The HTTP controller was run. The RPC controller was compiled and not run.
[dependencies]
ulo = "=0.1.0-alpha.3"
ulo-http = "=0.1.0-alpha.3"
ulo-http-hyper = "=0.1.0-alpha.3"
ulo-runtime-tokio = "=0.1.0-alpha.3"
ulo-transport = "=0.1.0-alpha.3"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
ulo-rpc = "=0.1.0-alpha.3"
cedar-policy = "4.15"
serde_json = "1"Cedar or Casbin
Cedar was chosen. Both decide synchronously, so either works in a Guard with no runtime concern at the call. Cedar's PolicySet and Entities build with plain constructors, as Authorize::new shows. Casbin's CoreApi::new is async and its Cargo features select a runtime (runtime-tokio or runtime-async-std), which the application's runtime choice has to agree with. That was read from its source and manifest and not exercised here. The deciding difference for a framework with several transports is the policy language: Cedar denies by default and a forbid overrides every permit, which the payroll policy below relies on and the run confirmed.
The code
use cedar_policy::{Authorizer, Context, Decision, Entities, EntityId, EntityTypeName, EntityUid, PolicySet, Request};
use serde_json::json;
use ulo::{App, AppBuilder, BoxError, ExecutionRef, Guard, Transport, controller, handlers, injectable, module};
use ulo_http::{CallError, Http, HttpCx};
const POLICIES: &str = r#"
permit(principal in Role::"admin", action, resource);
permit(principal in Role::"clerk", action == Action::"read", resource);
forbid(principal, action, resource == Resource::"payroll") unless { principal in Role::"admin" };
"#;
/// Who the call is made by, written by whichever stage authenticates it.
pub struct Principal(pub String);
/// Declared with `#[meta(..)]` on a handler: the action it performs on a resource.
pub struct Needs(pub &'static str, pub &'static str);
/// Reads `x-user` into the execution's extensions. No header is a 401 and the policies never run.
#[injectable]
pub struct Authenticate;
impl Guard<Http> for Authenticate {
async fn can_activate(&self, cx: &HttpCx) -> Result<bool, BoxError> {
let user = cx.headers().get("x-user").and_then(|value| value.to_str().ok());
let Some(user) = user else { return Err(CallError::unauthorized("Bearer").into()) };
cx.extensions().insert(Principal(user.to_owned()));
Ok(true)
}
}
/// Asks Cedar whether the principal may perform the action the handler declares. Generic over
/// the transport: it reads the principal and the declaration through the execution only.
pub struct Authorize {
policies: PolicySet,
entities: Entities,
}
impl Authorize {
pub fn new() -> Authorize {
let entities = json!([
{ "uid": { "type": "User", "id": "ada" }, "attrs": {}, "parents": [{ "type": "Role", "id": "admin" }] },
{ "uid": { "type": "User", "id": "bob" }, "attrs": {}, "parents": [{ "type": "Role", "id": "clerk" }] },
{ "uid": { "type": "Role", "id": "admin" }, "attrs": {}, "parents": [] },
{ "uid": { "type": "Role", "id": "clerk" }, "attrs": {}, "parents": [] },
]);
Authorize {
policies: POLICIES.parse().expect("the policies parse"),
entities: Entities::from_json_value(entities, None).expect("the entities are well formed"),
}
}
fn allows(&self, user: &str, action: &str, resource: &str) -> Result<bool, BoxError> {
let uid = |kind: &str, id: &str| -> Result<EntityUid, BoxError> {
Ok(EntityUid::from_type_name_and_id(kind.parse::<EntityTypeName>()?, EntityId::new(id)))
};
let request = Request::new(uid("User", user)?, uid("Action", action)?, uid("Resource", resource)?, Context::empty(), None)?;
let answer = Authorizer::new().is_authorized(&request, &self.policies, &self.entities);
Ok(answer.decision() == Decision::Allow)
}
}
impl<T: Transport> Guard<T> for Authorize
where
T::Cx: AsRef<ExecutionRef>,
{
async fn can_activate(&self, cx: &T::Cx) -> Result<bool, BoxError> {
let exec: &ExecutionRef = cx.as_ref();
let Some(Needs(action, resource)) = exec.handler().and_then(|handler| handler.meta::<Needs>()) else {
return Ok(false);
};
let Some(principal) = exec.extensions().get::<Principal>() else { return Ok(false) };
self.allows(&principal.0, action, resource)
}
}
#[controller]
pub struct OrdersController;
#[handlers]
#[guards(Authenticate, Authorize)]
impl OrdersController {
#[ulo_http::get("/orders")]
#[meta(Needs("read", "orders"))]
fn list(&self) -> &'static str {
"orders"
}
#[ulo_http::get("/payroll")]
#[meta(Needs("read", "payroll"))]
fn payroll(&self) -> &'static str {
"payroll"
}
#[ulo_http::get("/undeclared")]
fn undeclared(&self) -> &'static str {
"unreachable"
}
}
#[controller]
pub struct OrdersRpc;
/// The same `Authorize` on RPC. A stage that writes `Principal` for an RPC call is the caller's;
/// without one every message is refused.
#[handlers]
#[guards(Authorize)]
impl OrdersRpc {
#[ulo_rpc::message("orders.list")]
#[meta(Needs("read", "orders"))]
async fn list(&self) -> &'static str {
"orders"
}
}
#[module(providers = [Authenticate, with = || Authorize::new()], controllers = [OrdersController, OrdersRpc])]
pub struct AppModule;
pub fn builder() -> AppBuilder {
App::builder(AppModule)
}What each seam does
Authenticateis the transport-specific stage. It readsx-user, answers 401 with aBearerchallenge when the header is absent, and writesPrincipalinto the execution's extensions.Needs("read", "orders")is the declaration, written with#[meta(..)]beside the route. The policy set never sees a route string: the action and resource are the vocabulary of the policies.Authorizeis generic over the transport.T::Cx: AsRef<ExecutionRef>is what every transport's context implements, and the principal and the declaration come from the execution, so the same impl guardsOrdersControllerandOrdersRpc.allowsbuilds each entity id withEntityUid::from_type_name_and_idandEntityId::new, which take the id as data. A user nameda"breaches Cedar as that identity and is denied, where assembling the id into a parsed string would put the quotes into Cedar's syntax.- The entities hold the role hierarchy:
User::"ada"is inRole::"admin". Policies matchprincipal in Role::"admin". Production code loads entities from its store, per call or cached. - The guard is registered as a provider with
with = || Authorize::new(), so the policy set is parsed once, when the provider is constructed.
Test
The test uses the example support crate in the repository (ex_support::start and call); any HTTP client does the same.
use ex_support::http::{Call, call};
use ex_support::start;
use r3::authz::builder;
#[tokio::test]
async fn cedar_decides_each_call_from_the_principal_and_the_declared_action() {
let server = start(builder()).await;
let status = async |path: &str, user: Option<&str>| {
let mut request = Call::get(path);
if let Some(user) = user {
request = request.header("x-user", user);
}
let reply = call(server.addr, request).await;
(reply.status, reply.headers.iter().any(|(name, _)| name == "www-authenticate"))
};
assert_eq!(status("/orders", None).await, (401, true));
assert_eq!(status("/orders", Some("bob")).await, (200, false));
assert_eq!(status("/payroll", Some("bob")).await, (403, false));
assert_eq!(status("/payroll", Some("ada")).await, (200, false));
assert_eq!(status("/orders", Some("eve")).await.0, 403, "a principal no entity names is denied");
assert_eq!(status("/undeclared", Some("ada")).await.0, 403, "a handler declaring no action is denied");
assert_eq!(status("/orders", Some("a\"b\\")).await.0, 403, "quotes in the id are data");
server.stop().await.unwrap();
}Failure modes
- Anything Cedar does not permit is denied, so an unknown principal (
eve) and a handler with noNeedsboth answer 403. A handler that someone forgets to annotate stays closed. - An error building the request, such as an action name that is not a valid identifier, comes out of
can_activateasErrand renders as an internal error. A guard that returnsOk(false)renders 403. - The RPC controller has no stage writing
Principal, so every message to it is refused until the application adds one. The guard does not know how an RPC caller authenticates. - Cedar evaluates against the entities passed in. A stale entity set grants what the store no longer does. Load group membership at the freshness the application needs.
- Schema validation is optional in Cedar and this recipe passes
None, so a policy naming an action or entity type that no handler declares is accepted. Validate the policy set against a schema in CI.
Reference
- Guards: ordering within a tier, and one guard for several transports.
- Macros:
#[meta]and#[guards]. - Error handling: the 401 challenge and the 403 for a refusal.
- Microservices:
#[ulo_rpc::message]handlers.
Feature flags with OpenFeature
Install an OpenFeature provider at startup, inject a flag client, and hide a route behind a flag with a guard that reads the flag name from #[meta].
Moving from axum or actix-web
Move an existing axum or actix-web app onto Ulo one route at a time, with Ulo as the host's fallback service, and a contract test that diffs old and new answers.