| 1 |
// Copyright 2023 The Jujutsu Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
//! Generic APIs to work with cryptographic signatures created and verified by |
| 16 |
//! various backends. |
| 17 |
|
| 18 |
use crate::content_hash::blake2b_hash; |
| 19 |
use crate::hex_util; |
| 20 |
use crate::signing::SigStatus; |
| 21 |
use crate::signing::SignError; |
| 22 |
use crate::signing::SignResult; |
| 23 |
use crate::signing::SigningBackend; |
| 24 |
use crate::signing::Verification; |
| 25 |
|
| 26 |
/// A test signing backend that uses a simple hash-based signature format. |
| 27 |
#[derive(Debug)] |
| 28 |
pub struct TestSigningBackend; |
| 29 |
|
| 30 |
const PREFIX: &str = "--- JJ-TEST-SIGNATURE ---\nKEY: "; |
| 31 |
|
| 32 |
impl SigningBackend for TestSigningBackend { |
| 33 |
fn name(&self) -> &'static str { |
| 34 |
"test" |
| 35 |
} |
| 36 |
|
| 37 |
fn can_read(&self, signature: &[u8]) -> bool { |
| 38 |
signature.starts_with(PREFIX.as_bytes()) |
| 39 |
} |
| 40 |
|
| 41 |
fn sign(&self, data: &[u8], key: Option<&str>) -> SignResult<Vec<u8>> { |
| 42 |
let key = key.unwrap_or_default(); |
| 43 |
let mut body = Vec::with_capacity(data.len() + key.len()); |
| 44 |
body.extend_from_slice(key.as_bytes()); |
| 45 |
body.extend_from_slice(data); |
| 46 |
|
| 47 |
let hash = hex_util::encode_hex(&blake2b_hash(&body)); |
| 48 |
|
| 49 |
Ok(format!("{PREFIX}{key}\n{hash}\n").into_bytes()) |
| 50 |
} |
| 51 |
|
| 52 |
fn verify(&self, data: &[u8], signature: &[u8]) -> SignResult<Verification> { |
| 53 |
let Some(key) = signature |
| 54 |
.strip_prefix(PREFIX.as_bytes()) |
| 55 |
.and_then(|s| s.splitn(2, |&b| b == b'\n').next()) |
| 56 |
else { |
| 57 |
return Err(SignError::InvalidSignatureFormat); |
| 58 |
}; |
| 59 |
let key = (!key.is_empty()).then_some(str::from_utf8(key).unwrap().to_owned()); |
| 60 |
|
| 61 |
let sig = self.sign(data, key.as_deref())?; |
| 62 |
if sig == signature { |
| 63 |
Ok(Verification { |
| 64 |
status: SigStatus::Good, |
| 65 |
key, |
| 66 |
display: Some("test-display".into()), |
| 67 |
}) |
| 68 |
} else { |
| 69 |
Ok(Verification { |
| 70 |
status: SigStatus::Bad, |
| 71 |
key, |
| 72 |
display: Some("test-display".into()), |
| 73 |
}) |
| 74 |
} |
| 75 |
} |
| 76 |
} |