Compare commits

...

32 Commits

Author SHA1 Message Date
314145084e update schema to latest 2025-03-05 23:51:27 +01:00
5e0d615ada make schema (API) submodule static to allow easy project-forking 2025-03-05 23:09:37 +01:00
e4b7aa8766 remove dirty examples/ dir. proper and up to date examples can be found at https://gitlab.com/fabinfra/fabaccess/demos-environments for instance 2025-03-04 00:35:25 +01:00
bbf0e77571 remove obsolete test/ directory 2025-02-24 13:17:33 +01:00
40ca2acdb7 cleanup/update contributing infos 2025-02-20 16:44:37 +01:00
3e29df8b2c Remove obsolete installation docs, href the user to docs.fab-access.org instead 2025-02-20 16:18:42 +01:00
fdde8a933c Cleanup: remove /docs dir because we put it to https://docs.fab-access.org 2025-02-20 15:35:19 +01:00
Jonathan Krebs
c8f0337c1e set release date for 0.4.3 2025-02-11 16:56:25 +01:00
Jonathan Krebs
151c04d9df record changes since 0.4.2 2025-01-24 17:39:52 +01:00
Jonathan Krebs
1d2ba9eddc implement dumping and loading the full database 2025-01-24 04:45:03 +01:00
Jonathan Krebs
ee21f74d2d minimal dependency update to make it compatible with current rust 2025-01-24 04:30:37 +01:00
=
06083a63e3 Fix compilation error caused by overlooked renames: diflouroborane -> difluoroborane 2024-12-15 22:29:14 +01:00
57a0436ca1 fix typo; fixes https://gitlab.com/fabinfra/fabaccess/bffh/-/issues/68 2024-12-14 21:54:01 +01:00
Jonathan Krebs
8b15acf983 remove warnings around initiator loading. cleaner error handling remains todo. 2024-12-13 15:32:21 +01:00
Jonathan Krebs
40ba114e61 fix warnings: at the moment configuration by environment variables is not implemented 2024-12-13 15:32:21 +01:00
Jonathan Krebs
c2c34ede67 fix warnings: remove unused muts and variables 2024-12-13 15:32:21 +01:00
Jonathan Krebs
2b0fe0e868 add some error handling, mostly to quiet warnings 2024-12-13 15:32:21 +01:00
Jonathan Krebs
fbfb76c34e fix warnings: some more easy cases 2024-12-13 15:32:21 +01:00
Jonathan Krebs
971dee36fd fix warnings: replace some mem::replace with assignments 2024-12-13 15:32:21 +01:00
Jonathan Krebs
41983e6039 remove unused imports from bffhd 2024-12-13 15:32:21 +01:00
Falko Richter
ca25cd83d0 Update INSTALL.md 2024-11-20 12:29:45 +00:00
Jonathan Krebs
9805f4ee04 lightproc: drop span guard before deallocating the process
This should fix #77
2024-11-09 11:44:43 +01:00
Falko Richter
66877159f0 fixed links to the other repos 2024-07-22 06:53:45 +00:00
Nadja Reitzenstein
a9143b0cdd pin toolchain to a known good version while we get that 'fun' segfault 2023-02-23 17:00:19 +01:00
Nadja Reitzenstein
165b269d4f Fix example config 2023-02-23 14:25:44 +01:00
Nadja Reitzenstein
e35e2b7334 cargo fmt 2023-02-09 17:07:31 +01:00
Nadja Reitzenstein
98c2e3fd01 rsasl update 2023-02-09 17:07:22 +01:00
Kai Jan Kriegel
27f5413e3d i guess i forgot how to format string? 2023-02-06 18:07:42 +01:00
Kai Jan Kriegel
55e9bf6e2b check the configured space urn and not a hardcoded one 2023-02-03 21:35:53 +01:00
Kai Jan Kriegel
4cdbfd8925 fix bind / unbind card 2023-02-03 08:20:39 +01:00
Nadja Reitzenstein
7a85667a44 Whoops that was a premature push 2023-01-31 16:18:18 +01:00
Nadja Reitzenstein
cf3853263a Make spacename/instanceurl required and enable card interface 2023-01-31 16:16:00 +01:00
71 changed files with 912 additions and 1705 deletions

2
.gitmodules vendored
View File

@ -1,4 +1,4 @@
[submodule "schema"] [submodule "schema"]
path = api/schema path = api/schema
url = ../fabaccess-api url = https://gitlab.com/fabinfra/fabaccess/fabaccess-api
branch = main branch = main

View File

@ -1,5 +1,17 @@
# Revision history for Difluoroborane # Revision history for Difluoroborane
## 0.4.3 -- 2025-02-11
* Adds binary version of FabFire authenitcation protocol
* Adds commands to dump and restore the full database as a TOML text file (`--dump-db` and `--load-db`)
* allows compilation with current stable Rust (1.84)
- Attention: The database format still relies on Rust data layout, so when updating the compiler, the database must be transfered as TOML dump.
Therefore, the `rust-toolchain.toml` file pinning `rustc` to version `1.66` is still in place.
* resolves a crash (use after free) when disconnecting a client.
* resolves some compiler warnings
## 0.4.2 -- TODO
## 0.4.1 -- 2022-04-24 ## 0.4.1 -- 2022-04-24
* Initial full implementation of the FabAccess 0.3 API, "Spigots of Berlin". * Initial full implementation of the FabAccess 0.3 API, "Spigots of Berlin".

View File

