Secure your posts
Narrow blog's blanket Manage rule into a policy — anyone signed in reads, only an admin writes — and pin the refusal a plain user gets.
Authenticate and authorize read how api’s policy
scopes rows and masks fields. Your blog still runs on the one blanket rule
Expose over HTTP granted. This page turns it into a policy
of its own, and the suite pins the refusal it makes. By the end, POST /posts
answers 201 for an admin and 403 for a plain user, with no check in the
handler.
Narrow the policy
Section titled “Narrow the policy”Step 4 left posts on one blanket rule — Action::Manage for everybody.
Rewriting define in crates/features/src/authz/ability.rs turns it into a
policy, using only the columns blog already has:
use nest_rs::authz::{AbilityBuilder, AbilityFactory, Action};use nest_rs::core::injectable;
use crate::authn::Claims;use crate::posts as post;
#[injectable]pub struct AuthzAbility;
impl AbilityFactory for AuthzAbility { type Actor = Claims;
/// Every rule this app grants, keyed off the authenticated actor. Nothing /// is granted until you add a `can` here — reads return 403 and no row /// crosses the data layer. /// /// `nestrs g resource <name>` prints the grant to paste for the resource it /// just generated, with `_ab` renamed `ab`; narrow it to a user's own rows /// with `.when(|p| p.eq(Column::AuthorId, user_id))` under /// `if let Some(user_id) = actor.sub.user_id()` — a client owns none. fn define(&self, actor: &Claims, ab: &mut AbilityBuilder) { ab.can(Action::Read, post::Entity); if actor.is_admin() { ab.can(Action::Manage, post::Entity); } }
/// What an *unauthenticated* caller may do, on what `#[public(Action, Entity)]` /// opens. Empty on purpose: nothing is public until you say so here, and a /// route naming its read still serves no row without a grant — a /// `can(Action::Read, …)` narrowed by `.when(…)` to the rows meant for /// anyone. /// /// Such a route reached with a valid token uses `define` instead — this branch /// answers only for the visitor. fn define_visitor(&self, _ab: &mut AbilityBuilder) {}}Pin the refusal in the suite
Section titled “Pin the refusal in the suite”Anyone signed in may read; only an admin may write. The suite you finished on
page 7 signs its tokens as a plain user, so its writes now answer 403: sign
them as an admin, and pin the refusal a plain user gets — the policy is as
much the feature as its routes:
use nest_rs::http::StatusCode;use serde_json::json;use uuid::Uuid;
use features::authn::{Claims, Role, Subject};
use crate::boot;
fn bearer(app: &nest_rs::testing::TestApp, role: Role) -> String { app.bearer(&Claims { sub: Subject::User(Uuid::now_v7()), client_id: "e2e".into(), roles: vec![role], })}
#[tokio::test]async fn posts_round_trip() { let app = boot().await; let bearer = bearer(&app, Role::Admin);
let created = app .http() .post("/posts") .header("authorization", &bearer) .body_json(&json!({ "title": "Title 1", "body": "Body 1" })) .send() .await; created.assert_status(StatusCode::CREATED); let created = created.json().await; let id = created.value().object().get("id").string().to_owned();
let read = app .http() .get(format!("/posts/{id}")) .header("authorization", &bearer) .send() .await; read.assert_status_is_ok(); let read = read.json().await; let fields = read.value().object(); assert_eq!(fields.get("title").string(), "Title 1"); assert_eq!(fields.get("body").string(), "Body 1");}
#[tokio::test]async fn create_with_empty_title_returns_400() { let app = boot().await; app.http() .post("/posts") .header("authorization", bearer(&app, Role::Admin)) .body_json(&json!({ "title": "", "body": "Body 1" })) .send() .await .assert_status(StatusCode::BAD_REQUEST);}
#[tokio::test]async fn create_without_a_token_returns_401() { let app = boot().await; app.http() .post("/posts") .body_json(&json!({ "title": "Title 1", "body": "Body 1" })) .send() .await .assert_status(StatusCode::UNAUTHORIZED);}
#[tokio::test]async fn a_plain_user_cannot_create_a_post() { let app = boot().await; app.http() .post("/posts") .header("authorization", bearer(&app, Role::User)) .body_json(&json!({ "title": "Title 1", "body": "Body 1" })) .send() .await .assert_status(StatusCode::FORBIDDEN);}Restart, mint a plain token and a {"roles":["admin"]} one from
POST /auth/dev-token, and POST /posts answers 201 for the second and
403 for the first — with no check in the handler. That is the same mechanism
the previous page walked through, at the size your
domain is.
Going further
Section titled “Going further”- Mirror on GraphQL — the next step: expose the same feature through a resolver.
- Add login — the reference page for issuing the JWT these guards verify.