Security fixes for 27.1-rc.37 #511

Merged
jcoffey-dev merged 5 commits from sec/batch-11 into main 2026-11-20 20:48:02 +00:00
20 changed files with 1118 additions and 140 deletions

No files matched your search

+9 -1
View File
@@ -2,6 +2,8 @@
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*
* Modified by Coffey Labs in 2026 for INBUXA.
*/
use super::jose::{Body, eab_sign, sign};
@@ -49,7 +51,12 @@ pub async fn acme_create_account(
*contact = format!("mailto:{}", email);
}
let directory = Directory::discover(&provider.directory, provider.max_retries as u32).await?;
let directory = Directory::discover(
&provider.directory,
provider.max_retries as u32,
provider.member_tenant_id.is_some(),
)
.await?;
let account_key = EcdsaKeyPair::generate_pkcs8(ALG, &SystemRandom::new()).unwrap();
let key_pair = EcdsaKeyPair::from_pkcs8(ALG, account_key.as_ref())
.map_err(|err| AcmeError::Crypto(format!("Failed to create ECDSA key pair: {}", err)))?;
@@ -79,6 +86,7 @@ pub async fn acme_create_account(
Method::POST,
Some(body),
provider.max_retries as u32,
directory.public_only,
)
.await?,
"Location",
+38 -11
View File
@@ -2,6 +2,8 @@
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*
* Modified by Coffey Labs in 2026 for INBUXA.
*/
// Adapted from rustls-acme (https://github.com/FlorianUekermann/rustls-acme), licensed under MIT/Apache-2.0.
@@ -49,8 +51,12 @@ static ALG: &EcdsaSigningAlgorithm = &ECDSA_P256_SHA256_FIXED_SIGNING;
impl AcmeRequestBuilder {
pub async fn new(provider: AcmeProvider) -> AcmeResult<Self> {
let directory =
Directory::discover(&provider.directory, provider.max_retries as u32).await?;
let directory = Directory::discover(
&provider.directory,
provider.max_retries as u32,
provider.member_tenant_id.is_some(),
)
.await?;
let key_pair = EcdsaKeyPair::from_pkcs8(
ALG,
&URL_SAFE_NO_PAD
@@ -83,7 +89,14 @@ impl AcmeRequestBuilder {
url.as_ref(),
payload,
)?;
let response = https(url.as_ref(), Method::POST, Some(body), self.max_retries).await?;
let response = https(
url.as_ref(),
Method::POST,
Some(body),
self.max_retries,
self.directory.public_only,
)
.await?;
Ok(AcmeResponse {
location: get_header(&response, "Location").ok(),
@@ -188,19 +201,31 @@ impl AcmeRequestBuilder {
}
impl Directory {
pub async fn discover(url: impl AsRef<str>, max_retries: u32) -> AcmeResult<Self> {
serde_json::from_str(
&https(url, Method::GET, None, max_retries)
pub async fn discover(
url: impl AsRef<str>,
max_retries: u32,
public_only: bool,
) -> AcmeResult<Self> {
let mut directory: Self = serde_json::from_str(
&https(url, Method::GET, None, max_retries, public_only)
.await?
.text()
.await?,
)
.map_err(Into::into)
)?;
directory.public_only = public_only;
Ok(directory)
}
pub async fn nonce(&self, max_retries: u32) -> AcmeResult<String> {
get_header(
&https(&self.new_nonce.as_str(), Method::HEAD, None, max_retries).await?,
&https(
&self.new_nonce.as_str(),
Method::HEAD,
None,
max_retries,
self.public_only,
)
.await?,
"replay-nonce",
)
}
@@ -210,9 +235,11 @@ impl<L, T: DeserializeOwned> AcmeResponse<L, T> {
pub fn parse(input: AcmeResponse<L, String>) -> AcmeResult<AcmeResponse<L, T>> {
serde_json::from_str(&input.body)
.map_err(|err| {
// inbuxa: a bounded excerpt, not the whole body (see http.rs)
AcmeError::Invalid(format!(
"ACME response parsing error: {}, body: {}",
err, input.body
"ACME response parsing error: {}, body starts: {:?}",
err,
input.body.chars().take(120).collect::<String>()
))
})
.map(|body| AcmeResponse {
+202 -8
View File
@@ -2,9 +2,15 @@
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*
* Modified by Coffey Labs in 2026 for INBUXA.
*/
use crate::network::acme::{AcmeError, AcmeResult};
use crate::network::{
acme::{AcmeError, AcmeResult},
is_global_ip,
public_only::PublicOnly,
};
use chrono::{DateTime, Utc};
use hyper::{
Method, StatusCode,
@@ -14,13 +20,26 @@ use reqwest::Response;
use std::time::Duration;
#[allow(unused_mut)]
///
/// inbuxa: `public_only` is set for a tenant's own ACME provider. Its
/// administrator picks the directory URL and the directory names every URL
/// after it, so each request must be HTTPS to a public address, checked when
/// the name resolves, with no redirects (a redirect to an IP literal would
/// skip that check).
pub(crate) async fn https(
url: impl AsRef<str>,
method: Method,
body: Option<String>,
max_retries: u32,
public_only: bool,
) -> AcmeResult<Response> {
let url = url.as_ref();
if public_only && !(starts_with_ignore_case(url, "https://") && has_public_ip_or_name(url)) {
return Err(AcmeError::Invalid(format!(
"A tenant's ACME provider must use a public HTTPS address: {}",
redact_url(url)
)));
}
#[allow(unused_mut)]
#[allow(unused_assignments)]
@@ -32,8 +51,14 @@ pub(crate) async fn https(
url.starts_with("https://localhost") || url.starts_with("https://127.0.0.1");
}
let mut request = utils::http::http1_client_builder(allow_invalid_certs)
.timeout(Duration::from_secs(30))
let mut client =
utils::http::http1_client_builder(allow_invalid_certs).timeout(Duration::from_secs(30));
if public_only {
client = client
.public_only()
.redirect(reqwest::redirect::Policy::none());
}
let mut request = client
.build()?
.request(method, url)
.header(USER_AGENT, crate::USER_AGENT);
@@ -62,12 +87,24 @@ pub(crate) async fn https(
Err(AcmeError::Backoff { wait, max_retries })
} else {
// inbuxa: this message reaches the JMAP caller. Only an ACME problem
// document's own type and detail go into it, never the raw body of
// whatever answered.
let status = response.status();
let text = response.text().await.unwrap_or_default();
Err(AcmeError::HttpStatus(format!(
"Unexpected status {}: {}",
status, text
)))
let problem = if is_problem_document(&response) {
response
.json::<Problem>()
.await
.map(|problem| problem.summary())
.unwrap_or_default()
} else {
String::new()
};
Err(AcmeError::HttpStatus(if problem.is_empty() {
format!("Unexpected status {status}")
} else {
format!("Unexpected status {status}: {problem}")
}))
}
}
@@ -198,3 +235,160 @@ mod tests {
assert!(links.is_empty());
}
}
/// inbuxa: the parts of an RFC 7807 problem document an ACME server explains
/// itself with (RFC 8555 section 6.7).
#[derive(serde::Deserialize)]
struct Problem {
#[serde(rename = "type", default)]
kind: String,
#[serde(default)]
detail: String,
}
/// The longest detail passed on, in characters.
const MAX_PROBLEM_DETAIL: usize = 300;
impl Problem {
fn summary(&self) -> String {
let detail: String = self
.detail
.chars()
.filter(|c| !c.is_control())
.take(MAX_PROBLEM_DETAIL)
.collect();
let kind: String = self
.kind
.chars()
.filter(|c| c.is_ascii_graphic())
.take(100)
.collect();
match (kind.is_empty(), detail.is_empty()) {
(false, false) => format!("{kind}: {detail}"),
(false, true) => kind,
(true, false) => detail,
(true, true) => String::new(),
}
}
}
fn is_problem_document(response: &Response) -> bool {
response
.headers()
.get(CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| {
value
.split(';')
.next()
.unwrap_or_default()
.trim()
.eq_ignore_ascii_case("application/problem+json")
})
}
/// The URL's host is a name (checked when it resolves) or a public IP
/// literal. Unlike `public_only::has_public_host`, test builds get no
/// loopback exception: no test reaches a tenant's ACME server.
fn has_public_ip_or_name(url: &str) -> bool {
let Some(host) = reqwest::Url::parse(url)
.ok()
.and_then(|url| url.host_str().map(str::to_string))
else {
return false;
};
let host = host
.strip_prefix('[')
.and_then(|host| host.strip_suffix(']'))
.unwrap_or(&host);
match host.parse::<std::net::IpAddr>() {
Ok(ip) => is_global_ip(&ip),
Err(_) => true,
}
}
fn starts_with_ignore_case(value: &str, prefix: &str) -> bool {
value
.get(..prefix.len())
.is_some_and(|start| start.eq_ignore_ascii_case(prefix))
}
/// The URL without its query or any credentials, for an error message.
fn redact_url(url: &str) -> String {
match reqwest::Url::parse(url) {
Ok(mut url) => {
let _ = url.set_username("");
let _ = url.set_password(None);
url.set_query(None);
url.set_fragment(None);
url.to_string()
}
Err(_) => "(not a URL)".to_string(),
}
}
#[cfg(test)]
mod tenant_tests {
use super::*;
fn outcome(result: &AcmeResult<Response>) -> String {
match result {
Ok(response) => format!("status {}", response.status()),
Err(err) => err.to_string(),
}
}
#[tokio::test]
async fn tenant_destinations_are_checked_before_sending() {
for url in [
"http://acme.example.com/dir",
"ftp://acme.example.com/dir",
"https://10.0.0.1/dir",
"https://169.254.169.254/latest/meta-data/",
"https://[fd00::1]/dir",
"https://[::ffff:192.168.1.1]/dir",
"https://127.0.0.1/dir",
"https://[::1]/dir",
"not a url",
] {
let result = https(url, Method::GET, None, 0, true).await;
match &result {
Err(AcmeError::Invalid(message)) => {
assert!(message.contains("public HTTPS"), "{url}: {message}")
}
_ => panic!("{url}: expected a refusal, got {}", outcome(&result)),
}
}
}
#[tokio::test]
async fn tenant_host_names_must_resolve_to_public_addresses() {
// localhost resolves to loopback: refused when it resolves, before
// anything is sent.
let result = https("https://localhost:9/dir", Method::GET, None, 0, true).await;
match &result {
Err(AcmeError::Http(err)) => assert!(err.is_connect() || err.is_request(), "{err}"),
_ => panic!("expected a resolver refusal, got {}", outcome(&result)),
}
}
#[test]
fn problem_summary_is_bounded() {
let problem = Problem {
kind: "urn:ietf:params:acme:error:malformed".to_string(),
detail: format!("bad\nthing {}", "x".repeat(1000)),
};
let summary = problem.summary();
assert!(summary.starts_with("urn:ietf:params:acme:error:malformed: bad"));
assert!(!summary.contains('\n'));
assert!(summary.len() < 450, "{}", summary.len());
}
#[test]
fn redacted_urls_drop_credentials_and_query() {
assert_eq!(
redact_url("https://user:[email protected]/dir?token=1#x"),
"https://acme.example.com/dir"
);
}
}
+4
View File
@@ -83,6 +83,10 @@ pub struct Directory {
pub new_nonce: String,
pub new_account: String,
pub new_order: String,
/// inbuxa: a tenant's provider, so every request goes only to public
/// HTTPS addresses (see `http::https`).
#[serde(skip)]
pub public_only: bool,
}
#[derive(Debug, Deserialize, Eq, PartialEq, Clone, Copy)]
+3
View File
@@ -2,8 +2,11 @@
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*
* Modified by Coffey Labs in 2026 for INBUXA.
*/
pub mod records;
pub mod resolve;
pub mod tenant_endpoints; // inbuxa: a tenant's DNS provider stays on public addresses
pub mod update;
@@ -0,0 +1,246 @@
/*
* SPDX-FileCopyrightText: 2026 Coffey Labs LLC
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
//! A tenant's own DNS provider may only talk to public addresses.
//!
//! Some providers take an endpoint (cPanel, Plesk, PowerDNS, Infoblox, ...)
//! and RFC 2136 takes a server address, so a tenant administrator could aim
//! the server's DNS updates at a loopback or private service and read
//! something back in the error. Others build their URL from a region or zone
//! name, where a crafted value (`[email protected]/`) could move the host. For a
//! provider owned by a tenant, endpoints must be HTTPS to names that resolve
//! only to public addresses, an RFC 2136 server must be a public address, and
//! names that go into URLs must be plain names. The server's own providers,
//! which only a server administrator can create, keep any destination:
//! private DNS servers are a normal setup there.
//!
//! This runs each time a provider is saved and each time an updater is built
//! from it, so a name that later moves to a private address is caught at the
//! next use.
use super::super::is_global_ip;
use registry::schema::{prelude::ObjectInner, structs::DnsServer};
use reqwest::Url;
use std::net::IpAddr;
/// The endpoint and URL-name fields of a tenant's provider, or `Ok(())` for
/// a provider the server owns.
pub async fn check_tenant_dns_server(server: &DnsServer) -> Result<(), String> {
if ObjectInner::DnsServer(server.clone())
.member_tenant_id()
.is_none()
{
return Ok(());
}
let fields = TenantFields::of(server);
if fields.plain_http {
return Err("A tenant's DNS provider must use HTTPS (scheme)".to_string());
}
for (field, name) in fields.names {
if !is_plain_name(name) {
return Err(format!(
"{field} may only contain letters, digits, '-', '_' and '.'"
));
}
}
if let Some(ip) = fields.rfc2136 {
if !is_global_ip(&ip) {
return Err(format!(
"A tenant's DNS server must have a public address, not {ip}"
));
}
}
for (field, endpoint) in fields.endpoints {
check_endpoint(field, endpoint).await?;
}
Ok(())
}
#[derive(Default)]
struct TenantFields<'x> {
endpoints: Vec<(&'static str, &'x str)>,
names: Vec<(&'static str, &'x str)>,
rfc2136: Option<IpAddr>,
plain_http: bool,
}
impl<'x> TenantFields<'x> {
fn of(server: &'x DnsServer) -> Self {
let mut fields = TenantFields::default();
match server {
DnsServer::Tsig(server) => fields.rfc2136 = Some(server.host.0),
DnsServer::BluecatV2(server) => fields.endpoints.push(("baseUrl", &server.base_url)),
DnsServer::Cpanel(server) => fields.endpoints.push(("baseUrl", &server.base_url)),
DnsServer::Plesk(server) => fields.endpoints.push(("baseUrl", &server.base_url)),
DnsServer::EdgeDns(server) => fields.endpoints.push(("host", &server.host)),
DnsServer::Infoblox(server) => fields.endpoints.push(("host", &server.host)),
DnsServer::PowerDns(server) => {
fields
.endpoints
.extend(server.endpoint.as_deref().map(|e| ("endpoint", e)));
fields
.names
.extend(server.server_id.as_deref().map(|e| ("serverId", e)));
}
DnsServer::UltraDns(server) => {
fields
.endpoints
.extend(server.endpoint.as_deref().map(|e| ("endpoint", e)));
}
DnsServer::Volcengine(server) => {
if let Some(host) = server.host.as_deref() {
fields.endpoints.push(("host", host));
}
fields
.names
.extend(server.region.as_deref().map(|e| ("region", e)));
if server
.scheme
.as_deref()
.is_some_and(|scheme| !scheme.eq_ignore_ascii_case("https"))
{
fields.plain_http = true;
}
}
DnsServer::Route53(server) => {
fields.names.push(("region", &server.region));
fields.names.extend(
server
.hosted_zone_id
.as_deref()
.map(|e| ("hostedZoneId", e)),
);
}
DnsServer::Lightsail(server) => {
fields
.names
.extend(server.region.as_deref().map(|e| ("region", e)));
fields
.names
.extend(server.domain.as_deref().map(|e| ("domain", e)));
}
DnsServer::Alidns(server) => {
fields
.names
.extend(server.region.as_deref().map(|e| ("region", e)));
}
DnsServer::TencentCloud(server) => {
fields
.names
.extend(server.region.as_deref().map(|e| ("region", e)));
}
DnsServer::HuaweiCloud(server) => fields.names.push(("region", &server.region)),
DnsServer::OracleCloud(server) => fields.names.push(("region", &server.region)),
_ => {}
}
fields
}
}
/// A value that can sit inside a host name or a path segment and not move
/// the host: no '@', ':', '/', '?', '#', '%' or spaces.
fn is_plain_name(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 253
&& value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
}
/// An endpoint, given as a URL or a bare `host[:port]` (which providers
/// reach over HTTPS), must be HTTPS to a name whose every address is public.
async fn check_endpoint(field: &str, endpoint: &str) -> Result<(), String> {
let endpoint = endpoint.trim();
let url = if endpoint.contains("://") {
Url::parse(endpoint)
} else {
Url::parse(&format!("https://{endpoint}"))
}
.map_err(|_| format!("{field} is not a valid address"))?;
if url.scheme() != "https" {
return Err(format!("A tenant's DNS provider must use HTTPS ({field})"));
}
if !url.username().is_empty() || url.password().is_some() {
return Err(format!("{field} may not contain credentials"));
}
let host = url
.host_str()
.ok_or_else(|| format!("{field} has no host"))?
.trim_start_matches('[')
.trim_end_matches(']')
.to_string();
if let Ok(ip) = host.parse::<IpAddr>() {
return if is_global_ip(&ip) {
Ok(())
} else {
Err(format!(
"A tenant's DNS provider must use a public address ({field})"
))
};
}
let addrs =
tokio::net::lookup_host((host.as_str(), url.port_or_known_default().unwrap_or(443)))
.await
.map_err(|_| format!("{field}: {host} does not resolve"))?
.collect::<Vec<_>>();
if addrs.is_empty() || addrs.iter().any(|addr| !is_global_ip(&addr.ip())) {
return Err(format!(
"A tenant's DNS provider must use a public address ({field}: {host})"
));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plain_names() {
for ok in [
"eu-west-1",
"cn-hangzhou",
"Z123ABC",
"example.com",
"localhost_1",
] {
assert!(is_plain_name(ok), "{ok}");
}
for bad in ["", "[email protected]/", "a/b", "a:1", "a?b", "a#b", "a%2f", "a b"] {
assert!(!is_plain_name(bad), "{bad}");
}
}
#[tokio::test]
async fn endpoints() {
for bad in [
"http://dns.example.com/api",
"https://127.0.0.1/api",
"https://10.1.2.3:2083",
"10.1.2.3:2083",
"https://[::1]/",
"https://[fd00::1]/",
"https://169.254.169.254/",
"https://user:[email protected]/",
"https://localhost/",
"localhost:8081",
"ftp://8.8.8.8/",
] {
assert!(check_endpoint("endpoint", bad).await.is_err(), "{bad}");
}
for ok in [
"https://8.8.8.8/api",
"8.8.8.8:2083",
"https://[2606:4700::1111]/",
] {
assert!(check_endpoint("endpoint", ok).await.is_ok(), "{ok}");
}
}
}
+2
View File
@@ -104,6 +104,8 @@ pub static DNS_RECORDS: std::sync::LazyLock<
impl DnsUpdater {
pub async fn build(server: DnsServer, core: Arc<Core>) -> Result<Self, String> {
// inbuxa: a tenant's provider only reaches public addresses (F3)
super::tenant_endpoints::check_tenant_dns_server(&server).await?;
match server {
DnsServer::Tsig(server) => Ok(DnsUpdater {
polling_interval: server.polling_interval.into_inner(),
+3 -76
View File
@@ -19,7 +19,7 @@ use std::fmt::Debug;
use std::{
borrow::Cow,
io,
net::{IpAddr, Ipv4Addr, Ipv6Addr},
net::IpAddr,
sync::Arc,
time::{Duration, Instant},
};
@@ -303,81 +303,8 @@ impl Debug for TcpAcceptor {
}
}
pub fn is_global_ip(ip: &IpAddr) -> bool {
match ip {
IpAddr::V4(ip) => is_global_ipv4(ip),
IpAddr::V6(ip) => is_global_ipv6(ip),
}
}
fn is_global_ipv4(ip: &Ipv4Addr) -> bool {
let [a, b, c, _] = ip.octets();
let is_this_network = a == 0;
let is_shared = a == 100 && (64..128).contains(&b);
let is_protocol_assignment = a == 192 && b == 0 && c == 0;
let is_benchmarking = a == 198 && (b & 0xfe) == 18;
let is_relay_6to4 = a == 192 && b == 88 && c == 99;
let is_reserved = a >= 240;
!(ip.is_unspecified()
|| ip.is_loopback()
|| ip.is_private()
|| ip.is_link_local()
|| ip.is_multicast()
|| ip.is_broadcast()
|| ip.is_documentation()
|| is_this_network
|| is_shared
|| is_protocol_assignment
|| is_benchmarking
|| is_relay_6to4
|| is_reserved)
}
fn is_global_ipv6(ip: &Ipv6Addr) -> bool {
if ip.is_unspecified() || ip.is_loopback() || ip.is_multicast() {
return false;
}
if let Some(ip) = ip.to_ipv4() {
return is_global_ipv4(&ip);
}
let segments = ip.segments();
if segments[0] == 0x2002 {
return is_global_ipv4(&Ipv4Addr::from(
((segments[1] as u32) << 16) | segments[2] as u32,
));
}
if segments[0] == 0x0064 && segments[1] == 0xff9b {
let is_well_known_prefix =
segments[2] == 0 && segments[3] == 0 && segments[4] == 0 && segments[5] == 0;
return is_well_known_prefix
&& is_global_ipv4(&Ipv4Addr::from(
((segments[6] as u32) << 16) | segments[7] as u32,
));
}
let is_unique_local = (segments[0] & 0xfe00) == 0xfc00;
let is_link_local = (segments[0] & 0xffc0) == 0xfe80;
let is_site_local = (segments[0] & 0xffc0) == 0xfec0;
let is_discard_only =
segments[0] == 0x0100 && segments[1] == 0 && segments[2] == 0 && segments[3] == 0;
let is_documentation = segments[0] == 0x2001 && segments[1] == 0x0db8;
let is_teredo = segments[0] == 0x2001 && segments[1] == 0;
let is_orchid = segments[0] == 0x2001 && (segments[1] & 0xfff0) == 0x0020;
!(is_unique_local
|| is_link_local
|| is_site_local
|| is_discard_only
|| is_documentation
|| is_teredo
|| is_orchid)
}
// inbuxa: moved to utils so crates below common can use it
pub use utils::public_ip::is_global_ip;
pub fn ip_to_bytes(ip: &IpAddr) -> Vec<u8> {
match ip {
+2 -24
View File
@@ -13,10 +13,7 @@
//! [`has_public_host`] before sending.
use super::is_global_ip;
use reqwest::{
ClientBuilder, Url,
dns::{Addrs, Name, Resolve, Resolving},
};
use reqwest::{ClientBuilder, Url};
use std::net::IpAddr;
pub trait PublicOnly {
@@ -27,26 +24,7 @@ pub trait PublicOnly {
impl PublicOnly for ClientBuilder {
fn public_only(self) -> Self {
self.no_proxy().dns_resolver(PublicResolver)
}
}
struct PublicResolver;
impl Resolve for PublicResolver {
fn resolve(&self, name: Name) -> Resolving {
Box::pin(async move {
let addrs = tokio::net::lookup_host((name.as_str(), 0))
.await?
.filter(|addr| is_global_ip(&addr.ip()))
.collect::<Vec<_>>();
if !addrs.is_empty() {
Ok(Box::new(addrs.into_iter()) as Addrs)
} else {
Err(format!("{} has no public address", name.as_str()).into())
}
})
utils::public_ip::public_only(self)
}
}
+95 -5
View File
@@ -2,6 +2,8 @@
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*
* Modified by Coffey Labs in 2026 for INBUXA.
*/
use crate::{
@@ -127,6 +129,7 @@ impl FileGetRequestHandler for Server {
Some(Some(range)) => Some(range.start as usize..range.end as usize),
Some(None) => {
return Ok(HttpResponse::new(StatusCode::RANGE_NOT_SATISFIABLE)
.with_header(hyper::header::CONTENT_SECURITY_POLICY, FILE_CSP)
.with_accept_ranges()
.with_etag(etag)
.with_content_range(format!("bytes */{size}")));
@@ -134,11 +137,15 @@ impl FileGetRequestHandler for Server {
None => None,
};
let response = HttpResponse::new(StatusCode::OK)
.with_content_type(content_type.unwrap_or("application/octet-stream"))
.with_etag(etag)
.with_last_modified(last_modified)
.with_accept_ranges();
let content_type = content_type.unwrap_or("application/octet-stream");
let response = user_content_policy(
HttpResponse::new(StatusCode::OK)
.with_content_type(content_type)
.with_etag(etag)
.with_last_modified(last_modified)
.with_accept_ranges(),
content_type,
);
if is_head {
return Ok(response.with_content_length(size));
@@ -166,3 +173,86 @@ impl FileGetRequestHandler for Server {
.with_binary_body(contents))
}
}
/// inbuxa: a stored file is whatever its uploader sent, under the type they
/// claimed, and it is served on the same origin as the sign-in page, JMAP and
/// the console's API. Opened in a browser, an uploaded HTML or SVG page would
/// run as this server. So every file answer carries a sandbox policy, which
/// gives the document an opaque origin and no scripts, and only types that
/// can't hold active content are offered for display; everything else is a
/// download. WebDAV clients ignore both headers.
/// `frame-ancestors` is here so the default HTML headers don't add a second
/// policy of their own (security_headers.rs).
const FILE_CSP: &str = "default-src 'none'; frame-ancestors 'none'; sandbox";
fn user_content_policy(response: HttpResponse, content_type: &str) -> HttpResponse {
let response = response
.with_header(hyper::header::X_CONTENT_TYPE_OPTIONS, "nosniff")
.with_header(hyper::header::CONTENT_SECURITY_POLICY, FILE_CSP);
if shown_inline(content_type) {
response
} else {
response.with_content_disposition("attachment")
}
}
/// Types a browser shows without running anything: raster images, audio,
/// video and plain text. SVG, HTML, XML, PDF and anything unknown download.
fn shown_inline(content_type: &str) -> bool {
let essence = content_type
.split(';')
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase();
matches!(
essence.as_str(),
"image/png"
| "image/jpeg"
| "image/gif"
| "image/webp"
| "image/avif"
| "image/bmp"
| "text/plain"
) || ((essence.starts_with("audio/") || essence.starts_with("video/"))
&& !essence.contains("xml"))
}
#[cfg(test)]
mod tests {
use super::shown_inline;
#[test]
fn active_types_download() {
for ty in [
"text/html",
"TEXT/HTML; charset=utf-8",
"application/xhtml+xml",
"image/svg+xml",
"text/xml",
"application/xml",
"application/pdf",
"text/javascript",
"application/octet-stream",
"",
"garbage",
" text/html ",
] {
assert!(!shown_inline(ty), "{ty:?} must download");
}
}
#[test]
fn passive_types_show() {
for ty in [
"image/png",
"image/jpeg",
"IMAGE/WEBP",
"text/plain; charset=utf-8",
"audio/mpeg",
"video/mp4",
] {
assert!(shown_inline(ty), "{ty:?} should show inline");
}
}
}
+97 -2
View File
@@ -75,6 +75,7 @@ impl OpenIdDirectory {
};
Self::new(OidcConfig {
public_only: config.member_tenant_id.is_some(),
issue_url: config.issuer_url,
require_aud: config.require_audience,
require_scopes: config.require_scopes.into_inner(),
@@ -90,9 +91,21 @@ impl OpenIdDirectory {
}
pub async fn new(mut config: OidcConfig) -> Result<Self, OidcError> {
let http = utils::http::http_client_builder(false)
let mut http = utils::http::http_client_builder(false)
.user_agent("inbuxa/1.0") // types::brand!(); this crate does not depend on types
.timeout(Duration::from_secs(30))
.timeout(Duration::from_secs(30));
// inbuxa: a tenant's directory reaches only public addresses, with no
// redirects (a redirect to an IP literal would skip the resolver)
if config.public_only && !is_test_loopback(&config.issue_url) {
check_tenant_url("issuerUrl", &config.issue_url)?;
if let OpaqueTokens::Introspection(Introspection { url: Some(url), .. }) =
&config.opaque_tokens
{
check_tenant_url("introspectionUrl", url)?;
}
http = utils::public_ip::public_only(http).redirect(reqwest::redirect::Policy::none());
}
let http = http
.build()
.map_err(|e| OidcError::Network(format!("HTTP client build failed: {e}")))?;
@@ -115,6 +128,16 @@ impl OpenIdDirectory {
}
};
// inbuxa: the provider names the rest of its URLs; a tenant's must be
// public too
if config.public_only && !is_test_loopback(&config.issue_url) {
check_tenant_url("jwks_uri", &document.jwks_uri)?;
check_tenant_url("userinfo_endpoint", &document.userinfo_endpoint)?;
if let Some(url) = &document.introspection_endpoint {
check_tenant_url("introspection_endpoint", url)?;
}
}
// inbuxa: http-directory-services-13
if let OpaqueTokens::Introspection(introspection) = &mut config.opaque_tokens
&& introspection.url.is_none()
@@ -242,6 +265,51 @@ impl OpenIdDirectory {
}
}
/// The test harness runs its identity provider (Keycloak) on localhost, as
/// it serves push and reports on 127.0.0.1 (`common::network::public_only`).
/// Never true outside test builds.
fn is_test_loopback(_url: &str) -> bool {
#[cfg(feature = "test_mode")]
{
if let Some(host) = reqwest::Url::parse(_url)
.ok()
.and_then(|url| url.host_str().map(str::to_string))
{
return host == "localhost"
|| host
.trim_start_matches('[')
.trim_end_matches(']')
.parse::<std::net::IpAddr>()
.is_ok_and(|ip| ip.is_loopback());
}
}
false
}
/// inbuxa: a URL a tenant's directory may use: HTTPS, and not an IP literal
/// outside the public range. Host names are checked when they resolve
/// (`utils::public_ip::public_only`).
pub(crate) fn check_tenant_url(field: &str, url: &str) -> Result<(), OidcError> {
let refused = || {
OidcError::Config(format!(
"A tenant's directory must use public HTTPS addresses ({field})"
))
};
let parsed = reqwest::Url::parse(url).map_err(|_| refused())?;
if parsed.scheme() != "https" {
return Err(refused());
}
let host = parsed.host_str().ok_or_else(refused)?;
let host = host
.strip_prefix('[')
.and_then(|host| host.strip_suffix(']'))
.unwrap_or(host);
match host.parse::<std::net::IpAddr>() {
Ok(ip) if !utils::public_ip::is_global_ip(&ip) => Err(refused()),
_ => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -273,3 +341,30 @@ mod tests {
}
}
}
#[cfg(test)]
mod tenant_url_tests {
use super::check_tenant_url;
#[test]
fn tenant_directory_urls() {
for bad in [
"http://idp.example.org",
"https://127.0.0.1/realms/x",
"https://10.0.0.5:8443/",
"https://[::1]/",
"https://[fd12::1]/",
"https://169.254.169.254/",
"not a url",
] {
assert!(check_tenant_url("issuerUrl", bad).is_err(), "{bad}");
}
for ok in [
"https://idp.example.org/realms/x",
"https://8.8.8.8/",
"https://[2606:4700::1111]/",
] {
assert!(check_tenant_url("issuerUrl", ok).is_ok(), "{ok}");
}
}
}
@@ -727,6 +727,7 @@ MCowBQYDK2VwAyEAXNXjqSjw780GFXxFztdFBUMpxRoFqsYWN55FXnvncCE=
claim_groups: None,
default_domain: None,
opaque_tokens,
public_only: false,
},
discovery: crate::backend::oidc::OidcDiscovery {
url: "https://idp.example.org".to_string(),
+3
View File
@@ -25,6 +25,9 @@ pub struct OidcConfig {
pub claim_groups: Option<String>,
pub default_domain: Option<String>,
pub opaque_tokens: OpaqueTokens,
/// inbuxa: a tenant's own directory, which may only reach public HTTPS
/// addresses (see `config::check_tenant_url`).
pub public_only: bool,
}
/// inbuxa: http-directory-services-13: what a bearer token that isn't a
+43 -13
View File
@@ -39,7 +39,9 @@ use inbuxa_features::passkey::{self, Activated, HANDLE_LEN, Passkey};
use jmap::inbuxa::passkey::{allowed_for, settings};
use registry::schema::{enums::Permission, structs::Authentication};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use store::{
InMemoryStore,
dispatch::lookup::KeyValue,
rand::{RngExt, distr::Alphanumeric, rng},
write::now,
@@ -166,6 +168,44 @@ fn challenge_key(id: &str) -> Vec<u8> {
KeyValue::<()>::build_key(KV_PASSKEY_CEREMONY, key)
}
/// Reads a challenge or ceremony and makes sure only one request gets it.
///
/// Reading and then deleting is two steps, so two requests sent together
/// could both read it before either deleted it. Each reader also counts
/// itself on a claim counter for what it read, which every in-memory store
/// increments atomically (Redis, SQL, the key-value stores, sharded or not),
/// and only the first one is handed the value. The counter is named after
/// the value as well as the key: a registration ticket starts a new ceremony
/// under the same key after a failed try, and that one gets its own claim.
/// The counter expires with the challenge, so it needs no cleanup.
async fn take_once(server: &Server, key: Vec<u8>, ttl: u64) -> trc::Result<Option<String>> {
let store = server.in_memory_store();
let Some(value) = store.key_get::<String>(key.clone()).await? else {
return Ok(None);
};
let first = claim_once(store, &key, &value, ttl).await?;
store.key_delete(key).await?;
Ok(first.then_some(value))
}
/// Counts a reader of `value` under `key`; true only for the first one.
/// Public for the race test, which calls it directly: two sign-ins rarely
/// land between a read and a delete over HTTP, but here they all do.
pub async fn claim_once(
store: &InMemoryStore,
key: &[u8],
value: &str,
ttl: u64,
) -> trc::Result<bool> {
let mut claim = key.to_vec();
claim.push(b'!');
claim.extend_from_slice(&Sha256::digest(value.as_bytes())[..16]);
store
.counter_incr(KeyValue::new(claim, 1).expires(ttl), true)
.await
.map(|claims| claims == 1)
}
/// A sign-in challenge between the two requests.
#[derive(Serialize, Deserialize)]
struct SignInCeremony {
@@ -296,14 +336,9 @@ async fn check_assertion(
return Err(refused("Unknown passkey challenge"));
}
let key = challenge_key(&assertion.challenge_id);
let Some(ceremony) = server
.in_memory_store()
.key_get::<String>(key.clone())
.await?
else {
let Some(ceremony) = take_once(server, key, CHALLENGE_SECONDS).await? else {
return Err(refused("Unknown, used or expired passkey challenge"));
};
server.in_memory_store().key_delete(key).await?;
let ceremony = serde_json::from_str::<SignInCeremony>(&ceremony).map_err(|err| {
trc::StoreEvent::DataCorruption
.into_err()
@@ -571,16 +606,11 @@ async fn finish(
ticket: &str,
credential: &RegisterPublicKeyCredential,
) -> trc::Result<RegisterResponse> {
// Good once: read and deleted
// Good once: claimed, then deleted
let key = ceremony_key(ticket);
let Some(ceremony) = server
.in_memory_store()
.key_get::<String>(key.clone())
.await?
else {
let Some(ceremony) = take_once(server, key, CEREMONY_SECONDS).await? else {
return Ok(RegisterResponse::Expired);
};
server.in_memory_store().key_delete(key).await?;
let ceremony = serde_json::from_str::<Ceremony>(&ceremony).map_err(|err| {
trc::StoreEvent::DataCorruption
.into_err()
+1
View File
@@ -17,6 +17,7 @@ pub mod cron;
pub mod glob;
pub mod http;
pub mod map;
pub mod public_ip; // inbuxa
pub mod snowflake;
pub mod template;
pub mod tls;
+124
View File
@@ -0,0 +1,124 @@
/*
* SPDX-FileCopyrightText: 2026 Coffey Labs LLC
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
//! Public addresses, and an HTTP client that connects only to them.
//!
//! Requests to URLs that someone other than the server administrator chose
//! (a push endpoint, a report address, a tenant's provider) must not reach
//! inside the network. A host name is checked when it resolves, so a redirect
//! or a later re-resolution can't get round it. IP literals don't resolve:
//! callers check those with [`is_global_ip`] before sending.
//!
//! Moved here from `common::network` (is_global_ip) and
//! `common::network::public_only` (the resolver) so the directory crate,
//! which `common` depends on, can use them too.
use reqwest::{
ClientBuilder,
dns::{Addrs, Name, Resolve, Resolving},
};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
/// Connect only to public addresses, and never through a proxy (which would
/// resolve the name itself, out of our sight).
pub fn public_only(builder: ClientBuilder) -> ClientBuilder {
builder.no_proxy().dns_resolver(PublicResolver)
}
struct PublicResolver;
impl Resolve for PublicResolver {
fn resolve(&self, name: Name) -> Resolving {
Box::pin(async move {
let addrs = tokio::net::lookup_host((name.as_str(), 0))
.await?
.filter(|addr| is_global_ip(&addr.ip()))
.collect::<Vec<_>>();
if !addrs.is_empty() {
Ok(Box::new(addrs.into_iter()) as Addrs)
} else {
Err(format!("{} has no public address", name.as_str()).into())
}
})
}
}
pub fn is_global_ip(ip: &IpAddr) -> bool {
match ip {
IpAddr::V4(ip) => is_global_ipv4(ip),
IpAddr::V6(ip) => is_global_ipv6(ip),
}
}
fn is_global_ipv4(ip: &Ipv4Addr) -> bool {
let [a, b, c, _] = ip.octets();
let is_this_network = a == 0;
let is_shared = a == 100 && (64..128).contains(&b);
let is_protocol_assignment = a == 192 && b == 0 && c == 0;
let is_benchmarking = a == 198 && (b & 0xfe) == 18;
let is_relay_6to4 = a == 192 && b == 88 && c == 99;
let is_reserved = a >= 240;
!(ip.is_unspecified()
|| ip.is_loopback()
|| ip.is_private()
|| ip.is_link_local()
|| ip.is_multicast()
|| ip.is_broadcast()
|| ip.is_documentation()
|| is_this_network
|| is_shared
|| is_protocol_assignment
|| is_benchmarking
|| is_relay_6to4
|| is_reserved)
}
fn is_global_ipv6(ip: &Ipv6Addr) -> bool {
if ip.is_unspecified() || ip.is_loopback() || ip.is_multicast() {
return false;
}
if let Some(ip) = ip.to_ipv4() {
return is_global_ipv4(&ip);
}
let segments = ip.segments();
if segments[0] == 0x2002 {
return is_global_ipv4(&Ipv4Addr::from(
((segments[1] as u32) << 16) | segments[2] as u32,
));
}
if segments[0] == 0x0064 && segments[1] == 0xff9b {
let is_well_known_prefix =
segments[2] == 0 && segments[3] == 0 && segments[4] == 0 && segments[5] == 0;
return is_well_known_prefix
&& is_global_ipv4(&Ipv4Addr::from(
((segments[6] as u32) << 16) | segments[7] as u32,
));
}
let is_unique_local = (segments[0] & 0xfe00) == 0xfc00;
let is_link_local = (segments[0] & 0xffc0) == 0xfe80;
let is_site_local = (segments[0] & 0xffc0) == 0xfec0;
let is_discard_only =
segments[0] == 0x0100 && segments[1] == 0 && segments[2] == 0 && segments[3] == 0;
let is_documentation = segments[0] == 0x2001 && segments[1] == 0x0db8;
let is_teredo = segments[0] == 0x2001 && segments[1] == 0;
let is_orchid = segments[0] == 0x2001 && (segments[1] & 0xfff0) == 0x0020;
!(is_unique_local
|| is_link_local
|| is_site_local
|| is_discard_only
|| is_documentation
|| is_teredo
|| is_orchid)
}
+43
View File
@@ -269,6 +269,49 @@ pub async fn test(test: &mut TestServer) {
let key = registration(&user).await;
let client_id = sign_in(&user, &key).await;
policy(&admin, &user, &key, &client_id).await;
challenge_race(&key, &client_id).await;
claim_race(&test.server).await;
}
/// H1, without HTTP in the way: many readers of one challenge, all at once,
/// and exactly one may use it. A ticket's next ceremony is a new claim.
pub async fn claim_race(server: &common::Server) {
let store = server.in_memory_store();
let key = b"passkey-claim-race".to_vec();
let claims = (0..64)
.map(|_| http::auth::passkey::claim_once(store, &key, "ceremony-1", 60))
.collect::<Vec<_>>();
let won = futures::future::join_all(claims)
.await
.into_iter()
.filter(|claim| *claim.as_ref().unwrap())
.count();
assert_eq!(
won, 1,
"one challenge, read at once by 64, used {won} times"
);
assert!(
http::auth::passkey::claim_once(store, &key, "ceremony-2", 60)
.await
.unwrap(),
"a new ceremony under the same ticket is its own claim"
);
}
/// PK-10 under load (security batch 11, H1): one challenge sent several
/// times at once signs in once. Each copy is signed with its own, higher
/// counter, so only the challenge being used up can stop the rest.
async fn challenge_race(key: &SoftKey, client_id: &str) {
let challenge = new_challenge().await;
let attempts = (0..6)
.map(|n| login(client_id, key.get(&challenge, 100 + n, ORIGIN)))
.collect::<Vec<_>>();
let responses = futures::future::join_all(attempts).await;
let signed_in = responses
.iter()
.filter(|response| response["type"] == "authenticated")
.count();
assert_eq!(signed_in, 1, "{responses:?}");
}
/// A software authenticator: one P-256 key, user verification always done.
+112
View File
@@ -1297,6 +1297,8 @@ pub async fn test(test: &mut TestServer) {
.assert_destroyed(&[domain]);
}
}
tenant_outbound_requests(&admin, t_id).await;
for tenant in [t_id, u_id, p_id, q_id, d_id] {
admin
.registry_destroy(ObjectType::Tenant, [tenant])
@@ -1306,6 +1308,116 @@ pub async fn test(test: &mut TestServer) {
let _ = u_domain;
}
/// A tenant's own ACME and DNS providers only reach public HTTPS addresses,
/// and names that go into a provider's URL can't move its host (security
/// batch 11, F2 and F3). The server's own providers keep any destination.
async fn tenant_outbound_requests(admin: &Account, tenant: Id) {
use registry::schema::{
enums::{IpProtocol, TsigAlgorithm},
structs::{
AcmeProvider, DnsServer, DnsServerRoute53, DnsServerTsig, SecretKey, SecretKeyValue,
},
};
use registry::types::duration::Duration;
// ACME: an internal or plain-HTTP directory is refused before any request
for directory in [
"https://10.0.0.1/dir",
"https://169.254.169.254/latest/meta-data/",
"http://acme.example.org/dir",
"https://[::1]/dir",
] {
admin
.registry_create_object_expect_err(AcmeProvider {
directory: directory.to_string(),
contact: Map::new(vec!["mailto:[email protected]".to_string()]),
member_tenant_id: Some(tenant),
..Default::default()
})
.await
.assert_type(SetErrorType::InvalidProperties)
.assert_description_contains("public HTTPS");
}
// ... and a host name that resolves to loopback is refused when it resolves
let err = admin
.registry_create_object_expect_err(AcmeProvider {
directory: "https://localhost:1/dir".to_string(),
contact: Map::new(vec!["mailto:[email protected]".to_string()]),
member_tenant_id: Some(tenant),
..Default::default()
})
.await;
err.assert_type(SetErrorType::InvalidProperties);
// The server's own provider isn't held to it: it fails only on the
// connection, and the refused body isn't reflected either way
let err = admin
.registry_create_object_expect_err(AcmeProvider {
directory: "https://127.0.0.1:1/dir".to_string(),
contact: Map::new(vec!["mailto:[email protected]".to_string()]),
..Default::default()
})
.await;
err.assert_type(SetErrorType::InvalidProperties);
assert!(
!err.description
.as_deref()
.unwrap_or_default()
.contains("public HTTPS"),
"server-owned ACME provider: {err:?}"
);
// DNS: RFC 2136 to a private address, and a region that moves the host
let tsig = |host: &str, member_tenant_id: Option<Id>| {
DnsServer::Tsig(DnsServerTsig {
host: host.parse().unwrap(),
port: 53,
key_name: "update-key".to_string(),
key: SecretKey::Value(SecretKeyValue {
secret: "c2VjcmV0".into(),
}),
protocol: IpProtocol::Udp,
tsig_algorithm: TsigAlgorithm::HmacSha256,
description: "tenant outbound test".to_string(),
member_tenant_id,
timeout: Duration::from_millis(1_000),
ttl: Duration::from_millis(60_000),
polling_interval: Duration::from_millis(100),
propagation_timeout: Duration::from_millis(1_000),
propagation_delay: None,
})
};
for host in ["10.0.0.53", "127.0.0.1", "fd00::53"] {
admin
.registry_create_object_expect_err(tsig(host, Some(tenant)))
.await
.assert_type(SetErrorType::InvalidProperties)
.assert_description_contains("public address");
}
let route53 = |region: &str| {
DnsServer::Route53(DnsServerRoute53 {
access_key_id: "AKIDEXAMPLE".to_string(),
secret_access_key: SecretKey::Value(SecretKeyValue {
secret: "secret".into(),
}),
region: region.to_string(),
description: "tenant outbound test".to_string(),
member_tenant_id: Some(tenant),
..Default::default()
})
};
admin
.registry_create_object_expect_err(route53("[email protected]/"))
.await
.assert_type(SetErrorType::InvalidProperties)
.assert_description_contains("region may only contain");
// A private DNS server is a normal setup for the server's own provider
let server_owned = admin.registry_create_object(tsig("10.0.0.53", None)).await;
admin
.registry_destroy(ObjectType::DnsServer, [server_owned])
.await
.assert_destroyed(&[server_owned]);
}
/// Acceptance test 15 (compat): INBUXA's existing tenants, their members and
/// quotas read back unchanged, and each tenant admin sees what it saw before.
///
+2
View File
@@ -44,6 +44,7 @@ pub mod principals;
pub mod prop;
pub mod put_get;
pub mod sync;
pub mod user_content; // inbuxa: uploaded files never run on this origin
#[tokio::test(flavor = "multi_thread")]
pub async fn webdav_tests() {
@@ -189,6 +190,7 @@ pub async fn webdav_tests() {
basic::test(&test).await;
put_get::test(&test).await;
file_tasks::test(&test).await;
user_content::test(&test).await;
mkcol::test(&test).await;
copy_move::test(&test, assisted_discovery).await;
prop::test(&test, assisted_discovery).await;
+88
View File
@@ -0,0 +1,88 @@
/*
* SPDX-FileCopyrightText: 2026 Coffey Labs LLC
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
// inbuxa: a stored file is served on the server's own origin, so an uploaded
// page must never run there. Every file answer carries a sandbox policy, and
// anything that could hold active content downloads instead of displaying.
use crate::utils::server::TestServer;
use hyper::StatusCode;
const BASE: &str = "/dav/file/john%40example.com";
const CSP: &str = "default-src 'none'; frame-ancestors 'none'; sandbox";
pub async fn test(test: &TestServer) {
println!("Running WebDAV user content tests...");
let client = test.account("[email protected]").webdav_client();
for (name, content_type, body, download) in [
("page.html", "text/html", "<script>alert(1)</script>", true),
(
"page.xhtml",
"application/xhtml+xml; charset=utf-8",
"<html/>",
true,
),
(
"pic.svg",
"image/svg+xml",
"<svg xmlns=\"http://www.w3.org/2000/svg\"/>",
true,
),
("doc.pdf", "application/pdf", "%PDF-1.4", true),
("none.bin", "", "x", true),
("note.txt", "text/plain", "hello", false),
("pic.png", "image/png", "png", false),
] {
let path = format!("{BASE}/{name}");
let headers: Vec<(&str, &str)> = if content_type.is_empty() {
vec![]
} else {
vec![("content-type", content_type)]
};
client
.request_with_headers("PUT", &path, headers, body)
.await
.with_status(StatusCode::CREATED);
for method in ["GET", "HEAD"] {
let response = client
.request(method, &path, "")
.await
.with_status(StatusCode::OK)
.with_header("content-security-policy", CSP)
.with_header("x-content-type-options", "nosniff");
assert_eq!(
response
.headers
.get("content-disposition")
.map(String::as_str),
download.then_some("attachment"),
"{method} {name}"
);
}
// A range of the file is the same file
let response = client
.request_with_headers("GET", &path, [("range", "bytes=0-0")], "")
.await
.with_status(StatusCode::PARTIAL_CONTENT)
.with_header("content-security-policy", CSP);
assert_eq!(
response
.headers
.get("content-disposition")
.map(String::as_str),
download.then_some("attachment"),
"range {name}"
);
client
.request("DELETE", &path, "")
.await
.with_status(StatusCode::NO_CONTENT);
}
}