@ -2,120 +2,38 @@
Thank you for your interest in helping out the FabAccess system! Thank you for your interest in helping out the FabAccess system!
You found a bug, an exploit or a feature that doesn't work like it's documented? Please tell us You found a bug, an exploit or a feature that doesn't work like it's documented? Please tell us about it, see [Issues](#issues)
about it, see [Issues](#issues)
You have a feature request? Great, check out the paragraph on [Feature Requests](#feature-requests) You have a feature request? Great, check out the paragraph on [Feature Requests](#feature-requests)
## Issues ## Issues
While we try to not have any bugs or exploits or documentation bugs we're not perfect either. Thanks While we try to not have any bugs or exploits or documentation bugs we're not perfect either. Thanks for helping us out!
for helping us out!
We have labels that help us sort issues better, so if you know what would be the correct ones, We have labels that help us sort issues better, so if you know what would be the correct ones, please tag your issue with one or multiple keywords. See [Labels](https://gitlab.com/fabinfra/fabaccess/bffh/-/labels) to get an overview of all keywords and their use case.
please tag your issue:
- `documentation` if it's an documentation issue, be it lacking docs or even worse wrong docs.
- `bug` is for software bugs, unexpected behaviour, crashes and so on.
- `exploit` for any bugs that may be used as RCE, to escalate priviledges or some-such.
Don't worry if you aren't sure about the correct labels, an issue opened with no labels is much
better than no knowing about the issue!
Especially for bugs and exploits, please mark your issue as "confidential" if you think it impacts Especially for **bugs** and **exploits**, please mark your issue as "confidential" if you think it impacts the `stable` branch. If you're not sure, mark it as confidential anyway. It's easier to publish information than it is to un-publish information. You may also contact as by [mail](https://fab-access.org/impressum).
the `stable` branch. If you're not sure, mark it as confidential anyway. It's easier to publish
information than it is to un-publish information.
If you found an exploit and it's high-impact enough that you do not want to open an issue but
instead want direct contact with the developers, you can find public keys respectively fingerprints
for GPG, XMPP+OMEMO and Matrix+MegOlm in the git repository as blobs with tags assigned to them.
You can import the gpg key for dequbed either from the repository like so:
```
$ git cat-file -p keys/dequbed/gpg | gpg --import-key
```
Or from your local trusted gpg keyserver, and/or verify it using [keybase](https://keybase.io/dequbed)
This key is also used to sign the other tags so to verify them you can run e.g.
```
$ git tag -v keys/dequbed/xmpp+omemo
```
## Feature Requests ## Feature Requests
We also like new feature requests of course! We also like new feature requests of course!
But before you open an issue in this repo for a feature request, please first check a few things: But before you open an issue in this repo for a feature request, please first check a few things:
1. Is it a feature that needs to be implemented in more than just the backend server? For example,
is it something also having a GUI-component or something that you want to be able to do via the 1. Is it a feature that needs to be implemented in more than just the backend server? For example, is it something also having a GUI-component or something that you want to be able to do via the API? If so it's better suited over at the
API? If so it's better suited over at the [Lastenheft](https://gitlab.com/fabinfra/fabaccess_lastenheft) because that's where the required coordination for that will end up happening
[Lastenheft](https://gitlab.com/fabinfra/fabaccess_lastenheft) because that's where the required 2. Who else needs that feature? Is this something super specific to your environment/application or something that others will want too? If it's something that's relevant for more people please also tell us that in the feature request.
coordination for that will end up happening 3. Can you already get partway or all the way there using what's there already? If so please also tell us what you're currently doing and what doesn't work or why you dislike your current solution.
2. Who else needs that feature? Is this something super specific to your environment/application or
something that others will want too? If it's something that's relevant for more people please
also tell us that in the feature request.
3. Can you already get partway or all the way there using what's there already? If so please also
tell us what you're currently doing and what doesn't work or why you dislike your current
solution.
## Contributing Code ## Contributing Code
To help develop Diflouroborane you will need a Rust toolchain. I heavily recommend installing To help develop Difluoroborane you will need a Rust toolchain. We heavily recommend installing [rustup](https://rustup.rs) even if your distribution provides a recent enough rustc, simply because it allows to easily switch compilers between several versions of both stable and nightly. It also allows you to download the respective stdlib crate, giving you the option of an offline reference.
[rustup](https://rustup.rs) even if your distribution provides a recent enough rustc, simply because
it allows to easily switch compilers between several versions of both stable and nightly. It also
allows you to download the respective stdlib crate, giving you the option of an offline reference.
We use a stable release branch / moving development workflow. This means that all *new* development We use a stable release branch / moving development workflow. This means that all *new* development should happen on the `development` branch which is regularly merged into `stable` as releases. The exception of course are bug- and hotfixes that can target whichever branch.
should happen on the `development` branch which is regularly merged into `stable` as releases. The
exception of course are bug- and hotfixes that can target whichever branch.
If you want to add a new feature please work off the development branch. We suggest you create If you want to add a new feature please work off the development branch. We suggest you create yourself a feature branch, e.g. using
yourself a feature branch, e.g. using `git switch development; git checkout -b
feature/my-cool-feature`.
Using a feature branch keeps your local `development` branch clean, making it easier to later rebase
your feature branch onto it before you open a pull/merge request.
When you want feedback on your current progress or are ready to have it merged upstream open a merge ```git switch development; git checkout -b feature/my-cool-feature```
request. Don't worry we don't bite! ^^
Using a feature branch keeps your local `development` branch clean, making it easier to later rebase your feature branch onto it before you open a pull/merge request.
# Development Setup When you want feedback on your current progress or are ready to have it merged upstream open a merge request. Don't worry, we don't bite! ^^
## Cross-compilation
If you want to cross-compile you need both a C-toolchain for your target
and install the Rust stdlib for said target.
As an example for the target `aarch64-unknown-linux-gnu` (64-bit ARMv8
running Linux with the glibc, e.g. a Raspberry Pi 3 or later with a 64-bit
Debian Linux installation):
1. Install C-toolchain using your distro package manager:
- On Archlinux: `pacman -S aarch64-unknown-linux-gnu-gcc`
2. Install the Rust stdlib:
- using rustup: `rustup target add aarch64-unknown-linux-gnu`
3. Configure your cargo config:
### Configuring cargo
You need to tell Cargo to use your C-toolchain. For this you need to have
a block in [your user cargo config](https://doc.rust-lang.org/cargo/reference/config.html) setting at
least the paths to the gcc as `linker` and ar as `ar`:
```toml
[target.aarch64-unknown-linux-gnu]
# You must set the gcc as linker since a lot of magic must happen here.
linker = "aarch64-linux-gnu-gcc"
ar = "aarch64-linux-gnu-ar"
```
This block should be added to your **user** cargo config (usually
`~/.cargo/config.toml`), since these values can differ between distros and
users.
To actually compile for the given triple you need to call `cargo build`
with the `--target` flag:
```
$ cargo build --release --target=aarch64-unknown-linux-gnu
```
## Tests
Sadly, still very much `// TODO:`. We're working on it! :/

1063
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,5 @@
[package] [package]
name = "diflouroborane" name = "difluoroborane"
version = "0.4.2" version = "0.4.2"
authors = [ "dequbed <me@dequbed.space>" authors = [ "dequbed <me@dequbed.space>"
, "Kai Jan Kriegel <kai@kjkriegel.de>" , "Kai Jan Kriegel <kai@kjkriegel.de>"
@ -66,7 +66,7 @@ ptr_meta = "0.1"
rkyv_typename = "0.7" rkyv_typename = "0.7"
rkyv_dyn = "0.7" rkyv_dyn = "0.7"
inventory = "0.1" inventory = "0.1"
linkme = "0.2.10" linkme = "0.3"
chrono = { version = "0.4", features = ["serde"] } chrono = { version = "0.4", features = ["serde"] }
# Password hashing for internal users # Password hashing for internal users
@ -113,7 +113,7 @@ rustls-native-certs = "0.6.1"
shadow-rs = "0.11" shadow-rs = "0.11"
[dependencies.rsasl] [dependencies.rsasl]
version = "2.0.0-rc.3" version = "2.2.0"
default_features = false default_features = false
features = ["unstable_custom_mechanism", "provider", "registry_static", "config_builder", "plain"] features = ["unstable_custom_mechanism", "provider", "registry_static", "config_builder", "plain"]

View File

@ -1,53 +0,0 @@
# Installation
Currently there are no distribution packages available.
However installation is reasonably straight-forward, since Diflouroborane compiles into a single
mostly static binary with few dependencies.
At the moment only Linux is supported. If you managed to compile Diflouroborane please open an issue
outlining your steps or add a merge request expanding this part. Thanks!
## Requirements
General requirements; scroll down for distribution-specific instructions
- GNU SASL (libgsasl).
* If you want to compile Diflouroborane from source you will potentially also need development
headers
- capnproto
- rustc stable / nightly >= 1.48
* If your distribution does not provide a recent enough rustc, [rustup](https://rustup.rs/) helps
installing a local toolchain and keeping it up to date.
###### Arch Linux:
```shell
$ pacman -S gsasl rust capnproto
```
## Compiling from source
Diflouroborane uses Cargo, so compilation boils down to:
```shell
$ cargo build --release
```
The compiled binary can then be found in `./target/release/bffhd`
### Cross-compiling
If you need to compile for a different CPU target than your own (e.g. you want
to use BFFH on a raspberry pi but compile on your desktop PC), you need to
setup a cross-compilation toolchain and configure your Cargo correctly.
[The `CONTRIBUTING.md` has a section on how to setup a cross-compilation system.](CONTRIBUTING.md#cross-compilation)
# Running bffhd
The server can be ran either using `cargo`, which will also compile the binary if necessary, or directly.
When running using `cargo` you need to pass arguments to bffh after a `--`, so
e.g. `cargo run --release -- --help` or `cargo run --release -- -c examples/bffh.toml`.
When running directly the `bffhd` binary can be copied anywhere.
A list of arguments for the server is found in the help, so `bffhd --help` or `cargo run --release -- --help`.

View File

@ -1,8 +1,8 @@
# FabAccess Diflouroborane # FabAccess Difluoroborane
Diflouroborane (shorter: BFFH, the chemical formula for Diflouroborane) is the server part of Difluoroborane (shorter: BFFH, the chemical formula for Difluoroborane) is the server part of
FabAccess. FabAccess.
It provides a server-side implementation of the [FabAccess API](/fabinfra/fabaccess/fabaccess-api). It provides a server-side implementation of the [FabAccess API](https://gitlab.com/fabinfra/fabaccess/fabaccess-api).
## What is this? ## What is this?
@ -13,14 +13,14 @@ to be used for all other things one would like to give exclusive access to even
dangerous or expensive to use (think 3D printers, smart lightbulbs, meeting rooms). dangerous or expensive to use (think 3D printers, smart lightbulbs, meeting rooms).
FabAccess uses a Client/Server architecture with a [Cap'n Proto](https://capnproto.org/) API. You FabAccess uses a Client/Server architecture with a [Cap'n Proto](https://capnproto.org/) API. You
can find the API schema files over [in their own repository](/fabinfra/fabaccess/fabaccess-api). can find the API schema files over [in their own repository](https://gitlab.com/fabinfra/fabaccess/fabaccess-api).
The reference client is [Borepin](/fabinfra/fabaccess/borepin), written in C#/Xamarin to be able to The reference client is [Borepin](https://gitlab.com/fabinfra/fabaccess/borepin), written in C#/Xamarin to be able to
be ported to as many platforms as possible. be ported to as many platforms as possible.
## Installation ## Installation
See [INSTALL.md](INSTALL.md) See [https://fab-access.org/install](https://fab-access.org/install)
## Contributing ## Contributing

@ -1 +1 @@
Subproject commit 19f20f5154f0eced6288ff56cac840025ee51da1 Subproject commit f3f53dafb6b7d23a19947f2a32d4ed5ee4e91d22

View File

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

View File

@ -2,13 +2,27 @@ mod server;
pub use server::FabFire; pub use server::FabFire;
use rsasl::mechname::Mechname; use rsasl::mechname::Mechname;
use rsasl::registry::{Mechanism, Side, MECHANISMS}; use rsasl::registry::{Matches, Mechanism, Named, Side, MECHANISMS};
const MECHNAME: &'static Mechname = &Mechname::const_new_unchecked(b"X-FABFIRE"); const MECHNAME: &'static Mechname = &Mechname::const_new_unchecked(b"X-FABFIRE");
#[linkme::distributed_slice(MECHANISMS)] #[linkme::distributed_slice(MECHANISMS)]
pub static FABFIRE: Mechanism = pub static FABFIRE: Mechanism = Mechanism::build(
Mechanism::build(MECHNAME, 300, None, Some(FabFire::new_server), Side::Client); MECHNAME,
300,
None,
Some(FabFire::new_server),
Side::Client,
|_| Some(Matches::<Select>::name()),
|_| true,
);
struct Select;
impl Named for Select {
fn mech() -> &'static Mechanism {
&FABFIRE
}
}
use rsasl::property::SizedProperty; use rsasl::property::SizedProperty;
use std::marker::PhantomData; use std::marker::PhantomData;

View File

@ -2,7 +2,6 @@ use desfire::desfire::desfire::MAX_BYTES_PER_TRANSACTION;
use desfire::desfire::Desfire; use desfire::desfire::Desfire;
use desfire::error::Error as DesfireError; use desfire::error::Error as DesfireError;
use desfire::iso7816_4::apduresponse::APDUResponse; use desfire::iso7816_4::apduresponse::APDUResponse;
use rsasl::callback::SessionData;
use rsasl::mechanism::{ use rsasl::mechanism::{
Authentication, Demand, DemandReply, MechanismData, MechanismError, MechanismErrorKind, Authentication, Demand, DemandReply, MechanismData, MechanismError, MechanismErrorKind,
Provider, State, ThisProvider, Provider, State, ThisProvider,
@ -13,7 +12,6 @@ use serde::{Deserialize, Serialize};
use std::convert::TryFrom; use std::convert::TryFrom;
use std::fmt::{Debug, Display, Formatter}; use std::fmt::{Debug, Display, Formatter};
use std::io::Write; use std::io::Write;
use std::sync::Arc;
use crate::authentication::fabfire::FabFireCardKey; use crate::authentication::fabfire::FabFireCardKey;
@ -104,6 +102,7 @@ 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 {
@ -179,7 +178,7 @@ impl FabFire {
impl Authentication for FabFire { impl Authentication for FabFire {
fn step( fn step(
&mut self, &mut self,
session: &mut MechanismData<'_>, session: &mut MechanismData<'_, '_>,
input: Option<&[u8]>, input: Option<&[u8]>,
writer: &mut dyn Write, writer: &mut dyn Write,
) -> Result<State, SessionError> { ) -> Result<State, SessionError> {

View File

@ -2,10 +2,24 @@ mod server;
pub use server::FabFire; pub use server::FabFire;
use rsasl::mechname::Mechname; use rsasl::mechname::Mechname;
use rsasl::registry::{Mechanism, Side, MECHANISMS}; use rsasl::registry::{Matches, Mechanism, Named, Side, MECHANISMS};
const MECHNAME: &'static Mechname = &Mechname::const_new_unchecked(b"X-FABFIRE-BIN"); const MECHNAME: &'static Mechname = &Mechname::const_new_unchecked(b"X-FABFIRE-BIN");
#[linkme::distributed_slice(MECHANISMS)] #[linkme::distributed_slice(MECHANISMS)]
pub static FABFIRE: Mechanism = pub static FABFIRE: Mechanism = Mechanism::build(
Mechanism::build(MECHNAME, 300, None, Some(FabFire::new_server), Side::Client); MECHNAME,
300,
None,
Some(FabFire::new_server),
Side::Client,
|_| Some(Matches::<Select>::name()),
|_| true,
);
struct Select;
impl Named for Select {
fn mech() -> &'static Mechanism {
&FABFIRE
}
}

View File

@ -2,7 +2,6 @@ use desfire::desfire::desfire::MAX_BYTES_PER_TRANSACTION;
use desfire::desfire::Desfire; use desfire::desfire::Desfire;
use desfire::error::Error as DesfireError; use desfire::error::Error as DesfireError;
use desfire::iso7816_4::apduresponse::APDUResponse; use desfire::iso7816_4::apduresponse::APDUResponse;
use rsasl::callback::SessionData;
use rsasl::mechanism::{ use rsasl::mechanism::{
Authentication, Demand, DemandReply, MechanismData, MechanismError, MechanismErrorKind, Authentication, Demand, DemandReply, MechanismData, MechanismError, MechanismErrorKind,
Provider, State, ThisProvider, Provider, State, ThisProvider,
@ -13,9 +12,9 @@ use serde::{Deserialize, Serialize};
use std::convert::TryFrom; use std::convert::TryFrom;
use std::fmt::{Debug, Display, Formatter}; use std::fmt::{Debug, Display, Formatter};
use std::io::Write; use std::io::Write;
use std::sync::Arc;
use crate::authentication::fabfire::FabFireCardKey; use crate::authentication::fabfire::FabFireCardKey;
use crate::CONFIG;
enum FabFireError { enum FabFireError {
ParseError, ParseError,
@ -128,13 +127,20 @@ const MAGIC: &'static str = "FABACCESS\0DESFIRE\01.0\0";
impl FabFire { impl FabFire {
pub fn new_server(_sasl: &SASLConfig) -> Result<Box<dyn Authentication>, SASLError> { pub fn new_server(_sasl: &SASLConfig) -> Result<Box<dyn Authentication>, SASLError> {
let space = if let Some(space) = CONFIG.get().map(|c| c.spacename.as_str()) {
space
} else {
tracing::error!("No space configured");
"generic"
};
Ok(Box::new(Self { Ok(Box::new(Self {
step: Step::New, step: Step::New,
card_info: None, card_info: None,
key_info: None, key_info: None,
auth_info: None, auth_info: None,
app_id: 0x464142, app_id: 0x464142,
local_urn: "urn:fabaccess:lab:innovisionlab".to_string(), local_urn: format!("urn:fabaccess:lab:{space}"),
desfire: Desfire { desfire: Desfire {
card: None, card: None,
session_key: None, session_key: None,
@ -147,7 +153,7 @@ impl FabFire {
impl Authentication for FabFire { impl Authentication for FabFire {
fn step( fn step(
&mut self, &mut self,
session: &mut MechanismData<'_>, session: &mut MechanismData<'_, '_>,
input: Option<&[u8]>, input: Option<&[u8]>,
writer: &mut dyn Write, writer: &mut dyn Write,
) -> Result<State, SessionError> { ) -> Result<State, SessionError> {

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

@ -4,10 +4,8 @@ use capnp_rpc::pry;
use rsasl::mechname::Mechname; use rsasl::mechname::Mechname;
use rsasl::prelude::State as SaslState; use rsasl::prelude::State as SaslState;
use rsasl::prelude::{MessageSent, Session}; use rsasl::prelude::{MessageSent, Session};
use rsasl::property::AuthId;
use std::fmt; use std::fmt;
use std::fmt::{Formatter, Write}; use std::fmt::{Formatter, Write};
use std::io::Cursor;
use tracing::Span; use tracing::Span;
use crate::authentication::V; use crate::authentication::V;
@ -115,7 +113,7 @@ impl AuthenticationSystem for Authentication {
f.write_char(')') f.write_char(')')
} }
} }
let mut response; let 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,7 +211,6 @@ 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

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

View File

@ -1,4 +1,3 @@
use crate::authorization::roles::Role;
use crate::Roles; use crate::Roles;
use api::permissionsystem_capnp::permission_system::info::{ use api::permissionsystem_capnp::permission_system::info::{
GetRoleListParams, GetRoleListResults, Server as PermissionSystem, GetRoleListParams, GetRoleListResults, Server as PermissionSystem,
@ -37,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 mut builder = results.get(); let 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

@ -73,6 +73,7 @@ impl User {
} }
if session.has_perm(Permission::new("bffh.users.admin")) { if session.has_perm(Permission::new("bffh.users.admin")) {
builder.set_admin(capnp_rpc::new_client(client.clone())); builder.set_admin(capnp_rpc::new_client(client.clone()));
builder.set_card_d_e_s_fire_e_v2(capnp_rpc::new_client(client));
} }
} }
} }
@ -108,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());
self.session.users.put_user(uid, &user); pry!(self.session.users.put_user(uid, &user));
} }
} }
Promise::ok(()) Promise::ok(())
@ -142,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());
self.session pry!(self.session
.users .users
.put_user(self.user.get_username(), &target); .put_user(self.user.get_username(), &target));
} }
} }
@ -167,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);
self.session pry!(self.session
.users .users
.put_user(self.user.get_username(), &target); .put_user(self.user.get_username(), &target));
} }
} }
@ -184,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());
self.session.users.put_user(uid, &user); pry!(self.session.users.put_user(uid, &user));
} }
Promise::ok(()) Promise::ok(())
} }
@ -200,7 +201,7 @@ impl card_d_e_s_fire_e_v2::Server for User {
let _span = tracing::trace_span!(target: TARGET, "get_token_list").entered(); let _span = tracing::trace_span!(target: TARGET, "get_token_list").entered();
tracing::trace!("method call"); tracing::trace!("method call");
// TODO: This only supports a sigle key per user // TODO: This only supports a single token per user
let user = pry!(self let user = pry!(self
.session .session
.users .users
@ -209,27 +210,27 @@ impl card_d_e_s_fire_e_v2::Server for User {
"User API object with nonexisting user \"{}\"", "User API object with nonexisting user \"{}\"",
self.user.get_username() self.user.get_username()
)))); ))));
let ck = user let tk = user
.userdata .userdata
.kv .kv
.get("cardkey") .get("cardtoken")
.map(|ck| hex::decode(ck).ok()) .map(|ck| hex::decode(ck).ok())
.flatten() .flatten()
.unwrap_or_else(|| { .unwrap_or_else(|| {
tracing::debug!(user.id = &user.id, "no DESFire keys stored"); tracing::debug!(user.id = &user.id, "no tokens stored");
Vec::new() Vec::new()
}); });
if !ck.is_empty() { if !tk.is_empty() {
let mut b = results.get(); let b = results.get();
let mut lb = b.init_token_list(1); let mut lb = b.init_token_list(1);
lb.set(0, &ck[..]); lb.set(0, &tk[..]);
} }
Promise::ok(()) Promise::ok(())
} }
fn bind(&mut self, params: BindParams, _: BindResults) -> Promise<(), Error> { fn bind(&mut self, params: BindParams, _: BindResults) -> Promise<(), Error> {
let _guard = self.span.enter(); let _guard = self.span.enter();
let _span = tracing::trace_span!(target: TARGET, "get_token_list").entered(); let _span = tracing::trace_span!(target: TARGET, "bind").entered();
let params = pry!(params.get()); let params = pry!(params.get());
let card_key = pry!(params.get_auth_key()); let card_key = pry!(params.get_auth_key());
let token = pry!(params.get_token()); let token = pry!(params.get_token());
@ -297,12 +298,15 @@ impl card_d_e_s_fire_e_v2::Server for User {
.kv .kv
.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));
Promise::ok(()) Promise::ok(())
} }
fn unbind(&mut self, params: UnbindParams, _: UnbindResults) -> Promise<(), Error> { fn unbind(&mut self, params: UnbindParams, _: UnbindResults) -> Promise<(), Error> {
let _guard = self.span.enter(); let _guard = self.span.enter();
let _span = tracing::trace_span!(target: TARGET, "get_token_list").entered(); let _span = tracing::trace_span!(target: TARGET, "unbind").entered();
let params = pry!(params.get()); let params = pry!(params.get());
let token = pry!(params.get_token()); let token = pry!(params.get_token());
@ -325,11 +329,18 @@ impl card_d_e_s_fire_e_v2::Server for User {
)))); ))));
if let Some(prev_token) = user.userdata.kv.get("cardtoken") { if let Some(prev_token) = user.userdata.kv.get("cardtoken") {
if token.as_ref() == prev_token.as_str() { if token.as_ref() == prev_token.as_str() {
tracing::debug!(
user.id,
token = token.as_ref(),
"removing card key/token pair"
);
user.userdata.kv.remove("cardtoken"); user.userdata.kv.remove("cardtoken");
user.userdata.kv.remove("cardkey"); user.userdata.kv.remove("cardkey");
} }
} }
pry!(self.session.users.put_user(self.user.get_username(), &user));
Promise::ok(()) Promise::ok(())
} }
@ -339,7 +350,7 @@ impl card_d_e_s_fire_e_v2::Server for User {
mut results: GenCardTokenResults, mut results: GenCardTokenResults,
) -> Promise<(), Error> { ) -> Promise<(), Error> {
let _guard = self.span.enter(); let _guard = self.span.enter();
let _span = tracing::trace_span!(target: TARGET, "get_card_token").entered(); let _span = tracing::trace_span!(target: TARGET, "gen_card_token").entered();
tracing::trace!("method call"); tracing::trace!("method call");
results.get().set_token(Uuid::new_v4().as_bytes()); results.get().set_token(Uuid::new_v4().as_bytes());
@ -370,13 +381,13 @@ impl card_d_e_s_fire_e_v2::Server for User {
let _span = tracing::trace_span!(target: TARGET, "get_space_info").entered(); let _span = tracing::trace_span!(target: TARGET, "get_space_info").entered();
tracing::trace!("method call"); tracing::trace!("method call");
let space = if let Some(space) = CONFIG.get().and_then(|c| c.spacename.as_ref()) { let space = if let Some(space) = CONFIG.get().map(|c| c.spacename.as_str()) {
space space
} else { } else {
return Promise::err(Error::failed("No space name configured".to_string())); return Promise::err(Error::failed("No space name configured".to_string()));
}; };
let url = if let Some(url) = CONFIG.get().and_then(|c| c.instanceurl.as_ref()) { let url = if let Some(url) = CONFIG.get().map(|c| c.instanceurl.as_str()) {
url url
} else { } else {
return Promise::err(Error::failed("No instance url configured".to_string())); return Promise::err(Error::failed("No instance url configured".to_string()));

View File

@ -84,13 +84,13 @@ impl manage::Server for Users {
"method call" "method call"
); );
let mut builder = result.get(); let 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);
self.session.users.put_user(username, &user); pry!(self.session.users.put_user(username, &user));
let mut builder = builder.init_successful(); let 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

@ -1,8 +1,6 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::default::Default; use std::default::Default;
use std::error::Error; use std::fmt::Debug;
use std::fmt::{Debug, Display};
use std::marker::PhantomData;
use std::path::PathBuf; use std::path::PathBuf;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -12,7 +10,6 @@ use crate::authorization::roles::Role;
use crate::capnp::{Listen, TlsListen}; use crate::capnp::{Listen, TlsListen};
use crate::logging::LogConfig; use crate::logging::LogConfig;
use miette::IntoDiagnostic;
use std::path::Path; use std::path::Path;
#[derive(Debug)] #[derive(Debug)]
@ -97,11 +94,9 @@ pub struct Config {
#[serde(default, skip)] #[serde(default, skip)]
pub logging: LogConfig, pub logging: LogConfig,
#[serde(default, skip_serializing_if = "Option::is_none")] pub spacename: String,
pub spacename: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")] pub instanceurl: String,
pub instanceurl: Option<String>,
} }
impl Config { impl Config {
@ -170,8 +165,8 @@ impl Default for Config {
tlskeylog: None, tlskeylog: None,
verbosity: 0, verbosity: 0,
logging: LogConfig::default(), logging: LogConfig::default(),
instanceurl: None, instanceurl: "".into(),
spacename: None, spacename: "".into(),
} }
} }
} }

View File

@ -38,13 +38,15 @@ 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 mut config = dhall::read_config_file(file)?; let config = dhall::read_config_file(file)?;
for (envvar, value) in std::env::vars() { // TODO: configuration by environment variables?
match envvar.as_str() { // but rather in in a separate function
// Do things like this? // for (envvar, value) in std::env::vars() {
// "BFFH_LOG" => config.logging.filter = Some(value), // match envvar.as_str() {
_ => {} // // Do things like this?
} // // "BFFH_LOG" => config.logging.filter = Some(value),
} // _ => {}
// }
// }
Ok(config) Ok(config)
} }

View File

@ -1,10 +1,13 @@
use thiserror::Error; use thiserror::Error;
// for converting a database error into a failed promise
use capnp;
mod raw; mod raw;
use miette::{Diagnostic, LabeledSpan, Severity, SourceCode}; use miette::{Diagnostic, Severity};
pub use raw::RawDB; pub use raw::RawDB;
use std::fmt::{Debug, Display, Formatter}; use std::fmt::{Debug, Display};
mod typed; mod typed;
pub use typed::{Adapter, AlignedAdapter, ArchivedValue, DB}; pub use typed::{Adapter, AlignedAdapter, ArchivedValue, DB};
@ -79,3 +82,9 @@ 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

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

View File

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

View File

@ -5,14 +5,11 @@ use super::Initiator;
use crate::initiators::InitiatorCallbacks; use crate::initiators::InitiatorCallbacks;
use crate::resources::modules::fabaccess::Status; use crate::resources::modules::fabaccess::Status;
use crate::session::SessionHandle; use crate::session::SessionHandle;
use crate::users::UserRef;
use async_io::Timer; use async_io::Timer;
use futures_util::future::BoxFuture; use futures_util::future::BoxFuture;
use futures_util::ready; use futures_util::ready;
use lmdb::Stat;
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};
@ -64,10 +61,7 @@ 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…");
mem::replace( self.state = DummyState::Sleeping(Self::timer(), Some(Status::Free));
&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.");
@ -78,7 +72,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);
mem::replace(&mut self.state, DummyState::Updating(f)); 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 .");
@ -87,10 +81,7 @@ impl Future for Dummy {
tracing::trace!("Update future completed, sleeping!"); tracing::trace!("Update future completed, sleeping!");
mem::replace( self.state = DummyState::Sleeping(Self::timer(), Some(next));
&mut self.state,
DummyState::Sleeping(Self::timer(), Some(next)),
);
} }
} }
} }

