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";
#[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> {
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 {spec} as a component identifier; name a component plainly, \
as \"@path\", or in its serialized form, as '\"@path\";req'."
),
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.",
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.",
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 {}.",
spec_of(item),
if response { "response" } else { "request" },
supported.join(", ")
),
spec_of(item),
));
}
}
}
Ok(())
}
const DEFAULT_PORTS: [(&str, &str); 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) -> Target {
let (scheme, rest) = match raw.find("://") {
Some(at)
if raw[..at]
.chars()
.all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c)) =>
{
(Some(raw[..at].to_ascii_lowercase()), &raw[at + 3..])
}
_ => (None, raw),
};
let (authority, rest) = match scheme {
Some(_) => {
let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
(Some(rest[..end].to_string()), &rest[end..])
}
None => (None, rest),
};
let rest = rest.split('#').next().unwrap_or("");
let (path, query) = match rest.find('?') {
Some(at) => (&rest[..at], &rest[at + 1..]),
None => (rest, ""),
};
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>,
target: Option<Target>,
status: Option<u16>,
request: Option<Box<Message>>,
}
impl Message {
pub fn request(method: &str, url: &str, headers: &BTreeMap<String, String>) -> Self {
Message {
headers: lower_headers(headers),
method: Some(method.to_string()),
target: Some(split_target(url)),
status: None,
request: None,
}
}
pub fn response(
status: u16,
headers: &BTreeMap<String, String>,
request: Option<&Asked>,
) -> Self {
Message {
headers: lower_headers(headers),
method: None,
target: None,
status: Some(status),
request: request.map(|r| Box::new(Message::request(r.method, r.url, &r.headers))),
}
}
}
fn authority(target: &Target, headers: &BTreeMap<String, String>) -> Result<String> {
if let Some(raw) = &target.authority {
let raw = raw.to_ascii_lowercase();
let (host, port) = match raw.rsplit_once(':') {
Some((host, port)) if port.chars().all(|c| c.is_ascii_digit()) => (host, Some(port)),
_ => (raw.as_str(), None),
};
let default = target
.scheme
.as_deref()
.and_then(|s| DEFAULT_PORTS.iter().find(|(name, _)| *name == s))
.map(|(_, port)| *port);
return Ok(match port {
Some(port) if Some(port) != default => format!("{host}:{port}"),
_ => host.to_string(),
});
}
headers
.get("host")
.map(|h| h.to_ascii_lowercase())
.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",
)
})
}
fn missing(item: &Item, why: &str) -> Error {
Error::detailed(
Kind::MissingComponent,
format!("The signature covers {}, {why}", 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 = message.target.as_ref();
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", _) => match message.method.as_deref() {
None => Err(missing(item, "and a response has no method.")),
Some("") => Err(Error::new(
Kind::InvalidArgument,
"The method is empty, so there is no @method to sign or verify; pass the method \
exactly as it goes on the wire.",
)),
Some(method) => Ok(method.to_string()),
},
("@authority", Some(target)) => authority(target, &message.headers),
("@path", Some(target)) => Ok(target.path.clone()),
("@query", Some(target)) => Ok(format!("?{}", target.query)),
_ => message.headers.get(name).cloned().ok_or_else(|| {
missing(
item,
"but the message carries no value for it, so the signature base cannot be built.",
)
}),
}
}
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.",
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.insert(lower.clone(), value.clone()).is_some() {
return Err(Error::detailed(
Kind::InvalidArgument,
format!(
"The headers name the field \"{lower}\" 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."
),
lower,
));
}
}
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()
}
pub(crate) fn lower_headers(headers: &BTreeMap<String, String>) -> BTreeMap<String, String> {
headers
.iter()
.map(|(name, value)| {
(
name.to_ascii_lowercase(),
value.trim_matches([' ', '\t']).to_string(),
)
})
.collect()
}
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_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)?;
base_for(
&components(covered)?,
&Message::request(method, url, &headers),
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)?;
base_for(
&components(covered)?,
&Message::response(status, &headers, request.as_ref()),
true,
params,
)
}