Appearance
6. Authorization
So far any customer could do anything. Now customers may act only on themselves and their own orders.
Grants decide what a key, that is a process, may do: send shop.Register, run the shop's commands, read its events. They know nothing about the people using your shop. Who the person behind a request is, is business data: the request's request context, signed with the request, carries it as senderIdentity. A middleware checks every command and query against it before the kernel accepts it.
The guard
A middleware is a listener with a check: it builds its knowledge from events, like a read model, and answers every check from it.
ts
const SERVICES = new Set(["svc-confirmations"]);
// What a business process may send (part 10): it acts as `process:<name>`.
const PROCESSES: Record<string, string[]> = { "process:shop.fulfilment": ["Ship", "Cancel"] };
const registered = new Set<string>();
const ownerOf = new Map<string, string>(); // order -> customer
const guardReadmodel = shopDomain.readModel("guard")
.on("CustomerRegistered", (_data, evt) => void registered.add(evt.aggregateId))
.on("CustomerErased", (_data, evt) => void registered.delete(evt.aggregateId))
.on("OrderPlaced", (data: { customerId: string }, evt) => void ownerOf.set(evt.aggregateId, data.customerId))
.middleware({ types: ["shop.*"] }, (check) => {
const who = check.request.senderIdentity ?? "";
if (check.type === "Register") return; // anyone may sign up
if (check.kind === "query" && SERVICES.has(who)) return; // services may read
if (check.kind === "command" && PROCESSES[who]?.includes(check.type)) return;
// Files and cache requests carry no data: they have no owner, so only the rules above pass them.
const data = (check.data ?? {}) as { id?: string; customerId?: string };
const target = check.kind === "command" ? check.aggregateId! : data.id!;
const owner =
check.type === "Place" ? data.customerId
: check.type === "GetCustomer" || check.aggregateType === "customer" ? target
: ownerOf.get(target);
if (!registered.has(who) || owner !== who) throw new Rejected(`${check.type} is not allowed for ${who || "anonymous"}`, "forbidden");
});
await new Kernable().listener(guardReadmodel).run();py
SERVICES = {"svc-confirmations"}
# What a business process may send (part 10): it acts as `process:<name>`.
PROCESSES = {"process:shop.fulfilment": {"Ship", "Cancel"}}
registered: set[str] = set()
owner_of: dict[str, str] = {} # order -> customer
guard_readmodel = shop_domain.read_model("guard")
@guard_readmodel.on("CustomerRegistered")
def _(data, evt):
registered.add(evt.aggregate_id)
@guard_readmodel.on("CustomerErased")
def _(data, evt):
registered.discard(evt.aggregate_id)
@guard_readmodel.on("OrderPlaced")
def _(data, evt):
owner_of[evt.aggregate_id] = data["customerId"]
@guard_readmodel.middleware(["shop.*"])
def _(check: Check):
who = check.request.sender_identity
if check.type == "Register":
return # anyone may sign up
if check.kind == "query" and who in SERVICES:
return # services may read
if check.kind == "command" and check.type in PROCESSES.get(who, ()):
return
data = check.data or {} # files and cache requests carry none: they have no owner
target = check.aggregate_id if check.kind == "command" else data.get("id")
if check.type == "Place":
owner = check.data.get("customerId")
elif check.type == "GetCustomer" or check.aggregate_type == "customer":
owner = target
else:
owner = owner_of.get(target)
if who not in registered or owner != who:
raise Rejected(f"{check.type} is not allowed for {who or 'anonymous'}", "forbidden")
Kernable().listener(guard_readmodel).run()rs
const SERVICES: [&str; 1] = ["svc-confirmations"];
// What a business process may send (part 10): it acts as `process:<name>`.
const PROCESSES: [(&str, &[&str]); 1] = [("process:shop.fulfilment", &["Ship", "Cancel"])];
let registered = Arc::new(Mutex::new(HashSet::<String>::new()));
let owner_of = Arc::new(Mutex::new(HashMap::<String, String>::new())); // order -> customer
let shop_domain = shop().domain;
let guard_readmodel = shop_domain.read_model("guard");
let r = Arc::clone(®istered);
guard_readmodel.on("CustomerRegistered", move |_: Value, evt, _ctx| {
r.lock().unwrap().insert(evt.aggregate_id);
async { Ok(()) }
});
let r = Arc::clone(®istered);
guard_readmodel.on("CustomerErased", move |_: Value, evt, _ctx| {
r.lock().unwrap().remove(&evt.aggregate_id);
async { Ok(()) }
});
let o = Arc::clone(&owner_of);
guard_readmodel.on("OrderPlaced", move |data: Value, evt, _ctx| {
let customer = data["customerId"].as_str().unwrap_or_default().to_owned();
o.lock().unwrap().insert(evt.aggregate_id, customer);
async { Ok(()) }
});
let (r, o) = (Arc::clone(®istered), Arc::clone(&owner_of));
guard_readmodel.middleware(MiddlewareOptions::new(&["shop.*"]), move |check| {
let who = check.request.sender_identity.clone();
let allowed = check.type_name == "Register" // anyone may sign up
|| (check.kind == CheckKind::Query && SERVICES.contains(&who.as_str())) // services may read
|| (check.kind == CheckKind::Command
&& PROCESSES.iter().any(|(process, types)| *process == who && types.contains(&check.type_name.as_str())))
|| {
let field = |name: &str| check.data[name].as_str().map(str::to_owned);
let target = match check.kind {
CheckKind::Command | CheckKind::Cancel => check.aggregate_id.clone(),
CheckKind::Query => field("id"),
// The shop keeps no files: no customer's to protect.
CheckKind::Data | CheckKind::Cache => None,
};
let owner = if check.type_name == "Place" {
field("customerId")
} else if check.type_name == "GetCustomer" || check.aggregate_type.as_deref() == Some("customer") {
target
} else {
target.and_then(|t| o.lock().unwrap().get(&t).cloned())
};
r.lock().unwrap().contains(&who) && owner.as_deref() == Some(who.as_str())
};
let who = if who.is_empty() { "anonymous".to_owned() } else { who };
let refusal = format!("{} is not allowed for {who}", check.type_name);
async move {
if !allowed {
return Err(Rejected::new(refusal).code("forbidden").into());
}
Ok(())
}
});
let kernable = Kernable::new(Options::default())?;
kernable.listener(&guard_readmodel).run().await;The check sees the command or query, with its data and request context, before the kernel stores or routes it. Throwing Rejected refuses it; a refused command is never stored. Middleware runs in a chain by order, and the kernel asks a middleware only once it has processed every event committed before, so it never decides on stale knowledge.
The guard's key needs the check action on the types it checks; app, which --dev lets do everything, has it. The registration is kept by the kernel: while the guard is not running, every request it covers is refused. Authorization fails closed.
Try it
Start the guard (node guard.ts, .venv/bin/python guard.py or cargo run -q --bin guard) and send requests as different customers:
ts
// Who sends a request is part of its signed request context.
const as = (senderIdentity: string) => ({ context: { senderIdentity } });
const send = (who: string, aggregateType: string, aggregateId: string, type: string, data?: object) =>
kernable.submit({ domain: "shop", aggregateType, aggregateId, type, data, ...as(who) });
show("c1 registers", await send("c1", "customer", "c1", "Register", { email: "ann@example.com", name: "Ann" }));
show("c2 registers", await send("c2", "customer", "c2", "Register", { email: "bob@example.com", name: "Bob" }));
show("c1 places o1", await send("c1", "order", "o1", "Place", { customerId: "c1" }));
show("c2 adds to o1", await send("c2", "order", "o1", "AddItem", { sku: "apple", qty: 1 }));
show("c2 places for c1", await send("c2", "order", "o2", "Place", { customerId: "c1" }));
const getOrder = (who: string) => kernable.query({ domain: "shop", type: "GetOrder", data: { id: "o1" }, ...as(who) });
console.log("c1 reads o1:", await getOrder("c1"));
await getOrder("c2").catch((err) => console.log(`c2 reads o1: ${err.code} (${err.message})`));py
# Who sends a request is part of its signed request context.
def send(who, aggregate_type, aggregate_id, type, data=None):
return k.submit("shop", aggregate_type, aggregate_id, type, data, context=RequestContext(sender_identity=who))
show("c1 registers", send("c1", "customer", "c1", "Register", {"email": "ann@example.com", "name": "Ann"}))
show("c2 registers", send("c2", "customer", "c2", "Register", {"email": "bob@example.com", "name": "Bob"}))
show("c1 places o1", send("c1", "order", "o1", "Place", {"customerId": "c1"}))
show("c2 adds to o1", send("c2", "order", "o1", "AddItem", {"sku": "apple", "qty": 1}))
show("c2 places for c1", send("c2", "order", "o2", "Place", {"customerId": "c1"}))
def get_order(who):
return k.query("shop", "GetOrder", {"id": "o1"}, context=RequestContext(sender_identity=who))
print("c1 reads o1:", get_order("c1"))
try:
get_order("c2")
except Rejected as err:
print(f"c2 reads o1: {err.code} ({err})")rs
// Who sends a request is part of its signed request context.
let as_ = |who: &str| RequestContext {
sender_identity: who.into(),
..Default::default()
};
let send = |who, aggregate_type, aggregate_id, command_type, data: Value| {
let command = Submit::new("shop", aggregate_type, aggregate_id, command_type)
.data(data)
.context(as_(who));
kernable.submit(command)
};
show(
"c1 registers",
send(
"c1",
"customer",
"c1",
"Register",
json!({ "email": "ann@example.com", "name": "Ann" }),
)
.await?,
);
show(
"c2 registers",
send(
"c2",
"customer",
"c2",
"Register",
json!({ "email": "bob@example.com", "name": "Bob" }),
)
.await?,
);
show(
"c1 places o1",
send("c1", "order", "o1", "Place", json!({ "customerId": "c1" })).await?,
);
show(
"c2 adds to o1",
send(
"c2",
"order",
"o1",
"AddItem",
json!({ "sku": "apple", "qty": 1 }),
)
.await?,
);
show(
"c2 places for c1",
send("c2", "order", "o2", "Place", json!({ "customerId": "c1" })).await?,
);
let get_order = |who| {
kernable.query::<Value>(
Query::new("shop", "GetOrder")
.data(json!({ "id": "o1" }))
.context(as_(who)),
)
};
println!("c1 reads o1: {}", get_order("c1").await?);
if let Err(Error::Rejected(r)) = get_order("c2").await {
println!("c2 reads o1: {} ({})", r.code, r.message);
}text
c1 registers: committed
c2 registers: committed
c1 places o1: committed
c2 adds to o1: forbidden (AddItem is not allowed for c2)
c2 places for c1: forbidden (Place is not allowed for c2)
c1 reads o1: { id: 'o1', customerId: 'c1', status: 'draft', items: {} }
c2 reads o1: forbidden (GetOrder is not allowed for c2)text
c1 registers: committed
c2 registers: committed
c1 places o1: committed
c2 adds to o1: forbidden (AddItem is not allowed for c2)
c2 places for c1: forbidden (Place is not allowed for c2)
c1 reads o1: {'id': 'o1', 'customerId': 'c1', 'status': 'draft', 'items': {}}
c2 reads o1: forbidden (GetOrder is not allowed for c2)text
c1 registers: committed
c2 registers: committed
c1 places o1: committed
c2 adds to o1: forbidden (AddItem is not allowed for c2)
c2 places for c1: forbidden (Place is not allowed for c2)
c1 reads o1: {"id":"o1","customerId":"c1","status":"draft","items":{}}
c2 reads o1: forbidden (GetOrder is not allowed for c2)The reactor still confirms orders: its follow-up commands carry the customer's identity (ctx.submit follows the event), and its own queries (ctx.query) come from svc-confirmations, a service the guard lets read.
The kernel checks that the request was signed by a key with a grant to send it, not who senderIdentity names: any process that may submit can claim any identity. So in a real application the identity comes from your authentication, for example a verified token at your API, and only processes that verify it get a grant to submit. Part 8 gives each service its own key, so the reactor's key may submit nothing but shop.Confirm.
Next: 7. Personal data.
