Skip to content

Commit 48296d4

Browse files
avoid panic (#54)
1 parent 6588368 commit 48296d4

12 files changed

Lines changed: 90 additions & 45 deletions

File tree

benches/public.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ pub fn criterion_public_benchmark(c: &mut Criterion) {
167167
.unwrap();
168168
origin_key_store
169169
.insert(
170-
public_key_to_truncated_token_key_id(&public_key),
170+
public_key_to_truncated_token_key_id(&public_key).unwrap(),
171171
public_key.clone(),
172172
)
173173
.await;

src/auth/authenticate.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ impl TokenChallenge {
7777
if self.redemption_context.is_empty() {
7878
None
7979
} else {
80-
Some(self.redemption_context.as_slice().try_into().unwrap())
80+
self.redemption_context.as_slice().try_into().ok()
8181
}
8282
}
8383

src/common/errors.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,13 @@ pub enum CreateKeypairError {
3838
#[source]
3939
source: BlindRsaError,
4040
},
41+
#[error("Key serialization failed")]
42+
/// Error when serializing the public key fails.
43+
KeySerializationFailed {
44+
/// Underlying RSA error that triggered the failure.
45+
#[source]
46+
source: BlindRsaError,
47+
},
4148
#[error("Collision exhausted")]
4249
/// Error when collision attempts are exhausted
4350
CollisionExhausted,

src/common/private.rs

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,23 +16,19 @@ pub trait PrivateCipherSuite:
1616
+ Sync
1717
{
1818
/// Returns the token type for the cipher suite.
19+
fn token_type() -> TokenType;
20+
}
21+
22+
impl PrivateCipherSuite for p384::NistP384 {
1923
fn token_type() -> TokenType {
20-
match Self::ID {
21-
"P384-SHA384" => TokenType::PrivateP384,
22-
"ristretto255-SHA512" => TokenType::PrivateRistretto255,
23-
_ => panic!("Unsupported token type"),
24-
}
24+
TokenType::PrivateP384
2525
}
2626
}
2727

28-
impl<C> PrivateCipherSuite for C where
29-
C: CipherSuite<Group: Group<Elem: Send + Sync, Scalar: Send + Sync>>
30-
+ PartialEq
31-
+ Debug
32-
+ Clone
33-
+ Send
34-
+ Sync
35-
{
28+
impl PrivateCipherSuite for voprf::Ristretto255 {
29+
fn token_type() -> TokenType {
30+
TokenType::PrivateRistretto255
31+
}
3632
}
3733

3834
/// Public key alias

src/generic_tokens/response.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,8 +131,12 @@ impl GenericBatchTokenResponse {
131131
) => response
132132
.issue_token(state)
133133
.map(GenericToken::from_private_ristretto)?,
134-
// The mismatch case is handled above.
135-
_ => unreachable!("token type mismatch checked earlier"),
134+
_ => {
135+
return Err(IssueTokenError::UnexpectedTokenResponseType {
136+
expected,
137+
found,
138+
});
139+
}
136140
};
137141
tokens.push(token);
138142
}

src/public_tokens/det_rng.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,11 +76,15 @@ impl TryRng for DeterministicRng {
7676
type Error = Infallible;
7777

7878
fn try_next_u32(&mut self) -> Result<u32, Infallible> {
79-
unimplemented!()
79+
let mut buf = [0u8; 4];
80+
self.fill_with_data(&mut buf)?;
81+
Ok(u32::from_le_bytes(buf))
8082
}
8183

8284
fn try_next_u64(&mut self) -> Result<u64, Infallible> {
83-
unimplemented!()
85+
let mut buf = [0u8; 8];
86+
self.fill_with_data(&mut buf)?;
87+
Ok(u64::from_le_bytes(buf))
8488
}
8589

8690
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Infallible> {

src/public_tokens/mod.rs

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ use blind_rsa_signatures::{Deterministic, PSS, Sha384};
44
use sha2::{Digest, Sha256};
55
use typenum::U256;
66

7+
use blind_rsa_signatures::Error as BlindRsaError;
8+
79
use crate::{TokenKeyId, TruncatedTokenKeyId, auth::authorize::Token, truncate_token_key_id};
810

911
pub mod request;
@@ -26,13 +28,20 @@ use self::server::serialize_public_key;
2628
/// Size of the authenticator
2729
pub const NK: usize = 256;
2830

29-
/// Converts a public key to a token key ID
30-
pub fn public_key_to_truncated_token_key_id(public_key: &PublicKey) -> TruncatedTokenKeyId {
31-
truncate_token_key_id(&public_key_to_token_key_id(public_key))
31+
/// Converts a public key to a truncated token key ID.
32+
///
33+
/// # Errors
34+
/// Returns an error if the public key cannot be serialized.
35+
pub fn public_key_to_truncated_token_key_id(
36+
public_key: &PublicKey,
37+
) -> Result<TruncatedTokenKeyId, BlindRsaError> {
38+
Ok(truncate_token_key_id(&public_key_to_token_key_id(
39+
public_key,
40+
)?))
3241
}
3342

34-
fn public_key_to_token_key_id(public_key: &PublicKey) -> TokenKeyId {
35-
let public_key = serialize_public_key(public_key);
43+
fn public_key_to_token_key_id(public_key: &PublicKey) -> Result<TokenKeyId, BlindRsaError> {
44+
let public_key = serialize_public_key(public_key)?;
3645

37-
Sha256::digest(public_key).into()
46+
Ok(Sha256::digest(public_key).into())
3847
}

src/public_tokens/request.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,11 @@ impl TokenRequest {
5757
.inspect_err(|e| warn!(error:% = e; "Failed to create challenge digest"))
5858
.map_err(|source| IssueTokenRequestError::InvalidTokenChallenge { source })?;
5959

60-
let token_key_id = public_key_to_token_key_id(&public_key);
60+
let token_key_id = public_key_to_token_key_id(&public_key).map_err(|source| {
61+
IssueTokenRequestError::BlindingError {
62+
source: source.into(),
63+
}
64+
})?;
6165

6266
// nonce = random(32)
6367
// challenge_digest = SHA256(challenge)

src/public_tokens/server.rs

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -85,10 +85,14 @@ pub trait OriginKeyStore {
8585
async fn remove(&self, truncated_token_key_id: &TruncatedTokenKeyId) -> bool;
8686
}
8787

88-
/// Serializes a keypair into a DER-encoded PKCS#8 document.
89-
#[must_use]
90-
pub fn serialize_public_key(public_key: &PublicKey) -> Vec<u8> {
91-
public_key.to_spki().unwrap()
88+
/// Serializes a public key into a DER-encoded SPKI document.
89+
///
90+
/// # Errors
91+
/// Returns an error if the public key cannot be serialized.
92+
pub fn serialize_public_key(
93+
public_key: &PublicKey,
94+
) -> Result<Vec<u8>, blind_rsa_signatures::Error> {
95+
public_key.to_spki()
9296
}
9397

9498
const KEYSIZE_IN_BITS: usize = 2048;
@@ -119,8 +123,10 @@ impl IssuerServer {
119123
let key_pair = KeyPair::generate(rng, KEYSIZE_IN_BITS)
120124
.inspect_err(|e| debug!(error:% = e; "Failed to generate RSA keypair"))
121125
.map_err(|source| CreateKeypairError::KeyGenerationFailed { source })?;
122-
let truncated_token_key_id =
123-
truncate_token_key_id(&public_key_to_token_key_id(&key_pair.pk));
126+
let truncated_token_key_id = truncate_token_key_id(
127+
&public_key_to_token_key_id(&key_pair.pk)
128+
.map_err(|source| CreateKeypairError::KeySerializationFailed { source })?,
129+
);
124130

125131
if key_store.get(&truncated_token_key_id).await.is_some() {
126132
continue;
@@ -170,11 +176,21 @@ impl IssuerServer {
170176
}
171177

172178
/// Sets the given keypair.
179+
///
180+
/// # Errors
181+
/// Returns an error if the public key cannot be serialized.
173182
#[cfg(feature = "kat")]
174-
pub async fn set_keypair<IKS: IssuerKeyStore>(&self, key_store: &IKS, key_pair: KeyPair) {
175-
let truncated_token_key_id =
176-
truncate_token_key_id(&public_key_to_token_key_id(&key_pair.pk));
183+
pub async fn set_keypair<IKS: IssuerKeyStore>(
184+
&self,
185+
key_store: &IKS,
186+
key_pair: KeyPair,
187+
) -> Result<(), CreateKeypairError> {
188+
let truncated_token_key_id = truncate_token_key_id(
189+
&public_key_to_token_key_id(&key_pair.pk)
190+
.map_err(|source| CreateKeypairError::KeySerializationFailed { source })?,
191+
);
177192
key_store.insert(truncated_token_key_id, key_pair).await;
193+
Ok(())
178194
}
179195
}
180196

tests/generic_tokens.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,8 @@ async fn generic_tokens_cycle() {
6767
.insert(
6868
privacypass::public_tokens::public_key_to_truncated_token_key_id(
6969
&public_token_public_key,
70-
),
70+
)
71+
.unwrap(),
7172
public_token_public_key.clone(),
7273
)
7374
.await;

0 commit comments

Comments
 (0)