ash_jsonapi/hook.rs
1//! `before` and `after` — one interception point for every operation.
2//!
3//! A hook runs around an operation without the operation knowing. That is
4//! what authorization, audit, metrics and tracing all want, and building
5//! them on one mechanism is why this module exists: four separate
6//! interception points would be four places to forget, four orderings to
7//! reason about, and four things to test.
8//!
9//! ```
10//! use ash_jsonapi::hook::{Event, Hook, Outcome};
11//! use ash_jsonapi::{Context, JsonApiError};
12//!
13//! struct Timing;
14//!
15//! impl Hook for Timing {
16//! fn after(&self, event: &Event<'_>, outcome: &Outcome, _ctx: &Context) {
17//! println!(
18//! "{} {} -> {}",
19//! event.operation.as_str(),
20//! event.resource,
21//! outcome.status()
22//! );
23//! }
24//! }
25//! # let _ = Timing;
26//! ```
27//!
28//! # What a `before` hook can do
29//!
30//! Return an error, and the operation does not run: the request is answered
31//! with what the hook returned. That makes `before` the seam for
32//! authorization — a denial should never reach storage — and for anything
33//! else that decides a request must not proceed.
34//!
35//! An `after` hook cannot change the response. It observes: it is told what
36//! happened, and its return value is nothing. Recording must not be able to
37//! break a request that otherwise succeeded, and a hook that could rewrite a
38//! response is a second, invisible handler.
39//!
40//! # Ordering
41//!
42//! `before` hooks run in registration order, and the first error stops the
43//! rest — so a hook registered later can rely on an earlier one having
44//! passed. `after` hooks run in the same order, and all of them run: one
45//! panicking or misbehaving must not silence the others' records.
46
47use crate::context::Context;
48use crate::error::JsonApiError;
49
50/// Which operation is running.
51///
52/// The five JSON:API operations, named as [`api!`](crate::api!) names them —
53/// so a hook's `match` reads like the `operations` list that routed them.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum Operation {
56 /// `GET` on the collection.
57 List,
58 /// `POST` on the collection.
59 Create,
60 /// `GET` on one resource.
61 Read,
62 /// `PATCH` on one resource.
63 Update,
64 /// `DELETE` on one resource.
65 Delete,
66}
67
68impl Operation {
69 /// The lowercase name, for a log line or a metric label.
70 pub fn as_str(self) -> &'static str {
71 match self {
72 Self::List => "list",
73 Self::Create => "create",
74 Self::Read => "read",
75 Self::Update => "update",
76 Self::Delete => "delete",
77 }
78 }
79
80 /// Whether this operation changes state.
81 ///
82 /// The distinction an audit trail cares about most: a read that is
83 /// denied is worth recording, and a *write* that is denied is worth
84 /// alerting on.
85 pub fn is_write(self) -> bool {
86 matches!(self, Self::Create | Self::Update | Self::Delete)
87 }
88}
89
90/// What is about to run, or has just run.
91///
92/// Borrowed rather than owned: a hook is called on the request path, and
93/// copying a resource name per hook per request is a cost with no purpose.
94#[derive(Debug, Clone, Copy)]
95pub struct Event<'a> {
96 /// The operation.
97 pub operation: Operation,
98 /// The resource's JSON:API `type`, e.g. `"todo"`.
99 pub resource: &'a str,
100 /// The id the request addressed, for the operations that name one.
101 ///
102 /// `None` for [`List`](Operation::List) and
103 /// [`Create`](Operation::Create), which address the collection.
104 pub id: Option<&'a str>,
105}
106
107/// How an operation finished.
108///
109/// Handed to [`Hook::after`], which cannot change it — see the module docs.
110#[derive(Debug, Clone, Copy)]
111pub enum Outcome {
112 /// The operation ran and the response is being written.
113 Succeeded {
114 /// The status the client is being handed: `201` for a create, `204`
115 /// for a delete, `200` otherwise.
116 ///
117 /// Carried rather than assumed, so an audit record says what the
118 /// client actually saw.
119 status: u16,
120 },
121 /// The operation failed, or a `before` hook refused it.
122 Failed {
123 /// The status the client is being handed.
124 status: u16,
125 },
126}
127
128impl Outcome {
129 /// The HTTP status the client receives.
130 pub fn status(&self) -> u16 {
131 match self {
132 Self::Succeeded { status } | Self::Failed { status } => *status,
133 }
134 }
135
136 /// Whether the operation ran to completion.
137 pub fn succeeded(&self) -> bool {
138 matches!(self, Self::Succeeded { .. })
139 }
140}
141
142/// Something that runs around every operation.
143///
144/// Both methods have a default that does nothing, so a hook implements only
145/// the half it cares about: an audit sink is an `after`, an authorization
146/// check is a `before`.
147pub trait Hook: Send + Sync + 'static {
148 /// Runs before the operation. An `Err` refuses the request, and the
149 /// operation never runs.
150 ///
151 /// This is where authorization belongs: a denial that reaches storage
152 /// has already leaked whether the row exists.
153 fn before(&self, _event: &Event<'_>, _ctx: &Context) -> Result<(), JsonApiError> {
154 Ok(())
155 }
156
157 /// Runs after the operation, whatever happened.
158 ///
159 /// Cannot change the response — recording must not be able to break a
160 /// request that otherwise worked.
161 fn after(&self, _event: &Event<'_>, _outcome: &Outcome, _ctx: &Context) {}
162}
163
164/// The hooks a service runs, in order.
165///
166/// Built once at startup and held on your state. Empty by default, and an
167/// empty set is the zero-cost case: the generated handlers skip the whole
168/// mechanism when there is nothing registered.
169#[derive(Default, Clone)]
170pub struct Hooks(std::sync::Arc<Vec<Box<dyn Hook>>>);
171
172impl Hooks {
173 /// No hooks.
174 pub fn new() -> Self {
175 Self::default()
176 }
177
178 /// Add a hook, after the ones already registered.
179 #[must_use]
180 pub fn with(mut self, hook: impl Hook) -> Self {
181 // `Arc::make_mut` needs `Clone`; building the set is a startup-time
182 // operation, so taking the vec out and putting it back is fine and
183 // keeps `Hooks` cheap to clone per request.
184 let mut hooks = std::mem::take(&mut self.0);
185 let vec =
186 std::sync::Arc::get_mut(&mut hooks).expect("hooks are built before they are shared");
187 vec.push(Box::new(hook));
188 Self(hooks)
189 }
190
191 /// Whether any hook is registered.
192 pub fn is_empty(&self) -> bool {
193 self.0.is_empty()
194 }
195
196 /// Run every `before` hook, stopping at the first refusal.
197 pub fn before(&self, event: &Event<'_>, ctx: &Context) -> Result<(), JsonApiError> {
198 for hook in self.0.iter() {
199 hook.before(event, ctx)?;
200 }
201 Ok(())
202 }
203
204 /// Run every `after` hook. All of them run.
205 pub fn after(&self, event: &Event<'_>, outcome: &Outcome, ctx: &Context) {
206 for hook in self.0.iter() {
207 hook.after(event, outcome, ctx);
208 }
209 }
210}
211
212impl std::fmt::Debug for Hooks {
213 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214 // The hooks themselves are opaque; the count is what is useful.
215 f.debug_struct("Hooks")
216 .field("count", &self.0.len())
217 .finish()
218 }
219}