encore/reqctx.rs
1//! Request Context: typed fields that travel with a request to every service
2//! it reaches (for example, the authenticated user).
3//!
4//! Declare each field once in the application as a module-level `static` with a
5//! string literal name and value type so Encore can parse it statically:
6//!
7//! ```no_run
8//! use encore::reqctx::Field;
9//! use serde::{Deserialize, Serialize};
10//!
11//! #[derive(Serialize, Deserialize, Clone)]
12//! pub struct User {
13//! pub id: String,
14//! pub email: String,
15//! }
16//!
17//! /// The authenticated user for a request, set by the gateway.
18//! pub static CURRENT_USER: Field<User> = Field::new("user");
19//! ```
20//!
21//! Gateway middleware attaches fields to forwarded requests using `set_field`
22//! in `on_request` (`encore::gateway`), and downstream services read them while
23//! handling requests:
24//!
25//! ```no_run
26//! # use encore::reqctx::Field;
27//! # #[derive(serde::Serialize, serde::Deserialize, Clone)]
28//! # pub struct User { pub id: String }
29//! # static CURRENT_USER: Field<User> = Field::new("user");
30//! async fn orders() -> Result<(), encore::Error> {
31//! let Some(user) = CURRENT_USER.get() else {
32//! return Err(encore::Error::unauthenticated("not signed in"));
33//! };
34//! // …load orders for user.id…
35//! Ok(())
36//! }
37//! ```
38//!
39//! A service can also set or clear fields for nested operations and outbound
40//! service calls:
41//!
42//! ```no_run
43//! # use encore::reqctx::Field;
44//! # #[derive(serde::Serialize, serde::Deserialize, Clone)]
45//! # pub struct User { pub id: String }
46//! # static CURRENT_USER: Field<User> = Field::new("user");
47//! # async fn billing_invoices() {}
48//! # async fn f() -> Result<(), encore::reqctx::Error> {
49//! let system = User { id: "system".into() };
50//! CURRENT_USER.scope(&system, billing_invoices())?.await;
51//! # Ok(())
52//! # }
53//! ```
54//!
55//! Another service (even in a different language) can bind an existing field by
56//! name with `Field::named("user")`.
57//!
58//! # Context propagation
59//!
60//! Fields live inside [`opentelemetry::Context`](crate::opentelemetry::Context)
61//! alongside the trace, so they propagate across `.await` points with
62//! [`FutureExt::with_context`](crate::opentelemetry::trace::FutureExt::with_context).
63//! Tasks spawned with `tokio::spawn` do not inherit the current context
64//! automatically; wrap them with `fut.with_current_context()` to preserve both
65//! tracing and Request Context fields.
66//!
67//! # Trust model
68//!
69//! External clients cannot set Request Context fields. Encore strips the
70//! underlying headers at every public entry point and cryptographically signs
71//! them between containers, so services can trust field values from other
72//! services in the application.
73//!
74//! # Extracting and injecting headers
75//!
76//! [`extract`] reads Request Context fields from incoming request headers into
77//! a context. [`inject`] writes context fields onto outgoing request headers;
78//! only call it for requests to other Encore services in the same application,
79//! never for external third-party URLs. Pub/Sub messages automatically carry
80//! any set fields declared with [`Field::pubsub`] into their subscribers'
81//! contexts.
82//!
83//! # Size limits
84//!
85//! Each field is encoded as base64url JSON in its own header, so values must be
86//! compact: at most 4 KiB per field (1 KiB for fields marked with
87//! [`Field::pubsub`]), and at most 8 KiB across all fields on a request.
88//! Exceeding a limit fails immediately at the call site that sets the field.
89//!
90//! # Errors
91//!
92//! Setting a field returns this module's [`Error`] if serialization fails or a
93//! size limit is exceeded. It does not automatically convert into
94//! [`encore::Error`](crate::Error); map it to an appropriate error code at the
95//! call site.
96
97use std::collections::HashSet;
98use std::future::Future;
99use std::marker::PhantomData;
100use std::sync::Mutex;
101
102use encore_sdk_core::reqctx::{self as core_reqctx, FieldConfig, Values};
103use serde::Serialize;
104use serde::de::DeserializeOwned;
105
106use crate::opentelemetry::Context;
107use crate::opentelemetry::trace::{FutureExt, WithContext};
108
109pub use encore_sdk_core::reqctx::SizeError;
110
111/// Error returned when setting a Request Context field fails. See the
112/// [module documentation](self#errors).
113#[derive(Debug, thiserror::Error)]
114#[non_exhaustive]
115pub enum Error {
116 /// The field value failed to serialize to JSON.
117 #[error("reqctx: field {field:?}: cannot encode {type_name} as JSON: {error}")]
118 Encode {
119 /// The field's name.
120 field: &'static str,
121 /// The Rust type name of the value.
122 type_name: &'static str,
123 /// The underlying Serde serialization error.
124 error: serde_json::Error,
125 },
126 /// The encoded value (or total context size) exceeds the allowed limit; see
127 /// [size limits](self#size-limits).
128 #[error("reqctx: field {field:?}: the value {size}")]
129 Size {
130 /// The field's name.
131 field: &'static str,
132 /// Details about which limit was exceeded.
133 size: SizeError,
134 },
135}
136
137/// A typed Request Context field serialized as JSON.
138///
139/// Declare as a module-level `static` (for example,
140/// `static USER: Field<User> = Field::new("user");`). The type parameter `T`
141/// defines the field's schema, which Encore validates across all bindings by
142/// name. `T` must be serializable with Serde and representable in Encore's
143/// config schema.
144pub struct Field<T> {
145 name: &'static str,
146 /// The declaration's, or `None` for a field bound by name.
147 config: Option<FieldConfig>,
148 _value: PhantomData<fn() -> T>,
149}
150
151impl<T> Field<T> {
152 /// Declares a Request Context field.
153 ///
154 /// This constructor is `const` so it can initialize a module-level
155 /// `static`. `name` must be unique across the app and use kebab-case
156 /// (lowercase letters, digits, and hyphens, starting with a letter and
157 /// ending with a letter or digit).
158 pub const fn new(name: &'static str) -> Self {
159 Self {
160 name,
161 config: Some(FieldConfig {
162 pubsub: false,
163 trace: false,
164 }),
165 _value: PhantomData,
166 }
167 }
168
169 /// Binds a field declared elsewhere in the application (possibly in another
170 /// service or language).
171 ///
172 /// Encore checks that `T` is compatible with the original declaration, and
173 /// the bound field inherits its Pub/Sub and tracing behavior.
174 pub const fn named(name: &'static str) -> Self {
175 Self {
176 name,
177 config: None,
178 _value: PhantomData,
179 }
180 }
181
182 /// Propagates this field on Pub/Sub messages published while it is set,
183 /// making it available in subscriber contexts.
184 ///
185 /// Enabling Pub/Sub propagation limits the field's encoded size to 1 KiB
186 /// (matching GCP Pub/Sub's attribute value limit).
187 pub const fn pubsub(mut self) -> Self {
188 if let Some(config) = &mut self.config {
189 config.pubsub = true;
190 }
191 self
192 }
193
194 /// Records this field's JSON value as the `encore.ctx.<name>` attribute on
195 /// spans started while it is set.
196 ///
197 /// Useful for searchable identifiers such as tenant IDs. Never enable on
198 /// fields containing secrets.
199 pub const fn trace(mut self) -> Self {
200 if let Some(config) = &mut self.config {
201 config.trace = true;
202 }
203 self
204 }
205
206 /// Attaches a key/value tag to the field (for example, `.tag("data", "pci")`)
207 /// for policy and governance tooling.
208 ///
209 /// Call once per tag with unique keys. Both `key` and `value` must be string
210 /// literals so Encore can parse them statically. Keys must start with a
211 /// letter, contain only lowercase letters, digits, `_`, and `-`, and must
212 /// not start with `encore` (reserved for Encore's own tags). Values use the
213 /// same character set or may be empty. Each key and value is at most 63
214 /// characters, and a field may have at most 32 tags.
215 ///
216 /// ```no_run
217 /// use encore::reqctx::Field;
218 ///
219 /// static TENANT: Field<String> = Field::new("tenant").tag("data", "pii");
220 /// ```
221 pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
222 self
223 }
224
225 /// Returns the name this field was declared with.
226 pub const fn name(&self) -> &'static str {
227 self.name
228 }
229
230 /// How the field travels: as the app declares it, wherever that is,
231 /// else as this declaration says.
232 fn config(&self) -> FieldConfig {
233 crate::runtime::configured()
234 .and_then(|rt| rt.reqctx_fields().get(self.name))
235 .or(self.config)
236 .unwrap_or_default()
237 }
238}
239
240impl<T> std::fmt::Debug for Field<T> {
241 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242 f.debug_tuple("Field").field(&self.name).finish()
243 }
244}
245
246impl<T: Serialize + DeserializeOwned> Field<T> {
247 /// Returns this field's value from the current context, or `None` if unset.
248 ///
249 /// Each call decodes the value from the context. If the stored payload
250 /// cannot be decoded as `T` (for example, due to a type mismatch across
251 /// services), Encore logs a warning once and returns `None`.
252 pub fn get(&self) -> Option<T> {
253 Context::map_current(|cx| self.get_in(cx))
254 }
255
256 /// Returns this field's value from `cx`, or `None` if unset.
257 pub fn get_in(&self, cx: &Context) -> Option<T> {
258 let values = Values::of(cx);
259 let value = values.get(self.name)?;
260 match decode(value) {
261 Ok(v) => Some(v),
262 Err(why) => {
263 log_undecodable(self.name, std::any::type_name::<T>(), &why);
264 None
265 }
266 }
267 }
268
269 /// Returns a copy of the current context with this field set to `value`.
270 ///
271 /// # Errors
272 ///
273 /// Returns [`Error::Encode`] if `value` fails to serialize, or
274 /// [`Error::Size`] if the encoded value exceeds the field limit (4 KiB, or
275 /// 1 KiB with [`Field::pubsub`]) or causes the total Request Context to
276 /// exceed 8 KiB.
277 pub fn context(&self, value: &T) -> Result<Context, Error> {
278 Context::map_current(|cx| self.context_in(cx, value))
279 }
280
281 /// Returns a copy of `cx` with this field set to `value`. See
282 /// [`context`](Self::context).
283 pub fn context_in(&self, cx: &Context, value: &T) -> Result<Context, Error> {
284 let json = serde_json::to_vec(value).map_err(|error| Error::Encode {
285 field: self.name,
286 type_name: std::any::type_name::<T>(),
287 error,
288 })?;
289 let values = Values::of(cx)
290 .with(self.name, core_reqctx::encode(&json), self.config())
291 .map_err(|size| Error::Size {
292 field: self.name,
293 size,
294 })?;
295 Ok(values.in_context(cx))
296 }
297
298 /// Returns a copy of the current context with this field removed.
299 pub fn without(&self) -> Context {
300 Context::map_current(|cx| self.without_in(cx))
301 }
302
303 /// Returns a copy of `cx` with this field removed.
304 pub fn without_in(&self, cx: &Context) -> Context {
305 let values = Values::of(cx);
306 if values.get(self.name).is_none() {
307 return cx.clone();
308 }
309 values.without(self.name).in_context(cx)
310 }
311
312 /// Runs `fut` with this field set to `value` for nested operations and
313 /// outbound calls.
314 ///
315 /// To run a future with the field cleared instead, use
316 /// `fut.with_context(FIELD.without())`.
317 ///
318 /// # Errors
319 ///
320 /// Returns the same errors as [`context`](Self::context) before `fut` runs.
321 pub fn scope<F: Future>(&self, value: &T, fut: F) -> Result<WithContext<F>, Error> {
322 Ok(fut.with_context(self.context(value)?))
323 }
324}
325
326/// Returns a copy of `cx` populated with Request Context fields extracted from
327/// `headers`, replacing any existing fields in `cx`.
328pub fn extract(cx: &Context, headers: &http::HeaderMap) -> Context {
329 Values::from_headers(headers).in_context(cx)
330}
331
332/// Writes the Request Context fields from `cx` into `headers`, replacing any
333/// existing Request Context headers.
334///
335/// Only call this for requests to other Encore services in the same
336/// application; calling it on external requests would leak Request Context data
337/// to third parties.
338pub fn inject(cx: &Context, headers: &mut http::HeaderMap) {
339 Values::of(cx).to_headers(headers);
340}
341
342/// The value a field's wire form holds. Says where it is wrong, never what
343/// it holds: a field may hold who a request is made for.
344fn decode<T: DeserializeOwned>(value: &str) -> Result<T, String> {
345 let json = core_reqctx::decode(value).map_err(|e| e.to_string())?;
346 serde_json::from_slice(&json).map_err(|e| {
347 let what = match e.classify() {
348 serde_json::error::Category::Data => "it is JSON of another shape",
349 _ => "it is not valid JSON",
350 };
351 format!(
352 "{what}: the error is at line {} column {}",
353 e.line(),
354 e.column()
355 )
356 })
357}
358
359/// The fields, with the type read, whose undecodable values have been
360/// logged.
361static LOGGED: Mutex<Option<HashSet<(&'static str, &'static str)>>> = Mutex::new(None);
362
363fn log_undecodable(name: &'static str, ty: &'static str, why: &str) {
364 let mut logged = LOGGED.lock().unwrap_or_else(|e| e.into_inner());
365 if !logged.get_or_insert_with(HashSet::new).insert((name, ty)) {
366 return;
367 }
368 drop(logged);
369 tracing::warn!(
370 field = name,
371 value_type = ty,
372 "cannot decode Request Context field {name:?} as {ty}, treating it as unset: {why}"
373 );
374}
375
376#[cfg(test)]
377mod tests {
378 use super::*;
379 use serde::Deserialize;
380
381 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
382 struct User {
383 id: String,
384 admin: bool,
385 }
386
387 static USER: Field<User> = Field::new("test-user");
388 static BY_NAME: Field<User> = Field::named("test-user");
389 static TENANT: Field<String> = Field::new("test-tenant").pubsub().trace();
390 static COUNT: Field<u32> = Field::named("test-user");
391
392 fn alice() -> User {
393 User {
394 id: "alice".into(),
395 admin: false,
396 }
397 }
398
399 #[test]
400 fn a_field_reads_what_was_set_in_its_context() {
401 assert_eq!(USER.get(), None);
402 let cx = USER.context(&alice()).unwrap();
403 assert_eq!(USER.get_in(&cx), Some(alice()));
404 // Bound by name, it is the same field.
405 assert_eq!(BY_NAME.get_in(&cx), Some(alice()));
406 assert_eq!(USER.get_in(&USER.without_in(&cx)), None);
407 let _guard = cx.attach();
408 assert_eq!(USER.get(), Some(alice()));
409 assert_eq!(USER.get_in(&USER.without()), None);
410 }
411
412 #[test]
413 fn a_scope_carries_the_field_across_awaits() {
414 let rt = tokio::runtime::Builder::new_current_thread()
415 .build()
416 .unwrap();
417 let seen = rt.block_on(async {
418 let fut = async {
419 tokio::task::yield_now().await;
420 USER.get()
421 };
422 USER.scope(&alice(), fut).unwrap().await
423 });
424 assert_eq!(seen, Some(alice()));
425 assert_eq!(USER.get(), None);
426 let cleared = rt.block_on(async {
427 let cx = USER.context(&alice()).unwrap();
428 async { async { USER.get() }.with_context(USER.without()).await }
429 .with_context(cx)
430 .await
431 });
432 assert_eq!(cleared, None);
433 }
434
435 #[test]
436 fn a_value_of_another_shape_reads_as_unset() {
437 let cx = USER.context(&alice()).unwrap();
438 assert_eq!(COUNT.get_in(&cx), None);
439 assert!(
440 decode::<u32>(&core_reqctx::encode(b"{\"id\":\"secret-id\"}"))
441 .unwrap_err()
442 .contains("another shape")
443 );
444 let why = decode::<User>(&core_reqctx::encode(b"{\"id\":\"secret")).unwrap_err();
445 assert!(why.starts_with("it is not valid JSON"), "{why}");
446 assert!(!why.contains("secret"), "{why}");
447 assert_eq!(
448 decode::<u32>("!").unwrap_err(),
449 "it is not base64url without padding"
450 );
451 }
452
453 #[test]
454 fn limits_fail_where_the_value_is_set() {
455 let err = TENANT.context(&"a".repeat(1100)).unwrap_err();
456 assert!(
457 matches!(
458 err,
459 Error::Size {
460 field: "test-tenant",
461 size: SizeError::MessageValue(_)
462 }
463 ),
464 "{err:?}"
465 );
466 let msg = err.to_string();
467 assert!(
468 msg.contains("reqctx: field \"test-tenant\": the value encodes to")
469 && msg.contains("carried on Pub/Sub messages"),
470 "{msg}"
471 );
472 let err = USER
473 .context(&User {
474 id: "a".repeat(5000),
475 admin: true,
476 })
477 .unwrap_err();
478 assert!(
479 matches!(
480 err,
481 Error::Size {
482 size: SizeError::Value(_),
483 ..
484 }
485 ),
486 "{err:?}"
487 );
488 assert!(err.to_string().contains("more than the 4096"), "{err}");
489 }
490
491 #[test]
492 fn headers_carry_the_fields() {
493 let cx = TENANT.context(&"acme".to_string()).unwrap();
494 let mut headers = http::HeaderMap::new();
495 headers.insert("x-encore-meta-ctx-stale", "e30".parse().unwrap());
496 inject(&cx, &mut headers);
497 assert!(headers.get("x-encore-meta-ctx-stale").is_none());
498 let received = extract(&Context::new(), &headers);
499 assert_eq!(TENANT.get_in(&received), Some("acme".to_string()));
500 }
501}