Compare commits

..

1 Commits

Author SHA1 Message Date
Jonathan Krebs
b82bfa42f3 remove unused imports from bffhd 2024-11-09 13:01:26 +01:00
18 changed files with 48 additions and 60 deletions

View File

@ -31,7 +31,6 @@ Diflouroborane uses Cargo, so compilation boils down to:
```shell ```shell
$ cargo build --release $ cargo build --release
``` ```
https://www.geeksforgeeks.org/how-to-install-rust-on-raspberry-pi/ can show you how to install rust on your Linux computer.
The compiled binary can then be found in `./target/release/bffhd` The compiled binary can then be found in `./target/release/bffhd`

View File

@ -102,7 +102,6 @@ struct AuthInfo {
iv: Vec<u8>, iv: Vec<u8>,
} }
#[allow(non_camel_case_types)]
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "Cmd")] #[serde(tag = "Cmd")]
enum CardCommand { enum CardCommand {

View File

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

View File

@ -113,7 +113,7 @@ impl AuthenticationSystem for Authentication {
f.write_char(')') f.write_char(')')
} }
} }
let response; let mut response;
let mut builder = results.get(); let mut builder = results.get();
if let State::Running(mut session, manager) = if let State::Running(mut session, manager) =

View File

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

View File

@ -36,7 +36,7 @@ impl PermissionSystem for Permissions {
tracing::trace!("method call"); tracing::trace!("method call");
let roles = self.roles.list().collect::<Vec<&String>>(); 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); let mut b = builder.init_role_list(roles.len() as u32);
for (i, role) in roles.into_iter().enumerate() { for (i, role) in roles.into_iter().enumerate() {
let mut role_builder = b.reborrow().get(i as u32); 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 Some(mut user) = self.session.users.get_user(uid) {
if let Ok(true) = user.check_password(old_pw.as_bytes()) { if let Ok(true) = user.check_password(old_pw.as_bytes()) {
user.set_pw(new_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(()) Promise::ok(())
@ -143,9 +143,9 @@ impl admin::Server for User {
// Only update if needed // Only update if needed
if !target.userdata.roles.iter().any(|r| r.as_str() == rolename) { if !target.userdata.roles.iter().any(|r| r.as_str() == rolename) {
target.userdata.roles.push(rolename.to_string()); target.userdata.roles.push(rolename.to_string());
pry!(self.session self.session
.users .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 // Only update if needed
if target.userdata.roles.iter().any(|r| r.as_str() == rolename) { if target.userdata.roles.iter().any(|r| r.as_str() == rolename) {
target.userdata.roles.retain(|r| r.as_str() != rolename); target.userdata.roles.retain(|r| r.as_str() != rolename);
pry!(self.session self.session
.users .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(); let uid = self.user.get_username();
if let Some(mut user) = self.session.users.get_user(uid) { if let Some(mut user) = self.session.users.get_user(uid) {
user.set_pw(new_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(()) Promise::ok(())
} }
@ -221,7 +221,7 @@ impl card_d_e_s_fire_e_v2::Server for User {
Vec::new() Vec::new()
}); });
if !tk.is_empty() { if !tk.is_empty() {
let b = results.get(); let mut b = results.get();
let mut lb = b.init_token_list(1); let mut lb = b.init_token_list(1);
lb.set(0, &tk[..]); 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()); .insert("cardtoken".to_string(), token.to_string());
user.userdata.kv.insert("cardkey".to_string(), card_key); 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(()) 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(()) Promise::ok(())
} }

View File

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

View File

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

View File

@ -1,8 +1,5 @@
use thiserror::Error; use thiserror::Error;
// for converting a database error into a failed promise
use capnp;
mod raw; mod raw;
use miette::{Diagnostic, Severity}; use miette::{Diagnostic, Severity};
@ -82,9 +79,3 @@ impl Diagnostic for Error {
None None
} }
} }
impl From<Error> for capnp::Error {
fn from(dberr: Error) -> capnp::Error {
capnp::Error::failed(format!("database error: {}", dberr.to_string()))
}
}

View File

@ -10,6 +10,7 @@ use futures_util::future::BoxFuture;
use futures_util::ready; use futures_util::ready;
use std::collections::HashMap; use std::collections::HashMap;
use std::future::Future; use std::future::Future;
use std::mem;
use std::pin::Pin; use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
@ -61,7 +62,10 @@ impl Future for Dummy {
match &mut self.state { match &mut self.state {
DummyState::Empty => { DummyState::Empty => {
tracing::trace!("Dummy initiator is empty, initializing…"); 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) => { DummyState::Sleeping(timer, next) => {
tracing::trace!("Sleep timer exists, polling it."); tracing::trace!("Sleep timer exists, polling it.");
@ -72,7 +76,7 @@ impl Future for Dummy {
let status = next.take().unwrap(); let status = next.take().unwrap();
let f = self.flip(status); let f = self.flip(status);
self.state = DummyState::Updating(f); mem::replace(&mut self.state, DummyState::Updating(f));
} }
DummyState::Updating(f) => { DummyState::Updating(f) => {
tracing::trace!("Update future exists, polling it ."); tracing::trace!("Update future exists, polling it .");
@ -81,7 +85,10 @@ impl Future for Dummy {
tracing::trace!("Update future completed, sleeping!"); 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

@ -100,7 +100,7 @@ pub fn load(
config: &Config, config: &Config,
resources: ResourcesHandle, resources: ResourcesHandle,
sessions: SessionManager, sessions: SessionManager,
_authentication: AuthenticationHandle, authentication: AuthenticationHandle,
) -> miette::Result<()> { ) -> miette::Result<()> {
let span = tracing::info_span!("loading initiators"); let span = tracing::info_span!("loading initiators");
let _guard = span.enter(); let _guard = span.enter();

View File

@ -116,7 +116,7 @@ impl ProcessState {
impl Future for Process { impl Future for Process {
type Output = (); 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 { if let Process {
state: Some(state), state: Some(state),
buffer, buffer,

View File

@ -87,7 +87,6 @@ impl error::Description for SignalHandlerErr {
} }
#[derive(Debug, Error, Diagnostic)] #[derive(Debug, Error, Diagnostic)]
// TODO 0.5: #[non_exhaustive]
pub enum BFFHError { pub enum BFFHError {
#[error("DB operation failed")] #[error("DB operation failed")]
DBError( DBError(
@ -211,9 +210,7 @@ impl Diflouroborane {
self.resources.clone(), self.resources.clone(),
sessionmanager.clone(), sessionmanager.clone(),
authentication.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())?; actors::load(self.executor.clone(), &self.config, self.resources.clone())?;
let tlsconfig = TlsConfig::new(self.config.tlskeylog.as_ref(), !self.config.is_quiet())?; let tlsconfig = TlsConfig::new(self.config.tlskeylog.as_ref(), !self.config.is_quiet())?;
@ -232,13 +229,13 @@ impl Diflouroborane {
self.executor.spawn(apiserver.handle_until(rx)); self.executor.spawn(apiserver.handle_until(rx));
let f = async { let f = async {
let mut sig; let mut sig = None;
while { while {
sig = signals.next().await; sig = signals.next().await;
sig.is_none() sig.is_none()
} {} } {}
tracing::info!(signal = %sig.unwrap(), "Received signal"); 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); self.executor.run(f);

View File

@ -85,13 +85,10 @@ impl Inner {
self.db.put(&self.id.as_bytes(), &state).unwrap(); self.db.put(&self.id.as_bytes(), &state).unwrap();
tracing::trace!("Updated DB, sending update signal"); tracing::trace!("Updated DB, sending update signal");
let res = AUDIT AUDIT
.get() .get()
.unwrap() .unwrap()
.log(self.id.as_str(), &format!("{}", state)); .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); self.signal.set(state);
tracing::trace!("Sent update signal"); tracing::trace!("Sent update signal");
@ -164,7 +161,7 @@ impl Resource {
fn set_state(&self, state: MachineState) { fn set_state(&self, state: MachineState) {
let mut serializer = AllocSerializer::<1024>::default(); 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()); let archived = ArchivedValue::new(serializer.into_serializer().into_inner());
self.inner.set_state(archived) self.inner.set_state(archived)
} }

View File

@ -52,8 +52,8 @@ impl StateDB {
} }
pub fn open_with_env(env: Arc<Environment>) -> Result<Self, StateDBError> { pub fn open_with_env(env: Arc<Environment>) -> Result<Self, StateDBError> {
let db = RawDB::open(&env, Some("state")) let db = unsafe { RawDB::open(&env, Some("state")) };
.map_err(|e| StateDBError::Open(e.into()))?; let db = db.map_err(|e| StateDBError::Open(e.into()))?;
Ok(Self::new(env, db)) Ok(Self::new(env, db))
} }
@ -64,8 +64,8 @@ impl StateDB {
pub fn create_with_env(env: Arc<Environment>) -> Result<Self, StateDBError> { pub fn create_with_env(env: Arc<Environment>) -> Result<Self, StateDBError> {
let flags = DatabaseFlags::empty(); let flags = DatabaseFlags::empty();
let db = RawDB::create(&env, Some("state"), flags) let db = unsafe { RawDB::create(&env, Some("state"), flags) };
.map_err(|e| StateDBError::Create(e.into()))?; let db = db.map_err(|e| StateDBError::Create(e.into()))?;
Ok(Self::new(env, db)) Ok(Self::new(env, db))
} }

View File

@ -182,8 +182,8 @@ impl UserDB {
} }
pub fn clear_txn(&self, txn: &mut RwTransaction) -> Result<(), db::Error> { 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> { pub fn get_all(&self) -> Result<HashMap<String, UserData>, db::Error> {

View File

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