appstruct_module_sdk/
registry.rs1use base64::{Engine as _, engine::general_purpose::STANDARD};
2use ed25519_dalek::{Signature, VerifyingKey};
3use serde::{Deserialize, Serialize};
4use std::{error::Error, fmt};
5
6#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
8#[serde(deny_unknown_fields)]
9pub struct RegistryEnvelope {
10 pub schema_version: u32,
11 pub payload: String,
12 pub sha256: String,
13 pub signature: String,
14}
15
16#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(deny_unknown_fields)]
19pub struct RegistryPackage {
20 pub name: String,
21 pub version: String,
22 pub appstruct_version: String,
23 pub module_api_version: u32,
24 pub manifest: String,
25 #[serde(default)]
26 pub artifacts: Vec<RegistryArtifact>,
27}
28
29#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
31#[serde(deny_unknown_fields)]
32pub struct RegistryArtifact {
33 pub source: String,
34 pub content: String,
35 pub sha256: String,
36 pub byte_len: u64,
37}
38
39#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct RegistryVerificationError(String);
41
42impl fmt::Display for RegistryVerificationError {
43 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
44 formatter.write_str(&self.0)
45 }
46}
47
48impl Error for RegistryVerificationError {}
49
50pub fn verify_registry_envelope(
56 envelope: &RegistryEnvelope,
57 public_key: &str,
58) -> Result<(RegistryPackage, Vec<u8>), RegistryVerificationError> {
59 if envelope.schema_version != 1 {
60 return Err(invalid(format!(
61 "unsupported registry envelope version {}",
62 envelope.schema_version
63 )));
64 }
65 let payload = STANDARD
66 .decode(&envelope.payload)
67 .map_err(|error| invalid(format!("invalid payload base64: {error}")))?;
68 let digest = appstruct_core::sha256_tagged(&payload);
69 if envelope.sha256 != digest {
70 return Err(invalid("registry payload SHA-256 does not match"));
71 }
72 let key = STANDARD
73 .decode(public_key)
74 .map_err(|error| invalid(format!("invalid public key base64: {error}")))?;
75 let key: [u8; 32] = key
76 .try_into()
77 .map_err(|_| invalid("Ed25519 public key must contain 32 bytes"))?;
78 let key = VerifyingKey::from_bytes(&key)
79 .map_err(|error| invalid(format!("invalid Ed25519 public key: {error}")))?;
80 let signature = STANDARD
81 .decode(&envelope.signature)
82 .map_err(|error| invalid(format!("invalid signature base64: {error}")))?;
83 let signature = Signature::from_slice(&signature)
84 .map_err(|error| invalid(format!("invalid Ed25519 signature: {error}")))?;
85 key.verify_strict(&payload, &signature)
86 .map_err(|error| invalid(format!("registry signature verification failed: {error}")))?;
87 let package = serde_json::from_slice(&payload)
88 .map_err(|error| invalid(format!("invalid registry package JSON: {error}")))?;
89 Ok((package, payload))
90}
91
92fn invalid(message: impl Into<String>) -> RegistryVerificationError {
93 RegistryVerificationError(message.into())
94}