1use std::{
7 collections::BTreeMap,
8 sync::{Arc, Mutex},
9};
10
11use async_trait::async_trait;
12use base64::{
13 engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},
14 Engine as _,
15};
16use nkeys::{KeyPair, KeyPairType};
17use serde_json::{json, Value};
18use sha2::{Digest, Sha256};
19use subc_client_rs::{BindDecision, HandlerOutcome, ModuleHandler, RequestCtx, RouteBindRequest};
20use subc_protocol::{
21 manifest::{
22 Concurrency, ManagementOperation, ManagementOperationKind, ModuleManifest, ProviderRole,
23 },
24 Principal,
25};
26
27pub const SIGNER_OPERATIONS: &[&str] = &["credential.sign", "credential.public_key"];
29
30pub const PRODUCTION_CREDENTIAL_ID: &str = "signing:ck-bus-account:1";
35pub const PRODUCTION_PUBLIC_KEY_HEX: &str =
36 "c73fe2b0df0d9921f4531bf1277404839a6d630be49ed77dbd29848f3e1bfcfa";
37pub const PRODUCTION_KEY_ID: &str = "0253fac9609168a5";
38
39const MAX_SIGN_PAYLOAD: usize = 1024 * 1024;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum SignerFault {
45 Faithful,
47 PreHashes,
49 SignsBase64Text,
51 ReturnsBase64Url,
53}
54
55#[derive(Clone)]
57pub struct FixtureRoot {
58 pub pair: KeyPair,
59 pub public: [u8; 32],
60}
61
62impl FixtureRoot {
63 fn from_pair(pair: KeyPair) -> Self {
64 let (_, public) = nkeys::from_public_key(&pair.public_key())
65 .expect("a key pair's own public key always decodes");
66 Self { pair, public }
67 }
68
69 pub fn public_key_hex(&self) -> String {
70 hex(&self.public)
71 }
72
73 pub fn key_id(&self) -> String {
74 hex(&Sha256::digest(self.public)[..8])
75 }
76
77 pub fn account_public(&self) -> String {
79 self.pair.public_key()
80 }
81}
82
83#[derive(Clone)]
84pub struct HarnessSigner {
85 roots: Arc<BTreeMap<String, FixtureRoot>>,
86 fault: SignerFault,
87 principals: Arc<Mutex<Vec<Option<Principal>>>>,
88}
89
90impl HarnessSigner {
91 pub fn generated(credential_ids: &[&str]) -> Self {
93 Self::from_roots(credential_ids.iter().map(|id| {
94 (
95 (*id).to_string(),
96 FixtureRoot::from_pair(KeyPair::new(KeyPairType::Account)),
97 )
98 }))
99 }
100
101 pub fn fixed(credential_id: &str, secret: [u8; 32]) -> Self {
103 let pair = KeyPair::new_from_raw(KeyPairType::Account, secret)
104 .expect("any 32 bytes are an Ed25519 seed");
105 Self::from_roots([(credential_id.to_string(), FixtureRoot::from_pair(pair))])
106 }
107
108 pub fn from_pairs(roots: impl IntoIterator<Item = (String, KeyPair)>) -> Self {
111 Self::from_roots(
112 roots
113 .into_iter()
114 .map(|(id, pair)| (id, FixtureRoot::from_pair(pair))),
115 )
116 }
117
118 fn from_roots(roots: impl IntoIterator<Item = (String, FixtureRoot)>) -> Self {
119 let roots: BTreeMap<_, _> = roots.into_iter().collect();
120 for (credential_id, root) in &roots {
121 assert_not_production(credential_id, &root.public_key_hex(), &root.key_id());
122 }
123 Self {
124 roots: Arc::new(roots),
125 fault: SignerFault::Faithful,
126 principals: Arc::new(Mutex::new(Vec::new())),
127 }
128 }
129
130 pub fn without(&self, credential_id: &str) -> Self {
133 let mut roots = self.roots.as_ref().clone();
134 roots.remove(credential_id);
135 Self {
136 roots: Arc::new(roots),
137 fault: self.fault,
138 principals: Arc::new(Mutex::new(Vec::new())),
139 }
140 }
141
142 pub fn with_fault(mut self, fault: SignerFault) -> Self {
143 self.fault = fault;
144 self
145 }
146
147 pub fn root(&self, credential_id: &str) -> &FixtureRoot {
148 self.roots
149 .get(credential_id)
150 .unwrap_or_else(|| panic!("the harness signer holds no root {credential_id}"))
151 }
152
153 pub fn observed_principals(&self) -> Vec<Option<Principal>> {
154 self.principals
155 .lock()
156 .expect("signer principal log lock must remain usable")
157 .clone()
158 }
159
160 pub fn manifest(&self) -> ModuleManifest {
163 let operations = SIGNER_OPERATIONS
164 .iter()
165 .map(|name| ManagementOperation {
166 name: (*name).to_string(),
167 kind: ManagementOperationKind::Query,
168 description: Some("acceptance harness signer".to_string()),
169 })
170 .collect();
171 ModuleManifest::builder("claustrum", "0.0.0-harness-signer")
172 .provides(vec![ProviderRole::ManagementSurface {
173 operations,
174 config_schema: json!({}),
175 observability: vec![],
176 identity_scope: vec![],
177 concurrency: Concurrency::ModuleManaged,
178 }])
179 .build()
180 }
181
182 pub fn answer(&self, body: &[u8]) -> HandlerOutcome {
187 let Ok(request) = serde_json::from_slice::<Value>(body) else {
188 return invalid_params("request body is not JSON");
189 };
190 let params = request.get("params").cloned().unwrap_or(Value::Null);
191 let credential_id = params.get("credential_id").and_then(Value::as_str);
192 match request.get("method").and_then(Value::as_str) {
193 Some("credential.sign") => {
194 let (Some(credential_id), Some(payload_b64)) = (
195 credential_id,
196 params.get("payload_b64").and_then(Value::as_str),
197 ) else {
198 return invalid_params(
199 "credential.sign requires credential_id and payload_b64",
200 );
201 };
202 let Ok(payload) = STANDARD.decode(payload_b64) else {
203 return invalid_params("payload_b64 is not standard base64");
204 };
205 let Some(root) = self.roots.get(credential_id) else {
206 return refusal("not_found", "permanent");
207 };
208 if payload.len() > MAX_SIGN_PAYLOAD {
209 return refusal("sign_payload_too_large", "context_overflow");
210 }
211 let signed: Vec<u8> = match self.fault {
212 SignerFault::PreHashes => Sha256::digest(&payload).to_vec(),
213 SignerFault::SignsBase64Text => payload_b64.as_bytes().to_vec(),
214 SignerFault::Faithful | SignerFault::ReturnsBase64Url => payload,
215 };
216 let signature = root.pair.sign(&signed).expect("fixture roots hold seeds");
217 let signature_b64 = match self.fault {
218 SignerFault::ReturnsBase64Url => URL_SAFE_NO_PAD.encode(&signature),
219 _ => STANDARD.encode(&signature),
220 };
221 result(json!({"signature_b64": signature_b64, "key_id": root.key_id()}))
222 }
223 Some("credential.public_key") => {
224 let Some(credential_id) = credential_id else {
225 return invalid_params("credential.public_key requires credential_id");
226 };
227 let Some(root) = self.roots.get(credential_id) else {
228 return refusal("not_found", "permanent");
229 };
230 result(json!({
231 "public_key_hex": root.public_key_hex(),
232 "key_id": root.key_id(),
233 "algorithm": "ed25519",
234 }))
235 }
236 Some(other) => HandlerOutcome::Error {
237 code: "unknown_operation".to_string(),
238 message: format!("the harness signer does not serve {other}"),
239 },
240 None => invalid_params("request has no method"),
241 }
242 }
243}
244
245fn result(value: Value) -> HandlerOutcome {
246 HandlerOutcome::Response(
247 serde_json::to_vec(&json!({ "result": value })).expect("reply encodes"),
248 )
249}
250
251fn refusal(code: &str, class: &str) -> HandlerOutcome {
252 result(json!({"error": {"code": code, "class": class}}))
253}
254
255fn invalid_params(detail: &str) -> HandlerOutcome {
256 HandlerOutcome::Error {
257 code: "invalid_params".to_string(),
258 message: format!("params not decodable: {detail}"),
259 }
260}
261
262#[async_trait]
263impl ModuleHandler for HarnessSigner {
264 async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
265 self.answer(&body)
266 }
267
268 async fn on_bind(&self, request: &RouteBindRequest) -> BindDecision {
271 self.principals
272 .lock()
273 .expect("signer principal log lock must remain usable")
274 .push(request.principal.clone());
275 BindDecision::accept()
276 }
277}
278
279pub fn assert_not_production(credential_id: &str, public_key_hex: &str, key_id: &str) {
281 let _ = credential_id;
282 assert_ne!(
283 public_key_hex, PRODUCTION_PUBLIC_KEY_HEX,
284 "a harness fixture must never hold the production root's public key"
285 );
286 assert_ne!(
287 key_id, PRODUCTION_KEY_ID,
288 "a harness fixture must never carry the production root's key_id"
289 );
290}
291
292pub fn hex(bytes: &[u8]) -> String {
293 bytes.iter().map(|byte| format!("{byte:02x}")).collect()
294}
295
296pub fn unhex(text: &str) -> Vec<u8> {
297 (0..text.len())
298 .step_by(2)
299 .map(|index| u8::from_str_radix(&text[index..index + 2], 16).expect("fixture hex"))
300 .collect()
301}