View File

@ -3,22 +3,15 @@ use crate::initiators::process::Process;
use crate::resources::modules::fabaccess::Status; use crate::resources::modules::fabaccess::Status;
use crate::session::SessionHandle; use crate::session::SessionHandle;
use crate::{ use crate::{
AuthenticationHandle, Config, MachineState, Resource, ResourcesHandle, SessionManager, AuthenticationHandle, Config, Resource, ResourcesHandle, SessionManager,
}; };
use async_compat::CompatExt;
use executor::prelude::Executor; use executor::prelude::Executor;
use futures_util::ready; use futures_util::ready;
use miette::IntoDiagnostic;
use rumqttc::ConnectReturnCode::Success;
use rumqttc::{AsyncClient, ConnectionError, Event, Incoming, MqttOptions};
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt::Display;
use std::future::Future; use std::future::Future;
use std::pin::Pin; use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use std::time::Duration;
use tracing::Span; use tracing::Span;
use url::Url;
mod dummy; mod dummy;
mod process; mod process;
@ -107,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

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

@ -3,13 +3,12 @@
//#![warn(missing_docs)] //#![warn(missing_docs)]
//#![warn(missing_crate_level_docs)] //#![warn(missing_crate_level_docs)]
//! Diflouroborane //! Difluoroborane
//! //!
//! This is the capnp component of the FabAccess project. //! This is the capnp component of the FabAccess project.
//! The entry point of bffhd can be found in [bin/bffhd/main.rs](../bin/bffhd/main.rs) //! The entry point of bffhd can be found in [bin/bffhd/main.rs](../bin/bffhd/main.rs)
use miette::Diagnostic; use miette::{Diagnostic, IntoDiagnostic};
use std::io;
use thiserror::Error; use thiserror::Error;
pub mod config; pub mod config;
@ -48,7 +47,6 @@ mod tls;
use std::sync::Arc; use std::sync::Arc;
use futures_util::{FutureExt, StreamExt}; use futures_util::{FutureExt, StreamExt};
use miette::{Context, IntoDiagnostic, Report};
use once_cell::sync::OnceCell; use once_cell::sync::OnceCell;
use crate::audit::AuditLog; use crate::audit::AuditLog;
@ -69,7 +67,9 @@ use lightproc::recoverable_handle::RecoverableHandle;
use signal_hook::consts::signal::*; use signal_hook::consts::signal::*;
use tracing::Span; use tracing::Span;
pub struct Diflouroborane { use std::collections::HashMap;
pub struct Difluoroborane {
config: Config, config: Config,
executor: Executor<'static>, executor: Executor<'static>,
pub statedb: StateDB, pub statedb: StateDB,
@ -89,6 +89,7 @@ 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(
@ -136,7 +137,13 @@ pub enum BFFHError {
), ),
} }
impl Diflouroborane { #[derive(serde::Serialize, serde::Deserialize)]
struct DatabaseDump {
users: HashMap<String, users::db::UserData>,
state: HashMap<String, resources::state::State>,
}
impl Difluoroborane {
pub fn setup() {} pub fn setup() {}
pub fn new(config: Config) -> Result<Self, BFFHError> { pub fn new(config: Config) -> Result<Self, BFFHError> {
@ -198,6 +205,23 @@ impl Diflouroborane {
}) })
} }
pub fn dump_db(&mut self, file: &str) -> Result<(), miette::Error> {
let users = self.users.dump_map()?;
let state = self.statedb.dump_map()?;
let dump = DatabaseDump{users, state};
let data = toml::ser::to_vec(&dump).map_err(|e| miette::Error::msg(format!("Serializing database dump failed: {}", e)))?;
std::fs::write(file, &data).map_err(|e| miette::Error::msg(format!("writing database dump failed: {}", e)))?;
Ok(())
}
pub fn load_db(&mut self, file: &str) -> Result<(), miette::Error> {
let data = std::fs::read(file).into_diagnostic()?;
let dump: DatabaseDump = toml::de::from_slice(&data).into_diagnostic()?;
self.users.load_map(&dump.users)?;
self.statedb.load_map(&dump.state)?;
Ok(())
}
pub fn run(&mut self) -> Result<(), BFFHError> { pub fn run(&mut self) -> Result<(), BFFHError> {
let _guard = self.span.enter(); let _guard = self.span.enter();
let mut signals = signal_hook_async_std::Signals::new(&[SIGINT, SIGQUIT, SIGTERM]) let mut signals = signal_hook_async_std::Signals::new(&[SIGINT, SIGQUIT, SIGTERM])
@ -212,7 +236,9 @@ 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())?;
@ -231,13 +257,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 = None; let mut sig;
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(()); _ = tx.send(()); // ignore result, as an Err means that the executor we want to stop has already stopped
}; };
self.executor.run(f); self.executor.run(f);

