Compare commits

..

No commits in common. "8b15acf98353f7880bbc510e279ca35770601de1" and "ca25cd83d09aa396da4c4be9764a96191309e058" have entirely different histories.

28 changed files with 93 additions and 73 deletions

View File

@ -12,7 +12,7 @@ use std::future::Future;
use std::pin::Pin;
use miette::Diagnostic;
use miette::{Diagnostic, IntoDiagnostic};
use std::task::{Context, Poll};
use std::time::Duration;
use thiserror::Error;

View File

@ -2,6 +2,7 @@ use desfire::desfire::desfire::MAX_BYTES_PER_TRANSACTION;
use desfire::desfire::Desfire;
use desfire::error::Error as DesfireError;
use desfire::iso7816_4::apduresponse::APDUResponse;
use rsasl::callback::SessionData;
use rsasl::mechanism::{
Authentication, Demand, DemandReply, MechanismData, MechanismError, MechanismErrorKind,
Provider, State, ThisProvider,
@ -12,6 +13,7 @@ use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use std::fmt::{Debug, Display, Formatter};
use std::io::Write;
use std::sync::Arc;
use crate::authentication::fabfire::FabFireCardKey;
@ -102,7 +104,6 @@ struct AuthInfo {
iv: Vec<u8>,
}
#[allow(non_camel_case_types)]
#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "Cmd")]
enum CardCommand {

View File

@ -2,6 +2,7 @@ use desfire::desfire::desfire::MAX_BYTES_PER_TRANSACTION;
use desfire::desfire::Desfire;
use desfire::error::Error as DesfireError;
use desfire::iso7816_4::apduresponse::APDUResponse;
use rsasl::callback::SessionData;
use rsasl::mechanism::{
Authentication, Demand, DemandReply, MechanismData, MechanismError, MechanismErrorKind,
Provider, State, ThisProvider,
@ -12,6 +13,7 @@ use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use std::fmt::{Debug, Display, Formatter};
use std::io::Write;
use std::sync::Arc;
use crate::authentication::fabfire::FabFireCardKey;
use crate::CONFIG;

View File

@ -26,7 +26,7 @@ impl Callback {
impl SessionCallback for Callback {
fn callback(
&self,
_session_data: &SessionData,
session_data: &SessionData,
context: &Context,
request: &mut Request,
) -> Result<(), SessionError> {

View File

@ -4,8 +4,10 @@ use capnp_rpc::pry;
use rsasl::mechname::Mechname;
use rsasl::prelude::State as SaslState;
use rsasl::prelude::{MessageSent, Session};
use rsasl::property::AuthId;
use std::fmt;
use std::fmt::{Formatter, Write};
use std::io::Cursor;
use tracing::Span;
use crate::authentication::V;
@ -113,7 +115,7 @@ impl AuthenticationSystem for Authentication {
f.write_char(')')
}
}
let response;
let mut response;
let mut builder = results.get();
if let State::Running(mut session, manager) =

View File

@ -211,6 +211,7 @@ impl ManageServer for Machine {
mut result: manage::GetMachineInfoExtendedResults,
) -> Promise<(), ::capnp::Error> {
let mut builder = result.get();
let user = User::new_self(self.session.clone());
User::build_optional(
&self.session,
self.resource.get_current_user(),

View File

@ -5,11 +5,11 @@ use async_net::TcpListener;
use capnp_rpc::rpc_twoparty_capnp::Side;
use capnp_rpc::twoparty::VatNetwork;
use capnp_rpc::RpcSystem;
use executor::prelude::{Executor, SupervisionRegistry};
use executor::prelude::{Executor, GroupId, SupervisionRegistry};
use futures_rustls::server::TlsStream;
use futures_rustls::TlsAcceptor;
use futures_util::stream::FuturesUnordered;
use futures_util::{stream, AsyncRead, AsyncWrite, StreamExt};
use futures_util::{stream, AsyncRead, AsyncWrite, FutureExt, StreamExt};
use std::future::Future;
use std::io;

View File

@ -1,3 +1,4 @@
use crate::authorization::roles::Role;
use crate::Roles;
use api::permissionsystem_capnp::permission_system::info::{
GetRoleListParams, GetRoleListResults, Server as PermissionSystem,
@ -36,7 +37,7 @@ impl PermissionSystem for Permissions {
tracing::trace!("method call");
let roles = self.roles.list().collect::<Vec<&String>>();
let builder = results.get();
let mut builder = results.get();
let mut b = builder.init_role_list(roles.len() as u32);
for (i, role) in roles.into_iter().enumerate() {
let mut role_builder = b.reborrow().get(i as u32);

View File

@ -109,7 +109,7 @@ impl manage::Server for User {
if let Some(mut user) = self.session.users.get_user(uid) {
if let Ok(true) = user.check_password(old_pw.as_bytes()) {
user.set_pw(new_pw.as_bytes());
pry!(self.session.users.put_user(uid, &user));
self.session.users.put_user(uid, &user);
}
}
Promise::ok(())
@ -143,9 +143,9 @@ impl admin::Server for User {
// Only update if needed
if !target.userdata.roles.iter().any(|r| r.as_str() == rolename) {
target.userdata.roles.push(rolename.to_string());
pry!(self.session
self.session
.users
.put_user(self.user.get_username(), &target));
.put_user(self.user.get_username(), &target);
}
}
@ -168,9 +168,9 @@ impl admin::Server for User {
// Only update if needed
if target.userdata.roles.iter().any(|r| r.as_str() == rolename) {
target.userdata.roles.retain(|r| r.as_str() != rolename);
pry!(self.session
self.session
.users
.put_user(self.user.get_username(), &target));
.put_user(self.user.get_username(), &target);
}
}
@ -185,7 +185,7 @@ impl admin::Server for User {
let uid = self.user.get_username();
if let Some(mut user) = self.session.users.get_user(uid) {
user.set_pw(new_pw.as_bytes());
pry!(self.session.users.put_user(uid, &user));
self.session.users.put_user(uid, &user);
}
Promise::ok(())
}
@ -221,7 +221,7 @@ impl card_d_e_s_fire_e_v2::Server for User {
Vec::new()
});
if !tk.is_empty() {
let b = results.get();
let mut b = results.get();
let mut lb = b.init_token_list(1);
lb.set(0, &tk[..]);
}
@ -299,8 +299,7 @@ impl card_d_e_s_fire_e_v2::Server for User {
.insert("cardtoken".to_string(), token.to_string());
user.userdata.kv.insert("cardkey".to_string(), card_key);
pry!(self.session.users.put_user(self.user.get_username(), &user));
self.session.users.put_user(self.user.get_username(), &user);
Promise::ok(())
}
@ -339,7 +338,7 @@ impl card_d_e_s_fire_e_v2::Server for User {
}
}
pry!(self.session.users.put_user(self.user.get_username(), &user));
self.session.users.put_user(self.user.get_username(), &user);
Promise::ok(())
}

View File

@ -84,13 +84,13 @@ impl manage::Server for Users {
"method call"
);
let builder = result.get();
let mut builder = result.get();
if !username.is_empty() && !password.is_empty() {
if self.session.users.get_user(username).is_none() {
let user = db::User::new_with_plain_pw(username, password);
pry!(self.session.users.put_user(username, &user));
let builder = builder.init_successful();
self.session.users.put_user(username, &user);
let mut builder = builder.init_successful();
User::fill(&self.session, user, builder);
} else {
let mut builder = builder.init_failed();

View File

@ -1,6 +1,8 @@
use std::collections::HashMap;
use std::default::Default;
use std::fmt::Debug;
use std::error::Error;
use std::fmt::{Debug, Display};
use std::marker::PhantomData;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
@ -10,6 +12,7 @@ use crate::authorization::roles::Role;
use crate::capnp::{Listen, TlsListen};
use crate::logging::LogConfig;
use miette::IntoDiagnostic;
use std::path::Path;
#[derive(Debug)]

View File

@ -38,15 +38,13 @@ pub fn read(file: impl AsRef<Path>) -> Result<Config, ConfigError> {
if !path.is_file() {
return Err(ConfigError::NotAFile(path.to_string_lossy().to_string()));
}
let config = dhall::read_config_file(file)?;
// TODO: configuration by environment variables?
// but rather in in a separate function
// for (envvar, value) in std::env::vars() {
// match envvar.as_str() {
// // Do things like this?
// // "BFFH_LOG" => config.logging.filter = Some(value),
// _ => {}
// }
// }
let mut config = dhall::read_config_file(file)?;
for (envvar, value) in std::env::vars() {
match envvar.as_str() {
// Do things like this?
// "BFFH_LOG" => config.logging.filter = Some(value),
_ => {}
}
}
Ok(config)
}

View File

@ -1,13 +1,10 @@
use thiserror::Error;
// for converting a database error into a failed promise
use capnp;
mod raw;
use miette::{Diagnostic, Severity};
use miette::{Diagnostic, LabeledSpan, Severity, SourceCode};
pub use raw::RawDB;
use std::fmt::{Debug, Display};
use std::fmt::{Debug, Display, Formatter};
mod typed;
pub use typed::{Adapter, AlignedAdapter, ArchivedValue, DB};
@ -82,9 +79,3 @@ impl Diagnostic for Error {
None
}
}
impl From<Error> for capnp::Error {
fn from(dberr: Error) -> capnp::Error {
capnp::Error::failed(format!("database error: {}", dberr.to_string()))
}
}

View File

@ -1,3 +1,4 @@
use super::Result;
use lmdb::{DatabaseFlags, Environment, RwTransaction, Transaction, WriteFlags};
#[derive(Debug, Clone)]

View File

@ -1,4 +1,4 @@
use miette::{Diagnostic, Severity};
use miette::{Diagnostic, LabeledSpan, Severity, SourceCode};
use std::error;
use std::fmt::{Display, Formatter};
use std::io;

View File

@ -5,11 +5,14 @@ use super::Initiator;
use crate::initiators::InitiatorCallbacks;
use crate::resources::modules::fabaccess::Status;
use crate::session::SessionHandle;
use crate::users::UserRef;
use async_io::Timer;
use futures_util::future::BoxFuture;
use futures_util::ready;
use lmdb::Stat;
use std::collections::HashMap;
use std::future::Future;
use std::mem;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
@ -61,7 +64,10 @@ impl Future for Dummy {
match &mut self.state {
DummyState::Empty => {
tracing::trace!("Dummy initiator is empty, initializing…");
self.state = DummyState::Sleeping(Self::timer(), Some(Status::Free));
mem::replace(
&mut self.state,
DummyState::Sleeping(Self::timer(), Some(Status::Free)),
);
}
DummyState::Sleeping(timer, next) => {
tracing::trace!("Sleep timer exists, polling it.");
@ -72,7 +78,7 @@ impl Future for Dummy {
let status = next.take().unwrap();
let f = self.flip(status);
self.state = DummyState::Updating(f);
mem::replace(&mut self.state, DummyState::Updating(f));
}
DummyState::Updating(f) => {
tracing::trace!("Update future exists, polling it .");
@ -81,7 +87,10 @@ impl Future for Dummy {
tracing::trace!("Update future completed, sleeping!");
self.state = DummyState::Sleeping(Self::timer(), Some(next));
mem::replace(
&mut self.state,
DummyState::Sleeping(Self::timer(), Some(next)),
);
}
}
}

View File

@ -3,15 +3,22 @@ use crate::initiators::process::Process;
use crate::resources::modules::fabaccess::Status;
use crate::session::SessionHandle;
use crate::{
AuthenticationHandle, Config, Resource, ResourcesHandle, SessionManager,
AuthenticationHandle, Config, MachineState, Resource, ResourcesHandle, SessionManager,
};
use async_compat::CompatExt;
use executor::prelude::Executor;
use futures_util::ready;
use miette::IntoDiagnostic;
use rumqttc::ConnectReturnCode::Success;
use rumqttc::{AsyncClient, ConnectionError, Event, Incoming, MqttOptions};
use std::collections::HashMap;
use std::fmt::Display;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use tracing::Span;
use url::Url;
mod dummy;
mod process;
@ -100,7 +107,7 @@ pub fn load(
config: &Config,
resources: ResourcesHandle,
sessions: SessionManager,
_authentication: AuthenticationHandle,
authentication: AuthenticationHandle,
) -> miette::Result<()> {
let span = tracing::info_span!("loading initiators");
let _guard = span.enter();

View File

@ -1,9 +1,10 @@
use super::Initiator;
use super::InitiatorCallbacks;
use crate::resources::modules::fabaccess::Status;
use crate::resources::state::State;
use crate::utils::linebuffer::LineBuffer;
use async_process::{Child, ChildStderr, ChildStdout, Command, Stdio};
use futures_lite::AsyncRead;
use futures_lite::{ready, AsyncRead};
use miette::{miette, IntoDiagnostic};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
@ -116,7 +117,7 @@ impl ProcessState {
impl Future for Process {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if let Process {
state: Some(state),
buffer,

View File

@ -9,6 +9,7 @@
//! The entry point of bffhd can be found in [bin/bffhd/main.rs](../bin/bffhd/main.rs)
use miette::Diagnostic;
use std::io;
use thiserror::Error;
pub mod config;
@ -47,6 +48,7 @@ mod tls;
use std::sync::Arc;
use futures_util::{FutureExt, StreamExt};
use miette::{Context, IntoDiagnostic, Report};
use once_cell::sync::OnceCell;
use crate::audit::AuditLog;
@ -87,7 +89,6 @@ impl error::Description for SignalHandlerErr {
}
#[derive(Debug, Error, Diagnostic)]
// TODO 0.5: #[non_exhaustive]
pub enum BFFHError {
#[error("DB operation failed")]
DBError(
@ -211,9 +212,7 @@ impl Diflouroborane {
self.resources.clone(),
sessionmanager.clone(),
authentication.clone(),
).expect("initializing initiators failed");
// TODO 0.5: error handling. Add variant to BFFHError
);
actors::load(self.executor.clone(), &self.config, self.resources.clone())?;
let tlsconfig = TlsConfig::new(self.config.tlskeylog.as_ref(), !self.config.is_quiet())?;
@ -232,13 +231,13 @@ impl Diflouroborane {
self.executor.spawn(apiserver.handle_until(rx));
let f = async {
let mut sig;
let mut sig = None;
while {
sig = signals.next().await;
sig.is_none()
} {}
tracing::info!(signal = %sig.unwrap(), "Received signal");
_ = tx.send(()); // ignore result, as an Err means that the executor we want to stop has already stopped
tx.send(());
};
self.executor.run(f);

View File

@ -2,7 +2,8 @@ use serde::{Deserialize, Serialize};
use std::path::Path;
use tracing_subscriber::fmt::format::Format;
use tracing_subscriber::prelude::*;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::reload::Handle;
use tracing_subscriber::{reload, EnvFilter};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogConfig {

View File

@ -85,13 +85,10 @@ impl Inner {
self.db.put(&self.id.as_bytes(), &state).unwrap();
tracing::trace!("Updated DB, sending update signal");
let res = AUDIT
AUDIT
.get()
.unwrap()
.log(self.id.as_str(), &format!("{}", state));
if let Err(e) = res {
tracing::error!("Writing to the audit log failed for {} {}: {e}", self.id.as_str(), state);
}
self.signal.set(state);
tracing::trace!("Sent update signal");
@ -164,7 +161,7 @@ impl Resource {
fn set_state(&self, state: MachineState) {
let mut serializer = AllocSerializer::<1024>::default();
serializer.serialize_value(&state).expect("serializing a MachineState shoud be infallible");
serializer.serialize_value(&state);
let archived = ArchivedValue::new(serializer.into_serializer().into_inner());
self.inner.set_state(archived)
}

View File

@ -3,6 +3,7 @@ use crate::utils::oid::ObjectIdentifier;
use once_cell::sync::Lazy;
use rkyv::{Archive, Archived, Deserialize, Infallible};
use std::fmt;
use std::fmt::Write;
use std::str::FromStr;
//use crate::oidvalue;

View File

@ -3,8 +3,10 @@ use thiserror::Error;
use crate::db;
use crate::db::{AlignedAdapter, ArchivedValue, RawDB, DB};
use lmdb::{DatabaseFlags, Environment, EnvironmentFlags, Transaction, WriteFlags};
use miette::Diagnostic;
use std::fmt::Debug;
use miette::{Diagnostic, LabeledSpan, Severity, SourceCode};
use std::any::TypeId;
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::{path::Path, sync::Arc};
use crate::resources::state::State;
@ -52,8 +54,8 @@ impl StateDB {
}
pub fn open_with_env(env: Arc<Environment>) -> Result<Self, StateDBError> {
let db = RawDB::open(&env, Some("state"))
.map_err(|e| StateDBError::Open(e.into()))?;
let db = unsafe { RawDB::open(&env, Some("state")) };
let db = db.map_err(|e| StateDBError::Open(e.into()))?;
Ok(Self::new(env, db))
}
@ -64,8 +66,8 @@ impl StateDB {
pub fn create_with_env(env: Arc<Environment>) -> Result<Self, StateDBError> {
let flags = DatabaseFlags::empty();
let db = RawDB::create(&env, Some("state"), flags)
.map_err(|e| StateDBError::Create(e.into()))?;
let db = unsafe { RawDB::create(&env, Some("state"), flags) };
let db = db.map_err(|e| StateDBError::Create(e.into()))?;
Ok(Self::new(env, db))
}

View File

@ -1,5 +1,5 @@
use std::fmt::{Debug, Display, Formatter};
use std::fmt;
use std::{fmt, hash::Hasher};
use std::ops::Deref;

View File

@ -14,6 +14,8 @@ use inventory;
use rkyv::ser::{ScratchSpace, Serializer};
use serde::ser::SerializeMap;
use std::collections::HashMap;
use std::ops::Deref;

View File

@ -2,6 +2,7 @@ use lmdb::{DatabaseFlags, Environment, RwTransaction, Transaction, WriteFlags};
use rkyv::Infallible;
use std::collections::HashMap;
use miette::{Context, IntoDiagnostic};
use std::sync::Arc;
use crate::db;
@ -182,8 +183,8 @@ impl UserDB {
}
pub fn clear_txn(&self, txn: &mut RwTransaction) -> Result<(), db::Error> {
// TODO: why was the result ignored here?
self.db.clear(txn)
self.db.clear(txn);
Ok(())
}
pub fn get_all(&self) -> Result<HashMap<String, UserData>, db::Error> {

View File

@ -7,7 +7,8 @@ use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::io::Write;
use miette::{Diagnostic, IntoDiagnostic, SourceSpan};
use clap::ArgMatches;
use miette::{Context, Diagnostic, IntoDiagnostic, SourceOffset, SourceSpan};
use std::path::Path;
use std::sync::Arc;

View File

@ -1,4 +1,4 @@
fn main() {
// Extract build-time information using the `shadow-rs` crate
shadow_rs::new().unwrap();
shadow_rs::new();
}