Skip to content
This repository was archived by the owner on Feb 9, 2026. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
533 changes: 329 additions & 204 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
[toolchain]
channel = "1.78.0"
channel = "1.83.0"
components = ["rust-analyzer"]
profile = "default"
13 changes: 9 additions & 4 deletions sutera-lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@ version = "0.1.0"
edition = "2021"

[dev-dependencies]
assert_matches = "1.5.0"
concat-idents = "1.1.5"
pretty_assertions = "1.4.0"
serde_json = "1.0.117"
tracing-subscriber = "0.3.19"

[dependencies]
rand_core = { version = "0.6.4", features = ["std"] }
ring-compat = "0.8.0"
ed25519-dalek = { version = "2.1.1", features = ["rand_core"] }
rand = { version = "0.8.4", features = ["std_rng"] }
rand_core = "0.6.4"
serde = { version = "1.0.203", features = ["derive"] }
strum = { version = "0.26.2", features = ["derive"] }
serde_json_canonicalizer = "0.3.0"
thiserror = "1.0.61"
tracing = "0.1.41"
tracing-error = { version = "0.2.1", features = ["traced-error"] }
91 changes: 91 additions & 0 deletions sutera-lib/src/error/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
use std::fmt::{Debug, Display};

use tracing_error::SpanTrace;

pub trait TraceableError: std::error::Error {
fn trace(&self) -> &SpanTrace;
}

pub struct CapturedError<E: std::error::Error> {
pub error: E,
span_trace: SpanTrace,
}

impl<E: std::error::Error> TraceableError for CapturedError<E> {
fn trace(&self) -> &SpanTrace {
&self.span_trace
}
}

pub trait ResultTracingUnwrapExt<T, E: TraceableError> {
fn tracing_unwrap(self) -> T;
}
pub trait ResultCaptureErrExt<T, U: std::error::Error> {
fn capture_err(self) -> Result<T, CapturedError<U>>;
fn capture_and_unwrap(self) -> T;
}

impl<T, E: TraceableError> ResultTracingUnwrapExt<T, E> for Result<T, E> {
#[inline(always)]
fn tracing_unwrap(self) -> T {
match self {
Ok(value) => value,
Err(ref error) => {
tracing::error!(error = %error, "called `unwrap()` on an `Err` Value");
eprintln!("== TRACING ==");
eprintln!("{}", error.trace());
self.unwrap();
unreachable!()
}
}
}
}

impl<T, U: std::error::Error> ResultCaptureErrExt<T, U> for Result<T, U> {
#[inline(always)]
fn capture_err(self) -> Result<T, CapturedError<U>> {
self.map_err(|error| CapturedError {
error,
span_trace: SpanTrace::capture(),
})
}
#[inline(always)]
fn capture_and_unwrap(self) -> T {
self.capture_err().tracing_unwrap()
}
}

impl<E: std::error::Error> Display for CapturedError<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
<E as Display>::fmt(&self.error, f)
}
}

impl<E: std::error::Error + Debug> Debug for CapturedError<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
<E as Debug>::fmt(&self.error, f)
}
}

impl<E: std::error::Error + PartialEq> PartialEq for CapturedError<E> {
fn eq(&self, other: &Self) -> bool {
self.error == other.error
}
}

impl<E: std::error::Error + Eq> Eq for CapturedError<E> {}

impl<E: std::error::Error> std::error::Error for CapturedError<E> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.error.source()
}
}

impl<E: std::error::Error> From<E> for CapturedError<E> {
fn from(error: E) -> Self {
Self {
error,
span_trace: SpanTrace::capture(),
}
}
}
2 changes: 2 additions & 0 deletions sutera-lib/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
pub mod error;
pub mod signature;
pub mod util;
94 changes: 94 additions & 0 deletions sutera-lib/src/signature/algorithms/ed25519.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
use std::str::FromStr;

use crate::error::ResultCaptureErrExt;
use crate::signature::SuteraPrivateKey;
use crate::util::hex::{from_hex, to_hex, FromHexError, HexString};

use super::{SigningAlgorithm, SigningAlgorithmKind};
use ed25519_dalek::ed25519::signature::SignerMut;
use ed25519_dalek::{Signature, SigningKey, VerifyingKey, PUBLIC_KEY_LENGTH, SECRET_KEY_LENGTH};
use rand_core::CryptoRngCore;
use thiserror::Error;
use tracing::instrument;

