1use ed25519_dalek::{Signature, Verifier, VerifyingKey};
12
13use serde::{Deserialize, Serialize};
14
15use std::convert::TryInto;
16
17use std::time::{SystemTime, UNIX_EPOCH};
18
19#[derive(Serialize, Deserialize, Debug, Clone)]
20
21pub struct CommercialOverrideReceipt {
22 pub license_tier: String,
23
24 pub signer_did: String,
25
26 pub signature_algorithm: String,
27
28 pub credential_format: String,
29
30 pub distr_license_cid: String,
31
32 pub hardware_zk_proof: Option<String>,
33
34 pub issued_at_epoch: u64,
35
36 pub expires_at_epoch: u64,
37
38 pub exp: u64,
39
40 pub iat: u64,
41
42 pub entitlements: Vec<String>,
43
44 pub network_mode: String,
45
46 pub federation_enabled: bool,
47
48 pub signature: Option<String>,
49
50 #[serde(default = "default_tenant_cid")]
51 pub tenant_cid: String,
52}
53
54fn default_tenant_cid() -> String {
55 "coreason-tenant-default".to_string()
56}
57
58impl CommercialOverrideReceipt {
59 pub fn verify_signature(&self, public_key_hex: &str) -> Result<bool, &'static str> {
60 let signature_hex = match &self.signature {
61 Some(sig) => sig,
62
63 None => return Err("Missing signature in receipt"),
64 };
65
66 let message = format!("{}:{}", self.tenant_cid, self.expires_at_epoch);
67
68 let public_bytes = hex::decode(public_key_hex).map_err(|_| "Invalid hex in public key")?;
69
70 let signature_bytes = hex::decode(signature_hex).map_err(|_| "Invalid hex in signature")?;
71
72 let public_array: [u8; 32] = public_bytes
73 .as_slice()
74 .try_into()
75 .map_err(|_| "Public key must be 32 bytes")?;
76
77 let signature_array: [u8; 64] = signature_bytes
78 .as_slice()
79 .try_into()
80 .map_err(|_| "Signature must be 64 bytes")?;
81
82 let verifying_key =
83 VerifyingKey::from_bytes(&public_array).map_err(|_| "Invalid public key")?;
84
85 let signature = Signature::from_bytes(&signature_array);
86
87 Ok(verifying_key.verify(message.as_bytes(), &signature).is_ok())
88 }
89
90 pub fn is_valid_epoch(&self) -> bool {
91 let start = SystemTime::now();
92
93 let since_the_epoch = start
94 .duration_since(UNIX_EPOCH)
95 .expect("Time went backwards")
96 .as_secs();
97
98 self.expires_at_epoch > since_the_epoch && since_the_epoch >= self.issued_at_epoch
99 }
100}
101
102#[derive(Debug, Clone)]
107
108pub enum LicenseError {
109 TemporalExpiration(String),
110
111 CryptographicVerification(String),
112
113 HardwareFingerprint(String),
114
115 ProductionGuard(String),
116}
117
118impl std::fmt::Display for LicenseError {
119 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120 match self {
121 LicenseError::TemporalExpiration(msg) => write!(f, "TemporalExpiration: {}", msg),
122
123 LicenseError::CryptographicVerification(msg) => {
124 write!(f, "CryptographicVerification: {}", msg)
125 }
126
127 LicenseError::HardwareFingerprint(msg) => {
128 write!(f, "HardwareFingerprint: {}", msg)
129 }
130
131 LicenseError::ProductionGuard(msg) => write!(f, "ProductionGuard: {}", msg),
132 }
133 }
134}
135
136impl std::error::Error for LicenseError {}
137
138pub struct LicenseVerifier {
161 local_fingerprint: Option<String>,
162}
163
164impl LicenseVerifier {
165 pub fn new(local_cluster_fingerprint_hash: Option<String>) -> Self {
166 Self {
167 local_fingerprint: local_cluster_fingerprint_hash,
168 }
169 }
170
171 fn verify_zk_snark(&self, proof: &str) -> Result<bool, LicenseError> {
180 if proof.is_empty() {
181 return Ok(true); }
183
184 let local_fp = self.local_fingerprint.as_deref().ok_or_else(|| {
185 LicenseError::HardwareFingerprint(
186 "Receipt requires hardware binding, but no local fingerprint provided.".into(),
187 )
188 })?;
189
190 let plugins_dir =
193 std::env::var("PLUGINS_DIR").unwrap_or_else(|_| "/app/data/plugins".to_string());
194
195 let wasm_path = std::path::Path::new(&plugins_dir).join("license_verifier.wasm");
196
197 if wasm_path.exists() {
198 if let Ok(wasm_bytes) = std::fs::read(wasm_path) {
199 let expected_hash = crate::capability_allocator::wasm_hash(&wasm_bytes);
200
201 let input_json = serde_json::json!({
202
203 "proof": proof,
204
205 "local_fingerprint": local_fp
206
207 });
208
209 let input_bytes = serde_json::to_vec(&input_json).unwrap_or_default();
210
211 match crate::capability_allocator::call_with_telemetry(
212 &wasm_bytes,
213 &expected_hash,
214 "verify_proof",
215 &input_bytes,
216 None,
217 ) {
218 Ok((output_bytes, _telemetry)) => {
219 if let Ok(result_val) =
220 serde_json::from_slice::<serde_json::Value>(&output_bytes)
221 {
222 if result_val["valid"].as_bool().unwrap_or(false) {
223 return Ok(true);
224 } else {
225 return Err(LicenseError::HardwareFingerprint(
226 "zk-SNARK verification plugin rejected the proof.".into(),
227 ));
228 }
229 }
230 }
231
232 Err(err) => {
233 eprintln!(
234 "WASM zk-SNARK verifier failed: {}. Falling back to SHA-256.",
235 err
236 );
237 }
238 }
239 }
240 }
241
242 use sha2::{Digest, Sha256};
245
246 let mut hasher = Sha256::new();
247
248 hasher.update(local_fp.as_bytes());
249
250 let expected_hash = format!("{:x}", hasher.finalize());
251
252 if proof.trim() == expected_hash {
253 Ok(true)
254 } else {
255 Err(LicenseError::HardwareFingerprint(
256 "Hardware fingerprint mismatch: proof does not match local fingerprint hash."
257 .into(),
258 ))
259 }
260 }
261
262 pub fn verify_and_apply(
275 &self,
276
277 receipt: &CommercialOverrideReceipt,
278
279 public_key_hex: &str,
280 ) -> Vec<String> {
281 let coreason_env =
284 std::env::var("COREASON_ENV").unwrap_or_else(|_| "development".to_string());
285
286 if coreason_env == "production" {
287 let root_ca_key = std::env::var("COREASON_ROOT_CA_KEY").unwrap_or_default();
288
289 if root_ca_key.is_empty() {
290 eprintln!(
291 "CRITICAL: COREASON_ROOT_CA_KEY is not set in production. \
292 License verification fail-closed. Defaulting to Prosperity 3.0."
293 );
294
295 return Vec::new();
296 }
297
298 let dev_key = std::env::var("COREASON_DEV_KEY").unwrap_or_default();
299
300 if !dev_key.is_empty() && root_ca_key == dev_key {
301 eprintln!(
302 "CRITICAL: COREASON_ROOT_CA_KEY matches COREASON_DEV_KEY in production. \
303 This is a security violation. Fail-closed."
304 );
305
306 return Vec::new();
307 }
308 }
309
310 if !receipt.is_valid_epoch() {
313 eprintln!(
314 "License expired at {}. Falling back to Prosperity 3.0.",
315 receipt.expires_at_epoch
316 );
317
318 return Vec::new();
319 }
320
321 match receipt.verify_signature(public_key_hex) {
324 Ok(true) => {}
325
326 Ok(false) => {
327 eprintln!(
328 "License signature verification returned false. Defaulting to Prosperity 3.0."
329 );
330
331 return Vec::new();
332 }
333
334 Err(e) => {
335 eprintln!(
336 "License signature verification failed: {}. Defaulting to Prosperity 3.0.",
337 e
338 );
339
340 return Vec::new();
341 }
342 }
343
344 if let Some(ref proof) = receipt.hardware_zk_proof {
347 if let Err(e) = self.verify_zk_snark(proof) {
348 eprintln!(
349 "Hardware fingerprint verification failed: {}. Defaulting to Prosperity 3.0.",
350 e
351 );
352
353 return Vec::new();
354 }
355 }
356
357 if receipt.credential_format == "sd-jwt" {
360
361 }
363
364 receipt.entitlements.clone()
365 }
366}
367
368#[cfg(test)]
369
370mod tests {
371
372 use super::*;
373
374 fn make_receipt(expires_at_epoch: u64) -> CommercialOverrideReceipt {
375 let now = SystemTime::now()
376 .duration_since(UNIX_EPOCH)
377 .unwrap()
378 .as_secs();
379
380 CommercialOverrideReceipt {
381 license_tier: "enterprise".into(),
382
383 signer_did: "did:coreason:test".into(),
384
385 signature_algorithm: "Ed25519".into(),
386
387 credential_format: "jwt".into(),
388
389 distr_license_cid: "test-cid".into(),
390
391 hardware_zk_proof: None,
392
393 issued_at_epoch: now - 3600,
394
395 expires_at_epoch,
396
397 exp: expires_at_epoch,
398
399 iat: now - 3600,
400
401 entitlements: vec!["COMMERCIAL_USE".into()],
402
403 network_mode: "sovereign".into(),
404
405 federation_enabled: false,
406
407 signature: None,
408
409 tenant_cid: "test-tenant".into(),
410 }
411 }
412
413 #[test]
414
415 fn test_is_valid_epoch_unexpired() {
416 let now = SystemTime::now()
417 .duration_since(UNIX_EPOCH)
418 .unwrap()
419 .as_secs();
420
421 let receipt = make_receipt(now + 86400);
422
423 assert!(receipt.is_valid_epoch());
424 }
425
426 #[test]
427
428 fn test_is_valid_epoch_expired() {
429 let receipt = make_receipt(1000);
430
431 assert!(!receipt.is_valid_epoch());
432 }
433
434 #[test]
435
436 fn test_verify_and_apply_expired() {
437 let receipt = make_receipt(1000); let verifier = LicenseVerifier::new(None);
440
441 let entitlements = verifier.verify_and_apply(&receipt, "dummy");
442
443 assert!(entitlements.is_empty());
444 }
445
446 #[test]
447
448 fn test_zk_snark_empty_proof() {
449 let verifier = LicenseVerifier::new(None);
450
451 assert!(verifier.verify_zk_snark("").is_ok());
452 }
453
454 #[test]
455
456 fn test_zk_snark_no_fingerprint() {
457 let verifier = LicenseVerifier::new(None);
458
459 let result = verifier.verify_zk_snark("some_proof");
460
461 assert!(result.is_err());
462 }
463
464 #[test]
465
466 fn test_zk_snark_matching_fingerprint() {
467 use sha2::{Digest, Sha256};
468
469 let fp = "test-fingerprint";
470
471 let mut hasher = Sha256::new();
472
473 hasher.update(fp.as_bytes());
474
475 let proof = format!("{:x}", hasher.finalize());
476
477 let verifier = LicenseVerifier::new(Some(fp.to_string()));
478
479 assert!(verifier.verify_zk_snark(&proof).is_ok());
480 }
481
482 #[test]
483
484 fn test_zk_snark_mismatched_fingerprint() {
485 let verifier = LicenseVerifier::new(Some("test-fp".to_string()));
486
487 let result = verifier.verify_zk_snark("bad_proof");
488
489 assert!(result.is_err());
490 }
491}