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 |
|---|---|---|---|---|---|---|---|---|
facebookarchive/propfuzz | https://github.com/facebookarchive/propfuzz/blob/742567d73088988fc24f065a0aba3e88adb049f4/propfuzz/tests/compile-fail/non-top-level.rs | propfuzz/tests/compile-fail/non-top-level.rs | // Copyright (c) The propfuzz Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Propfuzz is not supported for methods, only for top-level functions.
use propfuzz::propfuzz;
struct Foo;
impl Foo {
/// Method.
#[propfuzz]
fn fuzz(&self, _: Vec<u8>) {}
/// Method 2.
#[propfuzz]
fn fuzz_mut(&mut self, _: Vec<u8>) {}
/// Method 3.
#[propfuzz]
fn fuzz_consume(self, _: Vec<u8>) {}
/// Don't know how to detect this one, but it fails.
#[propfuzz]
fn fuzz_static(_: Vec<u8>) {}
}
fn main() {}
| rust | Apache-2.0 | 742567d73088988fc24f065a0aba3e88adb049f4 | 2026-01-04T20:18:50.820316Z | false |
facebookarchive/propfuzz | https://github.com/facebookarchive/propfuzz/blob/742567d73088988fc24f065a0aba3e88adb049f4/propfuzz/tests/compile-fail/no-args.rs | propfuzz/tests/compile-fail/no-args.rs | // Copyright (c) The propfuzz Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
//! A propfuzz with no arguments.
use propfuzz::propfuzz;
/// Failing propfuzz.
#[propfuzz]
fn no_args() {}
fn main() {}
| rust | Apache-2.0 | 742567d73088988fc24f065a0aba3e88adb049f4 | 2026-01-04T20:18:50.820316Z | false |
facebookarchive/propfuzz | https://github.com/facebookarchive/propfuzz/blob/742567d73088988fc24f065a0aba3e88adb049f4/propfuzz-macro/src/config.rs | propfuzz-macro/src/config.rs | // Copyright (c) The propfuzz Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Configuration for propfuzz macros.
use crate::errors::{Error, ErrorList, Result};
use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::punctuated::Punctuated;
use syn::{spanned::Spanned, Attribute, Expr, Lit, Meta, MetaNameValue, NestedMeta, Token, Type};
// ---
// Config builders
// ---
pub(crate) trait ConfigBuilder {
fn apply_meta(&mut self, meta: &Meta, errors: &mut ErrorList);
/// Applies the given #[propfuzz] attributes.
fn apply_attrs<'a>(
&mut self,
attrs: impl IntoIterator<Item = &'a Attribute>,
errors: &mut ErrorList,
) {
for attr in attrs {
if let Some(args) = errors.combine_opt(|| {
attr.parse_args_with(Punctuated::<NestedMeta, Token![,]>::parse_terminated)
}) {
self.apply_args(&args, errors);
}
}
}
/// Applies the given arguments.
fn apply_args<'a>(
&mut self,
args: impl IntoIterator<Item = &'a NestedMeta>,
errors: &mut ErrorList,
) {
for arg in args {
self.apply_arg(arg, errors)
}
}
/// Applies a single argument.
fn apply_arg(&mut self, arg: &NestedMeta, errors: &mut ErrorList) {
match arg {
NestedMeta::Meta(meta) => {
self.apply_meta(meta, errors);
}
NestedMeta::Lit(meta) => {
errors.combine(Error::new_spanned(meta, "expected key = value format"));
}
}
}
}
// ---
// Config for a function
// ---
/// Configuration for a propfuzz target.
#[derive(Debug, Default)]
pub(crate) struct PropfuzzConfigBuilder {
fuzz_default: Option<bool>,
proptest: ProptestConfig,
}
impl PropfuzzConfigBuilder {
/// Completes building args and returns a `PropfuzzConfig`.
pub(crate) fn finish(self) -> PropfuzzConfig {
PropfuzzConfig {
fuzz_default: self.fuzz_default.unwrap_or(false),
proptest: self.proptest,
}
}
}
impl ConfigBuilder for PropfuzzConfigBuilder {
fn apply_meta(&mut self, meta: &Meta, errors: &mut ErrorList) {
let path = meta.path();
if path.is_ident("fuzz_default") {
errors.combine_fn(|| {
replace_empty(meta.span(), &mut self.fuzz_default, read_bool(meta)?)
});
} else if path.is_ident("cases") {
errors.combine_fn(|| {
replace_empty(meta.span(), &mut self.proptest.cases, read_u32(meta)?)
});
} else if path.is_ident("max_local_rejects") {
errors.combine_fn(|| {
replace_empty(
meta.span(),
&mut self.proptest.max_local_rejects,
read_u32(meta)?,
)
});
} else if path.is_ident("max_global_rejects") {
errors.combine_fn(|| {
replace_empty(
meta.span(),
&mut self.proptest.max_global_rejects,
read_u32(meta)?,
)
});
} else if path.is_ident("max_flat_map_regens") {
errors.combine_fn(|| {
replace_empty(
meta.span(),
&mut self.proptest.max_flat_map_regens,
read_u32(meta)?,
)
});
} else if path.is_ident("fork") {
errors.combine_fn(|| {
replace_empty(meta.span(), &mut self.proptest.fork, read_bool(meta)?)
});
} else if path.is_ident("timeout") {
errors.combine_fn(|| {
replace_empty(meta.span(), &mut self.proptest.timeout, read_u32(meta)?)
});
} else if path.is_ident("max_shrink_time") {
errors.combine_fn(|| {
replace_empty(
meta.span(),
&mut self.proptest.max_shrink_time,
read_u32(meta)?,
)
});
} else if path.is_ident("max_shrink_iters") {
errors.combine_fn(|| {
replace_empty(
meta.span(),
&mut self.proptest.max_shrink_iters,
read_u32(meta)?,
)
});
} else if path.is_ident("verbose") {
errors.combine_fn(|| {
replace_empty(meta.span(), &mut self.proptest.verbose, read_u32(meta)?)
});
} else {
errors.combine(Error::new_spanned(path, "argument not recognized"));
}
}
}
/// Overall config for a single propfuzz function, fully built.
#[derive(Debug)]
pub(crate) struct PropfuzzConfig {
// fuzz_default is currently unused.
fuzz_default: bool,
pub(crate) proptest: ProptestConfig,
}
/// Proptest config for a single propfuzz function.
///
/// This contains most of the settings in proptest's config.
#[derive(Debug, Default)]
pub(crate) struct ProptestConfig {
cases: Option<u32>,
max_local_rejects: Option<u32>,
max_global_rejects: Option<u32>,
max_flat_map_regens: Option<u32>,
fork: Option<bool>,
timeout: Option<u32>,
max_shrink_time: Option<u32>,
max_shrink_iters: Option<u32>,
verbose: Option<u32>,
}
macro_rules! extend_config {
($tokens:ident, $var:ident) => {
if let Some($var) = $var {
$tokens.extend(quote! {
config.$var = #$var;
})
}
};
}
/// Generates a ProptestConfig for this function.
impl ToTokens for ProptestConfig {
fn to_tokens(&self, tokens: &mut TokenStream) {
let Self {
cases,
max_local_rejects,
max_global_rejects,
max_flat_map_regens,
fork,
timeout,
max_shrink_time,
max_shrink_iters,
verbose,
} = self;
tokens.extend(quote! {
let mut config = ::propfuzz::proptest::test_runner::Config::default();
config.source_file = Some(file!());
});
extend_config!(tokens, cases);
extend_config!(tokens, max_local_rejects);
extend_config!(tokens, max_global_rejects);
extend_config!(tokens, max_flat_map_regens);
extend_config!(tokens, fork);
extend_config!(tokens, timeout);
extend_config!(tokens, max_shrink_time);
extend_config!(tokens, max_shrink_iters);
extend_config!(tokens, verbose);
tokens.extend(quote! { config })
}
}
// ---
// Configuration for arguments
// ---
pub(crate) struct ParamConfigBuilder<'a> {
ty: &'a Type,
strategy: Option<Expr>,
}
impl<'a> ParamConfigBuilder<'a> {
pub(crate) fn new(ty: &'a Type) -> Self {
Self { ty, strategy: None }
}
pub(crate) fn finish(self) -> ParamConfig {
let ty = self.ty;
let strategy = match self.strategy {
Some(expr) => quote! { #expr },
None => quote! { ::propfuzz::proptest::arbitrary::any::<#ty>() },
};
ParamConfig { strategy }
}
}
impl<'a> ConfigBuilder for ParamConfigBuilder<'a> {
fn apply_meta(&mut self, meta: &Meta, errors: &mut ErrorList) {
let path = meta.path();
if path.is_ident("strategy") {
errors.combine_fn(|| replace_empty(meta.span(), &mut self.strategy, read_expr(meta)?));
} else {
errors.combine(Error::new_spanned(path, "argument not recognized"));
}
}
}
#[derive(Debug)]
pub(crate) struct ParamConfig {
strategy: TokenStream,
}
impl ParamConfig {
pub(crate) fn strategy(&self) -> &TokenStream {
&self.strategy
}
}
// ---
// Helper functions
// ---
fn read_bool(meta: &Meta) -> Result<bool> {
let name_value = name_value(meta)?;
match &name_value.lit {
Lit::Bool(lit) => Ok(lit.value),
_ => Err(Error::new_spanned(&name_value.lit, "expected bool")),
}
}
fn read_u32(meta: &Meta) -> Result<u32> {
let name_value = name_value(meta)?;
match &name_value.lit {
Lit::Int(lit) => Ok(lit.base10_parse::<u32>()?),
_ => Err(Error::new_spanned(&name_value.lit, "expected integer")),
}
}
fn read_expr(meta: &Meta) -> Result<Expr> {
let name_value = name_value(meta)?;
match &name_value.lit {
Lit::Str(lit) => Ok(lit.parse::<Expr>()?),
_ => Err(Error::new_spanned(
&name_value.lit,
"expected expression string",
)),
}
}
fn name_value(meta: &Meta) -> Result<&MetaNameValue> {
match meta {
Meta::NameValue(meta) => Ok(meta),
_ => Err(Error::new_spanned(meta, "expected key = value format")),
}
}
fn replace_empty<T>(span: Span, dest: &mut Option<T>, val: T) -> Result<()> {
if dest.replace(val).is_some() {
Err(Error::new(span, "key specified more than once"))
} else {
Ok(())
}
}
| rust | Apache-2.0 | 742567d73088988fc24f065a0aba3e88adb049f4 | 2026-01-04T20:18:50.820316Z | false |
facebookarchive/propfuzz | https://github.com/facebookarchive/propfuzz/blob/742567d73088988fc24f065a0aba3e88adb049f4/propfuzz-macro/src/errors.rs | propfuzz-macro/src/errors.rs | // Copyright (c) The propfuzz Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
use std::mem;
pub use syn::Error;
/// The `Result` type.
pub type Result<T, E = Error> = ::std::result::Result<T, E>;
#[derive(Debug)]
pub(crate) enum ErrorList {
None,
Some(Error),
}
impl ErrorList {
pub(crate) fn new() -> Self {
ErrorList::None
}
/// Combine this error with the existing list of errors.
pub(crate) fn combine(&mut self, error: Error) {
match self {
ErrorList::None => {
let _ = mem::replace(self, ErrorList::Some(error));
}
ErrorList::Some(original) => original.combine(error),
}
}
/// Combine this error and return the consolidated list of errors, consuming `self`.
pub(crate) fn combine_finish(self, error: Error) -> Error {
match self {
ErrorList::None => error,
ErrorList::Some(mut original) => {
original.combine(error);
original
}
}
}
pub(crate) fn combine_fn<F>(&mut self, f: F)
where
F: FnOnce() -> Result<()>,
{
if let Err(error) = f() {
self.combine(error);
}
}
pub(crate) fn combine_opt<F, T>(&mut self, f: F) -> Option<T>
where
F: FnOnce() -> Result<T>,
{
match f() {
Ok(val) => Some(val),
Err(error) => {
self.combine(error);
None
}
}
}
pub(crate) fn finish(self) -> Result<()> {
match self {
ErrorList::None => Ok(()),
ErrorList::Some(error) => Err(error),
}
}
}
| rust | Apache-2.0 | 742567d73088988fc24f065a0aba3e88adb049f4 | 2026-01-04T20:18:50.820316Z | false |
facebookarchive/propfuzz | https://github.com/facebookarchive/propfuzz/blob/742567d73088988fc24f065a0aba3e88adb049f4/propfuzz-macro/src/lib.rs | propfuzz-macro/src/lib.rs | // Copyright (c) The propfuzz Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Procedural macros for propfuzz tests.
//!
//! This crate is an implementation detail of `propfuzz` and is **not** meant to be used directly.
//! Use it through [`propfuzz`](https://crates.io/crates/propfuzz) instead.
extern crate proc_macro;
use proc_macro::TokenStream;
use syn::{parse_macro_input, AttributeArgs, ItemFn};
mod config;
mod errors;
mod propfuzz_impl;
/// The core macro, used to annotate test methods.
///
/// Annotate a function with this in order to have it run as a property-based test using the
/// [`proptest`](https://docs.rs/proptest) framework. In the future, such tests will also be
/// available as fuzz targets.
///
/// # Examples
///
/// ```
/// // The prelude imports the `propfuzz` macro.
///
/// use propfuzz::prelude::*;
/// use proptest::collection::vec;
///
/// /// Reversing a list twice produces the same result.
/// #[propfuzz]
/// fn reverse(
/// #[propfuzz(strategy = "vec(any::<u32>(), 0..64)")]
/// mut list: Vec<u32>,
/// ) {
/// let list2 = list.clone();
/// list.reverse();
/// list.reverse();
/// prop_assert_eq!(list, list2);
/// }
/// ```
///
/// # Arguments
///
/// `propfuzz` supports a number of arguments which can be used to customize test behavior.
///
/// Attributes can be broken up with commas and split up across multiple lines like so:
///
/// ```
/// use propfuzz::prelude::*;
/// use proptest::collection::vec;
///
/// /// Options broken up across multiple lines.
/// #[propfuzz(cases = 1024, max_local_rejects = 10000)]
/// #[propfuzz(fork = true)]
/// fn reverse(
/// #[propfuzz(strategy = "vec(any::<u32>(), 0..64)")]
/// mut list: Vec<u32>,
/// ) {
/// let list2 = list.clone();
/// list.reverse();
/// list.reverse();
/// prop_assert_eq!(list, list2);
/// }
/// ```
///
/// ## Fuzzing configuration
///
/// These arguments are currently unused but may be set. They will be used in the future once fuzzing support is
/// available.
///
/// * `fuzz_default`: whether to fuzz this target by default. Defaults to `false`.
///
/// ## Proptest configuration
///
/// The following `proptest`
/// [configuration options](https://docs.rs/proptest/0.10/proptest/test_runner/struct.Config.html)
/// are supported:
///
/// * `cases`
/// * `max_local_rejects`
/// * `max_global_rejects`
/// * `max_flat_map_regens`
/// * `fork`
/// * `timeout`
/// * `max_shrink_time`
/// * `max_shrink_iters`
/// * `verbose`
///
/// ## Argument configuration
///
/// The following configuration options are supported on individual arguments:
///
/// * `strategy`: A strategy to generate and shrink values of the given type. The value must be a
/// string that parses as a Rust expression which evaluates to an implementation of
/// [`Strategy`](https://docs.rs/proptest/0.10/proptest/strategy/trait.Strategy.html)
/// for the given type. Defaults to [the
/// canonical strategy](https://docs.rs/proptest/0.10/proptest/arbitrary/trait.Arbitrary.html)
/// for the type.
#[proc_macro_attribute]
pub fn propfuzz(attr: TokenStream, item: TokenStream) -> TokenStream {
let attr = parse_macro_input!(attr as AttributeArgs);
let item = parse_macro_input!(item as ItemFn);
propfuzz_impl::propfuzz_impl(attr, item)
.unwrap_or_else(|err| err)
.into()
}
| rust | Apache-2.0 | 742567d73088988fc24f065a0aba3e88adb049f4 | 2026-01-04T20:18:50.820316Z | false |
facebookarchive/propfuzz | https://github.com/facebookarchive/propfuzz/blob/742567d73088988fc24f065a0aba3e88adb049f4/propfuzz-macro/src/propfuzz_impl.rs | propfuzz-macro/src/propfuzz_impl.rs | // Copyright (c) The propfuzz Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
use crate::config::{
ConfigBuilder, ParamConfig, ParamConfigBuilder, PropfuzzConfig, PropfuzzConfigBuilder,
};
use crate::errors::*;
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote, ToTokens};
use syn::{
Attribute, AttributeArgs, Block, FnArg, Index, ItemFn, Lit, Meta, NestedMeta, Pat, PatType,
Signature, Type,
};
pub(crate) fn propfuzz_impl(attr: AttributeArgs, item: ItemFn) -> Result<TokenStream, TokenStream> {
let propfuzz_fn = match PropfuzzFn::new(&attr, &item) {
Ok(propfuzz_fn) => propfuzz_fn,
Err(err) => return Err(err.to_compile_error()),
};
Ok(propfuzz_fn.into_token_stream())
}
/// Processor for a propfuzz function.
#[derive(Debug)]
struct PropfuzzFn<'a> {
name: &'a Ident,
description: Option<String>,
other_attrs: Vec<&'a Attribute>,
config: PropfuzzConfig,
struct_name: Ident,
body: PropfuzzFnBody<'a>,
}
impl<'a> PropfuzzFn<'a> {
const STRUCT_PREFIX: &'static str = "__PROPFUZZ__";
/// Creates a new instance of `PropfuzzFn`.
fn new(attr: &'a [NestedMeta], item: &'a ItemFn) -> Result<Self> {
let mut errors = ErrorList::new();
let mut config_builder = PropfuzzConfigBuilder::default();
// Apply the arguments from the first #[propfuzz] invocation.
config_builder.apply_args(attr, &mut errors);
let name = &item.sig.ident;
// Read the description from the doc comment.
let description = {
let description = item
.attrs
.iter()
.filter_map(|attr| {
if attr.path.is_ident("doc") {
Some(extract_doc_comment(attr))
} else {
None
}
})
.collect::<Result<Vec<_>>>()?;
if description.is_empty() {
None
} else {
Some(description.join("\n"))
}
};
// Read arguments from remaining #[propfuzz] attributes.
let (propfuzz_attrs, other_attrs) = item
.attrs
.iter()
.partition::<Vec<_>, _>(|attr| attr.path.is_ident("propfuzz"));
config_builder.apply_attrs(propfuzz_attrs, &mut errors);
let body = match PropfuzzFnBody::new(&item.sig, &item.block) {
Ok(body) => body,
Err(error) => return Err(errors.combine_finish(error)),
};
let struct_name = format_ident!("{}{}", Self::STRUCT_PREFIX, name);
// If any errors were collected, return them.
errors.finish()?;
Ok(Self {
name: &item.sig.ident,
description,
other_attrs,
config: config_builder.finish(),
struct_name,
body,
})
}
}
impl<'a> ToTokens for PropfuzzFn<'a> {
fn to_tokens(&self, tokens: &mut TokenStream) {
let Self {
name,
description,
other_attrs,
config,
struct_name,
body,
..
} = self;
// The ToTokens impl for Option isn't quite what we want, so do this by hand.
let description = match description {
Some(s) => quote! { Some(#s) },
None => quote! { None },
};
let proptest_config = &config.proptest;
let types = body.types();
let name_pats = body.name_pats();
// Use indexes as tuple accessors in fmt_value.
// Note that we can't destructure values because name_pats may contain modifiers like mut.
// TODO: modifiers like mut can be filtered out -- consider doing so for a nicer display.
let indexes = (0..body.num_params()).map(Index::from);
tokens.extend(quote! {
#[test]
#(#other_attrs )*
fn #name() {
::propfuzz::runtime::execute_as_proptest(#struct_name);
}
#[derive(Copy, Clone, Debug)]
#[allow(non_camel_case_types)]
struct #struct_name;
impl ::propfuzz::traits::StructuredTarget for #struct_name {
type Value = (#(#types,)*);
fn name(&self) -> &'static str {
concat!(module_path!(), "::", stringify!(#name))
}
fn description(&self) -> Option<&'static str> {
#description
}
fn proptest_config(&self) -> ::propfuzz::proptest::test_runner::Config {
#proptest_config
}
fn execute(&self, __propfuzz_test_runner: &mut ::propfuzz::proptest::test_runner::TestRunner)
-> ::std::result::Result<(), ::propfuzz::proptest::test_runner::TestError<Self::Value>> {
#body
}
fn fmt_value(&self, value: &Self::Value, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
#(writeln!(f, "{} = {:?}", stringify!(#name_pats), value.#indexes)?;)*
Ok(())
}
}
});
}
}
fn extract_doc_comment(attr: &Attribute) -> Result<String> {
match attr.parse_meta()? {
Meta::NameValue(name_value) => match name_value.lit {
Lit::Str(lit) => Ok(lit.value().trim().to_string()),
_ => Err(Error::new_spanned(attr, "expected #[doc = r\"string\"]")),
},
_ => Err(Error::new_spanned(attr, "expected #[doc = r\"string\"]")),
}
}
/// The body of a proptest function.
#[derive(Debug)]
struct PropfuzzFnBody<'a> {
params: Vec<PropfuzzParam<'a>>,
block: &'a Block,
}
impl<'a> PropfuzzFnBody<'a> {
fn new(sig: &'a Signature, block: &'a Block) -> Result<Self> {
if sig.inputs.is_empty() {
return Err(Error::new_spanned(
sig,
"#[propfuzz] requires at least one argument",
));
}
let mut errors = ErrorList::new();
let params = sig
.inputs
.iter()
.filter_map(|param| match param {
FnArg::Receiver(receiver) => {
errors.combine(Error::new_spanned(
receiver,
"#[propfuzz] is only supported on top-level functions",
));
None
}
FnArg::Typed(param) => errors.combine_opt(|| PropfuzzParam::new(param)),
})
.collect::<Vec<_>>();
// If there are any errors, return them.
errors.finish()?;
Ok(Self { params, block })
}
fn num_params(&self) -> usize {
self.params.len()
}
fn types(&self) -> impl Iterator<Item = impl ToTokens + '_> + '_ {
self.params.iter().map(|param| param.ty)
}
fn strategies(&self) -> impl Iterator<Item = impl ToTokens + '_> + '_ {
self.params.iter().map(|param| param.config.strategy())
}
fn name_pats(&self) -> impl Iterator<Item = impl ToTokens + '_> + '_ {
self.params.iter().map(|param| param.name_pat)
}
}
impl<'a> ToTokens for PropfuzzFnBody<'a> {
fn to_tokens(&self, tokens: &mut TokenStream) {
let strategies = self.strategies();
let name_pats = self.name_pats();
let block = self.block;
tokens.extend(quote! {
__propfuzz_test_runner.run(&(#(#strategies,)*), |(#(#name_pats,)*)| {
// This is similar to proptest -- it ensures that the block itself doesn't
// return a value, other than through an explicit `return` statement (as with
// the prop_assert_ methods).
let _: () = #block;
Ok(())
})
});
}
}
/// A propfuzz input parameter representing a random instance of a specific type, and a strategy to
/// generate that random instance.
#[derive(Debug)]
struct PropfuzzParam<'a> {
name_pat: &'a Pat,
ty: &'a Type,
config: ParamConfig,
}
impl<'a> PropfuzzParam<'a> {
fn new(param: &'a PatType) -> Result<Self> {
let ty = &*param.ty;
let mut errors = ErrorList::new();
let mut config_builder = ParamConfigBuilder::new(ty);
let (propfuzz_attrs, other_attrs) = param
.attrs
.iter()
.partition::<Vec<_>, _>(|attr| attr.path.is_ident("propfuzz"));
config_builder.apply_attrs(propfuzz_attrs, &mut errors);
// Non-propfuzz attributes on arguments aren't recognized (there's nowhere to put them!)
for attr in other_attrs {
errors.combine(Error::new_spanned(
attr,
"non-#[propfuzz] attributes are not supported",
));
}
errors.finish()?;
let config = config_builder.finish();
Ok(Self {
name_pat: ¶m.pat,
ty,
config,
})
}
}
| rust | Apache-2.0 | 742567d73088988fc24f065a0aba3e88adb049f4 | 2026-01-04T20:18:50.820316Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-dfs/build.rs | wasmer-dfs/build.rs | #[cfg(not(target_os = "macos"))]
const LIBFUSE_NAME: &str = "fuse";
#[cfg(target_os = "macos")]
const LIBFUSE_NAME: &str = "osxfuse";
fn main() {
pkg_config::Config::new()
.atleast_version("2.6.0")
.probe(LIBFUSE_NAME)
.map_err(|e| eprintln!("{}", e))
.unwrap();
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-dfs/src/lib.rs | wasmer-dfs/src/lib.rs | pub mod error;
pub mod fs;
pub mod fuse;
pub mod helper;
pub mod opts;
pub mod umount;
pub use helper::main_mount;
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-dfs/src/fs.rs | wasmer-dfs/src/fs.rs | #![allow(unused_imports)]
use ate_files::accessor::FileAccessor;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use std::ffi::{OsStr, OsString};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use std::vec::IntoIter;
use ::ate::chain::*;
use ::ate::crypto::*;
use ::ate::dio::Dao;
use ::ate::dio::DaoObj;
use ::ate::dio::Dio;
use ::ate::error::*;
use ::ate::header::PrimaryKey;
use ::ate::prelude::AteRolePurpose;
use ::ate::prelude::ReadOption;
use ::ate::prelude::*;
use ::ate::session::AteSessionUser;
use ::ate::{crypto::DerivedEncryptKey, prelude::TransactionScope};
use ate_files::prelude::*;
use async_trait::async_trait;
use futures_util::stream;
use futures_util::stream::Iter;
use fxhash::FxHashMap;
const FUSE_TTL: Duration = Duration::from_secs(1);
use ate_files::model;
use super::error::conv_result;
use super::fuse;
pub struct AteFS
where
Self: Send + Sync,
{
accessor: FileAccessor,
umask: u32,
}
pub fn conv_attr(attr: &FileAttr) -> fuse::FileAttr {
let size = attr.size;
let blksize = model::PAGE_SIZE as u64;
fuse::FileAttr {
ino: attr.ino,
generation: 0,
size: attr.size,
blocks: (size / blksize),
atime: SystemTime::UNIX_EPOCH + Duration::from_millis(attr.accessed),
mtime: SystemTime::UNIX_EPOCH + Duration::from_millis(attr.updated),
ctime: SystemTime::UNIX_EPOCH + Duration::from_millis(attr.created),
kind: conv_kind(attr.kind),
perm: fuse3::perm_from_mode_and_kind(conv_kind(attr.kind), attr.mode),
nlink: 0,
uid: attr.uid,
gid: attr.gid,
rdev: 0,
blksize: blksize as u32,
}
}
fn conv_kind(kind: FileKind) -> fuse::FileType {
match kind {
FileKind::Directory => fuse::FileType::Directory,
FileKind::FixedFile => fuse::FileType::RegularFile,
FileKind::RegularFile => fuse::FileType::RegularFile,
FileKind::SymLink => fuse::FileType::Symlink,
}
}
impl AteFS {
pub async fn new(
chain: Arc<Chain>,
group: Option<String>,
session: AteSessionType,
scope_io: TransactionScope,
scope_meta: TransactionScope,
no_auth: bool,
impersonate_uid: bool,
umask: u32,
) -> AteFS {
AteFS {
accessor: FileAccessor::new(
chain,
group,
session,
scope_io,
scope_meta,
no_auth,
impersonate_uid,
)
.await,
umask,
}
}
pub async fn load(&self, inode: u64) -> fuse::Result<Dao<Inode>> {
conv_result(self.accessor.load(inode).await)
}
pub async fn load_mut(&self, inode: u64) -> fuse::Result<DaoMut<Inode>> {
conv_result(self.accessor.load_mut(inode).await)
}
pub async fn load_mut_io(&self, inode: u64) -> fuse::Result<DaoMut<Inode>> {
conv_result(self.accessor.load_mut_io(inode).await)
}
async fn create_open_handle(
&self,
inode: u64,
req: &fuse::Request,
flags: i32,
) -> fuse::Result<OpenHandle> {
let req = req_ctx(req);
conv_result(self.accessor.create_open_handle(inode, &req, flags).await)
}
}
impl AteFS {
async fn tick(&self) -> fuse::Result<()> {
conv_result(self.accessor.tick().await)
}
}
fn req_ctx(req: &fuse::Request) -> RequestContext {
RequestContext {
uid: req.uid,
gid: req.gid,
}
}
#[async_trait]
impl fuse::Filesystem for AteFS {
type DirEntryStream = Iter<IntoIter<fuse::Result<fuse3::raw::prelude::DirectoryEntry>>>;
type DirEntryPlusStream = Iter<IntoIter<fuse::Result<fuse3::raw::prelude::DirectoryEntryPlus>>>;
async fn init(&self, req: fuse::Request) -> fuse::Result<()> {
let req = req_ctx(&req);
conv_result(self.accessor.init(&req).await)?;
Ok(())
}
async fn destroy(&self, req: fuse::Request) {
let _req = req_ctx(&req);
}
async fn getattr(
&self,
req: fuse::Request,
inode: u64,
fh: Option<u64>,
flags: u32,
) -> fuse::Result<fuse::ReplyAttr> {
let req = req_ctx(&req);
Ok(fuse::ReplyAttr {
ttl: FUSE_TTL,
attr: conv_attr(&conv_result(
self.accessor.getattr(&req, inode, fh, flags).await,
)?),
})
}
async fn setattr(
&self,
req: fuse::Request,
inode: u64,
fh: Option<u64>,
set_attr: fuse::SetAttr,
) -> fuse::Result<fuse::ReplyAttr> {
let req = req_ctx(&req);
let set_attr = SetAttr {
mode: set_attr.mode,
uid: set_attr.uid,
gid: set_attr.gid,
size: set_attr.size,
lock_owner: set_attr.lock_owner,
accessed: set_attr
.atime
.iter()
.filter_map(|a| {
a.duration_since(SystemTime::UNIX_EPOCH)
.ok()
.map(|a| a.as_millis() as u64)
})
.next(),
updated: set_attr
.mtime
.iter()
.filter_map(|a| {
a.duration_since(SystemTime::UNIX_EPOCH)
.ok()
.map(|a| a.as_millis() as u64)
})
.next(),
created: set_attr
.ctime
.iter()
.filter_map(|a| {
a.duration_since(SystemTime::UNIX_EPOCH)
.ok()
.map(|a| a.as_millis() as u64)
})
.next(),
};
let attr = conv_attr(&conv_result(
self.accessor.setattr(&req, inode, fh, set_attr).await,
)?);
Ok(fuse::ReplyAttr {
ttl: FUSE_TTL,
attr,
})
}
async fn opendir(
&self,
req: fuse::Request,
inode: u64,
flags: u32,
) -> fuse::Result<fuse::ReplyOpen> {
let req = req_ctx(&req);
Ok(fuse::ReplyOpen {
fh: conv_result(self.accessor.opendir(&req, inode, flags).await)?.fh,
flags: 0,
})
}
async fn releasedir(
&self,
req: fuse::Request,
inode: u64,
fh: u64,
flags: u32,
) -> fuse::Result<()> {
let req = req_ctx(&req);
conv_result(self.accessor.releasedir(&req, inode, fh, flags).await)
}
async fn readdirplus(
&self,
req: fuse::Request,
parent: u64,
fh: u64,
offset: u64,
_lock_owner: u64,
) -> fuse::Result<fuse::ReplyDirectoryPlus<Self::DirEntryPlusStream>> {
self.tick().await?;
debug!("wasmer-dfs::readdirplus id={} offset={}", parent, offset);
if fh == 0 {
let open = self
.create_open_handle(parent, &req, libc::O_RDONLY)
.await?;
let entries = open
.children
.iter()
.skip(offset as usize)
.map(|a| {
Ok(fuse::DirectoryEntryPlus {
inode: a.inode,
kind: conv_kind(a.kind),
name: OsString::from(a.name.as_str()),
generation: 0,
attr: conv_attr(&a.attr),
entry_ttl: FUSE_TTL,
attr_ttl: FUSE_TTL,
})
})
.map(|a| conv_result(a))
.collect::<Vec<_>>();
return Ok(fuse::ReplyDirectoryPlus {
entries: stream::iter(entries.into_iter()),
});
}
let lock = self.accessor.open_handles.lock().unwrap();
if let Some(open) = lock.get(&fh) {
let entries = open
.children
.iter()
.skip(offset as usize)
.map(|a| {
Ok(fuse::DirectoryEntryPlus {
inode: a.inode,
kind: conv_kind(a.kind),
name: OsString::from(a.name.as_str()),
generation: 0,
attr: conv_attr(&a.attr),
entry_ttl: FUSE_TTL,
attr_ttl: FUSE_TTL,
})
})
.map(|a| conv_result(a))
.collect::<Vec<_>>();
Ok(fuse::ReplyDirectoryPlus {
entries: stream::iter(entries.into_iter()),
})
} else {
Err(libc::ENOSYS.into())
}
}
async fn readdir(
&self,
req: fuse::Request,
parent: u64,
fh: u64,
offset: i64,
) -> fuse::Result<fuse::ReplyDirectory<Self::DirEntryStream>> {
self.tick().await?;
debug!("wasmer-dfs::readdir parent={}", parent);
if fh == 0 {
let open = self
.create_open_handle(parent, &req, libc::O_RDONLY)
.await?;
let entries = open
.children
.iter()
.skip(offset as usize)
.map(|a| {
Ok(fuse::DirectoryEntry {
inode: a.inode,
kind: conv_kind(a.kind),
name: OsString::from(a.name.as_str()),
})
})
.map(|a| conv_result(a))
.collect::<Vec<_>>();
return Ok(fuse::ReplyDirectory {
entries: stream::iter(entries.into_iter()),
});
}
let lock = self.accessor.open_handles.lock().unwrap();
if let Some(open) = lock.get(&fh) {
let entries = open
.children
.iter()
.skip(offset as usize)
.map(|a| {
Ok(fuse::DirectoryEntry {
inode: a.inode,
kind: conv_kind(a.kind),
name: OsString::from(a.name.as_str()),
})
})
.map(|a| conv_result(a))
.collect::<Vec<_>>();
Ok(fuse::ReplyDirectory {
entries: stream::iter(entries.into_iter()),
})
} else {
Err(libc::ENOSYS.into())
}
}
async fn lookup(
&self,
req: fuse::Request,
parent: u64,
name: &OsStr,
) -> fuse::Result<fuse::ReplyEntry> {
let req = req_ctx(&req);
let name = name.to_str().unwrap();
Ok(fuse::ReplyEntry {
ttl: FUSE_TTL,
attr: match conv_result(self.accessor.lookup(&req, parent, name).await)? {
Some(a) => conv_attr(&a),
None => {
return Err(libc::ENOENT.into());
}
},
generation: 0,
})
}
async fn forget(&self, req: fuse::Request, inode: u64, nlookup: u64) {
let req = req_ctx(&req);
self.accessor.forget(&req, inode, nlookup).await;
}
async fn fsync(
&self,
req: fuse::Request,
inode: u64,
fh: u64,
datasync: bool,
) -> fuse::Result<()> {
let req = req_ctx(&req);
conv_result(self.accessor.fsync(&req, inode, fh, datasync).await)
}
async fn flush(
&self,
req: fuse::Request,
inode: u64,
fh: u64,
lock_owner: u64,
) -> fuse::Result<()> {
let req = req_ctx(&req);
conv_result(self.accessor.flush(&req, inode, fh, lock_owner).await)
}
async fn access(&self, req: fuse::Request, inode: u64, mask: u32) -> fuse::Result<()> {
let req = req_ctx(&req);
conv_result(self.accessor.access(&req, inode, mask).await)
}
async fn mkdir(
&self,
req: fuse::Request,
parent: u64,
name: &OsStr,
mode: u32,
_umask: u32,
) -> fuse::Result<fuse::ReplyEntry> {
let req = req_ctx(&req);
let mode = if self.umask != 0o0000 {
0o777 & !self.umask
} else {
mode
};
let attr = conv_result(
self.accessor
.mkdir(&req, parent, name.to_str().unwrap(), mode)
.await,
)?;
Ok(fuse::ReplyEntry {
ttl: FUSE_TTL,
attr: conv_attr(&attr),
generation: 0,
})
}
async fn rmdir(&self, req: fuse::Request, parent: u64, name: &OsStr) -> fuse::Result<()> {
let req = req_ctx(&req);
conv_result(
self.accessor
.rmdir(&req, parent, name.to_str().unwrap())
.await,
)
}
async fn interrupt(&self, req: fuse::Request, unique: u64) -> fuse::Result<()> {
let req = req_ctx(&req);
conv_result(self.accessor.interrupt(&req, unique).await)
}
async fn mknod(
&self,
req: fuse::Request,
parent: u64,
name: &OsStr,
mode: u32,
_rdev: u32,
) -> fuse::Result<fuse::ReplyEntry> {
let req = req_ctx(&req);
let mode = if self.umask != 0o0000 {
0o666 & !self.umask
} else {
mode
};
let node = self
.accessor
.mknod(&req, parent, name.to_str().unwrap(), mode)
.await;
Ok(fuse::ReplyEntry {
ttl: FUSE_TTL,
attr: conv_attr(&conv_result(node)?),
generation: 0,
})
}
async fn create(
&self,
req: fuse::Request,
parent: u64,
name: &OsStr,
mode: u32,
flags: u32,
) -> fuse::Result<fuse::ReplyCreated> {
let req = req_ctx(&req);
let mode = if self.umask != 0o0000 {
0o666 & !self.umask
} else {
mode
};
let handle = conv_result(
self.accessor
.create(&req, parent, name.to_str().unwrap(), mode)
.await,
)?;
Ok(fuse::ReplyCreated {
ttl: FUSE_TTL,
attr: conv_attr(&handle.attr),
generation: 0,
fh: handle.fh,
flags,
})
}
async fn unlink(&self, req: fuse::Request, parent: u64, name: &OsStr) -> fuse::Result<()> {
let req = req_ctx(&req);
conv_result(
self.accessor
.unlink(&req, parent, name.to_str().unwrap())
.await,
)
}
async fn rename(
&self,
req: fuse::Request,
parent: u64,
name: &OsStr,
new_parent: u64,
new_name: &OsStr,
) -> fuse::Result<()> {
let req = req_ctx(&req);
conv_result(
self.accessor
.rename(
&req,
parent,
name.to_str().unwrap(),
new_parent,
new_name.to_str().unwrap(),
)
.await,
)
}
async fn open(
&self,
req: fuse::Request,
inode: u64,
flags: u32,
) -> fuse::Result<fuse::ReplyOpen> {
let req = req_ctx(&req);
let handle = conv_result(self.accessor.open(&req, inode, flags).await)?;
Ok(fuse::ReplyOpen {
fh: handle.fh,
flags,
})
}
async fn release(
&self,
req: fuse::Request,
inode: u64,
fh: u64,
flags: u32,
lock_owner: u64,
flush: bool,
) -> fuse::Result<()> {
let req = req_ctx(&req);
conv_result(
self.accessor
.release(&req, inode, fh, flags, lock_owner, flush)
.await,
)
}
async fn read(
&self,
req: fuse::Request,
inode: u64,
fh: u64,
offset: u64,
size: u32,
) -> fuse::Result<fuse::ReplyData> {
let req = req_ctx(&req);
let data = conv_result(self.accessor.read(&req, inode, fh, offset, size).await)?;
Ok(fuse::ReplyData { data })
}
async fn write(
&self,
req: fuse::Request,
inode: u64,
fh: u64,
offset: u64,
data: &[u8],
flags: u32,
) -> fuse::Result<fuse::ReplyWrite> {
let req = req_ctx(&req);
let wrote = conv_result(
self.accessor
.write(&req, inode, fh, offset, data, flags)
.await,
)?;
Ok(fuse::ReplyWrite { written: wrote })
}
async fn fallocate(
&self,
req: fuse::Request,
inode: u64,
fh: u64,
offset: u64,
length: u64,
mode: u32,
) -> fuse::Result<()> {
let req = req_ctx(&req);
conv_result(
self.accessor
.fallocate(&req, inode, fh, offset, length, mode)
.await,
)
}
async fn lseek(
&self,
req: fuse::Request,
inode: u64,
fh: u64,
offset: u64,
whence: u32,
) -> fuse::Result<fuse::ReplyLSeek> {
let req = req_ctx(&req);
let offset = conv_result(self.accessor.lseek(&req, inode, fh, offset, whence).await)?;
Ok(fuse::ReplyLSeek { offset })
}
async fn symlink(
&self,
req: fuse::Request,
parent: u64,
name: &OsStr,
link: &OsStr,
) -> fuse::Result<fuse::ReplyEntry> {
let req = req_ctx(&req);
let attr = conv_result(
self.accessor
.symlink(&req, parent, name.to_str().unwrap(), link.to_str().unwrap())
.await,
)?;
Ok(fuse::ReplyEntry {
ttl: FUSE_TTL,
attr: conv_attr(&attr),
generation: 0,
})
}
/// read symbolic link.
async fn readlink(&self, req: fuse::Request, _inode: u64) -> fuse::Result<fuse::ReplyData> {
let _req = req_ctx(&req);
Err(libc::ENOSYS.into())
}
/// create a hard link.
async fn link(
&self,
req: fuse::Request,
_inode: u64,
_new_parent: u64,
_new_name: &OsStr,
) -> fuse::Result<fuse::ReplyEntry> {
let _req = req_ctx(&req);
Err(libc::ENOSYS.into())
}
/// get filesystem statistics.
async fn statsfs(&self, req: fuse::Request, _inode: u64) -> fuse::Result<fuse::ReplyStatFs> {
let _req = req_ctx(&req);
Err(libc::ENOSYS.into())
}
/// set an extended attribute.
async fn setxattr(
&self,
req: fuse::Request,
inode: u64,
name: &OsStr,
value: &OsStr,
_flags: u32,
_position: u32,
) -> fuse::Result<()> {
let req = req_ctx(&req);
conv_result(
self.accessor
.setxattr(&req, inode, name.to_str().unwrap(), value.to_str().unwrap())
.await,
)
}
/// get an extended attribute. If size is too small, use [`ReplyXAttr::Size`] to return correct
/// size. If size is enough, use [`ReplyXAttr::Data`] to send it, or return error.
async fn getxattr(
&self,
req: fuse::Request,
inode: u64,
name: &OsStr,
size: u32,
) -> fuse::Result<fuse::ReplyXAttr> {
let req = req_ctx(&req);
let ret = match conv_result(
self.accessor
.getxattr(&req, inode, name.to_str().unwrap())
.await,
)? {
Some(a) => a,
None => {
return Err(libc::ENODATA.into());
}
};
let ret = {
let mut r = ret;
r.push('\0');
r
};
let ret = ret.into_bytes();
if ret.len() as u32 > size {
Ok(fuse::ReplyXAttr::Size(ret.len() as u32))
} else {
Ok(fuse::ReplyXAttr::Data(bytes::Bytes::from(ret)))
}
}
/// list extended attribute names. If size is too small, use [`ReplyXAttr::Size`] to return
/// correct size. If size is enough, use [`ReplyXAttr::Data`] to send it, or return error.
async fn listxattr(
&self,
req: fuse::Request,
inode: u64,
size: u32,
) -> fuse::Result<fuse::ReplyXAttr> {
let req = req_ctx(&req);
let attr = conv_result(self.accessor.listxattr(&req, inode).await)?;
let mut ret = String::new();
for (k, _) in attr {
ret.push_str(k.as_str());
ret.push('\0');
}
let ret = ret.into_bytes();
if ret.len() as u32 > size {
Ok(fuse::ReplyXAttr::Size(ret.len() as u32))
} else {
Ok(fuse::ReplyXAttr::Data(bytes::Bytes::from(ret)))
}
}
/// remove an extended attribute.
async fn removexattr(&self, req: fuse::Request, inode: u64, name: &OsStr) -> fuse::Result<()> {
let req = req_ctx(&req);
conv_result(
self.accessor
.removexattr(&req, inode, name.to_str().unwrap())
.await,
)?;
Ok(())
}
/// map block index within file to block index within device.
///
/// # Notes:
///
/// This may not works because currently this crate doesn't support fuseblk mode yet.
async fn bmap(
&self,
req: fuse::Request,
_inode: u64,
_blocksize: u32,
_idx: u64,
) -> fuse::Result<fuse::ReplyBmap> {
let _req = req_ctx(&req);
Err(libc::ENOSYS.into())
}
async fn poll(
&self,
req: fuse::Request,
_inode: u64,
_fh: u64,
_kh: Option<u64>,
_flags: u32,
_events: u32,
_notify: &fuse::Notify,
) -> fuse::Result<fuse::ReplyPoll> {
let _req = req_ctx(&req);
Err(libc::ENOSYS.into())
}
async fn notify_reply(
&self,
req: fuse::Request,
_inode: u64,
_offset: u64,
_data: bytes::Bytes,
) -> fuse::Result<()> {
let _req = req_ctx(&req);
Err(libc::ENOSYS.into())
}
/// forget more than one inode. This is a batch version [`forget`][Filesystem::forget]
async fn batch_forget(&self, req: fuse::Request, _inodes: &[u64]) {
let _req = req_ctx(&req);
}
async fn copy_file_range(
&self,
req: fuse::Request,
_inode: u64,
_fh_in: u64,
_off_in: u64,
_inode_out: u64,
_fh_out: u64,
_off_out: u64,
_length: u64,
_flags: u64,
) -> fuse::Result<fuse::ReplyCopyFileRange> {
let _req = req_ctx(&req);
Err(libc::ENOSYS.into())
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-dfs/src/error.rs | wasmer-dfs/src/error.rs | use ate::error::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use ate_files::error::FileSystemError;
use ate_files::error::FileSystemErrorKind;
use fuse3::Errno;
pub(crate) fn conv_result<T>(
r: std::result::Result<T, FileSystemError>,
) -> std::result::Result<T, Errno> {
match r {
Ok(a) => Ok(a),
Err(err) => {
error!("wasmer-dfs::error {}", err);
match err {
FileSystemError(FileSystemErrorKind::NoAccess, _) => Err(libc::EACCES.into()),
FileSystemError(FileSystemErrorKind::PermissionDenied, _) => {
Err(libc::EPERM.into())
}
FileSystemError(FileSystemErrorKind::ReadOnly, _) => Err(libc::EPERM.into()),
FileSystemError(FileSystemErrorKind::InvalidArguments, _) => {
Err(libc::EINVAL.into())
}
FileSystemError(FileSystemErrorKind::NoEntry, _) => Err(libc::ENOENT.into()),
FileSystemError(FileSystemErrorKind::DoesNotExist, _) => Err(libc::ENOENT.into()),
FileSystemError(FileSystemErrorKind::AlreadyExists, _) => Err(libc::EEXIST.into()),
FileSystemError(FileSystemErrorKind::NotDirectory, _) => Err(libc::ENOTDIR.into()),
FileSystemError(FileSystemErrorKind::IsDirectory, _) => Err(libc::EISDIR.into()),
FileSystemError(FileSystemErrorKind::NotImplemented, _) => Err(libc::ENOSYS.into()),
FileSystemError(
FileSystemErrorKind::AteError(AteErrorKind::CommitError(
CommitErrorKind::CommsError(CommsErrorKind::Disconnected),
)),
_,
) => Err(libc::EBUSY.into()),
FileSystemError(
FileSystemErrorKind::AteError(AteErrorKind::CommsError(
CommsErrorKind::Disconnected,
)),
_,
) => Err(libc::EBUSY.into()),
_ => Err(libc::EIO.into()),
}
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-dfs/src/helper.rs | wasmer-dfs/src/helper.rs | use ate::mesh::FatalTerminate;
use ate::prelude::*;
use ate::utils::LoadProgress;
use error_chain::bail;
use std::io::ErrorKind;
use std::sync::Arc;
use std::time::Duration;
use tokio::select;
#[allow(unused_imports, dead_code)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use crate::fs::AteFS;
use crate::opts::*;
use crate::umount;
use fuse3::raw::prelude::*;
use fuse3::MountOptions;
fn ctrl_channel() -> tokio::sync::watch::Receiver<bool> {
let (sender, receiver) = tokio::sync::watch::channel(false);
ctrlc_async::set_handler(move || {
let _ = sender.send(true);
})
.unwrap();
receiver
}
pub async fn main_mount(
mount: OptsMount,
conf: ConfAte,
group: Option<String>,
session: AteSessionType,
no_auth: bool,
) -> Result<(), AteError> {
let uid = match mount.uid {
Some(a) => a,
None => unsafe { libc::getuid() },
};
let gid = match mount.gid {
Some(a) => a,
None => unsafe { libc::getgid() },
};
debug!("uid: {}", uid);
debug!("gid: {}", uid);
let mount_options = MountOptions::default()
.uid(uid)
.gid(gid)
.allow_root(mount.allow_root)
.allow_other(mount.allow_other)
.read_only(mount.read_only)
.write_back(mount.write_back)
.nonempty(mount.non_empty);
debug!("allow_root: {}", mount.allow_root);
debug!("allow_other: {}", mount.allow_other);
debug!("read_only: {}", mount.read_only);
debug!("write_back: {}", mount.write_back);
debug!("non_empty: {}", mount.non_empty);
let mut conf = conf.clone();
conf.configured_for(mount.configured_for);
conf.log_format.meta = mount.meta_format;
conf.log_format.data = mount.data_format;
conf.log_path = mount
.log_path
.as_ref()
.map(|a| shellexpand::tilde(a).to_string());
conf.backup_path = mount
.backup_path
.as_ref()
.map(|a| shellexpand::tilde(a).to_string());
conf.recovery_mode = mount.recovery_mode;
conf.compact_bootstrap = mount.compact_now;
conf.compact_mode = mount
.compact_mode
.with_growth_factor(mount.compact_threshold_factor)
.with_growth_size(mount.compact_threshold_size)
.with_timer_value(Duration::from_secs(mount.compact_timer));
info!("configured_for: {:?}", mount.configured_for);
info!("meta_format: {:?}", mount.meta_format);
info!("data_format: {:?}", mount.data_format);
info!(
"log_path: {}",
match conf.log_path.as_ref() {
Some(a) => a.as_str(),
None => "(memory)",
}
);
info!("log_temp: {}", mount.temp);
info!("mount_path: {}", mount.mount_path);
match &mount.remote_name {
Some(remote) => info!("remote: {}", remote.to_string()),
None => info!("remote: local-only"),
};
let builder = ChainBuilder::new(&conf).await.temporal(mount.temp);
// Create a progress bar loader
let mut progress_local = LoadProgress::new(std::io::stdout());
let mut progress_remote = LoadProgress::new(std::io::stdout());
progress_local.units = pbr::Units::Bytes;
progress_local.msg_done = "Downloading latest events from server...".to_string();
progress_remote.msg_done =
"Loaded the remote chain-of-trust, proceeding to mount the file system.".to_string();
print!("Loading the chain-of-trust...");
// We create a chain with a specific key (this is used for the file name it creates)
debug!("chain-init");
let registry;
let chain = match mount.remote_name {
None => {
let trust = match &mount.configured_for {
ConfiguredFor::BestSecurity | ConfiguredFor::SmallestSize => {
TrustMode::Centralized(CentralizedRole::Client)
}
_ => TrustMode::Distributed,
};
Ok(Arc::new(
Chain::new_ext(
builder.clone(),
ChainKey::from("root"),
Some(Box::new(progress_local)),
true,
trust,
trust,
)
.await?,
))
}
Some(remote) => {
registry = ate::mesh::Registry::new(&conf).await.temporal(mount.temp);
let guard = registry
.open_ext(
&mount.remote,
&ChainKey::from(remote),
false,
progress_local,
progress_remote,
)
.await?;
Ok(guard.as_arc())
}
};
// Perform specific error handling (otherwise let it propogate up)
let chain = match chain {
Ok(a) => a,
Err(ChainCreationError(ChainCreationErrorKind::ServerRejected(reason), _)) => {
match reason {
FatalTerminate::Denied { reason } => {
println!("Access to this file system was denied by the server");
println!("---");
println!("{}", reason);
std::process::exit(1);
}
_ => {
bail!(AteErrorKind::ChainCreationError(
ChainCreationErrorKind::ServerRejected(reason)
));
}
}
}
Err(err) => {
bail!(err);
}
};
// Compute the scope
let scope_meta = match mount.recovery_mode.is_meta_sync() {
true => TransactionScope::Full,
false => TransactionScope::Local,
};
let scope_io = match mount.recovery_mode.is_sync() {
true => TransactionScope::Full,
false => TransactionScope::Local,
};
// Create the mount point
let mount_path = mount.mount_path.clone();
let mount_join = Session::new(mount_options).mount_with_unprivileged(
AteFS::new(
chain,
group,
session,
scope_io,
scope_meta,
no_auth,
mount.impersonate_uid,
mount.umask,
)
.await,
mount.mount_path,
);
// Install a ctrl-c command
info!("mounting file-system and entering main loop");
let mut ctrl_c = ctrl_channel();
// Add a panic hook that will unmount
{
let orig_hook = std::panic::take_hook();
let mount_path = mount_path.clone();
std::panic::set_hook(Box::new(move |panic_info| {
let _ = umount::unmount(std::path::Path::new(mount_path.as_str()));
orig_hook(panic_info);
std::process::exit(1);
}));
}
// Main loop
println!("Press ctrl-c to exit");
select! {
// Wait for a ctrl-c
_ = ctrl_c.changed() => {
umount::unmount(std::path::Path::new(mount_path.as_str()))?;
println!("Goodbye!");
return Ok(());
}
// Mount the file system
ret = mount_join => {
match ret {
Err(err) if err.kind() == ErrorKind::Other => {
if err.to_string().contains("find fusermount binary failed") {
error!("Fuse3 could not be found - you may need to install fuse3 via apt/yum");
return Ok(())
}
error!("{}", err);
println!("Mount failed");
let _ = umount::unmount(std::path::Path::new(mount_path.as_str()));
std::process::exit(1);
}
Err(err) => {
error!("{}", err);
println!("Mount failed");
let _ = umount::unmount(std::path::Path::new(mount_path.as_str()));
std::process::exit(1);
}
_ => {
println!("Mount shutdown");
let _ = umount::unmount(std::path::Path::new(mount_path.as_str()));
return Ok(());
}
}
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-dfs/src/umount.rs | wasmer-dfs/src/umount.rs | use libc::{self, c_char, c_int};
use std::ffi::{CStr, CString};
use std::io;
use std::path::Path;
extern "C" {
// *_compat25 functions were introduced in FUSE 2.6 when function signatures changed.
// Therefore, the minimum version requirement for *_compat25 functions is libfuse-2.6.0.
pub fn fuse_unmount_compat22(mountpoint: *const c_char);
}
/// Unmount an arbitrary mount point
pub fn unmount(mountpoint: &Path) -> io::Result<()> {
// fuse_unmount_compat22 unfortunately doesn't return a status. Additionally,
// it attempts to call realpath, which in turn calls into the filesystem. So
// if the filesystem returns an error, the unmount does not take place, with
// no indication of the error available to the caller. So we call unmount
// directly, which is what osxfuse does anyway, since we already converted
// to the real path when we first mounted.
#[cfg(any(
target_os = "macos",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "openbsd",
target_os = "bitrig",
target_os = "netbsd"
))]
#[inline]
fn libc_umount(mnt: &CStr) -> c_int {
unsafe { libc::unmount(mnt.as_ptr(), 0) }
}
#[cfg(not(any(
target_os = "macos",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "openbsd",
target_os = "bitrig",
target_os = "netbsd"
)))]
#[inline]
fn libc_umount(mnt: &CStr) -> c_int {
use std::io::ErrorKind::PermissionDenied;
let rc = unsafe { libc::umount(mnt.as_ptr()) };
if rc < 0 && io::Error::last_os_error().kind() == PermissionDenied {
// Linux always returns EPERM for non-root users. We have to let the
// library go through the setuid-root "fusermount -u" to unmount.
unsafe {
fuse_unmount_compat22(mnt.as_ptr());
}
0
} else {
rc
}
}
let mnt = CString::new(
mountpoint
.to_path_buf()
.into_os_string()
.into_string()
.unwrap(),
)?;
let rc = libc_umount(&mnt);
if rc < 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-dfs/src/fuse.rs | wasmer-dfs/src/fuse.rs | pub use fuse3::raw::prelude::*;
pub use fuse3::Errno;
pub use fuse3::Result;
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-dfs/src/opts.rs | wasmer-dfs/src/opts.rs | use ate::prelude::*;
use wasmer_auth::opt::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use ate::compact::CompactMode;
use wasmer_deploy_cli::opt::{OptsContract, OptsLogin, OptsLogout, OptsService, OptsWallet};
use clap::Parser;
#[derive(Parser)]
#[clap(version = "1.6", 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,
/// URL where the user is authenticated
#[clap(short, long, default_value = "ws://wasmer.sh/auth")]
pub auth: Url,
/// No authentication or passcode will be used to protect this file-system
#[clap(short, long)]
pub no_auth: bool,
/// Token used to access your encrypted file-system (if you do not supply a token then you will
/// be prompted for a username and password)
#[clap(short, long)]
pub token: Option<String>,
/// Token file to read that holds a previously created token to be used for this operation
#[clap(long, default_value = "~/wasmer/token")]
pub token_path: String,
/// No NTP server will be used to synchronize the time thus the server time
/// will be used instead
#[clap(long)]
pub no_ntp: bool,
/// NTP server address that the file-system will synchronize with
#[clap(long)]
pub ntp_pool: Option<String>,
/// NTP server port that the file-system will synchronize with
#[clap(long)]
pub ntp_port: Option<u16>,
/// Logs debug info to the console
#[clap(short, long)]
pub debug: bool,
/// Determines if ATE will use DNSSec or just plain DNS
#[clap(long)]
pub dns_sec: bool,
/// Address that DNS queries will be sent to
#[clap(long, default_value = "8.8.8.8")]
pub dns_server: String,
#[clap(subcommand)]
pub subcmd: SubCommand,
}
#[derive(Parser)]
pub enum SubCommand {
/// Users are personal accounts and services that have an authentication context.
/// Every user comes with a personal wallet that can hold commodities.
#[clap()]
User(OptsUser),
/// Domain groups are collections of users that share something together in association
/// with an internet domain name. Every group has a built in wallet(s) that you can
/// use instead of a personal wallet. In order to claim a domain group you will need
/// DNS access to an owned internet domain that can be validated.
#[clap()]
Domain(OptsDomain),
/// Databases are chains of data that make up a particular shard. These databases can be
/// use for application data persistance, file systems and web sites.
#[clap()]
Db(OptsDatabase),
/// Tokens are stored authentication and authorization secrets used by other processes.
/// Using this command you may generate a custom token however the usual method for
/// authentication is to use the login command instead.
#[clap()]
Token(OptsToken),
/// Services offered by Wasmer (and other 3rd parties) are accessible via this
/// sub command menu, including viewing the available services and subscribing
/// to them.
#[clap()]
Service(OptsService),
/// Contracts represent all the subscriptions you have made to specific services
/// you personally consume or a group consume that you act on your authority on
/// behalf of. This sub-menu allows you to perform actions such as cancel said
/// contracts.
#[clap()]
Contract(OptsContract),
/// Wallets are directly attached to groups and users - they hold a balance,
/// store transaction history and facilitate transfers, deposits and withdraws.
#[clap()]
Wallet(OptsWallet),
/// Login to an account and store the token locally for reuse.
#[clap()]
Login(OptsLogin),
/// Logout of the account by deleting the local token.
#[clap()]
Logout(OptsLogout),
/// Mounts a local or a remote file system (e.g. ws://wasmer.sh/db). When
/// using a Wasmer remote you can either use the default free hosting or subscribe
/// to the service which will consume funds from the wallet.
#[clap()]
Mount(OptsMount),
}
/// Mounts a particular directory as an ATE file system
#[derive(Parser)]
pub struct OptsMount {
/// Path to directory that the file system will be mounted at
#[clap(index = 1)]
pub mount_path: String,
/// Name of the file-system to be mounted (e.g. myfs).
/// If this URL is not specified then data will only be stored in a local chain-of-trust
#[clap(index = 2)]
pub remote_name: Option<String>,
/// URL where the data is remotely stored on a distributed commit log.
#[clap(short, long, default_value = "ws://wasmer.sh/db")]
pub remote: Url,
/// (Optional) Location of the local persistent redo log (e.g. ~/wasmer/fs")
/// If this parameter is not specified then chain-of-trust will cache in memory rather than disk
#[clap(long)]
pub log_path: Option<String>,
/// Path to the backup and restore location of log files
#[clap(short, long)]
pub backup_path: Option<String>,
/// Determines how the file-system will react while it is nominal and when it is
/// recovering from a communication failure (valid options are 'async', 'readonly-async',
/// 'readonly-sync' or 'sync')
#[clap(long, default_value = "readonly-async")]
pub recovery_mode: RecoveryMode,
/// User supplied passcode that will be used to encrypt the contents of this file-system
/// instead of using an authentication. Note that this can 'not' be used as combination
/// with a strong authentication system and hence implicitely implies the 'no-auth' option
/// as well.
#[clap(short, long)]
pub passcode: Option<String>,
/// Local redo log file will be deleted when the file system is unmounted, remotely stored data on
/// any distributed commit log will be persisted. Effectively this setting only uses the local disk
/// as a cache of the redo-log while it's being used.
#[clap(long)]
pub temp: bool,
/// UID of the user that this file system will be mounted as
#[clap(short, long)]
pub uid: Option<u32>,
/// GID of the group that this file system will be mounted as
#[clap(short, long)]
pub gid: Option<u32>,
/// Allow the root user to have access to this file system
#[clap(long)]
pub allow_root: bool,
/// Allow other users on the machine to have access to this file system
#[clap(long)]
pub allow_other: bool,
/// Mount the file system in readonly mode (`ro` mount option), default is disable.
#[clap(long)]
pub read_only: bool,
/// Enable write back cache for buffered writes, default is disable.
#[clap(short, long)]
pub write_back: bool,
/// By default this process will perform an extra umask(0o007) to prevent everything being public by default,
/// you can prevent this behaviour by selecting another umask (32bit) or just passing 0
#[clap(long, default_value = "7")]
pub umask: u32,
/// Allow fuse filesystem mount on a non-empty directory, default is not allowed.
#[clap(long)]
pub non_empty: bool,
/// For files and directories that the authenticated user owns, translate the UID and GID to the local machine ids instead of the global ones.
#[clap(short, long)]
pub impersonate_uid: bool,
/// Configure the log file for <raw>, <barebone>, <speed>, <compatibility>, <balanced> or <security>
#[clap(long, default_value = "speed")]
pub configured_for: ate::conf::ConfiguredFor,
/// Format of the metadata in the log file as <bincode>, <json> or <mpack>
#[clap(long, default_value = "bincode")]
pub meta_format: ate::spec::SerializationFormat,
/// Format of the data in the log file as <bincode>, <json> or <mpack>
#[clap(long, default_value = "bincode")]
pub data_format: ate::spec::SerializationFormat,
/// Forces the compaction of the local redo-log before it streams in the latest values
#[clap(long)]
pub compact_now: bool,
/// Mode that the compaction will run under (valid modes are 'never', 'modified', 'timer', 'factor', 'size', 'factor-or-timer', 'size-or-timer')
#[clap(long, default_value = "factor-or-timer")]
pub compact_mode: CompactMode,
/// Time in seconds between compactions of the log file (default: 1 hour) - this argument is ignored if you select a compact_mode that has no timer
#[clap(long, default_value = "3600")]
pub compact_timer: u64,
/// Factor growth in the log file which will trigger compaction - this argument is ignored if you select a compact_mode that has no growth trigger
#[clap(long, default_value = "0.4")]
pub compact_threshold_factor: f32,
/// Size of growth in bytes in the log file which will trigger compaction (default: 100MB) - this argument is ignored if you select a compact_mode that has no growth trigger
#[clap(long, default_value = "104857600")]
pub compact_threshold_size: u64,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-dfs/src/bin/wasmer-dfs.rs | wasmer-dfs/src/bin/wasmer-dfs.rs | use ate::prelude::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use wasmer_dfs::main_mount;
use wasmer_dfs::opts::*;
use wasmer_auth::cmd::*;
use wasmer_auth::helper::*;
use wasmer_deploy_cli::cmd::{
main_opts_contract, main_opts_login, main_opts_logout, main_opts_service, main_opts_wallet,
};
use clap::Parser;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let opts: Opts = Opts::parse();
//let opts = test_opts();
ate::log_init(opts.verbose, opts.debug);
let mut conf = AteConfig::default();
conf.dns_sec = opts.dns_sec;
conf.dns_server = opts.dns_server;
conf.ntp_sync = opts.no_ntp == false;
if let Some(pool) = opts.ntp_pool {
conf.ntp_pool = pool;
}
if let Some(port) = opts.ntp_port {
conf.ntp_port = port;
}
let token_path = { Some(opts.token_path.clone()) };
// Do we need a token
let needs_token = match &opts.subcmd {
SubCommand::Login(..) => false,
SubCommand::Token(..) => false,
_ => true,
};
// Make sure the token exists
if needs_token {
let token_path = shellexpand::tilde(&opts.token_path).to_string();
if std::path::Path::new(&token_path).exists() == false {
eprintln!("Token not found - please first login.");
std::process::exit(1);
}
}
match opts.subcmd {
SubCommand::Token(opts_token) => {
main_opts_token(opts_token, opts.token, token_path, opts.auth, "Domain name").await?;
}
SubCommand::User(opts_user) => {
main_opts_user(opts_user, opts.token, token_path, opts.auth).await?;
}
SubCommand::Db(opts_db) => {
main_opts_db(opts_db, opts.token, token_path, opts.auth, "Domain name").await?;
}
SubCommand::Domain(opts_group) => {
main_opts_group(opts_group, None, token_path, opts.auth, "Domain name").await?;
}
SubCommand::Wallet(opts_wallet) => {
main_opts_wallet(opts_wallet.source, opts.token_path, opts.auth).await?
}
SubCommand::Contract(opts_contract) => {
main_opts_contract(opts_contract.purpose, opts.token_path, opts.auth).await?;
}
SubCommand::Service(opts_service) => {
main_opts_service(opts_service.purpose, opts.token_path, opts.auth).await?;
}
SubCommand::Login(opts_login) => {
main_opts_login(opts_login, opts.token_path, opts.auth).await?
}
SubCommand::Logout(opts_logout) => main_opts_logout(opts_logout, opts.token_path).await?,
SubCommand::Mount(mount) => {
// Derive the group from the mount address
let mut group = None;
if let Some(remote) = &mount.remote_name {
if let Some((group_str, _)) = remote.split_once("/") {
group = Some(group_str.to_string());
}
}
let mut session: AteSessionType = AteSessionUser::default().into();
// If a passcode is supplied then use this
if let Some(pass) = &mount.passcode {
if opts.token.is_some() || token_path.is_some() {
eprintln!("You can not supply both a passcode and a token, either drop the --token arguments or the --passcode argument");
std::process::exit(1);
}
if mount.remote_name.is_some() {
eprintln!("Using a passcode is not compatible with remotely hosted file-systems as the distributed datchain needs to make authentication checks");
std::process::exit(1);
}
let prefix = "ate:".to_string();
let key = password_to_read_key(&prefix, &pass, 15, KeySize::Bit192);
let mut session_user = AteSessionUser::default();
session_user.user.add_read_key(&key);
session = session_user.into();
} else if opts.no_auth {
if mount.remote_name.is_some() {
eprintln!("In order to use remotely hosted file-systems you must use some form of authentication, without authentication the distributed databases will not be able to make the needed checks");
std::process::exit(1);
}
// We do not put anything in the session as no authentication method nor a passcode was supplied
} else {
// Load the session via the token or the authentication server
let session_user = main_session_user(
opts.token.clone(),
token_path.clone(),
Some(opts.auth.clone()),
)
.await?;
// Attempt to grab additional permissions for the group (if it has any)
session = if group.is_some() {
match main_gather(
group.clone(),
session_user.clone().into(),
opts.auth,
"Group",
)
.await
{
Ok(a) => a.into(),
Err(err) => {
debug!("Group authentication failed: {} - falling back to user level authorization", err);
session_user.into()
}
}
} else {
session_user.into()
}
}
// Mount the file system
main_mount(mount, conf, group, session, opts.no_auth).await?;
}
}
info!("wasmer-dfs::shutdown");
Ok(())
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/test.rs | wasmer-auth/src/test.rs | #![allow(unused_imports)]
use crate::prelude::*;
use ate::prelude::*;
use ate::time::TimeKeeper;
use std::time::Duration;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::cmd::*;
use crate::prelude::*;
#[tokio::main(flavor = "current_thread")]
#[test]
pub async fn test_create_user_and_group() {
ate::utils::bootstrap_test_env();
// Create the configuration
#[allow(unused_mut)]
let mut cfg_ate = conf_auth();
#[cfg(feature = "enable_local_fs")]
{
cfg_ate.log_path = Some(format!("/tmp/ate/test/{}", fastrand::u64(..)));
}
// Create the certificate
let cert = PrivateEncryptKey::generate(KeySize::Bit192);
ate::mesh::add_global_certificate(&cert.hash());
// Build a session for service
info!("building session for service");
let web_read_key = EncryptKey::generate(KeySize::Bit192);
let edge_read_key = EncryptKey::generate(KeySize::Bit192);
let contract_read_key = EncryptKey::generate(KeySize::Bit192);
let root_read_key = EncryptKey::generate(KeySize::Bit192);
let root_write_key = PrivateSignKey::generate(KeySize::Bit192);
let mut session = AteSessionUser::new();
session.user.add_read_key(&root_read_key);
session.user.add_write_key(&root_write_key);
// Create the chain flow and generate configuration
info!("generating random config");
let port_offset = fastrand::u16(..1000);
let port = 5000 + port_offset;
let auth = Url::parse(format!("ws://localhost:{}/auth", port).as_str()).unwrap();
let flow = ChainFlow::new(
&cfg_ate,
root_write_key,
session,
web_read_key.clone(),
edge_read_key.clone(),
contract_read_key.clone(),
&auth,
);
// Create the server and listen on port 5000
info!("creating server and listening on ports with routes");
let mut cfg_mesh = ConfMesh::solo_from_url(
&cfg_ate,
&auth,
&IpAddr::from_str("::1").unwrap(),
None,
None,
)
.await
.unwrap();
cfg_mesh.wire_protocol = StreamProtocol::WebSocket;
cfg_mesh.listen_certificate = Some(cert);
let server = create_server(&cfg_mesh).await.unwrap();
server.add_route(Box::new(flow), &cfg_ate).await.unwrap();
// Create the user
info!("creating user joe.blogs");
let username = "joe.blogs@nowhere.com".to_string();
let password = "letmein".to_string();
let response = main_create_user(Some(username.clone()), Some(password.clone()), auth.clone())
.await
.unwrap();
let session = response.authority;
// Get the read key for the user
info!("checking we have a read key");
let _read_key = session
.read_keys(AteSessionKeyCategory::AllKeys)
.next()
.unwrap()
.clone();
// Create the group
info!("creating group 'mygroup'");
let group = "mygroup".to_string();
let _session = main_create_group(
Some(group.clone()),
auth.clone(),
Some(username.clone()),
"Group",
)
.await
.unwrap();
// Compute the code using the returned QR secret
info!("computing login code");
let timer = TimeKeeper::new(&cfg_ate, 30000).await.unwrap();
let google_auth = google_authenticator::GoogleAuthenticator::new();
timer.wait_for_high_accuracy().await;
let code = google_auth
.get_code(
response.qr_secret.as_str(),
timer.current_timestamp_as_duration().unwrap().as_secs() / 30,
)
.unwrap();
// Login lots of times to hammer it
{
let registry = ate::mesh::Registry::new(&conf_cmd())
.await
.keep_alive(Duration::from_secs(30))
.cement();
for n in 0..10 {
info!("login request for joe.blogs [n={}]", n);
let response = login_command(
®istry,
username.clone(),
password.clone(),
None,
auth.clone(),
true,
)
.await;
info!("login completed for joe.blogs [n={}]", n);
let _ = handle_login_response(
®istry,
response,
username.clone(),
password.clone(),
auth.clone(),
)
.await
.unwrap();
}
}
// Login to the main user and gather the rights to the group (full sudo rights)
info!("sudo login for 'joe.blogs'");
let session = main_login(Some(username.clone()), Some(password.clone()), auth.clone())
.await
.unwrap();
let session = main_sudo(session, Some(code), auth.clone()).await.unwrap();
info!("gather permissions for group 'mygroup'");
let session = main_gather(Some(group.clone()), session.into(), auth.clone(), "Group")
.await
.unwrap();
// Make sure its got the permission
info!("test we have group roles");
let _group_read = session
.get_group_role(&AteRolePurpose::Owner)
.expect("Should have the owner role")
.private_read_keys()
.next()
.expect("Should have a private key for the owner role");
let _group_read = session
.get_group_role(&AteRolePurpose::Delegate)
.expect("Should have the delegate role")
.private_read_keys()
.next()
.expect("Should have a private key for the delegate role");
// Login to the main user and gather the rights to the group (we do not have sudo rights)
info!("login without sudo 'joe.blogs'");
let session = main_login(Some(username.clone()), Some(password.clone()), auth.clone())
.await
.unwrap();
info!("gather permissions for group 'mygroup'");
let session = main_gather(Some(group.clone()), session.into(), auth.clone(), "Group")
.await
.unwrap();
// Make sure its got the permission
info!("test we at have delegate and not owner");
let _group_read = session
.get_group_role(&AteRolePurpose::Delegate)
.expect("Should have the delegate role")
.private_read_keys()
.next()
.expect("Should have a private key for the delegate role");
assert!(
session.get_group_role(&AteRolePurpose::Owner).is_none(),
"The user should have had this role"
);
// Create a friend and add it to the new group we just added
info!("create a friend account 'myfriend'");
let friend_username = "myfriend@nowhere.come".to_string();
let friend = main_create_user(
Some(friend_username.clone()),
Some(password.clone()),
auth.clone(),
)
.await
.unwrap();
let friend_session = friend.authority;
info!("add friend to the group 'mygroup'");
main_group_user_add(
Some(AteRolePurpose::Contributor),
Some(friend_username.clone()),
auth.clone(),
&session,
"Group",
)
.await
.unwrap();
// Gather the extra rights for the friend
info!("gather extra rights for friend");
let friend = main_gather(
Some(group.clone()),
friend_session.clone().into(),
auth.clone(),
"Group",
)
.await
.unwrap();
// Make sure its got the permission
info!("test the friend got the 'contributor' role");
let _group_read = friend
.get_group_role(&AteRolePurpose::Contributor)
.expect("Should have the contributor role")
.private_read_keys()
.next()
.expect("Should have a private key for the owner role");
assert!(
friend.get_group_role(&AteRolePurpose::Owner).is_none(),
"The user should have had this role"
);
assert!(
friend.get_group_role(&AteRolePurpose::Delegate).is_none(),
"The user should have had this role"
);
// Load the details of the group
info!("get the group details");
main_group_details(Some(group.clone()), auth.clone(), Some(&session), "Group")
.await
.unwrap();
// Remove user the role
info!("remove the 'friend' from the group");
main_group_user_remove(
Some(AteRolePurpose::Contributor),
Some(friend_username.clone()),
auth.clone(),
&session,
"Group",
)
.await
.unwrap();
// Make sure its got the permission
info!("gather permissions and make sure they dont have contributor anymore");
let friend = main_gather(
Some(group.clone()),
friend_session.clone().into(),
auth.clone(),
"Group",
)
.await
.unwrap();
assert!(
friend
.get_group_role(&AteRolePurpose::Contributor)
.is_none(),
"The user should have had this role removed"
);
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/prelude.rs | wasmer-auth/src/prelude.rs | pub use super::error;
#[cfg(all(feature = "server"))]
pub use super::flow::ChainFlow;
pub use crate::cmd::gather_command;
pub use crate::cmd::main_gather;
pub use crate::cmd::main_session_group;
pub use crate::cmd::main_session_prompt;
pub use crate::cmd::main_session_sudo;
pub use crate::cmd::main_session_user;
pub use crate::helper::conf_auth;
pub use crate::helper::conf_cmd;
pub use crate::helper::DioBuilder;
pub use crate::util::origin_url;
pub use crate::util::origin_url_ext;
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/lib.rs | wasmer-auth/src/lib.rs | pub mod cmd;
pub mod error;
#[cfg(all(feature = "server"))]
pub mod flow;
pub mod helper;
pub mod model;
pub mod opt;
pub mod prelude;
pub mod request;
pub mod service;
mod test;
pub mod work;
pub mod util;
pub static GENERIC_TERMS_AND_CONDITIONS: &str = include_str!("generic_terms.txt");
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/flow.rs | wasmer-auth/src/flow.rs | use std::sync::Arc;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use async_trait::async_trait;
use ate::crypto::EncryptKey;
use ate::crypto::KeySize;
use ate::{error::ChainCreationError, prelude::*};
use regex::Regex;
use crate::service::*;
pub struct ChainFlow {
cfg: ConfAte,
auth_url: url::Url,
root_key: PrivateSignKey,
web_key: EncryptKey,
edge_key: EncryptKey,
contract_key: EncryptKey,
regex_auth: Regex,
regex_cmd: Regex,
session: AteSessionUser,
pub terms_and_conditions: Option<String>,
}
impl ChainFlow {
pub fn new(
cfg: &ConfAte,
root_key: PrivateSignKey,
session: AteSessionUser,
web_key: EncryptKey,
edge_key: EncryptKey,
contract_key: EncryptKey,
auth_url: &url::Url,
) -> Self {
ChainFlow {
cfg: cfg.clone(),
root_key,
regex_auth: Regex::new("^redo-[a-f0-9]{4}$").unwrap(),
regex_cmd: Regex::new("^cmd-[a-f0-9]{16}$").unwrap(),
auth_url: auth_url.clone(),
session,
web_key,
edge_key,
contract_key,
terms_and_conditions: None,
}
}
}
#[async_trait]
impl OpenFlow for ChainFlow {
fn hello_path(&self) -> &str {
self.auth_url.path()
}
async fn message_of_the_day(
&self,
_chain: &Arc<Chain>,
) -> Result<Option<String>, ChainCreationError> {
Ok(None)
}
async fn open(
&self,
mut builder: ChainBuilder,
key: &ChainKey,
wire_encryption: Option<KeySize>,
) -> Result<OpenAction, ChainCreationError> {
debug!("open_auth: {}", key);
let name = key.name.clone();
let name = name.as_str();
if self.regex_auth.is_match(name) {
let chain = builder
.set_session(self.session.clone_session())
.add_root_public_key(&self.root_key.as_public_key())
.load_integrity(TrustMode::Distributed)
.build()
.open(key)
.await?;
return Ok(OpenAction::DistributedChain { chain: chain });
}
if self.regex_cmd.is_match(name) {
// Build a secure session
let mut cmd_session = AteSessionUser::default();
cmd_session
.user
.add_read_key(&EncryptKey::generate(KeySize::Bit128));
// For command based chains that are already encryption there is no need
// to also add signatures which take lots of CPU power
let session_root_key = if wire_encryption.is_none() {
let key = PrivateSignKey::generate(KeySize::Bit128);
cmd_session.user.add_write_key(&key);
Some(key)
} else {
None
};
// Build the chain
builder = builder
.set_session(cmd_session.clone_session())
.temporal(true);
if let Some(session_root_key) = &session_root_key {
builder = builder.add_root_public_key(&session_root_key.as_public_key())
}
let chain = builder.build().open(key).await?;
// Add the services to this chain
service_auth_handlers(
&self.cfg,
cmd_session.clone(),
self.auth_url.clone(),
self.session.clone(),
self.web_key.clone(),
self.edge_key.clone(),
self.contract_key.clone(),
self.terms_and_conditions.clone(),
&Arc::clone(&chain),
)
.await?;
// Return the chain to the caller
return Ok(OpenAction::PrivateChain {
chain,
session: cmd_session,
});
}
Ok(OpenAction::Deny {
reason: format!(
"The chain-key ({}) does not match a valid chain supported by this server.",
key.to_string()
)
.to_string(),
})
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/service.rs | wasmer-auth/src/service.rs | #![allow(unused_imports)]
use async_trait::async_trait;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use ::ate::error::*;
use ::ate::prelude::*;
use ::ate::time::TimeKeeper;
use crate::helper::*;
use crate::model::*;
use crate::request::*;
pub struct AuthService {
pub auth_url: url::Url,
pub master_session: AteSessionUser,
pub web_key: EncryptKey,
pub edge_key: EncryptKey,
pub contract_key: EncryptKey,
pub time_keeper: TimeKeeper,
pub terms_and_conditions: Option<String>,
pub registry: Arc<Registry>,
}
impl AuthService {
pub async fn new(
cfg: &ConfAte,
auth_url: url::Url,
auth_session: AteSessionUser,
web_key: EncryptKey,
edge_key: EncryptKey,
contract_key: EncryptKey,
terms_and_conditions: Option<String>,
) -> Result<Arc<AuthService>, TimeError> {
let service = Arc::new(AuthService {
auth_url,
master_session: auth_session,
web_key,
edge_key,
contract_key,
time_keeper: TimeKeeper::new(cfg, 30000).await?,
registry: Registry::new(cfg)
.await
.temporal(true)
.keep_alive(Duration::from_secs(60))
.cement(),
terms_and_conditions,
});
Ok(service)
}
}
pub async fn service_auth_handlers(
cfg: &ConfAte,
cmd_session: AteSessionUser,
auth_url: url::Url,
auth_session: AteSessionUser,
web_key: EncryptKey,
edge_key: EncryptKey,
contract_key: EncryptKey,
terms_and_conditions: Option<String>,
chain: &Arc<Chain>,
) -> Result<(), TimeError> {
let service = AuthService::new(
cfg,
auth_url,
auth_session,
web_key,
edge_key,
contract_key,
terms_and_conditions,
)
.await?;
chain.add_service(&cmd_session, service.clone(), AuthService::process_login);
chain.add_service(&cmd_session, service.clone(), AuthService::process_sudo);
chain.add_service(&cmd_session, service.clone(), AuthService::process_reset);
chain.add_service(
&cmd_session,
service.clone(),
AuthService::process_create_user,
);
chain.add_service(
&cmd_session,
service.clone(),
AuthService::process_create_group,
);
chain.add_service(&cmd_session, service.clone(), AuthService::process_query);
chain.add_service(&cmd_session, service.clone(), AuthService::process_gather);
chain.add_service(
&cmd_session,
service.clone(),
AuthService::process_group_user_add,
);
chain.add_service(
&cmd_session,
service.clone(),
AuthService::process_group_user_remove,
);
chain.add_service(
&cmd_session,
service.clone(),
AuthService::process_group_details,
);
chain.add_service(
&cmd_session,
service.clone(),
AuthService::process_group_remove,
);
Ok(())
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/util.rs | wasmer-auth/src/util.rs | pub fn origin_url(url: &Option<url::Url>, postfix: &str) -> url::Url
{
origin_url_ext(url, postfix, false)
}
pub fn origin_url_ext(url: &Option<url::Url>, postfix: &str, force_insecure: bool) -> url::Url
{
let origin = if let Ok(origin) = std::env::var("ORIGIN") {
if origin.eq_ignore_ascii_case("localhost") {
"wasmer.sh".to_string()
} else {
origin
}
} else {
"wasmer.sh".to_string()
};
let scheme = if let Ok(location) = std::env::var("LOCATION") {
if location.starts_with("http://") || force_insecure {
"ws".to_string()
} else {
"wss".to_string()
}
} else {
"ws".to_string()
};
match url.clone() {
Some(a) => a,
None => url::Url::parse(format!("{}://{}/{}", scheme, origin, postfix).as_str()).unwrap()
}
} | rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/user.rs | wasmer-auth/src/cmd/user.rs | #![allow(unused_imports)]
use ate::prelude::*;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::cmd::*;
use crate::error::*;
use crate::helper::*;
use crate::opt::*;
use crate::prelude::*;
use crate::request::*;
pub async fn main_opts_user(
opts_user: OptsUser,
token: Option<String>,
token_path: Option<String>,
auth: url::Url,
) -> Result<(), AteError> {
match opts_user.action {
UserAction::Create(action) => {
let _session = main_create_user(action.email, action.password, auth).await?;
}
UserAction::Details => {
let session =
main_session_user(token.clone(), token_path.clone(), Some(auth.clone())).await?;
main_user_details(session).await?;
}
UserAction::Recover(action) => {
let _session = main_reset(
action.email,
action.recovery_code,
action.auth_code,
action.next_auth_code,
action.new_password,
auth,
)
.await?;
}
}
Ok(())
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/sudo.rs | wasmer-auth/src/cmd/sudo.rs | #![allow(unused_imports)]
use ate::prelude::*;
use chrono::Duration;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::error::*;
use crate::helper::*;
use crate::opt::*;
use crate::prelude::*;
use crate::request::*;
use super::*;
pub async fn main_session_sudo(
token_string: Option<String>,
token_file_path: Option<String>,
code: Option<String>,
auth_url: Option<url::Url>,
) -> Result<AteSessionSudo, SudoError> {
let session = main_session_start(token_string, token_file_path, auth_url.clone()).await?;
let session = match session {
AteSessionType::Group(a) => a.inner,
AteSessionType::User(a) => AteSessionInner::User(a),
AteSessionType::Sudo(a) => AteSessionInner::Sudo(a),
AteSessionType::Nothing => AteSessionInner::Nothing,
};
Ok(match session {
AteSessionInner::User(a) => {
if let Some(auth) = auth_url {
main_sudo(a, code, auth).await?
} else {
AteSessionSudo::default()
}
}
AteSessionInner::Sudo(a) => a,
AteSessionInner::Nothing => AteSessionSudo::new()
})
}
pub async fn sudo_command(
registry: &Registry,
session: &AteSessionUser,
authenticator_code: String,
auth: Url,
) -> Result<AteSessionSudo, SudoError> {
// Open a command chain
let chain = registry.open_cmd(&auth).await?;
// Create the sudo command
let login = SudoRequest {
session: session.clone(),
authenticator_code,
};
// Attempt the sudo request with a 10 second timeout
let response: Result<SudoResponse, SudoFailed> = chain.invoke(login).await?;
let result = response?;
// Success
Ok(result.authority)
}
pub async fn main_sudo(
session: AteSessionUser,
code: Option<String>,
auth: Url,
) -> Result<AteSessionSudo, SudoError> {
let registry = ate::mesh::Registry::new(&conf_cmd()).await.cement();
// Now we get the authenticator code and try again (but this time with sudo)
let code = match code {
Some(a) => a,
None => {
if !is_tty_stdin() {
bail!(SudoErrorKind::InvalidArguments);
}
// When no code is supplied we will ask for it
eprint!("Authenticator Code: ");
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect("Did not enter a valid code");
s.trim().to_string()
}
};
// Login using the authentication server which will give us a session with all the tokens
let response = sudo_command(®istry, &session, code.clone(), auth.clone()).await;
let ret = match response {
Ok(a) => a,
Err(SudoError(SudoErrorKind::AccountLocked(duration), _)) => {
if duration > Duration::days(1).to_std().unwrap() {
eprintln!(
"This account has been locked for {} days",
(duration.as_secs() as u64 / 86400u64)
);
} else if duration > Duration::hours(1).to_std().unwrap() {
eprintln!(
"This account has been locked for {} hours",
(duration.as_secs() as u64 / 3600u64)
);
} else if duration > Duration::minutes(1).to_std().unwrap() {
eprintln!(
"This account has been locked for {} minutes",
(duration.as_secs() as u64 / 60u64)
);
} else {
eprintln!(
"This account has been locked for {} seconds",
(duration.as_secs() as u64)
);
}
std::process::exit(1);
}
Err(SudoError(SudoErrorKind::WrongCode, _)) => {
eprintln!("The authentication code was incorrect");
eprintln!("(Warning! Repeated failed attempts will trigger a short ban)");
std::process::exit(1);
}
Err(SudoError(SudoErrorKind::NotFound(username), _)) => {
eprintln!("Account does not exist ({})", username);
std::process::exit(1);
}
Err(SudoError(SudoErrorKind::Unverified(username), _)) => {
eprintln!(
"The account ({}) has not yet been verified - please check your email.",
username
);
std::process::exit(1);
}
Err(err) => {
bail!(err);
}
};
Ok(ret)
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/create_user.rs | wasmer-auth/src/cmd/create_user.rs | #![allow(unused_imports)]
use ate::prelude::*;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::error::*;
use crate::helper::*;
use crate::opt::*;
use crate::prelude::*;
use crate::request::*;
#[allow(dead_code)]
pub async fn create_user_command(
registry: &Registry,
username: String,
password: String,
auth: Url,
accepted_terms: Option<String>,
) -> Result<CreateUserResponse, CreateError> {
// Open a command chain
let chain = registry.open_cmd(&auth).await?;
// 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 auth = match auth.domain() {
Some(a) => a.to_string(),
None => "ate".to_string(),
};
let request = CreateUserRequest {
auth,
email: username.clone(),
secret: read_key,
accepted_terms,
};
// Attempt the login request with a 10 second timeout
let response: Result<CreateUserResponse, CreateUserFailed> = chain.invoke(request).await?;
let result = response?;
debug!("key: {}", result.key);
Ok(result)
}
pub async fn main_create_user(
username: Option<String>,
password: Option<String>,
auth: Url,
) -> Result<CreateUserResponse, CreateError> {
let username = match username {
Some(a) => a,
None => {
#[cfg(not(feature = "force_tty"))]
if !is_tty_stdin() {
bail!(CreateErrorKind::InvalidArguments);
}
print!("Username: ");
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect("Did not enter a valid username");
s.trim().to_string()
}
};
let password = match password {
Some(a) => a,
None => {
#[cfg(not(feature = "force_tty"))]
if !is_tty_stdin() {
bail!(CreateErrorKind::InvalidArguments);
}
let ret1 = rpassword_wasi::prompt_password("Password: ").unwrap();
stdout().lock().flush()?;
let ret2 = rpassword_wasi::prompt_password("Password Again: ").unwrap();
if ret1 != ret2 {
bail!(CreateErrorKind::PasswordMismatch);
}
ret2
}
};
// Create a user using the authentication server which will give us a session with all the tokens
let registry = ate::mesh::Registry::new(&conf_cmd()).await.cement();
let result = match create_user_command(
®istry,
username.clone(),
password.clone(),
auth.clone(),
None,
)
.await
{
Ok(a) => a,
Err(CreateError(CreateErrorKind::AlreadyExists(msg), _)) => {
eprintln!("{}", msg);
std::process::exit(1);
}
Err(CreateError(CreateErrorKind::TermsAndConditions(terms), _)) => {
if !is_tty_stdin() {
bail!(CreateErrorKind::InvalidArguments);
}
// We need an agreement to the terms and conditions from the caller
println!("");
println!("{}", terms);
println!("");
println!(
"If you agree to the above terms and conditions then type the word 'agree' below"
);
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 account by specifically agreeing to the terms");
eprintln!("and conditions laid out above - this can only be confirmed if you");
eprintln!("specifically type the word 'agree' which you did not enter hence");
eprintln!("an account can not be created. If this is a mistake then please");
eprintln!("try again.");
std::process::exit(1);
}
// Try again but this time with an aggrement to the terms and conditions
create_user_command(®istry, username, password, auth, Some(terms)).await?
}
Err(err) => {
bail!(err);
}
};
if is_tty_stdout() {
println!("User created (id={})", result.key);
// Display the QR code
println!("");
if let Some(message_of_the_day) = &result.message_of_the_day {
println!("{}", message_of_the_day.as_str());
println!("");
}
println!("Below is your Google Authenticator QR code - scan it on your phone and");
println!("save it as this code is the only way you can recover the account.");
println!("");
println!("{}", result.qr_code);
}
Ok(result)
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/group.rs | wasmer-auth/src/cmd/group.rs | #![allow(unused_imports)]
use ate::prelude::*;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::cmd::*;
use crate::error::*;
use crate::helper::*;
use crate::opt::*;
use crate::prelude::*;
use crate::request::*;
pub async fn main_opts_group(
opts_group: OptsDomain,
token: Option<String>,
token_path: Option<String>,
auth: url::Url,
hint_group: &str,
) -> Result<(), AteError> {
match opts_group.action {
GroupAction::Create(action) => {
let session =
main_session_user(token.clone(), token_path.clone(), Some(auth.clone())).await?;
main_create_group(
Some(action.group),
auth,
Some(session.identity().to_string()),
hint_group,
)
.await?;
}
GroupAction::AddUser(action) => {
let session = main_session_group(
token.clone(),
token_path.clone(),
action.group.clone(),
true,
None,
Some(auth.clone()),
hint_group,
)
.await?;
main_group_user_add(
Some(action.role),
Some(action.username),
auth,
&session,
hint_group,
)
.await?;
}
GroupAction::RemoveUser(action) => {
let session = main_session_group(
token.clone(),
token_path.clone(),
action.group.clone(),
true,
None,
Some(auth.clone()),
hint_group,
)
.await?;
main_group_user_remove(
Some(action.role),
Some(action.username),
auth,
&session,
hint_group,
)
.await?;
}
GroupAction::RemoveGroup(action) => {
let session = main_session_group(
token.clone(),
token_path.clone(),
action.group.clone(),
true,
None,
Some(auth.clone()),
hint_group,
)
.await?;
main_group_remove(auth, &session, hint_group).await?;
}
GroupAction::Details(action) => {
if token.is_some() || token_path.is_some() {
let session = main_session_group(
token.clone(),
token_path.clone(),
action.group.clone(),
action.sudo,
None,
Some(auth.clone()),
hint_group,
)
.await?;
main_group_details(Some(action.group), auth, Some(&session), hint_group).await?;
} else {
main_group_details(Some(action.group), auth, None, hint_group).await?;
}
}
}
Ok(())
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/login.rs | wasmer-auth/src/cmd/login.rs | #![allow(unused_imports)]
use ate::prelude::*;
use chrono::Duration;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::error::*;
use crate::helper::*;
use crate::opt::*;
use crate::prelude::*;
use crate::request::*;
pub async fn login_command(
registry: &Registry,
username: String,
password: String,
verification_code: Option<String>,
auth: Url,
print_message_of_the_day: bool,
) -> Result<AteSessionUser, LoginError> {
// Open a command chain
let chain = registry.open_cmd(&auth).await?;
// 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,
};
// Attempt the login request with a 10 second timeout
trace!("invoking login (email={})", login.email);
let response: Result<LoginResponse, LoginFailed> = chain.invoke(login).await?;
let result = response?;
// Display the message of the day
if print_message_of_the_day {
if let Some(message_of_the_day) = result.message_of_the_day {
if is_tty_stderr() {
eprintln!("{}", message_of_the_day);
}
}
}
// Success
Ok(result.authority)
}
pub(crate) async fn main_session_start(
token_string: Option<String>,
token_file_path: Option<String>,
auth_url: Option<url::Url>,
) -> Result<AteSessionType, LoginError> {
// The session might come from a token_file
let mut session = None;
if session.is_none() {
if let Some(path) = token_file_path {
if token_string.is_some() {
eprintln!("You must not provide both a token string and a token file path - only specify one of them!");
std::process::exit(1);
}
let path = shellexpand::tilde(path.as_str()).to_string();
#[cfg(feature = "enable_full")]
if let Ok(token) = tokio::fs::read_to_string(path).await {
session = Some(b64_to_session(token));
}
#[cfg(not(feature = "enable_full"))]
if let Ok(token) = std::fs::read_to_string(path) {
session = Some(b64_to_session(token));
}
}
}
// The session might be supplied as a base64 string
if session.is_none() {
if let Some(token) = token_string {
session = Some(b64_to_session(token));
}
}
let session = match session {
Some(a) => a,
None => {
if let Some(auth) = auth_url.clone() {
AteSessionType::User(main_login(None, None, auth).await?)
} else {
AteSessionType::User(AteSessionUser::default())
}
}
};
Ok(session)
}
pub async fn main_session_prompt(auth_url: url::Url) -> Result<AteSessionUser, LoginError> {
main_session_user(None, None, Some(auth_url)).await
}
pub async fn main_session_user(
token_string: Option<String>,
token_file_path: Option<String>,
auth_url: Option<url::Url>,
) -> Result<AteSessionUser, LoginError> {
let session = main_session_start(token_string, token_file_path, auth_url.clone()).await?;
let session = match session {
AteSessionType::Group(a) => a.inner,
AteSessionType::User(a) => AteSessionInner::User(a),
AteSessionType::Sudo(a) => AteSessionInner::Sudo(a),
AteSessionType::Nothing => AteSessionInner::Nothing,
};
Ok(match session {
AteSessionInner::User(a) => a,
AteSessionInner::Sudo(a) => a.inner,
AteSessionInner::Nothing => AteSessionUser::new()
})
}
pub async fn main_user_details(session: AteSessionUser) -> Result<(), LoginError> {
println!("# User Details");
println!("");
println!("Name: {}", session.identity);
if let Some(uid) = session.user.uid() {
println!("UID: {}", uid);
}
Ok(())
}
pub async fn main_login(
username: Option<String>,
password: Option<String>,
auth: Url,
) -> Result<AteSessionUser, LoginError> {
let username = match username {
Some(a) => a,
None => {
if !is_tty_stdin() {
bail!(LoginErrorKind::InvalidArguments);
}
eprint!("Username: ");
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect("Did not enter a valid username");
s.trim().to_string()
}
};
let password = match password {
Some(a) => a,
None => {
if !is_tty_stdin() {
bail!(LoginErrorKind::InvalidArguments);
}
// When no password is supplied we will ask for both the password and the code
let pass = rpassword_wasi::prompt_password("Password: ").unwrap();
pass.trim().to_string()
}
};
// Login using the authentication server which will give us a session with all the tokens
let registry = ate::mesh::Registry::new(&conf_cmd()).await.cement();
let response = login_command(
®istry,
username.clone(),
password.clone(),
None,
auth.clone(),
true,
)
.await;
let ret = handle_login_response(®istry, response, username, password, auth).await?;
Ok(ret)
}
pub(crate) async fn handle_login_response(
registry: &Registry,
mut response: Result<AteSessionUser, LoginError>,
username: String,
password: String,
auth: Url,
) -> Result<AteSessionUser, LoginError> {
// If we are currently unverified then prompt for the verification code
let mut was_unverified = false;
if let Err(LoginError(LoginErrorKind::Unverified(_), _)) = &response {
was_unverified = true;
if !is_tty_stdin() {
bail!(LoginErrorKind::InvalidArguments);
}
// When no code is supplied we will ask for it
eprintln!("Check your email for a verification code and enter it below");
eprint!("Verification Code: ");
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect("Did not enter a valid code");
let verification_code = s.trim().to_string();
// Perform the login again but also supply the verification code
response = login_command(
registry,
username,
password,
Some(verification_code),
auth,
true,
)
.await;
}
match response {
Ok(a) => Ok(a),
Err(LoginError(LoginErrorKind::AccountLocked(duration), _)) => {
if duration > Duration::days(1).to_std().unwrap() {
eprintln!(
"This account has been locked for {} days",
(duration.as_secs() as u64 / 86400u64)
);
} else if duration > Duration::hours(1).to_std().unwrap() {
eprintln!(
"This account has been locked for {} hours",
(duration.as_secs() as u64 / 3600u64)
);
} else if duration > Duration::minutes(1).to_std().unwrap() {
eprintln!(
"This account has been locked for {} minutes",
(duration.as_secs() as u64 / 60u64)
);
} else {
eprintln!(
"This account has been locked for {} seconds",
(duration.as_secs() as u64)
);
}
std::process::exit(1);
}
Err(LoginError(LoginErrorKind::WrongPassword, _)) => {
if was_unverified {
eprintln!("Either the password or verification code was incorrect");
} else {
eprintln!("The password was incorrect");
}
eprintln!("(Warning! Repeated failed attempts will trigger a short ban)");
std::process::exit(1);
}
Err(LoginError(LoginErrorKind::NotFound(username), _)) => {
eprintln!("Account does not exist ({})", username);
std::process::exit(1);
}
Err(LoginError(LoginErrorKind::Unverified(username), _)) => {
eprintln!(
"The account ({}) has not yet been verified - please check your email.",
username
);
std::process::exit(1);
}
Err(err) => {
bail!(err);
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/database.rs | wasmer-auth/src/cmd/database.rs | #![allow(unused_imports)]
use ate::prelude::*;
use ate::utils::LoadProgress;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::cmd::*;
use crate::error::*;
use crate::helper::*;
use crate::opt::*;
use crate::prelude::*;
use crate::request::*;
pub async fn main_opts_db(
opts_db: OptsDatabase,
token: Option<String>,
token_path: Option<String>,
auth: url::Url,
hint_group: &str,
) -> Result<(), AteError> {
let db_name = match &opts_db.action {
DatabaseAction::Truncate(action) => action.name.clone(),
DatabaseAction::Details(action) => action.name.clone(),
};
let group_name = match db_name.split("/").map(|a| a.to_string()).next() {
Some(a) => a,
None => {
eprintln!("The database name is invalid");
std::process::exit(1);
}
};
// Build the conf and registry
let conf = ConfAte::default();
let session = main_session_group(
token.clone(),
token_path.clone(),
group_name.clone(),
true,
None,
Some(auth.clone()),
hint_group,
)
.await?;
let registry = ate::mesh::Registry::new(&conf).await.temporal(true);
// Create a progress bar loader
let progress_local = LoadProgress::new(std::io::stderr());
let progress_remote = LoadProgress::new(std::io::stderr());
// Load the chain
let remote = crate::prelude::origin_url(&opts_db.remote, "db");
let guard = registry
.open_ext(
&remote,
&ChainKey::from(db_name.clone()),
false,
progress_local,
progress_remote,
)
.await?;
let db = guard.as_arc();
match opts_db.action {
DatabaseAction::Details(_action) => {
let guard = db.metrics().lock().unwrap();
println!("Database Chain Details");
println!("======================");
println!("Remote: {}", remote);
println!("Group Name: {}", group_name);
println!("DB Name: {}", db_name);
println!("Size: {}", guard.chain_size);
}
DatabaseAction::Truncate(_action) => {
print!("Deleting all events...");
let dio = db.dio_full(&session).await;
let mut ids = dio.dio.all_keys().await;
while ids.is_empty() == false {
print!(".");
for _ in 0..100 {
let id = match ids.pop() {
Some(a) => a,
None => break,
};
let _ = dio.delete(&id).await;
}
dio.commit().await?;
}
println!("Done");
}
}
Ok(())
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/group_details.rs | wasmer-auth/src/cmd/group_details.rs | #![allow(unused_imports)]
use ate::prelude::*;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::error::*;
use crate::helper::*;
use crate::opt::*;
use crate::prelude::*;
use crate::request::*;
pub async fn group_details_command(
registry: &Registry,
group: String,
auth: Url,
session: Option<&AteSessionGroup>,
) -> Result<GroupDetailsResponse, GroupDetailsError> {
// Open a command chain
let chain = registry.open_cmd(&auth).await?;
// Make the create request and fire it over to the authentication server
let create = GroupDetailsRequest {
group,
session: session.map(|s| s.clone()),
};
let response: Result<GroupDetailsResponse, GroupDetailsFailed> = chain.invoke(create).await?;
let result = response?;
debug!("key: {}", result.key);
Ok(result)
}
pub async fn main_group_details(
group: Option<String>,
auth: Url,
session: Option<&AteSessionGroup>,
hint_group: &str,
) -> Result<(), GroupDetailsError> {
let group = match group {
Some(a) => a,
None => {
print!("{}: ", hint_group);
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect(format!("Did not enter a valid {}", hint_group.to_lowercase()).as_str());
s.trim().to_string()
}
};
// Looks up the details of a group and prints them to the console
let registry = ate::mesh::Registry::new(&conf_cmd()).await.cement();
let result = group_details_command(®istry, group, auth, session).await?;
println!("# Group Details");
println!("");
println!("Key: {}", result.key);
println!("Name: {}", result.name);
println!("GID: {}", result.gid);
println!("");
println!("# Roles");
println!("");
for role in result.roles {
println!("## {}", role.name);
println!("");
println!("read: {}", role.read);
println!("pread: {}", role.private_read);
println!("write: {}", role.write);
println!("");
if role.hidden {
println!("[membership hidden]")
} else {
println!("[membership]");
for member in role.members {
println!("- {}", member);
}
}
println!("");
}
Ok(())
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/mod.rs | wasmer-auth/src/cmd/mod.rs | pub mod create_group;
pub mod create_user;
pub mod database;
pub mod gather;
pub mod group;
pub mod group_details;
pub mod group_remove;
pub mod group_user_add;
pub mod group_user_remove;
pub mod login;
pub mod query;
pub mod reset;
pub mod sudo;
pub mod token;
pub mod user;
pub use create_group::*;
pub use create_user::*;
pub use database::*;
pub use gather::*;
pub use group::*;
pub use group_details::*;
pub use group_remove::*;
pub use group_user_add::*;
pub use group_user_remove::*;
pub use login::*;
pub use query::*;
pub use reset::*;
pub use sudo::*;
pub use token::*;
pub use user::*;
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/create_group.rs | wasmer-auth/src/cmd/create_group.rs | #![allow(unused_imports)]
use ate::prelude::*;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::error::*;
use crate::helper::*;
use crate::opt::*;
use crate::prelude::*;
use crate::request::*;
pub async fn create_group_command(
registry: &Registry,
group: String,
auth: Url,
username: String,
) -> Result<CreateGroupResponse, CreateError> {
// Open a command chain
let chain = registry.open_cmd(&auth).await?;
// Make the create request and fire it over to the authentication server
let create = CreateGroupRequest {
group,
identity: username.clone(),
};
let response: Result<CreateGroupResponse, CreateGroupFailed> = chain.invoke(create).await?;
let result = response?;
debug!("key: {}", result.key);
Ok(result)
}
pub async fn main_create_group_prelude(
group: Option<String>,
username: Option<String>,
hint_group: &str,
) -> Result<(String, String), CreateError> {
let group = match group {
Some(a) => a,
None => {
#[cfg(not(feature = "force_tty"))]
if !is_tty_stdin() {
bail!(CreateErrorKind::InvalidArguments);
}
print!("{}: ", hint_group);
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect("Did not enter a valid group");
s.trim().to_string()
}
};
let username = match username {
Some(a) => a,
None => {
#[cfg(not(feature = "force_tty"))]
if !is_tty_stdin() {
bail!(CreateErrorKind::InvalidArguments);
}
print!("Username: ");
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect("Did not enter a valid username");
s.trim().to_string()
}
};
Ok((group, username))
}
pub async fn main_create_group(
group: Option<String>,
auth: Url,
username: Option<String>,
hint_group: &str,
) -> Result<AteSessionGroup, CreateError> {
let (group, username) = main_create_group_prelude(group, username, hint_group).await?;
// Create a user using the authentication server which will give us a session with all the tokens
let registry = ate::mesh::Registry::new(&conf_cmd()).await.cement();
let result = match create_group_command(®istry, group, auth, username).await {
Ok(a) => a,
Err(CreateError(CreateErrorKind::OperatorBanned, _)) => {
eprintln!("Failed as the callers account is currently banned");
std::process::exit(1);
}
Err(CreateError(CreateErrorKind::OperatorNotFound, _)) => {
eprintln!("Failed as the callers account could not be found");
std::process::exit(1);
}
Err(CreateError(CreateErrorKind::AccountSuspended, _)) => {
eprintln!("Failed as the callers account is currently suspended");
std::process::exit(1);
}
Err(CreateError(CreateErrorKind::ValidationError(reason), _)) => {
eprintln!("{}", reason);
std::process::exit(1);
}
Err(CreateError(CreateErrorKind::AlreadyExists(msg), _)) => {
eprintln!("{}", msg);
std::process::exit(1);
}
Err(CreateError(CreateErrorKind::InvalidName(msg), _)) => {
eprintln!("{}", msg);
std::process::exit(1);
}
Err(err) => {
bail!(err);
}
};
println!("{} created (id={})", hint_group, result.key);
Ok(result.session)
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/group_user_add.rs | wasmer-auth/src/cmd/group_user_add.rs | #![allow(unused_imports)]
use ate::prelude::*;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::cmd::*;
use crate::error::*;
use crate::helper::*;
use crate::opt::*;
use crate::prelude::*;
use crate::request::*;
pub async fn group_user_add_command(
registry: &Registry,
session: &AteSessionGroup,
purpose: AteRolePurpose,
username: String,
auth: Url,
) -> Result<GroupUserAddResponse, GroupUserAddError> {
// Open a command chain
let group = session.identity().to_string();
let chain = registry.open_cmd(&auth).await?;
// First we query the user that needs to be added so that we can get their public encrypt key
let query = query_command(registry, username.clone(), auth).await?;
// Determine what level of authentication we will associate the role with
let who_key = match purpose {
AteRolePurpose::Owner => query.advert.sudo_encrypt,
_ => query.advert.nominal_encrypt,
};
// Make the create request and fire it over to the authentication server
let create = GroupUserAddRequest {
group,
session: session.clone(),
who_name: username.clone(),
who_key,
purpose,
};
let response: Result<GroupUserAddResponse, GroupUserAddFailed> = chain.invoke(create).await?;
let result = response?;
debug!("key: {}", result.key);
Ok(result)
}
pub async fn main_group_user_add(
purpose: Option<AteRolePurpose>,
username: Option<String>,
auth: Url,
session: &AteSessionGroup,
hint_group: &str,
) -> Result<(), GroupUserAddError> {
let purpose = match purpose {
Some(a) => a,
None => {
print!("Role: ");
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect("Did not enter a valid role purpose");
match AteRolePurpose::from_str(s.trim()) {
Ok(a) => a,
Err(_err) => {
bail!(GroupUserAddErrorKind::InvalidPurpose);
}
}
}
};
let username = match username {
Some(a) => a,
None => {
print!("Username: ");
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect("Did not enter a valid username");
s.trim().to_string()
}
};
// Add a user in a group using the authentication server
let registry = ate::mesh::Registry::new(&conf_cmd()).await.cement();
let result = group_user_add_command(®istry, &session, purpose, username, auth).await?;
println!("{} user added (id={})", result.key, hint_group);
Ok(())
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/query.rs | wasmer-auth/src/cmd/query.rs | #![allow(unused_imports)]
use ate::prelude::*;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::error::*;
use crate::helper::*;
use crate::model::Advert;
use crate::opt::*;
use crate::prelude::*;
use crate::request::*;
pub async fn query_command(
registry: &Registry,
username: String,
auth: Url,
) -> Result<QueryResponse, QueryError> {
// Open a command chain
let chain = registry.open_cmd(&auth).await?;
// Create the query command
let query = QueryRequest {
identity: username.clone(),
};
// Attempt the login request with a 10 second timeout
let response: Result<QueryResponse, QueryFailed> = chain.invoke(query).await?;
let result = response?;
//debug!("advert: {:?}", result.advert);
Ok(result)
}
pub async fn main_query(username: Option<String>, auth: Url) -> Result<Advert, QueryError> {
let username = match username {
Some(a) => a,
None => {
print!("Username: ");
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect("Did not enter a valid username");
s.trim().to_string()
}
};
let registry = ate::mesh::Registry::new(&conf_cmd()).await.cement();
let result = query_command(®istry, username, auth).await?;
Ok(result.advert)
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/gather.rs | wasmer-auth/src/cmd/gather.rs | #![allow(unused_imports)]
use ate::prelude::*;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::error::*;
use crate::helper::*;
use crate::opt::*;
use crate::prelude::*;
use crate::request::*;
use super::*;
pub async fn impersonate_command(
registry: &Registry,
group: String,
session: AteSessionInner,
auth: Url,
) -> Result<AteSessionGroup, GatherError> {
let ret = gather_command(registry, group, session, auth).await?;
let ret = AteSessionGroup {
inner: AteSessionInner::Nothing,
group: ret.group
};
Ok(ret)
}
pub async fn gather_command(
registry: &Registry,
group: String,
session: AteSessionInner,
auth: Url,
) -> Result<AteSessionGroup, GatherError> {
// If the group is localhost then obviously don't try and gather for it
if group == "localhost" {
bail!(GatherErrorKind::NotFound(group));
}
// Open a command chain
let chain = registry.open_cmd(&auth).await?;
// Create the gather command
let gather = GatherRequest {
group: group.clone(),
session,
};
// Attempt the gather request with a 10 second timeout
let response: Result<GatherResponse, GatherFailed> = chain.invoke(gather).await?;
let result = response?;
Ok(result.authority)
}
pub async fn main_session_group(
token_string: Option<String>,
token_file_path: Option<String>,
group: String,
sudo: bool,
code: Option<String>,
auth_url: Option<url::Url>,
hint_group: &str,
) -> Result<AteSessionGroup, GatherError> {
main_session_group_ext(token_string, token_file_path, group, sudo, code, auth_url, hint_group, false).await
}
pub async fn main_session_group_ext(
token_string: Option<String>,
token_file_path: Option<String>,
group: String,
sudo: bool,
code: Option<String>,
auth_url: Option<url::Url>,
hint_group: &str,
save: bool,
) -> Result<AteSessionGroup, GatherError> {
let session = main_session_start(token_string, token_file_path.clone(), auth_url.clone()).await?;
let mut session = match session {
AteSessionType::Group(a) => {
if a.group.name == group {
return Ok(a);
}
a.inner
}
AteSessionType::User(a) => AteSessionInner::User(a),
AteSessionType::Sudo(a) => AteSessionInner::Sudo(a),
AteSessionType::Nothing => AteSessionInner::Nothing,
};
if sudo {
session = match session {
AteSessionInner::User(a) => {
if let Some(auth) = auth_url.clone() {
AteSessionInner::Sudo(main_sudo(a, code, auth).await?)
} else {
AteSessionInner::User(a)
}
}
a => a,
};
}
if save {
if let Some(token_file_path) = token_file_path.clone() {
let token = session_to_b64(session.clone().into())?;
save_token(token, token_file_path)?;
}
}
if let Some(auth) = auth_url {
Ok(main_gather(Some(group), session, auth, hint_group).await?)
} else {
Ok(AteSessionGroup::new(session, group))
}
}
pub async fn main_gather(
group: Option<String>,
session: AteSessionInner,
auth: Url,
hint_group: &str,
) -> Result<AteSessionGroup, GatherError> {
let group = match group {
Some(a) => a,
None => {
eprint!("{}: ", hint_group);
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect(format!("Did not enter a valid {}", hint_group.to_lowercase()).as_str());
s.trim().to_string()
}
};
// Gather using the authentication server which will give us a new session with the extra tokens
let registry = ate::mesh::Registry::new(&conf_cmd()).await.cement();
let session = gather_command(®istry, group, session, auth).await?;
Ok(session)
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/group_remove.rs | wasmer-auth/src/cmd/group_remove.rs | #![allow(unused_imports)]
use ate::prelude::*;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::cmd::*;
use crate::error::*;
use crate::helper::*;
use crate::opt::*;
use crate::prelude::*;
use crate::request::*;
pub async fn group_remove_command(
registry: &Registry,
session: &AteSessionGroup,
auth: Url,
) -> Result<GroupRemoveResponse, GroupRemoveError> {
// Open a command chain
let group = session.identity().to_string();
let chain = registry.open_cmd(&auth).await?;
// Make the remove request and fire it over to the authentication server
let create = GroupRemoveRequest {
group,
session: session.clone(),
};
let response: Result<GroupRemoveResponse, GroupRemoveFailed> = chain.invoke(create).await?;
let result = response?;
debug!("key: {}", result.key);
Ok(result)
}
pub async fn main_group_remove(
auth: Url,
session: &AteSessionGroup,
hint_group: &str,
) -> Result<(), GroupRemoveError> {
// Remove a user from a group using the authentication server
let registry = ate::mesh::Registry::new(&conf_cmd()).await.cement();
let result = group_remove_command(®istry, &session, auth).await?;
println!("{} removed (id={})", hint_group, result.key);
Ok(())
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/reset.rs | wasmer-auth/src/cmd/reset.rs | #![allow(unused_imports)]
use ate::prelude::*;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::error::*;
use crate::helper::*;
use crate::opt::*;
use crate::prelude::*;
use crate::request::*;
pub async fn reset_command(
registry: &Registry,
email: String,
new_password: String,
recovery_key: EncryptKey,
sudo_code: String,
sudo_code_2: String,
auth: Url,
) -> Result<ResetResponse, ResetError> {
// Open a command chain
let chain = registry.open_cmd(&auth).await?;
// 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:{}:", email);
let new_secret = password_to_read_key(&prefix, &new_password, 15, KeySize::Bit192);
// Create the query command
let auth = match auth.domain() {
Some(a) => a.to_string(),
None => "ate".to_string(),
};
let reset = ResetRequest {
email,
auth,
new_secret,
recovery_key,
sudo_code,
sudo_code_2,
};
let response: Result<ResetResponse, ResetFailed> = chain.invoke(reset).await?;
let result = response?;
Ok(result)
}
pub async fn main_reset(
username: Option<String>,
recovery_code: Option<String>,
sudo_code: Option<String>,
sudo_code_2: Option<String>,
new_password: Option<String>,
auth: Url,
) -> Result<ResetResponse, ResetError> {
if recovery_code.is_none() || sudo_code.is_none() {
eprintln!(
r#"# Account Reset Process
You will need *both* of the following to reset your account:
- Your 'recovery code' that you saved during account creation - if not - then
the recovery code is likely still in your email inbox.
- Two sequential 'authenticator code' response challenges from your mobile app.
"#
);
}
let username = match username {
Some(a) => a,
None => {
print!("Username: ");
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect("Did not enter a valid username");
s.trim().to_string()
}
};
let recovery_code = match recovery_code {
Some(a) => a,
None => {
print!("Recovery Code: ");
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect("Did not enter a valid recovery code");
s.trim().to_string()
}
};
let recovery_prefix = format!("recover-login:{}:", username);
let recovery_key = password_to_read_key(&recovery_prefix, &recovery_code, 15, KeySize::Bit192);
let new_password = match new_password {
Some(a) => a,
None => {
let ret1 = rpassword_wasi::prompt_password("New Password: ").unwrap();
let ret2 = rpassword_wasi::prompt_password("New Password Again: ").unwrap();
if ret1 != ret2 {
bail!(ResetErrorKind::PasswordMismatch);
}
ret2
}
};
let sudo_code = match sudo_code {
Some(a) => a,
None => {
print!("Authenticator Code: ");
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect("Did not enter a valid authenticator code");
s.trim().to_string()
}
};
let sudo_code_2 = match sudo_code_2 {
Some(a) => a,
None => {
print!("Next Authenticator Code: ");
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect("Did not enter a valid authenticator code");
s = s.trim().to_string();
if sudo_code == s {
bail!(ResetErrorKind::AuthenticatorCodeEqual);
}
s
}
};
let registry = ate::mesh::Registry::new(&conf_cmd()).await.cement();
let result = match reset_command(
®istry,
username,
new_password,
recovery_key,
sudo_code,
sudo_code_2,
auth,
)
.await
{
Ok(a) => a,
Err(err) => {
bail!(err);
}
};
if is_tty_stdout() {
println!("Account reset (id={})", result.key);
// Display the QR code
println!("");
if let Some(message_of_the_day) = &result.message_of_the_day {
println!("{}", message_of_the_day.as_str());
println!("");
}
println!("Below is your new Google Authenticator QR code - scan it on your phone and");
println!("save it as this code is the only way you can recover the account another time.");
println!("");
println!("{}", result.qr_code);
}
Ok(result)
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/group_user_remove.rs | wasmer-auth/src/cmd/group_user_remove.rs | #![allow(unused_imports)]
use ate::prelude::*;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::cmd::*;
use crate::error::*;
use crate::helper::*;
use crate::opt::*;
use crate::prelude::*;
use crate::request::*;
pub async fn group_user_remove_command(
registry: &Registry,
session: &AteSessionGroup,
purpose: AteRolePurpose,
username: String,
auth: Url,
) -> Result<GroupUserRemoveResponse, GroupUserRemoveError> {
// Open a command chain
let group = session.identity().to_string();
let chain = registry.open_cmd(&auth).await?;
// First we query the user that needs to be removed so that we can get their public encrypt key
let query = query_command(registry, username, auth).await?;
// Determine what level of authentication we will associate the role with
let who = match purpose {
AteRolePurpose::Owner => query.advert.sudo_encrypt,
_ => query.advert.nominal_encrypt,
};
// Make the create request and fire it over to the authentication server
let create = GroupUserRemoveRequest {
group,
session: session.clone(),
who: who.hash(),
purpose,
};
let response: Result<GroupUserRemoveResponse, GroupUserRemoveFailed> =
chain.invoke(create).await?;
let result = response?;
debug!("key: {}", result.key);
Ok(result)
}
pub async fn main_group_user_remove(
purpose: Option<AteRolePurpose>,
username: Option<String>,
auth: Url,
session: &AteSessionGroup,
hint_group: &str,
) -> Result<(), GroupUserRemoveError> {
let purpose = match purpose {
Some(a) => a,
None => {
print!("Role: ");
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect("Did not enter a valid role purpose");
match AteRolePurpose::from_str(s.trim()) {
Ok(a) => a,
Err(_err) => {
bail!(GroupUserRemoveErrorKind::InvalidPurpose);
}
}
}
};
let username = match username {
Some(a) => a,
None => {
print!("Username: ");
stdout().lock().flush()?;
let mut s = String::new();
std::io::stdin()
.read_line(&mut s)
.expect("Did not enter a valid username");
s.trim().to_string()
}
};
// Remove a user from a group using the authentication server
let registry = ate::mesh::Registry::new(&conf_cmd()).await.cement();
let result = group_user_remove_command(®istry, &session, purpose, username, auth).await?;
println!("{} user removed (id={})", hint_group, result.key);
Ok(())
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/cmd/token.rs | wasmer-auth/src/cmd/token.rs | #![allow(unused_imports)]
use ate::prelude::*;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use crate::cmd::*;
use crate::error::*;
use crate::helper::*;
use crate::opt::*;
use crate::prelude::*;
use crate::request::*;
pub async fn main_opts_token(
opts_token: OptsToken,
token: Option<String>,
token_path: Option<String>,
auth: url::Url,
hint_group: &str,
) -> Result<(), AteError> {
match opts_token.action {
TokenAction::Generate(action) => {
let session = main_login(action.email, action.password, auth).await?;
if is_tty_stdout() {
eprintln!("The token string below can be used to secure your file system.\n");
}
let session: AteSessionType = session.into();
println!("{}", session_to_b64(session).unwrap());
}
TokenAction::Sudo(action) => {
let session = main_login(action.email, action.password, auth.clone()).await?;
let session = main_sudo(session, action.code, auth).await?;
if is_tty_stdout() {
eprintln!("The token string below can be used to secure your file system.\n");
}
let session: AteSessionType = session.into();
println!("{}", session_to_b64(session).unwrap());
}
TokenAction::Gather(action) => {
let session = main_session_group(
token.clone(),
token_path.clone(),
action.group,
action.sudo,
None,
Some(auth.clone()),
hint_group,
)
.await?;
if is_tty_stdout() {
eprintln!("The token string below can be used to secure your file system.\n");
}
let session: AteSessionType = session.into();
if action.summary {
println!("{}", session);
} else if action.human {
println!("{}", serde_json::to_string_pretty(&session).unwrap());
} else {
println!("{}", session_to_b64(session).unwrap());
}
}
TokenAction::View(_action) => {
let session =
main_session_user(token.clone(), token_path.clone(), Some(auth.clone())).await?;
eprintln!("The token contains the following claims.\n");
println!("{}", session);
}
}
Ok(())
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/work/sudo.rs | wasmer-auth/src/work/sudo.rs | #![allow(unused_imports)]
use chrono::Duration;
use error_chain::bail;
use std::io::stdout;
use std::io::Write;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use ate::error::LoadError;
use ate::error::TransformError;
use ate::prelude::*;
use crate::error::*;
use crate::helper::*;
use crate::helper::*;
use crate::model::*;
use crate::prelude::*;
use crate::request::*;
use crate::service::AuthService;
use super::login::*;
impl AuthService {
pub async fn process_sudo(
self: Arc<Self>,
request: SudoRequest,
) -> Result<SudoResponse, SudoFailed> {
info!("sudo attempt: {}", request.session.identity());
// Get token
let identity = request.session.identity().to_string();
let token = match &request.session.token {
Some(a) => a,
None => {
warn!("login attempt denied ({}) - no token supplied", identity);
return Err(SudoFailed::MissingToken);
}
};
// Load the master key which will be used to encrypt the group so that only
// the authentication server can access it
let master_key = match self.master_key() {
Some(a) => a,
None => {
return Err(SudoFailed::NoMasterKey);
}
};
// Extra the original super key that was used to access the user
let super_key = token.unwrap(&master_key)?;
// Create the super session
let mut super_session = self.master_session.clone();
super_session.user.add_read_key(&super_key);
let (super_super_key, super_token) = match self.compute_master_key(&super_key) {
Some(a) => a,
None => {
warn!("login attempt denied ({}) - no master key (sudo)", identity);
return Err(SudoFailed::NoMasterKey);
}
};
super_session.user.add_read_key(&super_super_key);
super_session.token = Some(super_token);
// Compute which chain the user should exist within
let chain_key = chain_key_4hex(identity.as_str(), Some("redo"));
let chain = self.registry.open(&self.auth_url, &chain_key, true).await?;
let dio = chain.dio_full(&super_session).await;
// Attempt to load the object (if it fails we will tell the caller)
let user_key = PrimaryKey::from(identity.clone());
let mut user = match dio.load::<User>(&user_key).await {
Ok(a) => a,
Err(err) => {
warn!("login attempt denied ({}) - error - ", err);
bail!(err);
}
};
// Check if the account is locked or not yet verified
match user.status.clone() {
UserStatus::Locked(until) => {
let local_now = chrono::Local::now();
let utc_now = local_now.with_timezone(&chrono::Utc);
if until > utc_now {
let duration = until - utc_now;
warn!(
"login attempt denied ({}) - account locked until {}",
identity, until
);
return Err(SudoFailed::AccountLocked(duration.to_std().unwrap()));
}
}
UserStatus::Unverified => {
warn!("login attempt denied ({}) - unverified", identity);
return Err(SudoFailed::Unverified(identity));
}
UserStatus::Nominal => {}
};
// If a google authenticator code has been supplied then we need to try and load the
// extra permissions from elevated rights
let session = {
// Load the sudo object
let mut user = user.as_mut();
if let Some(mut sudo) = match user.sudo.load_mut().await {
Ok(a) => a,
Err(LoadError(LoadErrorKind::NotFound(_), _)) => {
warn!("login attempt denied ({}) - user not found", identity);
return Err(SudoFailed::UserNotFound(identity));
}
Err(err) => {
bail!(err);
}
} {
// Check the code matches the authenticator code
self.time_keeper.wait_for_high_accuracy().await;
let time = self.time_keeper.current_timestamp_as_duration()?;
let time = time.as_secs() / 30;
let google_auth = google_authenticator::GoogleAuthenticator::new();
if google_auth.verify_code(
sudo.secret.as_str(),
request.authenticator_code.as_str(),
3,
time,
) {
debug!("code authenticated");
} else {
// Increment the failed count - every 5 failed attempts then
// ban the user for 30 mins to 1 day depending on severity.
sudo.as_mut().failed_attempts = sudo.failed_attempts + 1;
if sudo.failed_attempts % 5 == 0 {
let ban_time = if sudo.failed_attempts <= 5 {
Duration::seconds(30)
} else if sudo.failed_attempts <= 10 {
Duration::minutes(5)
} else if sudo.failed_attempts <= 15 {
Duration::hours(1)
} else {
Duration::days(1)
};
let local_now = chrono::Local::now();
let utc_now = local_now.with_timezone(&chrono::Utc);
if let Some(utc_ban) = utc_now.checked_add_signed(ban_time) {
user.status = UserStatus::Locked(utc_ban);
}
}
dio.commit().await?;
// Notify the caller that the login attempt has failed
warn!(
"login attempt denied ({}) - wrong code - attempts={}",
identity, sudo.failed_attempts
);
return Err(SudoFailed::WrongCode);
}
// If there are any failed attempts to login then clear them
if sudo.failed_attempts > 0 {
sudo.as_mut().failed_attempts = 0;
}
user.status = UserStatus::Nominal;
// Add the extra authentication objects from the sudo
compute_sudo_auth(&sudo.take(), request.session.clone())
} else {
warn!(
"login attempt denied ({}) - user not found (sudo)",
identity
);
return Err(SudoFailed::UserNotFound(identity));
}
};
dio.commit().await?;
// Return the session that can be used to access this user
info!("login attempt accepted ({})", identity);
Ok(SudoResponse { authority: session })
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/work/create_user.rs | wasmer-auth/src/work/create_user.rs | #![allow(unused_imports)]
use error_chain::bail;
use once_cell::sync::Lazy;
use qrcode::render::unicode;
use qrcode::QrCode;
use regex::Regex;
use std::io::stdout;
use std::io::Write;
use std::ops::Deref;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use ate::error::LoadError;
use ate::prelude::*;
use ate::utils::chain_key_4hex;
use crate::error::*;
use crate::helper::*;
use crate::model::*;
use crate::prelude::*;
use crate::request::*;
use crate::service::AuthService;
static BANNED_USERNAMES: Lazy<Vec<&'static str>> =
Lazy::new(|| vec!["nobody", "admin", "support", "help", "root"]);
impl AuthService {
pub async fn process_create_user(
self: Arc<Self>,
request: CreateUserRequest,
) -> Result<CreateUserResponse, CreateUserFailed> {
Ok(self
.process_create_user_internal(request, UserStatus::Nominal)
.await?
.0)
}
pub async fn process_create_user_internal(
self: Arc<Self>,
request: CreateUserRequest,
initial_status: UserStatus,
) -> Result<(CreateUserResponse, DaoMut<User>), CreateUserFailed> {
info!("create user: {}", request.email);
// Check the username matches the regex
let regex = Regex::new("^([a-z0-9\\.!#$%&'*+/=?^_`{|}~-]{1,})@([a-z0-9\\.!#$%&'*+/=?^_`{|}~-]{1,}).([a-z0-9\\.!#$%&'*+/=?^_`{|}~-]{1,})$").unwrap();
if regex.is_match(request.email.as_str()) == false {
warn!("invalid email address - {}", request.email);
return Err(CreateUserFailed::InvalidEmail);
}
// Get the master write key
let master_write_key = match self.master_session.user.write_keys().next() {
Some(a) => a.clone(),
None => {
warn!("no master write key");
return Err(CreateUserFailed::NoMasterKey);
}
};
// If the username is on the banned list then dont allow it
if BANNED_USERNAMES.contains(&request.email.as_str()) {
warn!("banned username - {}", request.email);
return Err(CreateUserFailed::InvalidEmail);
}
// Compute the super_key, super_super_key (elevated rights) and the super_session
let key_size = request.secret.size();
let (super_key, token) = match self.compute_master_key(&request.secret) {
Some(a) => a,
None => {
warn!("failed to generate super key");
return Err(CreateUserFailed::NoMasterKey);
}
};
let (super_super_key, super_token) = match self.compute_master_key(&super_key) {
Some(a) => a,
None => {
warn!("failed to generate super super key");
return Err(CreateUserFailed::NoMasterKey);
}
};
let mut super_session = self.master_session.clone();
super_session.user.add_read_key(&super_key);
super_session.user.add_read_key(&super_super_key);
super_session.token = Some(super_token);
// Generate the recovery code
let recovery_code = AteHash::generate().to_hex_string().to_uppercase();
let recovery_code = format!(
"{}-{}-{}-{}-{}",
&recovery_code[0..4],
&recovery_code[4..8],
&recovery_code[8..12],
&recovery_code[12..16],
&recovery_code[16..20]
);
let recovery_prefix = format!("recover-login:{}:", request.email);
let recovery_key =
password_to_read_key(&recovery_prefix, &recovery_code, 15, KeySize::Bit192);
let (super_recovery_key, _) = match self.compute_master_key(&recovery_key) {
Some(a) => a,
None => {
warn!("failed to generate recovery key");
return Err(CreateUserFailed::NoMasterKey);
}
};
super_session.user.add_read_key(&super_recovery_key);
// Create the access object
let read_key = EncryptKey::generate(key_size);
let private_read_key = PrivateEncryptKey::generate(key_size);
let write_key = PrivateSignKey::generate(key_size);
let mut access = Vec::new();
access.push(Authorization {
read: read_key.clone(),
private_read: private_read_key.clone(),
write: write_key.clone(),
});
// Create an aggregation session
let mut session = self.master_session.clone();
session.user.add_read_key(&read_key);
session.user.add_private_read_key(&private_read_key);
session.user.add_write_key(&write_key);
session.token = Some(token.clone());
// Compute which chain the user should exist within
let user_chain_key = chain_key_4hex(&request.email, Some("redo"));
let chain = self.registry.open(&self.auth_url, &user_chain_key, true).await?;
let dio = chain.dio_full(&super_session).await;
// Try and find a free UID
let mut uid = None;
for n in 0u32..50u32 {
let mut uid_test = estimate_user_name_as_uid(request.email.clone());
if uid_test < 1000 {
uid_test = uid_test + 1000;
}
uid_test = uid_test + n;
if dio.exists(&PrimaryKey::from(uid_test as u64)).await {
continue;
}
uid = Some(uid_test);
break;
}
let uid = match uid {
Some(a) => a,
None => {
return Err(CreateUserFailed::NoMoreRoom);
}
};
// If the terms and conditions don't match then reject it
if request.accepted_terms != self.terms_and_conditions {
if let Some(terms) = &self.terms_and_conditions {
warn!("did not accept terms and conditions");
return Err(CreateUserFailed::TermsAndConditions(terms.clone()));
}
}
// Generate a QR code
let google_auth = google_authenticator::GoogleAuthenticator::new();
let secret = google_auth.create_secret(32);
let google_auth_secret = format!(
"otpauth://totp/{}:{}?secret={}",
request.auth.to_string(),
request.email,
secret.clone()
);
// Build the QR image
let qr_code = QrCode::new(google_auth_secret.as_bytes())
.unwrap()
.render::<unicode::Dense1x2>()
.dark_color(unicode::Dense1x2::Light)
.light_color(unicode::Dense1x2::Dark)
.build();
// Create all the sudo keys
let sudo_read_key = EncryptKey::generate(key_size);
let sudo_private_read_key = PrivateEncryptKey::generate(key_size);
let sudo_write_key = PrivateSignKey::generate(key_size);
let mut sudo_access = Vec::new();
sudo_access.push(Authorization {
read: sudo_read_key.clone(),
private_read: sudo_private_read_key.clone(),
write: sudo_write_key.clone(),
});
// We generate a derived contract encryption key which we will give back to the caller
let contract_read_key = {
let contract_read_key_entropy = format!("contract-read:{}", request.email);
let contract_read_key_entropy =
AteHash::from_bytes(contract_read_key_entropy.as_bytes());
self.compute_contract_key_from_hash(&contract_read_key_entropy)
};
// Attempt to load it as maybe it is still being verified
// Otherwise create the record
let user_key = PrimaryKey::from(request.email.clone());
let mut user = match dio.load::<User>(&user_key).await.ok() {
Some(user) => {
if user.last_login.is_none() {
user
} else {
// Fail
warn!("username already active: {}", request.email);
return Err(CreateUserFailed::AlreadyExists(
"your account already exists and is in use".to_string(),
));
}
}
None => {
// If it already exists then fail
if dio.exists(&user_key).await {
// Fail
warn!("username already exists: {}", request.email);
return Err(CreateUserFailed::AlreadyExists(
"an account already exists for this username".to_string(),
));
}
// Generate the broker encryption keys used to extend trust without composing
// the confidentiality of the chain through wide blast radius
let broker_read = PrivateEncryptKey::generate(key_size);
let broker_write = PrivateSignKey::generate(key_size);
// Generate a verification code (if the inital state is not nominal)
let verification_code = if initial_status == UserStatus::Unverified {
let v = AteHash::generate().to_hex_string().to_uppercase();
let v = format!("{}-{}-{}", &v[0..4], &v[4..8], &v[8..12]);
Some(v)
} else {
None
};
// Create the user and save it
let user = User {
person: DaoChild::new(),
email: request.email.clone(),
uid,
role: UserRole::Human,
status: initial_status,
verification_code,
last_login: None,
access: access,
foreign: DaoForeign::default(),
sudo: DaoChild::new(),
advert: DaoChild::new(),
recovery: DaoChild::new(),
accepted_terms: DaoChild::new(),
nominal_read: read_key.hash(),
nominal_public_read: private_read_key.as_public_key().clone(),
nominal_write: write_key.as_public_key().clone(),
sudo_read: sudo_read_key.hash(),
sudo_public_read: sudo_private_read_key.as_public_key().clone(),
sudo_write: sudo_write_key.as_public_key().clone(),
broker_read: broker_read.clone(),
broker_write: broker_write.clone(),
};
dio.store_with_key(user, user_key.clone())?
}
};
user.auth_mut().read = ReadOption::from_key(&super_key);
user.auth_mut().write =
WriteOption::Any(vec![master_write_key.hash(), sudo_write_key.hash()]);
// Generate the account recovery object
let recovery_key_entropy = format!("recovery:{}", request.email.clone()).to_string();
let recovery_key = PrimaryKey::from(recovery_key_entropy);
let mut recovery = {
let mut user = user.as_mut();
if let Some(mut recovery) = user.recovery.load_mut().await? {
let mut recovery_mut = recovery.as_mut();
recovery_mut.email = request.email.clone();
recovery_mut.login_secret = request.secret.clone();
recovery_mut.sudo_secret = secret.clone();
recovery_mut.google_auth = google_auth_secret.clone();
recovery_mut.qr_code = qr_code.clone();
drop(recovery_mut);
recovery
} else {
let recovery = UserRecovery {
email: request.email.clone(),
login_secret: request.secret.clone(),
sudo_secret: secret.clone(),
google_auth: google_auth_secret.clone(),
qr_code: qr_code.clone(),
};
user.recovery.store_with_key(recovery, recovery_key).await?
}
};
recovery.auth_mut().read = ReadOption::from_key(&super_recovery_key);
recovery.auth_mut().write = WriteOption::Specific(master_write_key.hash());
// Get or create the sudo object and save it using another elevation of the key
let mut sudo = {
let mut user = user.as_mut();
if let Some(mut sudo) = user.sudo.load_mut().await? {
let mut sudo_mut = sudo.as_mut();
sudo_mut.email = request.email.clone();
sudo_mut.uid = uid;
sudo_mut.google_auth = google_auth_secret;
sudo_mut.secret = secret.clone();
sudo_mut.groups = Vec::new();
sudo_mut.access = sudo_access;
sudo_mut.contract_read_key = contract_read_key;
sudo_mut.qr_code = qr_code.clone();
sudo_mut.failed_attempts = 0u32;
drop(sudo_mut);
sudo
} else {
let sudo = Sudo {
email: request.email.clone(),
uid,
google_auth: google_auth_secret,
secret: secret.clone(),
groups: Vec::new(),
access: sudo_access,
contract_read_key,
qr_code: qr_code.clone(),
failed_attempts: 0u32,
};
user.sudo.store(sudo).await?
}
};
sudo.auth_mut().read = ReadOption::from_key(&super_super_key);
sudo.auth_mut().write = WriteOption::Inherit;
// Add the accepted terms and conditions to the datachain rrecord
if let Some(accepted_terms) = request.accepted_terms.as_ref() {
let mut user = user.as_mut();
if let Some(mut terms) = user.accepted_terms.load_mut().await? {
terms.as_mut().terms_and_conditions = accepted_terms.clone();
} else {
let mut terms = user
.accepted_terms
.store(AcceptedTerms {
terms_and_conditions: accepted_terms.clone(),
})
.await?;
terms.auth_mut().read = ReadOption::Everyone(None);
terms.auth_mut().write = WriteOption::Specific(master_write_key.hash());
}
}
// Create the advert object and save it using public read
let advert_key_entropy = format!("advert:{}", request.email.clone()).to_string();
let advert_key = PrimaryKey::from(advert_key_entropy);
let mut advert = match dio.load::<Advert>(&advert_key).await.ok() {
Some(mut advert) => {
let mut advert_mut = advert.as_mut();
advert_mut.identity = request.email.clone();
advert_mut.id = AdvertId::UID(uid);
advert_mut.nominal_encrypt = private_read_key.as_public_key().clone();
advert_mut.nominal_auth = write_key.as_public_key().clone();
advert_mut.sudo_encrypt = sudo_private_read_key.as_public_key().clone();
advert_mut.sudo_auth = sudo_write_key.as_public_key().clone();
advert_mut.broker_encrypt = user.broker_read.as_public_key().clone();
advert_mut.broker_auth = user.broker_write.as_public_key().clone();
drop(advert_mut);
advert
}
None => {
let advert = Advert {
identity: request.email.clone(),
id: AdvertId::UID(uid),
nominal_encrypt: private_read_key.as_public_key().clone(),
nominal_auth: write_key.as_public_key().clone(),
sudo_encrypt: sudo_private_read_key.as_public_key().clone(),
sudo_auth: sudo_write_key.as_public_key().clone(),
broker_encrypt: user.broker_read.as_public_key().clone(),
broker_auth: user.broker_write.as_public_key().clone(),
};
user.as_mut()
.advert
.store_with_key(advert, advert_key.clone())
.await?
}
};
advert.auth_mut().read = ReadOption::Everyone(None);
advert.auth_mut().write = WriteOption::Inherit;
// Save the data
dio.commit().await?;
// Create the authorizations and return them
let mut session = compute_user_auth(user.deref());
session.token = Some(token);
// Return success to the caller
Ok((
CreateUserResponse {
key: user.key().clone(),
qr_code: qr_code,
qr_secret: secret.clone(),
recovery_code,
authority: session,
message_of_the_day: None,
},
user,
))
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/work/login.rs | wasmer-auth/src/work/login.rs | #![allow(unused_imports)]
use chrono::Duration;
use error_chain::bail;
use std::io::Write;
use std::sync::Arc;
use std::{io::stdout, path::Path};
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use ate::error::LoadError;
use ate::error::TransformError;
use ate::prelude::*;
use ate::utils::chain_key_4hex;
use crate::error::*;
use crate::helper::conf_cmd;
use crate::helper::*;
use crate::helper::*;
use crate::model::*;
use crate::prelude::*;
use crate::request::*;
use crate::service::AuthService;
use super::sudo::*;
impl AuthService {
pub async fn process_login(
self: Arc<Self>,
request: LoginRequest,
) -> Result<LoginResponse, LoginFailed> {
debug!("login attempt: {}", request.email);
// Create the super key and token
let (super_key, token) = match self.compute_master_key(&request.secret) {
Some(a) => a,
None => {
warn!("login attempt denied ({}) - no master key", request.email);
return Err(LoginFailed::NoMasterKey);
}
};
// Create the super session
let mut super_session = self.master_session.clone();
super_session.user.add_read_key(&super_key);
// Compute which chain the user should exist within
let chain_key = chain_key_4hex(request.email.as_str(), Some("redo"));
let chain = self.registry.open(&self.auth_url, &chain_key, true).await?;
let dio = chain.dio_full(&super_session).await;
// Attempt to load the object (if it fails we will tell the caller)
let user_key = PrimaryKey::from(request.email.clone());
let mut user = match dio.load::<User>(&user_key).await {
Ok(a) => a,
Err(LoadError(LoadErrorKind::NotFound(_), _)) => {
warn!("login attempt denied ({}) - not found", request.email);
return Err(LoginFailed::UserNotFound(request.email));
}
Err(LoadError(
LoadErrorKind::TransformationError(TransformErrorKind::MissingReadKey(_)),
_,
)) => {
warn!("login attempt denied ({}) - wrong password", request.email);
return Err(LoginFailed::WrongPassword);
}
Err(err) => {
warn!("login attempt denied ({}) - error - ", err);
bail!(err);
}
};
// Check if the account is locked or not yet verified
match user.status.clone() {
UserStatus::Locked(until) => {
let local_now = chrono::Local::now();
let utc_now = local_now.with_timezone(&chrono::Utc);
if until > utc_now {
let duration = until - utc_now;
warn!(
"login attempt denied ({}) - account locked until {}",
request.email, until
);
return Err(LoginFailed::AccountLocked(duration.to_std().unwrap()));
}
}
UserStatus::Unverified => match request.verification_code {
Some(a) => {
if Some(a.to_lowercase())
!= user.verification_code.clone().map(|a| a.to_lowercase())
{
warn!("login attempt denied ({}) - wrong password", request.email);
return Err(LoginFailed::WrongPassword);
} else {
let mut user = user.as_mut();
user.verification_code = None;
user.status = UserStatus::Nominal;
}
}
None => {
warn!("login attempt denied ({}) - unverified", request.email);
return Err(LoginFailed::Unverified(request.email));
}
},
UserStatus::Nominal => {}
};
dio.commit().await?;
// Add all the authorizations
let mut session = compute_user_auth(&user);
session.token = Some(token.clone());
// Return the session that can be used to access this user
let user = user.take();
info!("login attempt accepted ({})", request.email);
Ok(LoginResponse {
user_key,
nominal_read: user.nominal_read,
nominal_write: user.nominal_write,
sudo_read: user.sudo_read,
sudo_write: user.sudo_write,
authority: session,
message_of_the_day: None,
})
}
pub(crate) fn master_key(&self) -> Option<&EncryptKey> {
self.master_session.user.read_keys().map(|a| a).next()
}
pub(crate) fn web_key(&self) -> &EncryptKey {
&self.web_key
}
pub(crate) fn edge_key(&self) -> &EncryptKey {
&self.edge_key
}
pub(crate) fn contract_key(&self) -> &EncryptKey {
&self.contract_key
}
pub fn compute_super_key(
master_key: &EncryptKey,
secret: &EncryptKey,
) -> (EncryptKey, EncryptedSecureData<EncryptKey>) {
// Create a session with crypto keys based off the username and password
let super_key = AteHash::from_bytes_twice(&master_key.value()[..], &secret.value()[..]);
let super_key = EncryptKey::from_seed_bytes(super_key.as_bytes(), KeySize::Bit192);
let token = EncryptedSecureData::new(&master_key, super_key).unwrap();
(super_key, token)
}
pub fn compute_super_key_from_hash(master_key: &EncryptKey, hash: &AteHash) -> EncryptKey {
// Create a session with crypto keys based off the username and password
let super_key = AteHash::from_bytes_twice(&master_key.value()[..], &hash.as_bytes()[..]);
let super_key = EncryptKey::from_seed_bytes(super_key.as_bytes(), KeySize::Bit192);
super_key
}
pub fn compute_master_key(
&self,
secret: &EncryptKey,
) -> Option<(EncryptKey, EncryptedSecureData<EncryptKey>)> {
self.master_key()
.map(|a| AuthService::compute_super_key(a, secret))
}
pub fn compute_master_key_from_hash(&self, hash: &AteHash) -> Option<EncryptKey> {
self.master_key()
.map(|a| AuthService::compute_super_key_from_hash(a, hash))
}
pub fn compute_web_key(
&self,
secret: &EncryptKey,
) -> (EncryptKey, EncryptedSecureData<EncryptKey>) {
AuthService::compute_super_key(self.web_key(), secret)
}
pub fn compute_web_key_from_hash(&self, hash: &AteHash) -> EncryptKey {
AuthService::compute_super_key_from_hash(self.web_key(), hash)
}
pub fn compute_edge_key(
&self,
secret: &EncryptKey,
) -> (EncryptKey, EncryptedSecureData<EncryptKey>) {
AuthService::compute_super_key(self.edge_key(), secret)
}
pub fn compute_edge_key_from_hash(&self, hash: &AteHash) -> EncryptKey {
AuthService::compute_super_key_from_hash(self.edge_key(), hash)
}
pub fn compute_contract_key(
&self,
secret: &EncryptKey,
) -> (EncryptKey, EncryptedSecureData<EncryptKey>) {
AuthService::compute_super_key(self.contract_key(), secret)
}
pub fn compute_contract_key_from_hash(&self, hash: &AteHash) -> EncryptKey {
AuthService::compute_super_key_from_hash(self.contract_key(), hash)
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/work/group_details.rs | wasmer-auth/src/work/group_details.rs | #![allow(unused_imports)]
use error_chain::bail;
use qrcode::render::unicode;
use qrcode::QrCode;
use std::io::stdout;
use std::io::Write;
use std::ops::Deref;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use ate::error::LoadError;
use ate::error::TransformError;
use ate::prelude::*;
use ate::session::AteRolePurpose;
use ate::utils::chain_key_4hex;
use crate::error::*;
use crate::helper::*;
use crate::model::*;
use crate::prelude::*;
use crate::request::*;
use crate::service::AuthService;
impl AuthService {
pub async fn process_group_details(
self: Arc<Self>,
request: GroupDetailsRequest,
) -> Result<GroupDetailsResponse, GroupDetailsFailed> {
debug!("group ({}) details", request.group);
// Compute which chain the group should exist within
let group_chain_key = chain_key_4hex(&request.group, Some("redo"));
let chain = self.registry.open(&self.auth_url, &group_chain_key, true).await?;
// Load the group
let group_key = PrimaryKey::from(request.group.clone());
let dio = chain.dio(&self.master_session).await;
let group = match dio.load::<Group>(&group_key).await {
Ok(a) => a,
Err(LoadError(LoadErrorKind::NotFound(_), _)) => {
return Err(GroupDetailsFailed::GroupNotFound);
}
Err(LoadError(
LoadErrorKind::TransformationError(TransformErrorKind::MissingReadKey(_)),
_,
)) => {
return Err(GroupDetailsFailed::NoMasterKey);
}
Err(err) => {
bail!(err);
}
};
// Check that we actually have the rights to view the details of this group
let has_access = match &request.session {
Some(session) => {
let hashes = session
.private_read_keys(AteSessionKeyCategory::AllKeys)
.map(|k| k.hash())
.collect::<Vec<_>>();
group
.roles
.iter()
.filter(|r| {
r.purpose == AteRolePurpose::Owner || r.purpose == AteRolePurpose::Delegate
})
.any(|r| {
for hash in hashes.iter() {
if r.access.exists(hash) {
return true;
}
}
return false;
})
}
None => false,
};
// Build the list of roles in this group
let mut roles = Vec::new();
for role in group.roles.iter() {
roles.push(GroupDetailsRoleResponse {
purpose: role.purpose.clone(),
name: role.purpose.to_string(),
read: role.read.clone(),
private_read: role.private_read.clone(),
write: role.write.clone(),
hidden: has_access == false,
members: match has_access {
true => role
.access
.meta_list()
.map(|m| m.clone())
.collect::<Vec<_>>(),
false => Vec::new(),
},
});
}
// Return success to the caller
Ok(GroupDetailsResponse {
key: group.key().clone(),
name: group.name.clone(),
gid: group.gid,
roles,
})
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/work/mod.rs | wasmer-auth/src/work/mod.rs | mod create_group;
mod create_user;
mod gather;
mod group_details;
mod group_remove;
mod group_user_add;
mod group_user_remove;
mod login;
mod query;
mod reset;
mod sudo;
pub use create_group::*;
pub use create_user::*;
pub use gather::*;
pub use group_details::*;
pub use group_remove::*;
pub use group_user_add::*;
pub use group_user_remove::*;
pub use login::*;
pub use query::*;
pub use reset::*;
pub use sudo::*;
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/work/create_group.rs | wasmer-auth/src/work/create_group.rs | #![allow(unused_imports)]
use error_chain::bail;
use qrcode::render::unicode;
use qrcode::QrCode;
use regex::Regex;
use std::io::stdout;
use std::io::Write;
use std::ops::Deref;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use ate::error::LoadError;
use ate::error::TransformError;
use ate::prelude::*;
use ate::session::AteRolePurpose;
use ate::utils::chain_key_4hex;
use crate::error::*;
use crate::helper::*;
use crate::model::*;
use crate::prelude::*;
use crate::request::*;
use crate::service::AuthService;
impl AuthService {
pub async fn process_create_group(
self: Arc<Self>,
request: CreateGroupRequest,
) -> Result<CreateGroupResponse, CreateGroupFailed> {
info!("create group: {}", request.group);
// There are certain areas that need a derived encryption key
let web_key = {
let web_key_entropy = format!("web-read:{}", request.group);
let web_key_entropy = AteHash::from_bytes(web_key_entropy.as_bytes());
self.compute_web_key_from_hash(&web_key_entropy)
};
let edge_key = {
let edge_key_entropy = format!("edge-read:{}", request.group);
let edge_key_entropy = AteHash::from_bytes(edge_key_entropy.as_bytes());
self.compute_edge_key_from_hash(&edge_key_entropy)
};
// First we query the user that needs to be added so that we can get their public encrypt key
let advert = match Arc::clone(&self)
.process_query(QueryRequest {
identity: request.identity.clone(),
})
.await
{
Ok(a) => Ok(a),
Err(QueryFailed::Banned) => Err(CreateGroupFailed::OperatorBanned),
Err(QueryFailed::NotFound) => Err(CreateGroupFailed::OperatorNotFound),
Err(QueryFailed::Suspended) => Err(CreateGroupFailed::AccountSuspended),
Err(QueryFailed::InternalError(code)) => Err(CreateGroupFailed::InternalError(code)),
}?
.advert;
// Extract the read key(s) from the query
let request_nominal_read_key = advert.nominal_encrypt;
let request_sudo_read_key = advert.sudo_encrypt;
// Make sure the group matches the regex and is valid
let regex = Regex::new("^/{0,1}([a-zA-Z0-9_\\.\\-]{1,})$").unwrap();
if let Some(_captures) = regex.captures(request.group.as_str()) {
if request.group.len() <= 0 {
return Err(CreateGroupFailed::InvalidGroupName(
"the group name you specified is not long enough".to_string(),
));
}
} else {
return Err(CreateGroupFailed::InvalidGroupName(
"the group name you specified is invalid".to_string(),
));
}
// Get the master write key
let master_write_key = match self.master_session.user.write_keys().next() {
Some(a) => a.clone(),
None => {
return Err(CreateGroupFailed::NoMasterKey);
}
};
// Load the master key which will be used to encrypt the group so that only
// the authentication server can access it
let key_size = request_nominal_read_key.size();
let master_key = match self.master_key() {
Some(a) => a,
None => {
return Err(CreateGroupFailed::NoMasterKey);
}
};
// Compute which chain the group should exist within
let group_chain_key = chain_key_4hex(&request.group, Some("redo"));
let chain = self.registry.open(&self.auth_url, &group_chain_key, true).await?;
let dio = chain.dio_mut(&self.master_session).await;
// Try and find a free GID
let gid_offset = u32::MAX as u64;
let mut gid = None;
for n in 0u32..50u32 {
let mut gid_test = estimate_group_name_as_gid(request.group.clone());
if gid_test < 1000 {
gid_test = gid_test + 1000;
}
gid_test = gid_test + n;
if dio.exists(&PrimaryKey::from(gid_test as u64)).await {
continue;
}
if dio
.exists(&PrimaryKey::from(gid_test as u64 + gid_offset))
.await
{
continue;
}
gid = Some(gid_test);
break;
}
let gid = match gid {
Some(a) => a,
None => {
return Err(CreateGroupFailed::NoMoreRoom);
}
};
// If it already exists then fail
let group_key = PrimaryKey::from(request.group.clone());
if dio.exists(&group_key).await {
return Err(CreateGroupFailed::AlreadyExists(
"the group with this name already exists".to_string(),
));
}
// Generate the owner encryption keys used to protect this role
let owner_read = EncryptKey::generate(key_size);
let owner_private_read = PrivateEncryptKey::generate(key_size);
let owner_write = PrivateSignKey::generate(key_size);
// Generate the delegate encryption keys used to protect this role
let delegate_read = EncryptKey::generate(key_size);
let delegate_private_read = PrivateEncryptKey::generate(key_size);
let delegate_write = PrivateSignKey::generate(key_size);
// Generate the contributor encryption keys used to protect this role
let contributor_read = EncryptKey::generate(key_size);
let contributor_private_read = PrivateEncryptKey::generate(key_size);
let contributor_write = PrivateSignKey::generate(key_size);
// Generate the observer encryption keys used to protect this role
let observer_read = EncryptKey::generate(key_size);
let observer_private_read = PrivateEncryptKey::generate(key_size);
let observer_write = PrivateSignKey::generate(key_size);
// Generate the web server encryption keys used to protect this role
let web_server_read = EncryptKey::generate(key_size);
let web_server_private_read = PrivateEncryptKey::generate(key_size);
let web_server_write = PrivateSignKey::generate(key_size);
// We generate a derived contract encryption key which we will give back to the caller
let contract_read_key = {
let contract_read_key_entropy = format!("contract-read:{}", request.group);
let contract_read_key_entropy =
AteHash::from_bytes(contract_read_key_entropy.as_bytes());
self.compute_contract_key_from_hash(&contract_read_key_entropy)
};
let finance_read = contract_read_key;
let finance_private_read = PrivateEncryptKey::generate(key_size);
let finance_write = PrivateSignKey::generate(key_size);
// We generate a derived edge compute encryption key which we will give back to the caller
let edge_compute_read = EncryptKey::generate(key_size);
let edge_compute_private_read = PrivateEncryptKey::generate(key_size);
let edge_compute_write = PrivateSignKey::generate(key_size);
// Generate the broker encryption keys used to extend trust without composing
// the confidentiality of the chain through wide blast radius
let broker_read = PrivateEncryptKey::generate(key_size);
let broker_write = PrivateSignKey::generate(key_size);
// The super session needs the owner keys so that it can save the records
let mut super_session = self.master_session.clone();
super_session.user.add_read_key(&owner_read);
super_session.user.add_read_key(&delegate_read);
super_session.user.add_private_read_key(&owner_private_read);
super_session
.user
.add_private_read_key(&delegate_private_read);
super_session.user.add_write_key(&owner_write);
super_session.user.add_write_key(&delegate_write);
let dio = chain.dio_full(&super_session).await;
// Create the group and save it
let group = Group {
name: request.group.clone(),
foreign: DaoForeign::default(),
gid,
roles: Vec::new(),
broker_read: broker_read.clone(),
broker_write: broker_write.clone(),
};
let mut group = dio.store_with_key(group, group_key.clone())?;
// Add the other roles
{
let mut group_mut = group.as_mut();
for purpose in vec![
AteRolePurpose::Owner,
AteRolePurpose::Delegate,
AteRolePurpose::Contributor,
AteRolePurpose::Finance,
AteRolePurpose::WebServer,
AteRolePurpose::EdgeCompute,
AteRolePurpose::Observer,
]
.iter()
{
// Generate the keys
let role_read;
let role_private_read;
let role_write;
match purpose {
AteRolePurpose::Owner => {
role_read = owner_read.clone();
role_private_read = owner_private_read.clone();
role_write = owner_write.clone();
}
AteRolePurpose::Delegate => {
role_read = delegate_read.clone();
role_private_read = delegate_private_read.clone();
role_write = delegate_write.clone();
}
AteRolePurpose::Contributor => {
role_read = contributor_read.clone();
role_private_read = contributor_private_read.clone();
role_write = contributor_write.clone();
}
AteRolePurpose::Finance => {
role_read = finance_read.clone();
role_private_read = finance_private_read.clone();
role_write = finance_write.clone();
}
AteRolePurpose::Observer => {
role_read = observer_read.clone();
role_private_read = observer_private_read.clone();
role_write = observer_write.clone();
}
AteRolePurpose::WebServer => {
role_read = web_server_read.clone();
role_private_read = web_server_private_read.clone();
role_write = web_server_write.clone();
}
AteRolePurpose::EdgeCompute => {
role_read = edge_compute_read.clone();
role_private_read = edge_compute_private_read.clone();
role_write = edge_compute_write.clone();
}
_ => {
role_read = EncryptKey::generate(key_size);
role_private_read = PrivateEncryptKey::generate(key_size);
role_write = PrivateSignKey::generate(key_size);
}
}
// Create the access object
let access_key = match purpose {
AteRolePurpose::WebServer => web_key.clone(),
AteRolePurpose::EdgeCompute => edge_key.clone(),
_ => EncryptKey::generate(owner_private_read.size()),
};
let mut access = MultiEncryptedSecureData::new_ext(
&owner_private_read.as_public_key(),
access_key.clone(),
"owner".to_string(),
Authorization {
read: role_read.clone(),
private_read: role_private_read.clone(),
write: role_write.clone(),
},
)?;
// Create the role permission tree
if let AteRolePurpose::Owner = purpose {
access.add(
&request_sudo_read_key,
request.identity.clone(),
&owner_private_read,
)?;
} else if let AteRolePurpose::Finance = purpose {
access.add(
&request_sudo_read_key,
request.identity.clone(),
&owner_private_read,
)?;
} else if let AteRolePurpose::Delegate = purpose {
access.add(
&request_nominal_read_key,
request.identity.clone(),
&owner_private_read,
)?;
} else if let AteRolePurpose::Observer = purpose {
access.add(
&delegate_private_read.as_public_key(),
"delegate".to_string(),
&owner_private_read,
)?;
access.add(
&contributor_private_read.as_public_key(),
"contributor".to_string(),
&owner_private_read,
)?;
} else if let AteRolePurpose::WebServer = purpose {
access.add(
&delegate_private_read.as_public_key(),
"delegate".to_string(),
&owner_private_read,
)?;
access.add(
&contributor_private_read.as_public_key(),
"contributor".to_string(),
&owner_private_read,
)?;
} else if let AteRolePurpose::EdgeCompute = purpose {
access.add(
&delegate_private_read.as_public_key(),
"delegate".to_string(),
&owner_private_read,
)?;
} else {
access.add(
&delegate_private_read.as_public_key(),
"delegate".to_string(),
&owner_private_read,
)?;
}
// Add the owner role to the group (as its a super_key the authentication server
// is required to read the group records and load them, while the authentication
// server can run in a distributed mode it is a centralized authority)
let role = Role {
purpose: purpose.clone(),
read: role_read.hash(),
private_read: role_private_read.as_public_key().clone(),
write: role_write.as_public_key().clone(),
access,
};
group_mut.roles.push(role);
}
}
// Set all the permissions and save the group. While the group is readable by everyone
// the data held within the structure is itself encrypted using the MultiEncryptedSecureData
// object which allows one to multiplex the access to the keys
group.auth_mut().read = ReadOption::from_key(&master_key);
group.auth_mut().write =
WriteOption::Any(vec![master_write_key.hash(), owner_write.hash()]);
// Create the advert object and save it using public read
let advert_key_entropy = format!("advert:{}", request.group.clone()).to_string();
let advert_key = PrimaryKey::from(advert_key_entropy);
let advert = Advert {
identity: request.group.clone(),
id: AdvertId::GID(gid),
nominal_encrypt: observer_private_read.as_public_key().clone(),
nominal_auth: contributor_write.as_public_key().clone(),
sudo_encrypt: owner_private_read.as_public_key().clone(),
sudo_auth: owner_write.as_public_key().clone(),
broker_auth: broker_write.as_public_key().clone(),
broker_encrypt: broker_read.as_public_key().clone(),
};
let mut advert = dio.store_with_key(advert, advert_key.clone())?;
advert.auth_mut().read = ReadOption::Everyone(None);
advert.auth_mut().write = WriteOption::Inherit;
// Commit
dio.commit().await?;
// Add the group credentials to the response
let session = complete_group_auth(group.deref(), AteSessionUser::default().into())?;
// Return success to the caller
Ok(CreateGroupResponse {
key: group.key().clone(),
session,
})
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/work/group_user_add.rs | wasmer-auth/src/work/group_user_add.rs | #![allow(unused_imports)]
use error_chain::bail;
use qrcode::render::unicode;
use qrcode::QrCode;
use std::io::stdout;
use std::io::Write;
use std::ops::Deref;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use ate::error::LoadError;
use ate::error::TransformError;
use ate::prelude::*;
use ate::session::AteRolePurpose;
use ate::utils::chain_key_4hex;
use crate::error::*;
use crate::helper::*;
use crate::model::*;
use crate::prelude::*;
use crate::request::*;
use crate::service::AuthService;
impl AuthService {
pub fn get_delegate_write(
request_session: &AteSessionGroup,
needed_role: AteRolePurpose,
) -> Result<Option<PrivateEncryptKey>, LoadError> {
let val = {
request_session
.get_group_role(&needed_role)
.iter()
.flat_map(|r| r.private_read_keys())
.map(|a| a.clone())
.next()
};
// Extract the controlling role as this is what we will use to create the role
let delegate_write = match val {
Some(a) => a,
None => {
// If it fails again then give up
debug!("group-user-add-failed with {}", request_session);
return Ok(None);
}
};
Ok(Some(delegate_write))
}
pub async fn process_group_user_add(
self: Arc<Self>,
request: GroupUserAddRequest,
) -> Result<GroupUserAddResponse, GroupUserAddFailed> {
info!("group ({}) user add", request.group);
// Copy the request session
let request_purpose = request.purpose;
let request_session = request.session;
// Load the master key which will be used to encrypt the group so that only
// the authentication server can access it
let key_size = request_session
.read_keys(AteSessionKeyCategory::AllKeys)
.map(|k| k.size())
.next()
.unwrap_or_else(|| KeySize::Bit192);
// Compute which chain the group should exist within
let group_chain_key = chain_key_4hex(&request.group, Some("redo"));
let chain = self.registry.open(&self.auth_url, &group_chain_key, true).await?;
// Create the super session that has all the rights we need
let mut super_session = self.master_session.clone();
super_session.append(request_session.properties());
// Load the group
let group_key = PrimaryKey::from(request.group.clone());
let dio = chain.dio_full(&super_session).await;
let mut group = match dio.load::<Group>(&group_key).await {
Ok(a) => a,
Err(LoadError(LoadErrorKind::NotFound(_), _)) => {
return Err(GroupUserAddFailed::GroupNotFound);
}
Err(LoadError(
LoadErrorKind::TransformationError(TransformErrorKind::MissingReadKey(_)),
_,
)) => {
return Err(GroupUserAddFailed::NoMasterKey);
}
Err(err) => {
bail!(err);
}
};
// Determine what role is needed to adjust the group
let needed_role = match &request_purpose {
AteRolePurpose::Owner => AteRolePurpose::Owner,
AteRolePurpose::Delegate => AteRolePurpose::Owner,
_ => AteRolePurpose::Delegate,
};
// Get the delegate write key
let delegate_write = match AuthService::get_delegate_write(&request_session, needed_role)? {
Some(a) => a,
None => {
return Err(GroupUserAddFailed::NoAccess);
}
};
// If the role does not exist then add it
if group.roles.iter().any(|r| r.purpose == request_purpose) == false {
// Get our own identity
let referrer_identity = request_session.inner.identity().to_string();
// Generate the role keys
let role_read = EncryptKey::generate(key_size);
let role_private_read = PrivateEncryptKey::generate(key_size);
let role_write = PrivateSignKey::generate(key_size);
// Add this customer role and attach it back to the delegate role
group.as_mut().roles.push(Role {
purpose: request_purpose.clone(),
access: MultiEncryptedSecureData::new(
&delegate_write.as_public_key(),
referrer_identity,
Authorization {
read: role_read.clone(),
private_read: role_private_read.clone(),
write: role_write.clone(),
},
)?,
read: role_read.hash(),
private_read: role_private_read.as_public_key().clone(),
write: role_write.as_public_key().clone(),
})
}
// Perform the operation that will add the other user to the specific group role
for role in group
.as_mut()
.roles
.iter_mut()
.filter(|r| r.purpose == request_purpose)
{
role.access
.add(&request.who_key, request.who_name.clone(), &delegate_write)?;
}
// Commit
dio.commit().await?;
// Return success to the caller
Ok(GroupUserAddResponse {
key: group.key().clone(),
})
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/work/query.rs | wasmer-auth/src/work/query.rs | #![allow(unused_imports)]
use error_chain::bail;
use qrcode::render::unicode;
use qrcode::QrCode;
use std::io::stdout;
use std::io::Write;
use std::ops::Deref;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use ate::error::LoadError;
use ate::prelude::*;
use ate::utils::chain_key_4hex;
use crate::error::*;
use crate::helper::*;
use crate::helper::*;
use crate::model::*;
use crate::prelude::*;
use crate::request::*;
use crate::service::AuthService;
impl AuthService {
pub async fn process_query(
self: Arc<Self>,
request: QueryRequest,
) -> Result<QueryResponse, QueryFailed> {
debug!("query user/group: {}", request.identity);
// Compute which chain the user should exist within
let chain_key = chain_key_4hex(&request.identity, Some("redo"));
let chain = self.registry.open(&self.auth_url, &chain_key, true).await?;
let dio = chain.dio(&self.master_session).await;
// If it does not exist then fail
let user_key_entropy = format!("advert:{}", request.identity).to_string();
let user_key = PrimaryKey::from(user_key_entropy);
if dio.exists(&user_key).await == false {
return Err(QueryFailed::NotFound);
}
// Load the advert
let advert = dio.load::<Advert>(&user_key).await?;
// Return success to the caller
Ok(QueryResponse {
advert: advert.take(),
})
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/work/gather.rs | wasmer-auth/src/work/gather.rs | #![allow(unused_imports)]
use error_chain::bail;
use std::io::Write;
use std::ops::Deref;
use std::sync::Arc;
use std::{io::stdout, path::Path};
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use ate::error::LoadError;
use ate::error::TransformError;
use ate::prelude::*;
use ate::utils::chain_key_4hex;
use crate::error::*;
use crate::helper::*;
use crate::helper::*;
use crate::model::*;
use crate::prelude::*;
use crate::request::*;
use crate::service::AuthService;
impl AuthService {
pub async fn process_gather(
self: Arc<Self>,
request: GatherRequest,
) -> Result<GatherResponse, GatherFailed> {
debug!("gather attempt: {}", request.group);
// Load the master key which is used to read the authentication chains
let master_key = match self.master_key() {
Some(a) => a,
None => {
error!("gather failed - no master key!");
return Err(GatherFailed::NoMasterKey);
}
};
let mut super_session = AteSessionUser::default();
super_session.user.add_read_key(&master_key);
// Compute which chain the group should exist within
let group_chain_key = chain_key_4hex(&request.group, Some("redo"));
let chain = self.registry.open(&self.auth_url, &group_chain_key, true).await?;
// Load the group
let group_key = PrimaryKey::from(request.group.clone());
let dio = chain.dio(&self.master_session).await;
let group = match dio.load::<Group>(&group_key).await {
Ok(a) => a,
Err(LoadError(LoadErrorKind::NotFound(_), _)) => {
return Err(GatherFailed::GroupNotFound(request.group));
}
Err(LoadError(
LoadErrorKind::TransformationError(TransformErrorKind::MissingReadKey(_)),
_,
)) => {
error!("gather failed - missing master key!");
return Err(GatherFailed::NoMasterKey);
}
Err(err) => {
bail!(err);
}
};
// Now go into a loading loop on the session
let session = complete_group_auth(group.deref(), request.session)?;
// Return the session that can be used to access this user
Ok(GatherResponse {
group_name: request.group.clone(),
gid: group.gid,
group_key: group.key().clone(),
authority: session,
})
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/work/group_remove.rs | wasmer-auth/src/work/group_remove.rs | #![allow(unused_imports)]
use error_chain::bail;
use qrcode::render::unicode;
use qrcode::QrCode;
use std::io::stdout;
use std::io::Write;
use std::ops::Deref;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use ate::error::LoadError;
use ate::error::TransformError;
use ate::prelude::*;
use ate::session::AteRolePurpose;
use ate::utils::chain_key_4hex;
use crate::error::*;
use crate::helper::*;
use crate::model::*;
use crate::prelude::*;
use crate::request::*;
use crate::service::AuthService;
impl AuthService {
pub async fn process_group_remove(
self: Arc<Self>,
request: GroupRemoveRequest,
) -> Result<GroupRemoveResponse, GroupRemoveFailed> {
info!("group ({}) remove", request.group);
// Copy the request session
let request_session = request.session;
// Compute which chain the group should exist within
let group_chain_key = chain_key_4hex(&request.group, Some("redo"));
let chain = self.registry.open(&self.auth_url, &group_chain_key, true).await?;
// Create the super session that has all the rights we need
let mut super_session = self.master_session.clone();
super_session.append(request_session.properties());
// Delete the group
let group_key = PrimaryKey::from(request.group.clone());
let dio = chain.dio_full(&super_session).await;
dio.delete(&group_key).await?;
// Delete the advert
let advert_key_entropy = format!("advert:{}", request.group.clone()).to_string();
let advert_key = PrimaryKey::from(advert_key_entropy);
let _ = dio.delete(&advert_key).await;
// Commit
dio.commit().await?;
// Return success to the caller
Ok(GroupRemoveResponse { key: group_key })
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/work/reset.rs | wasmer-auth/src/work/reset.rs | #![allow(unused_imports)]
use error_chain::bail;
use qrcode::render::unicode;
use qrcode::QrCode;
use std::io::stdout;
use std::io::Write;
use std::ops::Deref;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use ate::error::LoadError;
use ate::prelude::*;
use ate::utils::chain_key_4hex;
use crate::error::*;
use crate::helper::*;
use crate::helper::*;
use crate::model::*;
use crate::prelude::*;
use crate::request::*;
use crate::service::AuthService;
impl AuthService {
pub async fn process_reset(
self: Arc<Self>,
request: ResetRequest,
) -> Result<ResetResponse, ResetFailed> {
Ok(self.process_reset_internal(request).await?.0)
}
pub async fn process_reset_internal(
self: Arc<Self>,
request: ResetRequest,
) -> Result<(ResetResponse, DaoMut<User>), ResetFailed> {
info!("reset user: {}", request.email);
// Compute the super_key, super_super_key (elevated rights) and the super_session
let (super_key, token) = self
.compute_master_key(&request.new_secret)
.ok_or_else(|| ResetFailed::NoMasterKey)?;
let (super_super_key, super_token) = self
.compute_master_key(&super_key)
.ok_or_else(|| ResetFailed::NoMasterKey)?;
let mut super_session = self.master_session.clone();
super_session.user.add_read_key(&super_key);
super_session.user.add_read_key(&super_super_key);
super_session.token = Some(super_token);
// Convert the recovery code
let (super_recovery_key, _) = self
.compute_master_key(&request.recovery_key)
.ok_or_else(|| ResetFailed::NoMasterKey)?;
super_session.user.add_read_key(&super_recovery_key);
// Compute which chain the user should exist within
let chain_key = chain_key_4hex(request.email.as_str(), Some("redo"));
let chain = self.registry.open(&self.auth_url, &chain_key, true).await?;
let dio = chain.dio_full(&super_session).await;
// Check if the user exists
let user_key = PrimaryKey::from(request.email.clone());
if dio.exists(&user_key).await == false {
warn!("reset attempt denied ({}) - not found", request.email);
return Err(ResetFailed::InvalidEmail(request.email));
}
// Attempt to load the recovery object
let recovery_key_entropy = format!("recovery:{}", request.email.clone()).to_string();
let recovery_key = PrimaryKey::from(recovery_key_entropy);
let mut recovery = match dio.load::<UserRecovery>(&recovery_key).await {
Ok(a) => a,
Err(LoadError(LoadErrorKind::NotFound(_), _)) => {
warn!("reset attempt denied ({}) - not found", request.email);
return Err(ResetFailed::InvalidRecoveryCode);
}
Err(LoadError(
LoadErrorKind::TransformationError(TransformErrorKind::MissingReadKey(_)),
_,
)) => {
warn!(
"reset attempt denied ({}) - invalid recovery code",
request.email
);
return Err(ResetFailed::InvalidRecoveryCode);
}
Err(err) => {
warn!("reset attempt denied ({}) - error - ", err);
bail!(err);
}
};
// Check the code matches the authenticator code
self.time_keeper.wait_for_high_accuracy().await;
let time = self.time_keeper.current_timestamp_as_duration()?;
let time = time.as_secs() / 30;
let google_auth = google_authenticator::GoogleAuthenticator::new();
if request.sudo_code != request.sudo_code_2
&& google_auth.verify_code(
recovery.sudo_secret.as_str(),
request.sudo_code.as_str(),
4,
time,
)
&& google_auth.verify_code(
recovery.sudo_secret.as_str(),
request.sudo_code_2.as_str(),
4,
time,
)
{
debug!("code authenticated");
} else {
warn!("reset attempt denied ({}) - wrong code", request.email);
return Err(ResetFailed::InvalidAuthenticatorCode);
}
// We can now add the original encryption key that we grant us access to this account
{
let mut session_mut = dio.session_mut();
let (super_key, _) = self
.compute_master_key(&recovery.login_secret)
.ok_or_else(|| ResetFailed::NoMasterKey)?;
let (super_super_key, _) = self
.compute_master_key(&super_key.clone())
.ok_or_else(|| ResetFailed::NoMasterKey)?;
session_mut.user_mut().add_user_read_key(&super_key);
session_mut.user_mut().add_user_read_key(&super_super_key);
}
// Attempt to load the user (if it fails we will tell the caller)
let user_key = PrimaryKey::from(request.email.clone());
let mut user = match dio.load::<User>(&user_key).await {
Ok(a) => a,
Err(LoadError(LoadErrorKind::NotFound(_), _)) => {
warn!("reset attempt denied ({}) - not found", request.email);
return Err(ResetFailed::InvalidEmail(request.email));
}
Err(LoadError(
LoadErrorKind::TransformationError(TransformErrorKind::MissingReadKey(_)),
_,
)) => {
warn!(
"reset attempt denied ({}) - recovery is not possible",
request.email
);
return Err(ResetFailed::RecoveryImpossible);
}
Err(err) => {
warn!("reset attempt denied ({}) - error - ", err);
bail!(err);
}
};
{
// Update the credentials for the user
user.auth_mut().read = ReadOption::from_key(&super_key);
}
// Attempt to load the sudo (if it fails we will tell the caller)
let mut sudo = match user.as_mut().sudo.load_mut().await {
Ok(Some(a)) => a,
Ok(None) => {
warn!("reset attempt denied ({}) - sudo not found", request.email);
return Err(ResetFailed::InvalidEmail(request.email));
}
Err(LoadError(
LoadErrorKind::TransformationError(TransformErrorKind::MissingReadKey(_)),
_,
)) => {
warn!("reset attempt denied ({}) - wrong password", request.email);
return Err(ResetFailed::RecoveryImpossible);
}
Err(err) => {
warn!("reset attempt denied ({}) - error - ", err);
bail!(err);
}
};
// Generate a QR code
let google_auth = google_authenticator::GoogleAuthenticator::new();
let secret = google_auth.create_secret(32);
let google_auth_secret = format!(
"otpauth://totp/{}:{}?secret={}",
request.auth.to_string(),
request.email,
secret.clone()
);
// Build the QR image
let qr_code = QrCode::new(google_auth_secret.as_bytes())
.unwrap()
.render::<unicode::Dense1x2>()
.dark_color(unicode::Dense1x2::Light)
.light_color(unicode::Dense1x2::Dark)
.build();
{
// Update the credentials for the sudo
sudo.auth_mut().read = ReadOption::from_key(&super_super_key);
let mut sudo_mut = sudo.as_mut();
sudo_mut.google_auth = google_auth_secret.clone();
sudo_mut.secret = secret.clone();
sudo_mut.qr_code = qr_code.clone();
sudo_mut.failed_attempts = 0u32;
}
{
// Finally update the recovery object
recovery.auth_mut().read = ReadOption::from_key(&super_recovery_key);
let mut recovery_mut = recovery.as_mut();
recovery_mut.email = request.email.clone();
recovery_mut.login_secret = request.new_secret.clone();
recovery_mut.sudo_secret = secret.clone();
recovery_mut.google_auth = google_auth_secret.clone();
recovery_mut.qr_code = qr_code.clone();
}
// Commit the transaction
dio.commit().await?;
// Create the authorizations and return them
let mut session = compute_user_auth(user.deref());
session.token = Some(token);
// Return success to the caller
Ok((
ResetResponse {
key: user.key().clone(),
qr_code: qr_code,
qr_secret: secret.clone(),
authority: session,
message_of_the_day: None,
},
user,
))
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/work/group_user_remove.rs | wasmer-auth/src/work/group_user_remove.rs | #![allow(unused_imports)]
use error_chain::bail;
use qrcode::render::unicode;
use qrcode::QrCode;
use std::io::stdout;
use std::io::Write;
use std::ops::Deref;
use std::sync::Arc;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
use ate::error::LoadError;
use ate::error::TransformError;
use ate::prelude::*;
use ate::session::AteRolePurpose;
use ate::utils::chain_key_4hex;
use crate::error::*;
use crate::helper::*;
use crate::model::*;
use crate::prelude::*;
use crate::request::*;
use crate::service::AuthService;
impl AuthService {
pub async fn process_group_user_remove(
self: Arc<Self>,
request: GroupUserRemoveRequest,
) -> Result<GroupUserRemoveResponse, GroupUserRemoveFailed> {
info!("group ({}) user remove", request.group);
// Copy the request session
let request_purpose = request.purpose;
let request_session = request.session;
// Compute which chain the group should exist within
let group_chain_key = chain_key_4hex(&request.group, Some("redo"));
let chain = self.registry.open(&self.auth_url, &group_chain_key, true).await?;
// Create the super session that has all the rights we need
let mut super_session = self.master_session.clone();
super_session.append(request_session.properties());
// Load the group
let group_key = PrimaryKey::from(request.group.clone());
let dio = chain.dio_full(&super_session).await;
let mut group = match dio.load::<Group>(&group_key).await {
Ok(a) => a,
Err(LoadError(LoadErrorKind::NotFound(_), _)) => {
return Err(GroupUserRemoveFailed::GroupNotFound);
}
Err(LoadError(
LoadErrorKind::TransformationError(TransformErrorKind::MissingReadKey(_)),
_,
)) => {
return Err(GroupUserRemoveFailed::NoMasterKey);
}
Err(err) => {
bail!(err);
}
};
// Determine what role is needed to adjust the group
let needed_role = match request_purpose {
AteRolePurpose::Owner => AteRolePurpose::Owner,
AteRolePurpose::Delegate => AteRolePurpose::Owner,
_ => AteRolePurpose::Delegate,
};
// Extract the controlling role as this is what we will use to create the role
let delegate_write = match AuthService::get_delegate_write(&request_session, needed_role)? {
Some(a) => a,
None => {
return Err(GroupUserRemoveFailed::NoAccess);
}
};
let delegate_write_hash = delegate_write.as_public_key().hash();
{
let mut group = group.as_mut();
// Get the group role
let role = {
match group
.roles
.iter_mut()
.filter(|r| r.purpose == request_purpose)
.next()
{
Some(a) => a,
None => {
return Err(GroupUserRemoveFailed::RoleNotFound);
}
}
};
// Check that we actually have the rights to remove this item
if role.access.exists(&delegate_write_hash) == false {
return Err(GroupUserRemoveFailed::NoAccess);
}
// Perform the operation that will remove the other user to the specific group role
if role.access.remove(&request.who) == false {
return Err(GroupUserRemoveFailed::NothingToRemove);
}
}
// Commit
dio.commit().await?;
// Return success to the caller
Ok(GroupUserRemoveResponse {
key: group.key().clone(),
})
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/error/group_details_error.rs | wasmer-auth/src/error/group_details_error.rs | use error_chain::error_chain;
use crate::request::*;
use ::ate::prelude::*;
error_chain! {
types {
GroupDetailsError, GroupDetailsErrorKind, ResultExt, Result;
}
links {
AteError(::ate::error::AteError, ::ate::error::AteErrorKind);
ChainCreationError(::ate::error::ChainCreationError, ::ate::error::ChainCreationErrorKind);
SerializationError(::ate::error::SerializationError, ::ate::error::SerializationErrorKind);
InvokeError(::ate::error::InvokeError, ::ate::error::InvokeErrorKind);
}
foreign_links {
IO(tokio::io::Error);
}
errors {
GroupNotFound {
description("group details failed as the group does not exist")
display("group details failed as the group does not exist")
}
NoAccess {
description("group details failed as the referrer has no access to this group")
display("group details failed as the referrer has no access to this group")
}
NoMasterKey {
description("group details failed as the server has not been properly initialized")
display("group deatils failed as the server has not been properly initialized")
}
InternalError(code: u16) {
description("group details failed as the server experienced an internal error")
display("group details failed as the server experienced an internal error - code={}", code)
}
}
}
impl From<GroupDetailsError> for AteError {
fn from(err: GroupDetailsError) -> AteError {
AteErrorKind::ServiceError(err.to_string()).into()
}
}
impl From<GroupDetailsFailed> for GroupDetailsError {
fn from(err: GroupDetailsFailed) -> GroupDetailsError {
match err {
GroupDetailsFailed::GroupNotFound => GroupDetailsErrorKind::GroupNotFound.into(),
GroupDetailsFailed::NoAccess => GroupDetailsErrorKind::NoAccess.into(),
GroupDetailsFailed::NoMasterKey => GroupDetailsErrorKind::NoMasterKey.into(),
GroupDetailsFailed::InternalError(code) => {
GroupDetailsErrorKind::InternalError(code).into()
}
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/error/gather_error.rs | wasmer-auth/src/error/gather_error.rs | use error_chain::error_chain;
use crate::request::*;
use ::ate::prelude::*;
error_chain! {
types {
GatherError, GatherErrorKind, ResultExt, Result;
}
links {
AteError(::ate::error::AteError, ::ate::error::AteErrorKind);
ChainCreationError(::ate::error::ChainCreationError, ::ate::error::ChainCreationErrorKind);
SerializationError(::ate::error::SerializationError, ::ate::error::SerializationErrorKind);
InvokeError(::ate::error::InvokeError, ::ate::error::InvokeErrorKind);
LoginError(super::LoginError, super::LoginErrorKind);
SudoError(super::SudoError, super::SudoErrorKind);
}
foreign_links {
IO(tokio::io::Error);
}
errors {
Timeout {
description("login failed due to a timeout")
display("login failed due to a timeout")
}
NotFound(group: String) {
description("gather failed as the group does not exist"),
display("gather failed as the group does not exist ({})", group),
}
NoAccess {
description("gather failed as the session has no access to this group")
display("gather failed as the session has no access to this group")
}
NoMasterKey {
description("gather failed as the server has not been properly initialized")
display("gather failed as the server has not been properly initialized")
}
InternalError(code: u16) {
description("gather failed as the server experienced an internal error")
display("gather failed as the server experienced an internal error - code={}", code)
}
}
}
impl From<GatherError> for AteError {
fn from(err: GatherError) -> AteError {
AteErrorKind::ServiceError(err.to_string()).into()
}
}
impl From<GatherFailed> for GatherError {
fn from(err: GatherFailed) -> GatherError {
match err {
GatherFailed::GroupNotFound(group) => GatherErrorKind::NotFound(group).into(),
GatherFailed::NoAccess => GatherErrorKind::NoAccess.into(),
GatherFailed::NoMasterKey => GatherErrorKind::NoMasterKey.into(),
GatherFailed::InternalError(code) => GatherErrorKind::InternalError(code).into(),
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/error/create_error.rs | wasmer-auth/src/error/create_error.rs | use error_chain::error_chain;
use crate::request::*;
use ate::prelude::*;
error_chain! {
types {
CreateError, CreateErrorKind, ResultExt, Result;
}
links {
QueryError(super::QueryError, super::QueryErrorKind);
AteError(::ate::error::AteError, ::ate::error::AteErrorKind);
ChainCreationError(::ate::error::ChainCreationError, ::ate::error::ChainCreationErrorKind);
SerializationError(::ate::error::SerializationError, ::ate::error::SerializationErrorKind);
InvokeError(::ate::error::InvokeError, ::ate::error::InvokeErrorKind);
}
foreign_links {
IO(tokio::io::Error);
}
errors {
OperatorBanned {
description("create failed as the operator is currently banned")
display("create failed as the operator is currently banned")
}
OperatorNotFound {
description("create failed as the operator could not be found")
display("create failed as the operator could not be found")
}
InvalidArguments {
description("you did not provide the right type or quantity of arguments")
display("you did not provide the right type or quantity of arguments")
}
AccountSuspended {
description("create failed as the account is currently suspended")
display("create failed as the account is currently suspended")
}
MissingReadKey {
description("create failed as the session is missing a read key")
display("create failed as the session is missing a read key")
}
PasswordMismatch {
description("create failed as the passwords did not match")
display("create failed as the passwords did not match")
}
AlreadyExists(msg: String) {
description("create failed as the account or group already exists")
display("create failed - {}", msg)
}
InvalidEmail {
description("create failed as the email address is invalid")
display("create failed as the email address is invalid")
}
NoMoreRoom {
description("create failed as the account or group as there is no more room - try a different name")
display("create failed as the account or group as there is no more room - try a different name")
}
InvalidName(msg: String) {
description("create failed as the account or group name is invalid")
display("create failed - {}", msg)
}
NoMasterKey {
description("create failed as the server has not been properly initialized")
display("create failed as the server has not been properly initialized")
}
ValidationError(reason: String) {
description("create failed as there was a validation error")
display("create failed as there was a validation error - {}", reason)
}
TermsAndConditions(terms: String) {
description("create failed as the caller did not agree to the terms and conditions")
display("create failed as the caller did not agree to the terms and conditions")
}
InternalError(code: u16) {
description("create failed as the server experienced an internal error")
display("create failed as the server experienced an internal error - code={}", code)
}
}
}
impl From<CreateError> for AteError {
fn from(err: CreateError) -> AteError {
AteErrorKind::ServiceError(err.to_string()).into()
}
}
impl From<CreateGroupFailed> for CreateError {
fn from(err: CreateGroupFailed) -> CreateError {
match err {
CreateGroupFailed::OperatorBanned => CreateErrorKind::OperatorBanned.into(),
CreateGroupFailed::OperatorNotFound => CreateErrorKind::OperatorNotFound.into(),
CreateGroupFailed::AccountSuspended => CreateErrorKind::AccountSuspended.into(),
CreateGroupFailed::AlreadyExists(msg) => CreateErrorKind::AlreadyExists(msg).into(),
CreateGroupFailed::NoMoreRoom => CreateErrorKind::NoMoreRoom.into(),
CreateGroupFailed::NoMasterKey => CreateErrorKind::NoMasterKey.into(),
CreateGroupFailed::InvalidGroupName(msg) => CreateErrorKind::InvalidName(msg).into(),
CreateGroupFailed::ValidationError(reason) => {
CreateErrorKind::ValidationError(reason).into()
}
CreateGroupFailed::InternalError(code) => CreateErrorKind::InternalError(code).into(),
}
}
}
impl From<CreateUserFailed> for CreateError {
fn from(err: CreateUserFailed) -> CreateError {
match err {
CreateUserFailed::AlreadyExists(msg) => CreateErrorKind::AlreadyExists(msg).into(),
CreateUserFailed::InvalidEmail => CreateErrorKind::InvalidEmail.into(),
CreateUserFailed::NoMasterKey => CreateErrorKind::NoMasterKey.into(),
CreateUserFailed::NoMoreRoom => CreateErrorKind::NoMoreRoom.into(),
CreateUserFailed::InternalError(code) => CreateErrorKind::InternalError(code).into(),
CreateUserFailed::TermsAndConditions(terms) => {
CreateErrorKind::TermsAndConditions(terms).into()
}
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/error/group_user_remove_error.rs | wasmer-auth/src/error/group_user_remove_error.rs | use error_chain::error_chain;
use crate::request::*;
use ::ate::prelude::*;
error_chain! {
types {
GroupUserRemoveError, GroupUserRemoveErrorKind, ResultExt, Result;
}
links {
QueryError(super::QueryError, super::QueryErrorKind);
AteError(::ate::error::AteError, ::ate::error::AteErrorKind);
ChainCreationError(::ate::error::ChainCreationError, ::ate::error::ChainCreationErrorKind);
SerializationError(::ate::error::SerializationError, ::ate::error::SerializationErrorKind);
InvokeError(::ate::error::InvokeError, ::ate::error::InvokeErrorKind);
GatherError(super::GatherError, super::GatherErrorKind);
}
foreign_links {
IO(tokio::io::Error);
}
errors {
InvalidPurpose {
description("group user remove failed as the role purpose was invalid"),
display("group user remove failed as the role purpose was invalid"),
}
NoAccess {
description("group user remove failed as the referrer has no access to this group")
display("group user remove failed as the referrer has no access to this group")
}
NoMasterKey {
description("group user remove failed as the server has not been properly initialized")
display("group user remove failed as the server has not been properly initialized")
}
GroupNotFound {
description("group user remove failed as the group does not exist")
display("group user remove failed as the group does not exist")
}
RoleNotFound {
description("group user remove failed as the group role does not exist")
display("group user remove failed as the group role does not exist")
}
NothingToRemove {
description("group user remove failed as the user is not a member of this group role")
display("group user remove failed as the user is not a member of this group role")
}
InternalError(code: u16) {
description("group user remove failed as the server experienced an internal error")
display("group user remove failed as the server experienced an internal error - code={}", code)
}
}
}
impl From<GroupUserRemoveError> for AteError {
fn from(err: GroupUserRemoveError) -> AteError {
AteErrorKind::ServiceError(err.to_string()).into()
}
}
impl From<GroupUserRemoveFailed> for GroupUserRemoveError {
fn from(err: GroupUserRemoveFailed) -> GroupUserRemoveError {
match err {
GroupUserRemoveFailed::GroupNotFound => GroupUserRemoveErrorKind::GroupNotFound.into(),
GroupUserRemoveFailed::NoAccess => GroupUserRemoveErrorKind::NoAccess.into(),
GroupUserRemoveFailed::NoMasterKey => GroupUserRemoveErrorKind::NoMasterKey.into(),
GroupUserRemoveFailed::NothingToRemove => {
GroupUserRemoveErrorKind::NothingToRemove.into()
}
GroupUserRemoveFailed::RoleNotFound => GroupUserRemoveErrorKind::RoleNotFound.into(),
GroupUserRemoveFailed::InternalError(code) => {
GroupUserRemoveErrorKind::InternalError(code).into()
}
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/error/group_remove_error.rs | wasmer-auth/src/error/group_remove_error.rs | use error_chain::error_chain;
use crate::request::*;
use ::ate::prelude::*;
error_chain! {
types {
GroupRemoveError, GroupRemoveErrorKind, ResultExt, Result;
}
links {
QueryError(super::QueryError, super::QueryErrorKind);
AteError(::ate::error::AteError, ::ate::error::AteErrorKind);
ChainCreationError(::ate::error::ChainCreationError, ::ate::error::ChainCreationErrorKind);
SerializationError(::ate::error::SerializationError, ::ate::error::SerializationErrorKind);
InvokeError(::ate::error::InvokeError, ::ate::error::InvokeErrorKind);
GatherError(super::GatherError, super::GatherErrorKind);
}
foreign_links {
IO(tokio::io::Error);
}
errors {
NoAccess {
description("group remove failed as the referrer has no access to this group")
display("group remove failed as the referrer has no access to this group")
}
NoMasterKey {
description("group remove failed as the server has not been properly initialized")
display("group remove failed as the server has not been properly initialized")
}
GroupNotFound {
description("group remove failed as the group does not exist")
display("group remove failed as the group does not exist")
}
InternalError(code: u16) {
description("group remove failed as the server experienced an internal error")
display("group remove failed as the server experienced an internal error - code={}", code)
}
}
}
impl From<GroupRemoveError> for AteError {
fn from(err: GroupRemoveError) -> AteError {
AteErrorKind::ServiceError(err.to_string()).into()
}
}
impl From<GroupRemoveFailed> for GroupRemoveError {
fn from(err: GroupRemoveFailed) -> GroupRemoveError {
match err {
GroupRemoveFailed::GroupNotFound => GroupRemoveErrorKind::GroupNotFound.into(),
GroupRemoveFailed::NoAccess => GroupRemoveErrorKind::NoAccess.into(),
GroupRemoveFailed::NoMasterKey => GroupRemoveErrorKind::NoMasterKey.into(),
GroupRemoveFailed::InternalError(code) => {
GroupRemoveErrorKind::InternalError(code).into()
}
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/error/query_error.rs | wasmer-auth/src/error/query_error.rs | use error_chain::error_chain;
use crate::request::*;
use ::ate::prelude::*;
error_chain! {
types {
QueryError, QueryErrorKind, ResultExt, Result;
}
links {
AteError(::ate::error::AteError, ::ate::error::AteErrorKind);
ChainCreationError(::ate::error::ChainCreationError, ::ate::error::ChainCreationErrorKind);
SerializationError(::ate::error::SerializationError, ::ate::error::SerializationErrorKind);
InvokeError(::ate::error::InvokeError, ::ate::error::InvokeErrorKind);
}
foreign_links {
IO(tokio::io::Error);
}
errors {
NotFound {
description("query failed as the user could not be found")
display("query failed as the user could not be found")
}
Banned {
description("query failed as the user has been banned")
display("query failed as the user has been banned")
}
Suspended {
description("query failed as the user has been suspended")
display("query failed as the user has been suspended")
}
InternalError(code: u16) {
description("query failed as the server experienced an internal error")
display("query failed as the server experienced an internal error - code={}", code)
}
}
}
impl From<QueryError> for AteError {
fn from(err: QueryError) -> AteError {
AteErrorKind::ServiceError(err.to_string()).into()
}
}
impl From<QueryFailed> for QueryError {
fn from(err: QueryFailed) -> QueryError {
match err {
QueryFailed::Banned => QueryErrorKind::Banned.into(),
QueryFailed::NotFound => QueryErrorKind::NotFound.into(),
QueryFailed::Suspended => QueryErrorKind::Suspended.into(),
QueryFailed::InternalError(code) => QueryErrorKind::InternalError(code).into(),
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/error/mod.rs | wasmer-auth/src/error/mod.rs | mod create_error;
mod gather_error;
mod group_details_error;
mod group_remove_error;
mod group_user_add_error;
mod group_user_remove_error;
mod login_error;
mod query_error;
mod reset_error;
mod sudo_error;
pub use create_error::CreateError;
pub use create_error::CreateErrorKind;
pub use gather_error::GatherError;
pub use gather_error::GatherErrorKind;
pub use group_details_error::GroupDetailsError;
pub use group_details_error::GroupDetailsErrorKind;
pub use group_remove_error::GroupRemoveError;
pub use group_remove_error::GroupRemoveErrorKind;
pub use group_user_add_error::GroupUserAddError;
pub use group_user_add_error::GroupUserAddErrorKind;
pub use group_user_remove_error::GroupUserRemoveError;
pub use group_user_remove_error::GroupUserRemoveErrorKind;
pub use login_error::LoginError;
pub use login_error::LoginErrorKind;
pub use query_error::QueryError;
pub use query_error::QueryErrorKind;
pub use reset_error::ResetError;
pub use reset_error::ResetErrorKind;
pub use sudo_error::SudoError;
pub use sudo_error::SudoErrorKind;
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/error/group_user_add_error.rs | wasmer-auth/src/error/group_user_add_error.rs | use error_chain::error_chain;
use crate::request::*;
use ::ate::prelude::*;
error_chain! {
types {
GroupUserAddError, GroupUserAddErrorKind, ResultExt, Result;
}
links {
QueryError(super::QueryError, super::QueryErrorKind);
AteError(::ate::error::AteError, ::ate::error::AteErrorKind);
ChainCreationError(::ate::error::ChainCreationError, ::ate::error::ChainCreationErrorKind);
SerializationError(::ate::error::SerializationError, ::ate::error::SerializationErrorKind);
InvokeError(::ate::error::InvokeError, ::ate::error::InvokeErrorKind);
GatherError(super::GatherError, super::GatherErrorKind);
}
foreign_links {
IO(tokio::io::Error);
}
errors {
InvalidPurpose {
description("group user add failed as the role purpose was invalid"),
display("group user add failed as the role purpose was invalid"),
}
UnknownIdentity {
description("group user add failed as the identity of the caller could not be established")
display("group user add failed as the identity of the caller could not be established")
}
GroupNotFound {
description("group user add failed as the referenced group does not exist")
display("group user add failed as the referenced group does not exist")
}
NoAccess {
description("group user add failed as the referrer has no access to this group")
display("group user add failed as the referrer has no access to this group")
}
NoMasterKey {
description("group user add failed as the server has not been properly initialized")
display("group user add failed as the server has not been properly initialized")
}
InternalError(code: u16) {
description("group user add failed as the server experienced an internal error")
display("group user add failed as the server experienced an internal error - code={}", code)
}
}
}
impl From<GroupUserAddError> for AteError {
fn from(err: GroupUserAddError) -> AteError {
AteErrorKind::ServiceError(err.to_string()).into()
}
}
impl From<GroupUserAddFailed> for GroupUserAddError {
fn from(err: GroupUserAddFailed) -> GroupUserAddError {
match err {
GroupUserAddFailed::GroupNotFound => GroupUserAddErrorKind::GroupNotFound.into(),
GroupUserAddFailed::NoAccess => GroupUserAddErrorKind::NoAccess.into(),
GroupUserAddFailed::NoMasterKey => GroupUserAddErrorKind::NoMasterKey.into(),
GroupUserAddFailed::UnknownIdentity => GroupUserAddErrorKind::UnknownIdentity.into(),
GroupUserAddFailed::InvalidPurpose => GroupUserAddErrorKind::InvalidPurpose.into(),
GroupUserAddFailed::InternalError(code) => {
GroupUserAddErrorKind::InternalError(code).into()
}
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/error/login_error.rs | wasmer-auth/src/error/login_error.rs | use error_chain::error_chain;
use std::time::Duration;
use crate::request::*;
use ::ate::prelude::*;
error_chain! {
types {
LoginError, LoginErrorKind, ResultExt, Result;
}
links {
AteError(::ate::error::AteError, ::ate::error::AteErrorKind);
ChainCreationError(::ate::error::ChainCreationError, ::ate::error::ChainCreationErrorKind);
SerializationError(::ate::error::SerializationError, ::ate::error::SerializationErrorKind);
InvokeError(::ate::error::InvokeError, ::ate::error::InvokeErrorKind);
}
foreign_links {
IO(tokio::io::Error);
}
errors {
NoMasterKey {
description("login failed as the server has not been properly initialized")
display("login failed as the server has not been properly initialized")
}
InvalidArguments {
description("you did not provide the right type or quantity of arguments")
display("you did not provide the right type or quantity of arguments")
}
Timeout {
description("login failed due to a timeout"),
display("login failed due to a timeout"),
}
NotFound(username: String) {
description("login failed as the account does not exist"),
display("login failed for {} as the account does not exist", username),
}
AccountLocked(duration: Duration) {
description("login failed as the account is locked"),
display("login failed as the account is locked for {} hours", (duration.as_secs() as f32 / 3600f32)),
}
Unverified(username: String) {
description("login failed as the account is not yet verified")
display("login failed for {} as the account is not yet verified", username)
}
WrongPassword {
description("login failed due to an incorrect password")
display("login failed due to an incorrect password")
}
InternalError(code: u16) {
description("login failed as the server experienced an internal error")
display("login failed as the server experienced an internal error - code={}", code)
}
}
}
impl From<LoginError> for AteError {
fn from(err: LoginError) -> AteError {
AteErrorKind::ServiceError(err.to_string()).into()
}
}
impl From<LoginFailed> for LoginError {
fn from(err: LoginFailed) -> LoginError {
match err {
LoginFailed::AccountLocked(duration) => LoginErrorKind::AccountLocked(duration).into(),
LoginFailed::NoMasterKey => LoginErrorKind::NoMasterKey.into(),
LoginFailed::Unverified(username) => LoginErrorKind::Unverified(username).into(),
LoginFailed::UserNotFound(username) => LoginErrorKind::NotFound(username).into(),
LoginFailed::WrongPassword => LoginErrorKind::WrongPassword.into(),
LoginFailed::InternalError(code) => LoginErrorKind::InternalError(code).into(),
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/error/reset_error.rs | wasmer-auth/src/error/reset_error.rs | use error_chain::error_chain;
use crate::request::*;
use ::ate::prelude::*;
error_chain! {
types {
ResetError, ResetErrorKind, ResultExt, Result;
}
links {
AteError(::ate::error::AteError, ::ate::error::AteErrorKind);
ChainCreationError(::ate::error::ChainCreationError, ::ate::error::ChainCreationErrorKind);
SerializationError(::ate::error::SerializationError, ::ate::error::SerializationErrorKind);
InvokeError(::ate::error::InvokeError, ::ate::error::InvokeErrorKind);
LoginError(super::LoginError, super::LoginErrorKind);
SudoError(super::SudoError, super::SudoErrorKind);
}
foreign_links {
IO(tokio::io::Error);
}
errors {
NotFound(email: String) {
description("reset failed as the user does not exist"),
display("reset failed as the user does not exist ({})", email),
}
PasswordMismatch {
description("reset failed as the passwords did not match")
display("reset failed as the passwords did not match")
}
AuthenticatorCodeEqual {
description("reset failed as you entered the same authenticator code twice")
display("reset failed as you entered the same authenticator code twice")
}
RecoveryImpossible {
description("recovery of this account is impossible")
display("recovery of this account is impossible")
}
InvalidRecoveryCode {
description("the supplied recovery code was not valid")
display("the supplied recovery code was not valid")
}
InvalidAuthenticatorCode {
description("one or more of the supplied authenticator codes was not valid")
display("one or more of the supplied authenticator codes was not valid")
}
NoMasterKey {
description("reset failed as the server has not been properly initialized")
display("reset failed as the server has not been properly initialized")
}
InternalError(code: u16) {
description("reset failed as the server experienced an internal error")
display("reset failed as the server experienced an internal error - code={}", code)
}
}
}
impl From<ResetError> for AteError {
fn from(err: ResetError) -> AteError {
AteErrorKind::ServiceError(err.to_string()).into()
}
}
impl From<ResetFailed> for ResetError {
fn from(err: ResetFailed) -> ResetError {
match err {
ResetFailed::InvalidEmail(email) => ResetErrorKind::NotFound(email).into(),
ResetFailed::InvalidRecoveryCode => ResetErrorKind::InvalidRecoveryCode.into(),
ResetFailed::InvalidAuthenticatorCode => {
ResetErrorKind::InvalidAuthenticatorCode.into()
}
ResetFailed::RecoveryImpossible => ResetErrorKind::RecoveryImpossible.into(),
ResetFailed::NoMasterKey => ResetErrorKind::NoMasterKey.into(),
ResetFailed::InternalError(code) => ResetErrorKind::InternalError(code).into(),
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/error/sudo_error.rs | wasmer-auth/src/error/sudo_error.rs | use error_chain::error_chain;
use std::time::Duration;
use crate::request::*;
use ::ate::prelude::*;
error_chain! {
types {
SudoError, SudoErrorKind, ResultExt, Result;
}
links {
AteError(::ate::error::AteError, ::ate::error::AteErrorKind);
ChainCreationError(::ate::error::ChainCreationError, ::ate::error::ChainCreationErrorKind);
SerializationError(::ate::error::SerializationError, ::ate::error::SerializationErrorKind);
InvokeError(::ate::error::InvokeError, ::ate::error::InvokeErrorKind);
LoginError(super::LoginError, super::LoginErrorKind);
}
foreign_links {
IO(tokio::io::Error);
}
errors {
NoMasterKey {
description("login failed as the server has not been properly initialized")
display("login failed as the server has not been properly initialized")
}
InvalidArguments {
description("you did not provide the right type or quantity of arguments")
display("you did not provide the right type or quantity of arguments")
}
Timeout {
description("login failed due to a timeout"),
display("login failed due to a timeout"),
}
MissingToken {
description("login failed as the token was missing"),
display("login failed as the token was missing"),
}
NotFound(username: String) {
description("login failed as the account does not exist"),
display("login failed for {} as the account does not exist", username),
}
AccountLocked(duration: Duration) {
description("login failed as the account is locked"),
display("login failed as the account is locked for {} hours", (duration.as_secs() as f32 / 3600f32)),
}
Unverified(username: String) {
description("login failed as the account is not yet verified")
display("login failed for {} as the account is not yet verified", username)
}
WrongCode {
description("login failed due to an incorrect authentication code")
display("login failed due to an incorrect authentication code")
}
InternalError(code: u16) {
description("login failed as the server experienced an internal error")
display("login failed as the server experienced an internal error - code={}", code)
}
}
}
impl From<SudoError> for AteError {
fn from(err: SudoError) -> AteError {
AteErrorKind::ServiceError(err.to_string()).into()
}
}
impl From<SudoFailed> for SudoError {
fn from(err: SudoFailed) -> SudoError {
match err {
SudoFailed::AccountLocked(duration) => SudoErrorKind::AccountLocked(duration).into(),
SudoFailed::MissingToken => SudoErrorKind::MissingToken.into(),
SudoFailed::NoMasterKey => SudoErrorKind::NoMasterKey.into(),
SudoFailed::Unverified(username) => SudoErrorKind::Unverified(username).into(),
SudoFailed::UserNotFound(username) => SudoErrorKind::NotFound(username).into(),
SudoFailed::WrongCode => SudoErrorKind::WrongCode.into(),
SudoFailed::InternalError(code) => SudoErrorKind::InternalError(code).into(),
}
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/user.rs | wasmer-auth/src/model/user.rs | use ate::crypto::*;
use ate::prelude::*;
use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use super::*;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct User {
pub email: String,
pub person: DaoChild<Person>,
pub accepted_terms: DaoChild<AcceptedTerms>,
pub verification_code: Option<String>,
pub uid: u32,
pub role: UserRole,
pub status: UserStatus,
pub last_login: Option<chrono::naive::NaiveDate>,
pub access: Vec<Authorization>,
pub foreign: DaoForeign,
pub sudo: DaoChild<Sudo>,
pub advert: DaoChild<Advert>,
pub recovery: DaoChild<UserRecovery>,
pub nominal_read: ate::crypto::AteHash,
pub nominal_public_read: PublicEncryptKey,
pub nominal_write: PublicSignKey,
pub sudo_read: ate::crypto::AteHash,
pub sudo_public_read: PublicEncryptKey,
pub sudo_write: PublicSignKey,
pub broker_read: PrivateEncryptKey,
pub broker_write: PrivateSignKey,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/sudo.rs | wasmer-auth/src/model/sudo.rs | use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use super::*;
use ate::crypto::EncryptKey;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Sudo {
pub email: String,
pub uid: u32,
pub google_auth: String,
pub secret: String,
pub qr_code: String,
pub failed_attempts: u32,
pub contract_read_key: EncryptKey,
pub access: Vec<Authorization>,
pub groups: Vec<String>,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/user_status.rs | wasmer-auth/src/model/user_status.rs | use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum UserStatus {
Nominal,
Unverified,
Locked(chrono::DateTime<chrono::Utc>),
}
impl Default for UserStatus {
fn default() -> Self {
UserStatus::Nominal
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/sms_verification.rs | wasmer-auth/src/model/sms_verification.rs | use ate::crypto::*;
use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SmsVerification {
pub salt: String,
pub hash: AteHash,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/group.rs | wasmer-auth/src/model/group.rs | use ate::prelude::*;
use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use super::*;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Group {
pub name: String,
pub gid: u32,
pub roles: Vec<Role>,
pub foreign: DaoForeign,
pub broker_read: PrivateEncryptKey,
pub broker_write: PrivateSignKey,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/ssh_key_type.rs | wasmer-auth/src/model/ssh_key_type.rs | use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
pub enum SshKeyType {
DSA,
RSA,
ED25519,
ECDSA,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/person.rs | wasmer-auth/src/model/person.rs | use ate::prelude::*;
use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use super::*;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Person {
pub first_name: String,
pub last_name: String,
pub other_names: Vec<String>,
pub date_of_birth: Option<chrono::naive::NaiveDate>,
pub gender: Gender,
pub nationalities: Vec<isocountry::CountryCode>,
pub foreign: DaoForeign,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/user_recovery.rs | wasmer-auth/src/model/user_recovery.rs | use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use ate::prelude::*;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UserRecovery {
pub email: String,
pub google_auth: String,
pub sudo_secret: String,
pub qr_code: String,
pub login_secret: EncryptKey,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/accepted_terms.rs | wasmer-auth/src/model/accepted_terms.rs | use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AcceptedTerms {
pub terms_and_conditions: String,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/user_role.rs | wasmer-auth/src/model/user_role.rs | use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum UserRole {
Human,
Robot,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/company.rs | wasmer-auth/src/model/company.rs | use ate::prelude::*;
use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use super::*;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Company {
pub domain: String,
pub registration_no: String,
pub tax_id: String,
pub phone_number: String,
pub email: String,
pub do_business_as: String,
pub legal_business_name: String,
pub share_holders: DaoVec<Person>,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/advert.rs | wasmer-auth/src/model/advert.rs | use ate::crypto::*;
use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum AdvertId {
UID(u32),
GID(u32),
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Advert {
pub identity: String,
pub id: AdvertId,
pub nominal_encrypt: PublicEncryptKey,
pub nominal_auth: PublicSignKey,
pub sudo_encrypt: PublicEncryptKey,
pub sudo_auth: PublicSignKey,
pub broker_encrypt: PublicEncryptKey,
pub broker_auth: PublicSignKey,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/email_verification.rs | wasmer-auth/src/model/email_verification.rs | use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct EmailVerification {
pub code: String,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/mod.rs | wasmer-auth/src/model/mod.rs | mod accepted_terms;
mod advert;
mod authentication_method;
mod authorization;
mod company;
mod email_verification;
mod gender;
mod group;
mod person;
mod role;
mod sms_verification;
mod ssh_key_type;
mod sudo;
mod user;
mod user_recovery;
mod user_role;
mod user_status;
pub use accepted_terms::*;
pub use advert::*;
pub use authentication_method::*;
pub use authorization::*;
pub use company::*;
pub use email_verification::*;
pub use gender::*;
pub use group::*;
pub use person::*;
pub use role::*;
pub use sms_verification::*;
pub use ssh_key_type::*;
pub use sudo::*;
pub use user::*;
pub use user_recovery::*;
pub use user_role::*;
pub use user_status::*;
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/authentication_method.rs | wasmer-auth/src/model/authentication_method.rs | use ate::crypto::*;
use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use super::*;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum AuthenticationMethod {
WithPrivateKey(PublicSignKey),
WithPassword {
salt: String,
hash: AteHash,
},
WithAuthenticator {
secret: String,
},
WithSmsAuthentication {
salt: String,
hash: AteHash,
},
WithEmailVerification {
code: String,
},
WithSshKey {
key_type: SshKeyType,
secret: String,
},
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/gender.rs | wasmer-auth/src/model/gender.rs | use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum Gender {
Unspecified,
Male,
Female,
Other,
}
impl Default for Gender {
fn default() -> Self {
Gender::Unspecified
}
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/role.rs | wasmer-auth/src/model/role.rs | use ate::crypto::*;
use ate::prelude::*;
use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use super::*;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Role {
pub purpose: AteRolePurpose,
pub read: AteHash,
pub private_read: PublicEncryptKey,
pub write: PublicSignKey,
pub access: MultiEncryptedSecureData<Authorization>,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/model/authorization.rs | wasmer-auth/src/model/authorization.rs | use ate::crypto::*;
use serde::*;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Authorization {
pub read: EncryptKey,
pub private_read: PrivateEncryptKey,
pub write: PrivateSignKey,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/user.rs | wasmer-auth/src/opt/user.rs | use clap::Parser;
use super::*;
#[derive(Parser)]
#[clap()]
pub struct OptsUser {
#[clap(subcommand)]
pub action: UserAction,
}
#[derive(Parser)]
pub enum UserAction {
/// Creates a new user and generates login credentials
#[clap()]
Create(CreateUser),
/// Returns all the details about a specific user
#[clap()]
Details,
/// Recovers a lost account using your recovery code
#[clap()]
Recover(ResetUser),
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/gather_permissions.rs | wasmer-auth/src/opt/gather_permissions.rs | use clap::Parser;
/// Gathers the permissions needed to access a specific group into the token using either another supplied token or the prompted credentials
#[derive(Parser)]
pub struct GatherPermissions {
/// Name of the group to gather the permissions for
#[clap(index = 1)]
pub group: String,
/// Determines if sudo permissions should be sought
#[clap(long)]
pub sudo: bool,
/// Display the token in human readable format
#[clap(long)]
pub human: bool,
/// Summarises the token rather than returning it
#[clap(long)]
pub summary: bool,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/group_add_user.rs | wasmer-auth/src/opt/group_add_user.rs | use ate::prelude::*;
use clap::Parser;
/// Adds a particular user to a role within a group
#[derive(Parser)]
pub struct GroupAddUser {
/// Name of the group that the user will be added to
#[clap(index = 1)]
pub group: String,
/// Role within the group that the user will be added to, must be one of the following
/// [owner, delegate, contributor, observer, other-...]. Only owners and delegates can
/// modify the groups. Generally write actions are only allowed by members of the
/// 'contributor' role and all read actions require the 'observer' role.
#[clap(index = 2)]
pub role: AteRolePurpose,
/// Username that will be added to the group role
#[clap(index = 3)]
pub username: String,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/create_user.rs | wasmer-auth/src/opt/create_user.rs | use clap::Parser;
/// Creates a new user and login credentials on the authentication server
#[derive(Parser)]
pub struct CreateUser {
/// Email address of the user to be created
#[clap(index = 1)]
pub email: Option<String>,
/// New password to be associated with this account
#[clap(index = 2)]
pub password: Option<String>,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/view_token.rs | wasmer-auth/src/opt/view_token.rs | use clap::Parser;
/// Views the contents of the current token
#[derive(Parser)]
pub struct ViewToken {}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/group.rs | wasmer-auth/src/opt/group.rs | use clap::Parser;
use super::*;
#[allow(dead_code)]
#[derive(Parser)]
#[clap(version = "1.5", author = "Wasmer Inc <info@wasmer.io>")]
pub struct OptsDomain {
#[clap(subcommand)]
pub action: GroupAction,
}
#[derive(Parser)]
pub enum GroupAction {
/// Creates a new group
#[clap()]
Create(CreateGroup),
/// Removes the existing group
#[clap()]
RemoveGroup(GroupRemove),
/// Adds another user to an existing group
#[clap()]
AddUser(GroupAddUser),
/// Removes a user from an existing group
#[clap()]
RemoveUser(GroupRemoveUser),
/// Display the details about a particular group (token is required to see role membership)
#[clap()]
Details(GroupDetails),
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/database_details.rs | wasmer-auth/src/opt/database_details.rs | use clap::Parser;
/// Display the details about a particular database
#[derive(Parser)]
pub struct DatabaseDetails {
/// Name of the database to query
#[clap(index = 1)]
pub name: String,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/reset_user.rs | wasmer-auth/src/opt/reset_user.rs | use clap::Parser;
/// Recovers a lost account using the recovery code that you stored somewhere safely when you created your account
#[derive(Parser)]
pub struct ResetUser {
/// Email address of the user to be recovered
#[clap(index = 1)]
pub email: Option<String>,
/// Recovery code that you stored somewhere safely when you created your account
#[clap(index = 2)]
pub recovery_code: Option<String>,
/// New password for the user
#[clap(index = 3)]
pub new_password: Option<String>,
/// The authenticator code from your mobile authenticator
#[clap(index = 4)]
pub auth_code: Option<String>,
/// The next authenticator code from your mobile authenticator
#[clap(index = 5)]
pub next_auth_code: Option<String>,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/core.rs | wasmer-auth/src/opt/core.rs | use clap::Parser;
use url::Url;
use super::*;
#[derive(Parser)]
#[clap(version = "1.5", author = "John S. <johnathan.sharratt@gmail.com>")]
pub struct Opts {
/// Sets the level of log verbosity, can be used multiple times
#[clap(short, long, parse(from_occurrences))]
pub verbose: i32,
/// URL where the user is authenticated (e.g. wss://wasmer.sh/auth)
#[clap(short, long)]
pub auth: Option<Url>,
/// Token used to access your encrypted file-system (if you do not supply a token then you will
/// be prompted for a username and password)
#[clap(short, long)]
pub token: Option<String>,
/// Token file to read that holds a previously created token to be used to access your encrypted
/// file-system (if you do not supply a token then you will be prompted for a username and password)
#[clap(long)]
pub token_path: Option<String>,
/// Logs debug info to the console
#[clap(short, long)]
pub debug: bool,
#[clap(subcommand)]
pub subcmd: SubCommand,
}
#[derive(Parser)]
pub enum SubCommand {
/// Users are personal accounts and services that have an authentication context
#[clap()]
User(OptsUser),
/// Groups are collections of users that share something together
#[clap()]
Group(OptsDomain),
/// Tokens are stored authentication and authorization secrets used by other processes
#[clap()]
Token(OptsToken),
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/database_truncate.rs | wasmer-auth/src/opt/database_truncate.rs | use clap::Parser;
/// Removes a previously created database with a specific name
#[derive(Parser)]
pub struct DatabaseTruncate {
/// Name of the database to be removed
#[clap(index = 1)]
pub name: String,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/database.rs | wasmer-auth/src/opt/database.rs | use clap::Parser;
use url::Url;
use super::*;
#[derive(Parser)]
#[clap()]
pub struct OptsDatabase {
/// URL where the data is remotely stored on a distributed commit log (e.g. wss://wasmer.sh/db).
#[clap(short, long)]
pub remote: Option<Url>,
#[clap(subcommand)]
pub action: DatabaseAction,
}
#[derive(Parser)]
pub enum DatabaseAction {
/// Truncates an existing database by tombstoning all the events
#[clap()]
Truncate(DatabaseTruncate),
/// Display the details about a particular database
#[clap()]
Details(DatabaseDetails),
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/group_details.rs | wasmer-auth/src/opt/group_details.rs | use clap::Parser;
/// Display the details about a particular group
#[derive(Parser)]
pub struct GroupDetails {
/// Name of the group to query
#[clap(index = 1)]
pub group: String,
/// Determines if sudo permissions should be sought
#[clap(long)]
pub sudo: bool,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/mod.rs | wasmer-auth/src/opt/mod.rs | mod core;
mod create_group;
mod create_user;
mod database;
mod database_details;
mod database_truncate;
mod gather_permissions;
mod generate_token;
mod generate_token_sudo;
mod group;
mod group_add_user;
mod group_details;
mod group_remove;
mod group_remove_user;
mod reset_user;
mod token;
mod user;
mod view_token;
pub use self::core::*;
pub use create_group::*;
pub use create_user::*;
pub use database::*;
pub use database_details::*;
pub use database_truncate::*;
pub use gather_permissions::*;
pub use generate_token::*;
pub use generate_token_sudo::*;
pub use group::*;
pub use group_add_user::*;
pub use group_details::*;
pub use group_remove::*;
pub use group_remove_user::*;
pub use reset_user::*;
pub use token::*;
pub use user::*;
pub use view_token::*;
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/create_group.rs | wasmer-auth/src/opt/create_group.rs | use clap::Parser;
/// Creates a new group using the login credentials provided or prompted for
#[derive(Parser)]
pub struct CreateGroup {
/// Name of the group to be created
#[clap(index = 1)]
pub group: String,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/group_remove_user.rs | wasmer-auth/src/opt/group_remove_user.rs | use ate::prelude::*;
use clap::Parser;
/// Removes a particular user from a role within a group
#[derive(Parser)]
pub struct GroupRemoveUser {
/// Name of the group that the user will be removed from
#[clap(index = 1)]
pub group: String,
/// Role within the group that the user will be removed from, must be one of the following
/// [owner, delegate, contributor, observer, other-...]. Only owners and delegates can
/// modify the groups. Generally write actions are only allowed by members of the
/// 'contributor' role and all read actions require the 'observer' role.
#[clap(index = 2)]
pub role: AteRolePurpose,
/// Username that will be removed to the group role
#[clap(index = 3)]
pub username: String,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/group_remove.rs | wasmer-auth/src/opt/group_remove.rs | use clap::Parser;
/// Removes a particular group
#[derive(Parser)]
pub struct GroupRemove {
/// Name of the group to be removed
#[clap(index = 1)]
pub group: String,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/generate_token_sudo.rs | wasmer-auth/src/opt/generate_token_sudo.rs | use clap::Parser;
/// Logs into the authentication server using the supplied credentials and 2nd factor authentication
#[derive(Parser)]
pub struct CreateTokenSudo {
/// Email address that you wish to login using
#[clap(index = 1)]
pub email: Option<String>,
/// Password associated with this account
#[clap(index = 2)]
pub password: Option<String>,
/// Authenticator code from your google authenticator
#[clap(index = 3)]
pub code: Option<String>,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/generate_token.rs | wasmer-auth/src/opt/generate_token.rs | use clap::Parser;
/// Logs into the authentication server using the supplied credentials
#[derive(Parser)]
pub struct GenerateToken {
/// Email address that you wish to login using
#[clap(index = 1)]
pub email: Option<String>,
/// Password associated with this account
#[clap(index = 2)]
pub password: Option<String>,
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/opt/token.rs | wasmer-auth/src/opt/token.rs | use clap::Parser;
use super::*;
#[allow(dead_code)]
#[derive(Parser)]
#[clap(version = "1.5", author = "Wasmer Inc <info@wasmer.io>")]
pub struct OptsToken {
#[clap(subcommand)]
pub action: TokenAction,
}
#[derive(Parser)]
pub enum TokenAction {
/// Generate a token with normal permissions from the supplied username and password
#[clap()]
Generate(GenerateToken),
/// Generate a token with extra permissions with elevated rights to modify groups and other higher risk actions
#[clap()]
Sudo(CreateTokenSudo),
/// Gather the permissions needed to access a specific group into the token using either another supplied token or the prompted credentials
#[clap()]
Gather(GatherPermissions),
/// Views the contents of the supplied token
#[clap()]
View(ViewToken),
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/bin/auth-tools.rs | wasmer-auth/src/bin/auth-tools.rs | #![allow(unused_imports)]
use ate::prelude::*;
use wasmer_auth::cmd::*;
use wasmer_auth::opt::*;
use wasmer_auth::prelude::*;
use wasmer_auth::prelude::*;
use clap::Parser;
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use url::Url;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), AteError> {
let opts: Opts = Opts::parse();
ate::log_init(opts.verbose, opts.debug);
// Determine what we need to do
let auth = wasmer_auth::prelude::origin_url(&opts.auth, "auth");
match opts.subcmd {
SubCommand::User(opts_user) => {
main_opts_user(opts_user, opts.token, opts.token_path, auth).await?;
}
SubCommand::Group(opts_group) => {
main_opts_group(opts_group, opts.token, opts.token_path, auth, "Group").await?;
}
SubCommand::Token(opts_token) => {
main_opts_token(opts_token, opts.token, opts.token_path, auth, "Group").await?;
}
}
// We are done
Ok(())
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/bin/auth-server.rs | wasmer-auth/src/bin/auth-server.rs | use ate::prelude::*;
use ate::utils::load_node_list;
use clap::Parser;
#[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use wasmer_auth::helper::*;
use wasmer_auth::prelude::*;
#[derive(Parser)]
#[clap(version = "1.5", author = "John S. <johnathan.sharratt@gmail.com>")]
struct Opts {
/// Sets the level of log verbosity, can be used multiple times
#[clap(short, long, parse(from_occurrences))]
verbose: i32,
/// Logs debug info to the console
#[clap(short, long)]
debug: bool,
#[clap(subcommand)]
subcmd: SubCommand,
}
#[derive(Parser)]
enum SubCommand {
#[clap()]
Run(Run),
#[clap()]
Generate(Generate),
}
/// Runs the login authentication and authorization server
#[derive(Parser)]
struct Run {
/// Optional list of the nodes that make up this cluster
#[clap(long)]
nodes_list: String,
/// Path to the secret key that helps protect key operations like creating users and resetting passwords
#[clap(long, default_value = "~/wasmer/auth.key")]
auth_key_path: String,
/// Path to the secret key that grants access to the WebServer role within groups
#[clap(long, default_value = "~/wasmer/web.key")]
web_key_path: String,
/// Path to the secret key that grants access to the EdgeCompute role within groups
#[clap(long, default_value = "~/wasmer/edge.key")]
edge_key_path: String,
/// Path to the secret key that grants access to the contracts
#[clap(long, default_value = "~/wasmer/contract.key")]
contract_key_path: String,
/// Path to the certificate file that will be used by an listening servers
/// (there must be TXT records in the host domain servers for this cert)
#[clap(long, default_value = "~/wasmer/cert")]
cert_path: String,
/// Path to the log files where all the authentication data is stored
#[clap(index = 1, default_value = "~/wasmer/auth")]
logs_path: String,
/// Path to the backup and restore location of log files
#[clap(short, long)]
backup_path: Option<String>,
/// Address that the authentication server(s) are listening and that
/// this server can connect to if the chain is on another mesh node
#[clap(short, long, default_value = "ws://localhost:5001/auth")]
url: url::Url,
/// IP address that the authentication server will isten on
#[clap(short, long, default_value = "::")]
listen: IpAddr,
/// Ensures that this authentication server runs as a specific node_id
#[clap(short, long)]
node_id: Option<u32>,
}
/// Generates the secret key that helps protect key operations like creating users and resetting passwords
#[derive(Parser)]
struct Generate {
/// Path to the secret key
#[clap(index = 1, default_value = "~/wasmer/")]
key_path: String,
/// Strength of the key that will be generated
#[clap(short, long, default_value = "256")]
strength: KeySize,
}
fn ctrl_channel() -> tokio::sync::watch::Receiver<bool> {
let (sender, receiver) = tokio::sync::watch::channel(false);
ctrlc_async::set_handler(move || {
let _ = sender.send(true);
})
.unwrap();
receiver
}
#[tokio::main(flavor = "multi_thread")]
async fn main() -> Result<(), AteError> {
let opts: Opts = Opts::parse();
ate::log_init(opts.verbose, opts.debug);
// Determine what we need to do
match opts.subcmd {
SubCommand::Run(run) => {
// Open the key file
let root_write_key: PrivateSignKey = load_key(run.auth_key_path.clone(), ".write");
let root_read_key: EncryptKey = load_key(run.auth_key_path.clone(), ".read");
let root_cert_key: PrivateEncryptKey = load_key(run.cert_path.clone(), "");
let web_key: EncryptKey = load_key(run.web_key_path.clone(), ".read");
let edge_key: EncryptKey = load_key(run.edge_key_path.clone(), ".read");
let contract_key: EncryptKey = load_key(run.contract_key_path.clone(), ".read");
// Build a session for service
let mut cfg_ate = conf_auth();
cfg_ate.log_path = Some(shellexpand::tilde(&run.logs_path).to_string());
if let Some(backup_path) = run.backup_path {
cfg_ate.backup_path = Some(shellexpand::tilde(&backup_path).to_string());
}
cfg_ate.compact_mode = CompactMode::Never;
cfg_ate.nodes = load_node_list(Some(run.nodes_list));
let mut session = AteSessionUser::new();
session.user.add_read_key(&root_read_key);
session.user.add_write_key(&root_write_key);
// Create the server and listen
let mut flow = ChainFlow::new(
&cfg_ate,
root_write_key,
session,
web_key,
edge_key,
contract_key,
&run.url,
);
flow.terms_and_conditions = Some(wasmer_auth::GENERIC_TERMS_AND_CONDITIONS.to_string());
let mut cfg_mesh =
ConfMesh::solo_from_url(&cfg_ate, &run.url, &run.listen, None, run.node_id).await?;
cfg_mesh.wire_protocol = StreamProtocol::parse(&run.url)?;
cfg_mesh.listen_certificate = Some(root_cert_key);
let server = create_server(&cfg_mesh).await?;
server.add_route(Box::new(flow), &cfg_ate).await?;
// Wait for ctrl-c
let mut exit = ctrl_channel();
while *exit.borrow() == false {
exit.changed().await.unwrap();
}
println!("Shutting down...");
server.shutdown().await;
println!("Goodbye!");
}
SubCommand::Generate(generate) => {
let mut key_path = generate.key_path.clone();
if key_path.ends_with("/") == false {
key_path += "/";
}
let read_key = EncryptKey::generate(generate.strength);
save_key(key_path.clone(), read_key, "auth.key.read");
let write_key = PrivateSignKey::generate(generate.strength);
save_key(key_path.clone(), write_key, "auth.key.write");
let cert_key = PrivateEncryptKey::generate(generate.strength);
save_key(key_path.clone(), cert_key, "cert");
let web_key = EncryptKey::generate(generate.strength);
save_key(key_path.clone(), web_key, "web.key.read");
let edge_key = EncryptKey::generate(generate.strength);
save_key(key_path.clone(), edge_key, "edge.key.read");
let contract_key = EncryptKey::generate(generate.strength);
save_key(key_path.clone(), contract_key, "contract.key.read");
}
}
// We are done
Ok(())
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
wasmerio/ate | https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-auth/src/helper/misc.rs | wasmer-auth/src/helper/misc.rs | #[allow(unused_imports)]
use tracing::{debug, error, info, instrument, span, trace, warn, Level};
use ::ate::crypto::EncryptKey;
use ::ate::prelude::*;
pub fn password_to_read_key(
seed: &String,
password: &String,
repeat: i32,
key_size: KeySize,
) -> EncryptKey {
let mut bytes = Vec::from(seed.as_bytes());
bytes.extend(Vec::from(password.as_bytes()).iter());
while bytes.len() < 1000 {
bytes.push(0);
}
let hash = AteHash::from_bytes_sha3(password.as_bytes(), repeat);
EncryptKey::from_seed_bytes(hash.as_bytes(), key_size)
}
pub fn estimate_user_name_as_uid(email: String) -> u32 {
let min = ((u32::MAX as u64) * 2) / 4;
let max = ((u32::MAX as u64) * 3) / 4;
PrimaryKey::from_ext(AteHash::from(email), min as u64, max as u64).as_u64() as u32
}
pub fn estimate_group_name_as_gid(group: String) -> u32 {
let min = ((u32::MAX as u64) * 3) / 4;
let max = ((u32::MAX as u64) * 4) / 4;
PrimaryKey::from_ext(AteHash::from(group), min as u64, max as u64).as_u64() as u32
}
pub fn session_to_b64(session: AteSessionType) -> Result<String, SerializationError> {
let format = SerializationFormat::MessagePack;
let bytes = format.serialize(&session)?;
Ok(base64::encode(bytes))
}
pub fn b64_to_session(val: String) -> AteSessionType {
let val = val.trim().to_string();
let format = SerializationFormat::MessagePack;
let bytes = base64::decode(val).unwrap();
format.deserialize(bytes).unwrap()
}
#[allow(dead_code)]
pub fn is_public_domain(domain: &str) -> bool {
match domain {
"gmail.com" => true,
"zoho.com" => true,
"outlook.com" => true,
"hotmail.com" => true,
"mail.com" => true,
"yahoo.com" => true,
"gmx.com" => true,
"hushmail.com" => true,
"hush.com" => true,
"inbox.com" => true,
"aol.com" => true,
"yandex.com" => true,
_ => false,
}
}
#[cfg(any(feature = "force_tty", not(feature = "tty")))]
pub fn is_tty_stdin() -> bool {
true
}
#[cfg(all(not(feature = "force_tty"), feature = "tty"))]
pub fn is_tty_stdin() -> bool {
atty::is(atty::Stream::Stdin)
}
#[cfg(any(feature = "force_tty", not(feature = "tty")))]
pub fn is_tty_stdout() -> bool {
true
}
#[cfg(all(not(feature = "force_tty"), feature = "tty"))]
pub fn is_tty_stdout() -> bool {
atty::is(atty::Stream::Stdout)
}
#[cfg(any(feature = "force_tty", not(feature = "tty")))]
pub fn is_tty_stderr() -> bool {
true
}
#[cfg(all(not(feature = "force_tty"), feature = "tty"))]
pub fn is_tty_stderr() -> bool {
atty::is(atty::Stream::Stderr)
}
| rust | Apache-2.0 | 87635b5b49c4163885ce840f4f1c2f30977f40cc | 2026-01-04T20:14:33.413949Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.