pub struct Ed25519 {}

#[derive(Debug, Error)]
enum DecodeKeyError {
#[error("unable to decode hex: {0}")]
UnableToDecodeHex(#[from] FromHexError),
#[error("invalid key length: {actual} bytes, expected {expected}")]
KeyLengthMismatch { actual: usize, expected: usize },
#[error(transparent)]
SignatureError(#[from] ed25519_dalek::SignatureError),
}

#[instrument("parse_verifying_key")]
fn parse_verifying_key(value: &str) -> Result<VerifyingKey, DecodeKeyError> {
let bytes = from_hex(value)?;
if bytes.len() != PUBLIC_KEY_LENGTH {
return Err(DecodeKeyError::KeyLengthMismatch {
actual: bytes.len(),
expected: PUBLIC_KEY_LENGTH,
});
}
Ok(VerifyingKey::from_bytes(
&<[u8; PUBLIC_KEY_LENGTH]>::try_from(bytes).unwrap(),
)?)
}

#[instrument("parse_signing_key")]
fn parse_signing_key<T: HexString + ?Sized>(value: &T) -> Result<SigningKey, DecodeKeyError> {
let bytes = from_hex(value)?;
if bytes.len() != SECRET_KEY_LENGTH {
return Err(DecodeKeyError::KeyLengthMismatch {
actual: bytes.len(),
expected: SECRET_KEY_LENGTH,
});
}
Ok(SigningKey::from_bytes(
&<[u8; SECRET_KEY_LENGTH]>::try_from(bytes).unwrap(),
))
}

impl SigningAlgorithm for Ed25519 {
fn is_capable(kind: &SigningAlgorithmKind) -> bool {
kind.0 == "ed25519"
}

#[instrument("sign", skip_all)]
fn sign(data: &[u8], private_key: &SuteraPrivateKey) -> Result<String, super::SignatureError> {
let mut private_key = parse_signing_key(&private_key.key)
.map_err(|e| super::SignatureError::PrivateKey(Box::new(e)))?;
Ok(private_key.try_sign(data).capture_and_unwrap().to_string())
}

#[instrument("to_public_key", skip_all)]
fn to_public_key(private_key: &SuteraPrivateKey) -> Result<String, super::SignatureError> {
let private_key = parse_signing_key(&private_key.key)
.map_err(|e| super::SignatureError::PrivateKey(Box::new(e)))?;
Ok(to_hex(&private_key.verifying_key().to_bytes()))
}

#[instrument("generate_private_key", skip_all)]
fn generate_private_key<R: CryptoRngCore + ?Sized>(rng: &mut R) -> SuteraPrivateKey {
let private_key = SigningKey::generate(rng);
SuteraPrivateKey {
key: to_hex(&private_key.to_bytes()).into(),
algorithm: SigningAlgorithmKind("ed25519".into()),
}
}

#[instrument("verify", skip_all)]
fn verify(
data: &[u8],
signature: &str,
public_key: &str,
) -> Result<bool, super::SignatureError> {
let public_key = parse_verifying_key(public_key)
.map_err(|e| super::SignatureError::PublicKey(Box::new(e)))?;
let signature = Signature::from_str(signature)
.map_err(|e| super::SignatureError::Signature(Box::new(e)))?;
Ok(public_key.verify_strict(data, &signature).is_ok())
}
}
26 changes: 26 additions & 0 deletions sutera-lib/src/signature/algorithms/macros.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
macro_rules! algorithm_action {
($kind:expr => $e:expr) => {
if $crate::signature::algorithms::ed25519::Ed25519::is_capable($kind) {
type Algorithm = $crate::signature::algorithms::ed25519::Ed25519;
Some($e)
} else {
None
}
};
}
pub(crate) use algorithm_action;

#[cfg(test)]
macro_rules! algorithm_tests {
($(#[$attr:meta])* fn $name:ident $args:tt $b:block) => {
::concat_idents::concat_idents!(test_name = $name, _ed25519 {
$(#[$attr])*
fn test_name $args {
type Algorithm = $crate::signature::algorithms::ed25519::Ed25519;
$b
}
});
};
}
#[cfg(test)]
pub(crate) use algorithm_tests;
54 changes: 54 additions & 0 deletions sutera-lib/src/signature/algorithms/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
pub mod ed25519;
mod macros;

#[cfg(test)]
mod tests;

use rand_core::CryptoRngCore;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use self::macros::algorithm_action;

use super::{Signature, SuteraIdentity, SuteraPrivateKey};

#[derive(Error, Debug)]
pub enum SignatureError {
#[error("Algorithm not supported: {0:?}")]
AlgorithmNotSupported(SigningAlgorithmKind),
#[error("Invalid signature: {0}")]
Signature(Box<dyn std::error::Error>),
#[error("Invalid public key: {0}")]
PublicKey(Box<dyn std::error::Error>),
#[error("Invalid private key: {0}")]
PrivateKey(Box<dyn std::error::Error>),
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct SigningAlgorithmKind(String);

#[allow(dead_code)]
pub trait SigningAlgorithm {
fn is_capable(kind: &SigningAlgorithmKind) -> bool;
fn sign(data: &[u8], private_key: &SuteraPrivateKey) -> Result<String, SignatureError>;
fn to_public_key(private_key: &SuteraPrivateKey) -> Result<String, SignatureError>;
fn verify(data: &[u8], signature: &str, public_key: &str) -> Result<bool, SignatureError>;
fn generate_private_key<R: CryptoRngCore + ?Sized>(rng: &mut R) -> SuteraPrivateKey;
}

impl SuteraIdentity {
pub fn verify(&self, data: &[u8], signature: &str) -> Result<bool, SignatureError> {
algorithm_action!(&self.algorithm => {
Algorithm::verify(data, signature, &self.public_key)
})
.ok_or(SignatureError::AlgorithmNotSupported(
self.algorithm.clone(),
))?
}
}

impl Signature {
pub fn verify(&self, data: &[u8]) -> Result<bool, SignatureError> {
self.identity.verify(data, &self.signature)
}
}
55 changes: 55 additions & 0 deletions sutera-lib/src/signature/algorithms/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use crate::signature::algorithms::SigningAlgorithm as _;

use super::macros::algorithm_tests;
use assert_matches::assert_matches;
use rand::rngs::StdRng;
use rand::SeedableRng;

algorithm_tests! {
#[test]
fn verify_correct_sign() {
let mut rng = StdRng::seed_from_u64(0);
let private_key = Algorithm::generate_private_key(&mut rng);
let public_key = Algorithm::to_public_key(&private_key).unwrap();
let data = b"hello, world!";
let signature = Algorithm::sign(data, &private_key).unwrap();
assert_matches!(Algorithm::verify(data, &signature, &public_key), Ok(true));
}
}

algorithm_tests! {
#[test]
fn verify_unmatched_content() {
let mut rng = StdRng::seed_from_u64(0);
let private_key = Algorithm::generate_private_key(&mut rng);
let public_key = Algorithm::to_public_key(&private_key).unwrap();
let data = b"hello, world!";
let signature = Algorithm::sign(data, &private_key).unwrap();
assert_matches!(Algorithm::verify(b"broken content", &signature, &public_key), Ok(false));
}
}

algorithm_tests! {
#[test]
fn verify_unmatched_signature() {
let mut rng = StdRng::seed_from_u64(0);
let private_key = Algorithm::generate_private_key(&mut rng);
let public_key = Algorithm::to_public_key(&private_key).unwrap();
let data = b"hello, world!";
let fake_data = b"original!";
let signature = Algorithm::sign(fake_data, &private_key).unwrap();
assert_matches!(Algorithm::verify(data, &signature, &public_key), Ok(false));
}
}

algorithm_tests! {
#[test]
fn verify_unmatched_public_key() {
let mut rng = StdRng::seed_from_u64(0);
let private_key = Algorithm::generate_private_key(&mut rng);
let data = b"hello, world!";
let signature = Algorithm::sign(data, &private_key).unwrap();
let fake_public_key = Algorithm::to_public_key(&Algorithm::generate_private_key(&mut rng)).unwrap();
assert_matches!(Algorithm::verify(data, &signature, &fake_public_key), Ok(false));
}
}
Loading