repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/src/tree/get_encrypt_key.rs
lib/src/tree/get_encrypt_key.rs
#[allow(unused_imports)] use tracing::{debug, error, info, warn}; use crate::crypto::*; use crate::error::*; use crate::meta::*; use crate::session::*; use crate::transaction::*; use super::*; impl TreeAuthorityPlugin { pub(super) fn get_encrypt_key( &self, meta: &Metadata, confidentiality: &MetaConfidentiality, iv: Option<&InitializationVector>, session: &'_ dyn AteSession, ) -> Result<Option<EncryptKey>, TransformError> { let trans_meta = TransactionMetadata::default(); let auth_store; let auth = match &confidentiality._cache { Some(a) => a, None => { auth_store = self.compute_auth(meta, &trans_meta, ComputePhase::AfterStore)?; &auth_store.read } }; match auth { ReadOption::Inherit => Err(TransformErrorKind::UnspecifiedReadability.into()), ReadOption::Everyone(key) => { if let Some(_iv) = iv { if let Some(key) = key { return Ok(Some(key.clone())); } } Ok(None) } ReadOption::Specific(key_hash, derived) => { for key in session.read_keys(AteSessionKeyCategory::AllKeys) { if key.hash() == *key_hash { let inner = derived.transmute(key)?; if inner.short_hash() == confidentiality.hash { return Ok(Some(inner)); } } } for key in session.private_read_keys(AteSessionKeyCategory::AllKeys) { if key.hash() == *key_hash { let inner = derived.transmute_private(key)?; if inner.short_hash() == confidentiality.hash { return Ok(Some(inner)); } } } Err(TransformErrorKind::MissingReadKey(key_hash.to_hex_string()).into()) } } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/src/tree/validator.rs
lib/src/tree/validator.rs
use error_chain::bail; use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info, warn}; use crate::error::*; use crate::event::*; use crate::meta::*; use crate::spec::*; use crate::transaction::*; use crate::validator::*; use super::*; impl EventValidator for TreeAuthorityPlugin { fn clone_validator(&self) -> Box<dyn EventValidator> { Box::new(self.clone()) } fn validate( &self, header: &EventHeader, conversation: Option<&Arc<ConversationSession>>, ) -> Result<ValidationResult, ValidationError> { // We need to check all the signatures are valid self.signature_plugin.validate(header, conversation)?; // If it does not need a signature then accept it if header.meta.needs_signature() == false && header.raw.data_hash.is_none() { return Ok(ValidationResult::Allow); } // If it has data then we need to check it - otherwise we ignore it let sig_hash = header.raw.event_hash; // It might be the case that everyone is allowed to write freely let dummy_trans_meta = TransactionMetadata::default(); let auth = self.compute_auth(&header.meta, &dummy_trans_meta, ComputePhase::BeforeStore)?; // Of course if everyone can write here then its allowed if auth.write == WriteOption::Everyone { return Ok(ValidationResult::Allow); } // Make sure that it has a signature let verified_signatures = match self.signature_plugin.get_verified_signatures(&sig_hash) { Some(a) => a, None => { if let Some(conversation) = conversation { // If we are to skip validation then do so if conversation.weaken_validation { return Ok(ValidationResult::Allow); } // If integrity is centrally managed and we have seen this public key before in this // particular conversation then we can trust the rest of the integrity of the chain if self.integrity.is_centralized() { if self.integrity == TrustMode::Centralized(CentralizedRole::Client) { return Ok(ValidationResult::Allow); } let lock = conversation.signatures.read().unwrap(); let already = match &auth.write { WriteOption::Specific(hash) => lock.contains(hash), WriteOption::Any(hashes) => hashes.iter().any(|h| lock.contains(h)), _ => false, }; if already { return Ok(ValidationResult::Allow); } } // Otherwise fail if let Some(sig) = header.meta.get_sign_with() { debug!("rejected event ({}) which is in a conversation but is missing signature [{}] ({})", sig_hash, sig, self.integrity); } else { debug!("rejected event ({}) which is in a conversation but has no signatures ({})", sig_hash, self.integrity); } bail!(ValidationErrorKind::NoSignatures); } else { // Otherwise fail if let Some(sig) = header.meta.get_sign_with() { debug!("rejected event ({}) as it is missing signature [{}] no signatures ({})", sig_hash, sig, self.integrity); } else { debug!( "rejected event ({}) as it has no signatures ({})", sig_hash, self.integrity ); } bail!(ValidationErrorKind::NoSignatures); } } }; // Compute the auth tree and if a signature exists for any of the auths then its allowed let auth_write = auth.write.vals(); for hash in verified_signatures.iter() { if auth_write.contains(hash) { //debug!("- verified data ({}) with ({})", header.meta.get_data_key().unwrap(), hash); return Ok(ValidationResult::Allow); } } // If we get this far then any data events must be denied // as all the other possible routes for it to be accepted into the tree have failed #[cfg(feature = "enable_verbose")] { warn!( "rejected event as it is detached from the tree with auth.write = ({})", auth.write ); for hash in verified_signatures.iter() { warn!("- supplied hash signature ({})", hash); } } #[cfg(not(feature = "enable_verbose"))] warn!("rejected event as it is detached from the tree"); Err(ValidationErrorKind::Detached.into()) } fn set_integrity_mode(&mut self, mode: TrustMode) { self.integrity = mode; self.signature_plugin.set_integrity_mode(mode); } fn validator_name(&self) -> &str { "tree-authority-validator" } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/src/tree/transformer.rs
lib/src/tree/transformer.rs
use bytes::Bytes; use error_chain::bail; #[allow(unused_imports)] use tracing::{debug, error, info, warn}; use crate::error::*; use crate::meta::*; use crate::session::*; use crate::transaction::*; use crate::transform::*; use super::*; impl EventDataTransformer for TreeAuthorityPlugin { fn clone_transformer(&self) -> Box<dyn EventDataTransformer> { Box::new(self.clone()) } #[allow(unused_variables)] fn data_as_underlay( &self, meta: &mut Metadata, with: Bytes, session: &'_ dyn AteSession, trans_meta: &TransactionMetadata, ) -> Result<Bytes, TransformError> { let mut with = self .signature_plugin .data_as_underlay(meta, with, session, trans_meta)?; let cache = match meta.get_confidentiality() { Some(a) => a._cache.as_ref(), None => None, }; let auth_store; let auth = match &cache { Some(a) => a, None => { auth_store = self.compute_auth(meta, trans_meta, ComputePhase::AfterStore)?; &auth_store.read } }; if let Some((iv, key)) = self.generate_encrypt_key(auth, session)? { let encrypted = key.encrypt_with_iv(&iv, &with[..]); meta.core.push(CoreMetadata::InitializationVector(iv)); with = Bytes::from(encrypted); } Ok(with) } #[allow(unused_variables)] fn data_as_overlay( &self, meta: &Metadata, with: Bytes, session: &'_ dyn AteSession, ) -> Result<Bytes, TransformError> { let mut with = self.signature_plugin.data_as_overlay(meta, with, session)?; let iv = meta.get_iv().ok(); match meta.get_confidentiality() { Some(confidentiality) => { if let Some(key) = self.get_encrypt_key(meta, confidentiality, iv, session)? { let iv = match iv { Some(a) => a, None => { bail!(TransformErrorKind::CryptoError( CryptoErrorKind::NoIvPresent )); } }; let decrypted = key.decrypt(&iv, &with[..]); with = Bytes::from(decrypted); } } None if iv.is_some() => { bail!(TransformErrorKind::UnspecifiedReadability); } None => {} }; Ok(with) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/src/tree/compute.rs
lib/src/tree/compute.rs
use error_chain::bail; #[allow(unused_imports)] use tracing::{debug, error, info, warn}; use crate::error::*; use crate::meta::*; use crate::transaction::*; use super::*; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub(super) enum ComputePhase { BeforeStore, AfterStore, } impl TreeAuthorityPlugin { pub(super) fn compute_auth( &self, meta: &Metadata, trans_meta: &TransactionMetadata, phase: ComputePhase, ) -> Result<MetaAuthorization, TrustError> { // If its not got a key then it just inherits the permissions of the root let key = match meta.get_data_key() { Some(a) => a, None => { return Ok(MetaAuthorization { read: ReadOption::Everyone(None), write: self.root.clone(), }); } }; #[cfg(feature = "enable_super_verbose")] trace!("compute_auth(): key={}", key); // Get the authorization of this node itself (if its post phase) let mut auth = match phase { ComputePhase::BeforeStore => None, ComputePhase::AfterStore => meta.get_authorization(), }; // In the scenarios that this is before the record is saved or // if no authorization is attached to the record then we fall // back to whatever is the value in the existing chain of trust if auth.is_none() { auth = trans_meta.auth.get(&key); if auth.is_none() { auth = self.auth.get(&key); } } // Fall back on inheriting from the parent if there is no // record yet set for this data object let (mut read, mut write) = match auth { Some(a) => (a.read.clone(), a.write.clone()), None => (ReadOption::Inherit, WriteOption::Inherit), }; #[cfg(feature = "enable_super_verbose")] trace!("compute_auth(): read={}, write={}", read, write); // Resolve any inheritance through recursive queries let mut parent = meta.get_parent(); while (read == ReadOption::Inherit || write == WriteOption::Inherit) && parent.is_some() { { let parent = match parent { Some(a) => a.vec.parent_id, None => unreachable!(), }; #[cfg(feature = "enable_super_verbose")] trace!("compute_auth(): parent={}", parent); // Get the authorization for this parent (if there is one) let mut parent_auth = trans_meta.auth.get(&parent); if parent_auth.is_none() { parent_auth = self.auth.get(&parent); } let parent_auth = match parent_auth { Some(a) => a, None => { #[cfg(feature = "enable_super_verbose")] trace!("compute_auth(): missing_parent={}", parent); bail!(TrustErrorKind::MissingParent(parent)); } }; // Resolve the read inheritance if read == ReadOption::Inherit { read = parent_auth.read.clone(); } // Resolve the write inheritance if write == WriteOption::Inherit { write = parent_auth.write.clone(); } #[cfg(feature = "enable_super_verbose")] trace!("compute_auth(): read={}, write={}", read, write); } // Walk up the tree until we have a resolved inheritance or there are no more parents parent = match parent { Some(a) => { let mut r = trans_meta.parents.get(&a.vec.parent_id); if r.is_none() { r = match self.parents.get(&a.vec.parent_id) { Some(b) if b.vec.parent_id != a.vec.parent_id => Some(b), _ => None, }; } match r { Some(b) if b.vec.parent_id != a.vec.parent_id => Some(b), _ => { break; } } } None => unreachable!(), } } // If we are at the top of the walk and its still inherit then we inherit the // permissions of a root node if read == ReadOption::Inherit { read = ReadOption::Everyone(None); } if write == WriteOption::Inherit { #[cfg(feature = "enable_super_verbose")] trace!("compute_auth(): using_root_read={}", self.root); write = self.root.clone(); } #[cfg(feature = "enable_super_verbose")] trace!("compute_auth(): read={}, write={}", read, write); let auth = MetaAuthorization { read, write }; // Return the result Ok(auth) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/src/tree/plugin.rs
lib/src/tree/plugin.rs
use fxhash::FxHashMap; use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info, warn}; use crate::crypto::*; use crate::error::*; use crate::event::*; use crate::header::*; use crate::meta::*; use crate::plugin::*; use crate::signature::*; use crate::sink::*; use crate::spec::*; use crate::transaction::*; #[derive(Debug, Clone)] pub struct TreeAuthorityPlugin { pub(super) root: WriteOption, pub(super) root_keys: FxHashMap<AteHash, PublicSignKey>, pub(super) auth: FxHashMap<PrimaryKey, MetaAuthorization>, pub(super) parents: FxHashMap<PrimaryKey, MetaParent>, pub(super) signature_plugin: SignaturePlugin, pub(super) integrity: TrustMode, } impl TreeAuthorityPlugin { pub fn new() -> TreeAuthorityPlugin { TreeAuthorityPlugin { root: WriteOption::Everyone, root_keys: FxHashMap::default(), signature_plugin: SignaturePlugin::new(), auth: FxHashMap::default(), parents: FxHashMap::default(), integrity: TrustMode::Distributed, } } #[allow(dead_code)] pub fn add_root_public_key(&mut self, key: &PublicSignKey) { self.root_keys.insert(key.hash(), key.clone()); self.root = WriteOption::Any(self.root_keys.keys().map(|k| k.clone()).collect::<Vec<_>>()); } } impl EventPlugin for TreeAuthorityPlugin { fn clone_plugin(&self) -> Box<dyn EventPlugin> { Box::new(self.clone()) } fn rebuild( &mut self, headers: &Vec<EventHeader>, conversation: Option<&Arc<ConversationSession>>, ) -> Result<(), SinkError> { self.reset(); self.signature_plugin.rebuild(headers, conversation)?; for header in headers { match self.feed(header, conversation) { Ok(_) => {} Err(err) => { debug!("feed error: {}", err); } } } Ok(()) } fn root_keys(&self) -> Vec<PublicSignKey> { self.root_keys .values() .map(|a| a.clone()) .collect::<Vec<_>>() } fn set_root_keys(&mut self, root_keys: &Vec<PublicSignKey>) { self.root_keys.clear(); self.root = WriteOption::Everyone; for root_key in root_keys { #[cfg(feature = "enable_verbose")] debug!("old_chain_root_key: {}", self.root); debug!("chain_root_key: {}", root_key.hash().to_string()); self.add_root_public_key(root_key); } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/src/meta/read_option.rs
lib/src/meta/read_option.rs
use serde::{Deserialize, Serialize}; use crate::crypto::*; /// Determines if the event record will be restricted so that /// only a specific set of users can read the data. If it is /// limited to a specific set of users they must all possess /// the encryption key in their session when accessing these /// data records of which the hash of the encryption key must /// match this record. #[derive(Serialize, Deserialize, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub enum ReadOption { Inherit, Everyone(Option<EncryptKey>), Specific(AteHash, DerivedEncryptKey), } impl ReadOption { pub fn from_key(key: &EncryptKey) -> ReadOption { ReadOption::Specific(key.hash(), DerivedEncryptKey::new(key)) } } impl Default for ReadOption { fn default() -> ReadOption { ReadOption::Inherit } } impl std::fmt::Display for ReadOption { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { ReadOption::Everyone(key) => { if let Some(key) = key { write!(f, "everyone({})", key.hash()) } else { write!(f, "everyone") } } ReadOption::Inherit => { write!(f, "inherit") } ReadOption::Specific(hash, _derived) => { write!(f, "specifc({})", hash) } } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/src/meta/core.rs
lib/src/meta/core.rs
use crate::signature::MetaSignWith; use serde::{Deserialize, Serialize}; use crate::crypto::*; use crate::error::*; use crate::header::*; use crate::signature::MetaSignature; use crate::time::*; use super::*; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum CoreMetadata { None, Data(PrimaryKey), Tombstone(PrimaryKey), Authorization(MetaAuthorization), InitializationVector(InitializationVector), PublicKey(PublicSignKey), EncryptedPrivateKey(EncryptedPrivateKey), Confidentiality(MetaConfidentiality), Collection(MetaCollection), Parent(MetaParent), Timestamp(ChainTimestamp), Signature(MetaSignature), SignWith(MetaSignWith), Author(String), Type(MetaType), Reply(PrimaryKey), DelayedUpload(MetaDelayedUpload), } impl Default for CoreMetadata { fn default() -> Self { CoreMetadata::None } } impl std::fmt::Display for CoreMetadata { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { CoreMetadata::None => write!(f, "none"), CoreMetadata::Data(a) => write!(f, "data-{}", a), CoreMetadata::Tombstone(a) => write!(f, "tombstone-{}", a), CoreMetadata::Authorization(a) => write!(f, "auth({})", a), CoreMetadata::InitializationVector(a) => write!(f, "iv({})", a), CoreMetadata::PublicKey(a) => write!(f, "public_key({})", a.hash()), CoreMetadata::EncryptedPrivateKey(a) => { write!(f, "encrypt_private_key({})", a.as_public_key().hash()) } CoreMetadata::Confidentiality(a) => write!(f, "confidentiality-{}", a), CoreMetadata::Collection(a) => write!(f, "collection-{}", a), CoreMetadata::Parent(a) => write!(f, "parent-{}", a), CoreMetadata::Timestamp(a) => write!(f, "timestamp-{}", a), CoreMetadata::Signature(a) => write!(f, "signature-{}", a), CoreMetadata::SignWith(a) => write!(f, "sign_with({})", a), CoreMetadata::Author(a) => write!(f, "author-{}", a), CoreMetadata::Type(a) => write!(f, "type-{}", a), CoreMetadata::Reply(a) => write!(f, "reply-{}", a), CoreMetadata::DelayedUpload(a) => write!(f, "delayed_upload-{}", a), } } } #[derive(Serialize, Deserialize, Debug, Default, Clone)] pub struct Metadata { pub core: Vec<CoreMetadata>, } impl std::fmt::Display for Metadata { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut first = true; write!(f, "meta[")?; for core in self.core.iter() { if first { first = false; } else { write!(f, ",")?; } core.fmt(f)?; } write!(f, "]") } } impl Metadata { pub fn get_authorization(&self) -> Option<&MetaAuthorization> { for core in &self.core { match core { CoreMetadata::Authorization(a) => { return Some(a); } _ => {} } } None } pub fn get_parent(&self) -> Option<&MetaParent> { for core in &self.core { if let CoreMetadata::Parent(a) = core { return Some(a); } } None } pub fn get_collections(&self) -> Vec<MetaCollection> { let mut ret = Vec::new(); for core in &self.core { if let CoreMetadata::Collection(a) = core { ret.push(a.clone()); } } ret } pub fn get_confidentiality(&self) -> Option<&MetaConfidentiality> { for core in &self.core { if let CoreMetadata::Confidentiality(a) = core { return Some(a); } } None } pub fn generate_iv(&mut self) -> InitializationVector { let mut core = self .core .clone() .into_iter() .filter(|m| match m { CoreMetadata::InitializationVector(_) => false, _ => true, }) .collect::<Vec<_>>(); let iv = InitializationVector::generate(); core.push(CoreMetadata::InitializationVector(iv.clone())); self.core = core; return iv; } pub fn get_iv(&self) -> Result<&InitializationVector, CryptoError> { for m in self.core.iter() { match m { CoreMetadata::InitializationVector(iv) => return Result::Ok(iv), _ => {} } } Result::Err(CryptoErrorKind::NoIvPresent.into()) } pub fn needs_signature(&self) -> bool { for core in &self.core { match core { CoreMetadata::PublicKey(_) => {} CoreMetadata::Signature(_) => {} CoreMetadata::EncryptedPrivateKey(_) => {} CoreMetadata::Confidentiality(_) => {} CoreMetadata::DelayedUpload(_) => {} _ => { return true; } } } false } pub fn strip_signatures(&mut self) { self.core.retain(|a| match a { CoreMetadata::Signature(_) => false, _ => true, }); } pub fn strip_public_keys(&mut self) { self.core.retain(|a| match a { CoreMetadata::PublicKey(_) => false, _ => true, }); } pub fn get_sign_with(&self) -> Option<&MetaSignWith> { for core in &self.core { if let CoreMetadata::SignWith(a) = core { return Some(a); } } None } pub fn get_timestamp(&self) -> Option<&ChainTimestamp> { for core in &self.core { if let CoreMetadata::Timestamp(a) = core { return Some(a); } } None } pub fn get_type_name(&self) -> Option<&MetaType> { self.core .iter() .filter_map(|m| match m { CoreMetadata::Type(t) => Some(t), _ => None, }) .next() } pub fn get_public_key(&self) -> Option<&PublicSignKey> { self.core .iter() .filter_map(|m| match m { CoreMetadata::PublicKey(t) => Some(t), _ => None, }) .next() } pub fn is_of_type<T: ?Sized>(&self) -> bool { if let Some(m) = self .core .iter() .filter_map(|m| match m { CoreMetadata::Type(t) => Some(t), _ => None, }) .next() { return m.type_name == std::any::type_name::<T>().to_string(); } false } pub fn set_type_name<T: ?Sized>(&mut self) { let type_name = std::any::type_name::<T>().to_string(); if self .core .iter_mut() .filter_map(|m| match m { CoreMetadata::Type(t) => { t.type_name = type_name.clone(); Some(t) } _ => None, }) .next() .is_none() { self.core.push(CoreMetadata::Type(MetaType { type_name })); } } pub fn is_reply_to_what(&self) -> Option<PrimaryKey> { self.core .iter() .filter_map(|m| match m { CoreMetadata::Reply(a) => Some(a.clone()), _ => None, }) .next() } pub fn get_delayed_upload(&self) -> Option<MetaDelayedUpload> { self.core .iter() .filter_map(|m| match m { CoreMetadata::DelayedUpload(k) => Some(k.clone()), _ => None, }) .next() } pub fn include_in_history(&self) -> bool { if self.get_delayed_upload().is_some() { return false; } true } pub fn is_empty(&self) -> bool { self.core.is_empty() } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/src/meta/write_option.rs
lib/src/meta/write_option.rs
use fxhash::FxHashSet; use serde::{Deserialize, Serialize}; use crate::crypto::*; /// Determines who is allowed to attach events records to this part of the /// chain-of-trust key. Only users who have the `PrivateKey` in their session /// will be able to write these records to the chain. The hash of the `PublicKey` /// side is stored in this enum. #[derive(Serialize, Deserialize, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub enum WriteOption { Inherit, Everyone, Nobody, Specific(AteHash), Any(Vec<AteHash>), } impl WriteOption { pub fn vals(&self) -> FxHashSet<AteHash> { let mut ret = FxHashSet::default(); match self { WriteOption::Specific(a) => { ret.insert(a.clone()); } WriteOption::Any(hashes) => { for a in hashes { ret.insert(a.clone()); } } _ => {} } return ret; } pub fn or(self, other: &WriteOption) -> WriteOption { match other { WriteOption::Inherit => self, WriteOption::Any(keys) => { let mut vals = self.vals(); for a in keys { vals.insert(a.clone()); } WriteOption::Any(vals.iter().map(|k| k.clone()).collect::<Vec<_>>()) } WriteOption::Specific(hash) => { let mut vals = self.vals(); vals.insert(hash.clone()); let vals = vals.iter().map(|k| k.clone()).collect::<Vec<_>>(); match vals.len() { 1 => WriteOption::Specific(vals.into_iter().next().unwrap()), _ => WriteOption::Any(vals), } } a => a.clone(), } } } impl Default for WriteOption { fn default() -> WriteOption { WriteOption::Inherit } } impl std::fmt::Display for WriteOption { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { WriteOption::Everyone => { write!(f, "everyone") } WriteOption::Any(vec) => { write!(f, "any(")?; let mut first = true; for hash in vec { if first == true { first = false; } else { write!(f, ",")?; } write!(f, "{}", hash)?; } write!(f, ")") } WriteOption::Inherit => { write!(f, "inherit") } WriteOption::Nobody => { write!(f, "nobody") } WriteOption::Specific(hash) => { write!(f, "specifc({})", hash) } } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/src/meta/meta_type.rs
lib/src/meta/meta_type.rs
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct MetaType { pub type_name: String, } impl std::fmt::Display for MetaType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.type_name) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/src/meta/delayed_upload.rs
lib/src/meta/delayed_upload.rs
use serde::{Deserialize, Serialize}; use crate::time::ChainTimestamp; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct MetaDelayedUpload { pub complete: bool, pub from: ChainTimestamp, pub to: ChainTimestamp, } impl std::fmt::Display for MetaDelayedUpload { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "from-{}-to-{}", self.from, self.to)?; if self.complete { write!(f, "-complete")?; } else { write!(f, "-incomplete")?; } Ok(()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/src/meta/mod.rs
lib/src/meta/mod.rs
mod authorization; mod collection; mod confidentiality; mod core; mod delayed_upload; mod meta_type; mod parent; mod read_option; mod write_option; pub use self::core::*; pub use authorization::*; pub use collection::*; pub use confidentiality::*; pub use delayed_upload::*; pub use meta_type::*; pub use parent::*; pub use read_option::*; pub use write_option::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/src/meta/authorization.rs
lib/src/meta/authorization.rs
use serde::{Deserialize, Serialize}; use super::*; #[derive(Serialize, Deserialize, Debug, Clone, Default, Hash, PartialEq, Eq)] pub struct MetaAuthorization { pub read: ReadOption, pub write: WriteOption, } impl MetaAuthorization { pub fn is_relevant(&self) -> bool { self.read != ReadOption::Inherit || self.write != WriteOption::Inherit } } impl std::fmt::Display for MetaAuthorization { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let r = match &self.read { ReadOption::Everyone(key) => { if let Some(key) = key { format!("everyone({})", key.hash()) } else { "everyone".to_string() } } ReadOption::Inherit => "inherit".to_string(), ReadOption::Specific(a, _derived) => format!("specific-{}", a), }; let w = match &self.write { WriteOption::Everyone => "everyone".to_string(), WriteOption::Nobody => "nobody".to_string(), WriteOption::Inherit => "inherit".to_string(), WriteOption::Specific(a) => format!("specific-{}", a), WriteOption::Any(a) => { let mut r = "any".to_string(); for a in a { r.push_str("-"); r.push_str(a.to_string().as_str()); } r } }; write!(f, "(r:{}, w:{})", r, w) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/src/meta/confidentiality.rs
lib/src/meta/confidentiality.rs
use serde::{Deserialize, Serialize}; use crate::crypto::*; use super::*; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct MetaConfidentiality { pub hash: ShortHash, #[serde(skip)] pub _cache: Option<ReadOption>, } impl std::fmt::Display for MetaConfidentiality { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.hash) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/src/meta/collection.rs
lib/src/meta/collection.rs
use crate::header::*; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)] pub struct MetaCollection { pub parent_id: PrimaryKey, pub collection_id: u64, } impl std::fmt::Display for MetaCollection { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.parent_id)?; if self.collection_id > 1 { write!(f, ".{}", self.collection_id)?; } Ok(()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/src/meta/parent.rs
lib/src/meta/parent.rs
use serde::{Deserialize, Serialize}; use super::*; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct MetaParent { pub vec: MetaCollection, } impl std::fmt::Display for MetaParent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.vec.parent_id)?; if self.vec.collection_id > 1 { write!(f, "+col={}", self.vec.collection_id)?; } Ok(()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/tests/trust-tree.rs
lib/tests/trust-tree.rs
#![cfg(any(feature = "enable_full"))] #![allow(unused_imports)] use ate::prelude::*; use names::Generator; use rust_decimal::prelude::*; use serde::{Deserialize, Serialize}; use tokio::runtime::Runtime; use tracing::{debug, error, info, warn}; #[derive(Debug, Serialize, Deserialize, Clone, Default)] struct Car { name: String, } #[derive(Debug, Serialize, Deserialize, Clone, Default)] struct Garage { cars: DaoVec<Car>, } #[cfg(any(feature = "enable_server", feature = "enable_client"))] #[cfg(feature = "enable_local_fs")] #[test] fn test_trust_tree_persistent() -> Result<(), AteError> { ate::utils::bootstrap_test_env(); #[cfg(feature = "enable_mt")] let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build()?; #[cfg(not(feature = "enable_mt"))] let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build()?; rt.block_on(async { info!("generating crypto keys"); let write_key = PrivateSignKey::generate(KeySize::Bit192); let write_key2 = PrivateSignKey::generate(KeySize::Bit256); let read_key = EncryptKey::generate(KeySize::Bit256); let root_public_key = write_key.as_public_key(); let mut conf = ConfAte::default(); conf.log_path = Some("/tmp/ate".to_string()); conf.log_format.meta = SerializationFormat::Json; conf.log_format.data = SerializationFormat::Json; let key1; { info!("building the session"); let mut session = AteSessionUser::new(); session .user .properties .push(AteSessionProperty::WriteKey(write_key.clone())); session .user .properties .push(AteSessionProperty::WriteKey(write_key2.clone())); session .user .properties .push(AteSessionProperty::ReadKey(read_key.clone())); session.identity = "author@here.com".to_string(); info!("creating the chain-of-trust"); let builder = ChainBuilder::new(&conf) .await .add_root_public_key(&root_public_key) .truncate(true) .build(); let chain = builder.open(&ChainKey::from("trust")).await?; info!("add the objects to the DIO"); let dio = chain.dio_mut(&session).await; let mut garage = dio.store(Garage::default())?; garage.auth_mut().read = ReadOption::from_key(&read_key); garage.auth_mut().write = WriteOption::Specific(write_key2.hash()); for n in 0..100 { let name = format!("Car {}", n).to_string(); let mut car = Car::default(); car.name = name.clone(); let car = garage.as_mut().cars.push(car)?; assert_eq!(car.name, name); } dio.commit().await?; drop(dio); key1 = garage.key().clone(); } { info!("building the session"); let mut session = AteSessionUser::new(); session .user .properties .push(AteSessionProperty::WriteKey(write_key2.clone())); session .user .properties .push(AteSessionProperty::ReadKey(read_key.clone())); session.identity = "author@here.com".to_string(); let chain = { info!("loading the chain-of-trust again"); let mut conf = ConfAte::default(); conf.log_path = Some("/tmp/ate".to_string()); conf.log_format.meta = SerializationFormat::Json; conf.log_format.data = SerializationFormat::Json; let builder = ChainBuilder::new(&conf) .await .add_root_public_key(&root_public_key) .build(); builder.open(&ChainKey::from("trust")).await? }; // Load the garage let dio = chain.dio(&session).await; let garage = dio.load::<Garage>(&key1).await?; assert_eq!(garage.cars.iter().await?.count(), 100); // Delete the chain chain.single().await.destroy().await.unwrap(); } Ok(()) }) } #[cfg(any(feature = "enable_server", feature = "enable_client"))] #[test] fn test_trust_tree_memory() -> Result<(), AteError> { ate::utils::bootstrap_test_env(); #[cfg(feature = "enable_mt")] let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build()?; #[cfg(not(feature = "enable_mt"))] let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build()?; rt.block_on(async { info!("generating crypto keys"); let write_key = PrivateSignKey::generate(KeySize::Bit192); let write_key2 = PrivateSignKey::generate(KeySize::Bit256); let read_key = EncryptKey::generate(KeySize::Bit256); let root_public_key = write_key.as_public_key(); let mut conf = ConfAte::default(); conf.log_format.meta = SerializationFormat::Json; conf.log_format.data = SerializationFormat::Json; let key1; { info!("building the session"); let mut session = AteSessionUser::new(); session .user .properties .push(AteSessionProperty::WriteKey(write_key.clone())); session .user .properties .push(AteSessionProperty::WriteKey(write_key2.clone())); session .user .properties .push(AteSessionProperty::ReadKey(read_key.clone())); session.identity = "author@here.com".to_string(); info!("creating the chain-of-trust"); let builder = ChainBuilder::new(&conf) .await .add_root_public_key(&root_public_key) .truncate(true) .build(); let chain = builder.open(&ChainKey::from("trust")).await?; info!("add the objects to the DIO"); let dio = chain.dio_mut(&session).await; let mut garage = dio.store(Garage::default())?; garage.auth_mut().read = ReadOption::from_key(&read_key); garage.auth_mut().write = WriteOption::Specific(write_key2.hash()); for n in 0..100 { let name = format!("Car {}", n).to_string(); let mut car = Car::default(); car.name = name.clone(); let car = garage.as_mut().cars.push(car)?; assert_eq!(car.name, name); } dio.commit().await?; drop(dio); key1 = garage.key().clone(); info!("building the session"); let mut session = AteSessionUser::new(); session .user .properties .push(AteSessionProperty::WriteKey(write_key2.clone())); session .user .properties .push(AteSessionProperty::ReadKey(read_key.clone())); session.identity = "author@here.com".to_string(); // Load the garage let dio = chain.dio(&session).await; let garage = dio.load::<Garage>(&key1).await?; assert_eq!(garage.cars.iter().await?.count(), 100); // Delete the chain chain.single().await.destroy().await.unwrap(); } Ok(()) }) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/tests/rotate.rs
lib/tests/rotate.rs
#![cfg(any(feature = "enable_full"))] #![allow(unused_imports)] use ate::prelude::*; #[cfg(feature = "enable_server")] #[cfg(feature = "enable_rotate")] #[test] fn rotate_test() -> Result<(), AteError> { ate::utils::bootstrap_test_env(); #[cfg(feature = "enable_mt")] let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build()?; #[cfg(not(feature = "enable_mt"))] let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build()?; rt.block_on(async { // The default configuration will store the redo log locally in the temporary folder let mut conf = ConfAte::default(); #[cfg(feature = "enable_local_fs")] { conf.log_path = Some("/tmp/ate".to_string()); } conf.configured_for(ConfiguredFor::BestPerformance); let builder = ChainBuilder::new(&conf).await.build(); let key1; let key2; { // We create a chain with a specific key (this is used for the file name it creates) let chain = builder.open(&ChainKey::from("rotate")).await?; let session = AteSessionUser::new(); { // Write a test object let dio = chain.dio_mut(&session).await; key1 = dio.store("blah!".to_string())?.key().clone(); dio.commit().await?; } // Rotate the log file chain.rotate().await?; { // Write a test object let dio = chain.dio_mut(&session).await; key2 = dio.store("haha!".to_string())?.key().clone(); dio.commit().await?; } let dio = chain.dio(&session).await; assert_eq!(*dio.load::<String>(&key1).await?, "blah!".to_string()); assert_eq!(*dio.load::<String>(&key2).await?, "haha!".to_string()); } { let chain = builder.open(&ChainKey::from("rotate")).await?; let session = AteSessionUser::new(); let dio = chain.dio(&session).await; assert_eq!(*dio.load::<String>(&key1).await?, "blah!".to_string()); assert_eq!(*dio.load::<String>(&key2).await?, "haha!".to_string()); chain.single().await.destroy().await.unwrap(); } Ok(()) }) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/tests/load.rs
lib/tests/load.rs
#![cfg(any(feature = "enable_server", feature = "enable_client"))] use ate::prelude::*; use serde::{Deserialize, Serialize}; use tracing::info; #[derive(Debug, Serialize, Deserialize, Clone)] struct MyTestObject { firstname: String, lastname: String, data1: [u8; 32], data2: [u8; 32], data3: [u8; 32], data4: Vec<u128>, } #[test] fn load_test() -> Result<(), AteError> { ate::utils::bootstrap_test_env(); #[cfg(feature = "enable_mt")] let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build()?; #[cfg(not(feature = "enable_mt"))] let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build()?; rt.block_on(async { // The default configuration will store the redo log locally in the temporary folder let mut conf = ConfAte::default(); conf.configured_for(ConfiguredFor::BestPerformance); let builder = ChainBuilder::new(&conf).await.build(); { // We create a chain with a specific key (this is used for the file name it creates) let chain = builder.open(&ChainKey::from("load")).await?; // Prepare let session = AteSessionUser::new(); let mut test_obj = MyTestObject { firstname: "Joe".to_string(), lastname: "Blogs".to_string(), data1: [0 as u8; 32], data2: [1 as u8; 32], data3: [2 as u8; 32], data4: Vec::new(), }; for _ in 0..100 { test_obj.data4.push(1234 as u128); } // Do a whole let of work info!("create::running"); for _ in 0..100 { let dio = chain.dio_mut(&session).await; for _ in 0..100 { dio.store(test_obj.clone())?; } dio.commit().await?; } info!("create::finished"); } { // We create a chain with a specific key (this is used for the file name it creates) info!("load::running"); let chain = builder.open(&ChainKey::from("load")).await?; info!("load::finished"); // Destroy the chain chain.single().await.destroy().await.unwrap(); } Ok(()) }) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/examples/service-api.rs
lib/examples/service-api.rs
use serde::{Deserialize, Serialize}; use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use ate::prelude::*; #[derive(Clone, Serialize, Deserialize)] struct Ping { msg: String, } #[derive(Serialize, Deserialize)] struct Pong { msg: String, } #[derive(Serialize, Deserialize, Debug)] struct PingError {} #[derive(Default)] struct PingPongTable {} impl PingPongTable { async fn process(self: Arc<Self>, ping: Ping) -> Result<Pong, PingError> { Ok(Pong { msg: ping.msg }) } } #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), AteError> { ate::log_init(0, true); info!("creating test chain"); // Create the chain with a public/private key to protect its integrity let conf = ConfAte::default(); let builder = ChainBuilder::new(&conf).await.build(); let chain = builder.open(&ChainKey::from("cmd")).await?; info!("start the service on the chain"); let session = AteSessionUser::new(); chain.add_service( &session, Arc::new(PingPongTable::default()), PingPongTable::process, ); info!("sending ping"); let pong: Result<Pong, PingError> = chain .invoke(Ping { msg: "hi".to_string(), }) .await?; let pong = pong.unwrap(); info!("received pong with msg [{}]", pong.msg); Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/examples/server-client.rs
lib/examples/server-client.rs
#![allow(unused_imports)] use ate::prelude::*; use serde::{Deserialize, Serialize}; use tracing::{debug, error, info, instrument, span, trace, warn, Level}; #[cfg(not(feature = "enable_server"))] fn main() {} #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), AteError> { ate::log_init(0, true); // Create the server and listen on port 5000 let url = url::Url::parse("ws://localhost:5000/test-chain").unwrap(); let cfg_ate = ConfAte::default(); #[cfg(feature = "enable_dns")] let cfg_mesh = ConfMesh::solo_from_url(&cfg_ate, &url, &IpAddr::from_str("::").unwrap(), None, None) .await?; #[cfg(not(feature = "enable_dns"))] let cfg_mesh = ConfMesh::solo_from_url(&cfg_ate, &url)?; info!("create a persistent server"); let server = create_persistent_centralized_server(&cfg_ate, &cfg_mesh).await?; info!("write some data to the server"); let key = { let registry = Registry::new(&cfg_ate).await.cement(); let chain = registry .open( &url::Url::from_str("ws://localhost:5000/").unwrap(), &ChainKey::from("test-chain"), false ) .await?; let session = AteSessionUser::new(); let dio = chain.dio_mut(&session).await; let dao = dio.store("my test string".to_string())?; dio.commit().await?; dao.key().clone() }; info!("read it back again on a new client"); { let registry = Registry::new(&cfg_ate).await.cement(); let chain = registry .open( &url::Url::from_str("ws://localhost:5000/").unwrap(), &ChainKey::from("test-chain"), false ) .await?; let session = AteSessionUser::new(); let dio = chain.dio(&session).await; let dao = dio.load::<String>(&key).await?; assert_eq!(*dao, "my test string".to_string()); } server.shutdown().await; Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/examples/hello-world.rs
lib/examples/hello-world.rs
use ate::prelude::*; use serde::{Deserialize, Serialize}; #[derive(Clone, Serialize, Deserialize)] struct World { commandment: String, } #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), AteError> { // The default configuration will store the redo log locally in the temporary folder let conf = ConfAte::default(); let builder = ChainBuilder::new(&conf).await.build(); // We create a chain with a specific key (this is used for the file name it creates) let chain = builder.open(&ChainKey::from("universe")).await?; // We interact with the data stored in the chain-of-trust using a DIO let session = AteSessionUser::new(); let dio = chain.dio_mut(&session).await; // In this example we store some data in the "World" object let key = dio .store(World { commandment: "Hello".to_string(), })? .key() .clone(); dio.commit().await?; // Now we retreive the data and print it to console println!("{} world!", dio.load::<World>(&key).await?.commandment); // All errors in ATE will convert into the AteError Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/examples/bus-or-queue.rs
lib/examples/bus-or-queue.rs
use ate::prelude::*; use serde::{Deserialize, Serialize}; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; #[derive(Debug, Clone, Serialize, Deserialize)] enum BallSound { Ping, Pong, } #[derive(Debug, Clone, Serialize, Deserialize)] struct Table { ball: DaoVec<BallSound>, } #[cfg(not(feature = "enable_server"))] fn main() {} #[cfg(feature = "enable_server")] #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), AteError> { ate::log_init(0, true); // Create the server and listen on port 5001 info!("setting up a mesh server on 127.0.0.1:5001"); let mesh_url = url::Url::parse("ws://localhost:5001/").unwrap(); let cfg_ate = ConfAte::default(); #[cfg(feature = "enable_dns")] let mut cfg_mesh = ConfMesh::solo( &cfg_ate, &IpAddr::from_str("127.0.0.1").unwrap(), None, "localhost".to_string(), 5001, None, ) .await?; #[cfg(not(feature = "enable_dns"))] let mut cfg_mesh = ConfMesh::solo("localhost".to_string(), 5001)?; let _root = create_ethereal_distributed_server(&cfg_ate, &cfg_mesh).await?; // Connect to the server from a client info!("connection two clients to the mesh server"); cfg_mesh.force_listen = None; cfg_mesh.force_client_only = true; let client_a = create_temporal_client(&cfg_ate, &cfg_mesh); let client_b = create_temporal_client(&cfg_ate, &cfg_mesh); // Create a session let session = AteSessionUser::new(); // Setup a BUS that we will listen on info!("opening a chain on called 'ping-pong-table' using client 1"); let chain_a = client_a .open(&mesh_url, &ChainKey::from("ping-pong-table")) .await .unwrap(); let (mut bus, key) = { info!("writing a record ('table') to the remote chain from client 1"); let dio = chain_a.dio_trans(&session, TransactionScope::Full).await; let dao = dio.store(Table { ball: DaoVec::default(), })?; dio.commit().await?; // Now attach a BUS that will simple write to the console info!("opening a communication bus on the record 'table' from client 1"); (dao.ball.bus().await?, dao.key().clone()) }; { // Write a ping... twice info!("connecting to the communication bus from client 2"); let chain_b = client_b .open( &url::Url::parse("ws://localhost:5001/").unwrap(), &ChainKey::from("ping-pong-table"), ) .await .unwrap(); chain_b.sync().await?; info!("writing two records ('balls') onto the earlier saved record 'table' from client 2"); let dio = chain_b.dio_trans(&session, TransactionScope::Full).await; let mut dao = dio.load::<Table>(&key).await?; dao.as_mut().ball.push(BallSound::Ping)?; dao.as_mut().ball.push(BallSound::Ping)?; dio.commit().await?; } // Process any events that were received on the BUS { let dio = chain_a.dio_trans(&session, TransactionScope::Full).await; // (this is a broadcast event to all current subscribers) info!("waiting for the first record on the BUS of client 1 which we will process as a broadcast"); let ret = bus.recv().await?; println!("{:?}", ret); // (this is an exactly once queue) info!("waiting for the second record on the BUS of client 1 which we will process as an (exactly-once) event"); let ret = bus.process(&dio).await?; println!("{:?}", ret); dio.commit().await?; } Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/examples/coin.rs
lib/examples/coin.rs
use ate::prelude::*; #[allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Serialize, Deserialize)] struct TrustedRecord { hidden_data: String, } #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), AteError> { // Make the keys that will protect the data let root = PrivateSignKey::generate(KeySize::Bit192); let ek = EncryptKey::generate(KeySize::Bit192); let sk = PrivateSignKey::generate(KeySize::Bit192); // Create the chain with a public/private key to protect its integrity let conf = ConfAte::default(); let builder = ChainBuilder::new(&conf) .await .add_root_public_key(&root.as_public_key()) .build(); let chain = builder.open(&ChainKey::from("universe")).await?; // Our session needs the keys let mut session = AteSessionUser::new(); session.add_user_write_key(&root); session.add_user_write_key(&sk); session.add_user_read_key(&ek); let key = { // Now create the data using the keys we have let dio = chain.dio_mut(&session).await; let mut dao = dio.store(TrustedRecord { hidden_data: "Secret data".to_string(), })?; dao.auth_mut().read = ReadOption::from_key(&ek); dao.auth_mut().write = WriteOption::Specific(sk.hash()); dio.commit().await?; dao.key().clone() }; // Build a new session that does not have the root key let mut session = AteSessionUser::new(); session.add_user_write_key(&sk); session.add_user_read_key(&ek); { // Only we can read or write this record (and anything attached to it) in the chain-of-trust let dio = chain.dio(&session).await; let _ = dio.load::<TrustedRecord>(&key).await?; } // All errors in ATE will convert into the AteError Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/lib/examples/bank.rs
lib/examples/bank.rs
use ate::prelude::*; use names::Generator; use rust_decimal::prelude::*; #[allow(unused_imports)] use serde::{Deserialize, Serialize}; use std::sync::Arc; #[derive(Debug, Serialize, Deserialize, Clone)] struct Person { first_name: String, last_name: String, } #[derive(Debug, Serialize, Deserialize, Clone)] struct Transaction { from: PrimaryKey, to: DaoWeak<Person>, description: String, amount: Decimal, } #[derive(Debug, Serialize, Deserialize, Clone)] struct Account { name: String, transactions: DaoVec<Transaction>, balance: Decimal, } async fn make_account<'a>( chain: &Arc<Chain>, generator: &mut Generator<'a>, ) -> Result<(), AteError> { let session = AteSessionUser::new(); let dio = chain.dio_mut(&session).await; let person = Person { first_name: generator.next().unwrap(), last_name: generator.next().unwrap(), }; let _person = dio.store(person).unwrap(); let acc = Account { name: "Current Account".to_string(), transactions: DaoVec::new(), balance: Decimal::default(), }; let mut acc = dio.store(acc).unwrap(); for _ in 0..10 { let trans = Transaction { to: DaoWeak::from_key(&dio, acc.key().clone()), from: PrimaryKey::generate(), description: generator.next().unwrap(), amount: Decimal::from_i64(10).unwrap(), }; acc.as_mut().transactions.push(trans).unwrap(); } dio.commit().await?; Ok(()) } #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), AteError> { ate::log_init(0, true); // The default configuration will store the redo log locally in the temporary folder let conf = ConfAte::default(); let builder = ChainBuilder::new(&conf).await.build(); // We create a chain with a specific key (this is used for the file name it creates) let chain = builder.open(&ChainKey::from("bank")).await?; // Make a thousand bank accounts let mut generator = Generator::default(); for _ in 0..200 { make_account(&chain, &mut generator).await?; } chain.flush().await.unwrap(); Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-web/build.rs
wasmer-web/build.rs
extern crate build_deps; fn main() { build_deps::rerun_if_changed_paths( "public/bin/*" ).unwrap(); build_deps::rerun_if_changed_paths( "public/*" ).unwrap(); build_deps::rerun_if_changed_paths( "public/bin" ).unwrap(); build_deps::rerun_if_changed_paths( "public" ).unwrap(); }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-web/src/lib.rs
wasmer-web/src/lib.rs
mod common; mod glue; mod interval; mod pool; mod system; mod ws; mod webgl; use wasmer_os::err; use wasmer_os::fd; use wasmer_os::tty; pub use glue::start;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-web/src/webgl.rs
wasmer-web/src/webgl.rs
use wasm_bindgen::prelude::*; use web_sys::WebGlTexture; use web_sys::WebGlVertexArrayObject; use web_sys::WebGlBuffer; use web_sys::WebGlUniformLocation; use web_sys::WebGlFramebuffer; use web_sys::{WebGl2RenderingContext, WebGlProgram, WebGlShader}; use wasmer_os::api::ProgramId; use wasmer_os::api::BufferId; use wasmer_os::api::VertexArrayId; use wasmer_os::api::TextureId; use wasmer_os::api::ShaderId; use wasmer_os::api::ProgramLocationId; use wasmer_os::api::UniformLocationId; use wasmer_os::api::ProgramParameterId; use wasmer_os::api::FrameBufferId; use wasmer_os::api::WebGlAbi; use wasmer_os::api::RenderingContextAbi; use wasmer_os::api::glenum::*; use wasmer_os::api::System; use wasmer_os::api::SystemAbiExt; use wasmer_os::api::AsyncResult; use wasmer_os::api::SerializationFormat; use wasmer_os::common::MAX_MPSC; use std::collections::HashMap; use std::convert::*; use tokio::sync::mpsc; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use super::glue::show_canvas; use super::glue::show_terminal; pub enum WebGlCommand { CreateProgram(ProgramId), CreateBuffer(BufferId), CreateVertexArray(VertexArrayId), CreateTexture(TextureId), BindBuffer { buffer: BufferId, kind: BufferKind }, UnbindBuffer { kind: BufferKind }, DeleteBuffer { buffer: BufferId }, DeleteTexture { texture: TextureId }, ActiveTexture { active: u32 }, BindTexture { texture: TextureId, target: TextureKind }, BindTextureCube { texture: TextureId, target: TextureKind }, UnbindTexture { target: u32 }, UnbindTextureCube { target: u32 }, FramebufferTexture2D { texture: TextureId, target: Buffers, attachment: Buffers, textarget: TextureBindPoint, level: i32 }, ClearColor { red: f32, green: f32, blue: f32, alpha: f32 }, Clear { bit: BufferBit }, ClearDepth { value: f32 }, DrawArrays { mode: Primitives, first: i32, count: i32 }, DrawElements { mode: Primitives, count: i32, kind: DataType, offset: u32 }, Enable { flag: Flag }, Disable { flag: Flag }, CullFace { culling: Culling }, DepthMask { val: bool }, DepthFunct { val: DepthTest }, Viewport { x: i32, y: i32, width: u32, height: u32 }, BufferData { kind: BufferKind, data: Vec<u8>, draw: DrawMode }, ReadPixels { x: u32, y: u32, width: u32, height: u32, format: PixelFormat, kind: PixelType, tx: mpsc::Sender<Result<Vec<u8>, String>> }, PixelStorei { storage: PixelStorageMode, value: i32 }, GenerateMipMap, GenerateMipMapCube, TexImage2D { target: TextureBindPoint, level: u8, width: u32, height: u32, format: PixelFormat, kind: PixelType, pixels: Vec<u8> }, TexSubImage2D { target: TextureBindPoint, level: u8, xoffset: u32, yoffset: u32, width: u32, height: u32, format: PixelFormat, kind: PixelType, pixels: Vec<u8> }, CompressedTexImage2D { target: TextureBindPoint, level: u8, compression: TextureCompression, width: u32, height: u32, data: Vec<u8> }, BlendEquation { eq: BlendEquation }, BlendFunc { b1: BlendMode, b2: BlendMode }, BlendColor { red: f32, green: f32, blue: f32, alpha: f32 }, TexParameteri { kind: TextureKind, pname: TextureParameter, param: i32 }, TexParameterfv { kind: TextureKind, pname: TextureParameter, param: f32 }, DrawBuffers { buffers: Vec<ColorBuffer> }, CreateFramebuffer(FrameBufferId), DeleteFramebuffer { framebuffer: FrameBufferId }, BindFramebuffer { framebuffer: FrameBufferId, buffer: Buffers }, UnbindFramebuffer { buffer: Buffers }, DeleteProgram { program: ProgramId }, LinkProgram { program: ProgramId, tx: mpsc::Sender<Result<(), String>> }, UseProgram { program: ProgramId }, GetAttribLocation { program: ProgramId, name: String, id: ProgramLocationId }, DeleteAttribLocation { id: ProgramLocationId }, GetUniformLocation { program: ProgramId, name: String, id: UniformLocationId }, GetProgramParameter { program: ProgramId, pname: ShaderParameter, id: ProgramParameterId }, VertexAttribPointer { location: ProgramLocationId, size: AttributeSize, kind: DataType, normalized: bool, stride: u32, offset: u32 }, EnableVertexAttribArray { location: ProgramLocationId }, DeleteVertexArray { vertex_array: VertexArrayId }, BindVertexArray { vertex_array: VertexArrayId }, UnbindVertexArray, UniformMatrix4fv { location: UniformLocationId, transpose: bool, value: [[f32; 4]; 4] }, UniformMatrix3fv { location: UniformLocationId, transpose: bool, value: [[f32; 3]; 3] }, UniformMatrix2fv { location: UniformLocationId, transpose: bool, value: [[f32; 2]; 2] }, Uniform1i { location: UniformLocationId, value: i32 }, Uniform1f { location: UniformLocationId, value: f32 }, Uniform2f { location: UniformLocationId, value: (f32, f32) }, Uniform3f { location: UniformLocationId, value: (f32, f32, f32) }, Uniform4f { location: UniformLocationId, value: (f32, f32, f32, f32) }, CreateShader { kind: ShaderKind, id: ShaderId }, DeleteShader { shader: ShaderId }, ShaderSource { shader: ShaderId, source: String }, ShaderCompile { shader: ShaderId, tx: mpsc::Sender<Result<(), String>> }, AttachShader { program: ProgramId, shader: ShaderId, tx: mpsc::Sender<Result<(), String>> }, ShowCanvas, ShowTerminal, Sync { tx: mpsc::Sender<()> }, } pub struct WebGl { tx: mpsc::Sender<WebGlCommand>, } impl WebGl { pub fn new(tx: &mpsc::Sender<WebGlCommand>) -> WebGl { WebGl { tx: tx.clone(), } } } impl WebGlAbi for WebGl { fn context(&self) -> Box<dyn RenderingContextAbi> { let ctx = GlContext::new(&self.tx); Box::new(ctx) } } #[allow(dead_code)] type Reference = i32; pub struct GlContextInner { ctx: WebGl2RenderingContext, programs: HashMap<ProgramId, WebGlProgram>, buffers: HashMap<BufferId, WebGlBuffer>, vertex_arrays: HashMap<VertexArrayId, WebGlVertexArrayObject>, textures: HashMap<TextureId, WebGlTexture>, shaders: HashMap<ShaderId, WebGlShader>, uniform_locations: HashMap<UniformLocationId, WebGlUniformLocation>, program_parameters: HashMap<ProgramParameterId, JsValue>, program_locations: HashMap<ProgramLocationId, i32>, framebuffers: HashMap<FrameBufferId, WebGlFramebuffer>, } impl GlContextInner { pub fn new(ctx: WebGl2RenderingContext) -> GlContextInner { GlContextInner { ctx, programs: HashMap::default(), buffers: HashMap::default(), vertex_arrays: HashMap::default(), textures: HashMap::default(), shaders: HashMap::default(), uniform_locations: HashMap::default(), program_parameters: HashMap::default(), program_locations: HashMap::default(), framebuffers: HashMap::default(), } } } pub struct GlContext { tx: mpsc::Sender<WebGlCommand>, } impl GlContext { pub fn init(webgl2: WebGl2RenderingContext) -> mpsc::Sender<WebGlCommand> { let (webgl_tx, mut webgl_rx) = mpsc::channel(MAX_MPSC); { wasm_bindgen_futures::spawn_local(async move { let mut inner = GlContextInner::new(webgl2); while let Some(cmd) = webgl_rx.recv().await { GlContext::process(&mut inner, cmd).await; } }) } webgl_tx } pub fn new(tx: &mpsc::Sender<WebGlCommand>) -> GlContext { System::default().fire_and_forget(&tx, WebGlCommand::ShowCanvas); GlContext { tx: tx.clone() } } pub async fn process(inner: &mut GlContextInner, cmd: WebGlCommand) { match cmd { WebGlCommand::CreateProgram(id) => { if let Some(r) = inner.ctx.create_program() { inner.programs.insert(id, r); } else { warn!("failed to create program"); } }, WebGlCommand::CreateBuffer(id) => { if let Some(r) = inner.ctx.create_buffer() { inner.buffers.insert(id, r); } else { warn!("failed to create buffer"); } }, WebGlCommand::CreateVertexArray(id) => { if let Some(r) = inner.ctx.create_vertex_array() { inner.vertex_arrays.insert(id, r); } else { warn!("failed to create vertex array"); } }, WebGlCommand::CreateTexture(id) => { if let Some(r) = inner.ctx.create_texture() { inner.textures.insert(id, r); } else { warn!("failed to create texture"); } }, WebGlCommand::BindBuffer { buffer, kind } => { let buffer = inner.buffers.get(&buffer); inner.ctx.bind_buffer(kind as u32, buffer); }, WebGlCommand::UnbindBuffer { kind } => { inner.ctx.bind_buffer(kind as u32, None); }, WebGlCommand::DeleteBuffer { buffer: buffer_id } => { let buffer = inner.buffers.remove(&buffer_id); if buffer.is_some() { inner.ctx.delete_buffer(buffer.as_ref()); } else { warn!("orphaned buffer - {}", buffer_id); } }, WebGlCommand::DeleteTexture { texture: texture_id } => { let texture = inner.textures.remove(&texture_id); if texture.is_some() { inner.ctx.delete_texture(texture.as_ref()); } else { warn!("orphaned texture - {}", texture_id); } }, WebGlCommand::ActiveTexture { active } => { inner.ctx.active_texture(active); }, WebGlCommand::BindTexture { texture, target } => { let texture = inner.textures.get(&texture); inner.ctx.bind_texture(target as u32, texture); }, WebGlCommand::BindTextureCube { texture, target } => { let texture = inner.textures.get(&texture); inner.ctx.bind_texture(target as u32, texture); }, WebGlCommand::UnbindTexture { target } => { inner.ctx.bind_texture(target, None); }, WebGlCommand::UnbindTextureCube { target } => { inner.ctx.bind_texture(target, None); }, WebGlCommand::FramebufferTexture2D { texture, target, attachment, textarget, level } => { let texture = inner.textures.get(&texture); inner.ctx.framebuffer_texture_2d(target as u32, attachment as u32, textarget as u32, texture, level); }, WebGlCommand::ClearColor { red, green, blue, alpha } => { inner.ctx.clear_color(red, green, blue, alpha); }, WebGlCommand::Clear { bit } => { inner.ctx.clear(bit as u32); }, WebGlCommand::ClearDepth { value } => { inner.ctx.clear_depth(value); }, WebGlCommand::DrawArrays { mode, first, count } => { inner.ctx.draw_arrays(mode as u32, first, count); }, WebGlCommand::DrawElements { mode, count, kind, offset } => { inner.ctx.draw_elements_with_i32(mode as u32, count, kind as u32, offset as i32); }, WebGlCommand::Enable { flag } => { inner.ctx.enable(flag as u32); }, WebGlCommand::Disable { flag } => { inner.ctx.disable(flag as u32); }, WebGlCommand::CullFace { culling } => { inner.ctx.cull_face(culling as u32); }, WebGlCommand::DepthMask { val } => { inner.ctx.depth_mask(val); }, WebGlCommand::DepthFunct { val } => { inner.ctx.depth_func(val as u32); }, WebGlCommand::Viewport { x, y, width, height } => { inner.ctx.viewport(x, y, width as i32, height as i32); }, WebGlCommand::BufferData { kind, data, draw } => { inner.ctx.buffer_data_with_u8_array(kind as u32, &data[..], draw as u32); }, WebGlCommand::ReadPixels { x, y, width, height, format, kind, tx } => { let multiplier = match format { PixelFormat::DepthComponent => 1, PixelFormat::Alpha => 1, PixelFormat::Rgb => 3, PixelFormat::Rgba => 4, PixelFormat::Luminance => 1, PixelFormat::LuminanceAlpha => 1, }; let unit_size: usize = match (kind, format) { (PixelType::UnsignedByte, _) => multiplier, (PixelType::UnsignedShort4444, PixelFormat::Rgba) => 2, (PixelType::UnsignedShort5551, PixelFormat::Rgba) => 2, (PixelType::UnsignedShort565, PixelFormat::Rgb) => 2, (PixelType::UnsignedShort, _) => multiplier * 2, (PixelType::UnsignedInt, _) => multiplier * 4, (PixelType::UnsignedInt24, _) => multiplier * 3, (PixelType::Float, _) => multiplier * 4, (_, _) => { let _ = tx.send(Err("invalid pixel type".to_string())).await; return; } }; let size = (width as usize) * (height as usize) * unit_size; let mut data = vec![0u8; size]; let ret = inner.ctx .read_pixels_with_opt_u8_array(x as i32, y as i32, width as i32, height as i32, format as u32, kind as u32, Some(&mut data[..])) .map_err(|err| err.as_string().unwrap_or_else(|| format!("{:?}", err))); let ret = ret.map(|_| data); let _ = tx.send(ret).await; }, WebGlCommand::PixelStorei { storage, value } => { inner.ctx.pixel_storei(storage as u32, value as i32); }, WebGlCommand::GenerateMipMap => { inner.ctx.generate_mipmap(WebGl2RenderingContext::TEXTURE_2D); }, WebGlCommand::GenerateMipMapCube => { inner.ctx.generate_mipmap(WebGl2RenderingContext::TEXTURE_CUBE_MAP) }, WebGlCommand::TexImage2D { target, level, width, height, format, kind, pixels } => { let _ = inner.ctx.tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_u8_array(target as u32, level as i32, format as i32, width as i32, height as i32, 0, format as u32, kind as u32, Some(&pixels[..])); }, WebGlCommand::TexSubImage2D { target, level, xoffset, yoffset, width, height, format, kind, pixels } => { let _ = inner.ctx.tex_sub_image_2d_with_i32_and_i32_and_u32_and_type_and_opt_u8_array(target as u32, level as i32, xoffset as i32, yoffset as i32, width as i32, height as i32, format as u32, kind as u32, Some(&pixels[..])); }, WebGlCommand::CompressedTexImage2D { target, level, compression, width, height, data: pixels } => { inner.ctx.compressed_tex_image_2d_with_u8_array(target as u32, level as i32, compression as u32, width as i32, height as i32, 0, &pixels[..]); }, WebGlCommand::BlendEquation { eq } => { inner.ctx.blend_equation(eq as u32); }, WebGlCommand::BlendFunc { b1, b2 } => { inner.ctx.blend_func(b1 as u32, b2 as u32); }, WebGlCommand::BlendColor { red, green, blue, alpha } => { inner.ctx.blend_color(red, green, blue, alpha); }, WebGlCommand::TexParameteri { kind, pname, param } => { inner.ctx.tex_parameteri(kind as u32, pname as u32, param); }, WebGlCommand::TexParameterfv { kind, pname, param } => { inner.ctx.tex_parameterf(kind as u32, pname as u32, param); }, WebGlCommand::DrawBuffers { buffers } => { let vals = js_sys::Array::new(); for cb in buffers { let cb = cb as u32; vals.push(&wasm_bindgen::JsValue::from(cb)); } inner.ctx.draw_buffers(&vals); }, WebGlCommand::CreateFramebuffer( id ) => { if let Some(r) = inner.ctx.create_framebuffer() { inner.framebuffers.insert(id, r); } else { warn!("failed to create frame buffer"); } }, WebGlCommand::DeleteFramebuffer { framebuffer: framebuffer_id } => { let framebuffer = inner.framebuffers.remove(&framebuffer_id); if framebuffer.is_some() { inner.ctx.delete_framebuffer(framebuffer.as_ref()); } else { warn!("orphaned frame buffer - {}", framebuffer_id); } }, WebGlCommand::BindFramebuffer { framebuffer, buffer } => { let framebuffer = inner.framebuffers.get(&framebuffer); inner.ctx.bind_framebuffer(buffer as u32, framebuffer); }, WebGlCommand::UnbindFramebuffer { buffer } => { inner.ctx.bind_framebuffer(buffer as u32, None); }, WebGlCommand::DeleteProgram { program: program_id } => { let program = inner.programs.remove(&program_id); if program.is_some() { inner.ctx.delete_program(program.as_ref()); } else { warn!("orphaned program - {}", program_id); } }, WebGlCommand::LinkProgram { program, tx } => { let program = inner.programs.get(&program); if let Some(program) = program { inner.ctx.link_program(program); if inner.ctx .get_program_parameter(program, WebGl2RenderingContext::LINK_STATUS) .as_bool() .unwrap_or(false) { let _ = tx.send(Ok(())).await; } else { let err = inner.ctx.get_program_info_log(program); let err = err.unwrap_or_else(|| "Unknown error creating program object".to_string()); let _ = tx.send(Err(err)).await; } } else { let _ = tx.send(Err("Invalid program ID".to_string())).await; } }, WebGlCommand::UseProgram { program } => { let program = inner.programs.get(&program); inner.ctx.use_program(program); }, WebGlCommand::GetAttribLocation { program: program_id, name, id } => { let program = inner.programs.get(&program_id); if let Some(program) = program { let location = inner.ctx.get_attrib_location(program, name.as_str()); inner.program_locations.insert(id, location); } else { warn!("orphaned program - {}", program_id) } }, WebGlCommand::DeleteAttribLocation { id } => { inner.program_locations.remove(&id); } WebGlCommand::GetUniformLocation { program: program_id, name, id } => { let program = inner.programs.get(&program_id); if let Some(program) = program { if let Some(r) = inner.ctx.get_uniform_location(program, name.as_str()) { inner.uniform_locations.insert(id, r); } else { warn!("failed to get uniform location"); } } else { warn!("orphaned program - {}", program_id) } }, WebGlCommand::GetProgramParameter { program: program_id, pname, id } => { let program = inner.programs.get(&program_id); if let Some(program) = program { let r = inner.ctx.get_program_parameter(program, pname as u32); if r.is_null() == false && r.is_undefined() == false { inner.program_parameters.insert(id, r); } else { warn!("failed to get program parameter"); } } else { warn!("orphaned program - {}", program_id) } }, WebGlCommand::VertexAttribPointer { location: location_id, size, kind, normalized, stride, offset } => { let location = inner.program_locations.get(&location_id); if let Some(location) = location { inner.ctx.vertex_attrib_pointer_with_i32(*location as u32, size as i32, kind as u32, normalized, stride as i32, offset as i32); } else { warn!("orphaned program location - {}", location_id) } }, WebGlCommand::EnableVertexAttribArray { location: location_id } => { let location = inner.program_locations.get(&location_id); if let Some(location) = location { inner.ctx.enable_vertex_attrib_array(*location as u32); } else { warn!("orphaned program location - {}", location_id) } }, WebGlCommand::DeleteVertexArray { vertex_array: vertex_array_id } => { let vertex_array = inner.vertex_arrays.remove(&vertex_array_id); if vertex_array.is_some() { inner.ctx.delete_vertex_array(vertex_array.as_ref()); } else { warn!("orphaned vertex array - {}", vertex_array_id); } }, WebGlCommand::BindVertexArray { vertex_array } => { let vertex_array = inner.vertex_arrays.get(&vertex_array); inner.ctx.bind_vertex_array(vertex_array); }, WebGlCommand::UnbindVertexArray => { inner.ctx.bind_vertex_array(None); }, WebGlCommand::UniformMatrix4fv { location: location_id, transpose, value } => { let location = inner.uniform_locations.get(&location_id); if let Some(location) = location { unsafe { let array = std::mem::transmute::<&[[f32; 4]; 4], &[f32; 16]>(&value) as &[f32]; inner.ctx.uniform_matrix4fv_with_f32_array(Some(location), transpose, array); } } else { warn!("orphaned location - {}", location_id); } }, WebGlCommand::UniformMatrix3fv { location: location_id, transpose, value } => { let location = inner.uniform_locations.get(&location_id); if let Some(location) = location { unsafe { let array = std::mem::transmute::<&[[f32; 3]; 3], &[f32; 9]>(&value) as &[f32]; inner.ctx.uniform_matrix3fv_with_f32_array(Some(location), transpose, array); } } else { warn!("orphaned location - {}", location_id); } }, WebGlCommand::UniformMatrix2fv { location: location_id, transpose, value } => { let location = inner.uniform_locations.get(&location_id); if let Some(location) = location { unsafe { let array = std::mem::transmute::<&[[f32; 2]; 2], &[f32; 4]>(&value) as &[f32]; inner.ctx.uniform_matrix2fv_with_f32_array(Some(location), transpose, array); } } else { warn!("orphaned location - {}", location_id); } }, WebGlCommand::Uniform1i { location, value } => { let location = inner.uniform_locations.get(&location); inner.ctx.uniform1i(location, value); }, WebGlCommand::Uniform1f { location, value } => { let location = inner.uniform_locations.get(&location); inner.ctx.uniform1f(location, value); }, WebGlCommand::Uniform2f { location, value } => { let location = inner.uniform_locations.get(&location); inner.ctx.uniform2f(location, value.0, value.1); }, WebGlCommand::Uniform3f { location, value } => { let location = inner.uniform_locations.get(&location); inner.ctx.uniform3f(location, value.0, value.1, value.2); }, WebGlCommand::Uniform4f { location, value } => { let location = inner.uniform_locations.get(&location); inner.ctx.uniform4f(location, value.0, value.1, value.2, value.3); }, WebGlCommand::CreateShader { kind, id } => { if let Some(r) = inner.ctx.create_shader(kind as u32) { inner.shaders.insert(id, r); } else { warn!("failed to create shader"); } }, WebGlCommand::DeleteShader { shader: shader_id } => { let shader = inner.shaders.remove(&shader_id); if shader.is_some() { inner.ctx.delete_shader(shader.as_ref()); } else { warn!("orphaned shader - {}", shader_id); } }, WebGlCommand::ShaderSource { shader: shader_id, source } => { let shader = inner.shaders.get(&shader_id); if let Some(shader) = shader { inner.ctx.shader_source(shader, source.as_str()); } else { warn!("orphaned shader - {}", shader_id); } }, WebGlCommand::ShaderCompile { shader, tx } => { let shader = inner.shaders.get(&shader); if let Some(shader) = shader { inner.ctx.compile_shader(shader); if inner.ctx .get_shader_parameter(shader, WebGl2RenderingContext::COMPILE_STATUS) .as_bool() .unwrap_or(false) { let _ = tx.send(Ok(())).await; } else { let err = inner.ctx.get_shader_info_log(shader); let err = err.unwrap_or_else(|| "Unknown error compiling the shader".to_string()); let _ = tx.send(Err(err)).await; } } else { let _ = tx.send(Err("The shader is not valid".to_string())).await; } }, WebGlCommand::AttachShader { program, shader, tx } => { let program = inner.programs.get(&program); let shader = inner.shaders.get(&shader); if let (Some(program), Some(shader)) = (program, shader) { inner.ctx.attach_shader(program, shader); let _ = tx.send(Ok(())).await; } else { let _ = tx.send(Err("The shader is not valid".to_string())).await; } }, WebGlCommand::ShowCanvas => { show_canvas(); } WebGlCommand::ShowTerminal => { show_terminal(); } WebGlCommand::Sync { tx } => { let _ = tx.send(()).await; }, }; } } impl RenderingContextAbi for GlContext { fn create_program(&self) -> ProgramId { let id = ProgramId::new(); System::default().fire_and_forget(&self.tx, WebGlCommand::CreateProgram(id)); id } fn create_buffer(&self) -> BufferId { let id = BufferId::new(); System::default().fire_and_forget(&self.tx, WebGlCommand::CreateBuffer(id)); id } fn create_vertex_array(&self) -> VertexArrayId { let id = VertexArrayId::new(); System::default().fire_and_forget(&self.tx, WebGlCommand::CreateVertexArray(id)); id } fn create_texture(&self) -> TextureId { let id = TextureId::new(); System::default().fire_and_forget(&self.tx, WebGlCommand::CreateTexture(id)); id } fn bind_buffer(&self, buffer: BufferId, kind: BufferKind) { System::default().fire_and_forget(&self.tx, WebGlCommand::BindBuffer { buffer, kind }); } fn delete_buffer(&self, buffer: BufferId) { System::default().fire_and_forget(&self.tx, WebGlCommand::DeleteBuffer { buffer }); } fn delete_texture(&self, texture: TextureId) { System::default().fire_and_forget(&self.tx, WebGlCommand::DeleteTexture { texture }); } fn active_texture(&self, active: u32) { System::default().fire_and_forget(&self.tx, WebGlCommand::ActiveTexture { active }); } fn bind_texture(&self, texture: TextureId, target: TextureKind) { System::default().fire_and_forget(&self.tx, WebGlCommand::BindTexture { texture, target }); } fn bind_texture_cube(&self, texture: TextureId, target: TextureKind) { System::default().fire_and_forget(&self.tx, WebGlCommand::BindTextureCube { texture, target }); } fn framebuffer_texture2d(&self, texture: TextureId, target: Buffers, attachment: Buffers, textarget: TextureBindPoint, level: i32) { System::default().fire_and_forget(&self.tx, WebGlCommand::FramebufferTexture2D { texture, target, attachment, textarget, level }); } fn clear_color(&self, red: f32, green: f32, blue: f32, alpha: f32) { System::default().fire_and_forget(&self.tx, WebGlCommand::ClearColor { red, green, blue, alpha }); } fn clear(&self, bit: BufferBit) { System::default().fire_and_forget(&self.tx, WebGlCommand::Clear { bit }); } fn clear_depth(&self, value: f32) { System::default().fire_and_forget(&self.tx, WebGlCommand::ClearDepth { value }); } fn draw_arrays(&self, mode: Primitives, first: i32, count: i32) { System::default().fire_and_forget(&self.tx, WebGlCommand::DrawArrays { mode, first, count }); } fn draw_elements(&self, mode: Primitives, count: i32, kind: DataType, offset: u32) { System::default().fire_and_forget(&self.tx, WebGlCommand::DrawElements { mode, count, kind, offset }); } fn enable(&self, flag: Flag) { System::default().fire_and_forget(&self.tx, WebGlCommand::Enable { flag }); } fn disable(&self, flag: Flag) { System::default().fire_and_forget(&self.tx, WebGlCommand::Disable { flag }); } fn cull_face(&self, culling: Culling) { System::default().fire_and_forget(&self.tx, WebGlCommand::CullFace { culling }); } fn depth_mask(&self, val: bool) { System::default().fire_and_forget(&self.tx, WebGlCommand::DepthMask { val }); } fn depth_funct(&self, val: DepthTest) { System::default().fire_and_forget(&self.tx, WebGlCommand::DepthFunct { val }); } fn viewport(&self, x: i32, y: i32, width: u32, height: u32) { System::default().fire_and_forget(&self.tx, WebGlCommand::Viewport { x, y, width, height }); } fn buffer_data(&self, kind: BufferKind, data: Vec<u8>, draw: DrawMode) { System::default().fire_and_forget(&self.tx, WebGlCommand::BufferData { kind, data, draw }); } fn unbind_buffer(&self, kind: BufferKind) { System::default().fire_and_forget(&self.tx, WebGlCommand::UnbindBuffer { kind }); } fn read_pixels(&self, x: u32, y: u32, width: u32, height: u32, format: PixelFormat, kind: PixelType, serialization_format: SerializationFormat) -> AsyncResult<Result<Vec<u8>, String>> {
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
true
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-web/src/glue.rs
wasmer-web/src/glue.rs
use chrono::prelude::*; use wasmer_os::bin_factory::CachedCompiledModules; use std::sync::Arc; use wasmer_os::api::*; use wasmer_os::common::MAX_MPSC; use wasmer_os::console::Console; use tokio::sync::mpsc; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::HtmlCanvasElement; use web_sys::KeyboardEvent; use web_sys::WebGl2RenderingContext; #[allow(unused_imports)] use xterm_js_rs::addons::fit::FitAddon; #[allow(unused_imports)] use xterm_js_rs::addons::web_links::WebLinksAddon; #[allow(unused_imports)] use xterm_js_rs::addons::webgl::WebglAddon; use xterm_js_rs::Theme; use xterm_js_rs::{LogLevel, OnKeyEvent, Terminal, TerminalOptions}; use crate::system::TerminalCommand; use crate::system::WebConsole; use crate::system::WebSystem; use super::common::*; use super::pool::*; #[macro_export] #[doc(hidden)] macro_rules! csi { ($( $l:expr ),*) => { concat!("\x1B[", $( $l ),*) }; } #[wasm_bindgen(start)] pub fn main() { //let _ = console_log::init_with_level(log::Level::Debug); set_panic_hook(); } #[derive(Debug)] pub enum InputEvent { Key(KeyboardEvent), Data(String), } #[wasm_bindgen] pub fn start() -> Result<(), JsValue> { #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = navigator, js_name = userAgent)] static USER_AGENT: String; } //ate::log_init(0i32, false); tracing_wasm::set_as_global_default_with_config( tracing_wasm::WASMLayerConfigBuilder::new() .set_report_logs_in_timings(false) .set_max_level(tracing::Level::TRACE) .build(), ); info!("glue::start"); let terminal = Terminal::new( TerminalOptions::new() .with_log_level(LogLevel::Info) .with_rows(50) .with_cursor_blink(true) .with_cursor_width(10) .with_font_size(16u32) .with_draw_bold_text_in_bright_colors(true) .with_right_click_selects_word(true) .with_theme(&Theme::new()), ); let window = web_sys::window().unwrap(); let location = window.location().href().unwrap(); let user_agent = USER_AGENT.clone(); let is_mobile = wasmer_os::common::is_mobile(&user_agent); debug!("user_agent: {}", user_agent); let elem = window .document() .unwrap() .get_element_by_id("terminal") .unwrap(); terminal.open(elem.clone().dyn_into()?); let (term_tx, mut term_rx) = mpsc::channel(MAX_MPSC); { let terminal: Terminal = terminal.clone().dyn_into().unwrap(); wasm_bindgen_futures::spawn_local(async move { while let Some(cmd) = term_rx.recv().await { match cmd { TerminalCommand::Print(text) => { terminal.write(text.as_str()); } TerminalCommand::ConsoleRect(tx) => { let _ = tx .send(ConsoleRect { cols: terminal.get_cols(), rows: terminal.get_rows(), }) .await; } TerminalCommand::Cls => { terminal.clear(); } } } }); } let front_buffer = window .document() .unwrap() .get_element_by_id("frontBuffer") .unwrap(); let front_buffer: HtmlCanvasElement = front_buffer .dyn_into::<HtmlCanvasElement>() .map_err(|_| ()) .unwrap(); let webgl2 = front_buffer .get_context("webgl2")? .unwrap() .dyn_into::<WebGl2RenderingContext>()?; let pool = WebThreadPool::new_with_max_threads().unwrap(); let web_system = WebSystem::new(pool.clone(), webgl2); let web_console = WebConsole::new(term_tx); wasmer_os::api::set_system_abi(web_system); let system = System::default(); let compiled_modules = Arc::new(CachedCompiledModules::new(None)); let fs = wasmer_os::fs::create_root_fs(None); let mut console = Console::new( location, user_agent, wasmer_os::eval::Compiler::Browser, Arc::new(web_console), None, fs, compiled_modules, ); let tty = console.tty().clone(); let (tx, mut rx) = mpsc::channel(MAX_MPSC); let tx_key = tx.clone(); let callback = { Closure::wrap(Box::new(move |e: OnKeyEvent| { let event = e.dom_event(); tx_key.blocking_send(InputEvent::Key(event)).unwrap(); }) as Box<dyn FnMut(_)>) }; terminal.on_key(callback.as_ref().unchecked_ref()); callback.forget(); let tx_data = tx.clone(); let callback = { Closure::wrap(Box::new(move |data: String| { tx_data.blocking_send(InputEvent::Data(data)).unwrap(); }) as Box<dyn FnMut(_)>) }; terminal.on_data(callback.as_ref().unchecked_ref()); callback.forget(); /* { let addon = FitAddon::new(); terminal.load_addon(addon.clone().dyn_into::<FitAddon>()?.into()); addon.fit(); } */ /* { let addon = WebLinksAddon::new(); terminal.load_addon(addon.clone().dyn_into::<WebLinksAddon>()?.into()); addon.fit(); } */ /* { let addon = WebglAddon::new(None); terminal.load_addon(addon.clone().dyn_into::<WebglAddon>()?.into()); } */ { let front_buffer: HtmlCanvasElement = front_buffer.clone().dyn_into().unwrap(); let terminal: Terminal = terminal.clone().dyn_into().unwrap(); term_fit(terminal, front_buffer); } { let front_buffer: HtmlCanvasElement = front_buffer.clone().dyn_into().unwrap(); let terminal: Terminal = terminal.clone().dyn_into().unwrap(); let closure = { Closure::wrap(Box::new(move || { let front_buffer: HtmlCanvasElement = front_buffer.clone().dyn_into().unwrap(); let terminal: Terminal = terminal.clone().dyn_into().unwrap(); term_fit( terminal.clone().dyn_into().unwrap(), front_buffer.clone().dyn_into().unwrap(), ); let tty = tty.clone(); system.fork_local(async move { let cols = terminal.get_cols(); let rows = terminal.get_rows(); tty.set_bounds(cols, rows).await; }); }) as Box<dyn FnMut()>) }; window.add_event_listener_with_callback("resize", closure.as_ref().unchecked_ref())?; window.add_event_listener_with_callback( "orientationchange", closure.as_ref().unchecked_ref(), )?; closure.forget(); } terminal.focus(); system.fork_local(async move { console.init().await; crate::glue::show_terminal(); let mut last = None; while let Some(event) = rx.recv().await { match event { InputEvent::Key(event) => { console .on_key( event.key_code(), event.key(), event.alt_key(), event.ctrl_key(), event.meta_key(), ) .await; } InputEvent::Data(data) => { // Due to a nasty bug in xterm.js on Android mobile it sends the keys you press // twice in a row with a short interval between - this hack will avoid that bug if is_mobile { let now: DateTime<Local> = Local::now(); let now = now.timestamp_millis(); if let Some((what, when)) = last { if what == data && now - when < 200 { last = None; continue; } } last = Some((data.clone(), now)) } console.on_data(data).await; } } } }); Ok(()) } #[wasm_bindgen(module = "/js/fit.ts")] extern "C" { #[wasm_bindgen(js_name = "termFit")] fn term_fit(terminal: Terminal, front: HtmlCanvasElement); } #[wasm_bindgen(module = "/js/gl.js")] extern "C" { #[wasm_bindgen(js_name = "showTerminal")] pub fn show_terminal(); #[wasm_bindgen(js_name = "showCanvas")] pub fn show_canvas(); }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-web/src/system.rs
wasmer-web/src/system.rs
use async_trait::async_trait; use js_sys::Promise; use wasmer_os::wasmer::Module; use wasmer_os::wasmer::Store; use wasmer_os::wasmer::vm::VMMemory; use wasmer_os::wasmer_wasi::WasiThreadError; use std::future::Future; use std::pin::Pin; use wasmer_os::api::abi::SystemAbi; use tokio::sync::mpsc; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::*; use web_sys::WebGl2RenderingContext; use super::common::*; use super::pool::WebThreadPool; use super::ws::WebSocket; use wasmer_os::api::*; use super::webgl::WebGl; use super::webgl::GlContext; use super::webgl::WebGlCommand; pub(crate) enum TerminalCommand { Print(String), ConsoleRect(mpsc::Sender<ConsoleRect>), Cls, } pub(crate) struct WebSystem { pool: WebThreadPool, webgl_tx: mpsc::Sender<WebGlCommand>, } impl WebSystem { pub(crate) fn new(pool: WebThreadPool, webgl2: WebGl2RenderingContext) -> WebSystem { let webgl_tx = GlContext::init(webgl2); WebSystem { pool, webgl_tx, } } } #[async_trait] impl SystemAbi for WebSystem { fn task_shared( &self, task: Box< dyn FnOnce() -> Pin<Box<dyn Future<Output = ()> + Send + 'static>> + Send + 'static, >, ) { self.pool.spawn_shared(Box::new(move || { Box::pin(async move { let fut = task(); fut.await; }) })); } fn task_wasm( &self, task: Box<dyn FnOnce(Store, Module, Option<VMMemory>) -> Pin<Box<dyn Future<Output = ()> + 'static>> + Send + 'static>, store: Store, module: Module, spawn_type: SpawnType, ) -> Result<(), WasiThreadError> { let run = move |store, module, memory| { task(store, module, memory) }; let module_bytes = module.serialize().unwrap(); self.pool.spawn_wasm(run, store, module_bytes, spawn_type) } fn task_dedicated( &self, task: Box<dyn FnOnce() + Send + 'static>, ) { self.pool.spawn_dedicated(task); } fn task_dedicated_async( &self, task: Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = ()> + 'static>> + Send + 'static>, ) { self.pool.spawn_dedicated_async(task); } fn task_local(&self, task: Pin<Box<dyn Future<Output = ()> + 'static>>) { wasm_bindgen_futures::spawn_local(async move { task.await; }); } fn sleep(&self, ms: u128) -> AsyncResult<()> { let ms = ms as i32; let (tx, rx) = mpsc::channel(1); self.pool.spawn_shared(Box::new(move || { Box::pin(async move { let promise = sleep(ms); let js_fut = JsFuture::from(promise); let _ = js_fut.await; let _ = tx.send(()).await; }) })); AsyncResult::new(SerializationFormat::Json, rx) } fn fetch_file(&self, path: &str) -> AsyncResult<Result<Vec<u8>, u32>> { let url = path.to_string(); let headers = vec![("Accept".to_string(), "application/wasm".to_string())]; let (tx, rx) = mpsc::channel(1); self.pool.spawn_shared(Box::new(move || { Box::pin(async move { let ret = crate::common::fetch_data(url.as_str(), "GET", false, None, headers, None).await; let _ = tx.send(ret).await; }) })); AsyncResult::new(SerializationFormat::Bincode, rx) } fn reqwest( &self, url: &str, method: &str, options: ReqwestOptions, headers: Vec<(String, String)>, data: Option<Vec<u8>>, ) -> AsyncResult<Result<ReqwestResponse, u32>> { let url = url.to_string(); let method = method.to_string(); let (tx, rx) = mpsc::channel(1); self.pool.spawn_shared(Box::new(move || { Box::pin(async move { let resp = match crate::common::fetch( url.as_str(), method.as_str(), options.gzip, options.cors_proxy, headers, data) .await { Ok(a) => a, Err(err) => { let _ = tx.send(Err(err)).await; return; } }; let ok = resp.ok(); let redirected = resp.redirected(); let status = resp.status(); let status_text = resp.status_text(); let data = match crate::common::get_response_data(resp).await { Ok(a) => a, Err(err) => { let _ = tx.send(Err(err)).await; return; } }; let headers = Vec::new(); // we can't implement this as the method resp.headers().keys() is missing! // how else are we going to parse the headers debug!("received {} bytes", data.len()); let resp = ReqwestResponse { pos: 0, ok, redirected, status, status_text, headers, data: Some(data), }; debug!("response status {}", status); let _ = tx.send(Ok(resp)).await; }) })); AsyncResult::new(SerializationFormat::Bincode, rx) } async fn web_socket(&self, url: &str) -> Result<Box<dyn WebSocketAbi>, String> { WebSocket::new(url) } /// Open the WebGL async fn webgl(&self) -> Option<Box<dyn WebGlAbi>> { Some(Box::new(WebGl::new(&self.webgl_tx))) } } pub(crate) struct WebConsole { term_tx: mpsc::Sender<TerminalCommand>, } impl WebConsole { pub(crate) fn new(term_tx: mpsc::Sender<TerminalCommand>) -> WebConsole { WebConsole { term_tx } } } #[async_trait] impl ConsoleAbi for WebConsole { async fn stdout(&self, data: Vec<u8>) { if let Ok(text) = String::from_utf8(data) { let _ = self.term_tx.send(TerminalCommand::Print(text)).await; } } async fn stderr(&self, data: Vec<u8>) { if let Ok(text) = String::from_utf8(data) { let _ = self.term_tx.send(TerminalCommand::Print(text)).await; } } async fn flush(&self) {} async fn log(&self, text: String) { console::log(text.as_str()); } async fn console_rect(&self) -> ConsoleRect { let (ret_tx, mut ret_rx) = mpsc::channel(1); let _ = self .term_tx .send(TerminalCommand::ConsoleRect(ret_tx)) .await; ret_rx.recv().await.unwrap() } async fn cls(&self) { let _ = self.term_tx.send(TerminalCommand::Cls).await; } async fn exit(&self) { // Web terminals can not exit as they have nowhere to go! } } #[wasm_bindgen(module = "/js/time.js")] extern "C" { #[wasm_bindgen(js_name = "sleep")] fn sleep(ms: i32) -> Promise; }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-web/src/ws.rs
wasmer-web/src/ws.rs
use async_trait::async_trait; use std::ops::*; use std::sync::Arc; use wasmer_os::api::*; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{MessageEvent, WebSocket as WebSocketSys}; #[derive(Clone)] pub struct WebSocket { sys: WebSocketSys, } impl WebSocket { pub fn new(url: &str) -> Result<Box<dyn WebSocketAbi>, String> { // Open the web socket let ws_sys = WebSocketSys::new(url).map_err(|err| format!("{:?}", err))?; Ok(Box::new(WebSocket { sys: ws_sys })) } } #[async_trait] impl WebSocketAbi for WebSocket { fn set_onopen(&mut self, mut callback: Box<dyn FnMut()>) { let callback = Closure::wrap(Box::new(move |_e: web_sys::ProgressEvent| { callback.deref_mut()(); }) as Box<dyn FnMut(web_sys::ProgressEvent)>); self.sys.set_onopen(Some(callback.as_ref().unchecked_ref())); callback.forget(); } fn set_onclose(&mut self, callback: Box<dyn Fn() + Send + 'static>) { let callback = Closure::wrap(Box::new(move |_e: web_sys::ProgressEvent| { callback.deref()(); }) as Box<dyn FnMut(web_sys::ProgressEvent)>); self.sys .set_onclose(Some(callback.as_ref().unchecked_ref())); callback.forget(); } fn set_onmessage(&mut self, callback: Box<dyn Fn(Vec<u8>) + Send + 'static>) { let callback = Arc::new(callback); let fr = web_sys::FileReader::new().unwrap(); let fr_c = fr.clone(); let onloadend_cb = { let callback = callback.clone(); Closure::wrap(Box::new(move |_e: web_sys::ProgressEvent| { let array = js_sys::Uint8Array::new(&fr_c.result().unwrap()); let data = array.to_vec(); callback.deref()(data); }) as Box<dyn FnMut(web_sys::ProgressEvent)>) }; fr.set_onloadend(Some(onloadend_cb.as_ref().unchecked_ref())); onloadend_cb.forget(); // Attach the message process let onmessage_callback = { let callback = callback.clone(); Closure::wrap(Box::new(move |e: MessageEvent| { if let Ok(abuf) = e.data().dyn_into::<js_sys::ArrayBuffer>() { let data = js_sys::Uint8Array::new(&abuf).to_vec(); callback.deref()(data); } else if let Ok(blob) = e.data().dyn_into::<web_sys::Blob>() { fr.read_as_array_buffer(&blob).expect("blob not readable"); } else if let Ok(txt) = e.data().dyn_into::<js_sys::JsString>() { debug!("message event, received Text: {:?}", txt); } else { debug!("websocket received unknown message type"); } }) as Box<dyn FnMut(MessageEvent)>) }; self.sys.set_binary_type(web_sys::BinaryType::Arraybuffer); self.sys .set_onmessage(Some(onmessage_callback.as_ref().unchecked_ref())); onmessage_callback.forget(); } fn send(&mut self, data: Vec<u8>) -> Result<(), String> { let data_len = data.len(); let array = js_sys::Uint8Array::new_with_length(data_len as u32); array.copy_from(&data[..]); self.sys .send_with_array_buffer(&array.buffer()) .map_err(|err| format!("{:?}", err)) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-web/src/interval.rs
wasmer-web/src/interval.rs
use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { fn setInterval(closure: &Closure<dyn FnMut()>, millis: u32) -> f64; fn cancelInterval(token: f64); } #[wasm_bindgen] #[derive(Debug)] pub struct LeakyInterval { token: f64, } impl LeakyInterval { pub fn new<F: 'static>(duration: std::time::Duration, f: F) -> LeakyInterval where F: FnMut(), { let closure = { Closure::wrap(Box::new(f) as Box<dyn FnMut()>) }; let millis = duration.as_millis() as u32; #[allow(unused_unsafe)] let token = unsafe { setInterval(&closure, millis) }; closure.forget(); LeakyInterval { token } } } impl Drop for LeakyInterval { fn drop(&mut self) { #[allow(unused_unsafe)] unsafe { cancelInterval(self.token); } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-web/src/common.rs
wasmer-web/src/common.rs
use js_sys::Function; use std::cell::Cell; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures::*; use web_sys::*; use super::err; #[wasm_bindgen] #[derive(Default)] pub struct AnimationFrameCallbackWrapper { // These are both boxed because we want stable addresses! handle: Box<Cell<Option<i32>>>, func: Option<Box<dyn FnMut() -> bool + 'static>>, } #[allow(clippy::option_map_unit_fn)] impl Drop for AnimationFrameCallbackWrapper { fn drop(&mut self) { self.handle.get().map(cancel_animation_frame); } } pub(crate) fn set_panic_hook() { console_error_panic_hook::set_once(); } pub(crate) fn cancel_animation_frame(handle: i32) { debug!("Cancelling {}..", handle); web_sys::window() .unwrap() .cancel_animation_frame(handle) .unwrap() } impl AnimationFrameCallbackWrapper /*<'a>*/ { pub fn new() -> Self { Self { handle: Box::new(Cell::new(None)), func: None, } } pub fn leak(self) -> &'static mut Self { Box::leak(Box::new(self)) } /// To use this, you'll probably have to leak the wrapper. /// /// `Self::leak` can help you with this. pub fn safe_start(&'static mut self, func: impl FnMut() -> bool + 'static) { unsafe { self.inner(func) } } /// This is extremely prone to crashing and is probably unsound; use at your /// own peril. #[inline(never)] pub unsafe fn start<'s, 'f: 's>(&'s mut self, func: impl FnMut() -> bool + 'f) { debug!(""); // load bearing, somehow... self.inner(func) } #[allow(unused_unsafe, clippy::borrowed_box)] unsafe fn inner<'s, 'f: 's>(&'s mut self, func: impl FnMut() -> bool + 'f) { if let Some(handle) = self.handle.get() { cancel_animation_frame(handle) } let func: Box<dyn FnMut() -> bool + 'f> = Box::new(func); // Crime! let func: Box<dyn FnMut() -> bool + 'static> = unsafe { core::mem::transmute(func) }; self.func = Some(func); // This is the dangerous part; we're saying this is okay because we // cancel the RAF on Drop of this structure so, in theory, when the // function goes out of scope, the RAF will also be cancelled and the // invalid reference won't be used. let wrapper: &'static mut Self = unsafe { core::mem::transmute(self) }; let window = web_sys::window().unwrap(); fn recurse( f: &'static mut Box<dyn FnMut() -> bool + 'static>, h: &'static Cell<Option<i32>>, window: Window, ) -> Function { let val = Closure::once_into_js(move || { // See: https://github.com/rust-lang/rust/issues/42574 let f = f; if h.get().is_none() { warn!("you should never see this..."); return; } if (f)() { let next = recurse(f, h, window.clone()); let id = window.request_animation_frame(&next).unwrap(); h.set(Some(id)); } else { // No need to drop the function here, really. // It'll get dropped whenever the wrapper gets dropped. // drop(w.func.take()); // We should remove the handle though, so that when the // wrapper gets dropped it doesn't try to cancel something // that already ran. let _ = h.take(); } }); val.dyn_into().unwrap() } let func: &'static mut Box<dyn FnMut() -> bool + 'static> = wrapper.func.as_mut().unwrap(); let starting = recurse(func, &wrapper.handle, window.clone()); wrapper .handle .set(Some(window.request_animation_frame(&starting).unwrap())); } } fn fetch_internal( request: &Request ) -> JsFuture { if is_worker() { let global = js_sys::global(); JsFuture::from( global .dyn_into::<WorkerGlobalScope>() .unwrap() .fetch_with_request(request), ) } else { JsFuture::from(web_sys::window().unwrap().fetch_with_request(request)) } } pub async fn fetch( url: &str, method: &str, _gzip: bool, cors_proxy: Option<String>, headers: Vec<(String, String)>, data: Option<Vec<u8>>, ) -> Result<Response, u32> { let mut opts = RequestInit::new(); opts.method(method); opts.mode(RequestMode::Cors); if let Some(data) = data { let data_len = data.len(); let array = js_sys::Uint8Array::new_with_length(data_len as u32); array.copy_from(&data[..]); opts.body(Some(&array)); } let request = { let request = Request::new_with_str_and_init(&url, &opts).map_err(|_| err::ERR_EIO)?; let set_headers = request.headers(); for (name, val) in headers.iter() { set_headers .set(name.as_str(), val.as_str()) .map_err(|_| err::ERR_EIO)?; } request }; let resp_value = match fetch_internal(&request).await.ok() { Some(a) => a, None => { // If the request failed it may be because of CORS so if a cors proxy // is configured then try again with the cors proxy let url_store; let url = if let Some(cors_proxy) = cors_proxy { url_store = format!("https://{}/{}", cors_proxy, url); url_store.as_str() } else { return Err(err::ERR_EIO); }; let request = Request::new_with_str_and_init(url, &opts).map_err(|_| err::ERR_EIO)?; let set_headers = request.headers(); for (name, val) in headers.iter() { set_headers .set(name.as_str(), val.as_str()) .map_err(|_| err::ERR_EIO)?; } fetch_internal(&request).await.map_err(|_| err::ERR_EIO)? } }; assert!(resp_value.is_instance_of::<Response>()); let resp: Response = resp_value.dyn_into().unwrap(); if resp.status() < 200 || resp.status() >= 400 { debug!("fetch-failed: {}", resp.status_text()); return Err(match resp.status() { 404 => err::ERR_ENOENT, _ => err::ERR_EIO, }); } Ok(resp) } pub async fn fetch_data( url: &str, method: &str, gzip: bool, cors_proxy: Option<String>, headers: Vec<(String, String)>, data: Option<Vec<u8>>, ) -> Result<Vec<u8>, u32> { Ok(get_response_data(fetch(url, method, gzip, cors_proxy, headers, data).await?).await?) } pub async fn get_response_data(resp: Response) -> Result<Vec<u8>, u32> { let resp = { JsFuture::from(resp.array_buffer().unwrap()) }; let arrbuff_value = resp.await.map_err(|_| err::ERR_ENOEXEC)?; assert!(arrbuff_value.is_instance_of::<js_sys::ArrayBuffer>()); //let arrbuff: js_sys::ArrayBuffer = arrbuff_value.dyn_into().unwrap(); let typebuff: js_sys::Uint8Array = js_sys::Uint8Array::new(&arrbuff_value); let ret = typebuff.to_vec(); Ok(ret) } #[wasm_bindgen(module = "/public/worker.js")] extern "C" { #[wasm_bindgen(js_name = "isWorker")] pub fn is_worker() -> bool; } pub mod console { use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console)] pub fn log(s: &str); } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-web/src/pool.rs
wasmer-web/src/pool.rs
#![allow(unused_imports)] use bytes::Bytes; use js_sys::Uint8Array; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use derivative::*; use wasm_bindgen_futures::JsFuture; use wasmer_os::api::SpawnType; use wasmer_os::wasmer::MemoryType; use wasmer_os::wasmer::Module; use wasmer_os::wasmer::Store; use wasmer_os::wasmer::WASM_MAX_PAGES; use wasmer_os::wasmer::vm::VMMemory; use wasmer_os::wasmer_wasi::WasiThreadError; use std::borrow::Borrow; use std::cell::RefCell; use std::collections::VecDeque; use std::collections::HashMap; use std::fmt::Debug; use std::future::Future; use std::num::NonZeroU32; use std::ops::Deref; use std::ops::DerefMut; use std::pin::Pin; use std::rc::Rc; use std::sync::Mutex; use std::sync::atomic::AtomicU32; use tokio::select; use tokio::sync::broadcast; use tokio::sync::mpsc; use tokio::sync::oneshot; use tokio::sync::Semaphore; use once_cell::sync::Lazy; use js_sys::{JsString, Promise}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use wasmer_os::api::ThreadLocal; use wasmer_os::common::MAX_MPSC; use wasm_bindgen::{prelude::*, JsCast}; use web_sys::{DedicatedWorkerGlobalScope, WorkerOptions, WorkerType}; use xterm_js_rs::Terminal; use super::common::*; use super::fd::*; use super::interval::*; use super::tty::Tty; pub type BoxRun<'a> = Box<dyn FnOnce() + Send + 'a>; pub type BoxRunAsync<'a, T> = Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = T> + 'static>> + Send + 'a>; #[derive(Debug, Clone, Copy)] enum WasmRunType { Create, CreateWithMemory(MemoryType), Existing(u32), } struct WasmRunCommand { run: Box<dyn FnOnce(Store, Module, Option<VMMemory>) -> Pin<Box<dyn Future<Output = ()> + 'static>> + Send + 'static>, ty: WasmRunType, store: Store, module_bytes: Bytes, free_memory: Arc<mpsc::Sender<u32>>, } enum WasmRunMemory { WithoutMemory, WithMemory(MemoryType) } struct WasmRunContext { id: u32, cmd: WasmRunCommand, memory: WasmRunMemory, } #[derive(Clone)] struct WasmInstance { ref_cnt: u32, module: js_sys::WebAssembly::Module, module_bytes: Bytes, memory: js_sys::WebAssembly::Memory, memory_type: MemoryType, } thread_local! { static THREAD_LOCAL_ROOT_WASM_INSTANCES: std::cell::RefCell<HashMap<u32, WasmInstance>> = RefCell::new(HashMap::new()); static THREAD_LOCAL_CURRENT_WASM: std::cell::RefCell<Option<u32>> = RefCell::new(None); } static WASM_SEED: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(1)); trait AssertSendSync: Send + Sync {} impl AssertSendSync for WebThreadPool {} #[wasm_bindgen] #[derive(Debug, Clone)] pub struct WebThreadPool { pool_reactors: Arc<PoolState>, pool_dedicated: Arc<PoolState>, spawn_wasm: Arc<mpsc::Sender<WasmRunCommand>>, free_memory: Arc<mpsc::Sender<u32>>, } enum Message { Run(BoxRun<'static>), RunAsync(BoxRunAsync<'static, ()>), } impl Debug for Message { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Message::Run(_) => write!(f, "run"), Message::RunAsync(_) => write!(f, "run-async"), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] enum PoolType { Shared, Dedicated, } struct IdleThread { idx: usize, work: mpsc::Sender<Message>, } impl IdleThread { #[allow(dead_code)] fn consume(self, msg: Message) { let _ = self.work.blocking_send(msg); } fn try_consume(self, msg: Message) -> Result<(), (IdleThread, Message)> { match self.work.try_send(msg) { Ok(_) => Ok(()), Err(mpsc::error::TrySendError::Closed(a)) => Err((self, a)), Err(mpsc::error::TrySendError::Full(a)) => Err((self, a)), } } } #[derive(Derivative)] #[derivative(Debug)] pub struct PoolState { #[derivative(Debug = "ignore")] idle_rx: Mutex<mpsc::Receiver<IdleThread>>, idle_tx: mpsc::Sender<IdleThread>, idx_seed: AtomicUsize, idle_size: usize, blocking: bool, spawn: mpsc::Sender<Message>, #[allow(dead_code)] type_: PoolType, } pub struct ThreadState { pool: Arc<PoolState>, #[allow(dead_code)] idx: usize, tx: mpsc::Sender<Message>, rx: Mutex<Option<mpsc::Receiver<Message>>>, init: Mutex<Option<Message>>, } #[wasm_bindgen] pub struct LoaderHelper {} #[wasm_bindgen] impl LoaderHelper { #[wasm_bindgen(js_name = mainJS)] pub fn main_js(&self) -> JsString { #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = ["import", "meta"], js_name = url)] static URL: JsString; } URL.clone() } } #[wasm_bindgen(module = "/public/worker.js")] extern "C" { #[wasm_bindgen(js_name = "startWorker")] fn start_worker( module: JsValue, memory: JsValue, shared_data: JsValue, opts: WorkerOptions, builder: LoaderHelper, ) -> Promise; #[wasm_bindgen(js_name = "startWasm")] fn start_wasm( module: JsValue, memory: JsValue, ctx: JsValue, opts: WorkerOptions, builder: LoaderHelper, wasm_module: JsValue, wasm_memory: JsValue, ) -> Promise; } impl WebThreadPool { pub fn new(size: usize) -> Result<WebThreadPool, JsValue> { info!("pool::create(size={})", size); let (idle_tx1, idle_rx1) = mpsc::channel(MAX_MPSC); let (idle_tx3, idle_rx3) = mpsc::channel(MAX_MPSC); let (spawn_tx1, mut spawn_rx1) = mpsc::channel(MAX_MPSC); let (spawn_tx2, mut spawn_rx2) = mpsc::channel(MAX_MPSC); let (spawn_tx3, mut spawn_rx3) = mpsc::channel(MAX_MPSC); let (free_tx4, mut free_rx4) = mpsc::channel(MAX_MPSC); let pool_reactors = Arc::new(PoolState { idle_rx: Mutex::new(idle_rx1), idle_tx: idle_tx1, idx_seed: AtomicUsize::new(0), blocking: false, idle_size: 2usize.max(size), type_: PoolType::Shared, spawn: spawn_tx1, }); let pool_dedicated = Arc::new(PoolState { idle_rx: Mutex::new(idle_rx3), idle_tx: idle_tx3, idx_seed: AtomicUsize::new(0), blocking: true, idle_size: 1usize.max(size), type_: PoolType::Dedicated, spawn: spawn_tx3, }); let pool1 = pool_reactors.clone(); let pool3 = pool_dedicated.clone(); // The management thread will spawn other threads - this thread is safe from // being blocked by other threads wasm_bindgen_futures::spawn_local(async move { loop { select! { spawn = spawn_rx1.recv() => { if let Some(spawn) = spawn { pool1.expand(spawn); } else { break; } } spawn = spawn_rx2.recv() => { if let Some(spawn) = spawn { let _ = _spawn_wasm(spawn).await; } else { break; } } spawn = spawn_rx3.recv() => { if let Some(spawn) = spawn { pool3.expand(spawn); } else { break; } } free = free_rx4.recv() => { if let Some(free) = free { _free_memory(free) } else { break; } } } } }); let pool = WebThreadPool { pool_reactors, pool_dedicated, spawn_wasm: Arc::new(spawn_tx2), free_memory: Arc::new(free_tx4), }; Ok(pool) } pub fn new_with_max_threads() -> Result<WebThreadPool, JsValue> { #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = navigator, js_name = hardwareConcurrency)] static HARDWARE_CONCURRENCY: usize; } let pool_size = std::cmp::max(*HARDWARE_CONCURRENCY, 1); debug!("pool::max_threads={}", pool_size); Self::new(pool_size) } pub fn spawn_shared( &self, task: BoxRunAsync<'static, ()> ) { self.pool_reactors.spawn(Message::RunAsync(task)); } pub fn spawn_wasm( &self, run: impl FnOnce(Store, Module, Option<VMMemory>) -> Pin<Box<dyn Future<Output = ()> + 'static>> + Send + 'static, store: Store, mut module_bytes: Bytes, spawn_type: SpawnType, ) -> Result<(), WasiThreadError> { let run_type = match spawn_type { SpawnType::Create => WasmRunType::Create, SpawnType::CreateWithType(mem) => WasmRunType::CreateWithMemory(mem.ty), SpawnType::NewThread(_) => { let wasm_id = match THREAD_LOCAL_CURRENT_WASM.with(|c| c.borrow().clone()) { Some(id) => id, None => { return Err(WasiThreadError::InvalidWasmContext); } }; WasmRunType::Existing(wasm_id) } }; if module_bytes.starts_with(b"\0asm") == false { let parsed_bytes = wat::parse_bytes(module_bytes.as_ref()).map_err(|e| { error!("failed to parse WAT - {}", e); WasiThreadError::Unsupported })?; module_bytes = Bytes::from(parsed_bytes.to_vec()); } let msg = WasmRunCommand { run: Box::new(run), ty: run_type, store, module_bytes, free_memory: self.free_memory.clone(), }; _spawn_send(&self.spawn_wasm, msg); Ok(()) } pub fn spawn_dedicated( &self, task: BoxRun<'static> ) { self.pool_dedicated.spawn(Message::Run(task)); } pub fn spawn_dedicated_async( &self, task: BoxRunAsync<'static, ()> ) { self.pool_dedicated.spawn(Message::RunAsync(task)); } } async fn _compile_module(bytes: &[u8]) -> Result<js_sys::WebAssembly::Module, ()> { let js_bytes = unsafe { Uint8Array::view(bytes) }; Ok( match wasm_bindgen_futures::JsFuture::from( js_sys::WebAssembly::compile(&js_bytes.into()) ).await { Ok(a) => match a.dyn_into::<js_sys::WebAssembly::Module>() { Ok(a) => a, Err(err) => { error!("Failed to compile module - {}", err.as_string().unwrap_or_else(|| format!("{:?}", err))); return Err(()); } }, Err(err) => { error!("WebAssembly failed to compile - {}", err.as_string().unwrap_or_else(|| format!("{:?}", err))); return Err(()); } } //js_sys::WebAssembly::Module::new(&js_bytes.into()).unwrap() ) } async fn _spawn_wasm(mut run: WasmRunCommand) -> Result<(),()> { let mut opts = WorkerOptions::new(); opts.type_(WorkerType::Module); opts.name(&*format!("WasmWorker")); let result = match run.ty.clone() { WasmRunType::Create => { let wasm_module = _compile_module(&run.module_bytes[..]).await?; let wasm_id = WASM_SEED.fetch_add(1, Ordering::AcqRel); let ctx = WasmRunContext { id: wasm_id, cmd: run, memory: WasmRunMemory::WithoutMemory }; let ctx = Box::into_raw(Box::new(ctx)); wasm_bindgen_futures::JsFuture::from(start_wasm( wasm_bindgen::module(), wasm_bindgen::memory(), JsValue::from(ctx as u32), opts, LoaderHelper {}, JsValue::from(wasm_module), JsValue::null(), )) } WasmRunType::CreateWithMemory(ty) => { if ty.shared == false { // We can only pass memory around between web workers when its a shared memory error!("Failed to create WASM process with external memory as only shared memory is supported yet this web assembly binary imports non-shared memory."); return Err(()); } if ty.maximum.is_none() { // Browsers require maximum number defined on shared memory error!("Failed to create WASM process with external memory as shared memory must have a maximum size however this web assembly binary imports shared memory with no maximum defined."); return Err(()); } let wasm_module = _compile_module(&run.module_bytes[..]).await?; let wasm_memory = { let descriptor = js_sys::Object::new(); js_sys::Reflect::set(&descriptor, &"initial".into(), &ty.minimum.0.into()).unwrap(); //let min = 100u32.max(ty.minimum.0); //js_sys::Reflect::set(&descriptor, &"initial".into(), &min.into()).unwrap(); if let Some(max) = ty.maximum { js_sys::Reflect::set(&descriptor, &"maximum".into(), &max.0.into()).unwrap(); } js_sys::Reflect::set(&descriptor, &"shared".into(), &ty.shared.into()).unwrap(); match js_sys::WebAssembly::Memory::new(&descriptor) { Ok(a) => a, Err(err) => { error!("WebAssembly failed to create the memory - {}", err.as_string().unwrap_or_else(|| format!("{:?}", err))); return Err(()); } } }; let wasm_id = WASM_SEED.fetch_add(1, Ordering::AcqRel); THREAD_LOCAL_ROOT_WASM_INSTANCES.with(|c| { let mut root = c.borrow_mut(); let root = root.deref_mut(); root.insert(wasm_id, WasmInstance { ref_cnt: 1, module: wasm_module.clone(), module_bytes: run.module_bytes.clone(), memory: wasm_memory.clone(), memory_type: ty.clone() }) }); let ctx = WasmRunContext { id: wasm_id, cmd: run, memory: WasmRunMemory::WithMemory(ty) }; let ctx = Box::into_raw(Box::new(ctx)); wasm_bindgen_futures::JsFuture::from(start_wasm( wasm_bindgen::module(), wasm_bindgen::memory(), JsValue::from(ctx as u32), opts, LoaderHelper {}, JsValue::from(wasm_module), JsValue::from(wasm_memory), )) }, WasmRunType::Existing(wasm_id) => { let inst = THREAD_LOCAL_ROOT_WASM_INSTANCES.with(|c| { let mut root = c.borrow_mut(); let root = root.deref_mut(); if let Some(inst) = root.get_mut(&wasm_id) { inst.ref_cnt += 1; Some(inst.clone()) } else { error!("WebAssembly Memory must be sent to the management thread before attempting to reuse it in a new WebWorker, it must also use SharedMemory"); None } }); let wasm_module; let wasm_module_bytes; let wasm_memory; let wasm_memory_type; if let Some(inst) = inst { wasm_module = inst.module; wasm_module_bytes = inst.module_bytes; wasm_memory = inst.memory; wasm_memory_type = inst.memory_type; } else { return Err(()); } run.module_bytes = wasm_module_bytes; let ctx = WasmRunContext { id: wasm_id, cmd: run, memory: WasmRunMemory::WithMemory(wasm_memory_type) }; let ctx = Box::into_raw(Box::new(ctx)); wasm_bindgen_futures::JsFuture::from(start_wasm( wasm_bindgen::module(), wasm_bindgen::memory(), JsValue::from(ctx as u32), opts, LoaderHelper {}, JsValue::from(wasm_module), JsValue::from(wasm_memory), )) } }; _process_worker_result(result, None).await; Ok(()) } fn _free_memory(wasm_id: u32) { THREAD_LOCAL_ROOT_WASM_INSTANCES.with(|c| { let mut root = c.borrow_mut(); let root = root.deref_mut(); let should_remove = if let Some(mem) = root.get_mut(&wasm_id) { mem.ref_cnt -= 1; mem.ref_cnt <= 0 } else { false }; if should_remove { root.remove(&wasm_id); } }) } fn _spawn_send<T: 'static>(tx: &mpsc::Sender<T>, mut msg: T) { for _ in 0..100 { match tx.try_send(msg) { Ok(_) => { return; } Err(mpsc::error::TrySendError::Closed(_)) => { return; } Err(mpsc::error::TrySendError::Full(m)) => { msg = m; } } std::thread::yield_now(); } if crate::common::is_worker() { let _ = tx.blocking_send(msg); } else { let spawn = tx.clone(); wasm_bindgen_futures::spawn_local(async move { let _ = spawn.send(msg).await; }); } } impl PoolState { fn spawn(self: &Arc<Self>, mut msg: Message) { for _ in 0..10 { if let Ok(mut guard) = self.idle_rx.try_lock() { if let Ok(thread) = guard.try_recv() { match thread.try_consume(msg) { Ok(_) => { return; } Err((thread, a)) => { let _ = self.idle_tx.try_send(thread); msg = a; } } } break; } std::thread::yield_now(); } _spawn_send(&self.spawn, msg); } fn expand(self: &Arc<Self>, init: Message) { let (tx, rx) = mpsc::channel(MAX_MPSC); let idx = self.idx_seed.fetch_add(1usize, Ordering::Release); let state = Arc::new(ThreadState { pool: Arc::clone(self), idx, tx, rx: Mutex::new(Some(rx)), init: Mutex::new(Some(init)), }); Self::start_worker_now(idx, state, None); } pub fn start_worker_now( idx: usize, state: Arc<ThreadState>, should_warn_on_error: Option<Terminal>, ) { let mut opts = WorkerOptions::new(); opts.type_(WorkerType::Module); opts.name(&*format!("Worker-{:?}-{}", state.pool.type_, idx)); let ptr = Arc::into_raw(state); let result = wasm_bindgen_futures::JsFuture::from(start_worker( wasm_bindgen::module(), wasm_bindgen::memory(), JsValue::from(ptr as u32), opts, LoaderHelper {}, )); wasm_bindgen_futures::spawn_local(async move { _process_worker_result(result, should_warn_on_error).await; }); } } async fn _process_worker_result(result: JsFuture, should_warn_on_error: Option<Terminal>) { let ret = result.await; if let Err(err) = ret { let err = err .as_string() .unwrap_or_else(|| format!("{:?}", err)); error!("failed to start worker thread - {}", err); if let Some(term) = should_warn_on_error { term.write( Tty::BAD_WORKER .replace("\n", "\r\n") .replace("\\x1B", "\x1B") .replace("{error}", err.as_str()) .as_str(), ); } return; } } impl ThreadState { fn work(state: Arc<ThreadState>) { let thread_index = state.idx; info!( "worker started (index={}, type={:?})", thread_index, state.pool.type_ ); // Load the work queue receiver where other people will // send us the work that needs to be done let mut work_rx = { let mut lock = state.rx.lock().unwrap(); lock.take().unwrap() }; // Load the initial work let mut work = { let mut lock = state.init.lock().unwrap(); lock.take() }; // The work is done in an asynchronous engine (that supports Javascript) let work_tx = state.tx.clone(); let pool = Arc::clone(&state.pool); let driver = async move { let global = js_sys::global().unchecked_into::<DedicatedWorkerGlobalScope>(); loop { // Process work until we need to go idle while let Some(task) = work { match task { Message::Run(task) => { task(); } Message::RunAsync(task) => { let future = task(); if pool.blocking { future.await; } else { wasm_bindgen_futures::spawn_local(async move { future.await; }); } } } // Grab the next work work = work_rx.try_recv().ok(); } // If there iss already an idle thread thats older then // keep that one (otherwise ditch it) - this creates negative // pressure on the pool size. // The reason we keep older threads is to maximize cache hits such // as module compile caches. if let Ok(mut lock) = state.pool.idle_rx.try_lock() { let mut others = Vec::new(); while let Ok(other) = lock.try_recv() { others.push(other); } // Sort them in the order of index (so older ones come first) others.sort_by_key(|k| k.idx); // If the number of others (plus us) exceeds the maximum then // we either drop ourselves or one of the others if others.len() + 1 > pool.idle_size { // How many are there already there that have a lower index - are we the one without a chair? let existing = others .iter() .map(|a| a.idx) .filter(|a| *a < thread_index) .count(); if existing >= pool.idle_size { for other in others { let _ = state.pool.idle_tx.send(other).await; } info!( "worker closed (index={}, type={:?})", thread_index, pool.type_ ); break; } else { // Someone else is the one (the last one) let leftover_chairs = others.len() - 1; for other in others.into_iter().take(leftover_chairs) { let _ = state.pool.idle_tx.send(other).await; } } } else { // Add them all back in again (but in the right order) for other in others { let _ = state.pool.idle_tx.send(other).await; } } } // Now register ourselves as idle trace!( "pool is idle (thread_index={}, type={:?})", thread_index, pool.type_ ); let idle = IdleThread { idx: thread_index, work: work_tx.clone(), }; if let Err(_) = state.pool.idle_tx.send(idle).await { info!( "pool is closed (thread_index={}, type={:?})", thread_index, pool.type_ ); break; } // Do a blocking recv (if this fails the thread is closed) work = match work_rx.recv().await { Some(a) => Some(a), None => { info!( "worker closed (index={}, type={:?})", thread_index, pool.type_ ); break; } }; } global.close(); }; wasm_bindgen_futures::spawn_local(driver); } } #[wasm_bindgen(skip_typescript)] pub fn worker_entry_point(state_ptr: u32) { let state = unsafe { Arc::<ThreadState>::from_raw(state_ptr as *const ThreadState) }; let name = js_sys::global() .unchecked_into::<DedicatedWorkerGlobalScope>() .name(); debug!("{}: Entry", name); ThreadState::work(state); } #[wasm_bindgen(skip_typescript)] pub fn wasm_entry_point(ctx_ptr: u32, wasm_module: JsValue, wasm_memory: JsValue) { // Grab the run wrapper that passes us the rust variables (and extract the callback) let ctx = ctx_ptr as *mut WasmRunContext; let ctx = unsafe { Box::from_raw(ctx) }; let run_callback = (*ctx).cmd.run; // Compile the web assembly module let wasm_store = ctx.cmd.store; let wasm_module = match wasm_module.dyn_into::<js_sys::WebAssembly::Module>() { Ok(a) => a, Err(err) => { error!("Failed to receive module - {}", err.as_string().unwrap_or_else(|| format!("{:?}", err))); _spawn_send(ctx.cmd.free_memory.deref(), ctx.id); return; } }; let wasm_module = unsafe { match Module::from_js_module(&wasm_store, wasm_module, ctx.cmd.module_bytes.clone()){ Ok(a) => a, Err(err) => { error!("Failed to compile module - {}", err); _spawn_send(ctx.cmd.free_memory.deref(), ctx.id); return; } } }; // If memory was passed to the web worker then construct it let wasm_memory = match ctx.memory { WasmRunMemory::WithoutMemory => None, WasmRunMemory::WithMemory(wasm_memory_type) => { let wasm_memory = match wasm_memory.dyn_into::<js_sys::WebAssembly::Memory>() { Ok(a) => a, Err(err) => { error!("Failed to receive memory for module - {}", err.as_string().unwrap_or_else(|| format!("{:?}", err))); _spawn_send(ctx.cmd.free_memory.deref(), ctx.id); return; } }; Some(VMMemory::new(wasm_memory, wasm_memory_type)) } }; let name = js_sys::global() .unchecked_into::<DedicatedWorkerGlobalScope>() .name(); debug!("{}: Entry", name); // Invoke the callback which will run the web assembly module let wasm_id = ctx.id; let free_memory = ctx.cmd.free_memory.clone(); let driver = async move { THREAD_LOCAL_CURRENT_WASM.with(|c| c.borrow_mut().replace(wasm_id)); run_callback(wasm_store, wasm_module, wasm_memory).await; THREAD_LOCAL_CURRENT_WASM.with(|c| c.borrow_mut().take()); // Reduce the reference count on the memory _spawn_send(free_memory.deref(), wasm_id); }; wasm_bindgen_futures::spawn_local(driver); }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/lib.rs
crypto/src/lib.rs
pub mod crypto; pub mod utils; pub mod error; pub mod spec; pub use crypto::*; pub use spec::*; pub const HASH_ROUTINE: crypto::HashRoutine = crypto::HashRoutine::Blake3;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/error/crypto_error.rs
crypto/src/error/crypto_error.rs
use error_chain::error_chain; error_chain! { types { CryptoError, CryptoErrorKind, ResultExt, Result; } errors { NoIvPresent { description("no initialization vector") display("no initialization vector") } } } impl From<CryptoError> for std::io::Error { fn from(error: CryptoError) -> Self { match error { CryptoError(CryptoErrorKind::NoIvPresent, _) => std::io::Error::new( std::io::ErrorKind::Other, "The metadata does not have IV component present", ), _ => std::io::Error::new( std::io::ErrorKind::Other, "An unknown error occured while performing ate crypto", ), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/error/mod.rs
crypto/src/error/mod.rs
mod crypto_error; mod serialization_error; pub use crypto_error::*; pub use serialization_error::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/error/serialization_error.rs
crypto/src/error/serialization_error.rs
use error_chain::error_chain; use rmp_serde::decode::Error as RmpDecodeError; use rmp_serde::encode::Error as RmpEncodeError; use serde_json::Error as JsonError; use crate::spec::PrimaryKey; pub use wasmer_bus_types::BusError; error_chain! { types { SerializationError, SerializationErrorKind, ResultExt, Result; } links { } foreign_links { IO(tokio::io::Error); EncodeError(RmpEncodeError); DecodeError(RmpDecodeError); JsonError(JsonError); BincodeError(bincode::Error); Base64Error(base64::DecodeError); BusError(BusError); } errors { NoPrimarykey { description("data object does not have a primary key") display("data object does not have a primary key") } NoData { description("data object has no actual data") display("data object has no actual data") } MissingData { description("the data for this record is missing") display("the data for this record is missing") } InvalidSerializationFormat { description("data is stored in an unknown serialization format") display("data is stored in an unknown serialization format") } CollectionDetached { description("collection is detached from a parent") display("collection is detached from a parent") } SerdeError(err: String) { description("serde error during serialization"), display("serde error during serialization - {}", err), } WeakDio { description("the dio that created this object has gone out of scope") display("the dio that created this object has gone out of scope") } SaveParentFirst { description("you must save the parent object before attempting to push objects to this vector") display("you must save the parent object before attempting to push objects to this vector") } ObjectStillLocked(key: PrimaryKey) { description("data object with key is still being edited in the current scope"), display("data object with key ({}) is still being edited in the current scope", key.as_hex_string()), } AlreadyDeleted(key: PrimaryKey) { description("data object with key has already been deleted"), display("data object with key ({}) has already been deleted", key.as_hex_string()), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/utils/test.rs
crypto/src/utils/test.rs
#![allow(unused_imports)] use std::sync::Once; use tracing::{debug, error, info, instrument, span, trace, warn, Level}; static INIT: Once = Once::new(); pub fn bootstrap_test_env() { INIT.call_once(|| { super::log_init(0, false); }); }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/utils/b64.rs
crypto/src/utils/b64.rs
#![allow(unused_imports)] use std::convert::TryInto; use serde::{de::Deserializer, Serializer}; use serde::{Deserialize, Serialize}; use tracing::{debug, error, info, instrument, span, trace, warn, Level}; pub fn vec_serialize<S>(data: &Vec<u8>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { if std::any::type_name::<S>().contains("serde_json") { serializer.serialize_str(&base64::encode(&data[..])) } else { <Vec<u8>>::serialize(data, serializer) } } pub fn vec_deserialize<'a, D>(deserializer: D) -> Result<Vec<u8>, D::Error> where D: Deserializer<'a>, { if std::any::type_name::<D>().contains("serde_json") { use serde::de::Error; let ret = String::deserialize(deserializer).and_then(|string| { base64::decode(&string).map_err(|err| Error::custom(err.to_string())) })?; Ok(ret) } else { <Vec<u8>>::deserialize(deserializer) } } pub fn b16_serialize<S>(data: &[u8; 16], serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { if std::any::type_name::<S>().contains("serde_json") { serializer.serialize_str(&base64::encode(&data[..])) } else { <[u8; 16]>::serialize(data, serializer) } } pub fn b16_deserialize<'a, D>(deserializer: D) -> Result<[u8; 16], D::Error> where D: Deserializer<'a>, { if std::any::type_name::<D>().contains("serde_json") { use serde::de::Error; let ret = String::deserialize(deserializer).and_then(|string| { base64::decode(&string).map_err(|err| Error::custom(err.to_string())) })?; ret.try_into().map_err(|e: Vec<u8>| { Error::custom(format!("expected 16 bytes but found {}", e.len()).as_str()) }) } else { <[u8; 16]>::deserialize(deserializer) } } pub fn b24_serialize<S>(data: &[u8; 24], serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { if std::any::type_name::<S>().contains("serde_json") { serializer.serialize_str(&base64::encode(&data[..])) } else { <[u8; 24]>::serialize(data, serializer) } } pub fn b24_deserialize<'a, D>(deserializer: D) -> Result<[u8; 24], D::Error> where D: Deserializer<'a>, { if std::any::type_name::<D>().contains("serde_json") { use serde::de::Error; let ret = String::deserialize(deserializer).and_then(|string| { base64::decode(&string).map_err(|err| Error::custom(err.to_string())) })?; ret.try_into().map_err(|e: Vec<u8>| { Error::custom(format!("expected 24 bytes but found {}", e.len()).as_str()) }) } else { <[u8; 24]>::deserialize(deserializer) } } pub fn b32_serialize<S>(data: &[u8; 32], serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { if std::any::type_name::<S>().contains("serde_json") { serializer.serialize_str(&base64::encode(&data[..])) } else { <[u8; 32]>::serialize(data, serializer) } } pub fn b32_deserialize<'a, D>(deserializer: D) -> Result<[u8; 32], D::Error> where D: Deserializer<'a>, { if std::any::type_name::<D>().contains("serde_json") { use serde::de::Error; let ret = String::deserialize(deserializer).and_then(|string| { base64::decode(&string).map_err(|err| Error::custom(err.to_string())) })?; ret.try_into().map_err(|e: Vec<u8>| { Error::custom(format!("expected 32 bytes but found {}", e.len()).as_str()) }) } else { <[u8; 32]>::deserialize(deserializer) } } #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)] struct TestClass { pub header: String, #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] pub my_bytes: Vec<u8>, #[serde(serialize_with = "b16_serialize", deserialize_with = "b16_deserialize")] pub my_b1: [u8; 16], #[serde(serialize_with = "b24_serialize", deserialize_with = "b24_deserialize")] pub my_b2: [u8; 24], #[serde(serialize_with = "b32_serialize", deserialize_with = "b32_deserialize")] pub my_b3: [u8; 32], } #[test] fn test_b64() { crate::utils::bootstrap_test_env(); let plain = TestClass { header: "ate".to_string(), my_bytes: vec![ 112u8, 84u8, 99u8, 210u8, 55u8, 201u8, 202u8, 203u8, 204u8, 205u8, 206u8, 207u8, ], my_b1: [ 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8, 10u8, 11u8, 12u8, 13u8, 14u8, 15u8, 16u8, ], my_b2: [ 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8, 10u8, 11u8, 12u8, 13u8, 14u8, 15u8, 16u8, 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, ], my_b3: [ 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8, 10u8, 11u8, 12u8, 13u8, 14u8, 15u8, 16u8, 1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8, 9u8, 10u8, 11u8, 12u8, 13u8, 14u8, 15u8, 16u8, ], }; let cipher = bincode::serialize(&plain).unwrap(); trace!("{:?}", cipher); let test: TestClass = bincode::deserialize(&cipher[..]).unwrap(); assert_eq!(test, plain); let cipher = rmp_serde::to_vec(&plain).unwrap(); trace!("{:?}", cipher); let test: TestClass = rmp_serde::from_read_ref(&cipher[..]).unwrap(); assert_eq!(test, plain); let cipher = serde_json::to_string_pretty(&plain).unwrap(); trace!("{}", cipher); let test: TestClass = serde_json::from_str(&cipher).unwrap(); assert_eq!(test, plain); }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/utils/log.rs
crypto/src/utils/log.rs
#![allow(unused_imports)] use tracing::metadata::LevelFilter; use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use tracing_subscriber::fmt::SubscriberBuilder; use tracing_subscriber::EnvFilter; use std::sync::Once; static SYNC_OBJ: Once = Once::new(); pub fn log_init(verbose: i32, debug: bool) { SYNC_OBJ.call_once(move || { let mut log_level = match verbose { 0 => None, 1 => Some(LevelFilter::WARN), 2 => Some(LevelFilter::INFO), 3 => Some(LevelFilter::DEBUG), 4 => Some(LevelFilter::TRACE), _ => None, }; if debug { log_level = Some(LevelFilter::DEBUG); } if let Some(log_level) = log_level { SubscriberBuilder::default() .with_writer(std::io::stderr) .with_max_level(log_level) .init(); } else { SubscriberBuilder::default() .with_writer(std::io::stderr) .with_env_filter(EnvFilter::from_default_env()) .init(); } }); } pub fn obscure_error<E>(err: E) -> u16 where E: std::error::Error + Sized, { let err = err.to_string(); let hash = (fxhash::hash32(&err) % (u16::MAX as u32)) as u16; debug!("internal error - code={} - {}", hash, err); hash } pub fn obscure_error_str(err: &str) -> u16 { let err = err.to_string(); let hash = (fxhash::hash32(&err) % (u16::MAX as u32)) as u16; debug!("internal error - code={} - {}", hash, err); hash }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/utils/mod.rs
crypto/src/utils/mod.rs
pub mod b64; pub mod log; pub mod test; pub use b64::*; pub use log::*; pub use test::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/spec/node_id.rs
crypto/src/spec/node_id.rs
use core::fmt; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum NodeId { Unknown, Client(u64), Server(u32, u32), } impl Default for NodeId { fn default() -> Self { NodeId::Unknown } } impl fmt::Display for NodeId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { NodeId::Unknown => write!(f, "unknown"), NodeId::Client(id) => write!(f, "client({})", id), NodeId::Server(server_id, node_id) => write!(f, "server(id={}, node={})", server_id, node_id), } } } impl NodeId { pub fn generate_client_id() -> NodeId { let client_id = fastrand::u64(..); NodeId::Client(client_id) } pub fn generate_server_id(node_id: u32) -> NodeId { let server_id = fastrand::u32(..); NodeId::Server(server_id, node_id) } pub fn to_string(&self) -> String { match self { NodeId::Unknown => "[new]".to_string(), NodeId::Client(a) => hex::encode(a.to_be_bytes()).to_uppercase(), NodeId::Server(_, b) => format!("n{}", b), } } pub fn to_short_string(&self) -> String { match self { NodeId::Unknown => "[new]".to_string(), NodeId::Client(a) => { let client_id = hex::encode(a.to_be_bytes()).to_uppercase(); format!("{}", &client_id[..4]) } NodeId::Server(_, a) => format!("n{}", a), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/spec/mod.rs
crypto/src/spec/mod.rs
mod primary_key; mod node_id; mod chain_key; pub use primary_key::*; pub use wasmer_bus_types::SerializationFormat; pub use node_id::*; pub use chain_key::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/spec/primary_key.rs
crypto/src/spec/primary_key.rs
use std::mem::size_of; use std::cell::RefCell; use serde::*; use crate::AteHash; /// All event and data objects within ATE have a primary key that uniquely represents /// it and allows it to be indexed and referenced. This primary key can be derived from /// other input data like strings or numbers in order to make object lookups that are /// static (e.g. root nodes) #[allow(dead_code)] #[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd)] pub struct PrimaryKey { key: u64, } impl Default for PrimaryKey { fn default() -> PrimaryKey { PrimaryKey::generate() } } impl PrimaryKey { thread_local! { static CURRENT: RefCell<Option<PrimaryKey>> = RefCell::new(None) } pub fn current_get() -> Option<PrimaryKey> { PrimaryKey::CURRENT.with(|key| { let key = key.borrow(); return key.clone(); }) } pub fn current_set(val: Option<PrimaryKey>) -> Option<PrimaryKey> { PrimaryKey::CURRENT.with(|key| { let mut key = key.borrow_mut(); match val { Some(a) => key.replace(a), None => key.take(), } }) } #[allow(dead_code)] pub fn generate() -> PrimaryKey { PrimaryKey { key: fastrand::u64(..), } } #[allow(dead_code)] pub fn new(key: u64) -> PrimaryKey { PrimaryKey { key: key } } #[allow(dead_code)] pub fn sizeof() -> u64 { size_of::<u64>() as u64 } pub fn as_hex_string(&self) -> String { format!("{:X?}", self.key).to_string() } pub fn as_fixed_hex_string(&self) -> String { let hex = format!("{:016X?}", self.key).to_string(); let hex = hex.to_lowercase(); format!("{}", &hex[..16]) } pub fn as_u64(&self) -> u64 { self.key } pub fn from_ext(val: AteHash, min: u64, max: u64) -> PrimaryKey { let v = val.val; let bytes = [v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]]; let range = max - min; let key = (u64::from_be_bytes(bytes) % range) + min; PrimaryKey { key } } } impl From<AteHash> for PrimaryKey { fn from(val: AteHash) -> PrimaryKey { let v = val.val; let bytes = [v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]]; PrimaryKey { key: u64::from_be_bytes(bytes), } } } impl From<String> for PrimaryKey { fn from(val: String) -> PrimaryKey { PrimaryKey::from(AteHash::from(val)) } } impl From<&'static str> for PrimaryKey { fn from(val: &'static str) -> PrimaryKey { PrimaryKey::from(AteHash::from(val)) } } impl From<u64> for PrimaryKey { fn from(val: u64) -> PrimaryKey { PrimaryKey { key: val } } } impl std::fmt::Display for PrimaryKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.as_hex_string()) } } #[test] fn test_key_hex() { let key = PrimaryKey::from(1 as u64); assert_eq!(key.as_fixed_hex_string(), "0000000000000001".to_string()); }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/spec/chain_key.rs
crypto/src/spec/chain_key.rs
#[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use crate::crypto::AteHash; use super::PrimaryKey; use serde::{Deserialize, Serialize}; /// Unique key that represents this chain-of-trust. The design must /// partition their data space into seperate chains to improve scalability /// and performance as a single chain will reside on a single node within /// the cluster. #[derive(Serialize, Deserialize, Debug, Clone, Default, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct ChainKey { pub name: String, #[serde(skip)] pub hash: Option<AteHash>, } impl std::fmt::Display for ChainKey { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.name) } } impl ChainKey { pub fn new(mut val: String) -> ChainKey { while val.starts_with("/") == true { val = val[1..].to_string(); } ChainKey { hash: Some(AteHash::from_bytes(val.as_bytes())), name: val, } } pub const ROOT: ChainKey = ChainKey { name: String::new(), hash: None, }; pub fn with_name(&self, val: String) -> ChainKey { let mut ret = self.clone(); ret.name = val; ret } pub fn with_temp_name(&self, val: String) -> ChainKey { let mut ret = self.clone(); ret.name = format!("{}_{}", val, PrimaryKey::generate().as_hex_string()); ret } pub fn hash(&self) -> AteHash { match &self.hash { Some(a) => a.clone(), None => AteHash::from_bytes(self.name.as_bytes()), } } pub fn hash64(&self) -> u64 { match &self.hash { Some(a) => a.to_u64(), None => AteHash::from_bytes(self.name.as_bytes()).to_u64(), } } pub fn to_string(&self) -> String { self.name.clone() } } impl From<String> for ChainKey { fn from(val: String) -> ChainKey { ChainKey::new(val) } } impl From<&'static str> for ChainKey { fn from(val: &'static str) -> ChainKey { ChainKey::new(val.to_string()) } } impl From<u64> for ChainKey { fn from(val: u64) -> ChainKey { ChainKey::new(val.to_string()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/double_hash.rs
crypto/src/crypto/double_hash.rs
use serde::{Deserialize, Serialize}; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use super::*; #[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, Eq, PartialEq)] pub struct DoubleHash { hash1: AteHash, hash2: AteHash, } impl DoubleHash { #[allow(dead_code)] pub fn from_hashes(hash1: &AteHash, hash2: &AteHash) -> DoubleHash { DoubleHash { hash1: hash1.clone(), hash2: hash2.clone(), } } pub fn hash(&self) -> AteHash { AteHash::from_bytes_twice(&self.hash1.val[..], &self.hash2.val[..]) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/fast_random.rs
crypto/src/crypto/fast_random.rs
use once_cell::sync::Lazy; use rand::{rngs::adapter::ReseedingRng, RngCore, SeedableRng}; use rand_chacha::{ChaCha20Core, ChaCha20Rng}; use std::result::Result; use std::sync::{Mutex, MutexGuard}; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; static GLOBAL_SECURE_AND_FAST_RANDOM: Lazy<Mutex<ChaCha20Rng>> = Lazy::new(|| Mutex::new(ChaCha20Rng::from_entropy())); #[derive(Default)] pub(super) struct SingleThreadedSecureAndFastRandom {} impl<'a> SingleThreadedSecureAndFastRandom { pub(super) fn lock(&'a mut self) -> MutexGuard<'static, ChaCha20Rng> { GLOBAL_SECURE_AND_FAST_RANDOM .lock() .expect("Failed to create the crypto generator seedering engine") } } impl<'a> RngCore for SingleThreadedSecureAndFastRandom { fn next_u32(&mut self) -> u32 { self.lock().next_u32() } fn next_u64(&mut self) -> u64 { self.lock().next_u64() } fn fill_bytes(&mut self, dest: &mut [u8]) { self.lock().fill_bytes(dest) } fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> { self.lock().try_fill_bytes(dest) } } pub(super) struct SecureAndFastRandom { pub(super) rng: Box<dyn RngCore>, } impl SecureAndFastRandom { pub(super) fn new() -> SecureAndFastRandom { let mut seeder = SingleThreadedSecureAndFastRandom::default(); let rng = ChaCha20Core::from_rng(&mut seeder) .expect("Failed to properly seed the secure random number generator"); let reseeding_rng = ReseedingRng::new(rng, 0, seeder); SecureAndFastRandom { rng: Box::new(reseeding_rng), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/sign_key.rs
crypto/src/crypto/sign_key.rs
use crate::utils::vec_deserialize; use crate::utils::vec_serialize; use pqcrypto_falcon_wasi::falcon1024; use pqcrypto_falcon_wasi::falcon512; use pqcrypto_traits_wasi::sign::SecretKey as PQCryptoSecretKey; use pqcrypto_traits_wasi::sign::{DetachedSignature, PublicKey as PQCryptoPublicKey}; use serde::{Deserialize, Serialize}; use std::io::ErrorKind; use std::result::Result; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use super::*; /// Private keys provide the ability to sign records within the /// redo log chain-of-trust, these inserts records with associated /// public keys embedded within teh cahin allow /// records/events stored within the ATE redo log to have integrity /// without actually being able to read the records themselves. This /// attribute allows a chain-of-trust to be built without access to /// the data held within of chain. Asymetric crypto in ATE uses the /// leading candidates from NIST that provide protection against /// quantom computer attacks #[derive(Serialize, Deserialize, Debug, Clone, Hash, Eq, PartialEq)] pub enum PrivateSignKey { Falcon512 { pk: PublicSignKey, #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] sk: Vec<u8>, }, Falcon1024 { pk: PublicSignKey, #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] sk: Vec<u8>, }, } impl PrivateSignKey { #[allow(dead_code)] pub fn generate(size: KeySize) -> PrivateSignKey { match size { KeySize::Bit128 | KeySize::Bit192 => { let (pk, sk) = falcon512::keypair(); PrivateSignKey::Falcon512 { pk: PublicSignKey::Falcon512 { pk: Vec::from(pk.as_bytes()), }, sk: Vec::from(sk.as_bytes()), } } KeySize::Bit256 => { let (pk, sk) = falcon1024::keypair(); PrivateSignKey::Falcon1024 { pk: PublicSignKey::Falcon1024 { pk: Vec::from(pk.as_bytes()), }, sk: Vec::from(sk.as_bytes()), } } } } #[allow(dead_code)] pub fn as_public_key<'a>(&'a self) -> &'a PublicSignKey { match &self { PrivateSignKey::Falcon512 { sk: _, pk } => pk, PrivateSignKey::Falcon1024 { sk: _, pk } => pk, } } #[allow(dead_code)] pub fn hash(&self) -> AteHash { match &self { PrivateSignKey::Falcon512 { pk, sk: _ } => pk.hash(), PrivateSignKey::Falcon1024 { pk, sk: _ } => pk.hash(), } } #[allow(dead_code)] pub fn pk<'a>(&'a self) -> &'a [u8] { match &self { PrivateSignKey::Falcon512 { pk, sk: _ } => pk.pk(), PrivateSignKey::Falcon1024 { pk, sk: _ } => pk.pk(), } } #[allow(dead_code)] pub fn sk<'a>(&'a self) -> &'a [u8] { match &self { PrivateSignKey::Falcon512 { pk: _, sk } => &sk[..], PrivateSignKey::Falcon1024 { pk: _, sk } => &sk[..], } } #[allow(dead_code)] pub fn sign(&self, data: &[u8]) -> Result<Vec<u8>, std::io::Error> { let ret = match &self { PrivateSignKey::Falcon512 { pk: _, sk } => { let sk = match falcon512::SecretKey::from_bytes(&sk[..]) { Ok(sk) => sk, Err(err) => { return Result::Err(std::io::Error::new( ErrorKind::Other, format!("Failed to decode the secret key ({}).", err), )); } }; let sig = falcon512::detached_sign(data, &sk); Vec::from(sig.as_bytes()) } PrivateSignKey::Falcon1024 { pk: _, sk } => { let sk = match falcon1024::SecretKey::from_bytes(&sk[..]) { Ok(sk) => sk, Err(err) => { return Result::Err(std::io::Error::new( ErrorKind::Other, format!("Failed to decode the secret key ({}).", err), )); } }; let sig = falcon1024::detached_sign(data, &sk); Vec::from(sig.as_bytes()) } }; Ok(ret) } pub fn size(&self) -> KeySize { match &self { PrivateSignKey::Falcon512 { pk: _, sk: _ } => KeySize::Bit192, PrivateSignKey::Falcon1024 { pk: _, sk: _ } => KeySize::Bit256, } } } impl std::fmt::Display for PrivateSignKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { PrivateSignKey::Falcon512 { pk: _, sk: _ } => { write!(f, "falcon512:pk:{}+sk", self.hash()) } PrivateSignKey::Falcon1024 { pk: _, sk: _ } => { write!(f, "falcon1024:pk:{}+sk", self.hash()) } } } } /// Public key which is one side of a private key. Public keys allow /// records/events stored within the ATE redo log to have integrity /// without actually being able to read the records themselves. This /// attribute allows a chain-of-trust to be built without access to /// the data held within of chain. Asymetric crypto in ATE uses the /// leading candidates from NIST that provide protection against /// quantom computer attacks #[derive(Serialize, Deserialize, Debug, Clone, Hash, Eq, PartialEq)] pub enum PublicSignKey { Falcon512 { #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] pk: Vec<u8>, }, Falcon1024 { #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] pk: Vec<u8>, }, } impl PublicSignKey { #[allow(dead_code)] pub fn pk<'a>(&'a self) -> &'a [u8] { match &self { PublicSignKey::Falcon512 { pk } => &pk[..], PublicSignKey::Falcon1024 { pk } => &pk[..], } } #[allow(dead_code)] pub fn hash(&self) -> AteHash { match &self { PublicSignKey::Falcon512 { pk } => AteHash::from_bytes(&pk[..]), PublicSignKey::Falcon1024 { pk } => AteHash::from_bytes(&pk[..]), } } #[allow(dead_code)] pub fn verify(&self, data: &[u8], sig: &[u8]) -> Result<bool, pqcrypto_traits_wasi::Error> { let ret = match &self { PublicSignKey::Falcon512 { pk } => { let pk = falcon512::PublicKey::from_bytes(&pk[..])?; let sig = falcon512::DetachedSignature::from_bytes(sig)?; falcon512::verify_detached_signature(&sig, data, &pk).is_ok() } PublicSignKey::Falcon1024 { pk } => { let pk = falcon1024::PublicKey::from_bytes(&pk[..])?; let sig = falcon1024::DetachedSignature::from_bytes(sig)?; falcon1024::verify_detached_signature(&sig, data, &pk).is_ok() } }; Ok(ret) } } impl std::fmt::Display for PublicSignKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { PublicSignKey::Falcon512 { pk: _ } => write!(f, "falcon512:pk:{}", self.hash()), PublicSignKey::Falcon1024 { pk: _ } => write!(f, "falcon1024:pk:{}", self.hash()), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/random_generator_accessor.rs
crypto/src/crypto/random_generator_accessor.rs
use rand::RngCore; use std::cell::RefCell; use std::result::Result; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use super::fast_random::*; use super::*; thread_local! { static THREAD_LOCAL_SECURE_AND_FAST_RANDOM: RefCell<SecureAndFastRandom> = RefCell::new(SecureAndFastRandom::new()); } #[derive(Default)] pub struct RandomGeneratorAccessor {} impl RngCore for RandomGeneratorAccessor { fn next_u32(&mut self) -> u32 { THREAD_LOCAL_SECURE_AND_FAST_RANDOM.with(|s| s.borrow_mut().rng.next_u32()) } fn next_u64(&mut self) -> u64 { THREAD_LOCAL_SECURE_AND_FAST_RANDOM.with(|s| s.borrow_mut().rng.next_u64()) } fn fill_bytes(&mut self, dest: &mut [u8]) { THREAD_LOCAL_SECURE_AND_FAST_RANDOM.with(|s| s.borrow_mut().rng.fill_bytes(dest)) } fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> { THREAD_LOCAL_SECURE_AND_FAST_RANDOM.with(|s| s.borrow_mut().rng.try_fill_bytes(dest)) } } impl RandomGeneratorAccessor { pub fn generate_encrypt_key(size: KeySize) -> EncryptKey { THREAD_LOCAL_SECURE_AND_FAST_RANDOM.with(|s| { let rng = &mut s.borrow_mut().rng; match size { KeySize::Bit128 => { let mut aes_key = [0; 16]; rng.fill_bytes(&mut aes_key); EncryptKey::Aes128(aes_key) } KeySize::Bit192 => { let mut aes_key = [0; 24]; rng.fill_bytes(&mut aes_key); EncryptKey::Aes192(aes_key) } KeySize::Bit256 => { let mut aes_key = [0; 32]; rng.fill_bytes(&mut aes_key); EncryptKey::Aes256(aes_key) } } }) } pub fn generate_hash() -> AteHash { THREAD_LOCAL_SECURE_AND_FAST_RANDOM.with(|s| { let rng = &mut s.borrow_mut().rng; let mut val = [0; 16]; rng.fill_bytes(&mut val); AteHash { val } }) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/tests.rs
crypto/src/crypto/tests.rs
#![cfg(test)] use crate::error::*; use std::result::Result; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use serde::{Serialize, Deserialize}; use rand::RngCore; use super::*; #[test] fn test_secure_random() { crate::utils::bootstrap_test_env(); let t = 1024; for _ in 0..t { let mut data = [0 as u8; 1024]; RandomGeneratorAccessor::default().fill_bytes(&mut data); } } #[test] fn test_encrypt_key_seeding_new() { crate::utils::bootstrap_test_env(); let provided = EncryptKey::from_seed_string("test".to_string(), KeySize::Bit256); let expected = EncryptKey::Aes256([ 83, 208, 186, 19, 115, 7, 212, 194, 249, 182, 103, 76, 131, 237, 189, 88, 183, 12, 15, 67, 64, 19, 62, 208, 173, 198, 251, 161, 210, 71, 138, 106, ]); assert_eq!(provided, expected); let provided = EncryptKey::from_seed_string("test2".to_string(), KeySize::Bit256); let expected = EncryptKey::Aes256([ 159, 117, 193, 157, 58, 233, 178, 104, 76, 27, 193, 46, 126, 60, 139, 195, 55, 116, 66, 157, 228, 23, 223, 83, 106, 242, 81, 107, 17, 200, 1, 157, ]); assert_eq!(provided, expected); } #[test] fn test_asym_crypto_128() { crate::utils::bootstrap_test_env(); let key = EncryptKey::generate(KeySize::Bit128); let private = EncryptedPrivateKey::generate(&key); let public = private.as_public_key(); let plain = b"test"; let sig = private.as_private_key(&key).sign(plain).unwrap(); assert!( public.verify(plain, &sig[..]).unwrap(), "Signature verificaton failed" ); let negative = b"blahtest"; assert!( public.verify(negative, &sig[..]).unwrap() == false, "Signature verificaton passes when it should not" ); } #[test] fn test_asym_crypto_256() { crate::utils::bootstrap_test_env(); let key = EncryptKey::generate(KeySize::Bit256); let private = EncryptedPrivateKey::generate(&key); let public = private.as_public_key(); let plain = b"test"; let sig = private.as_private_key(&key).sign(plain).unwrap(); assert!( public.verify(plain, &sig[..]).unwrap(), "Signature verificaton failed" ); let negative = b"blahtest"; assert!( public.verify(negative, &sig[..]).unwrap() == false, "Signature verificaton passes when it should not" ); } #[test] fn test_ntru_encapsulate() -> Result<(), CryptoError> { crate::utils::bootstrap_test_env(); static KEY_SIZES: [KeySize; 3] = [KeySize::Bit128, KeySize::Bit192, KeySize::Bit256]; for key_size in KEY_SIZES.iter() { let sk = PrivateEncryptKey::generate(key_size.clone()); let pk = sk.as_public_key(); let (iv, ek1) = pk.encapsulate(); let ek2 = sk.decapsulate(&iv).unwrap(); assert_eq!(ek1.hash(), ek2.hash()); let plain_text1 = "the cat ran up the wall".to_string(); let cipher_text = ek1.encrypt(plain_text1.as_bytes()); let plain_test2 = String::from_utf8(ek2.decrypt(&cipher_text.iv, &cipher_text.data)).unwrap(); assert_eq!(plain_text1, plain_test2); } Ok(()) } #[test] fn test_ntru_encrypt() -> Result<(), Box<dyn std::error::Error>> { crate::utils::bootstrap_test_env(); static KEY_SIZES: [KeySize; 3] = [KeySize::Bit128, KeySize::Bit192, KeySize::Bit256]; for key_size in KEY_SIZES.iter() { let sk = PrivateEncryptKey::generate(key_size.clone()); let pk = sk.as_public_key(); let plain_text1 = "the cat ran up the wall".to_string(); let cipher_text = pk.encrypt(plain_text1.as_bytes()); let plain_test2 = String::from_utf8(sk.decrypt(&cipher_text.iv, &cipher_text.data)?).unwrap(); assert_eq!(plain_text1, plain_test2); } Ok(()) } #[test] fn test_derived_keys() -> Result<(), Box<dyn std::error::Error>> { static KEY_SIZES: [KeySize; 3] = [KeySize::Bit128, KeySize::Bit192, KeySize::Bit256]; for key_size1 in KEY_SIZES.iter() { for key_size2 in KEY_SIZES.iter() { // Generate a derived key and encryption key let key2 = EncryptKey::generate(*key_size1); let mut key1 = DerivedEncryptKey::new(&key2); // Encrypt some data let plain_text1 = "the cat ran up the wall".to_string(); let encrypted_text1 = key1.transmute(&key2)?.encrypt(plain_text1.as_bytes()); // Check that it decrypts properly let plain_text2 = String::from_utf8( key1.transmute(&key2)? .decrypt(&encrypted_text1.iv, &encrypted_text1.data[..]), ) .unwrap(); assert_eq!(plain_text1, plain_text2); // Now change the key let key3 = EncryptKey::generate(*key_size2); key1.change(&key2, &key3)?; // The decryption with the old key which should now fail let plain_text2 = match String::from_utf8( key1.transmute(&key2)? .decrypt(&encrypted_text1.iv, &encrypted_text1.data[..]), ) { Ok(a) => a, Err(_) => "nothing".to_string(), }; assert_ne!(plain_text1, plain_text2); // Check that it decrypts properly with the new key let plain_text2 = String::from_utf8( key1.transmute(&key3)? .decrypt(&encrypted_text1.iv, &encrypted_text1.data[..]), ) .unwrap(); assert_eq!(plain_text1, plain_text2); } } Ok(()) } #[test] fn test_public_secure_data() -> Result<(), Box<dyn std::error::Error>> { crate::utils::bootstrap_test_env(); #[derive(Debug, Serialize, Deserialize, Clone)] struct TestClass { data: String, } static KEY_SIZES: [KeySize; 3] = [KeySize::Bit128, KeySize::Bit192, KeySize::Bit256]; for key_size in KEY_SIZES.iter() { let key = PrivateEncryptKey::generate(key_size.clone()); let container = PublicEncryptedSecureData::<TestClass>::new(key.as_public_key(), TestClass { data: "the cat ran up the wall".to_string() }).unwrap(); let out = container.unwrap(&key).unwrap(); assert_eq!(out.data.as_str(), "the cat ran up the wall"); } Ok(()) } #[test] fn test_secure_data() -> Result<(), Box<dyn std::error::Error>> { crate::utils::bootstrap_test_env(); static KEY_SIZES: [KeySize; 3] = [KeySize::Bit128, KeySize::Bit192, KeySize::Bit256]; for key_size in KEY_SIZES.iter() { let client1 = EncryptKey::generate(key_size.clone()); let plain_text1 = "the cat ran up the wall".to_string(); let cipher = EncryptedSecureData::new(&client1, plain_text1.clone())?; let plain_text2 = cipher.unwrap(&client1).expect("Should have decrypted."); assert_eq!(plain_text1, plain_text2); } Ok(()) } #[test] fn test_multi_encrypt() -> Result<(), Box<dyn std::error::Error>> { crate::utils::bootstrap_test_env(); static KEY_SIZES: [KeySize; 3] = [KeySize::Bit128, KeySize::Bit192, KeySize::Bit256]; for key_size in KEY_SIZES.iter() { let client1 = PrivateEncryptKey::generate(key_size.clone()); let client2 = PrivateEncryptKey::generate(key_size.clone()); let client3 = PrivateEncryptKey::generate(key_size.clone()); let plain_text1 = "the cat ran up the wall".to_string(); let mut multi = MultiEncryptedSecureData::new( &client1.as_public_key(), "meta".to_string(), plain_text1.clone(), )?; multi.add( &client2.as_public_key(), "another_meta".to_string(), &client1, )?; let plain_text2 = multi.unwrap(&client1)?.expect("Should have decrypted."); assert_eq!(plain_text1, plain_text2); let plain_text2 = multi.unwrap(&client2)?.expect("Should have decrypted."); assert_eq!(plain_text1, plain_text2); let plain_text2 = multi.unwrap(&client3)?; assert!( plain_text2.is_none(), "The last client should not load anything" ); } Ok(()) } #[test] fn test_signed_protected_data() -> Result<(), Box<dyn std::error::Error>> { let sign_key = PrivateSignKey::generate(KeySize::Bit256); let data = "test data".to_string(); let test = SignedProtectedData::new(&sign_key, data)?; assert!( test.verify(&sign_key.as_public_key())?, "Failed to verify the protected data" ); Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/encrypted_secure_data.rs
crypto/src/crypto/encrypted_secure_data.rs
use crate::spec::SerializationFormat; use crate::utils::vec_deserialize; use crate::utils::vec_serialize; use serde::{Deserialize, Serialize}; use std::result::Result; use std::{io::ErrorKind, marker::PhantomData}; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use super::*; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct EncryptedSecureData<T> where T: serde::Serialize + serde::de::DeserializeOwned, { format: SerializationFormat, ek_hash: AteHash, sd_iv: InitializationVector, #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] sd_encrypted: Vec<u8>, #[serde(skip)] _marker: std::marker::PhantomData<T>, } impl<T> EncryptedSecureData<T> where T: serde::Serialize + serde::de::DeserializeOwned, { pub fn new( encrypt_key: &EncryptKey, data: T, ) -> Result<EncryptedSecureData<T>, std::io::Error> { let format = SerializationFormat::Bincode; let data = match format.serialize(data) { Ok(a) => a, Err(err) => { return Err(std::io::Error::new(ErrorKind::Other, err.to_string())); } }; let result = encrypt_key.encrypt(&data[..]); Ok(EncryptedSecureData { format, ek_hash: encrypt_key.hash(), sd_iv: result.iv, sd_encrypted: result.data, _marker: PhantomData, }) } pub fn unwrap(&self, key: &EncryptKey) -> Result<T, std::io::Error> { let data = key.decrypt(&self.sd_iv, &self.sd_encrypted[..]); Ok(match self.format.deserialize_ref(&data[..]) { Ok(a) => a, Err(err) => { return Err(std::io::Error::new(ErrorKind::Other, err.to_string())); } }) } pub fn ek_hash(&self) -> AteHash { self.ek_hash } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/key_size.rs
crypto/src/crypto/key_size.rs
use serde::{Deserialize, Serialize}; use std::result::Result; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; /// Size of a cryptographic key, smaller keys are still very secure but /// have less room in the future should new attacks be found against the /// crypto algorithms used by ATE. #[repr(u8)] #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum KeySize { #[allow(dead_code)] Bit128 = 16, #[allow(dead_code)] Bit192 = 24, #[allow(dead_code)] Bit256 = 32, } impl KeySize { pub fn as_str(&self) -> &str { match &self { KeySize::Bit128 => "128", KeySize::Bit192 => "192", KeySize::Bit256 => "256", } } } impl std::str::FromStr for KeySize { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "128" => Ok(KeySize::Bit128), "192" => Ok(KeySize::Bit192), "256" => Ok(KeySize::Bit256), _ => Err("valid values are '128', '192', '256'"), } } } impl std::fmt::Display for KeySize { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { KeySize::Bit128 => write!(f, "128"), KeySize::Bit192 => write!(f, "192"), KeySize::Bit256 => write!(f, "256"), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/short_hash.rs
crypto/src/crypto/short_hash.rs
use serde::{Deserialize, Serialize}; use sha3::Digest; use std::convert::TryInto; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use crate::crypto::HashRoutine; /// Represents a hash of a piece of data that is cryptographically secure enough /// that it can be used for integrity but small enough that it does not bloat /// the redo log metadata. #[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd)] pub struct ShortHash { pub val: u32, } impl ShortHash { pub fn from_bytes(input: &[u8]) -> ShortHash { Self::from_bytes_by_routine(input, crate::HASH_ROUTINE) } pub fn from_bytes_twice(input1: &[u8], input2: &[u8]) -> ShortHash { Self::from_bytes_twice_by_routine(input1, input2, crate::HASH_ROUTINE) } fn from_bytes_by_routine(input: &[u8], routine: HashRoutine) -> ShortHash { match routine { HashRoutine::Sha3 => ShortHash::from_bytes_sha3(input, 1), HashRoutine::Blake3 => ShortHash::from_bytes_blake3(input), } } fn from_bytes_twice_by_routine( input1: &[u8], input2: &[u8], routine: HashRoutine, ) -> ShortHash { match routine { HashRoutine::Sha3 => ShortHash::from_bytes_twice_sha3(input1, input2), HashRoutine::Blake3 => ShortHash::from_bytes_twice_blake3(input1, input2), } } pub fn from_bytes_blake3(input: &[u8]) -> ShortHash { let hash = blake3::hash(input); let bytes: [u8; 32] = hash.into(); let mut bytes4: [u8; 4] = Default::default(); bytes4.copy_from_slice(&bytes[0..4]); ShortHash { val: u32::from_be_bytes(bytes4), } } fn from_bytes_twice_blake3(input1: &[u8], input2: &[u8]) -> ShortHash { let mut hasher = blake3::Hasher::new(); hasher.update(input1); hasher.update(input2); let hash = hasher.finalize(); let bytes: [u8; 32] = hash.into(); let mut bytes4: [u8; 4] = Default::default(); bytes4.copy_from_slice(&bytes[0..4]); ShortHash { val: u32::from_be_bytes(bytes4), } } pub fn from_bytes_sha3(input: &[u8], repeat: i32) -> ShortHash { let mut hasher = sha3::Keccak384::new(); for _ in 0..repeat { hasher.update(input); } let result = hasher.finalize(); let result: Vec<u8> = result.into_iter().take(4).collect(); let result: [u8; 4] = result .try_into() .expect("The hash should fit into 4 bytes!"); let result = u32::from_be_bytes(result); ShortHash { val: result } } fn from_bytes_twice_sha3(input1: &[u8], input2: &[u8]) -> ShortHash { let mut hasher = sha3::Keccak384::new(); hasher.update(input1); hasher.update(input2); let result = hasher.finalize(); let result = result.iter().take(4).map(|b| *b).collect::<Vec<_>>(); let result: [u8; 4] = result .try_into() .expect("The hash should fit into 4 bytes!"); let result = u32::from_be_bytes(result); ShortHash { val: result } } pub fn to_hex_string(&self) -> String { hex::encode(self.val.to_be_bytes()) } pub fn to_string(&self) -> String { self.to_hex_string() } pub fn to_bytes(&self) -> [u8; 4] { self.val.to_be_bytes() } } impl From<String> for ShortHash { fn from(val: String) -> ShortHash { ShortHash::from_bytes(val.as_bytes()) } } impl From<&'static str> for ShortHash { fn from(val: &'static str) -> ShortHash { ShortHash::from(val.to_string()) } } impl From<u64> for ShortHash { fn from(val: u64) -> ShortHash { ShortHash::from_bytes(&val.to_be_bytes()) } } impl std::fmt::Display for ShortHash { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.to_string()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/private_encrypt_key.rs
crypto/src/crypto/private_encrypt_key.rs
use crate::utils::vec_deserialize; use crate::utils::vec_serialize; use pqcrypto_ntru_wasi::ntruhps2048509 as ntru128; use pqcrypto_ntru_wasi::ntruhps2048677 as ntru192; use pqcrypto_ntru_wasi::ntruhps4096821 as ntru256; use pqcrypto_traits_wasi::kem::*; use serde::{Deserialize, Serialize}; use std::result::Result; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use super::*; /// Private encryption keys provide the ability to decrypt a secret /// that was encrypted using a Public Key - this capability is /// useful for key-exchange and trust validation in the crypto chain. /// Asymetric crypto in ATE uses the leading candidates from NIST /// that provide protection against quantom computer attacks #[derive(Serialize, Deserialize, Debug, Clone, Hash, Eq, PartialEq)] pub enum PrivateEncryptKey { Ntru128 { pk: PublicEncryptKey, #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] sk: Vec<u8>, }, Ntru192 { pk: PublicEncryptKey, #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] sk: Vec<u8>, }, Ntru256 { pk: PublicEncryptKey, #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] sk: Vec<u8>, }, } impl PrivateEncryptKey { #[allow(dead_code)] pub fn generate(size: KeySize) -> PrivateEncryptKey { match size { KeySize::Bit128 => { let (pk, sk) = ntru128::keypair(); PrivateEncryptKey::Ntru128 { pk: PublicEncryptKey::Ntru128 { pk: Vec::from(pk.as_bytes()), }, sk: Vec::from(sk.as_bytes()), } } KeySize::Bit192 => { let (pk, sk) = ntru192::keypair(); PrivateEncryptKey::Ntru192 { pk: PublicEncryptKey::Ntru192 { pk: Vec::from(pk.as_bytes()), }, sk: Vec::from(sk.as_bytes()), } } KeySize::Bit256 => { let (pk, sk) = ntru256::keypair(); PrivateEncryptKey::Ntru256 { pk: PublicEncryptKey::Ntru256 { pk: Vec::from(pk.as_bytes()), }, sk: Vec::from(sk.as_bytes()), } } } } #[allow(dead_code)] pub fn as_public_key<'a>(&'a self) -> &'a PublicEncryptKey { match &self { PrivateEncryptKey::Ntru128 { sk: _, pk } => pk, PrivateEncryptKey::Ntru192 { sk: _, pk } => pk, PrivateEncryptKey::Ntru256 { sk: _, pk } => pk, } } #[allow(dead_code)] pub fn hash(&self) -> AteHash { match &self { PrivateEncryptKey::Ntru128 { pk, sk: _ } => pk.hash(), PrivateEncryptKey::Ntru192 { pk, sk: _ } => pk.hash(), PrivateEncryptKey::Ntru256 { pk, sk: _ } => pk.hash(), } } #[allow(dead_code)] pub fn pk<'a>(&'a self) -> &'a [u8] { match &self { PrivateEncryptKey::Ntru128 { pk, sk: _ } => pk.pk(), PrivateEncryptKey::Ntru192 { pk, sk: _ } => pk.pk(), PrivateEncryptKey::Ntru256 { pk, sk: _ } => pk.pk(), } } #[allow(dead_code)] pub fn sk<'a>(&'a self) -> &'a [u8] { match &self { PrivateEncryptKey::Ntru128 { pk: _, sk } => &sk[..], PrivateEncryptKey::Ntru192 { pk: _, sk } => &sk[..], PrivateEncryptKey::Ntru256 { pk: _, sk } => &sk[..], } } #[allow(dead_code)] pub fn decapsulate(&self, iv: &InitializationVector) -> Option<EncryptKey> { match &self { PrivateEncryptKey::Ntru128 { pk: _, sk } => { if iv.bytes.len() != ntru128::ciphertext_bytes() { return None; } let ct = ntru128::Ciphertext::from_bytes(&iv.bytes[..]).unwrap(); let sk = ntru128::SecretKey::from_bytes(&sk[..]).unwrap(); let ss = ntru128::decapsulate(&ct, &sk); Some(EncryptKey::from_seed_bytes(ss.as_bytes(), KeySize::Bit128)) } PrivateEncryptKey::Ntru192 { pk: _, sk } => { if iv.bytes.len() != ntru192::ciphertext_bytes() { return None; } let ct = ntru192::Ciphertext::from_bytes(&iv.bytes[..]).unwrap(); let sk = ntru192::SecretKey::from_bytes(&sk[..]).unwrap(); let ss = ntru192::decapsulate(&ct, &sk); Some(EncryptKey::from_seed_bytes(ss.as_bytes(), KeySize::Bit192)) } PrivateEncryptKey::Ntru256 { pk: _, sk } => { if iv.bytes.len() != ntru256::ciphertext_bytes() { return None; } let ct = ntru256::Ciphertext::from_bytes(&iv.bytes[..]).unwrap(); let sk = ntru256::SecretKey::from_bytes(&sk[..]).unwrap(); let ss = ntru256::decapsulate(&ct, &sk); Some(EncryptKey::from_seed_bytes(ss.as_bytes(), KeySize::Bit256)) } } } pub fn decrypt( &self, iv: &InitializationVector, data: &[u8], ) -> Result<Vec<u8>, std::io::Error> { let ek = match self.decapsulate(iv) { Some(a) => a, None => { return Err(std::io::Error::new( std::io::ErrorKind::Other, "The encryption key could not be decapsulated from the initialization vector.", )); } }; Ok(ek.decrypt(iv, data)) } pub fn decrypt_ext( &self, iv: &InitializationVector, data: &[u8], ek_hash: &AteHash, ) -> Result<Vec<u8>, std::io::Error> { let ek = match self.decapsulate(iv) { Some(a) => a, None => { return Err(std::io::Error::new( std::io::ErrorKind::Other, "The encryption key could not be decapsulated from the initialization vector.", )); } }; if ek.hash() != *ek_hash { return Err(std::io::Error::new( std::io::ErrorKind::Other, format!("The decryption key is not valid for this cipher data ({} vs {}).", ek.hash(), ek_hash).as_str(), )); } Ok(ek.decrypt(iv, data)) } pub fn size(&self) -> KeySize { match &self { PrivateEncryptKey::Ntru128 { pk: _, sk: _ } => KeySize::Bit128, PrivateEncryptKey::Ntru192 { pk: _, sk: _ } => KeySize::Bit192, PrivateEncryptKey::Ntru256 { pk: _, sk: _ } => KeySize::Bit256, } } } impl std::fmt::Display for PrivateEncryptKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { PrivateEncryptKey::Ntru128 { pk: _, sk: _ } => { write!(f, "ntru128:pk:{}+sk", self.hash()) } PrivateEncryptKey::Ntru192 { pk: _, sk: _ } => { write!(f, "ntru192:pk:{}+sk", self.hash()) } PrivateEncryptKey::Ntru256 { pk: _, sk: _ } => { write!(f, "ntru256:pk:{}+sk", self.hash()) } } } } /// Public encryption keys provide the ability to encrypt a secret /// without the ability to decrypt it yourself - this capability is /// useful for key-exchange and trust validation in the crypto chain. /// Asymetric crypto in ATE uses the leading candidates from NIST /// that provide protection against quantom computer attacks #[derive(Serialize, Deserialize, Debug, Clone, Hash, Eq, PartialEq)] pub enum PublicEncryptKey { Ntru128 { #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] pk: Vec<u8>, }, Ntru192 { #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] pk: Vec<u8>, }, Ntru256 { #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] pk: Vec<u8>, }, } impl PublicEncryptKey { pub fn from_bytes(bytes: Vec<u8>) -> Option<PublicEncryptKey> { match bytes.len() { a if a == ntru128::public_key_bytes() => Some(PublicEncryptKey::Ntru128 { pk: bytes }), a if a == ntru192::public_key_bytes() => Some(PublicEncryptKey::Ntru192 { pk: bytes }), a if a == ntru256::public_key_bytes() => Some(PublicEncryptKey::Ntru256 { pk: bytes }), _ => None, } } pub fn pk<'a>(&'a self) -> &'a [u8] { match &self { PublicEncryptKey::Ntru128 { pk } => &pk[..], PublicEncryptKey::Ntru192 { pk } => &pk[..], PublicEncryptKey::Ntru256 { pk } => &pk[..], } } #[allow(dead_code)] pub fn hash(&self) -> AteHash { match &self { PublicEncryptKey::Ntru128 { pk } => AteHash::from_bytes(&pk[..]), PublicEncryptKey::Ntru192 { pk } => AteHash::from_bytes(&pk[..]), PublicEncryptKey::Ntru256 { pk } => AteHash::from_bytes(&pk[..]), } } #[allow(dead_code)] pub fn encapsulate(&self) -> (InitializationVector, EncryptKey) { match &self { PublicEncryptKey::Ntru128 { pk } => { let pk = ntru128::PublicKey::from_bytes(&pk[..]).unwrap(); let (ss, ct) = ntru128::encapsulate(&pk); let iv = InitializationVector::from(ct.as_bytes()); ( iv, EncryptKey::from_seed_bytes(ss.as_bytes(), KeySize::Bit128), ) } PublicEncryptKey::Ntru192 { pk } => { let pk = ntru192::PublicKey::from_bytes(&pk[..]).unwrap(); let (ss, ct) = ntru192::encapsulate(&pk); let iv = InitializationVector::from(ct.as_bytes()); ( iv, EncryptKey::from_seed_bytes(ss.as_bytes(), KeySize::Bit192), ) } PublicEncryptKey::Ntru256 { pk } => { let pk = ntru256::PublicKey::from_bytes(&pk[..]).unwrap(); let (ss, ct) = ntru256::encapsulate(&pk); let iv = InitializationVector::from(ct.as_bytes()); ( iv, EncryptKey::from_seed_bytes(ss.as_bytes(), KeySize::Bit256), ) } } } pub fn encrypt(&self, data: &[u8]) -> EncryptResult { let (iv, ek) = self.encapsulate(); let data = ek.encrypt_with_iv(&iv, data); EncryptResult { iv, data } } pub fn size(&self) -> KeySize { match &self { PublicEncryptKey::Ntru128 { pk: _ } => KeySize::Bit128, PublicEncryptKey::Ntru192 { pk: _ } => KeySize::Bit192, PublicEncryptKey::Ntru256 { pk: _ } => KeySize::Bit256, } } } impl std::fmt::Display for PublicEncryptKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { PublicEncryptKey::Ntru128 { pk: _ } => write!(f, "ntru128:pk:{}", self.hash()), PublicEncryptKey::Ntru192 { pk: _ } => write!(f, "ntru192:pk:{}", self.hash()), PublicEncryptKey::Ntru256 { pk: _ } => write!(f, "ntru256:pk:{}", self.hash()), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/mod.rs
crypto/src/crypto/mod.rs
pub mod derived_encrypt_key; pub mod double_hash; pub mod encrypt_key; #[cfg(feature = "quantum")] pub mod encrypted_private_key; pub mod encrypted_secure_data; pub mod fast_random; pub mod hash; pub mod initialization_vector; pub mod key_size; #[cfg(feature = "quantum")] pub mod private_encrypt_key; #[cfg(feature = "quantum")] pub mod public_encrypted_secure_data; pub mod random_generator_accessor; pub mod short_hash; #[cfg(feature = "quantum")] pub mod sign_key; #[cfg(feature = "quantum")] pub mod signed_protected_data; pub mod tests; pub use double_hash::*; pub use random_generator_accessor::*; pub use self::hash::*; pub use derived_encrypt_key::*; pub use encrypt_key::*; #[cfg(feature = "quantum")] pub use encrypted_private_key::*; pub use encrypted_secure_data::*; pub use initialization_vector::*; pub use key_size::*; #[cfg(feature = "quantum")] pub use private_encrypt_key::*; #[cfg(feature = "quantum")] pub use public_encrypted_secure_data::*; pub use short_hash::*; #[cfg(feature = "quantum")] pub use sign_key::*; #[cfg(feature = "quantum")] pub use signed_protected_data::*; #[cfg(test)] pub use tests::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/signed_protected_data.rs
crypto/src/crypto/signed_protected_data.rs
use crate::spec::SerializationFormat; use crate::utils::vec_deserialize; use crate::utils::vec_serialize; use serde::{Deserialize, Serialize}; use std::io::ErrorKind; use std::result::Result; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use super::*; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct SignedProtectedData<T> { format: SerializationFormat, #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] sig: Vec<u8>, data: T, } impl<T> SignedProtectedData<T> { pub fn new(sign_key: &PrivateSignKey, data: T) -> Result<SignedProtectedData<T>, std::io::Error> where T: Serialize, { let format = SerializationFormat::Bincode; let binary_data = match format.serialize(&data) { Ok(a) => a, Err(err) => { return Err(std::io::Error::new(ErrorKind::Other, err.to_string())); } }; let binary_data_hash = AteHash::from_bytes(&binary_data[..]); let sig = sign_key.sign(&binary_data_hash.val)?; Ok(SignedProtectedData { format, sig, data }) } pub fn verify(&self, key: &PublicSignKey) -> Result<bool, std::io::Error> where T: Serialize, { let binary_data = match self.format.serialize(&self.data) { Ok(a) => a, Err(err) => { return Err(std::io::Error::new(ErrorKind::Other, err.to_string())); } }; let binary_data_hash = AteHash::from_bytes(&binary_data[..]); match key.verify(&binary_data_hash.val, &self.sig[..]) { Ok(a) => Ok(a), Err(err) => Err(std::io::Error::new( std::io::ErrorKind::Other, err.to_string(), )), } } pub fn sig64(&self) -> String { base64::encode(&self.sig) } pub fn sig_hash64(&self) -> String { AteHash::from_bytes(&self.sig[..]).to_string() } } impl<T> std::ops::Deref for SignedProtectedData<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.data } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/hash.rs
crypto/src/crypto/hash.rs
use crate::crypto::RandomGeneratorAccessor; use crate::utils::b16_deserialize; use crate::utils::b16_serialize; use serde::{Deserialize, Serialize}; use sha3::Digest; use std::convert::TryInto; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use super::InitializationVector; #[derive(Debug, Clone, Copy, PartialEq)] pub enum HashRoutine { Sha3, Blake3, } /// Represents a hash of a piece of data that is cryptographically secure enough /// that it can be used for integrity but small enough that it does not bloat /// the redo log metadata. #[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd)] pub struct AteHash { #[serde(serialize_with = "b16_serialize", deserialize_with = "b16_deserialize")] pub val: [u8; 16], } impl AteHash { pub const LEN: usize = 16; pub fn generate() -> AteHash { RandomGeneratorAccessor::generate_hash() } pub fn from_hex_string(input: &str) -> Option<AteHash> { hex::decode(input.trim()) .ok() .map(|a| { let bytes16: Option<[u8; 16]> = a.try_into().ok(); bytes16 }) .flatten() .map(|a| AteHash { val: a }) } pub fn from_bytes(input: &[u8]) -> AteHash { Self::from_bytes_by_routine(input, crate::HASH_ROUTINE) } pub fn from_bytes_twice(input1: &[u8], input2: &[u8]) -> AteHash { Self::from_bytes_twice_by_routine(input1, input2, crate::HASH_ROUTINE) } fn from_bytes_by_routine(input: &[u8], routine: HashRoutine) -> AteHash { match routine { HashRoutine::Sha3 => AteHash::from_bytes_sha3(input, 1), HashRoutine::Blake3 => AteHash::from_bytes_blake3(input), } } fn from_bytes_twice_by_routine(input1: &[u8], input2: &[u8], routine: HashRoutine) -> AteHash { match routine { HashRoutine::Sha3 => AteHash::from_bytes_twice_sha3(input1, input2), HashRoutine::Blake3 => AteHash::from_bytes_twice_blake3(input1, input2), } } pub fn from_bytes_blake3(input: &[u8]) -> AteHash { let hash = blake3::hash(input); let bytes: [u8; 32] = hash.into(); let mut bytes16: [u8; 16] = Default::default(); bytes16.copy_from_slice(&bytes[0..16]); AteHash { val: bytes16 } } fn from_bytes_twice_blake3(input1: &[u8], input2: &[u8]) -> AteHash { let mut hasher = blake3::Hasher::new(); hasher.update(input1); hasher.update(input2); let hash = hasher.finalize(); let bytes: [u8; 32] = hash.into(); let mut bytes16: [u8; 16] = Default::default(); bytes16.copy_from_slice(&bytes[0..16]); AteHash { val: bytes16 } } pub fn from_bytes_sha3(input: &[u8], repeat: i32) -> AteHash { let mut hasher = sha3::Keccak384::default(); for _ in 0..repeat { hasher.update(input); } let result = hasher.finalize(); let result: Vec<u8> = result.into_iter().take(16).collect(); let result: [u8; 16] = result .try_into() .expect("The hash should fit into 16 bytes!"); AteHash { val: result } } fn from_bytes_twice_sha3(input1: &[u8], input2: &[u8]) -> AteHash { let mut hasher = sha3::Keccak384::default(); hasher.update(input1); hasher.update(input2); let result = hasher.finalize(); let result: Vec<u8> = result.into_iter().take(16).collect(); let result: [u8; 16] = result .try_into() .expect("The hash should fit into 16 bytes!"); AteHash { val: result } } pub fn to_u64(&self) -> u64 { let mut val = [0u8; 8]; val.copy_from_slice(&self.val[..8]); u64::from_be_bytes(val) } pub fn to_hex_string(&self) -> String { hex::encode(self.val) } pub fn to_4hex(&self) -> String { let ret = hex::encode(self.val); format!("{}", &ret[..4]) } pub fn to_8hex(&self) -> String { let ret = hex::encode(self.val); format!("{}", &ret[..8]) } pub fn to_string(&self) -> String { self.to_hex_string() } pub fn to_base64(&self) -> String { base64::encode(&self.val[..]) } pub fn as_bytes(&self) -> &[u8; 16] { &self.val } pub fn to_iv(&self) -> InitializationVector { InitializationVector { bytes: self.as_bytes().to_vec() } } pub fn len(&self) -> usize { self.val.len() } } impl From<String> for AteHash { fn from(val: String) -> AteHash { AteHash::from_bytes(val.as_bytes()) } } impl From<&'static str> for AteHash { fn from(val: &'static str) -> AteHash { AteHash::from(val.to_string()) } } impl From<u64> for AteHash { fn from(val: u64) -> AteHash { AteHash::from_bytes(&val.to_be_bytes()) } } impl From<[u8; 16]> for AteHash { fn from(val: [u8; 16]) -> AteHash { AteHash { val, } } } impl std::fmt::Display for AteHash { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.to_string()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/initialization_vector.rs
crypto/src/crypto/initialization_vector.rs
use crate::utils::vec_deserialize; use crate::utils::vec_serialize; use rand::RngCore; use serde::{Deserialize, Serialize}; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use super::*; /// Represents an initiailization vector used for both hash prefixing /// to create entropy and help prevent rainbow table attacks. These /// vectors are also used as the exchange medium during a key exchange /// so that two parties can established a shared secret key #[derive(Serialize, Deserialize, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct InitializationVector { #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] pub bytes: Vec<u8>, } impl InitializationVector { pub fn generate() -> InitializationVector { let mut rng = RandomGeneratorAccessor::default(); let mut iv = InitializationVector { bytes: vec![0 as u8; 16], }; rng.fill_bytes(&mut iv.bytes); iv } pub fn len(&self) -> usize { self.bytes.len() } pub fn as_bytes<'a>(&'a self) -> &'a [u8] { &self.bytes[..] } } impl From<Vec<u8>> for InitializationVector { fn from(bytes: Vec<u8>) -> InitializationVector { InitializationVector { bytes } } } impl From<&[u8]> for InitializationVector { fn from(bytes: &[u8]) -> InitializationVector { InitializationVector { bytes: bytes.to_vec(), } } } impl From<&[u8; 16]> for InitializationVector { fn from(bytes: &[u8; 16]) -> InitializationVector { InitializationVector { bytes: bytes.to_vec(), } } } impl std::fmt::Display for InitializationVector { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", hex::encode(&self.bytes[..])) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/public_encrypted_secure_data.rs
crypto/src/crypto/public_encrypted_secure_data.rs
use crate::spec::SerializationFormat; use crate::utils::vec_deserialize; use crate::utils::vec_serialize; use fxhash::FxHashMap; use serde::{Deserialize, Serialize}; use std::result::Result; use std::{io::ErrorKind, marker::PhantomData}; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use super::*; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct PublicEncryptedSecureData<T> where T: serde::Serialize + serde::de::DeserializeOwned, { format: SerializationFormat, ek_hash: AteHash, sd_iv: InitializationVector, #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] sd_encrypted: Vec<u8>, #[serde(skip)] _marker: std::marker::PhantomData<T>, } impl<T> PublicEncryptedSecureData<T> where T: serde::Serialize + serde::de::DeserializeOwned, { pub fn new( encrypt_key: &PublicEncryptKey, data: T, ) -> Result<PublicEncryptedSecureData<T>, std::io::Error> { let format = SerializationFormat::Bincode; let data = match format.serialize(&data) { Ok(a) => a, Err(err) => { return Err(std::io::Error::new(ErrorKind::Other, err.to_string())); } }; let result = encrypt_key.encrypt(&data[..]); Ok(PublicEncryptedSecureData { format, ek_hash: encrypt_key.hash(), sd_iv: result.iv, sd_encrypted: result.data, _marker: PhantomData, }) } pub fn unwrap(&self, key: &PrivateEncryptKey) -> Result<T, std::io::Error> { if key.hash() != self.ek_hash { return Err(std::io::Error::new( std::io::ErrorKind::Other, format!("The decryption key is not valid for this cipher data ({} vs {}).", key.hash(), self.ek_hash).as_str(), )); } let data = key.decrypt(&self.sd_iv, &self.sd_encrypted[..]).unwrap(); Ok(match self.format.deserialize_ref(&data[..]) { Ok(a) => a, Err(err) => { return Err(std::io::Error::new(ErrorKind::Other, err.to_string())); } }) } pub fn ek_hash(&self) -> AteHash { self.ek_hash } } impl<T> std::fmt::Display for PublicEncryptedSecureData<T> where T: serde::Serialize + serde::de::DeserializeOwned { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "secure_data(format={},ek_hash={},size={})", self.format, self.ek_hash, self.sd_encrypted.len()) } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct MultiEncryptedSecureData<T> where T: serde::Serialize + serde::de::DeserializeOwned, { format: SerializationFormat, members: FxHashMap<String, PublicEncryptedSecureData<EncryptKey>>, metadata: FxHashMap<String, String>, sd_iv: InitializationVector, sd_hash: AteHash, #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] sd_encrypted: Vec<u8>, #[serde(skip)] _marker2: std::marker::PhantomData<T>, } impl<T> MultiEncryptedSecureData<T> where T: serde::Serialize + serde::de::DeserializeOwned, { pub fn new( encrypt_key: &PublicEncryptKey, meta: String, data: T, ) -> Result<MultiEncryptedSecureData<T>, std::io::Error> { let shared_key = EncryptKey::generate(encrypt_key.size()); MultiEncryptedSecureData::new_ext(encrypt_key, shared_key, meta, data) } pub fn new_ext( encrypt_key: &PublicEncryptKey, shared_key: EncryptKey, meta: String, data: T, ) -> Result<MultiEncryptedSecureData<T>, std::io::Error> { let format = SerializationFormat::Bincode; let index = encrypt_key.hash().to_hex_string(); let mut members = FxHashMap::default(); members.insert( index.clone(), PublicEncryptedSecureData::new(encrypt_key, shared_key)?, ); let mut metadata = FxHashMap::default(); metadata.insert(index, meta); let data = match format.serialize(&data) { Ok(a) => a, Err(err) => { return Err(std::io::Error::new(ErrorKind::Other, err.to_string())); } }; let result = shared_key.encrypt(&data[..]); let hash = AteHash::from_bytes_twice(&result.iv.bytes[..], &data[..]); Ok(MultiEncryptedSecureData { format, members, metadata, sd_iv: result.iv, sd_hash: hash, sd_encrypted: result.data, _marker2: PhantomData, }) } pub fn unwrap(&self, key: &PrivateEncryptKey) -> Result<Option<T>, std::io::Error> { Ok(match self.members.get(&key.hash().to_hex_string()) { Some(a) => { let shared_key = a.unwrap(key)?; let data = shared_key.decrypt(&self.sd_iv, &self.sd_encrypted[..]); Some(match self.format.deserialize_ref::<T>(&data[..]) { Ok(a) => a, Err(err) => { return Err(std::io::Error::new(ErrorKind::Other, err.to_string())); } }) } None => None, }) } pub fn unwrap_shared(&self, shared_key: &EncryptKey) -> Result<Option<T>, std::io::Error> { let data = shared_key.decrypt(&self.sd_iv, &self.sd_encrypted[..]); let hash = AteHash::from_bytes_twice(&self.sd_iv.bytes[..], &data[..]); if hash != self.sd_hash { return Ok(None); } Ok(match self.format.deserialize::<T>(data) { Ok(a) => Some(a), Err(err) => { return Err(std::io::Error::new(ErrorKind::Other, err.to_string())); } }) } pub fn add( &mut self, encrypt_key: &PublicEncryptKey, meta: String, referrer: &PrivateEncryptKey, ) -> Result<bool, std::io::Error> { match self.members.get(&referrer.hash().to_hex_string()) { Some(a) => { let shared_key = a.unwrap(referrer)?; let index = encrypt_key.hash().to_hex_string(); self.members.insert( index.clone(), PublicEncryptedSecureData::new(encrypt_key, shared_key)?, ); self.metadata.insert(index, meta); Ok(true) } None => Ok(false), } } pub fn remove(&mut self, what: &AteHash) -> bool { let index = what.to_hex_string(); let ret = self.members.remove(&index).is_some(); self.metadata.remove(&index); ret } pub fn exists(&self, what: &AteHash) -> bool { let what = what.to_hex_string(); self.members.contains_key(&what) } pub fn meta<'a>(&'a self, what: &AteHash) -> Option<&'a String> { let index = what.to_hex_string(); self.metadata.get(&index) } pub fn meta_list<'a>(&'a self) -> impl Iterator<Item = &'a String> { self.metadata.values() } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/encrypted_private_key.rs
crypto/src/crypto/encrypted_private_key.rs
use crate::utils::vec_deserialize; use crate::utils::vec_serialize; use serde::{Deserialize, Serialize}; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use super::*; #[derive(Serialize, Deserialize, Debug, Clone, Hash, Eq, PartialEq)] pub struct EncryptedPrivateKey { pk: PublicSignKey, ek_hash: AteHash, sk_iv: InitializationVector, #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] sk_encrypted: Vec<u8>, } impl EncryptedPrivateKey { #[allow(dead_code)] pub fn generate(encrypt_key: &EncryptKey) -> EncryptedPrivateKey { let pair = PrivateSignKey::generate(encrypt_key.size()); EncryptedPrivateKey::from_pair(&pair, encrypt_key) } #[allow(dead_code)] pub fn from_pair(pair: &PrivateSignKey, encrypt_key: &EncryptKey) -> EncryptedPrivateKey { let sk = pair.sk(); let sk = encrypt_key.encrypt(&sk[..]); EncryptedPrivateKey { pk: pair.as_public_key().clone(), ek_hash: encrypt_key.hash(), sk_iv: sk.iv, sk_encrypted: sk.data, } } #[allow(dead_code)] pub fn as_private_key(&self, key: &EncryptKey) -> PrivateSignKey { let data = key.decrypt(&self.sk_iv, &self.sk_encrypted[..]); match &self.pk { PublicSignKey::Falcon512 { pk } => PrivateSignKey::Falcon512 { pk: PublicSignKey::Falcon512 { pk: pk.clone() }, sk: data, }, PublicSignKey::Falcon1024 { pk } => PrivateSignKey::Falcon1024 { pk: PublicSignKey::Falcon1024 { pk: pk.clone() }, sk: data, }, } } #[allow(dead_code)] pub fn as_public_key<'a>(&'a self) -> &'a PublicSignKey { &self.pk } #[allow(dead_code)] pub fn pk_hash(&self) -> AteHash { self.pk.hash() } #[allow(dead_code)] pub(crate) fn double_hash(&self) -> DoubleHash { DoubleHash::from_hashes(&self.pk_hash(), &self.ek_hash) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/encrypt_key.rs
crypto/src/crypto/encrypt_key.rs
use crate::utils::b16_deserialize; use crate::utils::b16_serialize; use crate::utils::b24_deserialize; use crate::utils::b24_serialize; use crate::utils::b32_deserialize; use crate::utils::b32_serialize; use crate::utils::vec_deserialize; use crate::utils::vec_serialize; use serde::{Deserialize, Serialize}; use sha3::Digest; use std::convert::TryInto; use std::io::ErrorKind; use std::result::Result; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; #[cfg(feature = "use_openssl")] use openssl::symm::Cipher; #[cfg(not(feature = "enable_openssl"))] use ctr::cipher::*; #[cfg(not(feature = "enable_openssl"))] type Aes128Ctr = ctr::Ctr128BE<aes::Aes128>; #[cfg(not(feature = "enable_openssl"))] type Aes192Ctr = ctr::Ctr128BE<aes::Aes192>; #[cfg(not(feature = "enable_openssl"))] type Aes256Ctr = ctr::Ctr128BE<aes::Aes256>; use super::*; /// Represents an encryption key that will give confidentiality to /// data stored within the redo-log. Note this does not give integrity /// which comes from the `PrivateKey` crypto instead. #[derive(Serialize, Deserialize, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] pub enum EncryptKey { Aes128( #[serde(serialize_with = "b16_serialize", deserialize_with = "b16_deserialize")] [u8; 16], ), Aes192( #[serde(serialize_with = "b24_serialize", deserialize_with = "b24_deserialize")] [u8; 24], ), Aes256( #[serde(serialize_with = "b32_serialize", deserialize_with = "b32_deserialize")] [u8; 32], ), } impl EncryptKey { pub fn generate(size: KeySize) -> EncryptKey { RandomGeneratorAccessor::generate_encrypt_key(size) } pub fn resize(&self, size: KeySize) -> EncryptKey { // Pad the current key out to 256 bytes (with zeros) let mut bytes = self.value().iter().map(|a| *a).collect::<Vec<_>>(); while bytes.len() < 32 { bytes.push(0u8); } // Build a new key from the old key using these bytes match size { KeySize::Bit128 => { let aes_key: [u8; 16] = bytes .into_iter() .take(16) .collect::<Vec<_>>() .try_into() .unwrap(); EncryptKey::Aes128(aes_key) } KeySize::Bit192 => { let aes_key: [u8; 24] = bytes .into_iter() .take(24) .collect::<Vec<_>>() .try_into() .unwrap(); EncryptKey::Aes192(aes_key) } KeySize::Bit256 => { let aes_key: [u8; 32] = bytes .into_iter() .take(32) .collect::<Vec<_>>() .try_into() .unwrap(); EncryptKey::Aes256(aes_key) } } } pub fn size(&self) -> KeySize { match self { EncryptKey::Aes128(_) => KeySize::Bit128, EncryptKey::Aes192(_) => KeySize::Bit192, EncryptKey::Aes256(_) => KeySize::Bit256, } } pub fn value(&self) -> &[u8] { match self { EncryptKey::Aes128(a) => a, EncryptKey::Aes192(a) => a, EncryptKey::Aes256(a) => a, } } #[cfg(feature = "enable_openssl")] pub fn cipher(&self) -> Cipher { match self.size() { KeySize::Bit128 => Cipher::aes_128_ctr(), KeySize::Bit192 => Cipher::aes_192_ctr(), KeySize::Bit256 => Cipher::aes_256_ctr(), } } #[cfg(feature = "enable_openssl")] pub fn encrypt_with_iv(&self, iv: &InitializationVector, data: &[u8]) -> Vec<u8> { let mut iv_store; let iv = match iv.bytes.len() { 16 => iv, _ => { iv_store = InitializationVector { bytes: iv.bytes.clone().into_iter().take(16).collect::<Vec<_>>(), }; while iv_store.bytes.len() < 16 { iv_store.bytes.push(0u8); } &iv_store } }; openssl::symm::encrypt(self.cipher(), self.value(), Some(&iv.bytes[..]), data).unwrap() } #[cfg(not(feature = "enable_openssl"))] pub fn encrypt_with_iv(&self, iv: &InitializationVector, data: &[u8]) -> Vec<u8> { let mut iv_store; let iv = match iv.bytes.len() { 16 => iv, _ => { iv_store = InitializationVector { bytes: iv.bytes.clone().into_iter().take(16).collect::<Vec<_>>(), }; while iv_store.bytes.len() < 16 { iv_store.bytes.push(0u8); } &iv_store } }; let mut data = data.to_vec(); match self.size() { KeySize::Bit128 => { let mut cipher = Aes128Ctr::new(self.value().into(), (&iv.bytes[..]).into()); cipher.apply_keystream(data.as_mut_slice()); } KeySize::Bit192 => { let mut cipher = Aes192Ctr::new(self.value().into(), (&iv.bytes[..]).into()); cipher.apply_keystream(data.as_mut_slice()); } KeySize::Bit256 => { let mut cipher = Aes256Ctr::new(self.value().into(), (&iv.bytes[..]).into()); cipher.apply_keystream(data.as_mut_slice()); } } data } #[cfg(not(feature = "enable_openssl"))] pub fn encrypt_with_hash_iv(&self, hash: &AteHash, data: &[u8]) -> Vec<u8> { let iv: &[u8; 16] = hash.as_bytes(); let mut data = data.to_vec(); match self.size() { KeySize::Bit128 => { let mut cipher = Aes128Ctr::new(self.value().into(), iv.into()); cipher.apply_keystream(data.as_mut_slice()); } KeySize::Bit192 => { let mut cipher = Aes192Ctr::new(self.value().into(), iv.into()); cipher.apply_keystream(data.as_mut_slice()); } KeySize::Bit256 => { let mut cipher = Aes256Ctr::new(self.value().into(), iv.into()); cipher.apply_keystream(data.as_mut_slice()); } } data } #[cfg(not(feature = "enable_openssl"))] pub fn encrypt_with_hash_iv_with_capacity(&self, hash: &AteHash, data: &[u8], capacity: usize) -> Vec<u8> { let iv: &[u8; 16] = hash.as_bytes(); let mut ret: Vec<u8> = Vec::with_capacity(capacity); ret.extend_from_slice(hash.as_bytes()); let s = ret.len(); ret.extend_from_slice(data); let data = &mut ret[s..]; match self.size() { KeySize::Bit128 => { let mut cipher = Aes128Ctr::new(self.value().into(), iv.into()); cipher.apply_keystream(data); } KeySize::Bit192 => { let mut cipher = Aes192Ctr::new(self.value().into(), iv.into()); cipher.apply_keystream(data); } KeySize::Bit256 => { let mut cipher = Aes256Ctr::new(self.value().into(), iv.into()); cipher.apply_keystream(data); } } ret } #[cfg(not(feature = "enable_openssl"))] pub fn encrypt_with_hash_iv_with_capacity_and_prefix(&self, hash: &AteHash, data: &[u8], capacity: usize, prefix: &[u8]) -> Vec<u8> { let iv: &[u8; 16] = hash.as_bytes(); let mut ret: Vec<u8> = Vec::with_capacity(capacity); ret.extend_from_slice(prefix); ret.extend_from_slice(hash.as_bytes()); let s = ret.len(); ret.extend_from_slice(data); let data = &mut ret[s..]; match self.size() { KeySize::Bit128 => { let mut cipher = Aes128Ctr::new(self.value().into(), iv.into()); cipher.apply_keystream(data); } KeySize::Bit192 => { let mut cipher = Aes192Ctr::new(self.value().into(), iv.into()); cipher.apply_keystream(data); } KeySize::Bit256 => { let mut cipher = Aes256Ctr::new(self.value().into(), iv.into()); cipher.apply_keystream(data); } } ret } pub fn encrypt(&self, data: &[u8]) -> EncryptResult { let iv = InitializationVector::generate(); let data = self.encrypt_with_iv(&iv, data); EncryptResult { iv: iv, data: data } } #[cfg(feature = "enable_openssl")] pub fn decrypt(&self, iv: &InitializationVector, data: &[u8]) -> Vec<u8> { let mut iv_store; let iv = match iv.bytes.len() { 16 => iv, _ => { iv_store = InitializationVector { bytes: iv.bytes.clone().into_iter().take(16).collect::<Vec<_>>(), }; while iv_store.bytes.len() < 16 { iv_store.bytes.push(0u8); } &iv_store } }; openssl::symm::decrypt(self.cipher(), self.value(), Some(&iv.bytes[..]), data).unwrap() } #[cfg(not(feature = "enable_openssl"))] pub fn decrypt(&self, iv: &InitializationVector, data: &[u8]) -> Vec<u8> { let mut iv_store; let iv = match iv.bytes.len() { 16 => iv, _ => { iv_store = InitializationVector { bytes: iv.bytes.clone().into_iter().take(16).collect::<Vec<_>>(), }; while iv_store.bytes.len() < 16 { iv_store.bytes.push(0u8); } &iv_store } }; let mut data = data.to_vec(); match self.size() { KeySize::Bit128 => { let mut cipher = Aes128Ctr::new(self.value().into(), (&iv.bytes[..]).into()); cipher.apply_keystream(data.as_mut_slice()); } KeySize::Bit192 => { let mut cipher = Aes192Ctr::new(self.value().into(), (&iv.bytes[..]).into()); cipher.apply_keystream(data.as_mut_slice()); } KeySize::Bit256 => { let mut cipher = Aes256Ctr::new(self.value().into(), (&iv.bytes[..]).into()); cipher.apply_keystream(data.as_mut_slice()); } } data } #[cfg(not(feature = "enable_openssl"))] pub fn decrypt_with_hash_iv(&self, hash: &AteHash, data: &[u8]) -> Vec<u8> { let iv: &[u8; 16] = hash.as_bytes(); let mut data = data.to_vec(); match self.size() { KeySize::Bit128 => { let mut cipher = Aes128Ctr::new(self.value().into(), iv.into()); cipher.apply_keystream(data.as_mut_slice()); } KeySize::Bit192 => { let mut cipher = Aes192Ctr::new(self.value().into(), iv.into()); cipher.apply_keystream(data.as_mut_slice()); } KeySize::Bit256 => { let mut cipher = Aes256Ctr::new(self.value().into(), iv.into()); cipher.apply_keystream(data.as_mut_slice()); } } data } #[allow(dead_code)] pub fn as_bytes(&self) -> Vec<u8> { Vec::from(self.value()) } #[allow(dead_code)] pub fn from_bytes(bytes: &[u8]) -> Result<EncryptKey, std::io::Error> { let bytes: Vec<u8> = Vec::from(bytes); match bytes.len() { 16 => { Ok(EncryptKey::Aes128(bytes.try_into().expect( "Internal error while deserializing the Encryption Key", ))) } 24 => { Ok(EncryptKey::Aes192(bytes.try_into().expect( "Internal error while deserializing the Encryption Key", ))) } 32 => { Ok(EncryptKey::Aes256(bytes.try_into().expect( "Internal error while deserializing the Encryption Key", ))) } _ => Result::Err(std::io::Error::new( ErrorKind::Other, format!( "The encryption key bytes are the incorrect length ({}).", bytes.len() ), )), } } pub fn hash(&self) -> AteHash { match &self { EncryptKey::Aes128(a) => AteHash::from_bytes(a), EncryptKey::Aes192(a) => AteHash::from_bytes(a), EncryptKey::Aes256(a) => AteHash::from_bytes(a), } } pub fn short_hash(&self) -> ShortHash { match &self { EncryptKey::Aes128(a) => ShortHash::from_bytes(a), EncryptKey::Aes192(a) => ShortHash::from_bytes(a), EncryptKey::Aes256(a) => ShortHash::from_bytes(a), } } pub fn from_seed_string(str: String, size: KeySize) -> EncryptKey { EncryptKey::from_seed_bytes(str.as_bytes(), size) } pub fn from_seed_bytes(seed_bytes: &[u8], size: KeySize) -> EncryptKey { let mut hasher = sha3::Keccak384::new(); hasher.update(seed_bytes); let result = hasher.finalize(); match size { KeySize::Bit128 => { let aes_key: [u8; 16] = result .into_iter() .take(16) .collect::<Vec<_>>() .try_into() .unwrap(); EncryptKey::Aes128(aes_key) } KeySize::Bit192 => { let aes_key: [u8; 24] = result .into_iter() .take(24) .collect::<Vec<_>>() .try_into() .unwrap(); EncryptKey::Aes192(aes_key) } KeySize::Bit256 => { let aes_key: [u8; 32] = result .into_iter() .take(32) .collect::<Vec<_>>() .try_into() .unwrap(); EncryptKey::Aes256(aes_key) } } } pub fn xor(ek1: &EncryptKey, ek2: &EncryptKey) -> EncryptKey { let mut ek1_bytes = ek1.as_bytes(); let ek2_bytes = ek2.as_bytes(); ek1_bytes .iter_mut() .zip(ek2_bytes.iter()) .for_each(|(x1, x2)| *x1 ^= *x2); EncryptKey::from_bytes(&ek1_bytes[..]) .expect("Internal error while attempting to XOR encryption keys") } } impl std::fmt::Display for EncryptKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { EncryptKey::Aes128(a) => write!(f, "aes-128:{}", hex::encode(a)), EncryptKey::Aes192(a) => write!(f, "aes-192:{}", hex::encode(a)), EncryptKey::Aes256(a) => write!(f, "aes-256:{}", hex::encode(a)), } } } #[derive(Serialize, Deserialize, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct EncryptResult { pub iv: InitializationVector, #[serde(serialize_with = "vec_serialize", deserialize_with = "vec_deserialize")] pub data: Vec<u8>, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/crypto/src/crypto/derived_encrypt_key.rs
crypto/src/crypto/derived_encrypt_key.rs
use serde::{Deserialize, Serialize}; use std::result::Result; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use super::*; /// Encrypt key material is used to transform an encryption key using /// derivation which should allow encryption keys to be changed without /// having to decrypt and reencrypt the data itself. #[derive(Serialize, Deserialize, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct DerivedEncryptKey { pub(crate) inner: EncryptResult, } impl DerivedEncryptKey { pub fn new(key: &EncryptKey) -> DerivedEncryptKey { let inner = EncryptKey::generate(key.size()); DerivedEncryptKey { inner: key.encrypt(inner.value()), } } pub fn reverse(key: &EncryptKey, inner: &EncryptKey) -> DerivedEncryptKey { DerivedEncryptKey { inner: key.encrypt(inner.value()), } } pub fn transmute(&self, key: &EncryptKey) -> Result<EncryptKey, std::io::Error> { // Decrypt the derived key let bytes = key.decrypt(&self.inner.iv, &self.inner.data[..]); Ok(EncryptKey::from_bytes(&bytes[..])?) } #[cfg(feature = "quantum")] pub fn transmute_private(&self, key: &PrivateEncryptKey) -> Result<EncryptKey, std::io::Error> { // Decrypt the derived key let bytes = key.decrypt(&self.inner.iv, &self.inner.data[..])?; Ok(EncryptKey::from_bytes(&bytes[..])?) } pub fn change(&mut self, old: &EncryptKey, new: &EncryptKey) -> Result<(), std::io::Error> { // First derive the key, then replace the inner with a newly encrypted value let inner = self.transmute(old)?; self.inner = new.encrypt(inner.value()); Ok(()) } #[cfg(feature = "quantum")] pub fn change_private( &mut self, old: &PrivateEncryptKey, new: &PublicEncryptKey, ) -> Result<(), std::io::Error> { // First derive the key, then replace the inner with a newly encrypted value let inner = self.transmute_private(old)?; self.inner = new.encrypt(inner.value()); Ok(()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/key.rs
wasmer-ssh/src/key.rs
use serde::*; use std::convert::TryInto; use thrussh_keys::key::ed25519; use thrussh_keys::key::KeyPair; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum SshServerKey { Ed25519(Vec<u8>), } impl SshServerKey { pub fn generate_ed25519() -> SshServerKey { let key = KeyPair::generate_ed25519().unwrap(); let key: SshServerKey = key.into(); key } } impl Into<KeyPair> for SshServerKey { fn into(self) -> KeyPair { match self { SshServerKey::Ed25519(a) => KeyPair::Ed25519(ed25519::SecretKey { key: a.try_into().unwrap(), }), } } } impl From<KeyPair> for SshServerKey { fn from(key: KeyPair) -> SshServerKey { match key { KeyPair::Ed25519(a) => SshServerKey::Ed25519(a.key.to_vec()), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/lib.rs
wasmer-ssh/src/lib.rs
pub mod cconst; pub mod console_handle; pub mod error; pub mod handler; pub mod key; pub mod opt; pub mod server; pub mod system; pub mod utils; pub mod wizard; pub mod native_files; pub use wasmer_term::wasmer_os; pub use ate_files; pub use native_files::NativeFiles;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/error.rs
wasmer-ssh/src/error.rs
use error_chain::error_chain; use ate_files::error::FileSystemError; use ate_files::error::FileSystemErrorKind; error_chain! { types { SshServerError, SshServerErrorKind, SshServerResultExt, SshServerResult; } links { FileSystemError(FileSystemError, FileSystemErrorKind); } foreign_links { Thrussh(thrussh::Error); } errors { BadData { description("received bad data"), display("received bad data"), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/system.rs
wasmer-ssh/src/system.rs
use async_trait::async_trait; use ate::mesh::Registry; use ate_files::prelude::*; use wasmer_term::wasmer_os::wasmer::Module; use wasmer_term::wasmer_os::wasmer::Store; use wasmer_term::wasmer_os::wasmer::vm::VMMemory; use wasmer_term::wasmer_os::wasmer_wasi::WasiThreadError; use std::future::Future; use std::pin::Pin; use std::sync::Arc; use std::io::Read; use wasmer_os::api::*; use wasmer_os::err; use tokio::sync::mpsc; use wasmer_term::wasmer_os; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use super::NativeFiles; use std::path::PathBuf; use super::native_files::NativeFileInterface; use super::native_files::NativeFileType; pub struct System { pub inner: Arc<dyn SystemAbi>, pub native_files: NativeFileInterface, } impl System { pub async fn new(inner: Arc<dyn SystemAbi>, registry: Arc<Registry>, db_url: url::Url, native_files: NativeFileType) -> Self { let native_files = match native_files { NativeFileType::AteFileSystem(native_files) => { NativeFileInterface::AteFileSystem(NativeFiles::new(registry, db_url, native_files)) }, NativeFileType::LocalFileSystem(native_files) => { let path = PathBuf::from(native_files); NativeFileInterface::LocalFileSystem(path) }, NativeFileType::EmbeddedFiles => { NativeFileInterface::EmbeddedFiles } }; Self { inner, native_files, } } } #[async_trait] impl wasmer_os::api::SystemAbi for System { /// Starts an asynchronous task that will run on a shared worker pool /// This task must not block the execution or it could cause a deadlock fn task_shared( &self, task: Box< dyn FnOnce() -> Pin<Box<dyn Future<Output = ()> + Send + 'static>> + Send + 'static, >, ) { self.inner.task_shared(task) } /// Starts an asynchronous task will will run on a dedicated thread /// pulled from the worker pool that has a stateful thread local variable /// It is ok for this task to block execution and any async futures within its scope fn task_wasm( &self, task: Box<dyn FnOnce(Store, Module, Option<VMMemory>) -> Pin<Box<dyn Future<Output = ()> + 'static>> + Send + 'static>, store: Store, module: Module, spawn_type: SpawnType, ) -> Result<(), WasiThreadError> { self.inner.task_wasm(task, store, module, spawn_type) } /// Starts an synchronous task will will run on a dedicated thread /// pulled from the worker pool. It is ok for this task to block execution /// and any async futures within its scope fn task_dedicated( &self, task: Box<dyn FnOnce() + Send + 'static>, ) { self.inner.task_dedicated(task) } /// Starts an asynchronous task will will run on a dedicated thread /// pulled from the worker pool. It is ok for this task to block execution /// and any async futures within its scope fn task_dedicated_async( &self, task: Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = ()> + 'static>> + Send + 'static>, ) { self.inner.task_dedicated_async(task) } /// Starts an asynchronous task on the current thread. This is useful for /// launching background work with variables that are not Send. fn task_local(&self, task: Pin<Box<dyn Future<Output = ()> + 'static>>) { self.inner.task_local(task) } /// Puts the current thread to sleep for a fixed number of milliseconds fn sleep(&self, ms: u128) -> AsyncResult<()> { self.inner.sleep(ms) } /// Fetches a data file from the local context of the process fn fetch_file(&self, path: &str) -> AsyncResult<Result<Vec<u8>, u32>> { match &self.native_files { NativeFileInterface::AteFileSystem(native_files) => { self.fetch_file_via_ate(native_files, path) }, NativeFileInterface::LocalFileSystem(native_files) => { self.fetch_file_via_local_fs(native_files, path) }, NativeFileInterface::EmbeddedFiles => { self.inner.fetch_file(path) } } } /// Performs a HTTP or HTTPS request to a destination URL fn reqwest( &self, url: &str, method: &str, options: ReqwestOptions, headers: Vec<(String, String)>, data: Option<Vec<u8>>, ) -> AsyncResult<Result<ReqwestResponse, u32>> { self.inner.reqwest(url, method, options, headers, data) } async fn web_socket(&self, url: &str) -> Result<Box<dyn WebSocketAbi>, String> { self.inner.web_socket(url).await } async fn webgl(&self) -> Option<Box<dyn WebGlAbi>> { self.inner.webgl().await } } fn conv_err(err: FileSystemError) -> u32 { match err { FileSystemError(FileSystemErrorKind::NoAccess, _) => err::ERR_EACCES, FileSystemError(FileSystemErrorKind::PermissionDenied, _) => err::ERR_EPERM, FileSystemError(FileSystemErrorKind::ReadOnly, _) => err::ERR_EPERM, FileSystemError(FileSystemErrorKind::InvalidArguments, _) => err::ERR_EINVAL, FileSystemError(FileSystemErrorKind::NoEntry, _) => err::ERR_ENOENT, FileSystemError(FileSystemErrorKind::DoesNotExist, _) => err::ERR_ENOENT, FileSystemError(FileSystemErrorKind::AlreadyExists, _) => err::ERR_EEXIST, FileSystemError(FileSystemErrorKind::NotDirectory, _) => err::ERR_ENOTDIR, FileSystemError(FileSystemErrorKind::IsDirectory, _) => err::ERR_EISDIR, FileSystemError(FileSystemErrorKind::NotImplemented, _) => err::ERR_ENOSYS, _ => err::ERR_EIO, } } impl System { fn fetch_file_via_local_fs(&self, native_files: &PathBuf, path: &str) -> AsyncResult<Result<Vec<u8>, u32>> { let path = path.to_string(); let native_files = native_files.clone(); let (tx_result, rx_result) = mpsc::channel(1); self.task_dedicated_async(Box::new(move || { let task = async move { if path.contains("..") || path.contains("~") || path.contains("//") { warn!("relative paths are a security risk - {}", path); return Err(err::ERR_EACCES); } let mut path = path.as_str(); while path.starts_with("/") { path = &path[1..]; } let path = native_files.join(path); // Attempt to open the file let mut file = std::fs::File::open(path.clone()) .map_err(|err| { debug!("failed to open local file ({}) - {}", path.to_string_lossy(), err); err::ERR_EIO })?; let mut data = Vec::new(); file .read_to_end(&mut data) .map_err(|err| { debug!("failed to read local file ({}) - {}", path.to_string_lossy(), err); err::ERR_EIO })?; Ok(data) }; Box::pin(async move { let ret = task.await; let _ = tx_result.send(ret).await; }) })); AsyncResult::new(SerializationFormat::Bincode, rx_result) } fn fetch_file_via_ate(&self, native_files: &NativeFiles, path: &str) -> AsyncResult<Result<Vec<u8>, u32>> { let path = path.to_string(); let native_files = native_files.clone(); let (tx_result, rx_result) = mpsc::channel(1); self.task_dedicated_async(Box::new(move || { let task = async move { let native_files = native_files.get() .await .map_err(|err| { debug!("failed to fetch native files container - {}", err); err::ERR_EIO })?; // Search for the file let ctx = RequestContext { uid: 0, gid: 0 }; let flags = ate_files::codes::O_RDONLY as u32; let file = native_files .search(&ctx, &path) .await .map_err(conv_err)? .ok_or(err::ERR_ENOENT)?; let file = native_files .open(&ctx, file.ino, flags) .await .map_err(conv_err)?; let data = native_files .read_all(&ctx, file.inode, file.fh) .await .map_err(conv_err)?; Ok(data) }; Box::pin(async move { let ret = task.await; let _ = tx_result.send(ret).await; }) })); AsyncResult::new(SerializationFormat::Bincode, rx_result) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/utils.rs
wasmer-ssh/src/utils.rs
#![allow(unused_imports)] use serde::*; use std::fs::File; use tracing::metadata::LevelFilter; use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use tracing_subscriber::fmt::SubscriberBuilder; use tracing_subscriber::EnvFilter; pub fn log_init(verbose: i32, debug: bool) { let mut log_level = match verbose { 0 => None, 1 => Some(LevelFilter::WARN), 2 => Some(LevelFilter::INFO), 3 => Some(LevelFilter::DEBUG), 4 => Some(LevelFilter::TRACE), _ => None, }; if debug { log_level = Some(LevelFilter::DEBUG); } if let Some(log_level) = log_level { SubscriberBuilder::default() .with_max_level(log_level) .init(); } else { SubscriberBuilder::default() .with_env_filter(EnvFilter::from_default_env()) .init(); } } pub fn try_load_key<T>(key_path: String) -> Option<T> where T: serde::de::DeserializeOwned, { let path = shellexpand::tilde(&key_path).to_string(); debug!("loading key: {}", path); let path = std::path::Path::new(&path); File::open(path) .ok() .map(|file| bincode::deserialize_from(&file).unwrap()) } pub fn load_key<T>(key_path: String) -> T where T: serde::de::DeserializeOwned, { let path = shellexpand::tilde(&key_path).to_string(); debug!("loading key: {}", path); let path = std::path::Path::new(&path); let file = File::open(path).expect(format!("failed to load key at {}", key_path).as_str()); bincode::deserialize_from(&file).unwrap() } pub fn save_key<T>(key_path: String, key: T) where T: Serialize, { let path = shellexpand::tilde(&key_path).to_string(); debug!("saving key: {}", path); let path = std::path::Path::new(&path); let _ = std::fs::create_dir_all(path.parent().unwrap().clone()); let mut file = File::create(path).unwrap(); bincode::serialize_into(&mut file, &key).unwrap(); }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/cconst.rs
wasmer-ssh/src/cconst.rs
pub struct CConst {} impl CConst { pub const SSH_WELCOME: &'static str = r#" ██╗ ██╗ █████╗ ███████╗███╗ ███╗███████╗██████╗ ██║ ██║██╔══██╗██╔════╝████╗ ████║██╔════╝██╔══██╗ ██║ █╗ ██║███████║███████╗██╔████╔██║█████╗ ██████╔╝ ██║███╗██║██╔══██║╚════██║██║╚██╔╝██║██╔══╝ ██╔══██╗ ╚███╔███╔╝██║ ██║███████║██║ ╚═╝ ██║███████╗██║ ██║ ╚══╝╚══╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝"#; pub const SSH_INSTRUCTIONS_PASSWORD: &'static str = r#" Welcome back ({email}),"#; pub const SSH_INSTRUCTIONS_SUDO: &'static str = r#" Enter your authenticator code (or press enter to skip),"#; pub const SSH_ASSOCIATE: &'static str = r#" Would you like to associate your SSH key with account?"#; pub const SSH_INSTRUCTIONS_TERMS: &'static str = r#" {terms} If you agree to the above terms and conditions then type the word 'agree' below"#; pub const SSH_INSTRUCTIONS_SIGN_UP: &'static str = r#" The login user is not known to us... ...but do not fear!...as the sign-up wizard is here... Username: {email}"#; pub const SSH_INSTRUCTIONS_FAILED: &'static str = r#" Unfortunately the login has failed: '{message}'"#; pub const SSH_INSTRUCTIONS_QR: &'static str = r#" Below is your Google Authenticator QR code - scan it on your phone and save it as this code is the only way you can recover the account. {qr_code} "#; pub const SSH_INSTRUCTIONS_VERIFY: &'static str = r#" Check your email for a verification code and enter it below"#; pub const SSH_WRONG_PASSWORD: &'static str = r#" The password was incorrect (Warning! Repeated failed attempts will trigger a short ban)"#; pub const SSH_MUST_ACCEPT_TERMS: &'static str = r#" You may only create an account by specifically agreeing to the terms and conditions laid out above - this can only be confirmed if you specifically type the word 'agree' which you did not enter hence an account can not be created. If this is a mistake then please try again."#; pub const SSH_WRONG_VERIFY_CODE: &'static str = r#" The verification code was incorrect"#; pub const SSH_ACCOUNT_LOCKED: &'static str = r#" Your account has been locked, please try again later"#; pub const SSH_ACCOUNT_EXISTS: &'static str = r#" The account you specified already exists"#; pub const SSH_INTERNAL_ERROR: &'static str = r#" An internal error has occured"#; pub const SSH_INVALID_INPUT: &'static str = r#" The input you supplied was invalid"#; pub const SSH_INVALID_USERNAME: &'static str = r#" The username must be a valid email address (e.g. ssh joe@blogs.com@wasmer.sh)"#; pub const SSH_PASSWORD_MISMATCH: &'static str = r#" The two passwords you supplied did not match"#; pub const SSH_PASSWORD_WEAK: &'static str = r#" The password was not of sufficient complexity"#; }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/wizard.rs
wasmer-ssh/src/wizard.rs
use super::cconst::CConst; use ate::prelude::*; use wasmer_auth::error::*; use wasmer_auth::helper::*; use wasmer_auth::request::*; use std::borrow::Cow; use std::sync::Arc; use thrussh::server::*; use thrussh_keys::key::PublicKey; use wasmer_term::wasmer_os::api as term_api; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum SshWizardStep { /// The first step before we take any actions to login Init, /// At this step the user is prompted for their password Login, /// At this step the user is prompted for their authenticator code Sudo, /// If the user is not known to Wasmer then they enter a /// sign-up step that gets them to enter a new password SignUp, /// Next they must agree to the terms and conditions Terms, /// Lastly they need to verify their email address with /// the verification code that was sent to them. Also /// during this step the user must scan the QR code /// and save it to their phone for future use Verify, /// Lastly we enter the main shell Shell, /// Indicates that the session will be terminated Terminate, } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum LoginResult { LoginWithUser, LoginWithPublicKey, NoPasswordSupplied, IncorrectPassword, Unregistered, InvalidEmail, AccountLocked, Unverified, InternalError, } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum UserExistsResult { Found, NotFound, InvalidEmail, InternalError, Banned, Suspended, } #[derive(Debug, Clone)] pub enum UserCreateResult { NoUsernameSupplied, NoPasswordSupplied, AlreadyExists, InvalidEmail, InternalError, Created, Terms, } #[derive(Debug, Clone)] pub enum SudoResult { Success, NoAuthenticatorCodeSupplied, WrongCode, InternalError, } #[derive(Debug, Default)] pub struct SshWizardState { pub welcome: Option<String>, pub email: Option<String>, pub session: Option<AteSessionType>, pub public_key: Option<PublicKey>, pub password: Option<String>, pub verify_code: Option<String>, pub sudo_code: Option<String>, pub goodbye_message: Option<String>, pub message_of_the_day: Option<String>, pub needed_terms: Option<String>, pub accepted_terms: Option<String>, pub qr_code: Option<String>, } impl SshWizardState { pub fn set_public_key(&mut self, key: PublicKey) { self.public_key = Some(key); } pub fn set_welcome(&mut self, msg: String) { self.welcome = Some(msg); } pub fn parse_message(&self, msg: &str) -> String { msg.replace( "{email}", self.email.clone().unwrap_or("none".to_string()).as_str(), ) .replace( "{terms}", self.needed_terms .clone() .unwrap_or("none".to_string()) .as_str(), ) .replace( "{qr_code}", self.qr_code.clone().unwrap_or("none".to_string()).as_str(), ) } } pub struct SshWizard { pub step: SshWizardStep, pub state: SshWizardState, pub registry: Arc<Registry>, pub auth: url::Url, } impl SshWizard { async fn process_response<'a>(&mut self, response: Option<Vec<String>>) { match self.step.clone() { SshWizardStep::Init => { if self.state.session.is_some() { self.step = SshWizardStep::Sudo } else { let username = match self.state.email.clone() { Some(a) => a, None => { warn!("user check failed: no username supplied"); self.state.goodbye_message = Some(CConst::SSH_INVALID_USERNAME.to_string()); self.step = SshWizardStep::Terminate; return; } }; let regex = regex::Regex::new("^([a-z0-9\\.!#$%&'*+/=?^_`{|}~-]{1,})@([a-z0-9\\.!#$%&'*+/=?^_`{|}~-]{1,}).([a-z0-9\\.!#$%&'*+/=?^_`{|}~-]{1,})$").unwrap(); if regex.is_match(username.as_str()) == false { warn!( "user check failed: username was invalid (user={})", username ); self.state.goodbye_message = Some(CConst::SSH_INVALID_USERNAME.to_string()); self.step = SshWizardStep::Terminate; return; } self.step = match user_exists(&self.registry, &self.auth, &mut self.state).await { UserExistsResult::Found => { debug!("user found (user={})", self.state.email.clone().unwrap()); SshWizardStep::Login } UserExistsResult::InvalidEmail => { info!("user check failed: invalid email"); self.state.goodbye_message = Some(CConst::SSH_INVALID_USERNAME.to_string()); SshWizardStep::Terminate } UserExistsResult::Banned | UserExistsResult::Suspended => { info!("user check failed: banned or suspended"); self.state.goodbye_message = Some(CConst::SSH_ACCOUNT_LOCKED.to_string()); SshWizardStep::Terminate } UserExistsResult::NotFound => { info!( "user does not exist (user={})", self.state.email.clone().unwrap() ); SshWizardStep::SignUp } UserExistsResult::InternalError => { warn!("user check failed: internal error"); self.state.goodbye_message = Some(CConst::SSH_INTERNAL_ERROR.to_string()); SshWizardStep::Terminate } }; } } SshWizardStep::Login => { self.state.password = None; if let Some(response) = response { if response.len() == 1 { self.state.password = Some(response.get(0).unwrap().clone()); } } self.step = match login(&self.registry, &self.auth, &mut self.state).await { LoginResult::LoginWithUser | LoginResult::LoginWithPublicKey => { info!( "login successful (user={})", self.state.email.clone().unwrap() ); SshWizardStep::Sudo } LoginResult::Unverified => { info!( "login successful - must verify (user={})", self.state.email.clone().unwrap() ); SshWizardStep::Verify } LoginResult::Unregistered => { info!( "login failed - must sign-up (user={})", self.state.email.clone().unwrap() ); SshWizardStep::SignUp } LoginResult::NoPasswordSupplied => { warn!("login failed: no password supplied"); SshWizardStep::Login } LoginResult::IncorrectPassword => { warn!("login failed: incorrect password"); self.state.goodbye_message = Some(CConst::SSH_WRONG_PASSWORD.to_string()); SshWizardStep::Terminate } LoginResult::InvalidEmail => { warn!("login failed: invalid email"); self.state.goodbye_message = Some(CConst::SSH_INVALID_USERNAME.to_string()); SshWizardStep::Terminate } LoginResult::AccountLocked => { warn!("login failed: account locked"); self.state.goodbye_message = Some(CConst::SSH_ACCOUNT_LOCKED.to_string()); SshWizardStep::Terminate } LoginResult::InternalError => { warn!("login failed: internal error"); self.state.goodbye_message = Some(CConst::SSH_INTERNAL_ERROR.to_string()); SshWizardStep::Terminate } }; } SshWizardStep::Sudo => { self.state.sudo_code = None; if let Some(response) = response { if response.len() == 1 { self.state.sudo_code = Some(response.get(0).unwrap().clone()); } } self.step = match sudo(&self.registry, &self.auth, &mut self.state).await { SudoResult::Success => { info!( "login sudo successful (user={})", self.state.email.clone().unwrap() ); SshWizardStep::Shell } SudoResult::WrongCode => { warn!("login sudo failed: wrong code suppleid"); self.state.goodbye_message = Some(CConst::SSH_WRONG_PASSWORD.to_string()); SshWizardStep::Terminate } SudoResult::NoAuthenticatorCodeSupplied => { info!( "login sudo skipped (user={})", self.state.email.clone().unwrap() ); SshWizardStep::Shell } _ => { warn!("login sudo failed: internal error"); self.state.goodbye_message = Some(CConst::SSH_INTERNAL_ERROR.to_string()); SshWizardStep::Terminate } }; } SshWizardStep::SignUp => { self.state.password = None; if let Some(response) = response { if response.len() == 2 { let password = response.get(0).unwrap().clone(); if password.len() < 4 { self.state.goodbye_message = Some(CConst::SSH_PASSWORD_WEAK.to_string()); self.step = SshWizardStep::Terminate; return; } if response.get(1).unwrap().clone() != password { self.state.goodbye_message = Some(CConst::SSH_INVALID_INPUT.to_string()); self.step = SshWizardStep::Terminate; return; } self.state.password = Some(password); } } self.step = match user_create(&self.registry, &self.auth, &mut self.state).await { UserCreateResult::Created => { info!( "sign up successful (user={})", self.state.email.clone().unwrap() ); SshWizardStep::Verify } UserCreateResult::Terms => { info!( "sign up successful - new terms (user={})", self.state.email.clone().unwrap() ); SshWizardStep::Terms } UserCreateResult::AlreadyExists => { warn!( "sign-up failed: user already exists (user={})", self.state.email.clone().unwrap() ); self.state.goodbye_message = Some(CConst::SSH_ACCOUNT_EXISTS.to_string()); SshWizardStep::Terminate } UserCreateResult::InvalidEmail => { warn!( "sign-up failed: username is invalid (user={})", self.state.email.clone().unwrap() ); self.state.goodbye_message = Some(CConst::SSH_INVALID_USERNAME.to_string()); SshWizardStep::Terminate } UserCreateResult::NoPasswordSupplied => { warn!("sign-up failed: no password supplied"); self.state.goodbye_message = Some(CConst::SSH_INVALID_INPUT.to_string()); SshWizardStep::Terminate } UserCreateResult::NoUsernameSupplied => { warn!("sign-up failed: no username supplied"); self.state.goodbye_message = Some(CConst::SSH_INVALID_INPUT.to_string()); SshWizardStep::Terminate } UserCreateResult::InternalError => { warn!("sign-up failed: internal error"); self.state.goodbye_message = Some(CConst::SSH_INTERNAL_ERROR.to_string()); SshWizardStep::Terminate } } } SshWizardStep::Terms => { self.state.accepted_terms = None; if let Some(response) = response { if response.len() == 1 { let answer = response.get(0).unwrap().trim().to_lowercase(); match answer.as_str() { "agree" | "yes" | "ok" | "y" => { self.state.accepted_terms = self.state.needed_terms.clone(); } _ => {} } } } if self.state.accepted_terms.is_none() { self.state.goodbye_message = Some(CConst::SSH_MUST_ACCEPT_TERMS.to_string()); self.step = SshWizardStep::Terminate; return; } self.step = match user_create(&self.registry, &self.auth, &mut self.state).await { UserCreateResult::Created => { info!( "terms accepted (user={})", self.state.email.clone().unwrap() ); SshWizardStep::Verify } UserCreateResult::Terms => { info!( "new terms and conditions (user={})", self.state.email.clone().unwrap() ); SshWizardStep::Terms } _ => { warn!("terms acceptance failed: internal error"); self.state.goodbye_message = Some(CConst::SSH_INTERNAL_ERROR.to_string()); SshWizardStep::Terminate } } } SshWizardStep::Verify => { self.state.verify_code = None; if let Some(response) = response { if response.len() == 1 { self.state.verify_code = Some(response.get(0).unwrap().clone()); } } self.step = match login(&self.registry, &self.auth, &mut self.state).await { LoginResult::LoginWithUser => { info!("user verified (user={})", self.state.email.clone().unwrap()); SshWizardStep::Shell } LoginResult::IncorrectPassword => { warn!("user verify failed: incorrect password"); self.state.goodbye_message = Some(CConst::SSH_WRONG_VERIFY_CODE.to_string()); SshWizardStep::Terminate } LoginResult::AccountLocked => { warn!("user verify failed: account locked"); self.state.goodbye_message = Some(CConst::SSH_ACCOUNT_LOCKED.to_string()); SshWizardStep::Terminate } _ => { warn!("user verify failed: internal error"); self.state.goodbye_message = Some(CConst::SSH_INTERNAL_ERROR.to_string()); SshWizardStep::Terminate } }; } SshWizardStep::Shell => {} SshWizardStep::Terminate => {} }; } pub fn fail(&mut self, msg: &str) { self.state.goodbye_message = Some(msg.to_string()); self.step = SshWizardStep::Terminate; } fn get_welcome(&mut self) -> String { self.state.welcome.take().unwrap_or_else(|| "".to_string()) } pub async fn next_auth(&mut self, response: Option<Vec<String>>) -> Auth { self.process_response(response).await; match self.step { SshWizardStep::Login => Auth::Partial { name: self.get_welcome().into(), instructions: Cow::Owned( self.state.parse_message(CConst::SSH_INSTRUCTIONS_PASSWORD), ), prompts: Cow::Owned(vec![("Password: ".into(), false)]), }, SshWizardStep::Sudo => Auth::Partial { name: self.get_welcome().into(), instructions: Cow::Owned(self.state.parse_message(CConst::SSH_INSTRUCTIONS_SUDO)), prompts: Cow::Owned(vec![("Authenticator Code: ".into(), true)]), }, SshWizardStep::SignUp => Auth::Partial { name: self.get_welcome().into(), instructions: Cow::Owned( self.state.parse_message(CConst::SSH_INSTRUCTIONS_SIGN_UP), ), prompts: Cow::Owned(vec![ ("Password: ".into(), false), ("Password Again: ".into(), false), ]), }, SshWizardStep::Terms => Auth::Partial { name: self.get_welcome().into(), instructions: Cow::Owned(self.state.parse_message(CConst::SSH_INSTRUCTIONS_TERMS)), prompts: Cow::Owned(vec![("(agree?): ".into(), true)]), }, SshWizardStep::Verify => { let mut instructions = String::new(); if self.state.qr_code.is_some() { instructions.push_str( self.state .parse_message(CConst::SSH_INSTRUCTIONS_QR) .as_str(), ); } instructions.push_str( self.state .parse_message(CConst::SSH_INSTRUCTIONS_VERIFY) .as_str(), ); Auth::Partial { name: self.get_welcome().into(), instructions: Cow::Owned(instructions), prompts: Cow::Owned(vec![("Verification Code: ".into(), true)]), } } _ => Auth::Accept, } } pub fn next_shell(&self) -> bool { self.step == SshWizardStep::Shell } pub fn goodbye_message(&self) -> Option<String> { self.state.goodbye_message.clone() } } #[async_trait::async_trait] impl term_api::WizardAbi for SshWizard { async fn process(&mut self, responses: Vec<String>) -> term_api::WizardAction { let responses = if responses.len() > 0 { Some(responses) } else { None }; match self.next_auth(responses).await { Auth::Accept => { if self.next_shell() { term_api::WizardAction::Shell } else { term_api::WizardAction::Terminate { with_message: self.state.goodbye_message.clone(), } } } Auth::Partial { name, instructions, prompts, } => term_api::WizardAction::Challenge { name: name.to_string(), instructions: instructions.to_string(), prompts: prompts .iter() .map(|(prompt, echo)| term_api::WizardPrompt { prompt: prompt.to_string(), echo: *echo, }) .collect(), }, Auth::Reject | Auth::UnsupportedMethod => term_api::WizardAction::Terminate { with_message: self.state.goodbye_message.clone(), }, } } fn token(&self) -> Option<String> { self.state .session .clone() .map(|a| wasmer_auth::helper::session_to_b64(a).unwrap()) } } async fn login( registry: &Arc<Registry>, auth: &url::Url, state: &mut SshWizardState, ) -> LoginResult { // Open a command chain let chain = match registry.open_cmd(&auth).await { Ok(a) => a, Err(err) => { debug!("{}", err); return LoginResult::InternalError; } }; // Get the username and password let username = match state.email.clone() { Some(a) => a, None => { return LoginResult::InvalidEmail; } }; let password = match state.password.clone() { Some(a) => a, None => { return LoginResult::NoPasswordSupplied; } }; // Generate a read-key using the password and some seed data // (this read-key will be mixed with entropy on the server side to decrypt the row // which means that neither the client nor the server can get at the data alone) let prefix = format!("remote-login:{}:", username); let read_key = password_to_read_key(&prefix, &password, 15, KeySize::Bit192); // Create the login command let login = LoginRequest { email: username.clone(), secret: read_key, verification_code: state.verify_code.clone(), }; // Attempt the login request with a 10 second timeout trace!("invoking login (email={})", login.email); let response: Result<LoginResponse, LoginFailed> = match chain.invoke(login).await { Ok(a) => a, Err(err) => { debug!("{}", err); return LoginResult::InternalError; } }; let result = match response { Ok(a) => a, Err(LoginFailed::AccountLocked(_)) => { return LoginResult::AccountLocked; } Err(LoginFailed::Unverified(_)) => { return LoginResult::Unverified; } Err(LoginFailed::UserNotFound(_)) => { return LoginResult::Unregistered; } Err(LoginFailed::WrongPassword) => { return LoginResult::IncorrectPassword; } _ => { return LoginResult::InternalError; } }; state.session = Some(AteSessionType::User(result.authority)); // Display the message of the day if let Some(message_of_the_day) = result.message_of_the_day { state.message_of_the_day = Some(message_of_the_day); } LoginResult::LoginWithUser } async fn user_exists( registry: &Arc<Registry>, auth: &url::Url, state: &mut SshWizardState, ) -> UserExistsResult { // Open a command chain let chain = match registry.open_cmd(&auth).await { Ok(a) => a, Err(err) => { debug!("{}", err); return UserExistsResult::InternalError; } }; // Get the username and password let username = match state.email.clone() { Some(a) => a, None => { return UserExistsResult::InvalidEmail; } }; // Create the login command let query = QueryRequest { identity: username.clone(), }; // Attempt the login request with a 10 second timeout trace!("invoking query (identity={})", query.identity); let response: Result<QueryResponse, QueryFailed> = match chain.invoke(query).await { Ok(a) => a, Err(err) => { debug!("{}", err); return UserExistsResult::InternalError; } }; let result = match response { Ok(a) => a, Err(QueryFailed::NotFound) => { return UserExistsResult::NotFound; } Err(QueryFailed::Banned) => { return UserExistsResult::Banned; } Err(QueryFailed::Suspended) => { return UserExistsResult::Suspended; } Err(QueryFailed::InternalError(_)) => { return UserExistsResult::InternalError; } }; let _id = result.advert.id; UserExistsResult::Found } async fn sudo(registry: &Arc<Registry>, auth: &url::Url, state: &mut SshWizardState) -> SudoResult { let authenticator_code = match state.sudo_code.clone() { Some(a) if a.len() > 0 => a, _ => { return SudoResult::NoAuthenticatorCodeSupplied; } }; // Open a command chain let chain = match registry.open_cmd(&auth).await { Ok(a) => a, Err(err) => { warn!("{}", err); return SudoResult::InternalError; } }; let session = match state.session.clone() { Some(AteSessionType::User(a)) => a, Some(_) => { warn!("internal error: wrong type of session"); return SudoResult::InternalError; } None => { warn!("internal error: no session"); return SudoResult::InternalError; } }; // Create the sudo command let login = SudoRequest { session, authenticator_code, }; // Attempt the sudo request with a 10 second timeout let response: Result<SudoResponse, SudoFailed> = match chain.invoke(login).await { Ok(a) => a, Err(err) => { warn!("{}", err); return SudoResult::InternalError; } }; let result = match response { Ok(a) => a, Err(SudoFailed::WrongCode) => { return SudoResult::WrongCode; } Err(SudoFailed::MissingToken) => { warn!("invoke sudo failed: missing token"); return SudoResult::InternalError; } Err(SudoFailed::UserNotFound(msg)) => { warn!("invoke sudo failed: user not found - {}", msg); return SudoResult::InternalError; } Err(SudoFailed::AccountLocked(_)) => { warn!("invoke sudo failed: account locked"); return SudoResult::InternalError; } Err(SudoFailed::Unverified(msg)) => { warn!("invoke sudo failed: unverified ({})", msg); return SudoResult::InternalError; } Err(SudoFailed::NoMasterKey) => { warn!("invoke sudo failed: no master key"); return SudoResult::InternalError; } Err(SudoFailed::InternalError(code)) => { warn!("invoke sudo failed: internal error({})", code); return SudoResult::InternalError; } }; state.session = Some(AteSessionType::Sudo(result.authority)); SudoResult::Success } async fn user_create( registry: &Arc<Registry>, auth: &url::Url, state: &mut SshWizardState, ) -> UserCreateResult { // Grab the two main parts let username = match state.email.clone() { Some(a) => a, None => { return UserCreateResult::NoUsernameSupplied; } }; let password = match state.password.clone() { Some(a) => a, None => { return UserCreateResult::NoPasswordSupplied; } }; // Create a user using the authentication server which will give us a session with all the tokens let result = match wasmer_auth::cmd::create_user_command( registry, username, password, auth.clone(), state.accepted_terms.clone(), ) .await { Ok(a) => a, Err(CreateError(CreateErrorKind::AlreadyExists(_), _)) => { return UserCreateResult::AlreadyExists; } Err(CreateError(CreateErrorKind::TermsAndConditions(terms), _)) => { state.needed_terms = Some(terms); return UserCreateResult::Terms; } Err(CreateError(CreateErrorKind::InvalidEmail, _)) => { return UserCreateResult::InvalidEmail; } Err(err) => { warn!("{}", err); return UserCreateResult::InternalError; } }; if let Some(message_of_the_day) = &result.message_of_the_day { state.message_of_the_day = Some(message_of_the_day.clone()); } state.qr_code = Some(result.qr_code); return UserCreateResult::Created; }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/console_handle.rs
wasmer-ssh/src/console_handle.rs
use async_trait::async_trait; use std::io::{self, Write}; use std::ops::Deref; use std::sync::Arc; use std::sync::Mutex; use wasmer_os::api::ConsoleAbi; use wasmer_os::api::ConsoleRect; use thrussh::server::Handle; use thrussh::ChannelId; use thrussh::CryptoVec; use wasmer_term::wasmer_os; pub struct ConsoleHandle { pub rect: Arc<Mutex<ConsoleRect>>, pub channel: ChannelId, pub handle: Handle, pub stdio_lock: Arc<Mutex<()>>, pub enable_stderr: bool, } #[async_trait] impl ConsoleAbi for ConsoleHandle { /// Writes output to the SSH pipe async fn stdout(&self, data: Vec<u8>) { let channel = self.channel; let data = CryptoVec::from_slice(&data[..]); let mut handle = self.handle.clone(); let _ = handle.data(channel, data).await; } /// Writes output to the SSH pipe async fn stderr(&self, data: Vec<u8>) { let channel = self.channel; let data = CryptoVec::from_slice(&data[..]); let mut handle = self.handle.clone(); if self.enable_stderr { let _ = handle.extended_data(channel, 1, data).await; } else { let _ = handle.data(channel, data).await; } } /// Flushes the data down the SSH pipe async fn flush(&self) { let channel = self.channel; let mut handle = self.handle.clone(); let _ = handle.flush(channel).await; } /// Writes output to the log async fn log(&self, text: String) { use raw_tty::GuardMode; let _guard = self.stdio_lock.lock().unwrap(); if let Ok(mut stderr) = io::stderr().guard_mode() { write!(&mut *stderr, "{}\r\n", text).unwrap(); stderr.flush().unwrap(); } } /// Gets the number of columns and rows in the terminal async fn console_rect(&self) -> ConsoleRect { let rect = self.rect.lock().unwrap(); rect.deref().clone() } /// Clears the terminal async fn cls(&self) { let txt = format!("{}[2J", 27 as char); let data = txt.as_bytes().to_vec(); self.stdout(data).await; } /// Tell the process to exit (if it can) async fn exit(&self) { let mut handle = self.handle.clone(); let _ = handle.close(self.channel).await; } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/server.rs
wasmer-ssh/src/server.rs
use ate::prelude::*; use std::net::IpAddr; use std::sync::Arc; use std::sync::Mutex; use std::time::Duration; use wasmer_os::api::ConsoleRect; use thrussh::server; use tokio::sync::watch; use wasmer_term::wasmer_os; use wasmer_os::bin_factory::CachedCompiledModules; use crate::native_files::NativeFileInterface; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use crate::key::SshServerKey; use crate::opt::*; use crate::wizard::*; pub struct Server { pub listen: IpAddr, pub port: u16, pub server_key: SshServerKey, pub connection_timeout: Duration, pub auth_rejection_time: Duration, pub compiler: wasmer_os::eval::Compiler, pub registry: Arc<Registry>, pub native_files: NativeFileInterface, pub auth: url::Url, pub compiled_modules: Arc<CachedCompiledModules>, pub exit_rx: watch::Receiver<bool>, pub stdio_lock: Arc<Mutex<()>>, } impl Server { pub async fn new(host: OptsHost, server_key: SshServerKey, registry: Arc<Registry>, compiled_modules: Arc<CachedCompiledModules>, native_files: NativeFileInterface, rx_exit: watch::Receiver<bool>) -> Self { // Succes let auth = wasmer_auth::prelude::origin_url(&host.auth_url, "auth"); Self { native_files, listen: host.listen, port: host.port, server_key, connection_timeout: Duration::from_secs(600), auth_rejection_time: Duration::from_secs(0), compiler: host.compiler, registry, auth, compiled_modules, exit_rx: rx_exit, stdio_lock: Arc::new(Mutex::new(())), } } pub async fn listen(self) -> Result<(), Box<dyn std::error::Error>> { let mut config = thrussh::server::Config::default(); config.connection_timeout = Some(self.connection_timeout.clone()); config.auth_rejection_time = self.auth_rejection_time.clone(); config.keys.push(self.server_key.clone().into()); let config = Arc::new(config); let addr = format!("[{}]:{}", self.listen, self.port); info!("listening on {}", addr); thrussh::server::run(config, addr.as_str(), self).await?; Ok(()) } } impl server::Server for Server { type Handler = super::handler::Handler; fn new(&mut self, peer_addr: Option<std::net::SocketAddr>) -> super::handler::Handler { let peer_addr_str = peer_addr .map(|a| a.to_string()) .unwrap_or_else(|| "[unknown]".to_string()); info!("new connection from {}", peer_addr_str); // Return the handler let mut wizard = SshWizard { step: SshWizardStep::Init, state: SshWizardState::default(), registry: self.registry.clone(), auth: self.auth.clone(), }; wizard.state.welcome = Some(super::cconst::CConst::SSH_WELCOME.to_string()); super::handler::Handler { rect: Arc::new(Mutex::new(ConsoleRect { cols: 80, rows: 25 })), registry: self.registry.clone(), native_files: self.native_files.clone(), compiler: self.compiler, console: None, peer_addr, peer_addr_str, user: None, client_pubkey: None, wizard: Some(wizard), compiled_modules: self.compiled_modules.clone(), stdio_lock: self.stdio_lock.clone(), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/handler.rs
wasmer-ssh/src/handler.rs
use ate::mesh::Registry; use std::future::Future; use std::pin::Pin; use std::sync::Arc; use std::sync::Mutex; use wasmer_os::api::ConsoleRect; use wasmer_os::api::System; use wasmer_os::console::Console; use thrussh::server; use thrussh::server::Auth; use thrussh::server::Session; use thrussh::ChannelId; use thrussh_keys::key::ed25519; use thrussh_keys::key::PublicKey; use wasmer_term::wasmer_os; use wasmer_term::wasmer_os::api as term_api; use wasmer_term::wasmer_os::api::SystemAbiExt; use wasmer_term::wasmer_os::bin_factory::CachedCompiledModules; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use crate::native_files::NativeFileInterface; use crate::wizard::SshWizard; use super::console_handle::*; use super::error::*; pub struct Handler { pub registry: Arc<Registry>, pub native_files: NativeFileInterface, pub peer_addr: Option<std::net::SocketAddr>, pub peer_addr_str: String, pub user: Option<String>, pub client_pubkey: Option<thrussh_keys::key::PublicKey>, pub console: Option<Console>, pub compiler: wasmer_os::eval::Compiler, pub rect: Arc<Mutex<ConsoleRect>>, pub wizard: Option<SshWizard>, pub compiled_modules: Arc<CachedCompiledModules>, pub stdio_lock: Arc<Mutex<()>>, } impl server::Handler for Handler { type Error = SshServerError; type FutureAuth = Pin<Box<dyn Future<Output = Result<(Self, Auth), Self::Error>> + Send>>; type FutureUnit = Pin<Box<dyn Future<Output = Result<(Self, Session), Self::Error>> + Send>>; type FutureBool = Pin<Box<dyn Future<Output = Result<(Self, Session, bool), Self::Error>> + Send>>; fn finished_auth(self, auth: Auth) -> Self::FutureAuth { Box::pin(async move { Ok((self, auth)) }) } fn finished_bool(self, b: bool, session: Session) -> Self::FutureBool { Box::pin(async move { Ok((self, session, b)) }) } fn finished(self, session: Session) -> Self::FutureUnit { Box::pin(async move { Ok((self, session)) }) } fn auth_keyboard_interactive( mut self, user: &str, _submethods: &str, response: Option<server::Response>, ) -> Self::FutureAuth { debug!("authenticate with keyboard interactive (user={})", user); self.user = Some(user.to_string()); // Get the current wizard or fail let wizard = match self.wizard.as_mut() { Some(a) => a, None => { return self.finished_auth(Auth::Reject); } }; // Root is always rejected (as this is what bots attack on) if user == "root" { warn!("root attempt rejected from {}", self.peer_addr_str); wizard.fail("root not supported - instead use 'ssh joe@blogs.com@wasmer.sh'\r\n"); } // Set the user if its not set if wizard.state.email.is_none() { wizard.state.email = Some(user.to_string()); } // Process it in the wizard let _response = match response { Some(mut a) => Some(convert_response(&mut a)), None => None, }; // Unfortunately the SSH server isnt working properly so we accept // the session into the shell and process it there instead self.finished_auth(Auth::Accept) } fn data(mut self, channel: ChannelId, data: &[u8], session: Session) -> Self::FutureUnit { trace!("data on channel {:?}: len={:?}", channel, data.len()); let data = String::from_utf8(data.to_vec()).map_err(|_| { let err: SshServerError = SshServerErrorKind::BadData.into(); err }); Box::pin(async move { let data = data?; if let Some(console) = self.console.as_mut() { console.on_data(data).await; } Ok((self, session)) }) } #[allow(unused_variables)] fn shell_request(mut self, channel: ChannelId, session: Session) -> Self::FutureUnit { debug!("shell_request"); let native_files = self.native_files.clone(); Box::pin(async move { // Create the handle let handle = Arc::new(ConsoleHandle { rect: self.rect.clone(), channel: channel.clone(), handle: session.handle(), stdio_lock: self.stdio_lock.clone(), enable_stderr: false, }); // Spawn a dedicated thread and wait for it to do its thing let system = System::default(); system .spawn_shared(move || async move { // Get the wizard let wizard = self.wizard.take().map(|a| { Box::new(a) as Box<dyn term_api::WizardAbi + Send + Sync + 'static> }); // Create the console let fs = wasmer_os::fs::create_root_fs(None); let location = "ssh://wasmer.sh/?no_welcome".to_string(); let user_agent = "ssh".to_string(); let compiled_modules = self.compiled_modules.clone(); let mut console = Console::new( location, user_agent, self.compiler, handle, wizard, fs, compiled_modules, ); console.init().await; self.console.replace(console); // We are ready to receive data Ok((self, session)) }) .await .unwrap() }) } #[allow(unused_variables)] fn pty_request( self, channel: ChannelId, term: &str, col_width: u32, row_height: u32, pix_width: u32, pix_height: u32, modes: &[(thrussh::Pty, u32)], session: Session, ) -> Self::FutureUnit { debug!("pty_request"); { let mut guard = self.rect.lock().unwrap(); guard.cols = col_width; guard.rows = row_height; } self.finished(session) } } impl Drop for Handler { fn drop(&mut self) { info!("ssh connection closed ({})", self.peer_addr_str); } } #[allow(dead_code)] fn clone_public_key(key: &PublicKey) -> PublicKey { match key { PublicKey::Ed25519(a) => PublicKey::Ed25519(ed25519::PublicKey { key: a.key.clone() }), } } fn convert_response<'a>(response: &mut thrussh::server::Response<'a>) -> Vec<String> { let mut ret = Vec::new(); for txt in response.map(|a| a.to_vec()).collect::<Vec<Vec<u8>>>() { if let Ok(txt) = String::from_utf8(txt) { ret.push(txt); } else { break; } } ret }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/native_files.rs
wasmer-ssh/src/native_files.rs
use ate::mesh::Registry; use ate::session::AteSessionType; use ate::session::AteSessionUser; use ate::transaction::TransactionScope; use ate_files::prelude::*; use ate::prelude::AteErrorKind; use std::sync::Arc; use tokio::sync::Mutex; use std::path::PathBuf; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; #[derive(Debug, Clone)] pub enum NativeFileType { AteFileSystem(String), LocalFileSystem(String), EmbeddedFiles, } #[derive(Debug, Clone)] pub enum NativeFileInterface { AteFileSystem(NativeFiles), LocalFileSystem(PathBuf), EmbeddedFiles } #[derive(Debug, Clone)] pub struct NativeFiles { registry: Arc<Registry>, db_url: url::Url, native_files_name: String, native_files: Arc<Mutex<Option<Arc<FileAccessor>>>>, } impl NativeFiles { pub fn new(registry: Arc<Registry>, db_url: url::Url, native_files: String) -> Self { Self { registry, db_url, native_files_name: native_files, native_files: Arc::new(Mutex::new(None)) } } pub async fn get(&self) -> Result<Arc<FileAccessor>, FileSystemError> { // Lock and fast path let mut guard = self.native_files.lock().await; if guard.is_some() { return Ok(guard.as_ref().unwrap().clone()); } // Connect to the file system that holds all the binaries that // we will present natively to the consumers // Note: These are the same files presenting to the web-site version of the terminal let native_files_key = ate::prelude::ChainKey::from(self.native_files_name.clone()); let native_files = self.registry.open(&self.db_url, &native_files_key, false).await .map_err(|err| FileSystemErrorKind::AteError(AteErrorKind::ChainCreationError(err.0)))?; let native_files = Arc::new( FileAccessor::new( native_files.as_arc(), None, AteSessionType::User(AteSessionUser::default()), TransactionScope::Local, TransactionScope::Local, true, false, ) .await, ); // Attempt to read the root from the native file system which will make sure that its // all nicely running native_files .search(&RequestContext { uid: 0, gid: 0 }, "/") .await?; // Set the object and return guard.replace(native_files.clone()); Ok(native_files) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/opt/core.rs
wasmer-ssh/src/opt/core.rs
use clap::Parser; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use super::ssh::OptsSsh; #[derive(Parser)] #[clap(version = "1.0", author = "John S. <johnathan.sharratt@gmail.com>")] pub struct Opts { /// Sets the level of log verbosity, can be used multiple times #[allow(dead_code)] #[clap(short, long, parse(from_occurrences))] pub verbose: i32, /// Logs debug info to the console #[clap(short, long)] pub debug: bool, /// URL where the user is authenticated (e.g. ws://wasmer.sh/auth) #[clap(short, long)] pub auth: Option<url::Url>, /// Path to the secret server key #[clap(default_value = "~/wasmer/ssh.server.key")] pub key_path: String, #[clap(subcommand)] pub subcmd: SubCommand, } #[derive(Parser)] pub enum SubCommand { /// Starts an SSH command #[clap()] Ssh(OptsSsh), }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/opt/mod.rs
wasmer-ssh/src/opt/mod.rs
mod core; mod generate; mod ssh; mod host; pub use self::core::*; pub use generate::*; pub use ssh::*; pub use host::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/opt/host.rs
wasmer-ssh/src/opt/host.rs
use std::net::IpAddr; use wasmer_term::wasmer_os; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use clap::Parser; /// Runs a ssh server host #[derive(Parser)] pub struct OptsHost { /// IP address that the SSH server will isten on #[clap(short, long, default_value = "::")] pub listen: IpAddr, /// Port that the server will listen on for SSH requests #[clap(long, default_value = "22")] pub port: u16, /// Determines which compiler to use #[clap(short, long, default_value = "default")] pub compiler: wasmer_os::eval::Compiler, /// Location where cached compiled modules are stored #[clap(long, default_value = "~/wasmer/compiled")] pub compiler_cache_path: String, /// URL of the datachain servers (e.g. wss://wasmer.sh/db) #[clap(long)] pub db_url: Option<url::Url>, /// URL of the authentication servers (e.g. wss://wasmer.sh/auth) #[clap(long)] pub auth_url: Option<url::Url>, /// Location where the native binary files are stored #[clap(long, default_value = "wasmer.sh/www")] pub native_files: String, /// Uses a local directory for native files rather than the published ate chain #[clap(long)] pub native_files_path: Option<String>, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/opt/generate.rs
wasmer-ssh/src/opt/generate.rs
use clap::Parser; /// Generates the SSH server key that helps protect from man-in-the-middle attacks #[derive(Parser)] pub struct OptsGenerate { }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/opt/ssh.rs
wasmer-ssh/src/opt/ssh.rs
#[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use clap::Parser; use super::generate::*; use super::host::*; #[derive(Parser)] pub struct OptsSsh { #[clap(subcommand)] pub action: OptsSshAction, } #[derive(Parser)] pub enum OptsSshAction { /// Starts a ssh host #[clap()] Host(OptsHost), /// Generates the SSH serve side keys #[clap()] Generate(OptsGenerate), }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-ssh/src/bin/wasmer-ssh.rs
wasmer-ssh/src/bin/wasmer-ssh.rs
use clap::Parser; #[allow(unused_imports)] use tracing::{debug, error, info, instrument, span, trace, warn, Level}; use tokio::sync::watch; use wasmer_auth::helper::conf_cmd; use wasmer_ssh::key::*; use wasmer_ssh::opt::*; use wasmer_ssh::server::Server; use wasmer_ssh::utils::*; use wasmer_ssh::native_files::NativeFileType; use std::sync::Arc; use tokio::runtime::Builder; use wasmer_ssh::wasmer_os; use wasmer_os::bin_factory::CachedCompiledModules; fn main() -> Result<(), Box<dyn std::error::Error>> { let opts: Opts = Opts::parse(); // Enable the logging log_init(opts.verbose, opts.debug); // Create the runtime let runtime = Arc::new(Builder::new_multi_thread().enable_all().build().unwrap()); // Process the command let key_path = opts.key_path.clone(); match opts.subcmd { SubCommand::Ssh(ssh) => { match ssh.action { OptsSshAction::Host(host) => { runtime.clone().block_on(async move { // Load the SSH key let server_key: SshServerKey = load_key(key_path); // Create the registry that will be used to validate logins let registry = ate::mesh::Registry::new(&conf_cmd()).await.cement(); // Set the system let (tx_exit, rx_exit) = watch::channel(false); let sys = Arc::new(wasmer_term::system::SysSystem::new_with_runtime( tx_exit, runtime, )); let native_files = if let Some(path) = host.native_files_path.clone() { NativeFileType::LocalFileSystem(path) } else { NativeFileType::AteFileSystem(host.native_files.clone()) }; // Start the system and add the native files let db_url = wasmer_auth::prelude::origin_url(&host.db_url, "db"); let sys = wasmer_ssh::system::System::new(sys, registry.clone(), db_url, native_files).await; let native_files = sys.native_files.clone(); wasmer_os::api::set_system_abi(sys); // Start the SSH server let compiled_modules = Arc::new(CachedCompiledModules::new(Some(host.compiler_cache_path.clone()))); let server = Server::new(host, server_key, registry, compiled_modules, native_files, rx_exit).await; server.listen().await?; Ok(()) }) } OptsSshAction::Generate(_) => { let key = SshServerKey::generate_ed25519(); save_key(key_path, key); Ok(()) } } } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/prelude.rs
wasmer-deploy-cli/src/prelude.rs
pub use wasmer_auth::prelude::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/lib.rs
wasmer-deploy-cli/src/lib.rs
pub mod api; pub mod bus; pub mod cmd; pub mod error; pub mod helper; pub mod model; pub mod opt; pub mod prelude; pub mod request;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/peering.rs
wasmer-deploy-cli/src/cmd/peering.rs
use ate::prelude::*; use crate::api::DeployApi; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use crate::error::*; use crate::model::{ServiceInstance, InstancePeering, WalletInstance}; use crate::opt::*; pub async fn main_opts_peering_list( instance: DaoMut<ServiceInstance>, ) -> Result<(), InstanceError> { println!("|---network peerings---|"); for peer in instance.subnet.peerings.iter() { println!("{}", peer.name); } Ok(()) } pub async fn main_opts_peering_add( api: &mut DeployApi, mut instance: DaoMut<ServiceInstance>, wallet_instance: DaoMut<WalletInstance>, opts: OptsPeeringAdd ) -> Result<(), InstanceError> { let (peer, peer_wallet) = api.instance_action(opts.peer.as_str()).await?; let mut peer = peer?; { let dio = instance.dio_mut(); if instance.subnet.peerings.iter().any(|p| p.chain.name == peer.chain) == false { let mut instance = instance.as_mut(); instance.subnet.peerings.push( InstancePeering { id: peer.id, name: peer_wallet.name.clone(), chain: ChainKey::from(peer.chain.clone()), access_token: peer.subnet.network_token.clone(), } ); } dio.commit().await?; } { let dio = peer.dio_mut(); if peer.subnet.peerings.iter().any(|p| p.chain.name == instance.chain) == false { let mut peer = peer.as_mut(); peer.subnet.peerings.push( InstancePeering { id: instance.id, name: wallet_instance.name.clone(), chain: ChainKey::from(instance.chain.clone()), access_token: instance.subnet.network_token.clone(), } ); } dio.commit().await?; } Ok(()) } pub async fn main_opts_peering_remove( api: &mut DeployApi, mut instance: DaoMut<ServiceInstance>, opts: OptsPeeringRemove ) -> Result<(), InstanceError> { let (peer, _) = api.instance_action(opts.peer.as_str()).await?; let mut peer = peer?; { let dio = instance.dio_mut(); let mut instance = instance.as_mut(); instance.subnet.peerings.retain(|p| p.chain.name != peer.chain); drop(instance); dio.commit().await?; } { let dio = peer.dio_mut(); let mut peer = peer.as_mut(); peer.subnet.peerings.retain(|p| p.chain.name != instance.chain); drop(peer); dio.commit().await?; } Ok(()) } pub async fn main_opts_peering( api: &mut DeployApi, instance: DaoMut<ServiceInstance>, wallet_instance: DaoMut<WalletInstance>, action: OptsPeeringAction, ) -> Result<(), InstanceError> { // Determine what we need to do match action { OptsPeeringAction::List => { main_opts_peering_list(instance).await?; } OptsPeeringAction::Add(add) => { main_opts_peering_add(api, instance, wallet_instance, add).await?; } OptsPeeringAction::Remove(remove) => { main_opts_peering_remove(api, instance, remove).await?; } } Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/cancel_deposit.rs
wasmer-deploy-cli/src/cmd/cancel_deposit.rs
use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use url::Url; use ate::prelude::*; use crate::error::*; use crate::model::*; use crate::request::*; pub async fn cancel_deposit_command( registry: &Arc<Registry>, coin_ancestor: Ownership, auth: Url, ) -> Result<CancelDepositResponse, WalletError> { // Open a command chain let chain = registry.open_cmd(&auth).await?; // Create the login command let query = CancelDepositRequest { owner: coin_ancestor, }; // Attempt the login request with a 10 second timeout let response: Result<CancelDepositResponse, CancelDepositFailed> = chain.invoke(query).await?; let result = response?; Ok(result) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/service_find.rs
wasmer-deploy-cli/src/cmd/service_find.rs
use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use ate::prelude::*; use crate::error::*; use crate::model::*; use crate::request::*; pub fn get_advertised_service<'a>( response: &'a ServiceFindResponse, service_name: &'_ str, ) -> Result<Option<&'a AdvertisedService>, CoreError> { let service = response .services .iter() .filter(|a| a.name.to_lowercase() == service_name || a.code == service_name) .next(); Ok(service) } pub async fn service_find_command( registry: &Arc<Registry>, service_name: Option<String>, auth: url::Url, ) -> Result<ServiceFindResponse, CoreError> { // Open a command chain let chain = registry.open_cmd(&auth).await?; // Create the login command let query = ServiceFindRequest { service_name }; // Attempt the login request with a 10 second timeout let response: Result<ServiceFindResponse, ServiceFindFailed> = chain.invoke(query).await?; let result = response?; Ok(result) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/contract.rs
wasmer-deploy-cli/src/cmd/contract.rs
#[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use url::Url; use crate::error::*; use crate::opt::*; use super::*; pub async fn main_opts_contract( opts: OptsContractFor, token_path: String, auth_url: Url, ) -> Result<(), ContractError> { let mut context = PurposeContext::new(&opts, token_path.as_str(), &auth_url, None, true).await?; let identity = context.identity.clone(); match context.action.clone() { OptsContractAction::List => { main_opts_contract_list(&mut context.api).await?; } OptsContractAction::Details(opts) => { main_opts_contract_details(opts, &mut context.api).await?; } OptsContractAction::Cancel(opts) => { main_opts_contract_cancel(opts, &mut context.api, &identity).await?; } } context.api.commit().await?; Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/withdraw.rs
wasmer-deploy-cli/src/cmd/withdraw.rs
use error_chain::bail; use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use url::Url; use ate::prelude::*; use crate::api::*; use crate::error::*; use crate::model::*; use crate::opt::*; use crate::request::*; use super::*; pub async fn withdraw_command( registry: &Arc<Registry>, coins: Vec<CarvedCoin>, session: &'_ dyn AteSession, auth: Url, wallet_name: String, ) -> Result<WithdrawResponse, WalletError> { // The signature key needs to be present to send the notification let sign_key = match session.user().user.write_keys().next() { Some(a) => a, None => { bail!(CoreError::from_kind(CoreErrorKind::NoMasterKey)); } }; // Get the receiver email address let receiver = session.user().identity().to_string(); // Create the login command let email = session.user().identity().to_string(); let query = WithdrawRequest { coins, params: SignedProtectedData::new( sign_key, WithdrawRequestParams { sender: email.clone(), receiver: receiver.clone(), wallet: wallet_name, }, )?, }; // Attempt the login request with a 10 second timeout let chain = registry.open_cmd(&auth).await?; let response: Result<WithdrawResponse, WithdrawFailed> = chain.invoke(query).await?; let result = response?; Ok(result) } pub async fn main_opts_withdraw<A>( opts: OptsWithdraw, source: &dyn OptsPurpose<A>, api: &mut DeployApi, ) -> Result<(), WalletError> where A: Clone, { let identity = api.dio.session().user().identity().to_string(); api.withdraw( opts.currency, opts.amount, source.fullname(identity.as_str()), ) .await?; println!("Successfully withdrawn {} {}", opts.amount, opts.currency); // Show the new balances println!(""); main_opts_balance( OptsBalance { coins: false, no_reconcile: false, }, api, ) .await?; // Done Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/transfer.rs
wasmer-deploy-cli/src/cmd/transfer.rs
#[allow(unused_imports)] use tracing::{debug, error, info}; use crate::api::*; use crate::error::*; use crate::opt::*; pub async fn main_opts_transfer<A>( opts: OptsTransfer, source: &dyn OptsPurpose<A>, api: &mut DeployApi, ) -> Result<(), WalletError> where A: Clone, { let repeat = opts.repeat.unwrap_or_else(|| 1u32); let should_notify = repeat <= 1 && opts.silent == false; for _ in 0..repeat { api.transfer( opts.amount, opts.currency, &opts.destination, source, should_notify, ) .await?; println!("Successfully transferred {} {}", opts.amount, opts.currency); } // Success Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/network.rs
wasmer-deploy-cli/src/cmd/network.rs
#[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; #[cfg(unix)] #[allow(unused_imports)] use std::os::unix::fs::symlink; #[allow(unused_imports)] #[cfg(unix)] use std::os::unix::fs::PermissionsExt; use std::ops::Deref; use error_chain::bail; use async_stream::stream; use futures_util::pin_mut; use futures_util::stream::StreamExt; #[cfg(feature = "enable_bridge")] #[cfg(any(target_os = "linux", target_os = "macos"))] use { std::process::Command, std::process::Stdio, std::net::Ipv4Addr, tokio::io::AsyncReadExt, tokio::io::AsyncWriteExt, tokio_tun::TunBuilder, }; use ate::prelude::*; #[allow(unused_imports)] use wasmer_bus_mio::prelude::*; use crate::error::*; use crate::model::NetworkToken; #[allow(unused_imports)] use crate::model::HardwareAddress; use crate::opt::*; use crate::api::DeployApi; use super::*; pub async fn main_opts_network( opts_network: OptsNetwork, token_path: String, auth_url: url::Url, ) -> Result<(), InstanceError> { #[allow(unused_variables)] let db_url = wasmer_auth::prelude::origin_url(&opts_network.db_url, "db"); match opts_network.cmd { OptsNetworkCommand::For(opts) => { let purpose: &dyn OptsPurpose<OptsNetworkAction> = &opts.purpose; let mut context = PurposeContext::new(purpose, token_path.as_str(), &auth_url, Some(&db_url), true).await?; match context.action.clone() { OptsNetworkAction::List => { main_opts_network_list(&mut context.api).await }, OptsNetworkAction::Details(opts) => { main_opts_network_details(&mut context.api, opts.name.as_str()).await }, OptsNetworkAction::Cidr(opts) => { main_opts_network_cidr(&mut context.api, opts.name.as_str(), opts.action).await }, OptsNetworkAction::Peering(opts) => { main_opts_network_peering(&mut context.api, opts.name.as_str(), opts.action).await }, OptsNetworkAction::Reset(opts) => { main_opts_network_reset(&mut context.api, opts.name.as_str()).await }, OptsNetworkAction::Connect(opts) => { main_opts_network_connect(&mut context.api, opts.name.as_str(), token_path, opts.export).await }, OptsNetworkAction::Create(opts) => { let mut instance_authority = db_url.domain() .map(|a| a.to_string()) .unwrap_or_else(|| "wasmer.sh".to_string()); if instance_authority == "localhost" { instance_authority = "wasmer.sh".to_string(); } main_opts_network_create(&mut context.api, opts.name, purpose.group_name(), db_url, instance_authority, opts.force).await }, OptsNetworkAction::Kill(opts) => { main_opts_network_kill(&mut context.api, opts.name.as_str(), opts.force).await }, } }, OptsNetworkCommand::Reconnect(opts) => { main_opts_network_reconnect(opts.token, token_path).await }, OptsNetworkCommand::Disconnect => { main_opts_network_disconnect(token_path).await; Ok(()) }, OptsNetworkCommand::Monitor(opts) => { let net_url = wasmer_auth::prelude::origin_url(&opts.net_url, "net"); main_opts_network_monitor(token_path, net_url, opts_network.security).await }, #[cfg(feature = "enable_bridge")] #[cfg(any(target_os = "linux", target_os = "macos"))] OptsNetworkCommand::Bridge(opts) => { let net_url = wasmer_auth::prelude::origin_url(&opts.net_url, "net"); main_opts_network_bridge(opts, token_path, net_url, opts_network.security).await } } } pub async fn main_opts_network_list( api: &mut DeployApi, ) -> Result<(), InstanceError> { println!("|-------name-------|-peerings"); let instances = api.instances().await; let instances = instances.iter_ext(true, true).await?; let instances_ext = { let api = api.clone(); stream! { for instance in instances { let name = instance.name.clone(); yield ( api.instance_chain(instance.name.as_str()) .await .map(|chain| (instance, chain)), name, ) } } }; pin_mut!(instances_ext); while let Some((res, name)) = instances_ext.next().await { let (wallet_instance, _) = match res { Ok(a) => a, Err(err) => { debug!("error loading wallet instance - {} - {}", name, err); println!( "- {:<16} - {:<19} - {}", name, "error", err ); continue; } }; let mut peerings = String::new(); if let Ok(service_instance) = api.instance_load(wallet_instance.deref()).await { for peer in service_instance.subnet.peerings.iter() { if peerings.len() > 0 { peerings.push_str(","); } peerings.push_str(peer.name.as_str()); } } println!( "- {:<16} - {}", wallet_instance.name, peerings ); } Ok(()) } pub async fn main_opts_network_details( api: &mut DeployApi, network_name: &str, ) -> Result<(), InstanceError> { let network = api.instance_find(network_name) .await; let network = match network { Ok(a) => a, Err(InstanceError(InstanceErrorKind::InvalidInstance, _)) => { eprintln!("An network does not exist for this token."); std::process::exit(1); } Err(err) => { bail!(err); } }; println!("Network"); println!("{}", serde_json::to_string_pretty(network.deref()).unwrap()); if let Ok(service_instance) = api.instance_load(network.deref()).await { println!("{}", serde_json::to_string_pretty(&service_instance.subnet).unwrap()); for node in service_instance.mesh_nodes.iter().await? { println!(""); println!("Mesh Node"); println!("Key: {}", node.key()); println!("Address: {}", node.node_addr); if node.switch_ports.len() > 0 { println!("Switch Ports:"); for switch_port in node.switch_ports.iter() { println!("- {}", switch_port); } } if node.dhcp_reservation.len() > 0 { println!("DHCP"); for (mac, ip) in node.dhcp_reservation.iter() { println!("- {} - {},", mac, ip.addr4); } } } } Ok(()) } pub async fn main_opts_network_cidr( api: &mut DeployApi, network_name: &str, action: OptsCidrAction, ) -> Result<(), InstanceError> { let (instance, _) = api.instance_action(network_name).await?; let instance = instance?; main_opts_cidr(instance, action).await?; Ok(()) } pub async fn main_opts_network_peering( api: &mut DeployApi, network_name: &str, action: OptsPeeringAction, ) -> Result<(), InstanceError> { let (instance, wallet_instance) = api.instance_action(network_name).await?; let instance = instance?; main_opts_peering(api, instance, wallet_instance, action).await?; Ok(()) } pub async fn main_opts_network_reset( api: &mut DeployApi, network_name: &str, ) -> Result<(), InstanceError> { main_opts_instance_reset(api, network_name).await } pub async fn main_opts_network_connect( api: &mut DeployApi, network_name: &str, token_path: String, export: bool, ) -> Result<(), InstanceError> { // Get the specifics around the network we will be connecting too let (instance, _) = api.instance_action(network_name).await?; let instance = instance?; let chain = instance.chain.clone(); let access_token = instance.subnet.network_token.clone(); // Build the access token let token = NetworkToken { chain: ChainKey::from(chain.clone()), access_token: access_token.clone(), }; // If we are exporting then just throw it out to STDOUT if export { println!("{}", token); return Ok(()); } // Save the token save_access_token(token_path, &token).await?; Ok(()) } pub async fn main_opts_network_create( api: &mut DeployApi, network_name: Option<String>, group: Option<String>, db_url: url::Url, instance_authority: String, force: bool, ) -> Result<(), InstanceError> { main_opts_instance_create(api, network_name, group, db_url, instance_authority, force).await } pub async fn main_opts_network_kill( api: &mut DeployApi, network_name: &str, force: bool, ) -> Result<(), InstanceError> { main_opts_instance_kill(api, network_name, force).await } pub async fn main_opts_network_reconnect( token: String, token_path: String, ) -> Result<(), InstanceError> { // Decode the token let token = FromStr::from_str(token.as_str())?; // Save the token save_access_token(token_path, &token).await?; Ok(()) } pub async fn main_opts_network_disconnect(token_path: String) { clear_access_token(token_path).await; } pub async fn main_opts_network_monitor( token_path: String, net_url: url::Url, security: StreamSecurity, ) -> Result<(), InstanceError> { let token_path = if let Ok(t) = std::env::var("NETWORK_TOKEN_PATH") { t } else { shellexpand::tilde(token_path.as_str()).to_string() }; let port = Port::new(TokenSource::ByPath(token_path), net_url, security)?; let socket = port.bind_raw() .await .map_err(|err| { let err = format!("failed to open raw socket - {}", err); error!("{}", err); InstanceErrorKind::InternalError(0) })?; socket.set_promiscuous(true) .await .map_err(|err| { let err = format!("failed to set promiscuous - {}", err); error!("{}", err); InstanceErrorKind::InternalError(0) })?; println!("Monitoring {}", port.chain()); while let Ok(data) = socket.recv().await { tcpdump(&data[..]); } Ok(()) } #[cfg(not(feature = "smoltcp"))] fn tcpdump(data: &[u8]) { if data.len() > 18 { let end = data.len() - 18; let dst = hex::encode(&data[0..6]).to_uppercase(); let src = hex::encode(&data[6..12]).to_uppercase(); let ty = hex::encode(&data[12..14]).to_uppercase(); let data = hex::encode(&data[14..end]).to_uppercase(); println!("{}->{} ({}): {}", src, dst, ty, data); } else { println!("JUNK 0x{}", hex::encode(data).to_uppercase()); } } #[cfg(feature = "smoltcp")] fn tcpdump(data: &[u8]) { let pck = smoltcp::wire::PrettyPrinter::<smoltcp::wire::EthernetFrame<&[u8]>>::new("", &data); println!("{}", pck); } #[cfg(feature = "enable_bridge")] #[cfg(any(target_os = "linux", target_os = "macos"))] pub async fn main_opts_network_bridge( bridge: OptsNetworkBridge, token_path: String, net_url: url::Url, security: StreamSecurity, ) -> Result<(), InstanceError> { let token_path = if let Ok(t) = std::env::var("NETWORK_TOKEN_PATH") { t } else { shellexpand::tilde(token_path.as_str()).to_string() }; std::env::set_var("NETWORK_TOKEN_PATH", token_path.as_str()); ::sudo::with_env(&(vec!("NETWORK_TOKEN_PATH")[..])).unwrap(); if bridge.daemon { if let Ok(fork::Fork::Parent(_)) = fork::daemon(true, true) { return Ok(()) } } let port = Port::new(TokenSource::ByPath(token_path), net_url, security)?; let hw = port.hardware_address() .await? .ok_or_else(|| { error!("the hardware address (MAC) on the port has not been set"); InstanceErrorKind::InternalError(0) })?; let hw: [u8; 6] = hw.into(); let (ip4, netmask4) = port.dhcp_acquire().await?; print!("connected:"); if let Ok(Some(mac)) = port.hardware_address().await { print!(" mac={}", mac); } if let Ok(Some(ip)) = port.addr_ipv4().await { print!(" ip={}", ip); } println!(""); let mtu = bridge.mtu.unwrap_or(1500); let socket = port.bind_raw() .await .map_err(|err| { let err = format!("failed to open raw socket - {}", err); error!("{}", err); InstanceErrorKind::InternalError(0) })?; if bridge.promiscuous { socket.set_promiscuous(true) .await .map_err(|err| { let err = format!("failed to set promiscuous - {}", err); error!("{}", err); InstanceErrorKind::InternalError(0) })?; } let name_id = fastrand::u64(..); let name = format!("ate{}", hex::encode(name_id.to_ne_bytes()).to_uppercase()); let name = &name[..15]; let tap = TunBuilder::new() .name(name) .tap(true) .packet_info(false) .mtu(mtu as i32) .mac(hw.clone()) //.up() .address(ip4) .netmask(netmask4) .broadcast(Ipv4Addr::BROADCAST) .try_build() .map_err(|err| { let err = format!("failed to build tun/tap device - {}", err); error!("{}", err); InstanceErrorKind::InternalError(0) })?; let (mut reader, mut writer) = tokio::io::split(tap); std::thread::sleep(std::time::Duration::from_millis(200)); cmd("ip", &["link", "set", "dev", name, "down"]); if bridge.promiscuous { cmd("ip", &["link", "set", "dev", name, "promisc", "on"]); } let hw = hex::encode(hw.as_slice()); let hw = format!("{}:{}:{}:{}:{}:{}", &hw[0..2], &hw[2..4], &hw[4..6], &hw[6..8], &hw[8..10], &hw[10..12]); let _ = cmd("ip", &["link", "set", "dev", name, "address", hw.as_str()]); let _ = cmd("ip", &["link", "set", "dev", name, "up"]); loop { let mut buf = [0u8; 2048]; tokio::select! { n = reader.read(&mut buf) => { match n { Ok(n) => { let buf = (&buf[..n]).to_vec(); socket.send(buf).await?; } Err(err) => { error!("TAP device closed - {}", err); break; } } }, data = socket.recv() => { let data = data?; writer.write(&data[..]).await?; } } } Ok(()) } #[cfg(feature = "enable_bridge")] #[cfg(any(target_os = "linux", target_os = "macos"))] fn cmd_inner(cmd: &str, args: &[&str], stderr: Stdio, stdout: Stdio) -> Result<std::process::ExitStatus, std::io::Error> { Command::new(cmd) .args(args) .stderr(stderr) .stdout(stdout) .spawn() .unwrap() .wait() } #[cfg(feature = "enable_bridge")] #[cfg(any(target_os = "linux", target_os = "macos"))] fn cmd(cmd: &str, args: &[&str]) { let ecode = cmd_inner(cmd, args, Stdio::inherit(), Stdio::inherit()).unwrap(); assert!(ecode.success(), "Failed to execte {}", cmd); std::thread::sleep(std::time::Duration::from_millis(10)); } pub use wasmer_bus_mio::prelude::TokenSource; pub use wasmer_bus_mio::prelude::Port; pub use wasmer_bus_mio::prelude::load_access_token; pub use wasmer_bus_mio::prelude::save_access_token; pub use wasmer_bus_mio::prelude::clear_access_token;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/login.rs
wasmer-deploy-cli/src/cmd/login.rs
use ate::error::AteError; use ate::prelude::*; use wasmer_auth::cmd::*; use wasmer_auth::helper::*; #[cfg(target_os = "wasi")] use wasmer_bus_process::prelude::*; use crate::opt::*; pub async fn main_opts_login( action: OptsLogin, token_path: String, auth: url::Url, ) -> Result<(), AteError> { // Convert the token path to a real path let token_path = shellexpand::tilde(&token_path).to_string(); // If a token was supplied then just use it, otherwise we need to get one let token = if let Some(token) = action.token { token } else { // Get the token session let session = main_login(action.email, action.password, auth.clone()).await?; let session: AteSessionType = if action.sudo { main_sudo(session, None, auth).await?.into() } else { session.into() }; session_to_b64(session).unwrap() }; // Read the session let session = b64_to_session(token.clone()); #[allow(unused)] let identity = session.identity(); // Save the token save_token(token, token_path)?; // If we are in WASM mode and there is a login script then run it #[cfg(target_os = "wasi")] if std::path::Path::new("/etc/login.sh").exists() == true { Command::new("export") .args(&[format!("USER={}", identity).as_str()]) .execute() .await?; Command::new("source") .args(&["/etc/login.sh"]) .execute() .await?; } #[cfg(target_os = "wasi")] if std::path::Path::new("/usr/etc/login.sh").exists() == true { Command::new("export") .args(&[format!("USER={}", identity).as_str()]) .execute() .await?; Command::new("source") .args(&["/usr/etc/login.sh"]) .execute() .await?; } Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/disconnect.rs
wasmer-deploy-cli/src/cmd/disconnect.rs
#[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use crate::bus::disconnect_from_networks; pub async fn main_opts_disconnect() { disconnect_from_networks().await; }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/core.rs
wasmer-deploy-cli/src/cmd/core.rs
use std::ops::Deref; use std::ops::DerefMut; use std::sync::Arc; use std::time::Duration; #[allow(unused_imports)] use tracing::{debug, error, info}; use ate::prelude::*; use crate::api::*; use crate::error::*; use crate::model::*; use crate::opt::*; use super::*; pub async fn session_with_permissions<A>( purpose: &dyn OptsPurpose<A>, token_path: &str, auth_url: &url::Url, sudo: bool, ) -> Result<(A, AteSessionType), AteError> where A: Clone, { let session: AteSessionType; if let Purpose::<A>::Domain { domain_name: group_name, wallet_name: _, action: _, } = purpose.purpose() { session = main_session_group( None, Some(token_path.to_string()), group_name, sudo, None, Some(auth_url.clone()), "Domain name", ) .await? .into(); } else if sudo { session = main_session_sudo( None, Some(token_path.to_string()), None, Some(auth_url.clone()), ) .await? .into(); } else { session = main_session_user(None, Some(token_path.to_string()), Some(auth_url.clone())) .await? .into(); } Ok((purpose.action(), session)) } pub async fn get_identity<A>( purpose: &dyn OptsPurpose<A>, session: &dyn AteSession, ) -> Result<String, AteError> where A: Clone, { let identity = match purpose.purpose() { Purpose::Personal { wallet_name: _, action: _, } => session.user().identity().to_string(), Purpose::Domain { domain_name: group_name, wallet_name: _, action: _, } => group_name, }; debug!("identity={}", identity); Ok(identity) } pub fn get_wallet_name<A>(purpose: &dyn OptsPurpose<A>) -> std::result::Result<String, AteError> where A: Clone, { // Validate a wallet name is supplied correctly let wallet_name = purpose.wallet_name().to_lowercase(); if wallet_name.len() <= 0 { eprintln!("No wallet name was supplied."); std::process::exit(1); } debug!("wallet_name={}", wallet_name); Ok(wallet_name) } pub async fn create_wallet( dio: &Arc<DioMut>, auth: &url::Url, registry: &Arc<Registry>, identity: &String, wallet_name: &String, parent_key: &PrimaryKey, gst_country: Country, ) -> std::result::Result<DaoMut<Wallet>, AteError> { // Get the sudo rights from the session (as we will use these for the wallet) let session = dio.session(); let sudo_read = { let sudo_read = match session.read_keys(AteSessionKeyCategory::SudoKeys).next() { Some(a) => a, None => { eprintln!("Login sudo rights do not have a read key."); std::process::exit(1); } }; if session .write_keys(AteSessionKeyCategory::SudoKeys) .next() .is_none() { eprintln!("Login sudo rights do not have a write key."); std::process::exit(1); }; sudo_read }; // Generate the broker key let broker_unlock_key = EncryptKey::generate(sudo_read.size()); let broker_key = EncryptKey::xor(sudo_read, &broker_unlock_key); // If it already exists then fail let wallet_key_entropy = format!("wallet://{}/{}", identity, wallet_name); let wallet_key = PrimaryKey::from(wallet_key_entropy); if dio.exists(&wallet_key).await { eprintln!("Wallet ({}) already exists (with same key).", wallet_name); std::process::exit(1); } // Create the new wallet let mut wallet = dio.store_with_key( Wallet { name: wallet_name.clone(), inbox: DaoVec::default(), bags: DaoMap::default(), history: DaoVec::default(), gst_country, broker_key, broker_unlock_key, }, wallet_key, )?; // Set its permissions and attach it to the parent wallet.auth_mut().read = ReadOption::from_key(sudo_read); wallet.auth_mut().write = WriteOption::Inherit; wallet.attach_orphaned_ext(&parent_key, WALLET_COLLECTION_ID)?; // Now add the history let wallet = { let mut api = crate::api::build_api_accessor(&dio, wallet, auth.clone(), None, registry).await; if let Err(err) = api .record_activity(HistoricActivity::WalletCreated(activities::WalletCreated { when: chrono::offset::Utc::now(), by: api.user_identity(), })) .await { error!("Error writing activity: {}", err); } api.wallet }; Ok(wallet) } pub async fn get_wallet<A>( purpose: &dyn OptsPurpose<A>, dio: &Arc<DioMut>, identity: &String, ) -> std::result::Result<DaoMut<Wallet>, AteError> where A: Clone, { // Make sure the parent exists let parent_key = PrimaryKey::from(identity.clone()); debug!("parent_key={}", parent_key); if dio.exists(&parent_key).await == false { eprintln!("The parent user or group does not exist in the chain-or-trust."); std::process::exit(1); } // Grab a reference to the wallet let wallet_name = get_wallet_name(purpose)?; let mut wallet_vec = DaoVec::<Wallet>::new_orphaned_mut(dio, parent_key, WALLET_COLLECTION_ID); let wallet = wallet_vec .iter_mut() .await? .into_iter() .filter(|a| a.name.eq_ignore_ascii_case(wallet_name.as_str())) .next(); let wallet = match wallet { Some(a) => a, None => { eprintln!( "Wallet ({}) does not exist - you must first 'create' the wallet before using it.", wallet_name ); std::process::exit(1); } }; Ok(wallet) } pub(crate) struct PurposeContextPrelude<A> where A: Clone, { pub action: A, #[allow(dead_code)] pub session: AteSessionType, pub identity: String, pub registry: Arc<Registry>, #[allow(dead_code)] pub chain_key: ChainKey, #[allow(dead_code)] pub chain: ChainGuard, pub dio: Arc<DioMut>, } pub(crate) struct PurposeContext<A> where A: Clone, { pub inner: PurposeContextPrelude<A>, pub api: DeployApi, } impl<A> Deref for PurposeContext<A> where A: Clone, { type Target = PurposeContextPrelude<A>; fn deref(&self) -> &Self::Target { &self.inner } } impl<A> DerefMut for PurposeContext<A> where A: Clone, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } impl<A> PurposeContextPrelude<A> where A: Clone, { pub async fn new( purpose: &dyn OptsPurpose<A>, token_path: &str, auth_url: &url::Url, sudo: bool, ) -> Result<PurposeContextPrelude<A>, CoreError> { // Build a session with all the needed permissions let (action, session) = session_with_permissions(purpose, token_path, auth_url, sudo).await?; // Compute the identity of the requesting user or group let identity = get_identity(purpose, &session).await?; // Open the chain let registry = ate::mesh::Registry::new(&wasmer_auth::helper::conf_auth()) .await .keep_alive(Duration::from_secs(10)) .cement(); let chain_key = chain_key_4hex(&identity, Some("redo")); debug!("chain_url={}", auth_url); debug!("chain_key={}", chain_key); let chain = registry.open(&auth_url, &chain_key, true).await?; // Open the DIO let dio = chain.dio_trans(&session, TransactionScope::Full).await; Ok(PurposeContextPrelude { action, session, identity, registry, chain_key, chain, dio, }) } } impl<A> PurposeContext<A> where A: Clone, { pub async fn new( purpose: &dyn OptsPurpose<A>, token_path: &str, auth_url: &url::Url, db_url: Option<&url::Url>, sudo: bool, ) -> Result<PurposeContext<A>, CoreError> { let inner = PurposeContextPrelude::new(purpose, token_path, auth_url, sudo).await?; // Create the API to the wallet let wallet = get_wallet(purpose, &inner.dio, &inner.identity).await?; let api = build_api_accessor(&inner.dio, wallet, auth_url.clone(), db_url.map(|a| a.clone()), &inner.registry).await; Ok(PurposeContext { inner, api }) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/coin_carve.rs
wasmer-deploy-cli/src/cmd/coin_carve.rs
use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use url::Url; use ate::prelude::*; use crate::error::*; use crate::model::*; use crate::request::*; pub async fn coin_carve_command( registry: &Arc<Registry>, owner: Ownership, coin: PrimaryKey, needed_denomination: Decimal, new_token: EncryptKey, auth: Url, ) -> Result<CoinCarveResponse, CoinError> { // Open a command chain let chain = registry.open_cmd(&auth).await?; // Create the login command let query = CoinCarveRequest { owner, coin, needed_denomination, new_token, }; // Attempt the login request with a 10 second timeout let response: Result<CoinCarveResponse, CoinCarveFailed> = chain.invoke(query).await?; let result = response?; Ok(result) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/coin_rotate.rs
wasmer-deploy-cli/src/cmd/coin_rotate.rs
use error_chain::*; use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use url::Url; use ate::prelude::*; use crate::error::*; use crate::model::*; use crate::request::*; pub fn coin_rotate_request( coins: Vec<CarvedCoin>, new_token: EncryptKey, session: &'_ dyn AteSession, notify: Option<CoinRotateNotification>, ) -> Result<CoinRotateRequest, CoinError> { // The signature key needs to be present to send the notification let notify_sign_key = match session .write_keys(AteSessionKeyCategory::NonGroupKeys) .next() { Some(a) => a.clone(), None => { bail!(CoinErrorKind::CoreError(CoreErrorKind::MissingTokenKey)); } }; // Create the login command let notification = match notify { Some(notify) => Some(SignedProtectedData::new(&notify_sign_key, notify)?), None => None, }; let query = CoinRotateRequest { coins, new_token, notification, }; Ok(query) } #[allow(dead_code)] pub async fn coin_rotate_command( registry: &Arc<Registry>, coins: Vec<CarvedCoin>, new_token: EncryptKey, session: &'_ dyn AteSession, auth: Url, notify: Option<CoinRotateNotification>, ) -> Result<CoinRotateResponse, CoinError> { let chain = registry.open_cmd(&auth).await?; let query = coin_rotate_request(coins, new_token, session, notify)?; // Attempt the login request with a 10 second timeout let response: Result<CoinRotateResponse, CoinRotateFailed> = chain.invoke(query).await?; let result = response?; Ok(result) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/contract_list.rs
wasmer-deploy-cli/src/cmd/contract_list.rs
#[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::api::*; use crate::error::*; pub async fn main_opts_contract_list(api: &mut DeployApi) -> Result<(), ContractError> { let result = api.contract_summary().await?; println!("|-----code-----|-------------reference------------|---status---"); for contract in result { println!( "- {:12} - {:16} - {}", contract.service.code, contract.reference_number, contract.status ); } Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/contract_action.rs
wasmer-deploy-cli/src/cmd/contract_action.rs
use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use url::Url; use ate::prelude::*; use crate::error::*; use crate::helper::*; use crate::request::*; pub async fn contract_action_command( registry: &Arc<Registry>, session: &dyn AteSession, auth: Url, service_code: String, requester_identity: String, consumer_identity: String, action_key: Option<EncryptKey>, action: ContractAction, ) -> Result<ContractActionResponse, ContractError> { // Open a command chain let chain = registry.open_cmd(&auth).await?; // Now build the request to perform an action on the contract let sign_key = session_sign_key(session, requester_identity.contains("@"))?; let contract_action = ContractActionRequest { requester_identity, action_key, params: SignedProtectedData::new( sign_key, ContractActionRequestParams { service_code, consumer_identity, action, }, )?, }; // Attempt the create contract request let response: Result<ContractActionResponse, ContractActionFailed> = chain.invoke(contract_action).await?; let result = response?; Ok(result) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/service.rs
wasmer-deploy-cli/src/cmd/service.rs
use wasmer_auth::helper::*; use error_chain::bail; use std::time::Duration; #[allow(unused_imports)] use tracing::{debug, error, info}; use crate::api::*; use crate::error::*; use crate::opt::*; use super::*; pub async fn main_opts_service_list(auth_url: &url::Url) -> Result<(), CoreError> { println!("|-----code-----|---provider---|---name---"); let registry = ate::mesh::Registry::new(&conf_cmd()) .await .keep_alive(Duration::from_secs(10)) .cement(); let services = service_find_command(&registry, None, auth_url.clone()).await?; for service in services.services { println!( "- {:12} - {:12} - {}", service.code, service.owner_identity, service.name ); } Ok(()) } pub async fn main_opts_service_details( opts: OptsServiceDetails, auth_url: &url::Url, ) -> Result<(), CoreError> { let registry = ate::mesh::Registry::new(&conf_cmd()) .await .keep_alive(Duration::from_secs(10)) .cement(); let services = service_find_command(&registry, None, auth_url.clone()).await?; let service_name = opts.service_name.to_lowercase(); let service = match get_advertised_service(&services, &service_name)? { Some(a) => a, None => { eprintln!("The named service does not exist."); std::process::exit(1); } }; println!("{}", service.description); for rate_card in service.rate_cards.iter() { println!("=================="); println!("{}", serde_json::to_string_pretty(rate_card).unwrap()); } Ok(()) } pub async fn main_opts_service_subscribe( opts: OptsSubscribe, api: &mut DeployApi, ) -> Result<(), ContractError> { let services = service_find_command(&api.registry, None, api.auth.clone()).await?; let service_name = opts.service_name.to_lowercase(); let service = match get_advertised_service(&services, &service_name)? { Some(a) => a, None => { eprintln!("The named service does not exist."); std::process::exit(1); } }; // Find the rate card that matches this particular countries currency let rate_card = service .rate_cards .iter() .filter(|a| a.currency == api.wallet.gst_country.national_currency()) .map(|a| a.clone()) .next(); let rate_card = match rate_card { Some(a) => a, None => { eprintln!( "Unfortunately your national currency ({}) is not supported by this.", api.wallet.gst_country.national_currency() ); std::process::exit(1); } }; // We need an agreement to the terms and conditions from the caller println!("{}", service.terms_and_conditions); println!("=================="); println!("{}", service.description); println!("=================="); println!("{}", serde_json::to_string_pretty(&rate_card).unwrap()); println!("=================="); println!( "Please agree to contract and its terms and conditions above by typing the word 'agree'" ); let mut s = String::new(); std::io::stdin() .read_line(&mut s) .expect("Did not enter a valid response"); let agreement = s.trim().to_string().to_lowercase(); if agreement != "agree" { eprintln!("You may only create an contracts by specifically agreeing to the terms"); eprintln!("which can only be confirmed if you specifically type the word 'agree'"); std::process::exit(1); } let ret = match api.contract_create(service.clone(), opts.force).await { Ok(a) => a, Err(ContractError(ContractErrorKind::AlreadyExists(msg), _)) => { eprintln!("{}", msg); std::process::exit(1); } Err(err) => { bail!(err); } }; println!("Contract created ({})", ret.contract_reference); Ok(()) } pub async fn main_opts_service( opts: OptsServiceFor, token_path: String, auth_url: url::Url, ) -> Result<(), ContractError> { // Determine what we need to do let purpose: &dyn OptsPurpose<OptsServiceAction> = &opts; match purpose.action() { OptsServiceAction::List => { main_opts_service_list(&auth_url).await?; } OptsServiceAction::Details(opts) => { main_opts_service_details(opts, &auth_url).await?; } OptsServiceAction::Subscribe(opts) => { let mut context = PurposeContext::new(purpose, token_path.as_str(), &auth_url, None, true).await?; main_opts_service_subscribe(opts, &mut context.api).await?; context.api.commit().await?; } } Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/contract_create.rs
wasmer-deploy-cli/src/cmd/contract_create.rs
use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use url::Url; use ate::prelude::*; use crate::error::*; use crate::helper::*; use crate::model::*; use crate::request::*; pub async fn contract_create_command( registry: &Arc<Registry>, session: &dyn AteSession, auth: Url, service_code: String, identity: String, gst_country: Country, consumer_wallet: PrimaryKey, broker_key: PublicEncryptedSecureData<EncryptKey>, broker_unlock_key: EncryptKey, force: bool ) -> Result<ContractCreateResponse, ContractError> { // Open a command chain let chain = registry.open_cmd(&auth).await?; // Now build the request to create the contract let sign_key = session_sign_key(session, identity.contains("@"))?; let contract_create = ContractCreateRequest { consumer_identity: identity, params: SignedProtectedData::new( sign_key, ContractCreateRequestParams { service_code, gst_country, consumer_wallet, broker_unlock_key, broker_key, force, limited_duration: None, }, )?, }; // Attempt the create contract request let response: Result<ContractCreateResponse, ContractCreateFailed> = chain.invoke(contract_create).await?; let result = response?; Ok(result) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/coin_collect.rs
wasmer-deploy-cli/src/cmd/coin_collect.rs
use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use url::Url; use ate::prelude::*; use crate::error::*; use crate::model::*; use crate::request::*; pub async fn coin_collect_command( registry: &Arc<Registry>, coin_ancestors: Vec<Ownership>, auth: Url, ) -> Result<CoinCollectResponse, CoinError> { // Open a command chain let chain = registry.open_cmd(&auth).await?; // Create the login command let query = CoinCollectRequest { coin_ancestors }; // Attempt the login request with a 10 second timeout let response: Result<CoinCollectResponse, CoinCollectFailed> = chain.invoke(query).await?; let result = response?; Ok(result) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/history.rs
wasmer-deploy-cli/src/cmd/history.rs
use chrono::Datelike; use crate::api::*; use crate::cmd::*; use crate::error::*; use crate::opt::*; #[allow(unreachable_code)] pub async fn main_opts_transaction_history( opts: OptsTransactionHistory, api: &mut DeployApi, ) -> Result<(), WalletError> { // We first get the wallet summary and output it if opts.balance { main_opts_balance( OptsBalance { coins: false, no_reconcile: opts.no_reconcile, }, api, ) .await?; } // Loop through all the history and display it let mut cur_year = 0i32; let mut cur_month = 0u32; let mut cur_day = 0u32; for event in api.read_activity(opts.year, opts.month, opts.day).await? { if cur_year != event.when().year() || cur_month != event.when().month() || cur_day != event.when().day() { cur_year = event.when().year(); cur_month = event.when().month(); cur_day = event.when().day(); println!(""); println!("[{}]", event.when().date()); } match event.financial() { Some(a) => { let mut amount = a.amount; amount.rescale(a.currency.decimal_points() as u32); println!("{:11} {:3}: {}", amount, a.currency, event.summary()); } None => { println!(" ...: {}", event.summary()); } } if opts.details { match event.details() { Ok(a) => println!("{}", a), Err(err) => println!("details error - {}", err), }; } } Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/cidr.rs
wasmer-deploy-cli/src/cmd/cidr.rs
use ate::prelude::*; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use crate::error::*; use crate::model::{ServiceInstance, IpCidr}; use crate::opt::*; pub async fn main_opts_cidr_list( instance: DaoMut<ServiceInstance>, ) -> Result<(), InstanceError> { println!("|-------cidr-------|"); for cidr in instance.subnet.cidrs.iter() { println!("{}/{}", cidr.ip, cidr.prefix); } Ok(()) } pub async fn main_opts_cidr_add( mut instance: DaoMut<ServiceInstance>, opts: OptsCidrAdd ) -> Result<(), InstanceError> { let dio = instance.dio_mut(); { let mut instance = instance.as_mut(); instance.subnet.cidrs.push( IpCidr { ip: opts.ip, prefix: opts.prefix, } ) } dio.commit().await?; Ok(()) } pub async fn main_opts_cidr_remove( mut instance: DaoMut<ServiceInstance>, opts: OptsCidrRemove ) -> Result<(), InstanceError> { let dio = instance.dio_mut(); { let mut instance = instance.as_mut(); instance.subnet.cidrs.retain(|cidr| cidr.ip != opts.ip); } dio.commit().await?; Ok(()) } pub async fn main_opts_cidr( instance: DaoMut<ServiceInstance>, action: OptsCidrAction, ) -> Result<(), InstanceError> { // Determine what we need to do match action { OptsCidrAction::List => { main_opts_cidr_list(instance).await?; } OptsCidrAction::Add(add) => { main_opts_cidr_add(instance, add).await?; } OptsCidrAction::Remove(remove) => { main_opts_cidr_remove(instance, remove).await?; } } Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false