File size: 10,067 Bytes
9425aed | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 | // SEB Rust Contract Template
// Generated from: SEB_SOVEREIGN_EVENT_BUS_MASTER_SPECIFICATION.xml
// Version: 1.0.0
// Target: Rust Kernel Implementation
use serde::{Deserialize, Serialize};
use blake3;
use ed25519_dalek::{Signature, Signer, Verifier, PublicKey, SecretKey};
use ulid::Ulid;
use chrono::{DateTime, Utc};
/// Event envelope structure following the SEB specification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventEnvelope {
/// Event type identifier (e.g., "snapkitty.intent.verify_proof")
#[serde(rename = "type")]
pub event_type: String,
/// Schema version for compatibility checking
pub version: String,
/// Unique event identifier (ULID format)
pub id: String,
/// Event creation timestamp in UTC
pub timestamp: DateTime<Utc>,
/// Structured intent describing the requested action
pub intent: Intent,
/// Execution context including environment and constraints
pub context: Context,
/// Authority scope and credentials for the requesting principal
pub authority: Authority,
/// Continuation data for multi-step workflows
#[serde(skip_serializing_if = "Option::is_none")]
pub continuation: Option<Continuation>,
/// Array of cryptographic evidence from prior steps
#[serde(default)]
pub evidence: Vec<Evidence>,
/// Cryptographic seal (added by WORM sealer after execution)
#[serde(skip_serializing_if = "Option::is_none")]
pub seal: Option<Seal>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Intent {
pub action: String,
pub subject: String,
pub parameters: serde_json::Value,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Context {
pub environment: String,
pub constraints: Constraints,
pub metadata: serde_json::Value,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Constraints {
pub network: NetworkPolicy,
pub max_runtime_ms: u64,
pub max_memory_bytes: u64,
pub filesystem: FilesystemPolicy,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NetworkPolicy {
Allow,
Deny,
Restricted,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FilesystemPolicy {
ReadOnly,
ReadWrite,
Deny,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Authority {
pub principal: String,
pub credentials: Credentials,
pub scope: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Credentials {
pub credential_type: String,
pub value: String,
pub signature: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Continuation {
pub step: u32,
pub total_steps: u32,
pub state: serde_json::Value,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Evidence {
pub evidence_type: String,
pub hash: String,
pub signature: String,
pub timestamp: DateTime<Utc>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Seal {
pub hash: String,
pub signature: String,
pub public_key: String,
pub timestamp: DateTime<Utc>,
pub algorithm: String,
}
impl EventEnvelope {
/// Create a new event envelope with generated ID and timestamp
pub fn new(
event_type: String,
intent: Intent,
context: Context,
authority: Authority,
) -> Self {
Self {
event_type,
version: "1.0.0".to_string(),
id: Ulid::new().to_string(),
timestamp: Utc::now(),
intent,
context,
authority,
continuation: None,
evidence: Vec::new(),
seal: None,
}
}
/// Compute Blake3 hash of the envelope (excluding seal)
pub fn compute_hash(&self) -> Result<String, Box<dyn std::error::Error>> {
let mut envelope_copy = self.clone();
envelope_copy.seal = None;
let json = serde_json::to_string(&envelope_copy)?;
let hash = blake3::hash(json.as_bytes());
Ok(hash.to_hex().to_string())
}
/// Seal the envelope with Ed25519 signature
pub fn seal(&mut self, secret_key: &SecretKey) -> Result<(), Box<dyn std::error::Error>> {
let hash = self.compute_hash()?;
let signature = secret_key.sign(hash.as_bytes());
let public_key = PublicKey::from(secret_key);
self.seal = Some(Seal {
hash: hash.clone(),
signature: hex::encode(signature.to_bytes()),
public_key: hex::encode(public_key.to_bytes()),
timestamp: Utc::now(),
algorithm: "ed25519".to_string(),
});
Ok(())
}
/// Verify the envelope seal
pub fn verify_seal(&self) -> Result<bool, Box<dyn std::error::Error>> {
let seal = self.seal.as_ref()
.ok_or("No seal present")?;
let public_key_bytes = hex::decode(&seal.public_key)?;
let public_key = PublicKey::from_bytes(&public_key_bytes)?;
let signature_bytes = hex::decode(&seal.signature)?;
let signature = Signature::from_bytes(&signature_bytes)?;
let hash = self.compute_hash()?;
Ok(public_key.verify(hash.as_bytes(), &signature).is_ok())
}
}
/// Policy gate for pre-execution verification
pub trait PolicyGate {
fn evaluate(&self, envelope: &EventEnvelope) -> Result<PolicyDecision, PolicyError>;
}
#[derive(Debug, Clone)]
pub enum PolicyDecision {
Allow,
Deny { reason: String },
RequireAdditionalEvidence { required: Vec<String> },
}
#[derive(Debug, Clone)]
pub struct PolicyError {
pub message: String,
pub code: String,
}
/// Routing engine for event dispatch
pub trait RoutingEngine {
fn route(&self, envelope: &EventEnvelope) -> Result<RouteDestination, RoutingError>;
}
#[derive(Debug, Clone)]
pub enum RouteDestination {
Adapter { adapter_id: String },
Queue { queue_name: String },
Reject { reason: String },
}
#[derive(Debug, Clone)]
pub struct RoutingError {
pub message: String,
pub code: String,
}
/// Execution adapter trait
pub trait ExecutionAdapter {
fn execute(&self, envelope: &EventEnvelope) -> Result<ExecutionResult, ExecutionError>;
fn capabilities(&self) -> Vec<String>;
fn constraints(&self) -> Constraints;
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionResult {
pub status: ExecutionStatus,
pub output: serde_json::Value,
pub evidence: Vec<Evidence>,
pub metrics: ExecutionMetrics,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ExecutionStatus {
Success,
Failure,
Timeout,
Denied,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionMetrics {
pub duration_ms: u64,
pub memory_used_bytes: u64,
pub network_calls: u32,
pub filesystem_operations: u32,
}
#[derive(Debug, Clone)]
pub struct ExecutionError {
pub message: String,
pub code: String,
pub recoverable: bool,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_envelope_creation() {
let intent = Intent {
action: "verify_proof".to_string(),
subject: "bundle:01J...".to_string(),
parameters: serde_json::json!({}),
};
let context = Context {
environment: "test".to_string(),
constraints: Constraints {
network: NetworkPolicy::Deny,
max_runtime_ms: 5000,
max_memory_bytes: 1024 * 1024,
filesystem: FilesystemPolicy::ReadOnly,
},
metadata: serde_json::json!({}),
};
let authority = Authority {
principal: "test-principal".to_string(),
credentials: Credentials {
credential_type: "api_key".to_string(),
value: "test-key".to_string(),
signature: None,
},
scope: vec!["read".to_string()],
};
let envelope = EventEnvelope::new(
"snapkitty.intent.verify_proof".to_string(),
intent,
context,
authority,
);
assert_eq!(envelope.version, "1.0.0");
assert!(!envelope.id.is_empty());
}
#[test]
fn test_envelope_hash() {
let envelope = create_test_envelope();
let hash = envelope.compute_hash().unwrap();
assert_eq!(hash.len(), 64); // Blake3 produces 32 bytes = 64 hex chars
}
fn create_test_envelope() -> EventEnvelope {
EventEnvelope::new(
"test.event".to_string(),
Intent {
action: "test".to_string(),
subject: "test".to_string(),
parameters: serde_json::json!({}),
},
Context {
environment: "test".to_string(),
constraints: Constraints {
network: NetworkPolicy::Deny,
max_runtime_ms: 1000,
max_memory_bytes: 1024,
filesystem: FilesystemPolicy::Deny,
},
metadata: serde_json::json!({}),
},
Authority {
principal: "test".to_string(),
credentials: Credentials {
credential_type: "test".to_string(),
value: "test".to_string(),
signature: None,
},
scope: vec![],
},
)
}
} |