1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
mod custom_signer;
mod signer_v1;
use indexmap::IndexMap;
use std::fmt;
use crate::{base64::ToUrlSafeBase64, common::Unset, http::HeaderName, openssl, Error, Method};
pub use self::custom_signer::CustomSigner;
use self::signer_v1::SignerV1;
/// Builder to generate a `Tl-Signature` header value.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), truelayer_signing::Error> {
/// # let (kid, private_key, idempotency_key, body) = unimplemented!();
/// let tl_signature = truelayer_signing::SignerBuilder::build_with_pem(kid, private_key)
/// .method(truelayer_signing::Method::Post)
/// .path("/payouts")
/// .header("Idempotency-Key", idempotency_key)
/// .body(body)
/// .build_signer()
/// .sign()?;
/// # Ok(()) }
/// ```
#[derive(Default)]
pub struct SignerBuilder<'a, Kid, Pk, Body, Method, Path> {
kid: Kid,
private_key: Pk,
body: Body,
method: Method,
path: Path,
headers: IndexMap<HeaderName<'a>, &'a [u8]>,
jws_jku: Option<&'a str>,
}
impl<Kid, Pk, Body, Method, Path> fmt::Debug for SignerBuilder<'_, Kid, Pk, Body, Method, Path> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Signer")
}
}
impl<'a> SignerBuilder<'a, Unset, Unset, Unset, Unset, Unset> {
pub fn new() -> Self {
SignerBuilder {
kid: Unset,
private_key: Unset,
body: Unset,
method: Unset,
path: Unset,
headers: <_>::default(),
jws_jku: <_>::default(),
}
}
}
impl<'a> SignerBuilder<'a, &'a str, &'a [u8], Unset, Unset, Unset> {
pub fn build_with_pem(kid: &'a str, private_key: &'a [u8]) -> Self {
SignerBuilder {
kid,
private_key,
body: Unset,
method: Unset,
path: Unset,
headers: <_>::default(),
jws_jku: <_>::default(),
}
}
}
impl<'a, Pk, Body, Method, Path> SignerBuilder<'a, Unset, Pk, Body, Method, Path> {
/// Add the private key kid.
pub fn kid(self, kid: &str) -> SignerBuilder<'a, &str, Pk, Body, Method, Path> {
SignerBuilder {
kid,
private_key: self.private_key,
body: self.body,
method: self.method,
path: self.path,
headers: self.headers,
jws_jku: self.jws_jku,
}
}
}
impl<'a, K, Body, Method, Path> SignerBuilder<'a, K, Unset, Body, Method, Path> {
/// Add the private key.
pub fn private_key(
self,
private_key: &[u8],
) -> SignerBuilder<'a, K, &[u8], Body, Method, Path> {
SignerBuilder {
kid: self.kid,
private_key,
body: self.body,
method: self.method,
path: self.path,
headers: self.headers,
jws_jku: self.jws_jku,
}
}
}
impl<'a, K, Pk, Method, Path> SignerBuilder<'a, K, Pk, Unset, Method, Path> {
/// Add the full request body.
///
/// Note: This **must** be identical to what is sent with the request.
pub fn body(self, body: &[u8]) -> SignerBuilder<'a, K, Pk, &[u8], Method, Path> {
SignerBuilder {
kid: self.kid,
private_key: self.private_key,
body,
method: self.method,
path: self.path,
headers: self.headers,
jws_jku: self.jws_jku,
}
}
}
impl<'a, K, Pk, Body, Path> SignerBuilder<'a, K, Pk, Body, Unset, Path> {
/// Add the request method.
pub fn method(self, method: Method) -> SignerBuilder<'a, K, Pk, Body, Method, Path> {
SignerBuilder {
kid: self.kid,
private_key: self.private_key,
body: self.body,
method,
path: self.path,
headers: self.headers,
jws_jku: self.jws_jku,
}
}
}
impl<'a, K, Pk, Body, Method> SignerBuilder<'a, K, Pk, Body, Method, Unset> {
/// Add the request absolute path starting with a leading `/` and without
/// any trailing slashes.
pub fn path(self, path: &str) -> SignerBuilder<'a, K, Pk, Body, Method, &str> {
assert!(
path.starts_with('/'),
"Invalid path \"{path}\" must start with '/'"
);
SignerBuilder {
kid: self.kid,
private_key: self.private_key,
body: self.body,
method: self.method,
path,
headers: self.headers,
jws_jku: self.jws_jku,
}
}
}
impl<'a, K, Pk, Body, Method, Path> SignerBuilder<'a, K, Pk, Body, Method, Path> {
/// Add a header name & value.
/// May be called multiple times to add multiple different headers.
///
/// Warning: Only a single value per header name is supported.
pub fn header(mut self, key: &'a str, value: &'a [u8]) -> Self {
self.headers.insert(HeaderName(key), value);
self
}
/// Appends multiple header names & values.
///
/// Warning: Only a single value per header name is supported.
pub fn headers(mut self, headers: impl IntoIterator<Item = (&'a str, &'a [u8])>) -> Self {
self.headers
.extend(headers.into_iter().map(|(k, v)| (HeaderName(k), v)));
self
}
/// Sets the jws header `jku` JSON Web Key URL.
///
/// Note: This is not generally required when calling APIs,
/// but is set on webhook signatures.
pub fn jku(mut self, jku: &'a str) -> Self {
self.jws_jku = Some(jku);
self
}
}
impl<'a> SignerBuilder<'a, &'a str, Unset, &'a [u8], Method, &'a str> {
/// Builds a [`CustomSigner`]
///
/// requires the kid, body, method, and path to be set to call this function.
/// if the private key is set this function will not be available.
pub fn build_custom_signer(self) -> CustomSigner<'a> {
CustomSigner {
kid: self.kid,
body: self.body,
method: self.method.name(),
path: self.path,
headers: self.headers,
jws_jku: self.jws_jku,
}
}
}
impl<'a> SignerBuilder<'a, &'a str, &'a [u8], &'a [u8], Unset, Unset> {
/// Build a V1 Signer see [`SignerV1`].
///
/// requires the private key, kid, and body to be set to call this function.
/// if the method of path is set this function will not be available.
///
/// In general full request signing should be preferred, see [`Signer`].
pub fn build_v1_signer(self) -> SignerV1<'a> {
SignerV1 {
private_key: self.private_key,
kid: self.kid,
body: self.body,
jws_jku: self.jws_jku,
}
}
}
impl<'a> SignerBuilder<'a, &'a str, &'a [u8], &'a [u8], Method, &'a str> {
/// Build a V2 Signer see [`Signer`].
///
/// requires the private key, kid, body, method, and path to be set to call this function.
pub fn build_signer(self) -> Signer<'a> {
Signer {
private_key: self.private_key,
base: CustomSigner {
kid: self.kid,
body: self.body,
method: self.method.name(),
path: self.path,
headers: self.headers,
jws_jku: self.jws_jku,
},
}
}
}
/// Signer to generate a `Tl-Signature` header value using a private key.
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), truelayer_signing::Error> {
/// # let (kid, private_key, idempotency_key, body) = unimplemented!();
/// let tl_signature = truelayer_signing::SignerBuilder::build_with_pem(kid, private_key)
/// .method(truelayer_signing::Method::Post)
/// .path("/payouts")
/// .header("Idempotency-Key", idempotency_key)
/// .body(body)
/// .build_signer()
/// .sign()?;
/// # Ok(()) }
/// ```
pub struct Signer<'a> {
base: CustomSigner<'a>,
private_key: &'a [u8],
}
/// Debug does not display key info.
impl fmt::Debug for Signer<'_> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Signer")
}
}
impl<'a> Signer<'a> {
/// Produce a JWS `Tl-Signature` v2 header value.
pub fn sign(self) -> Result<String, Error> {
let private_key =
openssl::parse_ec_private_key(self.private_key).map_err(Error::InvalidKey)?;
self.base.sign_with(|bytes| {
openssl::sign_es512(&private_key, bytes)
.map(|sig| sig.to_url_safe_base64())
.map_err(Error::JwsError)
})
}
}
/// Build a v2 signing payload.
///
/// # Example
/// ```txt
/// POST /test-signature
/// Idempotency-Key: 619410b3-b00c-406e-bb1b-2982f97edb8b
/// {"bar":123}
/// ```
pub(crate) fn build_v2_signing_payload(
method: &str,
path: &str,
headers: &IndexMap<HeaderName<'_>, &[u8]>,
body: &[u8],
add_path_trailing_slash: bool,
) -> Vec<u8> {
let mut payload = Vec::new();
payload.extend(method.as_bytes());
payload.push(b' ');
payload.extend(path.as_bytes());
if add_path_trailing_slash {
payload.push(b'/');
}
payload.push(b'\n');
for (h_name, h_val) in headers {
payload.extend(h_name.0.as_bytes());
payload.extend(b": ");
payload.extend(*h_val);
payload.push(b'\n');
}
payload.extend(body);
payload
}