use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use bytes::Bytes;
use encore_gateway::program::ProgramEnv;
use encore_sdk_core::reqctx::Values;
use encore_sdk_core::telemetry::{SpanContext, SpanContextExt};
use opentelemetry::trace::{FutureExt as _, TraceContextExt as _};
use opentelemetry::Context;
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::opentelemetry;
use crate::reqctx::Field;
use crate::ErrCode;
pub use async_trait::async_trait;
pub use encore_gateway::middleware::{
cookies, AttributeValue, Completed, Cond, Continue, Decision, FieldMatch, HeaderEdit, Hook,
HookError, Hooks, Match, Middleware, OnError, PathMatch, Rejection, RequestId, RequestView,
ResponseView, RouteMatch, REJECTED_BY_GATEWAY,
};
#[derive(Debug, Clone)]
pub struct Error(String);
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for Error {}
pub struct Registration {
name: String,
hooks: Hooks,
matches: Option<Match>,
timeout: Duration,
on_error: OnError,
handler: Arc<dyn Middleware>,
}
pub fn register(name: impl Into<String>, hooks: Hooks, handler: impl Middleware) -> Registration {
Registration {
name: name.into(),
hooks,
matches: None,
timeout: encore_gateway::middleware::MiddlewareSpec::DEFAULT_TIMEOUT,
on_error: OnError::default(),
handler: Arc::new(handler),
}
}
impl Registration {
pub fn matching(mut self, m: Match) -> Self {
self.matches = Some(m);
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn on_error(mut self, on_error: OnError) -> Self {
self.on_error = on_error;
self
}
fn spec(self, mark: bool) -> encore_gateway::middleware::MiddlewareSpec {
use encore_gateway::middleware::{Interest, MiddlewareSpec, ReadSet, Reads};
let remembers = [Hook::RequestBody, Hook::Response, Hook::ResponseBody]
.into_iter()
.any(|hook| self.hooks.contains(hook.into()));
let observes = remembers && !self.hooks.contains(Hooks::REQUEST);
let interest = Interest {
hooks: if observes {
self.hooks | Hooks::REQUEST
} else {
self.hooks
},
matches: self.matches,
reads: Reads {
headers: ReadSet::All,
query: ReadSet::All,
cookies: ReadSet::Names(Vec::new()),
response_headers: ReadSet::All,
},
};
let traced = Traced {
inner: self.handler,
observes,
remembers,
mark,
contexts: Mutex::new(HashMap::new()),
};
let mut spec = MiddlewareSpec::new(self.name, interest, Arc::new(traced));
spec.timeout = self.timeout;
spec.on_error = self.on_error;
spec
}
}
struct Traced {
inner: Arc<dyn Middleware>,
observes: bool,
remembers: bool,
mark: bool,
contexts: Mutex<HashMap<RequestId, Context>>,
}
impl Traced {
fn context_of(&self, req: &RequestView) -> Context {
let cx = self.trace_of(req);
if req.context.is_empty() {
return cx;
}
Values::from_map(req.context.iter().cloned().collect()).in_context(&cx)
}
fn trace_of(&self, req: &RequestView) -> Context {
let Some(trace) = &req.trace else {
return Context::new();
};
let tracestate = if self.mark {
Some(encore_telemetry::propagation::with_mark(
trace.tracestate.as_deref(),
!req.context.is_empty(),
))
} else {
trace.tracestate.clone()
};
match SpanContext::parse_traceparent(&trace.traceparent, tracestate.as_deref()) {
Some(sc) => Context::new().with_remote_span_context(sc),
None => Context::new(),
}
}
fn remember(&self, req: RequestId, cx: Context) {
self.contexts
.lock()
.expect("contexts lock poisoned")
.insert(req, cx);
}
fn remembered(&self, req: RequestId) -> Context {
self.contexts
.lock()
.expect("contexts lock poisoned")
.get(&req)
.cloned()
.unwrap_or_default()
}
}
#[allow(clippy::double_must_use)]
#[async_trait]
impl Middleware for Traced {
async fn on_request(&self, req: &RequestView) -> Result<Decision, HookError> {
let cx = self.context_of(req);
if self.remembers {
self.remember(req.id, cx.clone());
}
if self.observes {
return Ok(Decision::proceed());
}
let decision = self.inner.on_request(req).with_context(cx.clone()).await;
if let Ok(Decision::Continue(cont)) = &decision {
if self.remembers && !cont.context.is_empty() {
let values = with_edits(&Values::of(&cx), &cont.context);
self.remember(req.id, values.in_context(&cx));
}
}
decision
}
async fn on_response(
&self,
req: RequestId,
resp: &ResponseView,
) -> Result<Vec<HeaderEdit>, HookError> {
let cx = self.remembered(req);
self.inner.on_response(req, resp).with_context(cx).await
}
fn on_request_body(&self, req: RequestId, chunk: &Bytes, end: bool) {
let _guard = self.remembered(req).attach();
self.inner.on_request_body(req, chunk, end)
}
fn on_response_body(&self, req: RequestId, chunk: &Bytes, end: bool) {
let _guard = self.remembered(req).attach();
self.inner.on_response_body(req, chunk, end)
}
fn on_complete(&self, done: &Completed) {
let _guard = self.context_of(&done.request).attach();
self.inner.on_complete(done)
}
fn on_finish(&self, req: RequestId) {
if self.remembers {
self.contexts
.lock()
.expect("contexts lock poisoned")
.remove(&req);
}
self.inner.on_finish(req)
}
}
pub fn proceed() -> Continue {
Continue::default()
}
pub fn reject(code: ErrCode, message: impl Into<String>) -> Decision {
let code = encore_sdk_core::api::ErrCode::from(code);
Decision::Respond(Rejection::error(
code.status_code().as_u16(),
code.to_string(),
message,
))
}
pub fn respond<K, V>(
status: u16,
headers: impl IntoIterator<Item = (K, V)>,
body: impl Into<Bytes>,
) -> Decision
where
K: Into<String>,
V: Into<String>,
{
Decision::Respond(Rejection {
status,
code: None,
message: String::new(),
headers: headers
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect(),
body: Some(body.into()),
})
}
pub trait ContinueExt: Sized {
fn set_header(self, name: impl Into<String>, value: impl Into<String>) -> Self;
fn add_header(self, name: impl Into<String>, value: impl Into<String>) -> Self;
fn del_header(self, name: impl Into<String>) -> Self;
fn attribute(self, key: impl Into<String>, value: impl Into<AttributeValue>) -> Self;
fn skip(self, hooks: Hooks) -> Self;
fn set_field<T: Serialize + DeserializeOwned>(
self,
field: &Field<T>,
value: &T,
) -> Result<Self, HookError>;
fn unset_field<T>(self, field: &Field<T>) -> Self;
}
impl ContinueExt for Continue {
fn set_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.header_edits.push(HeaderEdit::Set {
name: name.into(),
value: value.into(),
});
self
}
fn add_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.header_edits.push(HeaderEdit::Add {
name: name.into(),
value: value.into(),
});
self
}
fn del_header(mut self, name: impl Into<String>) -> Self {
self.header_edits
.push(HeaderEdit::Remove { name: name.into() });
self
}
fn attribute(mut self, key: impl Into<String>, value: impl Into<AttributeValue>) -> Self {
self.attributes.push((key.into(), value.into()));
self
}
fn skip(mut self, hooks: Hooks) -> Self {
self.skip |= hooks;
self
}
fn set_field<T: Serialize + DeserializeOwned>(
mut self,
field: &Field<T>,
value: &T,
) -> Result<Self, HookError> {
let cx = Context::current();
let fields = with_edits(&Values::of(&cx), &self.context).in_context(&cx);
let set = field
.context_in(&fields, value)
.map_err(|err| HookError::failed(err.to_string()))?;
let encoded = Values::of(&set)
.get(field.name())
.expect("the field was just set")
.to_string();
self.context.push((field.name().to_string(), Some(encoded)));
Ok(self)
}
fn unset_field<T>(mut self, field: &Field<T>) -> Self {
self.context.push((field.name().to_string(), None));
self
}
}
fn with_edits(values: &Values, edits: &[(String, Option<String>)]) -> Values {
if edits.is_empty() {
return values.clone();
}
let mut fields: BTreeMap<String, String> = values
.iter()
.map(|(name, value)| (name.to_string(), value.to_string()))
.collect();
for (name, value) in edits {
match value {
Some(value) => fields.insert(name.clone(), value.clone()),
None => fields.remove(name),
};
}
Values::from_map(fields)
}
pub trait RequestExt {
fn header(&self, name: &str) -> Option<&str>;
fn header_values(&self, name: &str) -> Vec<&str>;
fn query(&self, name: &str) -> Option<&str>;
fn query_values(&self, name: &str) -> Vec<&str>;
fn cookie(&self, name: &str) -> Option<&str>;
fn path_param(&self, name: &str) -> Option<&str>;
}
impl RequestExt for RequestView {
fn header(&self, name: &str) -> Option<&str> {
header_values(&self.headers, name).next()
}
fn header_values(&self, name: &str) -> Vec<&str> {
header_values(&self.headers, name).collect()
}
fn query(&self, name: &str) -> Option<&str> {
self.query
.iter()
.find(|(n, _)| n == name)
.map(|(_, v)| v.as_str())
}
fn query_values(&self, name: &str) -> Vec<&str> {
self.query
.iter()
.filter(|(n, _)| n == name)
.map(|(_, v)| v.as_str())
.collect()
}
fn cookie(&self, name: &str) -> Option<&str> {
header_values(&self.headers, "cookie")
.flat_map(cookies)
.find_map(|(n, v)| (n == name).then_some(v))
}
fn path_param(&self, name: &str) -> Option<&str> {
self.params
.iter()
.find(|(n, _)| n == name)
.map(|(_, v)| v.as_str())
}
}
pub trait ResponseExt {
fn header(&self, name: &str) -> Option<&str>;
fn header_values(&self, name: &str) -> Vec<&str>;
}
impl ResponseExt for ResponseView {
fn header(&self, name: &str) -> Option<&str> {
header_values(&self.headers, name).next()
}
fn header_values(&self, name: &str) -> Vec<&str> {
header_values(&self.headers, name).collect()
}
}
fn header_values<'a: 'n, 'n>(
headers: &'a [(String, String)],
name: &'n str,
) -> impl Iterator<Item = &'a str> + 'n {
headers
.iter()
.filter(move |(n, _)| n.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_str())
}
pub struct State<T> {
shards: Box<[Mutex<HashMap<RequestId, T>>]>,
}
impl<T> Default for State<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> State<T> {
pub fn new() -> Self {
State {
shards: (0..16).map(|_| Mutex::new(HashMap::new())).collect(),
}
}
fn shard(&self, req: RequestId) -> std::sync::MutexGuard<'_, HashMap<RequestId, T>> {
let i = (req.0 as usize) % self.shards.len();
self.shards[i].lock().expect("state lock poisoned")
}
pub fn insert(&self, req: RequestId, value: T) {
self.shard(req).insert(req, value);
}
pub fn with<R>(&self, req: RequestId, f: impl FnOnce(Option<&mut T>) -> R) -> R {
f(self.shard(req).get_mut(&req))
}
pub fn remove(&self, req: RequestId) -> Option<T> {
self.shard(req).remove(&req)
}
}
impl<T: Clone> State<T> {
pub fn get(&self, req: RequestId) -> Option<T> {
self.with(req, |v| v.cloned())
}
}
pub mod matcher {
use super::{Cond, FieldMatch, Match, PathMatch, RouteMatch};
fn strings<S: Into<String>>(values: impl IntoIterator<Item = S>) -> Vec<String> {
values.into_iter().map(Into::into).collect()
}
pub fn all_of(ms: impl IntoIterator<Item = Match>) -> Match {
Match::All(ms.into_iter().collect())
}
pub fn any_of(ms: impl IntoIterator<Item = Match>) -> Match {
Match::AnyOf(ms.into_iter().collect())
}
pub fn not(m: Match) -> Match {
Match::Not(Box::new(m))
}
pub fn service<S: Into<String>>(services: impl IntoIterator<Item = S>) -> Match {
Match::Service(strings(services))
}
pub fn route(method: Option<&str>, template: impl Into<String>) -> Match {
Match::Route(RouteMatch {
method: method.map(str::to_string),
template: template.into(),
})
}
pub fn method<S: Into<String>>(methods: impl IntoIterator<Item = S>) -> Match {
Match::Method(strings(methods))
}
pub fn path(path: impl Into<String>) -> Match {
Match::Path(PathMatch::Exact(path.into()))
}
pub fn path_prefix(prefix: impl Into<String>) -> Match {
Match::Path(PathMatch::Prefix(prefix.into()))
}
pub fn path_glob(glob: impl Into<String>) -> Match {
Match::Path(PathMatch::Glob(glob.into()))
}
pub fn header(name: impl Into<String>, cond: Cond) -> Match {
Match::Header(FieldMatch {
name: name.into(),
cond,
})
}
pub fn query(name: impl Into<String>, cond: Cond) -> Match {
Match::Query(FieldMatch {
name: name.into(),
cond,
})
}
pub fn cookie(name: impl Into<String>, cond: Cond) -> Match {
Match::Cookie(FieldMatch {
name: name.into(),
cond,
})
}
pub fn present() -> Cond {
Cond::Present
}
pub fn absent() -> Cond {
Cond::Absent
}
pub fn equals(value: impl Into<String>) -> Cond {
Cond::Equals(value.into())
}
pub fn prefix(prefix: impl Into<String>) -> Cond {
Cond::Prefix(prefix.into())
}
pub fn one_of<S: Into<String>>(values: impl IntoIterator<Item = S>) -> Cond {
Cond::OneOf(strings(values))
}
pub fn regex(pattern: impl Into<String>) -> Cond {
Cond::Regex(pattern.into())
}
}
fn served() -> &'static Mutex<bool> {
static SERVED: Mutex<bool> = Mutex::new(false);
&SERVED
}
pub async fn serve(middleware: impl IntoIterator<Item = Registration>) -> Result<(), Error> {
let middleware: Vec<Registration> = middleware.into_iter().collect();
if middleware.is_empty() {
return Err(Error(
"gateway::serve requires at least one middleware".into(),
));
}
if let Some(none) = middleware.iter().find(|m| m.hooks == Hooks::NONE) {
return Err(Error(format!(
"middleware {:?} has no hooks enabled",
none.name
)));
}
{
let mut served = served().lock().expect("served lock poisoned");
if *served {
return Err(Error(
"gateway::serve can only be called once per process".into(),
));
}
*served = true;
}
let stopped = start(middleware).inspect_err(|_| {
*served().lock().expect("served lock poisoned") = false;
})?;
match stopped.await {
Ok(Ok(())) | Err(_) => Ok(()),
Ok(Err(err)) => Err(Error(format!("gateway server failed: {err}"))),
}
}
fn start(
middleware: Vec<Registration>,
) -> Result<tokio::sync::oneshot::Receiver<Result<(), encore_gateway::GatewayError>>, Error> {
let env = ProgramEnv::from_env().map_err(|err| {
Error(format!(
"this process is not a gateway program: {err}. Encore launches services with a \
\"gateway\" section in encore.service.json as gateway programs and sets {} to \
the listen address",
encore_gateway::program::LISTEN_ENV
))
})?;
let core = crate::runtime::core();
crate::pubsub::start_registered();
let cfg = core.config_proto();
let mark = cfg
.deployment
.as_ref()
.and_then(|d| d.observability.as_ref())
.and_then(|o| o.telemetry.as_ref())
.is_some_and(|t| t.check_propagation);
let specs = middleware.into_iter().map(|m| m.spec(mark)).collect();
let (stopped_tx, stopped) = tokio::sync::oneshot::channel();
let listen = encore_sdk_core_gateway::serve::serve(
cfg,
&env,
core.tokio_handle(),
core.resources().serving(),
specs,
move |result| {
let _ = stopped_tx.send(result);
},
)
.map_err(|err| Error(err.to_string()))?;
tracing::debug!("serving the gateway on {listen}");
hurry_on_second_signal(core);
Ok(stopped)
}
fn hurry_on_second_signal(core: &'static encore_sdk_core::Runtime) {
let controller = core.shutdown_controller();
core.tokio_handle().spawn(async move {
if controller.started().await.is_err() {
return;
}
let signal = {
let _guard = core.tokio_handle().enter();
encore_os::signal::listen_shutdown_signal()
};
match signal {
Ok(signal) => {
signal.await;
tracing::info!("received a second shutdown signal: the gateway stops draining");
let _ = controller.force_cleanup();
}
Err(err) => tracing::warn!("not listening for a second shutdown signal: {err}"),
}
});
}
#[cfg(test)]
mod tests {
use super::*;
fn view(headers: &[(&str, &str)]) -> RequestView {
RequestView {
id: RequestId(1),
gateway: "edge".into(),
service: "users".into(),
route: "/users/{id}".into(),
method: "GET".into(),
path: "/users/7".into(),
host: None,
client_ip: None,
params: vec![("id".into(), "7".into())],
headers: headers
.iter()
.map(|(n, v)| (n.to_string(), v.to_string()))
.collect(),
query: vec![("q".into(), "a".into()), ("q".into(), "b".into())],
cookies: Vec::new(),
trace: None,
context: Vec::new(),
hooks: Hooks::REQUEST,
}
}
#[test]
fn a_request_reads_its_headers_query_and_cookies() {
let req = view(&[
("authorization", "Bearer t"),
("cookie", "a=1; theme=\"dark\""),
("cookie", "b=2"),
]);
assert_eq!(req.header("Authorization"), Some("Bearer t"));
assert_eq!(req.query_values("q"), ["a", "b"]);
assert_eq!(req.cookie("theme"), Some("dark"));
assert_eq!(req.cookie("b"), Some("2"));
assert_eq!(req.cookie("c"), None);
assert_eq!(req.path_param("id"), Some("7"));
}
#[test]
fn reject_answers_with_the_code_and_its_status() {
let Decision::Respond(rej) = reject(ErrCode::ResourceExhausted, "slow down") else {
panic!("not an answer");
};
assert_eq!(rej.status, 429);
assert_eq!(rej.code.as_deref(), Some("resource_exhausted"));
assert_eq!(rej.message, "slow down");
let Decision::Respond(rej) = respond(302, [("location", "/login")], "") else {
panic!("not an answer");
};
assert_eq!((rej.status, rej.code), (302, None));
assert_eq!(
rej.headers,
[("location".to_string(), "/login".to_string())]
);
}
#[test]
fn edits_chain_on_proceed() {
let c = proceed()
.set_header("x-user", "ada")
.del_header("x-drop")
.attribute("user.id", "ada")
.skip(Hooks::COMPLETE);
assert_eq!(c.header_edits.len(), 2);
assert_eq!(c.attributes.len(), 1);
assert!(c.skip == Hooks::COMPLETE);
}
struct Body;
impl Middleware for Body {}
#[test]
fn a_middleware_is_shown_everything_and_told_of_requests_for_its_later_hooks() {
let spec = register("body", Hooks::from(Hook::RequestBody), Body)
.matching(matcher::path_prefix("/api"))
.timeout(Duration::from_millis(250))
.on_error(OnError::FailOpen)
.spec(false);
assert_eq!(spec.name, "body");
assert!(spec.interest.hooks == Hooks::REQUEST | Hook::RequestBody.into());
assert_eq!(
spec.interest.reads.headers,
encore_gateway::middleware::ReadSet::All
);
assert!(spec.interest.reads.cookies.is_empty());
assert_eq!(spec.timeout, Duration::from_millis(250));
assert_eq!(spec.on_error, OnError::FailOpen);
assert_eq!(
spec.interest.matches,
Some(Match::Path(PathMatch::Prefix("/api".into())))
);
}
#[test]
fn state_is_kept_per_request() {
let state = State::new();
state.insert(RequestId(1), "ada");
state.insert(RequestId(17), "bob");
assert_eq!(state.get(RequestId(1)), Some("ada"));
assert_eq!(state.remove(RequestId(17)), Some("bob"));
assert_eq!(state.get(RequestId(17)), None);
}
#[tokio::test]
async fn a_gateway_that_failed_to_start_may_be_served_again() {
assert!(std::env::var_os(encore_gateway::program::LISTEN_ENV).is_none());
for _ in 0..2 {
let err = serve([register("body", Hooks::from(Hook::RequestBody), Body)])
.await
.expect_err("served outside a gateway program");
assert!(
err.to_string().contains("not a gateway program"),
"unexpected error: {err}"
);
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
struct User {
id: String,
}
static USER: Field<User> = Field::new("gw-user");
static PLAN: Field<String> = Field::new("gw-plan");
fn wire(json: &str) -> String {
encore_sdk_core::reqctx::encode(json.as_bytes())
}
fn ada() -> User {
User { id: "ada".into() }
}
type Seen = (&'static str, Option<User>, Option<String>);
#[derive(Default)]
struct Auth {
seen: Mutex<Vec<Seen>>,
}
impl Auth {
fn saw(&self, hook: &'static str) {
self.seen
.lock()
.unwrap()
.push((hook, USER.get(), PLAN.get()));
}
}
#[async_trait]
impl Middleware for Auth {
async fn on_request(&self, _req: &RequestView) -> Result<Decision, HookError> {
self.saw("request");
Ok(proceed()
.set_field(&USER, &ada())?
.unset_field(&PLAN)
.into())
}
async fn on_response(
&self,
_req: RequestId,
_resp: &ResponseView,
) -> Result<Vec<HeaderEdit>, HookError> {
self.saw("response");
Ok(Vec::new())
}
fn on_complete(&self, _done: &Completed) {
self.saw("complete");
}
}
#[tokio::test]
async fn hooks_run_in_their_request_s_context_as_on_request_sets_it() {
let auth = Arc::new(Auth::default());
let traced = Traced {
inner: auth.clone(),
observes: false,
remembers: true,
mark: false,
contexts: Mutex::new(HashMap::new()),
};
let mut req = view(&[]);
req.context = vec![("gw-plan".into(), wire("\"pro\""))];
let Ok(Decision::Continue(cont)) = traced.on_request(&req).await else {
panic!("not let through");
};
assert_eq!(
cont.context,
[
("gw-user".to_string(), Some(wire(r#"{"id":"ada"}"#))),
("gw-plan".to_string(), None),
]
);
let resp = ResponseView {
status: 200,
headers: Vec::new(),
};
traced.on_response(req.id, &resp).await.unwrap();
let mut forwarded = req.clone();
forwarded.context = vec![("gw-plan".into(), wire("\"team\""))];
traced.on_complete(&Completed {
request: forwarded,
status: 200,
rejected_by: None,
error: None,
received: std::time::SystemTime::UNIX_EPOCH,
duration: Duration::from_millis(3),
upstream_duration: None,
request_body_size: 0,
response_body_size: 0,
});
traced.on_finish(req.id);
assert_eq!(
*auth.seen.lock().unwrap(),
[
("request", None, Some("pro".to_string())),
("response", Some(ada()), None),
("complete", None, Some("team".to_string())),
]
);
assert!(Values::current().is_empty());
assert!(traced.contexts.lock().unwrap().is_empty());
}
#[test]
fn a_field_set_beyond_its_limits_fails_the_hook() {
let err = proceed()
.set_field(&PLAN, &"x".repeat(4096))
.expect_err("set beyond its limit");
assert!(
err.message()
.starts_with("reqctx: field \"gw-plan\": the value encodes to")
&& err.message().contains("more than the 4096 a field may"),
"{}",
err.message()
);
let big = "x".repeat(3000);
let _guard = Values::from_map([("gw-a".to_string(), wire(&format!("\"{big}\"")))].into())
.in_context(&Context::new())
.attach();
let err = proceed()
.set_field(&PLAN, &big)
.unwrap()
.set_field(&USER, &User { id: big.clone() })
.expect_err("set beyond the request's limit");
assert!(
err.message().contains("more than the 8192 they may"),
"{}",
err.message()
);
}
#[test]
fn matchers_spell_the_cores_json() {
let m = matcher::all_of([
matcher::header("authorization", matcher::prefix("Bearer ")),
matcher::not(matcher::method(["OPTIONS"])),
]);
assert_eq!(
serde_json::to_value(&m).unwrap(),
serde_json::json!({"all": [
{"header": {"name": "authorization", "cond": {"prefix": "Bearer "}}},
{"not": {"method": ["OPTIONS"]}},
]})
);
}
}