use std::collections::{BTreeMap, HashSet};
use crate::errors::{Error, Kind, Result};
use crate::sfv::{
parse_item, serialize_inner_list, serialize_item, serialize_parameters, InnerList, Item, Value,
};
pub const DERIVED: [&str; 4] = ["@method", "@authority", "@path", "@query"];
pub const RESPONSE_DERIVED: [&str; 1] = ["@status"];
pub const DEFAULT_COVERED: [&str; 4] = ["@method", "@authority", "@path", "@query"];
pub const CONTENT_DIGEST: &str = "content-digest";
const REQ: &str = "req";
const SF_INTEGER_MAX: i64 = 999_999_999_999_999;
const PORT_MAX: u32 = 65535;
pub const MAX_FIELD_BYTES: usize = 8192;
const SHOWN: usize = 64;
pub(crate) fn shown(text: &str) -> String {
let length = text.chars().count();
if length <= SHOWN {
return format!("{text:?}");
}
let head: String = text.chars().take(SHOWN).collect();
format!("{head:?} (cut from {length} characters)")
}
pub(crate) fn brief(text: &str) -> String {
if text.chars().count() <= SHOWN && text.chars().all(|c| (' '..='~').contains(&c)) {
return text.to_string();
}
shown(text)
}
pub(crate) fn is_token(text: &str) -> bool {
!text.is_empty()
&& text
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b))
}
fn is_key(text: &str) -> bool {
let mut bytes = text.bytes();
matches!(bytes.next(), Some(b'a'..=b'z' | b'*'))
&& bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_.*-".contains(&b))
}
fn check_method(method: &str) -> Result<()> {
if is_token(method) {
return Ok(());
}
Err(Error::detailed(
Kind::InvalidArgument,
format!(
"The method {} is not an HTTP method: a method is one or more token characters, with \
no spaces, line breaks or separators.",
shown(method)
),
method,
))
}
pub(crate) fn check_label(label: &str) -> Result<()> {
if is_key(label) {
return Ok(());
}
Err(Error::detailed(
Kind::InvalidArgument,
format!(
"The label {} is not an RFC 8941 key: it starts with a lowercase letter or '*' and \
continues with lowercase letters, digits, '_', '-', '.' and '*'.",
shown(label)
),
label,
))
}
fn check_signer_params(params: &SignatureParams) -> Result<()> {
for (name, value) in [("created", params.created), ("expires", params.expires)] {
if let Some(value) = value.filter(|v| !(0..=SF_INTEGER_MAX).contains(v)) {
return Err(Error::detailed(
Kind::InvalidArgument,
format!(
"{name} is {value}, and RFC 8941 carries an integer of at most fifteen \
digits; fiki signs one from 0 to {SF_INTEGER_MAX}."
),
value.to_string(),
));
}
}
for (name, value) in [
("keyid", ¶ms.keyid),
("alg", ¶ms.alg),
("nonce", ¶ms.nonce),
("tag", ¶ms.tag),
] {
if let Some(value) = value
.as_deref()
.filter(|v| !v.bytes().all(|b| (0x20..=0x7e).contains(&b)))
{
return Err(Error::detailed(
Kind::InvalidArgument,
format!(
"The {name} {} holds a character outside printable ASCII, which an RFC 8941 \
string cannot carry; a line break there would forge a header line.",
shown(value)
),
value,
));
}
}
Ok(())
}
#[derive(Debug, Default, Clone)]
pub struct SignatureParams {
pub created: Option<i64>,
pub keyid: Option<String>,
pub alg: Option<String>,
pub expires: Option<i64>,
pub nonce: Option<String>,
pub tag: Option<String>,
}
#[derive(Debug, Default, Clone)]
pub struct Request {
pub method: String,
pub url: String,
pub headers: BTreeMap<String, String>,
pub body: Option<Vec<u8>>,
}
pub fn req(name: &str) -> String {
serialize_item(&Item {
value: Value::Text(name.to_ascii_lowercase()),
params: vec![(REQ.into(), Value::Boolean(true))],
})
}
pub(crate) fn component(spec: &str) -> Result<Item> {
let item = component_item(spec)?;
match item.text() {
Some(name) if !name.starts_with('@') && !is_token(name) => Err(Error::detailed(
Kind::InvalidArgument,
format!(
"{} is not a component fiki can name: a field is named by an HTTP field name, one \
or more token characters, and a derived component by its @ name.",
shown(spec)
),
spec,
)),
_ => Ok(item),
}
}
fn component_item(spec: &str) -> Result<Item> {
if !spec.starts_with('"') {
return Ok(Item {
value: Value::Text(spec.to_ascii_lowercase()),
params: Vec::new(),
});
}
let mut item = parse_item(spec).map_err(|_| {
Error::detailed(
Kind::UnsupportedComponent,
format!(
"fiki cannot read {} as a component identifier; name a component plainly, as \
\"@path\", or in its serialized form, as '\"@path\";req'.",
brief(spec)
),
spec,
)
})?;
if let Value::Text(name) = &mut item.value {
*name = name.to_ascii_lowercase();
}
Ok(item)
}
pub(crate) fn spec_of(item: &Item) -> String {
match (item.text(), item.params.is_empty()) {
(Some(name), true) => name.to_string(),
_ => serialize_item(item),
}
}
pub(crate) fn identity(item: &Item) -> (String, String) {
let mut params = item.params.clone();
params.sort_by(|a, b| a.0.cmp(&b.0));
(
item.text().unwrap_or_default().to_string(),
serialize_parameters(¶ms),
)
}
fn is_req(item: &Item) -> bool {
item.params
.iter()
.any(|(k, v)| k == REQ && *v == Value::Boolean(true))
}
pub(crate) fn check_covered(items: &[Item], response: bool) -> Result<()> {
let mut seen = HashSet::new();
for item in items {
if !seen.insert(identity(item)) {
return Err(Error::detailed(
Kind::DuplicateComponent,
format!(
"The covered components name {} twice, so the signature base would not be \
what either copy says it is.",
brief(&spec_of(item))
),
spec_of(item),
));
}
}
for item in items {
let req = is_req(item);
let foreign = item.params.iter().any(|(k, _)| k != REQ);
if foreign || (item.params.iter().any(|(k, _)| k == REQ) && !(req && response)) {
return Err(Error::detailed(
Kind::UnsupportedComponent,
format!(
"fiki does not support the component {}: the only component parameter it \
supports is \"{REQ}\", and only in a response.",
brief(&spec_of(item))
),
spec_of(item),
));
}
let name = item.text().unwrap_or_default();
if name.starts_with('@') {
let supported: &[&str] = if req || !response {
&DERIVED
} else {
&RESPONSE_DERIVED
};
if !supported.contains(&name) {
return Err(Error::detailed(
Kind::UnsupportedComponent,
format!(
"fiki does not build the derived component {} in a {}; it builds {}.",
brief(&spec_of(item)),
if response { "response" } else { "request" },
supported.join(", ")
),
spec_of(item),
));
}
}
}
Ok(())
}
const DEFAULT_PORTS: [(&str, u32); 4] = [("http", 80), ("https", 443), ("ws", 80), ("wss", 443)];
pub(crate) struct Target {
pub scheme: Option<String>,
pub authority: Option<String>,
pub path: String,
pub query: String,
}
pub(crate) fn split_target(raw: &str) -> std::result::Result<Target, &'static str> {
const _: () = assert!(MAX_FIELD_BYTES == 8192);
if raw.len() > MAX_FIELD_BYTES {
return Err("it is over 8192 bytes.");
}
if raw.chars().any(|c| c <= ' ' || c == '\x7f') {
return Err("it contains a space or a control character.");
}
if raw.contains('#') {
return Err("it carries a fragment, which no request target has.");
}
let (scheme, authority, rest) = if raw.starts_with('/') {
(None, None, raw)
} else {
let absolute = raw.find("://").filter(|&at| {
let scheme = &raw[..at];
scheme.starts_with(|c: char| c.is_ascii_alphabetic())
&& scheme
.chars()
.all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c))
&& !raw[at + 3..].is_empty()
&& !raw[at + 3..].starts_with(['/', '?'])
});
let Some(at) = absolute else {
return Err(
"it is neither origin-form, beginning with a slash, nor an absolute URI \
with a scheme and an authority.",
);
};
let rest = &raw[at + 3..];
let end = rest.find(['/', '?']).unwrap_or(rest.len());
(
Some(raw[..at].to_ascii_lowercase()),
Some(rest[..end].to_string()),
&rest[end..],
)
};
let (path, query) = rest.split_once('?').unwrap_or((rest, ""));
Ok(Target {
scheme,
authority,
path: if path.is_empty() {
"/".to_string()
} else {
path.to_string()
},
query: query.to_string(),
})
}
pub(crate) struct Message {
headers: BTreeMap<String, String>,
method: Option<String>,
url: String,
target: Option<std::result::Result<Target, &'static str>>,
status: Option<u16>,
request: Option<Box<Message>>,
received: bool,
}
impl Message {
pub fn request(
method: &str,
url: &str,
headers: &BTreeMap<String, String>,
received: bool,
) -> Result<Self> {
check_method(method)?;
Ok(Message {
headers: headers.clone(),
method: Some(method.to_string()),
url: url.to_string(),
target: Some(split_target(url)),
status: None,
request: None,
received,
})
}
pub fn response(
status: u16,
headers: &BTreeMap<String, String>,
request: Option<&Asked>,
received: bool,
) -> Result<Self> {
Ok(Message {
headers: headers.clone(),
method: None,
url: String::new(),
target: None,
status: Some(status),
request: request
.map(|r| Message::request(r.method, r.url, &r.headers, received).map(Box::new))
.transpose()?,
received,
})
}
fn unreadable(&self, reason: &str) -> Error {
if self.received {
return Error::detailed(
Kind::SignatureMismatch,
format!(
"The URL {} cannot be read: {reason} So there is no signature base to check \
the signature against.",
shown(&self.url)
),
shown(&self.url),
);
}
Error::detailed(
Kind::InvalidArgument,
format!("The URL {} cannot be read: {reason}", shown(&self.url)),
shown(&self.url),
)
}
}
fn port(text: &str, message: &Message) -> Result<Option<u32>> {
if text.is_empty() {
return Ok(None);
}
let significant = text.trim_start_matches('0');
if text.bytes().all(|b| b.is_ascii_digit()) && significant.len() <= 5 {
let number = significant.parse::<u32>().unwrap_or(0);
if number <= PORT_MAX {
return Ok(Some(number));
}
}
Err(message.unreadable(&format!(
"its port {} is not a number from 0 to {PORT_MAX}.",
shown(text)
)))
}
fn ip_literal(inside: &str) -> bool {
if let Some(future) = inside.strip_prefix('v') {
return future.split_once('.').is_some_and(|(version, rest)| {
!version.is_empty()
&& version.bytes().all(|b| b.is_ascii_hexdigit())
&& !rest.is_empty()
&& !rest.contains('\n')
});
}
let address = match inside.split_once('%') {
Some((address, zone)) if !zone.is_empty() && !zone.contains('%') => address,
Some(_) => return false,
None => inside,
};
match address.split_once("::") {
Some((head, tail)) => match (groups(head, false), groups(tail, true)) {
(Some(head), Some(tail)) => head + tail <= 7,
_ => false,
},
None => groups(address, true) == Some(8),
}
}
fn groups(run: &str, ends_address: bool) -> Option<usize> {
if run.is_empty() {
return Some(0);
}
let pieces: Vec<&str> = run.split(':').collect();
let mut count = 0;
for (i, piece) in pieces.iter().enumerate() {
if ends_address && i == pieces.len() - 1 && piece.contains('.') {
if !ipv4(piece) {
return None;
}
count += 2;
} else if (1..=4).contains(&piece.len()) && piece.bytes().all(|b| b.is_ascii_hexdigit()) {
count += 1;
} else {
return None;
}
}
Some(count)
}
fn ipv4(text: &str) -> bool {
let octets: Vec<&str> = text.split('.').collect();
octets.len() == 4
&& octets.iter().all(|octet| {
(1..=3).contains(&octet.len())
&& octet.bytes().all(|b| b.is_ascii_digit())
&& !(octet.len() > 1 && octet.starts_with('0'))
&& octet.parse::<u16>().is_ok_and(|n| n <= 255)
})
}
fn authority(target: &Target, message: &Message) -> Result<String> {
if let Some(raw) = &target.authority {
if raw.contains('@') {
return Err(message.unreadable("its authority carries user information."));
}
return host_and_port(raw, target.scheme.as_deref(), message);
}
let host = message.headers.get("host").ok_or_else(|| {
Error::detailed(
Kind::MissingComponent,
"The signature covers \"@authority\", but the URL carries no authority and the \
request has no Host header, so there is nothing to derive it from.",
"@authority",
)
})?;
if host.len() > MAX_FIELD_BYTES {
return Err(
message.unreadable(&format!("its Host header is over {MAX_FIELD_BYTES} bytes."))
);
}
let host = ows_trimmed(host);
if host.contains(['@', ',']) {
return Err(message.unreadable("its Host header is not a single host and optional port."));
}
host_and_port(host, None, message)
}
fn host_and_port(hostport: &str, scheme: Option<&str>, message: &Message) -> Result<String> {
let (host, port_text) = match hostport.strip_prefix('[') {
Some(literal) => {
let Some((inside, rest)) = literal.split_once(']') else {
return Err(message.unreadable("its IP-literal has no closing ']'."));
};
let Some(port_text) = rest.strip_prefix(':').or((rest.is_empty()).then_some("")) else {
return Err(message
.unreadable("something other than a port follows the ']' of its IP-literal."));
};
if !ip_literal(inside) {
return Err(
message.unreadable("its IP-literal is not an IPv6 address or IPvFuture.")
);
}
(format!("[{inside}]"), port_text)
}
None if hostport.contains(['[', ']']) => {
return Err(message.unreadable("it has a ']' with no IP-literal to close."));
}
None => {
let (host, port_text) = hostport.split_once(':').unwrap_or((hostport, ""));
(host.to_string(), port_text)
}
};
let host = host.to_ascii_lowercase();
let port = port(port_text, message)?;
let default = scheme
.and_then(|s| DEFAULT_PORTS.iter().find(|(name, _)| *name == s))
.map(|(_, port)| *port);
Ok(match port {
Some(port) if Some(port) != default => format!("{host}:{port}"),
_ => host,
})
}
fn missing(item: &Item, why: &str) -> Error {
Error::detailed(
Kind::MissingComponent,
format!("The signature covers {}, {why}", brief(&spec_of(item))),
spec_of(item),
)
}
fn component_value(item: &Item, message: &Message) -> Result<String> {
let mut message = message;
if is_req(item) {
message = message.request.as_deref().ok_or_else(|| {
missing(
item,
"which is read from the request this response answers, and no request was \
supplied.",
)
})?;
}
let name = item.text().unwrap_or_default();
let target = match (name, message.target.as_ref()) {
("@authority" | "@path" | "@query", Some(Err(reason))) => {
return Err(message.unreadable(reason))
}
(_, target) => target.and_then(|t| t.as_ref().ok()),
};
match (name, target) {
("@status", _) => match message.status {
Some(status @ 100..=999) => Ok(status.to_string()),
other => Err(Error::detailed(
Kind::MissingComponent,
format!(
"The signature covers @status, and {} is not a three-digit HTTP status \
code, so there is no status line to build.",
other.map_or("a request".to_string(), |s| s.to_string())
),
"@status",
)),
},
("@method", _) => message
.method
.clone()
.ok_or_else(|| missing(item, "and a response has no method.")),
("@authority", Some(target)) => authority(target, message),
("@path", Some(target)) => Ok(target.path.clone()),
("@query", Some(target)) => Ok(format!("?{}", target.query)),
_ => {
let raw = message.headers.get(name).ok_or_else(|| {
missing(
item,
"but the message carries no value for it, so the signature base cannot be \
built.",
)
})?;
if name != CONTENT_DIGEST && raw.len() > MAX_FIELD_BYTES {
return Err(Error::detailed(
Kind::SignatureMismatch,
format!(
"The value of {} is over {MAX_FIELD_BYTES} bytes, so no signature base is \
built from it.",
brief(&spec_of(item))
),
spec_of(item),
));
}
Ok(ows_trimmed(raw).to_string())
}
}
}
pub(crate) fn value_of(item: &Item, message: &Message) -> Result<String> {
let value = component_value(item, message)?;
if value
.chars()
.any(|c| !(c == '\t' || (' '..='~').contains(&c)))
{
return Err(Error::detailed(
Kind::SignatureMismatch,
format!(
"The value of {} contains a line break, a control character or a non-ASCII \
character, so there is no signature base both sides would build from it.",
brief(&spec_of(item))
),
spec_of(item),
));
}
Ok(value)
}
pub(crate) fn canonical(headers: &BTreeMap<String, String>) -> Result<BTreeMap<String, String>> {
let mut out = BTreeMap::new();
for (name, value) in headers {
let lower = name.to_ascii_lowercase();
if out.contains_key(&lower) {
return Err(Error::detailed(
Kind::InvalidArgument,
format!(
"The headers name the field {} more than once in different case, so it has \
two values and fiki cannot know which one was meant; combine them into one \
entry before signing or verifying.",
shown(&lower)
),
lower,
));
}
out.insert(lower, value.clone());
}
Ok(out)
}
pub(crate) struct Asked<'a> {
pub method: &'a str,
pub url: &'a str,
pub headers: BTreeMap<String, String>,
pub body: Option<&'a [u8]>,
}
pub(crate) fn canonical_request(request: Option<&Request>) -> Result<Option<Asked<'_>>> {
request
.map(|r| {
Ok(Asked {
method: &r.method,
url: &r.url,
headers: canonical(&r.headers)?,
body: r.body.as_deref(),
})
})
.transpose()
}
fn ows_trimmed(value: &str) -> &str {
value.trim_matches([' ', '\t'])
}
pub(crate) fn lines_for(items: &[Item], message: &Message) -> Result<Vec<String>> {
items
.iter()
.map(|item| {
Ok(format!(
"{}: {}",
serialize_item(item),
value_of(item, message)?
))
})
.collect()
}
pub(crate) fn finish(mut lines: Vec<String>, items: &[Item], params: &SignatureParams) -> Vec<u8> {
let mut list = InnerList {
items: items.to_vec(),
params: Vec::new(),
};
let text = |s: &Option<String>| s.clone().map(Value::Text);
for (name, value) in [
("created", params.created.map(Value::Integer)),
("expires", params.expires.map(Value::Integer)),
("nonce", text(¶ms.nonce)),
("alg", text(¶ms.alg)),
("keyid", text(¶ms.keyid)),
("tag", text(¶ms.tag)),
] {
if let Some(value) = value {
list.params.push((name.into(), value));
}
}
lines.push(format!(
"\"@signature-params\": {}",
serialize_inner_list(&list)
));
lines.join("\n").into_bytes()
}
pub(crate) fn components(covered: &[String]) -> Result<Vec<Item>> {
covered.iter().map(|spec| component(spec)).collect()
}
pub(crate) fn base_for(
items: &[Item],
message: &Message,
response: bool,
params: &SignatureParams,
) -> Result<Vec<u8>> {
check_signer_params(params)?;
check_covered(items, response)?;
Ok(finish(lines_for(items, message)?, items, params))
}
pub fn signature_base(
method: &str,
url: &str,
headers: &BTreeMap<String, String>,
covered: &[String],
params: &SignatureParams,
) -> Result<Vec<u8>> {
let headers = canonical(headers)?;
let message = Message::request(method, url, &headers, false)?;
base_for(&components(covered)?, &message, false, params)
}
pub fn response_signature_base(
status: u16,
headers: &BTreeMap<String, String>,
request: Option<&Request>,
covered: &[String],
params: &SignatureParams,
) -> Result<Vec<u8>> {
let headers = canonical(headers)?;
let request = canonical_request(request)?;
let message = Message::response(status, &headers, request.as_ref(), false)?;
base_for(&components(covered)?, &message, true, params)
}