chadtmiller.com/group-host
atmosphere group host
0
0
The host limits how much one caller asks, and how often
crates/group-host/src/app_passwords.rs+11−3
| @@ -17,6 +17,7 @@ use crate::Host; | ||
use crate::api::{Params, invalid, param}; | ||
use crate::group::members_space; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::limits::{Client, SESSIONS, key}; | ||
use crate::oauth_dpop::hmac; | ||
use crate::oauth_resource::{Acting, Refusal}; | ||
use crate::oauth_store::{AppPassword, Grant, Tokens, app_password_client}; | ||
| @@ -25,9 +26,9 @@ use crate::scopes::Permissions; | ||
use crate::time::{iso, now_millis}; | ||
use crate::xrpc::XrpcError; | ||
use atproto::jose; | ||
use axum::Json; | ||
use axum::extract::{Query, State}; | ||
use axum::http::{HeaderMap, StatusCode, header}; | ||
use axum::{Extension, Json}; | ||
use serde_json::{Value, json}; | ||
use std::sync::Arc; | ||
| ||
| @@ -236,8 +237,13 @@ impl Host { | ||
} | ||
} | ||
| ||
/// Signs in to a group with one of its app passwords. | ||
pub async fn create_session(State(host): State<Arc<Host>>, Json(body): Json<Value>) -> Answer { | ||
/// Signs in to a group with one of its app passwords, as often as | ||
/// [`crate::limits::SESSIONS`] lets one handle from one address. | ||
pub async fn create_session( | ||
State(host): State<Arc<Host>>, | ||
client: Option<Extension<Client>>, | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let no = || refused("AuthenticationRequired", "Invalid identifier or password"); | ||
let identifier = body["identifier"] | ||
.as_str() | ||
| @@ -246,6 +252,8 @@ pub async fn create_session(State(host): State<Arc<Host>>, Json(body): Json<Valu | ||
.as_str() | ||
.ok_or_else(|| invalid("password is required"))?; | ||
let identifier = identifier.trim().trim_start_matches('@').to_lowercase(); | ||
let from = client.map_or_else(String::new, |Extension(Client(ip))| key(ip)); | ||
host.spend(&SESSIONS, &format!("{identifier} {from}"), 1)?; | ||
let account = host | ||
.store | ||
.account(&identifier) | ||
crates/group-host/src/config.rs+9−0
| @@ -83,6 +83,9 @@ pub struct Config { | ||
/// in front that the host can't reach at its public addresses). Unset, | ||
/// the domain itself, over https. | ||
pub site_check_at: Option<String>, | ||
/// Whether it limits how much one caller asks, `RATE_LIMITS`: `on`, | ||
/// unless `off` (`limits`). | ||
pub rate_limits: bool, | ||
} | ||
| ||
/// The service that finds anyone on the network by what is typed. | ||
| @@ -181,6 +184,11 @@ impl Config { | ||
var("SITE_HANDLE_RESOLVER").unwrap_or_else(|| "https://bsky.social".into()); | ||
let site_plc_url = var("SITE_PLC_URL").unwrap_or_else(|| plc_url.clone()); | ||
let site_check_at = var("SITE_CHECK_AT").map(|u| u.trim_end_matches('/').to_string()); | ||
let rate_limits = match var("RATE_LIMITS").as_deref() { | ||
None | Some("on") => true, | ||
Some("off") => false, | ||
Some(other) => bail!("RATE_LIMITS is on or off, not {other}"), | ||
}; | ||
Ok(Config { | ||
port, | ||
public_url, | ||
| @@ -204,6 +212,7 @@ impl Config { | ||
site_handle_resolver, | ||
site_plc_url, | ||
site_check_at, | ||
rate_limits, | ||
}) | ||
} | ||
| ||
crates/group-host/src/group_handle.rs+1−0
| @@ -113,6 +113,7 @@ pub async fn update_group_handle( | ||
if before == handle { | ||
return Ok(Json(json!({ "handle": handle }))); | ||
} | ||
host.spend(&crate::limits::HANDLES, group, 1)?; | ||
if named(&host, group, &address, &handle).await.as_deref() != Some(group) { | ||
return Err(bad( | ||
"NotPointing", | ||
crates/group-host/src/group_join.rs+1−0
| @@ -65,6 +65,7 @@ pub async fn request_join( | ||
Json(body): Json<Value>, | ||
) -> Answer { | ||
let me = signed_in(&host, &headers, &format!("{NS}.requestJoin")).await?; | ||
host.spend(&crate::limits::JOINS, &me, 1)?; | ||
let group = body["group"].as_str().expect("its lexicon requires it"); | ||
group_of(&host, group)?; | ||
host.active(group)?; | ||
crates/group-host/src/lib.rs+10−3
| @@ -33,6 +33,7 @@ pub mod index; | ||
pub mod index_api; | ||
pub mod lexicons; | ||
pub mod lifecycle; | ||
pub mod limits; | ||
pub mod logs; | ||
pub mod mcp; | ||
pub mod member_writes; | ||
| @@ -101,6 +102,8 @@ pub struct Host { | ||
pub logs: Arc<logs::Logs>, | ||
/// How it is used, counted for its operators. | ||
pub stats: stats::Stats, | ||
/// How much each caller has asked, against the limits. | ||
pub limits: limits::Limiter, | ||
} | ||
| ||
impl Host { | ||
| @@ -115,6 +118,7 @@ impl Host { | ||
let identity = identity::Resolver::new(&config.plc_url, &config.did_web_scheme); | ||
// A clock id of its own, so two hosts' revisions never collide. | ||
let clock = atproto::tid::TidClock::new(u64::from(secrets.signing.public().to_sec1()[1])); | ||
let limits = limits::Limiter::new(config.rate_limits); | ||
Ok(Host { | ||
config, | ||
store, | ||
| @@ -132,6 +136,7 @@ impl Host { | ||
handles: Default::default(), | ||
logs: Arc::new(logs), | ||
stats, | ||
limits, | ||
}) | ||
} | ||
} | ||
| @@ -161,10 +166,11 @@ pub fn client() -> reqwest::Client { | ||
} | ||
| ||
/// The host's routes, each request logged and counted | ||
/// ([`observe`]). | ||
/// ([`observe`]), and spent from its client's limits ([`limits`]). | ||
pub fn router(host: Arc<Host>) -> Router { | ||
let observing = axum::middleware::from_fn_with_state(host.clone(), observe::observe); | ||
routes(host).layer(observing) | ||
let limiting = axum::middleware::from_fn_with_state(host.clone(), limits::by_address); | ||
routes(host).layer(limiting).layer(observing) | ||
} | ||
| ||
/// The host's routes, as the MCP server calls them for a tool, within | ||
| @@ -715,7 +721,8 @@ pub async fn serve(config: Config) -> anyhow::Result<()> { | ||
tokio::time::sleep(std::time::Duration::from_secs(10)).await; | ||
} | ||
}); | ||
let app = router(host.clone()); | ||
// Served knowing each request's address, which the limits count by. | ||
let app = router(host.clone()).into_make_service_with_connect_info::<std::net::SocketAddr>(); | ||
axum::serve(listener, app) | ||
.with_graceful_shutdown(stopped()) | ||
.await?; | ||
crates/group-host/src/limits.rsnew+276−0
| @@ -0,0 +1,276 @@ | ||
//! How much one caller may ask of the host, and how often: the reference | ||
//! PDS's limits, and a few of the host's own where it asks other servers | ||
//! or keeps what anyone sends. Each limit is a fixed window of points for | ||
//! each key, begun at its first request: a client's address, a group, or | ||
//! someone signed in. Past them, a request is refused as | ||
//! `RateLimitExceeded`, a 429 saying when to try again. The windows are | ||
//! kept in memory, as only one host runs over its data, and `RATE_LIMITS` | ||
//! turns them off. | ||
//! | ||
//! The client is the address a request came from, unless that is this | ||
//! machine or its private network, as a proxy in front is: then the | ||
//! address `X-Forwarded-For` names, read from the right past each such | ||
//! address. An IPv6 client is counted with the rest of its /64. | ||
| ||
use crate::Host; | ||
use crate::time::now_millis; | ||
use crate::xrpc::XrpcError; | ||
use axum::extract::{ConnectInfo, Request, State}; | ||
use axum::middleware::Next; | ||
use axum::response::{IntoResponse, Response}; | ||
use std::collections::HashMap; | ||
use std::net::{IpAddr, SocketAddr}; | ||
use std::sync::{Arc, Mutex, PoisonError}; | ||
| ||
pub const MINUTE: i64 = 60 * 1000; | ||
pub const HOUR: i64 = 60 * MINUTE; | ||
pub const DAY: i64 = 24 * HOUR; | ||
| ||
/// How many points a key may spend in a window of `window` milliseconds. | ||
#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
pub struct Limit { | ||
/// What it limits, its windows kept apart from every other's. | ||
pub name: &'static str, | ||
pub points: u32, | ||
pub window: i64, | ||
} | ||
| ||
/// A [`Limit`], as a constant: a macro, so that nothing runs to make one. | ||
macro_rules! limit { | ||
($name:literal, $points:expr, $window:expr) => { | ||
Limit { | ||
name: $name, | ||
points: $points, | ||
window: $window, | ||
} | ||
}; | ||
} | ||
| ||
/// Every request from one address, but those [`by_path`] spares. | ||
pub const BY_ADDRESS: Limit = limit!("address", 3000, 5 * MINUTE); | ||
/// A whole repo, read from one address, as a relay reads them. | ||
pub const SYNC_REPO: Limit = limit!("sync-repo", 6000, 5 * MINUTE); | ||
/// Groups made from one address, each an identity in the directory. | ||
pub const NEW_GROUPS: Limit = limit!("new-groups", 100, 5 * MINUTE); | ||
/// An app's pushed request, which may fetch its metadata, from one | ||
/// address. | ||
pub const PUSHED: Limit = limit!("pushed", 300, 5 * MINUTE); | ||
/// MCP clients registering from one address, each one kept a day. | ||
pub const REGISTER: Limit = limit!("register", 30, 5 * MINUTE); | ||
/// Signing in to the console, or to move an account here, from one | ||
/// address: each asks the person's own server. | ||
pub const SIGN_IN: Limit = limit!("sign-in", 30, 5 * MINUTE); | ||
/// Searches for a handle being typed, from one address: each asks the | ||
/// search service. | ||
pub const SEARCH: Limit = limit!("search", 600, 5 * MINUTE); | ||
/// Signing in with an app password, by the handle and address. | ||
pub const SESSIONS: [Limit; 2] = [ | ||
limit!("session", 30, 5 * MINUTE), | ||
limit!("session-day", 300, DAY), | ||
]; | ||
/// What a group's tokens write, in points (see [`write_points`]). | ||
pub const WRITES_HOUR: Limit = limit!("writes", 5000, HOUR); | ||
pub const WRITES_DAY: Limit = limit!("writes-day", 35000, DAY); | ||
pub const WRITES: [Limit; 2] = [WRITES_HOUR, WRITES_DAY]; | ||
/// Blobs a group's tokens upload. | ||
pub const BLOBS: Limit = limit!("blobs", 1000, DAY); | ||
/// Changes to a group's handle, each an operation in the directory. | ||
pub const HANDLES: [Limit; 2] = [ | ||
limit!("handle", 10, 5 * MINUTE), | ||
limit!("handle-day", 50, DAY), | ||
]; | ||
/// Reports someone files, into groups' queues. | ||
pub const REPORTS: [Limit; 2] = [ | ||
limit!("reports", 10, 5 * MINUTE), | ||
limit!("reports-day", 100, DAY), | ||
]; | ||
/// Requests to join someone makes. | ||
pub const JOINS: [Limit; 2] = [ | ||
limit!("joins", 10, 5 * MINUTE), | ||
limit!("joins-day", 100, DAY), | ||
]; | ||
| ||
/// The headers a refusal says when to try again in, for a browser app to | ||
/// read. | ||
pub const EXPOSED: &str = | ||
"retry-after, ratelimit-limit, ratelimit-remaining, ratelimit-reset, ratelimit-policy"; | ||
| ||
/// A refusal: the limit spent, and when its window ends. | ||
#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
pub struct Spent { | ||
/// The limit's points. | ||
pub limit: u32, | ||
/// Its window, in seconds. | ||
pub window: i64, | ||
/// When the window ends, in seconds since the epoch. | ||
pub resets: i64, | ||
/// Seconds until then, at least one. | ||
pub retry_after: i64, | ||
} | ||
| ||
struct Window { | ||
ends: i64, | ||
used: u32, | ||
} | ||
| ||
#[derive(Default)] | ||
struct Windows { | ||
open: HashMap<(&'static str, String), Window>, | ||
/// When those ended are next let go. | ||
sweep_at: i64, | ||
} | ||
| ||
/// The windows of every limit and key. | ||
pub struct Limiter { | ||
on: bool, | ||
windows: Mutex<Windows>, | ||
} | ||
| ||
impl Limiter { | ||
/// Limits that count, or, `on` false, that count nothing. | ||
pub fn new(on: bool) -> Limiter { | ||
Limiter { | ||
on, | ||
windows: Mutex::default(), | ||
} | ||
} | ||
| ||
/// Spends `points` of `limit` for `key` at `now`, in milliseconds: | ||
/// refused, spending nothing, when the window has fewer left. | ||
pub fn spend(&self, limit: &Limit, key: &str, points: u32, now: i64) -> Result<(), Spent> { | ||
if !self.on { | ||
return Ok(()); | ||
} | ||
let mut held = self.windows.lock().unwrap_or_else(PoisonError::into_inner); | ||
if now >= held.sweep_at { | ||
held.open.retain(|_, w| w.ends > now); | ||
held.sweep_at = now + MINUTE; | ||
} | ||
let fresh = || Window { | ||
ends: now + limit.window, | ||
used: 0, | ||
}; | ||
let window = held | ||
.open | ||
.entry((limit.name, key.into())) | ||
.or_insert_with(fresh); | ||
if window.ends <= now { | ||
*window = fresh(); | ||
} | ||
if window.used + points > limit.points { | ||
return Err(Spent { | ||
limit: limit.points, | ||
window: limit.window / 1000, | ||
resets: window.ends / 1000, | ||
retry_after: (window.ends - now + 999) / 1000, | ||
}); | ||
} | ||
window.used += points; | ||
Ok(()) | ||
} | ||
} | ||
| ||
impl Host { | ||
/// Spends `points` of each of `limits` for `key`, now. | ||
pub fn spend(&self, limits: &[Limit], key: &str, points: u32) -> Result<(), XrpcError> { | ||
let now = now_millis(); | ||
for limit in limits { | ||
self.limits.spend(limit, key, points, now)?; | ||
} | ||
Ok(()) | ||
} | ||
| ||
/// Spends what `writes` cost of `group`'s writing. | ||
pub(crate) fn spend_writes( | ||
&self, | ||
group: &str, | ||
writes: &[crate::repo::Write], | ||
) -> Result<(), XrpcError> { | ||
self.spend(&WRITES, group, write_points(writes)) | ||
} | ||
} | ||
| ||
/// What writes cost, as the reference PDS counts them: a create three | ||
/// points, an update two, a delete one. | ||
pub fn write_points(writes: &[crate::repo::Write]) -> u32 { | ||
use crate::repo::Write; | ||
let each = |w: &Write| match w { | ||
Write::Create { .. } => 3, | ||
Write::Update { .. } => 2, | ||
Write::Delete { .. } => 1, | ||
}; | ||
writes.iter().map(each).sum() | ||
} | ||
| ||
/// Whether `ip` is this machine or its private network, where a proxy in | ||
/// front of the host is. | ||
fn proxy(ip: IpAddr) -> bool { | ||
match ip { | ||
IpAddr::V4(v4) => v4.is_loopback() || v4.is_private() || v4.is_link_local(), | ||
IpAddr::V6(v6) => v6.is_loopback() || v6.is_unique_local() || v6.is_unicast_link_local(), | ||
} | ||
} | ||
| ||
/// Who a request from `peer` is from, as `forwarded` | ||
/// (`X-Forwarded-For`) names them when `peer` is a proxy here. | ||
pub fn client(peer: IpAddr, forwarded: Option<&str>) -> IpAddr { | ||
let mut from = peer.to_canonical(); | ||
let named = forwarded.unwrap_or_default().rsplit(','); | ||
for next in named.filter_map(|a| a.trim().parse::<IpAddr>().ok()) { | ||
if !proxy(from) { | ||
break; | ||
} | ||
from = next.to_canonical(); | ||
} | ||
from | ||
} | ||
| ||
/// What a client is counted by: its address, or for IPv6, its /64. | ||
pub fn key(ip: IpAddr) -> String { | ||
match ip.to_canonical() { | ||
IpAddr::V6(v6) => { | ||
let [a, b, c, d, ..] = v6.segments(); | ||
format!("{a:x}:{b:x}:{c:x}:{d:x}::/64") | ||
} | ||
v4 => v4.to_string(), | ||
} | ||
} | ||
| ||
/// The client a request is from, as [`by_address`] found it. | ||
#[derive(Debug, Clone, Copy)] | ||
pub struct Client(pub IpAddr); | ||
| ||
/// The limits a request to `path` spends from its client's address. | ||
fn by_path(path: &str) -> &'static [Limit] { | ||
match path { | ||
// Asked by the machine's own checks and the proxy, and a relay's | ||
// stream, open for as long as it reads. | ||
"/xrpc/_health" | "/tls/ask" | "/xrpc/com.atproto.sync.subscribeRepos" => &[], | ||
"/xrpc/com.atproto.sync.getRepo" => &[SYNC_REPO], | ||
"/xrpc/fyi.opensocial.createGroup" | "/xrpc/fyi.opensocial.provisionGroup" => { | ||
&[BY_ADDRESS, NEW_GROUPS] | ||
} | ||
"/oauth/par" => &[BY_ADDRESS, PUSHED], | ||
"/mcp/register" => &[BY_ADDRESS, REGISTER], | ||
"/console/login" | "/console/move/login" => &[BY_ADDRESS, SIGN_IN], | ||
"/xrpc/fyi.opensocial.searchActors" => &[BY_ADDRESS, SEARCH], | ||
_ => &[BY_ADDRESS], | ||
} | ||
} | ||
| ||
/// Spends what a request costs its client's address, and notes the | ||
/// client for the methods that count by it too. A request with no | ||
/// address, made within the host, spends nothing. | ||
pub async fn by_address(State(host): State<Arc<Host>>, mut req: Request, next: Next) -> Response { | ||
let peer = req.extensions().get::<ConnectInfo<SocketAddr>>(); | ||
let peer = peer.map(|c| c.0.ip()); | ||
if let Some(peer) = peer { | ||
let forwarded = req.headers().get("x-forwarded-for"); | ||
let from = client(peer, forwarded.and_then(|v| v.to_str().ok())); | ||
if let Err(refused) = host.spend(by_path(req.uri().path()), &key(from), 1) { | ||
return refused.into_response(); | ||
} | ||
req.extensions_mut().insert(Client(from)); | ||
} | ||
next.run(req).await | ||
} | ||
crates/group-host/src/moderation.rs+2−0
| @@ -659,6 +659,8 @@ pub async fn create_report( | ||
if !appealed && !reads.map_err(XrpcError::internal)? { | ||
return Err(invalid_subject("not in a space you can read")); | ||
} | ||
// Counted once it goes in the queue: a refused one fills nothing. | ||
host.spend(&crate::limits::REPORTS, &me, 1)?; | ||
let now = now_millis(); | ||
let event = Event { | ||
kind: "report".into(), | ||
crates/group-host/src/oauth.rs+1−1
| @@ -125,7 +125,7 @@ pub async fn cors(req: HttpRequest, next: Next) -> Response { | ||
), | ||
( | ||
header::ACCESS_CONTROL_EXPOSE_HEADERS, | ||
"dpop-nonce, www-authenticate", | ||
"dpop-nonce, www-authenticate, retry-after, ratelimit-limit, ratelimit-remaining, ratelimit-reset, ratelimit-policy", | ||
), | ||
(header::ACCESS_CONTROL_MAX_AGE, "600"), | ||
] { | ||
crates/group-host/src/token_writes.rs+5−0
| @@ -309,6 +309,7 @@ pub async fn create_record( | ||
rkey: rkey.clone(), | ||
value: body["record"].clone(), | ||
}; | ||
host.spend_writes(group, std::slice::from_ref(&write))?; | ||
let (swap_commit, _) = swaps(&body)?; | ||
let allow = |w: &[Write]| host.may_repo(&acting, w); | ||
let asked = Asked { | ||
| @@ -339,6 +340,7 @@ async fn put_or_delete( | ||
let acting = host.writer(headers, nsid, body)?; | ||
let group = &acting.grant.group; | ||
let write = one(body, delete)?; | ||
host.spend_writes(group, std::slice::from_ref(&write))?; | ||
let (collection, rkey) = write.path(); | ||
let (swap_commit, swap_record) = swaps(body)?; | ||
let allow = |w: &[Write]| host.may_repo(&acting, w); | ||
| @@ -395,6 +397,7 @@ pub async fn apply_writes( | ||
let acting = host.writer(&headers, "com.atproto.repo.applyWrites", &body)?; | ||
let group = &acting.grant.group; | ||
let writes = listed(&host, "repo", &body)?; | ||
host.spend_writes(group, &writes)?; | ||
let (swap_commit, _) = swaps(&body)?; | ||
let allow = |w: &[Write]| host.may_repo(&acting, w); | ||
let asked = Asked { | ||
| @@ -431,6 +434,7 @@ pub async fn upload_blob(State(host): State<Arc<Host>>, headers: HeaderMap, body | ||
if !acting.permissions.blob(mime) { | ||
return Err(missing(format!("blob:{mime}")).into()); | ||
} | ||
host.spend(&[crate::limits::BLOBS], group, 1)?; | ||
let limit = host.config.blob_upload_limit; | ||
let bytes = crate::xrpc::read_body(body, limit, "BlobTooLarge").await?; | ||
let blob = host.upload_blob(group, &bytes, mime)?; | ||
| @@ -555,6 +559,7 @@ async fn space_writes( | ||
let (uri, space) = space_of(body)?; | ||
let writes = writes(host)?; | ||
let group = acting.grant.group.clone(); | ||
host.spend_writes(&group, &writes)?; | ||
// Someone's inbox, where the group writes invites, is theirs. | ||
if is_inbox(&space) { | ||
let made = host.write_invites(&acting, &space, writes).await?; | ||
crates/group-host/src/xrpc.rs+42−2
| @@ -1,9 +1,10 @@ | ||
//! XRPC's failures, as atproto's servers answer them: an HTTP status and | ||
//! `{error, message}`. | ||
| ||
use crate::limits::{EXPOSED, Spent}; | ||
use axum::Json; | ||
use axum::body::{Body, Bytes}; | ||
use axum::http::StatusCode; | ||
use axum::http::{HeaderValue, StatusCode}; | ||
use axum::response::{IntoResponse, Response}; | ||
use serde_json::json; | ||
| ||
| @@ -13,6 +14,8 @@ pub struct XrpcError { | ||
/// The failure's name, as the method's lexicon lists it. | ||
pub error: &'static str, | ||
pub message: String, | ||
/// The limit spent, for a refusal past one: when to try again. | ||
pub limited: Option<Spent>, | ||
} | ||
| ||
impl XrpcError { | ||
| @@ -21,6 +24,19 @@ impl XrpcError { | ||
status, | ||
error, | ||
message: message.into(), | ||
limited: None, | ||
} | ||
} | ||
| ||
/// A refusal past a limit, until its window ends. | ||
pub fn limited(spent: Spent) -> Self { | ||
let said = format!( | ||
"too many requests: try again in {} seconds", | ||
spent.retry_after | ||
); | ||
XrpcError { | ||
limited: Some(spent), | ||
..XrpcError::new(StatusCode::TOO_MANY_REQUESTS, "RateLimitExceeded", said) | ||
} | ||
} | ||
| ||
| @@ -44,13 +60,37 @@ impl XrpcError { | ||
} | ||
} | ||
| ||
impl From<Spent> for XrpcError { | ||
fn from(spent: Spent) -> XrpcError { | ||
XrpcError::limited(spent) | ||
} | ||
} | ||
| ||
impl IntoResponse for XrpcError { | ||
/// The failure as JSON, and kept with the answer, for the line logged | ||
/// of the request to say why. | ||
/// of the request to say why. A refusal past a limit says, in the | ||
/// headers the reference PDS sends, when to try again, to any origin. | ||
fn into_response(self) -> Response { | ||
let body = json!({ "error": self.error, "message": self.message }); | ||
let limited = self.limited; | ||
let mut res = (self.status, Json(body)).into_response(); | ||
res.extensions_mut().insert(self); | ||
if let Some(s) = limited { | ||
let headers = res.headers_mut(); | ||
let policy = format!("{};w={}", s.limit, s.window); | ||
for (name, value) in [ | ||
("ratelimit-limit", s.limit.to_string()), | ||
("ratelimit-remaining", "0".into()), | ||
("ratelimit-reset", s.resets.to_string()), | ||
("ratelimit-policy", policy), | ||
("retry-after", s.retry_after.to_string()), | ||
("access-control-allow-origin", "*".into()), | ||
("access-control-expose-headers", EXPOSED.into()), | ||
] { | ||
let value = HeaderValue::try_from(value).expect("numbers are a header's value"); | ||
headers.insert(name, value); | ||
} | ||
} | ||
res | ||
} | ||
} | ||