View File

@ -2,16 +2,15 @@ use serde::{Deserialize, Serialize};
use std::path::Path; use std::path::Path;
use tracing_subscriber::fmt::format::Format; use tracing_subscriber::fmt::format::Format;
use tracing_subscriber::prelude::*; use tracing_subscriber::prelude::*;
use tracing_subscriber::reload::Handle; use tracing_subscriber::EnvFilter;
use tracing_subscriber::{reload, EnvFilter};
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogConfig { pub struct LogConfig {
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
/// Log filter string in the tracing format `target[span{field=value}]=level`. /// Log filter string in the tracing format `target[span{field=value}]=level`.
/// lvalue is optional and multiple filters can be combined with comma. /// lvalue is optional and multiple filters can be combined with comma.
/// e.g. `warn,diflouroborane::actors=debug` will only print `WARN` and `ERROR` unless the /// e.g. `warn,difluoroborane::actors=debug` will only print `WARN` and `ERROR` unless the
/// message is logged in a span below `diflouroborane::actors` (i.e. by an actor task) in /// message is logged in a span below `difluoroborane::actors` (i.e. by an actor task) in
/// which case `DEBUG` and `INFO` will also be printed. /// which case `DEBUG` and `INFO` will also be printed.
pub filter: Option<String>, pub filter: Option<String>,

View File

@ -85,10 +85,13 @@ 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");
AUDIT let res = 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");
@ -161,7 +164,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); serializer.serialize_value(&state).expect("serializing a MachineState shoud be infallible");
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

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

View File

@ -1,12 +1,12 @@
use rkyv::ser::Serializer;
use rkyv::ser::serializers::AllocSerializer;
use thiserror::Error; use thiserror::Error;
use crate::db; use crate::db;
use crate::db::{AlignedAdapter, ArchivedValue, RawDB, DB}; use crate::db::{AlignedAdapter, ArchivedValue, RawDB, DB};
use lmdb::{DatabaseFlags, Environment, EnvironmentFlags, Transaction, WriteFlags}; use lmdb::{DatabaseFlags, Environment, EnvironmentFlags, Transaction, WriteFlags};
use miette::{Diagnostic, LabeledSpan, Severity, SourceCode}; use miette::Diagnostic;
use std::any::TypeId; use std::fmt::Debug;
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::{path::Path, sync::Arc}; use std::{path::Path, sync::Arc};
use crate::resources::state::State; use crate::resources::state::State;
@ -54,8 +54,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 = unsafe { RawDB::open(&env, Some("state")) }; let db = RawDB::open(&env, Some("state"))
let db = db.map_err(|e| StateDBError::Open(e.into()))?; .map_err(|e| StateDBError::Open(e.into()))?;
Ok(Self::new(env, db)) Ok(Self::new(env, db))
} }
@ -66,8 +66,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 = unsafe { RawDB::create(&env, Some("state"), flags) }; let db = RawDB::create(&env, Some("state"), flags)
let db = db.map_err(|e| StateDBError::Create(e.into()))?; .map_err(|e| StateDBError::Create(e.into()))?;
Ok(Self::new(env, db)) Ok(Self::new(env, db))
} }
@ -99,6 +99,30 @@ impl StateDB {
self.db.put(&mut txn, key, val, flags)?; self.db.put(&mut txn, key, val, flags)?;
Ok(txn.commit()?) Ok(txn.commit()?)
} }
pub fn load_map(&self, map: &std::collections::HashMap<String, State>) -> miette::Result<()> {
use miette::IntoDiagnostic;
let mut txn = self.env.begin_rw_txn().into_diagnostic()?;
let flags = WriteFlags::empty();
for (key, val) in map {
let mut serializer = AllocSerializer::<1024>::default();
serializer.serialize_value(val).into_diagnostic()?;
let serialized = ArchivedValue::new(serializer.into_serializer().into_inner());
self.db.put(&mut txn, &key.as_bytes(), &serialized, flags)?;
}
txn.commit().into_diagnostic()?;
Ok(())
}
pub fn dump_map(&self) -> miette::Result<std::collections::HashMap<String, State>> {
let mut map = std::collections::HashMap::new();
for (key, val) in self.get_all(&self.begin_ro_txn()?)? {
let key_str = core::str::from_utf8(&key).map_err(|_e| miette::Error::msg("state key not UTF8"))?.to_string();
let val_state: State = rkyv::Deserialize::deserialize(val.as_ref(), &mut rkyv::Infallible).unwrap();
map.insert(key_str, val_state);
}
Ok(map)
}
} }
#[cfg(test)] #[cfg(test)]

View File

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

View File

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

View File

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

View File

@ -7,8 +7,7 @@ use std::collections::HashMap;
use std::fmt::{Display, Formatter}; use std::fmt::{Display, Formatter};
use std::io::Write; use std::io::Write;
use clap::ArgMatches; use miette::{Diagnostic, IntoDiagnostic, SourceSpan};
use miette::{Context, Diagnostic, IntoDiagnostic, SourceOffset, SourceSpan};
use std::path::Path; use std::path::Path;
use std::sync::Arc; use std::sync::Arc;
@ -174,6 +173,29 @@ impl Users {
Ok(()) Ok(())
} }
pub fn load_map(&mut self, dump: &HashMap<String,UserData>) -> miette::Result<()> {
let mut txn = unsafe { self.userdb.get_rw_txn() }?;
self.userdb.clear_txn(&mut txn)?;
for (uid, data) in dump {
let user = db::User {
id: uid.clone(),
userdata: data.clone(),
};
tracing::trace!(%uid, ?user, "Storing user object");
if let Err(e) = self.userdb.put_txn(&mut txn, uid.as_str(), &user) {
tracing::warn!(error=?e, "failed to add user")
}
}
txn.commit().map_err(crate::db::Error::from)?;
Ok(())
}
pub fn dump_map(&self) -> miette::Result<HashMap<String, UserData>> {
return Ok(self.userdb.get_all()?)
}
pub fn dump_file(&self, path_str: &str, force: bool) -> miette::Result<usize> { pub fn dump_file(&self, path_str: &str, force: bool) -> miette::Result<usize> {
let path = Path::new(path_str); let path = Path::new(path_str);
let exists = path.exists(); let exists = path.exists();
@ -204,7 +226,7 @@ impl Users {
} }
let mut file = fs::File::create(path).into_diagnostic()?; let mut file = fs::File::create(path).into_diagnostic()?;
let users = self.userdb.get_all()?; let users = self.dump_map()?;
let encoded = toml::ser::to_vec(&users).into_diagnostic()?; let encoded = toml::ser::to_vec(&users).into_diagnostic()?;
file.write_all(&encoded[..]).into_diagnostic()?; file.write_all(&encoded[..]).into_diagnostic()?;

View File

@ -1,5 +1,5 @@
use clap::{Arg, Command, ValueHint}; use clap::{Arg, Command, ValueHint};
use diflouroborane::{config, Diflouroborane}; use difluoroborane::{config, Difluoroborane};
use std::str::FromStr; use std::str::FromStr;
use std::{env, io, io::Write, path::PathBuf}; use std::{env, io, io::Write, path::PathBuf};
@ -15,12 +15,12 @@ fn main() -> miette::Result<()> {
FabAccess {apiver}\n\ FabAccess {apiver}\n\
\t[{build_kind} build built on {build_time}]\n\ \t[{build_kind} build built on {build_time}]\n\
\t {rustc_version}\n\t {cargo_version}", \t {rustc_version}\n\t {cargo_version}",
version=diflouroborane::env::PKG_VERSION, version=difluoroborane::env::PKG_VERSION,
apiver="0.3", apiver="0.3",
rustc_version=diflouroborane::env::RUST_VERSION, rustc_version=difluoroborane::env::RUST_VERSION,
cargo_version=diflouroborane::env::CARGO_VERSION, cargo_version=difluoroborane::env::CARGO_VERSION,
build_time=diflouroborane::env::BUILD_TIME_3339, build_time=difluoroborane::env::BUILD_TIME_3339,
build_kind=diflouroborane::env::BUILD_RUST_CHANNEL)) build_kind=difluoroborane::env::BUILD_RUST_CHANNEL))
.about(clap::crate_description!()) .about(clap::crate_description!())
.arg(Arg::new("config") .arg(Arg::new("config")
.help("Path to the config file to use") .help("Path to the config file to use")
@ -57,10 +57,18 @@ fn main() -> miette::Result<()> {
.help("Check config for validity") .help("Check config for validity")
.long("check")) .long("check"))
.arg( .arg(
Arg::new("dump") Arg::new("dump-db")
.help("Dump all internal databases") .help("Dump all internal databases")
.long("dump") .long("dump-db")
.conflicts_with("load")) .alias("dump")
.conflicts_with("dump-users")
.conflicts_with("load-users")
.conflicts_with("load-db")
.takes_value(true)
.value_name("FILE")
.value_hint(ValueHint::AnyPath)
.default_missing_value("bffh-db.toml")
)
.arg( .arg(
Arg::new("dump-users") Arg::new("dump-users")
.help("Dump the users db to the given file as TOML") .help("Dump the users db to the given file as TOML")
@ -69,18 +77,33 @@ fn main() -> miette::Result<()> {
.value_name("FILE") .value_name("FILE")
.value_hint(ValueHint::AnyPath) .value_hint(ValueHint::AnyPath)
.default_missing_value("users.toml") .default_missing_value("users.toml")
.conflicts_with("load")) .conflicts_with("load-users")
.conflicts_with("load-db")
.conflicts_with("dump-db")
)
.arg( .arg(
Arg::new("force") Arg::new("force")
.help("force ops that may clobber") .help("force ops that may clobber")
.long("force") .long("force")
) )
.arg( .arg(
Arg::new("load") Arg::new("load-users")
.help("Load values into the internal databases") .help("Load users into the internal databases")
.long("load") .long("load-users")
.alias("load")
.takes_value(true) .takes_value(true)
.conflicts_with("dump")) .conflicts_with("dump-db")
.conflicts_with("load-db")
.conflicts_with("dump-users")
)
.arg(
Arg::new("load-db")
.help("Load values into the internal databases")
.long("load-db")
.takes_value(true)
.conflicts_with("dump-db")
.conflicts_with("load-users")
.conflicts_with("dump-users"))
.arg(Arg::new("keylog") .arg(Arg::new("keylog")
.help("log TLS keys into PATH. If no path is specified the value of the envvar SSLKEYLOGFILE is used.") .help("log TLS keys into PATH. If no path is specified the value of the envvar SSLKEYLOGFILE is used.")
.long("tls-key-log") .long("tls-key-log")
@ -98,7 +121,7 @@ fn main() -> miette::Result<()> {
let configpath = matches let configpath = matches
.value_of("config") .value_of("config")
.unwrap_or("/etc/diflouroborane.dhall"); .unwrap_or("/etc/difluoroborane.dhall");
// Check for the --print-default option first because we don't need to do anything else in that // Check for the --print-default option first because we don't need to do anything else in that
// case. // case.
@ -137,10 +160,18 @@ fn main() -> miette::Result<()> {
let mut config = config::read(&PathBuf::from_str(configpath).unwrap())?; let mut config = config::read(&PathBuf::from_str(configpath).unwrap())?;
if matches.is_present("dump") { if matches.is_present("dump-db") {
return Err(miette::miette!("DB Dumping is currently not implemented, except for the users db, using `--dump-users`")); let mut bffh = Difluoroborane::new(config)?;
let fname = matches.value_of("dump-db").unwrap();
bffh.dump_db(fname)?;
return Ok(());
} else if matches.is_present("load-db") {
let mut bffh = Difluoroborane::new(config)?;
let fname = matches.value_of("load-db").unwrap();
bffh.load_db(fname)?;
return Ok(());
} else if matches.is_present("dump-users") { } else if matches.is_present("dump-users") {
let bffh = Diflouroborane::new(config)?; let bffh = Difluoroborane::new(config)?;
let number = bffh.users.dump_file( let number = bffh.users.dump_file(
matches.value_of("dump-users").unwrap(), matches.value_of("dump-users").unwrap(),
@ -150,12 +181,12 @@ fn main() -> miette::Result<()> {
tracing::info!("successfully dumped {} users", number); tracing::info!("successfully dumped {} users", number);
return Ok(()); return Ok(());
} else if matches.is_present("load") { } else if matches.is_present("load-users") {
let bffh = Diflouroborane::new(config)?; let bffh = Difluoroborane::new(config)?;
bffh.users.load_file(matches.value_of("load").unwrap())?; bffh.users.load_file(matches.value_of("load-users").unwrap())?;
tracing::info!("loaded users from {}", matches.value_of("load").unwrap()); tracing::info!("loaded users from {}", matches.value_of("load-users").unwrap());
return Ok(()); return Ok(());
} else { } else {
@ -179,7 +210,7 @@ fn main() -> miette::Result<()> {
} }
config.logging.format = matches.value_of("log format").unwrap_or("full").to_string(); config.logging.format = matches.value_of("log format").unwrap_or("full").to_string();
let mut bffh = Diflouroborane::new(config)?; let mut bffh = Difluoroborane::new(config)?;
bffh.run()?; bffh.run()?;
} }

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(); shadow_rs::new().unwrap();
} }

View File

@ -1,39 +0,0 @@
strict digraph connection {
Establish [label="TCP/SCTP connection established"];
Closed [label="TCP/SCTP connection closed"];
Open;
SASL;
Authenticated;
STARTTLS;
Encrypted;
Establish -> Open [label=open];
Open -> Closed [label=close];
Open -> SASL [label=auth];
SASL -> SASL [label=step];
// Authentication fails
SASL -> Closed [label=fails];
// Authentication succeeds
SASL -> Authenticated [label=successful];
Open -> STARTTLS [label=starttls];
// TLS wrapping succeeds
STARTTLS -> Encrypted [label=successful];
// TLS wrapping fails
STARTTLS -> Closed [label=fails];
Authenticated -> SASL_TLS [label=starttls];
SASL_TLS -> Closed [label=fails];
SASL_TLS -> AuthEnc [label=successful];
Encrypted -> TLS_SASL [label=auth];
TLS_SASL -> TLS_SASL [label=step];
TLS_SASL -> Closed [label=fails];
TLS_SASL -> AuthEnc [label=successful];
// Only authenticated connections may open RPC. For "unauth", use the `Anonymous` SASL method.
AuthEnc -> RPC [label=bootstrap];
Authenticated -> RPC [label=bootstrap];
}

View File

@ -1,42 +0,0 @@
# Stream initiation
In a session there are two parties: The initiating entity and the receiving
entity. This terminology does not refer to information flow but rather to the
side opening a connection respectively the one listening for connection
attempts.
In the currently envisioned use-case the initiating entity is a) a client
(i.e. interactive or batch/automated program) trying to interact in some way or
other with a server b) a server trying to exchange / request information
with/from another server (i.e. federating). The receiving entity however is
already a server.
Additionally the amount and type of clients is likely to be more diverse and
less up to date than the servers.
Conclusions I draw from this:
- Clients are more likely to implement an outdated version of the communication
protocol.
- The place for backwards-compatability should be the servers.
- Thus the client (initiating entity) should send the expected API version
first, the server then using that as a basis to decide with which API
version to answer.
# Stream negotiation
Since the receiving entity for a connection is responsible for the machines it
controls it imposes conditions for connecting either as client or as federating
server. At least every initiating entity is required to authenticate itself to
the receiving entity before attempting further actions or requesting
information. But a receiving entity can require other features, such as
transport layer encryption.
To this end a receiving entity informs the initiating entity about features that
it requires from the initiating entity before taking any further action and
features that are voluntary to negotiate but may improve qualities of the stream
(such as message compression)
A varying set of conditions implies negotiation needs to take place. Since
features potentially require a strict order (e.g. Encryption before
Authentication) negotiation has to be a multi-stage process. Further
restrictions are imposed because some features may only be offered after others
have been established (e.g. SASL authentication only becoming available after
encryption, EXTERNAL mechanism only being available to local sockets or
connections providing a certificate)

View File

@ -1,93 +0,0 @@
strict digraph state {
rank = 0
subgraph "cluster_internal_state" {
rank = 1
ctr = applied
start
[shape=doublecircle, label="BFFH"]
created
[label="Machine object created"];
start -> created;
created -> attach
[label="New state or loaded from disk"];
attach
[label="Attach actor", shape=box];
unapplied
[label="Unapplied"];
applied
[label="Applied"];
verified
[label="Verified"];
wait_apply
[label="Wait ∀ Actors", shape=box]
wait_verify
[label="Wait ∀ Actors", shape=box]
unapplied -> wait_apply -> applied;
applied -> wait_verify -> verified;
applied -> unapplied
[label="statechange received"];
verified -> unapplied
[label="statechange received"];
unapplied -> unapplied
[label="statechange received"];
unapplied -> attach -> unapplied;
applied -> attach -> unapplied;
verified -> attach -> unapplied;
}
subgraph "cluster_actor" {
rank = 1
center = actor_applied
actor_start
[shape=doublecircle, label="Actor"];
actor_fresh
[label="Actor was just constructed"];
actor_start -> actor_fresh;
actor_attached
[label="Attached"];
actor_unapplied
[label="Unapplied"];
actor_applied
[label="Applied"];
actor_verified
[label="Verified"];
wait_initial
[label="Recv", shape=box];
wait_state
[label="Recv", shape=box];
actor_fresh -> wait_initial -> actor_attached;
actor_attached -> actor_applied
[label="initialize/apply"];
actor_unapplied -> actor_applied
[label="apply"];
actor_applied -> actor_verified
[label="verify"];
actor_unapplied -> wait_state;
actor_applied -> wait_state;
actor_verified -> wait_state;
wait_state -> actor_unapplied;
}
attach -> wait_initial
[label="Send initial state to that actor", style=dotted]
unapplied -> wait_state
[label="Send new state to all actors", style=dotted];
actor_applied -> wait_apply
[label="Confirm apply", style=dotted];
actor_verified -> wait_verify
[label="Confirm verify", style=dotted];
}

View File

@ -1,11 +0,0 @@
# API-Testsetup
wirklich nur um das API zu testen. ATM implementiert: machines::* & machine::read, authenticate
1. Ein mosquitto o.ä MQTT Server starten
1. Datenbanken füllen: `cargo run -- -c examples/bffh.dhall --load=examples`
1. Daemon starten: `cargo run -- -c examples/bffh.dhall`
1. ???
1. PROFIT!
A dockerized version of this example can be found in the docker subdirectory

View File

@ -1,179 +0,0 @@
#!/usr/bin/env python3
import sys
import argparse
def on_free(args, actor_name):
"""
Function called when the state of the connected machine changes to Free
again
"""
if args.verbose > 2:
print("on_free called!")
if actor_name == "DoorControl1":
# Do whatever you want to do in case `DoorControl1` is returned back to free.
# Keep in mind that process actors should return quickly to not miss
# updates, so if you need to do things that take a while fork a new
# process e.g. with the `subprocess` Module
print("I'm locking door 1!")
pass
elif actor_name == "DoorControl2":
print("I'm locking door 2!")
pass # Close a different door
else:
if not args.quiet:
print("process called with unknown id %s for state `Free`" % actor_name)
# It's a good idea to exit with an error code in case something
# unexpected happens.
# The process module logs everything printed to stdout by actors into
# the server log, but marks them as `Error` in case the actor process
# exits with a code != 0, making debugging somewhat easier.
exit(-1)
def on_use(args, actor_name, user_id):
"""
Function called when an user takes control of the connected machine
user_id contains the UID of the user now using the machine
"""
if args.verbose > 2:
print("on_use called!")
if actor_name == "DoorControl1":
print("I'm opening door 1 for 10 seconds!")
pass # Open door one
elif actor_name == "DoorControl2":
print("I'm opening door 2 for 10 seconds!")
pass # Open a different door
else:
if not args.quiet:
print("process called with unknown id %s for state `InUse`" % actor_name)
# It's a good idea to exit with an error code in case something
# unexpected happens.
# The process module logs everything printed to stdout by actors into
# the server log, but marks them as `Error` in case the actor process
# exits with a code != 0, making debugging somewhat easier.
exit(-1)
def on_tocheck(args, actor_name, user_id):
"""
Function called when an user returns control and the connected machine is
configured to go to state `ToCheck` instead of `Free` in that case.
user_id contains the UID of the manager expected to check the machine.
The user that used the machine beforehand has to be taken from the last
user field using the API (via e.g. the mobile app)
"""
if args.verbose > 2:
print("on_tocheck called!")
if not args.quiet:
print("process called with unexpected combo id %s and state 'ToCheck'" % actor_name)
exit(-1)
def on_blocked(args, actor_name, user_id):
"""
Function called when an manager marks the connected machine as `Blocked`
user_id contains the UID of the manager that blocked the machine
"""
if args.verbose > 2:
print("on_blocked called!")
if not args.quiet:
print("process called with unexpected combo id %s and state 'Blocked'" % actor_name)
exit(-1)
def on_disabled(args, actor_name):
"""
Function called when the connected machine is marked `Disabled`
"""
if not args.quiet:
print("process called with unexpected combo id %s and state 'Disabled'" % actor_name)
exit(-1)
def on_reserve(args, actor_name, user_id):
"""
Function called when the connected machine has been reserved by somebody.
user_id contains the UID of the reserving user.
"""
if not args.quiet:
print("process called with unexpected combo id %s and state 'Reserved'" % actor_name)
exit(-1)
def main(args):
"""
Python example actor
This is an example how to use the `process` actor type to run a Python script.
"""
if args.verbose is not None:
if args.verbose == 1:
print("verbose output enabled")
elif args.verbose == 2:
print("loud output enabled!")
elif args.verbose == 3:
print("LOUD output enabled!!!")
elif args.verbose > 4:
print("Okay stop you're being ridiculous.")
sys.exit(-2)
else:
args.verbose = 0
# You could also check the actor name here and call different functions
# depending on that variable instead of passing it to the state change
# methods.
new_state = args.state
if new_state == "free":
on_free(args, args.name)
elif new_state == "inuse":
on_use(args, args.name, args.userid)
elif new_state == "tocheck":
on_tocheck(args, args.name, args.userid)
elif new_state == "blocked":
on_blocked(args, args.name, args.userid)
elif new_state == "disabled":
on_disabled(args, args.name)
elif new_state == "reserved":
on_reserve(args, args.name, args.userid)
else:
print("Process actor called with unknown state %s" % new_state)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
# Parameters are passed to the Process actor as follows:
# 1. the contents of params.args, split by whitespace as separate args
# 2. the configured id of the actor (e.g. "DoorControl1")
# 3. the new state as one of [free|inuse|tocheck|blocked|disabled|reserved]
parser.add_argument("-q", "--quiet", help="be less verbose", action="store_true")
parser.add_argument("-v", "--verbose", help="be more verbose", action="count")
parser.add_argument("name",
help="name of this actor as configured in bffh.dhall"
)
# We parse the new state using subparsers so that we only require a userid
# in case it's a state that sets one.
subparsers = parser.add_subparsers(required=True, dest="state")
parser_free = subparsers.add_parser("free")
parser_inuse = subparsers.add_parser("inuse")
parser_inuse.add_argument("userid", help="The user that is now using the machine")
parser_tocheck = subparsers.add_parser("tocheck")
parser_tocheck.add_argument("userid", help="The user that should go check the machine")
parser_blocked = subparsers.add_parser("blocked")
parser_blocked.add_argument("userid", help="The user that marked the machine as blocked")
parser_disabled = subparsers.add_parser("disabled")
parser_reserved = subparsers.add_parser("reserved")
parser_reserved.add_argument("userid", help="The user that reserved the machine")
args = parser.parse_args()
main(args)

View File

@ -1,4 +0,0 @@
#!/usr/bin/env bash
echo "Bash actor called with $@" > /tmp/act
echo "Bash actor called with: $@"

View File

@ -1,234 +0,0 @@
{- Main configuration file for bffh
- ================================
-
- In this configuration file you configure almost all parts of how bffh operates, but most importantly:
- * Machines
- * Initiators and Actors
- * Which Initiators and Actors relate to which machine(s)
- * Roles and the permissions granted by them
-}
-- The config is in the configuration format/language dhall. You can find more information about dhall over at
-- https://dhall-lang.org
-- (Our) Dhall is somewhat similar to JSON and YAML in that it expects a top-level object containing the
-- configuration values
{
-- Configure the addresses and ports bffh listens on
listens = [
-- BFFH binds a port for every listen object in this array.
-- Each listen object is of the format { address = <STRING>, port = <INTEGER> }
-- If you don't specify a port bffh will use the default of `59661`
-- 'address' can be a IP address or a hostname
-- If bffh can not bind a port for the specified combination if will log an error but *continue with the remaining ports*
{ address = "127.0.0.1", port = 59661 },
{ address = "::1", port = 59661 },
{ address = "steak.fritz.box", port = 59661 }
],
-- Configure TLS. BFFH requires a PEM-encoded certificate and the associated key as two separate files
certfile = "examples/self-signed-cert.pem",
keyfile = "examples/self-signed-key.pem",
-- BFFH right now requires a running MQTT broker.
mqtt_url = "tcp://localhost:1883",
-- Path to the database file for bffh. bffh will in fact create two files; ${db_path} and ${db_path}.lock.
-- BFFH will *not* create any directories so ensure that the directory exists and the user running bffh has write
-- access into them.
db_path = "/tmp/bffh",
-- Audit log path. Bffh will log state changes into this file, one per line.
-- Audit log entries are for now JSON:
-- {"timestamp":1641497361,"machine":"Testmachine","state":{"state":{"InUse":{"uid":"Testuser","subuid":null,"realm":null}}}}
auditlog_path = "/tmp/bffh.audit",
-- In dhall you can also easily import definitions from other files, e.g. you could write
-- roles = ./roles.dhall
roles = {
-- Role definitions
-- A role definition is of the form
-- rolename = {
-- parents = [<list of role names to inherit from>],
-- permissions = [<list of perm rules>],
-- }
--
-- Role names are case sensitive, so RoleName != rolename.
--
-- If you want either parents or permissions to be empty its best to completely skip it:
testrole = {
permissions = [ "lab.some.admin" ]
},
somerole = {
parents = ["testparent"],
-- "Permissions" are formatted as Perm Rules, so you can use the wildcards '*' and '+'
permissions = [ "lab.test.*" ]
},
-- Roles can inherit from each other. In that case a member of e.g. 'somerole' that inherits from
-- 'testparent' will have all the permissions of 'somerole' AND 'testparent' assigned to them.
-- Right now permissions are stricly additive so you can't take a permission away in a child role that a parent
-- role grants.
testparent = {
permissions = [
"lab.some.write",
"lab.some.read",
"lab.some.disclose"
]
}
},
-- Configure machines
-- "Machines" (which in future will be more appropiately named "resources") are the main thing bffh is concerned
-- with.
-- You can define an almost limitless amount of machines (well 2^64 - 1, so 18_446_744_073_709_551_615 to be precise)
-- Each of these machines can then have several "actors" and "initiators" assigned
machines = {
Testmachine = {
-- A machine comes with two "names". The id above ("Testmachine") and the "name" ("MachineA").
-- The id is what you'll use in the config format and is strictly limited to alphanumeric characters and '_'
-- and must begin with a letter. Most importantly you CAN NOT use '-' or spaces in an identifier
-- (dhall makes this technically possible but you can break things in subtle ways)
-- REQUIRED. The "name" of a machine is what will be presented to humans. It can contain all unicode
-- including spaces and nonprintable characters.
-- A name SHOULD be short but unique.
name = "MachineA",
-- OPTIONAL. A description can be assigned to machines. It will also only be shown to humans. Thus it is
-- once again limited only to unicode. If you want to provide your users with important additional
-- information other than the name this is the place to do it.
description = "A test machine",
-- OPTIONAL. If you have a wiki going into more detail how to use a certain machine or what to keep in
-- mind when using it you can provide a URL here that will be presented to users.
wiki = "https://wiki.example.org/machineA",
-- OPTIONAL. You can assign categories to machines to allow clients to group/filter machines by them.
category = "Testcategory",
-- REQUIRED.
-- Each machine MUST have *all* Permission levels assigned to it.
-- Permissions aren't PermRules as used in the 'roles' definitions but must be precise without wildcards.
-- Permission levels aren't additive, so a user having 'manage' permission does not automatically get
-- 'read' or 'write' permission.
-- (Note, disclose is not fully implemented at the moment)
-- Users lacking 'disclose' will not be informed about this machine in any way and it will be hidden from
-- them in the client. Usually the best idea is to assign 'read' and 'disclose' to the same permission.
disclose = "lab.test.read",
-- Users lacking 'read' will be shown a machine including name, description, category and wiki but not
-- it's current state. The current user is not disclosed.
read = "lab.test.read",
-- The 'write' permission allows to 'use' the machine.
write = "lab.test.write",
-- Manage represents the 'superuser' permission. Users with this permission can force set any state and
-- read out the current user
manage = "lab.test.admin"
},
Another = {
wiki = "test_another",
category = "test",
disclose = "lab.test.read",
manage = "lab.test.admin",
name = "Another",
read = "lab.test.read",
write = "lab.test.write"
},
Yetmore = {
description = "Yet more test machines",
disclose = "lab.test.read",
manage = "lab.test.admin",
name = "Yetmore",
read = "lab.test.read",
write = "lab.test.write"
}
},
-- Actor configuration. Actors are how bffh affects change in the real world by e.g. switching a power socket
-- using a shelly
actors = {
-- Actors similarly to machines have an 'id'. This id (here "Shelly1234") is limited to Alphanumeric ASCII
-- and must begin with a letter.
Shelly1234 = {
-- Actors are modular pieces of code that are loaded as required. The "Shelly" module will send
-- activation signals to a shelly switched power socket over MQTT
module = "Shelly",
-- Actors can have arbitrary parameters passed to them, varying by actor module.
params = {
-- For Shelly you can configure the MQTT topic segment it uses. Shellies listen to a specific topic
-- containing their name (which is usually of the form "shelly_<id>" but can be changed).
-- If you do not configure a topic here the actor will use it's 'id' (in this case "Shelly1234").
topic = "Topic1234"
}
},
Bash = {
-- The "Process" module runs a given script or command on state change.
-- bffh invoces the given cmd as `$ ${cmd} ${args} ${id} ${state}` so e.g. as
-- `$ ./examples/actor.sh your ad could be here Bash inuse`
module = "Process",
params = {
-- which is configured by the (required) 'cmd' parameter. Paths are relative to PWD of bffh. Systemd
-- and similar process managers may change this PWD so it's usually the most future-proof to use
-- absolute paths.
cmd = "./examples/actor.sh",
-- You can pass static args in here, these will be passed to every invocation of the command by this actor.
-- args passed here are split by whitespace, so these here will be passed as 5 separate arguments
args = "your ad could be here"
}
},
DoorControl1 = {
-- This actor calls the actor.py script in examples/
-- It gets passed it's own name, so you can have several actors
-- from the same script.
-- If you need to pass more arguments to the command you can use the `args` key in
-- `params` as is done with the actor `Bash`
module = "Process",
-- the `args` are passed in front of all other parameters so they are best suited to
-- optional parameters like e.g. the verboseness
params = { cmd = "./examples/actor.py", args = "-vvv" }
},
DoorControl2 = {
module = "Process",
params = { cmd = "./examples/actor.py" }
},
DoorControl3 = {
-- This is an example for how it looks like if an actor is misconfigured.
-- the actor.py doesn't know anything about DoorControl3 and, if this actor is enabled,
-- will return with an error showing up in the server logs.
module = "Process",
params = { cmd = "./examples/actor.py" }
},
Bash2 = { module = "Process", params = { cmd = "./examples/actor.sh" , args = "this is a different one" }},
FailBash = { module = "Process", params = { cmd = "./examples/fail-actor.sh" }}
},
-- Linkng up machines to actors
-- Actors need to be connected to machines to be useful. A machine can be connected to multiple actors, but one
-- actor can only be connected to one machine.
actor_connections = [
{ machine = "Testmachine", actor = "Shelly1234" },
{ machine = "Another", actor = "Bash" },
{ machine = "Yetmore", actor = "Bash2" },
{ machine = "Yetmore", actor = "FailBash"}
],
-- Initiators are configured almost the same way as Actors, refer to actor documentation for more details
-- The below '{=}' is what you need if you want to define *no* initiators at all and only use the API with apps
-- to let people use machines.
initiators = {=},
-- The "Dummy" initiator will try to use and return a machine as the given user every few seconds. It's good to
-- test your system but will spam your log so is disabled by default.
--initiators = { Initiator = { module = "Dummy", params = { uid = "Testuser" } } },
-- Linking up machines to initiators. Similar to actors a machine can have several initiators assigned but an
-- initiator can only be assigned to one machine.
-- The below is once again how you have to define *no* initiators.
init_connections = [] : List { machine : Text, initiator : Text }
--init_connections = [{ machine = "Testmachine", initiator = "Initiator" }]
}

View File

@ -1,5 +0,0 @@
# API-Testsetup, aber mit Docker
wirklich nur um das API zu testen. ATM implementiert: machines::* & machine::read, authenticate
* run `docker-compose up` in this directory

View File

@ -1,42 +0,0 @@
-- { actor_connections = [] : List { _1 : Text, _2 : Text }
{ actor_connections = [{ _1 = "Testmachine", _2 = "Actor" }]
, actors =
{ Actor = { module = "Shelly", params = {=} }
}
, init_connections = [] : List { _1 : Text, _2 : Text }
--, init_connections = [{ _1 = "Initiator", _2 = "Testmachine" }]
, initiators =
{ Initiator = { module = "Dummy", params = {=} }
}
, listens =
[ { address = "::", port = Some 59661 }
]
, machines =
{ Testmachine =
{ description = Some "A test machine"
, disclose = "lab.test.read"
, manage = "lab.test.admin"
, name = "Testmachine"
, read = "lab.test.read"
, write = "lab.test.write"
},
Another =
{ description = Some "Another test machine"
, disclose = "lab.test.read"
, manage = "lab.test.admin"
, name = "Another"
, read = "lab.test.read"
, write = "lab.test.write"
},
Yetmore =
{ description = Some "Yet more test machines"
, disclose = "lab.test.read"
, manage = "lab.test.admin"
, name = "Yetmore"
, read = "lab.test.read"
, write = "lab.test.write"
}
}
, mqtt_url = "tcp://mqtt:1883"
, db_path = "/tmp/bffh"
}

View File

@ -1 +0,0 @@
Testuser = "secret"

View File

@ -1,19 +0,0 @@
[anotherrole]
[testrole]
permissions = [
"lab.test.*"
]
[somerole]
parents = ["testparent/lmdb"]
permissions = [
"lab.some.admin"
]
[testparent]
permissions = [
"lab.some.write",
"lab.some.read",
"lab.some.disclose",
]

View File

@ -1,11 +0,0 @@
[Testuser]
# Define them in roles.toml as well
roles = ["somerole/lmdb", "testrole/lmdb"]
# If two or more users want to use the same machine at once the higher prio
# wins
priority = 0
# You can add whatever random data you want.
# It will get stored in the `kv` field in UserData.
noot = "noot!"

View File

@ -1,13 +0,0 @@
version: "3.8"
services:
bffh:
image: registry.gitlab.com/fabinfra/fabaccess/bffh:dev-latest
ports:
- "59661:59661"
volumes:
# generate a sample config.toml by running "docker run registry.gitlab.com/fabinfra/fabaccess/bffh:dev-latest --print-default > examples/config.toml" from the project root. You may have to delete the ipv6 listen section.
- "./config:/etc/bffh"
links:
- mqtt
mqtt:
image: eclipse-mosquitto:1.6.13

View File

@ -1,11 +0,0 @@
# Integration tests with Docker
## How it works
* spawns 2 instances of our bffh container and required mqqt broker
* spawns an additional debian to run a shell
* the containers can reach each other by their hostname
## How to start
* run `docker-compose up --exit-code-from test-manager` in this directory
* this will kill all containers when

View File

@ -1,20 +0,0 @@
{ actor_connections = [{ _1 = "Testmachine", _2 = "Actor" }]
, actors =
{ Actor = { module = "Shelly", params = {=} }
}
, init_connections = [{ _1 = "Initiator", _2 = "Testmachine" }]
, initiators =
{ Initiator = { module = "Dummy", params = {=} }
}
, listens = [{ address = "::", port = Some 59661 }]
, machines =
{ Testmachine =
{ description = Some "A test machine"
, disclose = "lab.test.read"
, manage = "lab.test.admin"
, name = "Testmachine"
, read = "lab.test.read"
, write = "lab.test.write"
} }
, mqtt_url = "tcp://mqtt-a:1883"
}

View File

@ -1 +0,0 @@
Testuser = "secret"

View File

@ -1,20 +0,0 @@
[testrole]
name = "Testrole"
permissions = [
"lab.test.*"
]
[somerole]
name = "Somerole"
parents = ["testparent%lmdb"]
permissions = [
"lab.some.admin"
]
[testparent]
name = "Testparent"
permissions = [
"lab.some.write",
"lab.some.read",
"lab.some.disclose",
]

View File

@ -1,11 +0,0 @@
[Testuser]
# Define them in roles.toml as well
roles = []
# If two or more users want to use the same machine at once the higher prio
# wins
priority = 0
# You can add whatever random data you want.
# It will get stored in the `kv` field in UserData.
noot = "noot!"

View File

@ -1,20 +0,0 @@
{ actor_connections = [{ _1 = "Testmachine", _2 = "Actor" }]
, actors =
{ Actor = { module = "Shelly", params = {=} }
}
, init_connections = [{ _1 = "Initiator", _2 = "Testmachine" }]
, initiators =
{ Initiator = { module = "Dummy", params = {=} }
}
, listens = [{ address = "::", port = Some 59661 }]
, machines =
{ Testmachine =
{ description = Some "A test machine"
, disclose = "lab.test.read"
, manage = "lab.test.admin"
, name = "Testmachine"
, read = "lab.test.read"
, write = "lab.test.write"
} }
, mqtt_url = "tcp://mqtt-b:1883"
}

View File

@ -1 +0,0 @@
Testuser = "secret"

View File

@ -1,20 +0,0 @@
[testrole]
name = "Testrole"
permissions = [
"lab.test.*"
]
[somerole]
name = "Somerole"
parents = ["testparent%lmdb"]
permissions = [
"lab.some.admin"
]
[testparent]
name = "Testparent"
permissions = [
"lab.some.write",
"lab.some.read",
"lab.some.disclose",
]

View File

@ -1,11 +0,0 @@
[Testuser]
# Define them in roles.toml as well
roles = []
# If two or more users want to use the same machine at once the higher prio
# wins
priority = 0
# You can add whatever random data you want.
# It will get stored in the `kv` field in UserData.
noot = "noot!"

View File

@ -1,26 +0,0 @@
version: "3.8"
services:
bffh-a:
image: registry.gitlab.com/fabinfra/fabaccess/bffh:dev-latest
command: ["sh", "-c", "diflouroborane -c /etc/bffh/bffh.dhall --load=/etc/bffh; diflouroborane -c /etc/bffh/bffh.dhall"]
volumes:
# generate a sample config.toml by running "docker run registry.gitlab.com/fabinfra/fabaccess/bffh:dev-latest --print-default > examples/config.toml" from the project root. You may have to delete the ipv6 listen section.
- "./config_a:/etc/bffh"
links:
- mqtt-a
mqtt-a:
image: eclipse-mosquitto
bffh-b:
image: registry.gitlab.com/fabinfra/fabaccess/bffh:dev-latest
command: ["sh", "-c", "diflouroborane -c /etc/bffh/bffh.dhall --load=/etc/bffh; diflouroborane -c /etc/bffh/bffh.dhall"]
volumes:
# generate a sample config.toml by running "docker run registry.gitlab.com/fabinfra/fabaccess/bffh:dev-latest --print-default > examples/config.toml" from the project root. You may have to delete the ipv6 listen section.
- "./config_b:/etc/bffh"
links:
- mqtt-b
mqtt-b:
image: eclipse-mosquitto
test-manager:
image: debian
tty: true

View File

@ -1,4 +0,0 @@
#!/usr/bin/env bash
echo "This is some error output" > /dev/stderr
exit 115

View File

@ -1,13 +0,0 @@
#!/usr/bin/env python
import sys
import time
while True:
print('{ "state": { "1.3.6.1.4.1.48398.612.2.4": { "state": "Free" } } }')
sys.stdout.flush()
time.sleep(2)
print('{ "state": { "1.3.6.1.4.1.48398.612.2.4": { "state": { "InUse": { "id": "Testuser" } } } } }')
sys.stdout.flush()
time.sleep(2)

View File

@ -1,19 +0,0 @@
-----BEGIN CERTIFICATE-----
MIIDFzCCAf+gAwIBAgIUDr+1F3zzyza+soLtiurKEXW9pGIwDQYJKoZIhvcNAQEL
BQAwGzEZMBcGA1UEAwwQYmZmaC1kZXZlbG9wbWVudDAeFw0yMTEyMDkxODQ2Mjla
Fw0zMTEyMDkxODQ2MjlaMBsxGTAXBgNVBAMMEGJmZmgtZGV2ZWxvcG1lbnQwggEi
MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDGwNy7yGaURR08dWfoDmnJeyx1
0FVRmozoGCIb3Oj6c2t+84QUxqTdknE7Cdcz5Wi1o0x2CWPZG4z1vgTaCcJVhcME
hxn+7eK1NtDQEjs8Ojs7uaraVvooIe8R7jat0qs7Dmf8RO9P0I4MMZlvijhI7aLw
0C6vNsr1ebeppIiwO5aUuCGuKqxJGghHeqZv18ZcPayunyNrxMC6uyX7y6nUVkfq
x0m9gDsN112Iv9Dd/ZE5Gxivm8jZvVUGZgJD2szK7zbeCDeo5aU3cRWfYaoN0QDx
AKmo4bjciJzfMDDgvcIBq9lGS3FxEv394Mc5YX/ZdP+KRTiHcYCXfBzr3B6HAgMB
AAGjUzBRMB0GA1UdDgQWBBTtUvvWXlo5tU8cEoxbs5UJdodOVDAfBgNVHSMEGDAW
gBTtUvvWXlo5tU8cEoxbs5UJdodOVDAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3
DQEBCwUAA4IBAQAB3IxRnWi/LrxCvlHNaWEi3ZvlbN+KpegWZeKtjHwQoizhR/Fi
SMC7z4y6trJE7LXUOSb9Pu8QQSvpVQZd3W4XCPZMl10Lt7iV8vc3pVviCseDnT9r
X1gXdbeuyYm9lE8KtlhX03jD/CiEx7Qe/q8Rc20AQIKAAJzvl7sXU2tmJ5kpzMEO
v5czlLaX2ajlD/QMgNBUuDyw6wPo3wx9Khph484RygN2LHeT6kfu/PBiF0dGDTUu
mgxg4K0GfwTcHgtz5Bag/HyuuJEKx8Wv7jth59PyKPT+lMVBznxIm3gLS5U+Nnr1
uAws8dgLXRlPo5HJORuJCcZWVBClruZUpyDT
-----END CERTIFICATE-----

View File

@ -1,28 +0,0 @@
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDGwNy7yGaURR08
dWfoDmnJeyx10FVRmozoGCIb3Oj6c2t+84QUxqTdknE7Cdcz5Wi1o0x2CWPZG4z1
vgTaCcJVhcMEhxn+7eK1NtDQEjs8Ojs7uaraVvooIe8R7jat0qs7Dmf8RO9P0I4M
MZlvijhI7aLw0C6vNsr1ebeppIiwO5aUuCGuKqxJGghHeqZv18ZcPayunyNrxMC6
uyX7y6nUVkfqx0m9gDsN112Iv9Dd/ZE5Gxivm8jZvVUGZgJD2szK7zbeCDeo5aU3
cRWfYaoN0QDxAKmo4bjciJzfMDDgvcIBq9lGS3FxEv394Mc5YX/ZdP+KRTiHcYCX
fBzr3B6HAgMBAAECggEAS5DGG6ssvRCt9e+ZatQYCl+HXt+voJAHJLMQPNG3zokV
hLXnMNL5mbh0zoKGTJfbQLvudS5KxR/BbykoxRFSzptFszH+gztEp6tIpuNXnCVz
odiMiejpwVptf763EU14hsKKbJJ0/j6H00EEWjEOB0Q6YB52sW0+qyf02U3SHlZN
k2PZYkpHi3YCONtOGj7jOdW7M3RfvcBNg9EW7fZc1KkiRAlscUAYLMkKcOLevil0
lUuF/JWj4iH22Oq6+JeSiecf6izF6lyIGvMXPry+woa8Iq0BBdmbZsK7r/Pa+wlz
+E6xHGn2rcyrnYB2pPc+RfHhYlodaOo69DxAYlRYaQKBgQDxnKySmlcfHe8lMqR4
2LvqMyGjNRo2+q9VZYej2mvr6+TGyd7Op/fRJ1t5f9DgtINomNQYSOtYAsPiEnl+
43z2N/Rdh6XSmOj4gLkDeiYNSpy86L/F39uCWZpkkqiy2zxYLWOs15MA0GWOtQGh
dz4cM0b/jyZOdHZR//L5WiMLawKBgQDSltEfQKqCEKJTqp4SU9BCHQmyheIjepY2
eKakgcsjpFjRBK2VrUalDLOQV74rtd7wp8F8kqqPJpRshb+oVuDCg6JB17UxYd34
iB+5cMdLRpg8f0HOqcYz4KOql2QhJQhFc3jzY7n1piPEhFO/MqFwmlUB4RdgJ3ix
HqX+F/T8VQKBgGos76l9KcwC25T9LEnu9KV20tFmBJ8kiuh8NZ9L3SFQCLlS/RbT
uZOwOAKsqJ4WtajBgHMrmECU9n/inoGkdsW80SZI9hYWHEsYRjXA9/ffUgGyRpQu
S8h8l9yalogC0AHv8F2EXpV8/yQ3ZwAN5r19yzWDMtJHW7etQplRgxUBAoGAGeOy
t+3iSHU1D6YlIsmtC8O4Int1LrluaCnzCrxuNeaJiMDTelhAHCBwnuk6lvMYAmwN
THxXfZvXmXPj+RUdMqyuMPwM6ZJHkLtjcw/bYHTAWIeolnimxk/yrxFHnQ+Jcchd
cUasYPfY49sE1Lerw0Ul+EIs9oRDwTqsW42kb7UCgYEA2y+oc7Fz2eq38hSbTfy7
OcATtny+xQ1+4IELtQIP7VctkMInJs57J+vS//IT41P0L2K1YjvL8RacnvG7yMvP
GnwHBcKgvL6zuoy11I3zPPYtbKGwcJoVGomPX7W0csfl4gdST3uugd9iCDEB8NsS
QmOYM/dk8x8aWpndBjRF5ig=
-----END PRIVATE KEY-----

View File

@ -1,16 +0,0 @@
[Testuser]
# These roles have to be defined in 'bffh.dhall'.
# Non-existant roles will not crash the server but print a `WARN` level message in the
# server log in the form "Did not find role somerole/internal while trying to tally".
roles = ["somerole", "testrole"]
# The password will be hashed using argon2id on load time and is not available in plaintext afterwards.
passwd = "secret"
# You can add whatever random data you want.
# It will get stored in the `kv` field in UserData.
# This is not used for anything at the moment
noot = "noot!"
# Store the card specific AES key in kv userdata
cardkey = "7ab8704a61b5317e1fe4cae9e3e1fd8d"

View File

@ -8,4 +8,4 @@ edition = "2021"
[dependencies] [dependencies]
sdk-proc = { path = "sdk_proc" } sdk-proc = { path = "sdk_proc" }
futures-util = "0.3" futures-util = "0.3"
diflouroborane = { path = "../.." } difluoroborane = { path = "../.." }

View File

@ -395,7 +395,7 @@ where
unsafe fn tick(ptr: *const ()) { unsafe fn tick(ptr: *const ()) {
let mut raw = Self::from_ptr(ptr); let mut raw = Self::from_ptr(ptr);
// Enter the span associated with the process to track execution time if enabled. // Enter the span associated with the process to track execution time if enabled.
let _guard = (&(*raw.pdata).span).enter(); let guard = (&(*raw.pdata).span).enter();
// Create a context from the raw proc pointer and the vtable inside its pdata. // Create a context from the raw proc pointer and the vtable inside its pdata.
let waker = ManuallyDrop::new(Waker::from_raw(RawWaker::new( let waker = ManuallyDrop::new(Waker::from_raw(RawWaker::new(
@ -487,6 +487,8 @@ where
(*raw.pdata).notify(); (*raw.pdata).notify();
} }
// the tracing guard is inside the proc, so it must be dropped first
drop(guard);
// Drop the proc reference. // Drop the proc reference.
Self::decrement(ptr); Self::decrement(ptr);
break; break;

2
rust-toolchain.toml Normal file
View File

@ -0,0 +1,2 @@
[toolchain]
channel = "1.66"

View File

@ -1,8 +0,0 @@
[UniqueUser]
roles = ["foorole", "barrole"]
[DuplicateUser]
roles = ["somerole"]
[DuplicateUser]
roles = ["different", "roles"]