Fundamentum client v0.5.0
This commit is contained in:
@@ -0,0 +1 @@
|
|||||||
|
target/
|
||||||
Generated
+2647
File diff suppressed because it is too large
Load Diff
+22
@@ -0,0 +1,22 @@
|
|||||||
|
[workspace]
|
||||||
|
resolver = "3"
|
||||||
|
members = ["crates/*"]
|
||||||
|
|
||||||
|
[workspace.package]
|
||||||
|
version = "0.5.0"
|
||||||
|
edition = "2024"
|
||||||
|
license = "Apache-2.0 OR MIT"
|
||||||
|
repository = "https://gitea.marek-novak.cz/mnovak/fundamentum-client"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[workspace.lints.rust]
|
||||||
|
unsafe_code = "forbid"
|
||||||
|
|
||||||
|
[workspace.dependencies]
|
||||||
|
ed25519-dalek = { version = "2.2", default-features = false, features = ["std", "zeroize", "fast"] }
|
||||||
|
sha2 = "0.10"
|
||||||
|
hkdf = "0.12"
|
||||||
|
bip39 = { version = "2", default-features = false, features = ["std"] }
|
||||||
|
zeroize = { version = "1.8", features = ["derive"] }
|
||||||
|
thiserror = "2"
|
||||||
|
data-encoding = "2"
|
||||||
+202
@@ -0,0 +1,202 @@
|
|||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 The Fundamentum Domi contributors
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Fundamentum Domi: the client crates
|
||||||
|
|
||||||
|
One identity and one relay for every Domi app. This repository holds the client side of Fundamentum 0.5.0
|
||||||
|
(tag `v0.5.0`), published so that public code (Fabrica's core, the apps) can depend on it:
|
||||||
|
|
||||||
|
| Crate | What |
|
||||||
|
| :-- | :-- |
|
||||||
|
| `tessera` | identity: root key from a mnemonic, subkey certificates, match code, hybrid logical clock, merge, revocation, backup |
|
||||||
|
| `envelope` | the signed event envelope (`TEV1`), strict decoding |
|
||||||
|
| `tabellarius-proto` | the Tabellarius wire protocol: mailbox ids, per-mailbox request signatures, limits |
|
||||||
|
| `custos-local` | Windows: the app side of Custos' local API (subkey seed, certificate request) |
|
||||||
|
| `tabellarius-client` | the Tabellarius client: OpenMLS groups, sealed invites, offline outbox, encrypted state |
|
||||||
|
|
||||||
|
The formats are in `docs/TESSERA.md` and `docs/TABELLARIUS.md`. Depend by tag:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
tessera = { git = "https://gitea.marek-novak.cz/mnovak/fundamentum-client.git", tag = "v0.5.0" }
|
||||||
|
```
|
||||||
|
|
||||||
|
This is a snapshot made at each release of the private Fundamentum repository, which also holds the relay
|
||||||
|
(AGPL-3.0) and the client's tests against it. Changes are made there, not here.
|
||||||
|
|
||||||
|
**Licence:** Apache-2.0 OR MIT (`LICENSE-APACHE`, `LICENSE-MIT`).
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
[package]
|
||||||
|
name = "tabellarius-client"
|
||||||
|
description = "Tabellarius client: MLS groups (OpenMLS) of Domi devices, signed event logs, offline-first sync (docs/TABELLARIUS.md)"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tessera = { path = "../tessera" }
|
||||||
|
envelope = { path = "../envelope" }
|
||||||
|
tabellarius-proto = { path = "../proto" }
|
||||||
|
openmls = "0.9"
|
||||||
|
openmls_rust_crypto = "0.6"
|
||||||
|
openmls_basic_credential = "0.6"
|
||||||
|
openmls_memory_storage = "0.6"
|
||||||
|
openmls_traits = "0.6"
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
chacha20poly1305 = "0.10"
|
||||||
|
sha2.workspace = true
|
||||||
|
zeroize.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
|
data-encoding.workspace = true
|
||||||
|
|
||||||
|
# The native driver only (docs/V1_1B.md §1); the browser talks through fetch.
|
||||||
|
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||||
|
ureq = "3"
|
||||||
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,161 @@
|
|||||||
|
//! The native driver (docs/V1_1B.md §1): [`Client`] is the [`Core`] over `ureq` and the app's [`Subkey`],
|
||||||
|
//! with the blocking API apps have used since v0.2. Neither the transport nor the signer ever waits, so each
|
||||||
|
//! operation completes the first time its future is polled: no executor, no thread.
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
AppEvent, Core, Device, GroupId, HttpRequest, HttpResponse, Result, StateStore, SyncReport, Transport,
|
||||||
|
VerifiedEvent,
|
||||||
|
};
|
||||||
|
use std::future::Future;
|
||||||
|
use std::ops::{Deref, DerefMut};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::task::{Context, Poll, Waker};
|
||||||
|
use std::time::Duration;
|
||||||
|
use tessera::{BackupSecret, Revocation, Subkey, SubkeyCert};
|
||||||
|
|
||||||
|
/// The blocking HTTP transport: no redirects, 15 s for a whole request.
|
||||||
|
pub struct Ureq(ureq::Agent);
|
||||||
|
|
||||||
|
impl Default for Ureq {
|
||||||
|
fn default() -> Self {
|
||||||
|
Ureq(
|
||||||
|
ureq::Agent::config_builder()
|
||||||
|
.max_redirects(0)
|
||||||
|
.http_status_as_error(false)
|
||||||
|
.timeout_global(Some(Duration::from_secs(15)))
|
||||||
|
.build()
|
||||||
|
.into(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Transport for Ureq {
|
||||||
|
async fn send(&self, req: HttpRequest) -> std::result::Result<HttpResponse, String> {
|
||||||
|
fn with<B>(mut r: ureq::RequestBuilder<B>, headers: &[(&'static str, String)]) -> ureq::RequestBuilder<B> {
|
||||||
|
for (n, v) in headers {
|
||||||
|
r = r.header(*n, v);
|
||||||
|
}
|
||||||
|
r
|
||||||
|
}
|
||||||
|
let resp = match req.method.as_str() {
|
||||||
|
"GET" => with(self.0.get(&req.url), &req.headers).call(),
|
||||||
|
"DELETE" => with(self.0.delete(&req.url), &req.headers).call(),
|
||||||
|
"PUT" => with(self.0.put(&req.url), &req.headers).send(&req.body[..]),
|
||||||
|
_ => with(self.0.post(&req.url), &req.headers).send(&req.body[..]),
|
||||||
|
};
|
||||||
|
let mut resp = resp.map_err(|e| e.to_string())?;
|
||||||
|
let status = resp.status().as_u16();
|
||||||
|
let body = resp.body_mut().read_to_vec().unwrap_or_default();
|
||||||
|
Ok(HttpResponse { status, body })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs a core operation over the native transport and signer: it is ready on the first poll.
|
||||||
|
fn now<F: Future>(f: F) -> F::Output {
|
||||||
|
let mut f = std::pin::pin!(f);
|
||||||
|
match f.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
|
||||||
|
Poll::Ready(v) => v,
|
||||||
|
// Unreachable: `Ureq` and `Subkey` never return Pending, and the core awaits nothing else.
|
||||||
|
Poll::Pending => unreachable!("a native operation waited"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn system_ms() -> u64 {
|
||||||
|
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The native client. Every operation that does not talk to the relay or sign (`groups`, `log`, `members`,
|
||||||
|
/// `import`, …) is the [`Core`]'s, reached through `Deref`.
|
||||||
|
pub struct Client(Core<Ureq, Subkey>);
|
||||||
|
|
||||||
|
impl Deref for Client {
|
||||||
|
type Target = Core<Ureq, Subkey>;
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DerefMut for Client {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
&mut self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Client {
|
||||||
|
/// Opens the client for `device`'s app, with its state from `store` (or empty).
|
||||||
|
pub fn open(relay: &str, device: Device, store: Box<dyn StateStore>) -> Result<Client> {
|
||||||
|
Core::open(relay, device.cert, device.subkey, Ureq::default(), store, Arc::new(system_ms)).map(Client)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The group of this person's own devices for this app; created on first use.
|
||||||
|
pub fn self_group(&mut self) -> Result<GroupId> {
|
||||||
|
now(self.0.self_group())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A new group shared with people you will invite.
|
||||||
|
pub fn open_group(&mut self, name: &str) -> Result<GroupId> {
|
||||||
|
now(self.0.open_group(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Signs `events`, applies them to the local log at once, and queues them for the group. Never needs the
|
||||||
|
/// relay.
|
||||||
|
pub fn send(&mut self, g: &GroupId, events: Vec<AppEvent>) -> Result<()> {
|
||||||
|
now(self.0.send(g, events))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An invite token (`tab1:…`). Needs the relay. See [`Core::invite`].
|
||||||
|
pub fn invite(&mut self, g: &GroupId) -> Result<String> {
|
||||||
|
now(self.0.invite(g))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asks to join with an invite token. Needs the relay. See [`Core::join`].
|
||||||
|
pub fn join(&mut self, token: &str) -> Result<()> {
|
||||||
|
now(self.0.join(token))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes a member. Needs the relay.
|
||||||
|
pub fn remove(&mut self, g: &GroupId, member: u32) -> Result<()> {
|
||||||
|
now(self.0.remove(g, member))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// See [`Core::apply_revocation`].
|
||||||
|
pub fn apply_revocation(&mut self, statements: &[Revocation]) -> Result<usize> {
|
||||||
|
now(self.0.apply_revocation(statements))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// See [`Core::announce_revocation`].
|
||||||
|
pub fn announce_revocation(&mut self, g: &GroupId, statements: Vec<Revocation>) -> Result<()> {
|
||||||
|
now(self.0.announce_revocation(g, statements))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// See [`Core::revoke`].
|
||||||
|
pub fn revoke(&mut self, g: &GroupId, statements: Vec<Revocation>) -> Result<usize> {
|
||||||
|
now(self.0.revoke(g, statements))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// See [`Core::renew`].
|
||||||
|
pub fn renew(&mut self, cert: SubkeyCert) -> Result<()> {
|
||||||
|
now(self.0.renew(cert))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// See [`Core::backup`].
|
||||||
|
pub fn backup(&mut self, secret: &BackupSecret) -> Result<bool> {
|
||||||
|
now(self.0.backup(secret))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// See [`Core::restore`].
|
||||||
|
pub fn restore(&self, secret: &BackupSecret) -> Result<Vec<Vec<u8>>> {
|
||||||
|
now(self.0.restore(secret))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Uploads what is queued, downloads and verifies what is new, admits invited devices, picks up groups this
|
||||||
|
/// device was admitted to. An unreachable relay is `relay_ok: false`, not an error.
|
||||||
|
pub fn sync(&mut self) -> Result<SyncReport> {
|
||||||
|
now(self.0.sync())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `sync`, then the group's log.
|
||||||
|
pub fn pull(&mut self, g: &GroupId) -> Result<Vec<VerifiedEvent>> {
|
||||||
|
now(self.0.pull(g))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
//! Where the client keeps its state (docs/TABELLARIUS.md §5). The state holds MLS secrets, so on disk it is
|
||||||
|
//! always encrypted, with a key the app keeps in Custos.
|
||||||
|
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
|
||||||
|
use std::io;
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
/// `Send`, so a [`crate::Client`] can live in a server task or a Tauri app's state.
|
||||||
|
pub trait StateStore: Send {
|
||||||
|
fn load(&self) -> io::Result<Option<Vec<u8>>>;
|
||||||
|
fn save(&self, state: &[u8]) -> io::Result<()>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// State in memory only: tests, and apps that persist it themselves.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct MemoryStore(Mutex<Option<Zeroizing<Vec<u8>>>>);
|
||||||
|
|
||||||
|
impl MemoryStore {
|
||||||
|
pub fn with(state: Vec<u8>) -> MemoryStore {
|
||||||
|
MemoryStore(Mutex::new(Some(Zeroizing::new(state))))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StateStore for MemoryStore {
|
||||||
|
fn load(&self) -> io::Result<Option<Vec<u8>>> {
|
||||||
|
Ok(self.0.lock().map_err(|_| io::Error::other("lock"))?.as_ref().map(|s| s.to_vec()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(&self, state: &[u8]) -> io::Result<()> {
|
||||||
|
*self.0.lock().map_err(|_| io::Error::other("lock"))? = Some(Zeroizing::new(state.to_vec()));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
const MAGIC: &[u8; 4] = b"TSF1";
|
||||||
|
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
/// State in a file: `TSF1 ‖ nonce (24) ‖ XChaCha20-Poly1305(key, nonce, state, aad = TSF1)`, written to a temporary
|
||||||
|
/// file and renamed. The key comes from Custos (`domi://<app>/tabellarius-state`), never from a file.
|
||||||
|
pub struct EncryptedFileStore {
|
||||||
|
path: PathBuf,
|
||||||
|
key: Zeroizing<[u8; 32]>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
impl EncryptedFileStore {
|
||||||
|
pub fn new(path: impl Into<PathBuf>, key: [u8; 32]) -> EncryptedFileStore {
|
||||||
|
EncryptedFileStore { path: path.into(), key: Zeroizing::new(key) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cipher(&self) -> XChaCha20Poly1305 {
|
||||||
|
XChaCha20Poly1305::new_from_slice(self.key.as_ref()).expect("32-byte key")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
impl StateStore for EncryptedFileStore {
|
||||||
|
fn load(&self) -> io::Result<Option<Vec<u8>>> {
|
||||||
|
let bytes = match std::fs::read(&self.path) {
|
||||||
|
Ok(b) => b,
|
||||||
|
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
};
|
||||||
|
if bytes.len() < 4 + 24 || &bytes[..4] != MAGIC {
|
||||||
|
return Err(io::Error::other("not a Tabellarius state file"));
|
||||||
|
}
|
||||||
|
let nonce = XNonce::from_slice(&bytes[4..28]);
|
||||||
|
let plain = self
|
||||||
|
.cipher()
|
||||||
|
.decrypt(nonce, Payload { msg: &bytes[28..], aad: MAGIC })
|
||||||
|
.map_err(|_| io::Error::other("the state file does not open with this key (wrong key or damaged)"))?;
|
||||||
|
Ok(Some(plain))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(&self, state: &[u8]) -> io::Result<()> {
|
||||||
|
let nonce_bytes = tabellarius_proto::random32();
|
||||||
|
let nonce = XNonce::from_slice(&nonce_bytes[..24]);
|
||||||
|
let ct = self
|
||||||
|
.cipher()
|
||||||
|
.encrypt(nonce, Payload { msg: state, aad: MAGIC })
|
||||||
|
.map_err(|_| io::Error::other("encryption"))?;
|
||||||
|
let mut out = MAGIC.to_vec();
|
||||||
|
out.extend_from_slice(&nonce_bytes[..24]);
|
||||||
|
out.extend_from_slice(&ct);
|
||||||
|
let tmp = self.path.with_extension("tmp");
|
||||||
|
std::fs::write(&tmp, &out)?;
|
||||||
|
std::fs::rename(&tmp, &self.path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_file_is_ciphertext_and_opens_only_with_its_key() {
|
||||||
|
let dir =
|
||||||
|
std::env::temp_dir().join(format!("tsf-{}", tabellarius_proto::b64(&tabellarius_proto::random32()[..6])));
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
let path = dir.join("state.tsf");
|
||||||
|
let s = EncryptedFileStore::new(&path, [7; 32]);
|
||||||
|
assert_eq!(s.load().unwrap(), None);
|
||||||
|
s.save(b"MARKER-SECRET-STATE").unwrap();
|
||||||
|
let raw = std::fs::read(&path).unwrap();
|
||||||
|
assert!(!raw.windows(6).any(|w| w == b"MARKER"));
|
||||||
|
assert_eq!(s.load().unwrap().unwrap(), b"MARKER-SECRET-STATE");
|
||||||
|
assert!(EncryptedFileStore::new(&path, [8; 32]).load().is_err());
|
||||||
|
std::fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
//! What the core needs from its surroundings (docs/V1_1B.md §1, §2): a way to reach the relay and the device
|
||||||
|
//! key. The native driver implements both without ever waiting; the browser's wait on `fetch` and WebCrypto.
|
||||||
|
|
||||||
|
use std::future::Future;
|
||||||
|
use tessera::{PublicKey, Signature, Subkey};
|
||||||
|
|
||||||
|
/// One HTTP request to the relay, already signed with a mailbox key.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct HttpRequest {
|
||||||
|
pub method: String,
|
||||||
|
pub url: String,
|
||||||
|
pub headers: Vec<(&'static str, String)>,
|
||||||
|
pub body: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The relay's answer: any status, and the body.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct HttpResponse {
|
||||||
|
pub status: u16,
|
||||||
|
pub body: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reaches the relay. `Err` only when it could not be reached (offline); every HTTP status is an `Ok` answer.
|
||||||
|
/// No redirects are followed.
|
||||||
|
pub trait Transport {
|
||||||
|
fn send(&self, req: HttpRequest) -> impl Future<Output = Result<HttpResponse, String>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The device key: the app subkey its cert certifies. The domains are prepended here, never by the caller,
|
||||||
|
/// so a signer cannot be asked to sign one kind of statement as another.
|
||||||
|
pub trait DeviceSigner {
|
||||||
|
fn public(&self) -> PublicKey;
|
||||||
|
/// A signature over `tessera::EVENT_DOMAIN ‖ tbs`.
|
||||||
|
fn sign_event_tbs(&self, tbs: &[u8]) -> impl Future<Output = Result<Signature, String>>;
|
||||||
|
/// A signature over `tessera::CREDENTIAL_DOMAIN ‖ tbs`.
|
||||||
|
fn sign_credential_tbs(&self, tbs: &[u8]) -> impl Future<Output = Result<Signature, String>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DeviceSigner for Subkey {
|
||||||
|
fn public(&self) -> PublicKey {
|
||||||
|
Subkey::public(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn sign_event_tbs(&self, tbs: &[u8]) -> Result<Signature, String> {
|
||||||
|
Ok(Subkey::sign_event_tbs(self, tbs))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn sign_credential_tbs(&self, tbs: &[u8]) -> Result<Signature, String> {
|
||||||
|
Ok(Subkey::sign_credential_tbs(self, tbs))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
[package]
|
||||||
|
name = "custos-local"
|
||||||
|
description = "The app side of Custos' local API on Windows: keep a subkey seed in Custos and ask Custos to certify the subkey (docs/TESSERA.md §10)"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tessera = { path = "../tessera" }
|
||||||
|
serde_json = "1"
|
||||||
|
getrandom = "0.3"
|
||||||
|
sha2.workspace = true
|
||||||
|
data-encoding.workspace = true
|
||||||
|
zeroize.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
//! Asks the running Custos for a subkey cert, as a Domi app would.
|
||||||
|
//!
|
||||||
|
//! `cargo run -p custos-local --example request_subkey -- <app_id> [purpose] [app name]`
|
||||||
|
|
||||||
|
use tessera::{Id, match_code};
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let app_id = Id::new(args.first().map(String::as_str).unwrap_or("demo")).expect("an app id: a-z, 0-9, '-'");
|
||||||
|
let purpose = Id::new(args.get(1).map(String::as_str).unwrap_or("sync")).expect("a purpose: a-z, 0-9, '-'");
|
||||||
|
let app = args.get(2).cloned().unwrap_or_else(|| format!("{app_id} (request_subkey example)"));
|
||||||
|
|
||||||
|
let run = || -> Result<(), custos_local::LocalError> {
|
||||||
|
let mut custos = custos_local::Custos::connect()?;
|
||||||
|
let subkey = custos.subkey(&app, &app_id)?;
|
||||||
|
println!("subkey {}", subkey.public());
|
||||||
|
println!("match {} <- Custos shows the same code", match_code(&subkey.public()));
|
||||||
|
let cert = custos.request_cert(&app, &app_id, &purpose, &subkey)?;
|
||||||
|
println!("root {}", cert.root());
|
||||||
|
println!("app {} / {}", cert.app_id(), cert.purpose());
|
||||||
|
println!("valid {} .. {} (Unix seconds)", cert.not_before(), cert.not_after());
|
||||||
|
println!("cert {}", cert.to_text());
|
||||||
|
Ok(())
|
||||||
|
};
|
||||||
|
if let Err(e) = run() {
|
||||||
|
eprintln!("error: {e}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,319 @@
|
|||||||
|
//! The app side of Custos' local API (docs/TESSERA.md §10): a Domi app on the same Windows machine keeps its
|
||||||
|
//! subkey seed in Custos and asks Custos to certify the subkey with the person's root.
|
||||||
|
//!
|
||||||
|
//! ```no_run
|
||||||
|
//! # use tessera::Id;
|
||||||
|
//! let mut custos = custos_local::Custos::connect().unwrap();
|
||||||
|
//! let app_id = Id::new("fiscus").unwrap();
|
||||||
|
//! let subkey = custos.subkey("Fiscus Domi", &app_id).unwrap();
|
||||||
|
//! println!("Custos will show {}", tessera::match_code(&subkey.public()));
|
||||||
|
//! let cert = custos.request_cert("Fiscus Domi", &app_id, &Id::new("sync").unwrap(), &subkey).unwrap();
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! The seed lives in Custos under `domi://<app_id>/tessera-subkey`; the root never leaves Custos, and no
|
||||||
|
//! answer contains private key material other than the app's own secrets, in its own namespace: the subkey
|
||||||
|
//! seed, the state keys and the backup secret.
|
||||||
|
//!
|
||||||
|
//! v1.1 (docs/TESSERA.md §12): on every sync an app applies the revocations the person started in Custos and
|
||||||
|
//! backs up its self group:
|
||||||
|
//!
|
||||||
|
//! ```ignore
|
||||||
|
//! for statements in custos.revocations_to_apply("Fiscus Domi", &app_id, |k| client.events_by_all(k))? {
|
||||||
|
//! client.apply_revocation(&statements)?;
|
||||||
|
//! }
|
||||||
|
//! client.backup(&custos.backup_secret("Fiscus Domi", &app_id)?)?;
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
use data_encoding::BASE64URL_NOPAD;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use sha2::Digest;
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
use tessera::{BackupSecret, Id, PublicKey, Revocation, Subkey, SubkeyCert};
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
/// The pipe Custos listens on; `CUSTOS_PIPE` overrides it (tests, a second Custos).
|
||||||
|
pub const PIPE: &str = r"\\.\pipe\custos-domi";
|
||||||
|
const SEED_NAME: &str = "tessera-subkey";
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum LocalError {
|
||||||
|
#[error("Custos is not running (or this is not Windows): {0}")]
|
||||||
|
NotRunning(std::io::Error),
|
||||||
|
#[error("talking to Custos failed: {0}")]
|
||||||
|
Io(std::io::Error),
|
||||||
|
#[error("Custos refused: {error} ({message})")]
|
||||||
|
Refused { error: String, message: String },
|
||||||
|
#[error("Custos sent an answer this app does not understand")]
|
||||||
|
BadAnswer,
|
||||||
|
#[error("the certificate Custos sent does not match the request: {0}")]
|
||||||
|
WrongCert(&'static str),
|
||||||
|
#[error("no random numbers from the OS")]
|
||||||
|
Random,
|
||||||
|
#[error("the revocation Custos sent does not match the request")]
|
||||||
|
WrongRevocation,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A revocation the person started in Custos (Domi identity → a key → Revoke).
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct PendingRevocation {
|
||||||
|
pub subkey: PublicKey,
|
||||||
|
/// Unix seconds, as Custos chose it.
|
||||||
|
pub revoked_at: u64,
|
||||||
|
/// `None` until a device of this app sent the list of events to keep.
|
||||||
|
pub statements: Option<Vec<Revocation>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A connection to Custos.
|
||||||
|
pub struct Custos {
|
||||||
|
pipe: std::fs::File,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Custos {
|
||||||
|
pub fn connect() -> Result<Custos, LocalError> {
|
||||||
|
let name = std::env::var("CUSTOS_PIPE").unwrap_or_else(|_| PIPE.to_owned());
|
||||||
|
let pipe = std::fs::OpenOptions::new().read(true).write(true).open(name).map_err(LocalError::NotRunning)?;
|
||||||
|
Ok(Custos { pipe })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One request, one answer. Answers with `"ok": false` become [`LocalError::Refused`].
|
||||||
|
fn call(&mut self, req: &Value) -> Result<Value, LocalError> {
|
||||||
|
let out = Zeroizing::new(serde_json::to_vec(req).map_err(|_| LocalError::BadAnswer)?);
|
||||||
|
self.pipe.write_all(&out).map_err(LocalError::Io)?;
|
||||||
|
let mut buf = Zeroizing::new(Vec::new());
|
||||||
|
let mut chunk = Zeroizing::new(vec![0u8; 64 * 1024]);
|
||||||
|
let v: Value = loop {
|
||||||
|
let n = self.pipe.read(&mut chunk).map_err(LocalError::Io)?;
|
||||||
|
if n == 0 {
|
||||||
|
return Err(LocalError::BadAnswer);
|
||||||
|
}
|
||||||
|
buf.extend_from_slice(&chunk[..n]);
|
||||||
|
match serde_json::from_slice(&buf) {
|
||||||
|
Ok(v) => break v,
|
||||||
|
Err(e) if e.is_eof() => continue,
|
||||||
|
Err(_) => return Err(LocalError::BadAnswer),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if v["ok"] == true {
|
||||||
|
return Ok(v);
|
||||||
|
}
|
||||||
|
Err(LocalError::Refused {
|
||||||
|
error: v["error"].as_str().unwrap_or("unknown").to_owned(),
|
||||||
|
message: v["message"].as_str().unwrap_or("").to_owned(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This app's subkey: the seed kept in Custos, or a new one from the OS CSPRNG stored there first.
|
||||||
|
/// Custos asks the person once whether `app` may use the namespace `app_id`.
|
||||||
|
pub fn subkey(&mut self, app: &str, app_id: &Id) -> Result<Subkey, LocalError> {
|
||||||
|
let seed = self.random_secret(app, &format!("domi://{app_id}/{SEED_NAME}"), "Domi subkey")?;
|
||||||
|
Ok(Subkey::from_seed(&seed))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The key that encrypts this app's Tabellarius state file at `state_path` (one per file), kept in Custos.
|
||||||
|
pub fn state_key(&mut self, app: &str, app_id: &Id, state_path: &str) -> Result<Zeroizing<[u8; 32]>, LocalError> {
|
||||||
|
let id: String =
|
||||||
|
sha2::Sha256::digest(state_path.as_bytes()).iter().take(6).map(|b| format!("{b:02x}")).collect();
|
||||||
|
self.random_secret(app, &format!("domi://{app_id}/tabellarius-state-{id}"), "Tabellarius state key")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 32 bytes kept in Custos under `r`: read, or made from the OS CSPRNG and stored first.
|
||||||
|
fn random_secret(&mut self, app: &str, r: &str, what: &str) -> Result<Zeroizing<[u8; 32]>, LocalError> {
|
||||||
|
match self.call(&json!({ "op": "get", "ref": r, "app": app })) {
|
||||||
|
Ok(v) => {
|
||||||
|
let text = Zeroizing::new(v["value"].as_str().ok_or(LocalError::BadAnswer)?.to_owned());
|
||||||
|
let seed = Zeroizing::new(BASE64URL_NOPAD.decode(text.as_bytes()).map_err(|_| LocalError::BadAnswer)?);
|
||||||
|
Ok(Zeroizing::new(seed.as_slice().try_into().map_err(|_| LocalError::BadAnswer)?))
|
||||||
|
}
|
||||||
|
Err(LocalError::Refused { error, .. }) if error == "not_found" => {
|
||||||
|
let mut seed = Zeroizing::new([0u8; 32]);
|
||||||
|
getrandom::fill(seed.as_mut()).map_err(|_| LocalError::Random)?;
|
||||||
|
let text = Zeroizing::new(BASE64URL_NOPAD.encode(seed.as_ref()));
|
||||||
|
let label = format!("{app}: {what}");
|
||||||
|
self.call(&json!({ "op": "set", "ref": r, "value": text.as_str(), "label": label, "app": app }))?;
|
||||||
|
Ok(seed)
|
||||||
|
}
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asks Custos to certify `subkey` for `app_id` and `purpose`. Custos shows the subkey's match code
|
||||||
|
/// (`tessera::match_code`); show the same code in the app while this waits. Blocks until the person
|
||||||
|
/// answers. The cert is checked before it is returned.
|
||||||
|
pub fn request_cert(
|
||||||
|
&mut self,
|
||||||
|
app: &str,
|
||||||
|
app_id: &Id,
|
||||||
|
purpose: &Id,
|
||||||
|
subkey: &Subkey,
|
||||||
|
) -> Result<SubkeyCert, LocalError> {
|
||||||
|
self.request_cert_for(app, app_id, purpose, &subkey.public())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Custos::request_cert`] for a key this app does not hold: another device of the same person (an app's
|
||||||
|
/// server-side device, paired through this desktop). Custos shows the key's match code; the other device
|
||||||
|
/// shows the same code, so the person approves only the key they see there.
|
||||||
|
pub fn request_cert_for(
|
||||||
|
&mut self,
|
||||||
|
app: &str,
|
||||||
|
app_id: &Id,
|
||||||
|
purpose: &Id,
|
||||||
|
key: &PublicKey,
|
||||||
|
) -> Result<SubkeyCert, LocalError> {
|
||||||
|
let v = self.call(&json!({
|
||||||
|
"op": "subkey",
|
||||||
|
"app": app,
|
||||||
|
"app_id": app_id.as_str(),
|
||||||
|
"purpose": purpose.as_str(),
|
||||||
|
"subkey": key.to_string(),
|
||||||
|
}))?;
|
||||||
|
let cert = SubkeyCert::from_text(v["cert"].as_str().ok_or(LocalError::BadAnswer)?)
|
||||||
|
.map_err(|_| LocalError::BadAnswer)?;
|
||||||
|
check(&cert, app_id, purpose, key, now())?;
|
||||||
|
Ok(cert)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Custos {
|
||||||
|
/// The revocations the person started for this app's subkeys and for device keys.
|
||||||
|
pub fn revocations(&mut self, app: &str, app_id: &Id) -> Result<Vec<PendingRevocation>, LocalError> {
|
||||||
|
let v = self.call(&json!({ "op": "revocations", "app": app, "app_id": app_id.as_str() }))?;
|
||||||
|
let list = v["revocations"].as_array().ok_or(LocalError::BadAnswer)?;
|
||||||
|
list.iter()
|
||||||
|
.map(|r| {
|
||||||
|
let subkey = r["subkey"].as_str().and_then(PublicKey::from_text).ok_or(LocalError::BadAnswer)?;
|
||||||
|
let revoked_at = r["revoked_at"].as_u64().ok_or(LocalError::BadAnswer)?;
|
||||||
|
let statements = match &r["statements"] {
|
||||||
|
Value::Null => None,
|
||||||
|
s => Some(statements(s, &subkey, revoked_at)?),
|
||||||
|
};
|
||||||
|
Ok(PendingRevocation { subkey, revoked_at, statements })
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends the hashes of the events `pending`'s key wrote that stay valid (`Client::events_by_all`); Custos
|
||||||
|
/// signs the revocation with the root. If another device of this app answered first, Custos returns
|
||||||
|
/// what it signed then.
|
||||||
|
pub fn revoke(
|
||||||
|
&mut self,
|
||||||
|
app: &str,
|
||||||
|
app_id: &Id,
|
||||||
|
pending: &PendingRevocation,
|
||||||
|
accepted: &[[u8; 32]],
|
||||||
|
) -> Result<Vec<Revocation>, LocalError> {
|
||||||
|
let v = self.call(&json!({
|
||||||
|
"op": "revoke",
|
||||||
|
"app": app,
|
||||||
|
"app_id": app_id.as_str(),
|
||||||
|
"subkey": pending.subkey.to_string(),
|
||||||
|
"revoked_at": pending.revoked_at,
|
||||||
|
"accepted": BASE64URL_NOPAD.encode(&accepted.concat()),
|
||||||
|
}))?;
|
||||||
|
statements(&v["statements"], &pending.subkey, pending.revoked_at)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every revocation this app has to apply, signed: answers the ones still waiting with `accepted_of`
|
||||||
|
/// (`|k| client.events_by_all(k)`). Hand each to `Client::apply_revocation`.
|
||||||
|
pub fn revocations_to_apply(
|
||||||
|
&mut self,
|
||||||
|
app: &str,
|
||||||
|
app_id: &Id,
|
||||||
|
accepted_of: impl Fn(&PublicKey) -> Vec<[u8; 32]>,
|
||||||
|
) -> Result<Vec<Vec<Revocation>>, LocalError> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for p in self.revocations(app, app_id)? {
|
||||||
|
out.push(match &p.statements {
|
||||||
|
Some(s) => s.clone(),
|
||||||
|
None => self.revoke(app, app_id, &p, &accepted_of(&p.subkey))?,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This app's backup secret (docs/TESSERA.md §12), derived by Custos from the root. Nothing reads it back
|
||||||
|
/// out of [`BackupSecret`].
|
||||||
|
pub fn backup_secret(&mut self, app: &str, app_id: &Id) -> Result<BackupSecret, LocalError> {
|
||||||
|
let v = self.call(&json!({ "op": "backup_key", "app": app, "app_id": app_id.as_str() }))?;
|
||||||
|
let text = Zeroizing::new(v["secret"].as_str().ok_or(LocalError::BadAnswer)?.to_owned());
|
||||||
|
let bytes = Zeroizing::new(BASE64URL_NOPAD.decode(text.as_bytes()).map_err(|_| LocalError::BadAnswer)?);
|
||||||
|
let secret: [u8; 32] = bytes.as_slice().try_into().map_err(|_| LocalError::BadAnswer)?;
|
||||||
|
Ok(BackupSecret::from_bytes(secret))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Signed statements from an answer: one root, the asked-for key and time, each signature valid.
|
||||||
|
fn statements(v: &Value, subkey: &PublicKey, revoked_at: u64) -> Result<Vec<Revocation>, LocalError> {
|
||||||
|
let list: Vec<Revocation> = v
|
||||||
|
.as_array()
|
||||||
|
.ok_or(LocalError::BadAnswer)?
|
||||||
|
.iter()
|
||||||
|
.map(|t| t.as_str().and_then(|t| Revocation::from_text(t).ok()).ok_or(LocalError::BadAnswer))
|
||||||
|
.collect::<Result<_, _>>()?;
|
||||||
|
let root = list.first().ok_or(LocalError::WrongRevocation)?.root();
|
||||||
|
let ok = list
|
||||||
|
.iter()
|
||||||
|
.all(|r| r.root() == root && r.subkey() == *subkey && r.revoked_at() == revoked_at && r.verify(&root).is_ok());
|
||||||
|
if !ok {
|
||||||
|
return Err(LocalError::WrongRevocation);
|
||||||
|
}
|
||||||
|
Ok(list)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now() -> u64 {
|
||||||
|
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `cert` is what was asked for, and valid now under the root it names.
|
||||||
|
fn check(cert: &SubkeyCert, app_id: &Id, purpose: &Id, key: &PublicKey, now: u64) -> Result<(), LocalError> {
|
||||||
|
if cert.subkey() != *key {
|
||||||
|
return Err(LocalError::WrongCert("another subkey"));
|
||||||
|
}
|
||||||
|
if cert.app_id() != app_id || cert.purpose() != purpose {
|
||||||
|
return Err(LocalError::WrongCert("another app id or purpose"));
|
||||||
|
}
|
||||||
|
cert.verify(&cert.root(), now).map_err(|_| LocalError::WrongCert("not valid now"))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use tessera::{CertRequest, RootKey, certify};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cert_is_checked_against_the_request() {
|
||||||
|
let root = RootKey::from_mnemonic(
|
||||||
|
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
|
||||||
|
abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
let (fiscus, sync) = (Id::new("fiscus").unwrap(), Id::new("sync").unwrap());
|
||||||
|
let cert = certify(&root, &CertRequest::standard(sub.public(), fiscus.clone(), sync.clone(), 1000)).unwrap();
|
||||||
|
let key = sub.public();
|
||||||
|
assert!(check(&cert, &fiscus, &sync, &key, 1000).is_ok());
|
||||||
|
assert!(check(&cert, &Id::new("calenda").unwrap(), &sync, &key, 1000).is_err());
|
||||||
|
assert!(check(&cert, &fiscus, &sync, &Subkey::from_seed(&[2; 32]).public(), 1000).is_err());
|
||||||
|
assert!(check(&cert, &fiscus, &sync, &key, 1000 + 366 * 86_400).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn statements_are_checked_against_the_request() {
|
||||||
|
let root = RootKey::from_mnemonic(
|
||||||
|
"abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let lost = Subkey::from_seed(&[1; 32]).public();
|
||||||
|
let signed = tessera::revoke(&root, lost, 1000, vec![[7; 32]]).unwrap();
|
||||||
|
let answer = json!(signed.iter().map(|r| r.to_text()).collect::<Vec<_>>());
|
||||||
|
assert_eq!(statements(&answer, &lost, 1000).unwrap(), signed);
|
||||||
|
assert!(matches!(statements(&answer, &lost, 999), Err(LocalError::WrongRevocation)));
|
||||||
|
let other = Subkey::from_seed(&[2; 32]).public();
|
||||||
|
assert!(matches!(statements(&answer, &other, 1000), Err(LocalError::WrongRevocation)));
|
||||||
|
assert!(matches!(statements(&json!([]), &lost, 1000), Err(LocalError::WrongRevocation)));
|
||||||
|
let mut forged = signed[0].to_bytes();
|
||||||
|
let n = forged.len();
|
||||||
|
forged[n - 1] ^= 1;
|
||||||
|
let forged = json!([data_encoding::BASE64URL_NOPAD.encode(&forged)]);
|
||||||
|
assert!(matches!(statements(&forged, &lost, 1000), Err(LocalError::WrongRevocation)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
[package]
|
||||||
|
name = "envelope"
|
||||||
|
description = "The signed Domi event envelope (TEV1): strict decoding, verification against trusted roots (docs/TESSERA.md §8)"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tessera = { path = "../tessera" }
|
||||||
|
thiserror.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
proptest = "1"
|
||||||
@@ -0,0 +1,296 @@
|
|||||||
|
//! The Domi event envelope, `TEV1` (docs/TESSERA.md §8).
|
||||||
|
//!
|
||||||
|
//! Decoding is strict and total: it returns a whole [`Envelope`] or a [`DecodeError`] that says why, never
|
||||||
|
//! a panic and never part of an event. Encoding is canonical, so `decode(b).as_bytes() == b`. A decoded
|
||||||
|
//! envelope is not trusted until [`Envelope::verify`] passes.
|
||||||
|
|
||||||
|
use std::fmt;
|
||||||
|
use tessera::{CertError, Hlc, Id, LogEvent, OrderKey, PublicKey, Signature, Subkey, SubkeyCert, verify_event_sig};
|
||||||
|
|
||||||
|
pub const MAGIC: &[u8; 4] = b"TEV1";
|
||||||
|
/// The largest payload (MLS ciphertext) one event may carry.
|
||||||
|
pub const MAX_PAYLOAD: usize = 256 * 1024;
|
||||||
|
/// The largest envelope: the payload plus room for every other field.
|
||||||
|
pub const MAX_ENVELOPE: usize = MAX_PAYLOAD + 1024;
|
||||||
|
|
||||||
|
const CERT_MIN: usize = 4 + 32 + 32 + 2 + 2 + 8 + 8 + 64;
|
||||||
|
const CERT_MAX: usize = CERT_MIN + 2 * 31;
|
||||||
|
|
||||||
|
/// The fields in their only allowed order: (tag, name, smallest and largest length).
|
||||||
|
const FIELDS: [(u8, &str, usize, usize); 7] = [
|
||||||
|
(1, "app", 1, 32),
|
||||||
|
(2, "schema", 4, 4),
|
||||||
|
(3, "hlc", 12, 12),
|
||||||
|
(4, "author", 32, 32),
|
||||||
|
(5, "cert", CERT_MIN, CERT_MAX),
|
||||||
|
(6, "payload", 0, MAX_PAYLOAD),
|
||||||
|
(7, "sig", 64, 64),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// One signed event.
|
||||||
|
#[derive(Clone, PartialEq, Eq)]
|
||||||
|
pub struct Envelope {
|
||||||
|
app: Id,
|
||||||
|
schema: u32,
|
||||||
|
hlc: Hlc,
|
||||||
|
author: PublicKey,
|
||||||
|
cert: SubkeyCert,
|
||||||
|
payload: Vec<u8>,
|
||||||
|
sig: Signature,
|
||||||
|
/// The canonical encoding; the signature covers `bytes[..sig_at]`.
|
||||||
|
bytes: Vec<u8>,
|
||||||
|
sig_at: usize,
|
||||||
|
hash: [u8; 32],
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum DecodeError {
|
||||||
|
#[error("the envelope is {0} bytes, more than the limit")]
|
||||||
|
TooLarge(usize),
|
||||||
|
#[error("too short to be an envelope")]
|
||||||
|
TooShort,
|
||||||
|
#[error("not a TEV1 envelope")]
|
||||||
|
BadMagic,
|
||||||
|
#[error("unknown field {0}")]
|
||||||
|
UnknownField(u8),
|
||||||
|
#[error("field {found} where field {expected} must be")]
|
||||||
|
FieldOutOfOrder { expected: u8, found: u8 },
|
||||||
|
#[error("the envelope ends inside field {field}")]
|
||||||
|
Truncated { field: &'static str },
|
||||||
|
#[error("field {field} has a wrong length ({len})")]
|
||||||
|
BadLength { field: &'static str, len: u64 },
|
||||||
|
#[error("field {field} is invalid: {reason}")]
|
||||||
|
Invalid { field: &'static str, reason: &'static str },
|
||||||
|
#[error("bytes after the last field")]
|
||||||
|
TrailingBytes,
|
||||||
|
#[error("the certificate does not decode: {0}")]
|
||||||
|
Cert(CertError),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum SealError {
|
||||||
|
#[error("the certificate is for another key than the one signing")]
|
||||||
|
CertForAnotherKey,
|
||||||
|
#[error("the payload is larger than {MAX_PAYLOAD} bytes")]
|
||||||
|
PayloadTooLarge,
|
||||||
|
#[error("the bytes are not the to-be-signed part of an envelope")]
|
||||||
|
NotToBeSigned,
|
||||||
|
#[error("the signature does not verify for the author")]
|
||||||
|
BadSignature,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum VerifyError {
|
||||||
|
#[error("the author is not the key the certificate certifies")]
|
||||||
|
AuthorNotCert,
|
||||||
|
#[error("the certificate is for another app")]
|
||||||
|
WrongApp,
|
||||||
|
#[error("the certificate's identity is not a member of this group")]
|
||||||
|
UnknownRoot,
|
||||||
|
#[error("the certificate was not valid at the event's time: {0}")]
|
||||||
|
Cert(CertError),
|
||||||
|
#[error("the event's clock is too far in the future")]
|
||||||
|
FromTheFuture,
|
||||||
|
#[error("the event's signature is not valid")]
|
||||||
|
BadSignature,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn put(out: &mut Vec<u8>, tag: u8, value: &[u8]) {
|
||||||
|
out.push(tag);
|
||||||
|
out.extend_from_slice(&(value.len() as u32).to_be_bytes());
|
||||||
|
out.extend_from_slice(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Envelope {
|
||||||
|
/// Signs an event with `subkey`, whose cert is `cert`. The app is the cert's app.
|
||||||
|
pub fn seal(
|
||||||
|
subkey: &Subkey,
|
||||||
|
cert: &SubkeyCert,
|
||||||
|
schema: u32,
|
||||||
|
hlc: Hlc,
|
||||||
|
payload: &[u8],
|
||||||
|
) -> Result<Envelope, SealError> {
|
||||||
|
let tbs = Envelope::to_be_signed(&subkey.public(), cert, schema, hlc, payload)?;
|
||||||
|
let sig = subkey.sign_event_tbs(&tbs);
|
||||||
|
Envelope::with_signature(tbs, sig)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bytes `author` signs (after `EVENT_DOMAIN`), for a signer that cannot sign at once (a WebCrypto
|
||||||
|
/// key in the browser, docs/V1_1B.md §2). Finish with [`Envelope::with_signature`].
|
||||||
|
pub fn to_be_signed(
|
||||||
|
author: &PublicKey,
|
||||||
|
cert: &SubkeyCert,
|
||||||
|
schema: u32,
|
||||||
|
hlc: Hlc,
|
||||||
|
payload: &[u8],
|
||||||
|
) -> Result<Vec<u8>, SealError> {
|
||||||
|
if cert.subkey() != *author {
|
||||||
|
return Err(SealError::CertForAnotherKey);
|
||||||
|
}
|
||||||
|
if payload.len() > MAX_PAYLOAD {
|
||||||
|
return Err(SealError::PayloadTooLarge);
|
||||||
|
}
|
||||||
|
let mut bytes = MAGIC.to_vec();
|
||||||
|
put(&mut bytes, 1, cert.app_id().as_str().as_bytes());
|
||||||
|
put(&mut bytes, 2, &schema.to_be_bytes());
|
||||||
|
put(&mut bytes, 3, &hlc.to_bytes());
|
||||||
|
put(&mut bytes, 4, author.as_bytes());
|
||||||
|
put(&mut bytes, 5, &cert.to_bytes());
|
||||||
|
put(&mut bytes, 6, payload);
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finishes an envelope from [`Envelope::to_be_signed`]'s bytes and the author's signature over them.
|
||||||
|
/// Refuses a signature that does not verify, so a broken signer cannot make an event others would drop.
|
||||||
|
pub fn with_signature(tbs: Vec<u8>, sig: Signature) -> Result<Envelope, SealError> {
|
||||||
|
let mut bytes = tbs;
|
||||||
|
let sig_at = bytes.len();
|
||||||
|
put(&mut bytes, 7, sig.as_bytes());
|
||||||
|
let e = Envelope::decode(&bytes).map_err(|_| SealError::NotToBeSigned)?;
|
||||||
|
if e.sig_at != sig_at || !verify_event_sig(&e.author, &e.bytes[..sig_at], &sig) {
|
||||||
|
return Err(SealError::BadSignature);
|
||||||
|
}
|
||||||
|
Ok(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decodes untrusted bytes. All or nothing.
|
||||||
|
pub fn decode(b: &[u8]) -> Result<Envelope, DecodeError> {
|
||||||
|
if b.len() > MAX_ENVELOPE {
|
||||||
|
return Err(DecodeError::TooLarge(b.len()));
|
||||||
|
}
|
||||||
|
if b.len() < MAGIC.len() {
|
||||||
|
return Err(DecodeError::TooShort);
|
||||||
|
}
|
||||||
|
if &b[..4] != MAGIC {
|
||||||
|
return Err(DecodeError::BadMagic);
|
||||||
|
}
|
||||||
|
let mut pos = 4;
|
||||||
|
let mut values: [&[u8]; 7] = [&[]; 7];
|
||||||
|
let mut sig_at = 0;
|
||||||
|
for (i, &(tag, field, min, max)) in FIELDS.iter().enumerate() {
|
||||||
|
let found = *b.get(pos).ok_or(DecodeError::Truncated { field })?;
|
||||||
|
if found != tag {
|
||||||
|
return Err(if (1..=7).contains(&found) {
|
||||||
|
DecodeError::FieldOutOfOrder { expected: tag, found }
|
||||||
|
} else {
|
||||||
|
DecodeError::UnknownField(found)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if tag == 7 {
|
||||||
|
sig_at = pos;
|
||||||
|
}
|
||||||
|
let len_bytes: [u8; 4] =
|
||||||
|
b.get(pos + 1..pos + 5).and_then(|s| s.try_into().ok()).ok_or(DecodeError::Truncated { field })?;
|
||||||
|
let len = u32::from_be_bytes(len_bytes) as usize;
|
||||||
|
if len < min || len > max {
|
||||||
|
return Err(DecodeError::BadLength { field, len: len as u64 });
|
||||||
|
}
|
||||||
|
let start = pos + 5;
|
||||||
|
values[i] = b.get(start..start + len).ok_or(DecodeError::Truncated { field })?;
|
||||||
|
pos = start + len;
|
||||||
|
}
|
||||||
|
if pos != b.len() {
|
||||||
|
return Err(DecodeError::TrailingBytes);
|
||||||
|
}
|
||||||
|
let invalid = |field, reason| DecodeError::Invalid { field, reason };
|
||||||
|
let app = std::str::from_utf8(values[0])
|
||||||
|
.ok()
|
||||||
|
.and_then(|s| Id::new(s).ok())
|
||||||
|
.ok_or(invalid("app", "not an id (a-z, 0-9, '-')"))?;
|
||||||
|
let schema = u32::from_be_bytes(values[1].try_into().map_err(|_| invalid("schema", "length"))?);
|
||||||
|
let hlc = Hlc::from_bytes(values[2].try_into().map_err(|_| invalid("hlc", "length"))?);
|
||||||
|
let author = PublicKey::from_bytes(values[3].try_into().map_err(|_| invalid("author", "length"))?);
|
||||||
|
let cert = SubkeyCert::from_bytes(values[4]).map_err(DecodeError::Cert)?;
|
||||||
|
let sig = Signature::from_bytes(values[6].try_into().map_err(|_| invalid("sig", "length"))?);
|
||||||
|
Ok(Envelope {
|
||||||
|
app,
|
||||||
|
schema,
|
||||||
|
hlc,
|
||||||
|
author,
|
||||||
|
cert,
|
||||||
|
payload: values[5].to_vec(),
|
||||||
|
sig,
|
||||||
|
bytes: b.to_vec(),
|
||||||
|
sig_at,
|
||||||
|
hash: tessera::hash(b),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_bytes(&self) -> &[u8] {
|
||||||
|
&self.bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hash(&self) -> [u8; 32] {
|
||||||
|
self.hash
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn app(&self) -> &Id {
|
||||||
|
&self.app
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn schema(&self) -> u32 {
|
||||||
|
self.schema
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hlc(&self) -> Hlc {
|
||||||
|
self.hlc
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn author(&self) -> PublicKey {
|
||||||
|
self.author
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cert(&self) -> &SubkeyCert {
|
||||||
|
&self.cert
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn payload(&self) -> &[u8] {
|
||||||
|
&self.payload
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether this event comes from an app subkey of one of `roots`, for this app, made while its cert
|
||||||
|
/// was valid, and not from the future (`now_ms` + `max_drift_ms`). The first failure is the reason.
|
||||||
|
pub fn verify(&self, roots: &[PublicKey], now_ms: u64, max_drift_ms: u64) -> Result<(), VerifyError> {
|
||||||
|
if self.author != self.cert.subkey() {
|
||||||
|
return Err(VerifyError::AuthorNotCert);
|
||||||
|
}
|
||||||
|
if self.cert.app_id() != &self.app {
|
||||||
|
return Err(VerifyError::WrongApp);
|
||||||
|
}
|
||||||
|
let root = self.cert.root();
|
||||||
|
if !roots.contains(&root) {
|
||||||
|
return Err(VerifyError::UnknownRoot);
|
||||||
|
}
|
||||||
|
self.cert.verify(&root, self.hlc.wall / 1000).map_err(VerifyError::Cert)?;
|
||||||
|
if self.hlc.wall > now_ms.saturating_add(max_drift_ms) {
|
||||||
|
return Err(VerifyError::FromTheFuture);
|
||||||
|
}
|
||||||
|
if !verify_event_sig(&self.author, &self.bytes[..self.sig_at], &self.sig) {
|
||||||
|
return Err(VerifyError::BadSignature);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LogEvent for Envelope {
|
||||||
|
fn order_key(&self) -> OrderKey {
|
||||||
|
OrderKey { hlc: self.hlc, author: self.author, hash: self.hash }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encoded(&self) -> &[u8] {
|
||||||
|
&self.bytes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Metadata only; the payload is shown by its length.
|
||||||
|
impl fmt::Debug for Envelope {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("Envelope")
|
||||||
|
.field("app", &self.app)
|
||||||
|
.field("schema", &self.schema)
|
||||||
|
.field("hlc", &self.hlc)
|
||||||
|
.field("author", &self.author)
|
||||||
|
.field("payload_len", &self.payload.len())
|
||||||
|
.finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,349 @@
|
|||||||
|
//! The mandatory tests for the envelope (docs/TESSERA.md §8): hostile input, verification, convergence.
|
||||||
|
//! Written before the code.
|
||||||
|
|
||||||
|
use envelope::{DecodeError, Envelope, MAX_PAYLOAD, SealError, VerifyError};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
use tessera::{CertError, CertRequest, Clock, Hlc, Id, Log, PublicKey, RootKey, Subkey, SubkeyCert, certify, merge};
|
||||||
|
|
||||||
|
const ALICE: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
|
||||||
|
abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art";
|
||||||
|
const MALLORY: &str = "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth \
|
||||||
|
useful legal winner thank year wave sausage worth title";
|
||||||
|
|
||||||
|
const DAY: u64 = 86_400;
|
||||||
|
const NOW_S: u64 = 1_793_000_000;
|
||||||
|
const NOW_MS: u64 = NOW_S * 1000;
|
||||||
|
const DRIFT: u64 = 5 * 60 * 1000;
|
||||||
|
|
||||||
|
fn root(m: &str) -> RootKey {
|
||||||
|
RootKey::from_mnemonic(m).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cert_for(root: &RootKey, sub: &Subkey, app: &str) -> SubkeyCert {
|
||||||
|
let req = CertRequest {
|
||||||
|
subkey: sub.public(),
|
||||||
|
app_id: Id::new(app).unwrap(),
|
||||||
|
purpose: Id::new("sync").unwrap(),
|
||||||
|
not_before: NOW_S - DAY,
|
||||||
|
not_after: NOW_S + 30 * DAY,
|
||||||
|
};
|
||||||
|
certify(root, &req).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Alice's Fiscus subkey and an event from it at `NOW`.
|
||||||
|
fn alice_event(payload: &[u8]) -> (Subkey, SubkeyCert, Envelope) {
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
let cert = cert_for(&root(ALICE), &sub, "fiscus");
|
||||||
|
let e = Envelope::seal(&sub, &cert, 1, Hlc { wall: NOW_MS, logical: 0 }, payload).unwrap();
|
||||||
|
(sub, cert, e)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn alice() -> Vec<PublicKey> {
|
||||||
|
vec![root(ALICE).public()]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds envelope bytes field by field, independently of the crate, so tests can make what `seal` never
|
||||||
|
/// would. `fields` are (tag, value); the signature (tag 7) is computed over everything before it.
|
||||||
|
fn raw(fields: &[(u8, Vec<u8>)], signer: &Subkey) -> Vec<u8> {
|
||||||
|
let mut out = b"TEV1".to_vec();
|
||||||
|
for (tag, v) in fields {
|
||||||
|
out.push(*tag);
|
||||||
|
out.extend_from_slice(&(v.len() as u32).to_be_bytes());
|
||||||
|
out.extend_from_slice(v);
|
||||||
|
}
|
||||||
|
let sig = signer.sign_event_tbs(&out);
|
||||||
|
out.push(7);
|
||||||
|
out.extend_from_slice(&64u32.to_be_bytes());
|
||||||
|
out.extend_from_slice(sig.as_bytes());
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fields(app: &str, hlc: Hlc, author: &Subkey, cert: &SubkeyCert, payload: &[u8]) -> Vec<(u8, Vec<u8>)> {
|
||||||
|
vec![
|
||||||
|
(1, app.as_bytes().to_vec()),
|
||||||
|
(2, 1u32.to_be_bytes().to_vec()),
|
||||||
|
(3, hlc.to_bytes().to_vec()),
|
||||||
|
(4, author.public().as_bytes().to_vec()),
|
||||||
|
(5, cert.to_bytes()),
|
||||||
|
(6, payload.to_vec()),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- round trip ----------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_sealed_event_decodes_to_itself_and_verifies() {
|
||||||
|
let (sub, cert, e) = alice_event(b"ciphertext");
|
||||||
|
let back = Envelope::decode(e.as_bytes()).unwrap();
|
||||||
|
assert_eq!(back.as_bytes(), e.as_bytes());
|
||||||
|
assert_eq!(back.app().as_str(), "fiscus");
|
||||||
|
assert_eq!(back.schema(), 1);
|
||||||
|
assert_eq!(back.author(), sub.public());
|
||||||
|
assert_eq!(back.cert(), &cert);
|
||||||
|
assert_eq!(back.payload(), b"ciphertext");
|
||||||
|
assert_eq!(back.verify(&alice(), NOW_MS, DRIFT), Ok(()));
|
||||||
|
// The independent encoder agrees with seal byte for byte.
|
||||||
|
let same = raw(&fields("fiscus", Hlc { wall: NOW_MS, logical: 0 }, &sub, &cert, b"ciphertext"), &sub);
|
||||||
|
assert_eq!(same, e.as_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn seal_refuses_a_cert_for_another_key_and_an_oversized_payload() {
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
let other = Subkey::from_seed(&[2; 32]);
|
||||||
|
let cert = cert_for(&root(ALICE), &other, "fiscus");
|
||||||
|
assert!(Envelope::seal(&sub, &cert, 1, Hlc::default(), b"x").is_err());
|
||||||
|
let cert = cert_for(&root(ALICE), &sub, "fiscus");
|
||||||
|
assert!(Envelope::seal(&sub, &cert, 1, Hlc::default(), &vec![0; MAX_PAYLOAD + 1]).is_err());
|
||||||
|
assert!(Envelope::seal(&sub, &cert, 1, Hlc::default(), &vec![0; MAX_PAYLOAD]).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The two-step seal for a signer that cannot sign at once (docs/V1_1B.md §2) makes the same bytes as `seal`,
|
||||||
|
/// and refuses a signature that is not the author's.
|
||||||
|
#[test]
|
||||||
|
fn the_two_step_seal_equals_seal_and_refuses_a_wrong_signature() {
|
||||||
|
let (sub, cert, e) = alice_event(b"two steps");
|
||||||
|
let hlc = Hlc { wall: NOW_MS, logical: 0 };
|
||||||
|
let tbs = Envelope::to_be_signed(&sub.public(), &cert, 1, hlc, b"two steps").unwrap();
|
||||||
|
let sig = sub.sign_event_tbs(&tbs);
|
||||||
|
assert_eq!(Envelope::with_signature(tbs.clone(), sig).unwrap().as_bytes(), e.as_bytes());
|
||||||
|
|
||||||
|
let other = Subkey::from_seed(&[9; 32]);
|
||||||
|
assert_eq!(Envelope::with_signature(tbs.clone(), other.sign_event_tbs(&tbs)).unwrap_err(), SealError::BadSignature);
|
||||||
|
// A signature in the credential domain is not an event signature.
|
||||||
|
assert_eq!(
|
||||||
|
Envelope::with_signature(tbs.clone(), sub.sign_credential_tbs(&tbs)).unwrap_err(),
|
||||||
|
SealError::BadSignature
|
||||||
|
);
|
||||||
|
assert_eq!(Envelope::with_signature(tbs[..10].to_vec(), sig).unwrap_err(), SealError::NotToBeSigned);
|
||||||
|
assert_eq!(Envelope::to_be_signed(&other.public(), &cert, 1, hlc, b"x").unwrap_err(), SealError::CertForAnotherKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- hostile events: dropped with a reason ----------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wrong_signature_is_rejected() {
|
||||||
|
let (_, _, e) = alice_event(b"x");
|
||||||
|
let mut b = e.as_bytes().to_vec();
|
||||||
|
let last = b.len() - 1;
|
||||||
|
b[last] ^= 1;
|
||||||
|
let d = Envelope::decode(&b).unwrap();
|
||||||
|
assert_eq!(d.verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::BadSignature));
|
||||||
|
// Signed by a key other than the author's.
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
let cert = cert_for(&root(ALICE), &sub, "fiscus");
|
||||||
|
let forged =
|
||||||
|
raw(&fields("fiscus", Hlc { wall: NOW_MS, logical: 0 }, &sub, &cert, b"x"), &Subkey::from_seed(&[9; 32]));
|
||||||
|
assert_eq!(Envelope::decode(&forged).unwrap().verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::BadSignature));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_expired_or_premature_cert_is_rejected() {
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
let cert = cert_for(&root(ALICE), &sub, "fiscus");
|
||||||
|
let late = Hlc { wall: (NOW_S + 30 * DAY) * 1000, logical: 0 };
|
||||||
|
let e = Envelope::seal(&sub, &cert, 1, late, b"x").unwrap();
|
||||||
|
assert_eq!(e.verify(&alice(), late.wall, DRIFT), Err(VerifyError::Cert(CertError::Expired)));
|
||||||
|
let early = Hlc { wall: (NOW_S - DAY - 1) * 1000, logical: 0 };
|
||||||
|
let e = Envelope::seal(&sub, &cert, 1, early, b"x").unwrap();
|
||||||
|
assert_eq!(e.verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::Cert(CertError::NotYetValid)));
|
||||||
|
// An event made while the cert was valid stays valid after it expires: logs can be rebuilt.
|
||||||
|
let (_, _, e) = alice_event(b"x");
|
||||||
|
assert_eq!(e.verify(&alice(), (NOW_S + 400 * DAY) * 1000, DRIFT), Ok(()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cert_from_a_root_outside_the_group_is_rejected() {
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
let cert = cert_for(&root(MALLORY), &sub, "fiscus");
|
||||||
|
let e = Envelope::seal(&sub, &cert, 1, Hlc { wall: NOW_MS, logical: 0 }, b"x").unwrap();
|
||||||
|
assert_eq!(e.verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::UnknownRoot));
|
||||||
|
let both = vec![root(ALICE).public(), root(MALLORY).public()];
|
||||||
|
assert_eq!(e.verify(&both, NOW_MS, DRIFT), Ok(()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_event_for_another_app_or_author_is_rejected() {
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
let cert = cert_for(&root(ALICE), &sub, "calenda");
|
||||||
|
let hlc = Hlc { wall: NOW_MS, logical: 0 };
|
||||||
|
let wrong_app = raw(&fields("fiscus", hlc, &sub, &cert, b"x"), &sub);
|
||||||
|
assert_eq!(Envelope::decode(&wrong_app).unwrap().verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::WrongApp));
|
||||||
|
// The author field names another key than the cert (and that key signed).
|
||||||
|
let other = Subkey::from_seed(&[2; 32]);
|
||||||
|
let cert = cert_for(&root(ALICE), &sub, "fiscus");
|
||||||
|
let wrong_author = raw(&fields("fiscus", hlc, &other, &cert, b"x"), &other);
|
||||||
|
assert_eq!(
|
||||||
|
Envelope::decode(&wrong_author).unwrap().verify(&alice(), NOW_MS, DRIFT),
|
||||||
|
Err(VerifyError::AuthorNotCert)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_event_from_the_future_is_rejected() {
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
let cert = cert_for(&root(ALICE), &sub, "fiscus");
|
||||||
|
let e = Envelope::seal(&sub, &cert, 1, Hlc { wall: NOW_MS + DRIFT + 1, logical: 0 }, b"x").unwrap();
|
||||||
|
assert_eq!(e.verify(&alice(), NOW_MS, DRIFT), Err(VerifyError::FromTheFuture));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn malformed_bodies_are_typed_errors() {
|
||||||
|
let (sub, cert, e) = alice_event(b"x");
|
||||||
|
let hlc = Hlc { wall: NOW_MS, logical: 0 };
|
||||||
|
let good = e.as_bytes().to_vec();
|
||||||
|
|
||||||
|
let mut magic = good.clone();
|
||||||
|
magic[3] = b'2';
|
||||||
|
assert_eq!(Envelope::decode(&magic).err(), Some(DecodeError::BadMagic));
|
||||||
|
|
||||||
|
let mut trailing = good.clone();
|
||||||
|
trailing.push(0);
|
||||||
|
assert_eq!(Envelope::decode(&trailing).err(), Some(DecodeError::TrailingBytes));
|
||||||
|
|
||||||
|
assert!(matches!(Envelope::decode(&good[..good.len() - 1]), Err(DecodeError::Truncated { .. })));
|
||||||
|
assert_eq!(Envelope::decode(b"TE").err(), Some(DecodeError::TooShort));
|
||||||
|
|
||||||
|
let mut f = fields("fiscus", hlc, &sub, &cert, b"x");
|
||||||
|
f.insert(2, (9, b"surprise".to_vec()));
|
||||||
|
assert_eq!(Envelope::decode(&raw(&f, &sub)).err(), Some(DecodeError::UnknownField(9)));
|
||||||
|
|
||||||
|
let mut f = fields("fiscus", hlc, &sub, &cert, b"x");
|
||||||
|
f.swap(1, 2);
|
||||||
|
assert_eq!(Envelope::decode(&raw(&f, &sub)).err(), Some(DecodeError::FieldOutOfOrder { expected: 2, found: 3 }));
|
||||||
|
|
||||||
|
let mut f = fields("fiscus", hlc, &sub, &cert, b"x");
|
||||||
|
f.insert(1, (1, b"fiscus".to_vec()));
|
||||||
|
assert_eq!(Envelope::decode(&raw(&f, &sub)).err(), Some(DecodeError::FieldOutOfOrder { expected: 2, found: 1 }));
|
||||||
|
|
||||||
|
let mut f = fields("fiscus", hlc, &sub, &cert, b"x");
|
||||||
|
f[1].1 = vec![0, 0, 1];
|
||||||
|
assert!(matches!(Envelope::decode(&raw(&f, &sub)), Err(DecodeError::BadLength { field: "schema", .. })));
|
||||||
|
|
||||||
|
let f = fields("Fiscus", hlc, &sub, &cert, b"x");
|
||||||
|
assert!(matches!(Envelope::decode(&raw(&f, &sub)), Err(DecodeError::Invalid { field: "app", .. })));
|
||||||
|
|
||||||
|
let mut f = fields("fiscus", hlc, &sub, &cert, b"x");
|
||||||
|
let mut bad_cert = cert.to_bytes();
|
||||||
|
bad_cert[0] = b'X';
|
||||||
|
f[4].1 = bad_cert;
|
||||||
|
assert!(matches!(Envelope::decode(&raw(&f, &sub)), Err(DecodeError::Cert(_))));
|
||||||
|
|
||||||
|
let mut huge = good.clone();
|
||||||
|
huge.resize(envelope::MAX_ENVELOPE + 1, 0);
|
||||||
|
assert!(matches!(Envelope::decode(&huge), Err(DecodeError::TooLarge(_))));
|
||||||
|
|
||||||
|
// A length that claims more than there is.
|
||||||
|
let mut lie = good.clone();
|
||||||
|
lie[5..9].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||||
|
assert!(Envelope::decode(&lie).is_err());
|
||||||
|
|
||||||
|
// Every error has a reason.
|
||||||
|
for b in [&magic, &trailing, &huge, &lie] {
|
||||||
|
assert!(!Envelope::decode(b).unwrap_err().to_string().is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig::with_cases(2000))]
|
||||||
|
|
||||||
|
/// Random bytes: never a panic, and every rejection says why.
|
||||||
|
#[test]
|
||||||
|
fn random_bytes_never_panic(b in prop::collection::vec(any::<u8>(), 0..600), magic in any::<bool>()) {
|
||||||
|
let mut b = b;
|
||||||
|
if magic && b.len() >= 4 {
|
||||||
|
b[..4].copy_from_slice(b"TEV1");
|
||||||
|
}
|
||||||
|
match Envelope::decode(&b) {
|
||||||
|
Ok(e) => prop_assert_eq!(e.as_bytes(), &b[..]),
|
||||||
|
Err(err) => prop_assert!(!err.to_string().is_empty()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A valid envelope with random damage: either a typed error, or a whole envelope that is exactly the
|
||||||
|
/// input — and then it verifies only if nothing changed.
|
||||||
|
#[test]
|
||||||
|
fn damaged_envelopes_are_all_or_nothing(
|
||||||
|
edits in prop::collection::vec((any::<prop::sample::Index>(), any::<u8>(), 0u8..3), 1..4),
|
||||||
|
) {
|
||||||
|
let (_, _, e) = alice_event(b"some ciphertext");
|
||||||
|
let original = e.as_bytes().to_vec();
|
||||||
|
let mut b = original.clone();
|
||||||
|
for (at, byte, kind) in edits {
|
||||||
|
if b.is_empty() { break; }
|
||||||
|
let i = at.index(b.len());
|
||||||
|
match kind {
|
||||||
|
0 => b[i] ^= byte | 1,
|
||||||
|
1 => { b.remove(i); }
|
||||||
|
_ => b.insert(i, byte),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match Envelope::decode(&b) {
|
||||||
|
Ok(d) => {
|
||||||
|
prop_assert_eq!(d.as_bytes(), &b[..]);
|
||||||
|
if d.verify(&alice(), NOW_MS, DRIFT).is_ok() {
|
||||||
|
prop_assert_eq!(&b, &original);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => prop_assert!(!err.to_string().is_empty()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- two devices converge ----------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn two_devices_writing_offline_converge_in_either_order() {
|
||||||
|
let r = root(ALICE);
|
||||||
|
let (pc, phone) = (Subkey::from_seed(&[1; 32]), Subkey::from_seed(&[2; 32]));
|
||||||
|
let (pc_cert, phone_cert) = (cert_for(&r, &pc, "fiscus"), cert_for(&r, &phone, "fiscus"));
|
||||||
|
let (mut pc_clock, mut phone_clock) = (Clock::default(), Clock::default());
|
||||||
|
// Both offline, writing at overlapping times; the phone's clock is 2 s behind.
|
||||||
|
let mut a = Vec::new();
|
||||||
|
let mut b = Vec::new();
|
||||||
|
for i in 0..5u64 {
|
||||||
|
let t = NOW_MS + i * 1000;
|
||||||
|
a.push(Envelope::seal(&pc, &pc_cert, 1, pc_clock.tick(t).unwrap(), format!("pc {i}").as_bytes()).unwrap());
|
||||||
|
b.push(
|
||||||
|
Envelope::seal(
|
||||||
|
&phone,
|
||||||
|
&phone_cert,
|
||||||
|
1,
|
||||||
|
phone_clock.tick(t - 2000).unwrap(),
|
||||||
|
format!("phone {i}").as_bytes(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let roots = alice();
|
||||||
|
let check = |e: &Envelope| e.verify(&roots, NOW_MS + 10_000, DRIFT);
|
||||||
|
// Each device has its own log; then they exchange in either order.
|
||||||
|
let pc_log = merge(&Log::new(), a.clone(), check).log;
|
||||||
|
let phone_log = merge(&Log::new(), b.clone(), check).log;
|
||||||
|
let on_pc = merge(&pc_log, phone_log.events().to_vec(), check).log;
|
||||||
|
let on_phone = merge(&phone_log, pc_log.events().to_vec(), check).log;
|
||||||
|
assert_eq!(on_pc.len(), 10);
|
||||||
|
assert_eq!(on_pc.to_bytes(), on_phone.to_bytes(), "byte-identical");
|
||||||
|
// Receiving everything again changes nothing.
|
||||||
|
let again = merge(&on_pc, [a, b].concat(), check);
|
||||||
|
assert_eq!(again.added, 0);
|
||||||
|
assert_eq!(again.log.to_bytes(), on_pc.to_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_hostile_event_leaves_the_log_unchanged() {
|
||||||
|
let (_, _, good) = alice_event(b"x");
|
||||||
|
let roots = alice();
|
||||||
|
let check = |e: &Envelope| e.verify(&roots, NOW_MS, DRIFT);
|
||||||
|
let log = merge(&Log::new(), vec![good], check).log;
|
||||||
|
let before = log.to_bytes();
|
||||||
|
let sub = Subkey::from_seed(&[5; 32]);
|
||||||
|
let evil =
|
||||||
|
Envelope::seal(&sub, &cert_for(&root(MALLORY), &sub, "fiscus"), 1, Hlc { wall: NOW_MS, logical: 1 }, b"y")
|
||||||
|
.unwrap();
|
||||||
|
let m = merge(&log, vec![evil], check);
|
||||||
|
assert_eq!(m.log.to_bytes(), before);
|
||||||
|
assert_eq!(m.rejected.len(), 1);
|
||||||
|
assert_eq!(m.rejected[0].1, VerifyError::UnknownRoot);
|
||||||
|
assert!(!m.rejected[0].1.to_string().is_empty());
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
[package]
|
||||||
|
name = "tabellarius-proto"
|
||||||
|
description = "Tabellarius wire protocol: mailbox ids, per-mailbox request signatures, limits (docs/TABELLARIUS.md §3)"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
ed25519-dalek.workspace = true
|
||||||
|
sha2.workspace = true
|
||||||
|
zeroize.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
|
data-encoding.workspace = true
|
||||||
|
getrandom = "0.3"
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
//! The Tabellarius wire protocol (docs/TABELLARIUS.md §3), shared by the relay and the client.
|
||||||
|
//!
|
||||||
|
//! - Mailbox ids: a group's is `SHA-256("tabellarius mailbox v1" ‖ group id)`, an invite's is random.
|
||||||
|
//! - Every request is signed by a random **per-mailbox** key ([`MailboxKey`]), never by an identity key.
|
||||||
|
|
||||||
|
use data_encoding::{BASE64URL_NOPAD, HEXLOWER};
|
||||||
|
use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::fmt;
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
/// The largest message (MLS ciphertext) the relay keeps.
|
||||||
|
pub const MAX_MESSAGE: usize = 300 * 1024;
|
||||||
|
/// The most messages in one upload.
|
||||||
|
pub const MAX_BATCH: usize = 100;
|
||||||
|
/// The largest request body.
|
||||||
|
pub const MAX_BODY: usize = 2 * 1024 * 1024;
|
||||||
|
/// The most messages one fetch returns.
|
||||||
|
pub const FETCH_LIMIT: usize = 200;
|
||||||
|
/// How far a request's time may be from the relay's, in seconds.
|
||||||
|
pub const MAX_SKEW: u64 = 120;
|
||||||
|
|
||||||
|
/// Live subscribe (docs/V1_1B.md §3): the most subscriptions on one socket.
|
||||||
|
pub const LIVE_MAX_SUBS: usize = 32;
|
||||||
|
/// The most open subscriptions per mailbox key, over all sockets.
|
||||||
|
pub const LIVE_MAX_PER_KEY: u32 = 4;
|
||||||
|
/// A socket with nothing from its client for this long is closed.
|
||||||
|
pub const LIVE_IDLE_SECS: u64 = 600;
|
||||||
|
/// The method a subscription is signed with.
|
||||||
|
pub const LIVE_METHOD: &str = "LIVE";
|
||||||
|
|
||||||
|
/// The path a subscription to `mailbox` from `after` is signed with (method [`LIVE_METHOD`], empty body).
|
||||||
|
pub fn live_path(mailbox: &str, after: u64) -> String {
|
||||||
|
format!("/v1/mailboxes/{mailbox}/live?after={after}")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const H_KEY: &str = "tab-key";
|
||||||
|
pub const H_TIME: &str = "tab-time";
|
||||||
|
pub const H_NONCE: &str = "tab-nonce";
|
||||||
|
pub const H_SIG: &str = "tab-sig";
|
||||||
|
|
||||||
|
const REQUEST_DOMAIN: &[u8] = b"tabellarius request v1\0";
|
||||||
|
const MAILBOX_DOMAIN: &[u8] = b"tabellarius mailbox v1";
|
||||||
|
|
||||||
|
pub fn b64(b: &[u8]) -> String {
|
||||||
|
BASE64URL_NOPAD.encode(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn unb64(s: &str) -> Option<Vec<u8>> {
|
||||||
|
BASE64URL_NOPAD.decode(s.as_bytes()).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn unb64_32(s: &str) -> Option<[u8; 32]> {
|
||||||
|
unb64(s)?.try_into().ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A group's mailbox id.
|
||||||
|
pub fn group_mailbox(group_id: &[u8]) -> [u8; 32] {
|
||||||
|
Sha256::new().chain_update(MAILBOX_DOMAIN).chain_update(group_id).finalize().into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 32 bytes from the OS CSPRNG.
|
||||||
|
pub fn random32() -> [u8; 32] {
|
||||||
|
let mut b = [0u8; 32];
|
||||||
|
getrandom::fill(&mut b).expect("the OS has randomness");
|
||||||
|
b
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a request's signature covers.
|
||||||
|
pub fn signed_bytes(method: &str, path_and_query: &str, time: u64, nonce: &str, body: &[u8]) -> Vec<u8> {
|
||||||
|
let body_hash = HEXLOWER.encode(&Sha256::digest(body));
|
||||||
|
let mut out = REQUEST_DOMAIN.to_vec();
|
||||||
|
out.extend_from_slice(format!("{method}\n{path_and_query}\n{time}\n{nonce}\n{body_hash}").as_bytes());
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The four headers of a signed request.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct SignedHeaders {
|
||||||
|
pub key: String,
|
||||||
|
pub time: String,
|
||||||
|
pub nonce: String,
|
||||||
|
pub sig: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SignedHeaders {
|
||||||
|
pub fn pairs(&self) -> [(&'static str, &str); 4] {
|
||||||
|
[(H_KEY, &self.key), (H_TIME, &self.time), (H_NONCE, &self.nonce), (H_SIG, &self.sig)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A random key for one mailbox. It identifies a device in that mailbox and nowhere else.
|
||||||
|
pub struct MailboxKey(SigningKey);
|
||||||
|
|
||||||
|
impl MailboxKey {
|
||||||
|
pub fn generate() -> MailboxKey {
|
||||||
|
let seed = Zeroizing::new(random32());
|
||||||
|
MailboxKey(SigningKey::from_bytes(&seed))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// From a seed kept in the client's encrypted state.
|
||||||
|
pub fn from_seed(seed: &[u8; 32]) -> MailboxKey {
|
||||||
|
MailboxKey(SigningKey::from_bytes(seed))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For the client's encrypted state only.
|
||||||
|
pub fn seed(&self) -> Zeroizing<[u8; 32]> {
|
||||||
|
Zeroizing::new(self.0.to_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn public(&self) -> [u8; 32] {
|
||||||
|
self.0.verifying_key().to_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sign_request(&self, method: &str, path_and_query: &str, body: &[u8], time: u64) -> SignedHeaders {
|
||||||
|
let nonce = b64(&random32()[..16]);
|
||||||
|
let sig = self.0.sign(&signed_bytes(method, path_and_query, time, &nonce, body));
|
||||||
|
SignedHeaders { key: b64(&self.public()), time: time.to_string(), nonce, sig: b64(&sig.to_bytes()) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for MailboxKey {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str("MailboxKey([redacted])")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum AuthError {
|
||||||
|
#[error("unsigned")]
|
||||||
|
Unsigned,
|
||||||
|
#[error("stale")]
|
||||||
|
Stale,
|
||||||
|
#[error("bad_signature")]
|
||||||
|
BadSignature,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks a request's signature and time. Returns the key and nonce; registration and replay are the
|
||||||
|
/// relay's to check.
|
||||||
|
pub fn verify_request(
|
||||||
|
method: &str,
|
||||||
|
path_and_query: &str,
|
||||||
|
body: &[u8],
|
||||||
|
headers: [Option<&str>; 4],
|
||||||
|
now: u64,
|
||||||
|
) -> Result<([u8; 32], Vec<u8>), AuthError> {
|
||||||
|
let [Some(key), Some(time), Some(nonce), Some(sig)] = headers else { return Err(AuthError::Unsigned) };
|
||||||
|
let key = unb64_32(key).ok_or(AuthError::Unsigned)?;
|
||||||
|
let t: u64 = time.parse().map_err(|_| AuthError::Unsigned)?;
|
||||||
|
let nonce_bytes = unb64(nonce).filter(|n| n.len() == 16).ok_or(AuthError::Unsigned)?;
|
||||||
|
let sig: [u8; 64] = unb64(sig).and_then(|s| s.try_into().ok()).ok_or(AuthError::Unsigned)?;
|
||||||
|
if now.abs_diff(t) > MAX_SKEW {
|
||||||
|
return Err(AuthError::Stale);
|
||||||
|
}
|
||||||
|
let vk = VerifyingKey::from_bytes(&key).map_err(|_| AuthError::BadSignature)?;
|
||||||
|
vk.verify_strict(
|
||||||
|
&signed_bytes(method, path_and_query, t, nonce, body),
|
||||||
|
&ed25519_dalek::Signature::from_bytes(&sig),
|
||||||
|
)
|
||||||
|
.map_err(|_| AuthError::BadSignature)?;
|
||||||
|
Ok((key, nonce_bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_signed_request_verifies_and_any_change_breaks_it() {
|
||||||
|
let k = MailboxKey::generate();
|
||||||
|
let h = k.sign_request("POST", "/v1/mailboxes/x/messages", b"{}", 1000);
|
||||||
|
fn hs(h: &SignedHeaders) -> [Option<&str>; 4] {
|
||||||
|
[Some(h.key.as_str()), Some(h.time.as_str()), Some(h.nonce.as_str()), Some(h.sig.as_str())]
|
||||||
|
}
|
||||||
|
assert_eq!(verify_request("POST", "/v1/mailboxes/x/messages", b"{}", hs(&h), 1000).unwrap().0, k.public());
|
||||||
|
assert_eq!(
|
||||||
|
verify_request("POST", "/v1/mailboxes/y/messages", b"{}", hs(&h), 1000),
|
||||||
|
Err(AuthError::BadSignature)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
verify_request("POST", "/v1/mailboxes/x/messages", b"{ }", hs(&h), 1000),
|
||||||
|
Err(AuthError::BadSignature)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
verify_request("GET", "/v1/mailboxes/x/messages", b"{}", hs(&h), 1000),
|
||||||
|
Err(AuthError::BadSignature)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
verify_request("POST", "/v1/mailboxes/x/messages", b"{}", hs(&h), 1000 + MAX_SKEW + 1),
|
||||||
|
Err(AuthError::Stale)
|
||||||
|
);
|
||||||
|
assert_eq!(verify_request("POST", "/", b"", [None, None, None, None], 1000), Err(AuthError::Unsigned));
|
||||||
|
assert_eq!(format!("{k:?}"), "MailboxKey([redacted])");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn group_mailboxes_are_distinct_and_stable() {
|
||||||
|
assert_eq!(group_mailbox(b"g1"), group_mailbox(b"g1"));
|
||||||
|
assert_ne!(group_mailbox(b"g1"), group_mailbox(b"g2"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
[package]
|
||||||
|
name = "tessera"
|
||||||
|
description = "Domi identity: root key from a mnemonic, subkey certificates, match code, hybrid logical clock, deterministic merge (docs/TESSERA.md)"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
ed25519-dalek.workspace = true
|
||||||
|
sha2.workspace = true
|
||||||
|
hkdf.workspace = true
|
||||||
|
bip39.workspace = true
|
||||||
|
zeroize.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
|
data-encoding.workspace = true
|
||||||
|
chacha20poly1305 = "0.10"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
proptest = "1"
|
||||||
|
static_assertions = "1"
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
//! The backup secret (docs/TESSERA.md §12, docs/V1_1.md §3): per app, derived from the root secret, so the
|
||||||
|
//! 24 words bring it back with every device lost. It seals the app's backup and names its relay mailbox.
|
||||||
|
//!
|
||||||
|
//! Custos derives it and hands an app only its own; the app keeps it as an opaque value. Nothing reads the
|
||||||
|
//! secret back out: it seals, opens, and gives the backup mailbox's access-key seed (a relay credential of
|
||||||
|
//! the kind invite tokens carry; it lets its holder fetch ciphertext, nothing more).
|
||||||
|
|
||||||
|
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
|
||||||
|
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
|
||||||
|
use hkdf::Hkdf;
|
||||||
|
use sha2::Sha256;
|
||||||
|
use std::fmt;
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
const BACKUP_SALT: &[u8] = b"tessera backup v1";
|
||||||
|
const SEAL_INFO: &[u8] = b"seal";
|
||||||
|
const MAILBOX_INFO: &[u8] = b"mailbox";
|
||||||
|
|
||||||
|
/// An app's backup secret: 32 bytes from `HKDF-SHA256(salt "tessera backup v1", ikm = root secret,
|
||||||
|
/// info = app id)`.
|
||||||
|
pub struct BackupSecret(Zeroizing<[u8; 32]>);
|
||||||
|
|
||||||
|
pub(crate) fn derive(root_secret: &[u8; 32], app_id: &crate::Id) -> BackupSecret {
|
||||||
|
let mut out = Zeroizing::new([0u8; 32]);
|
||||||
|
Hkdf::<Sha256>::new(Some(BACKUP_SALT), root_secret)
|
||||||
|
.expand(app_id.as_str().as_bytes(), out.as_mut())
|
||||||
|
.expect("32 bytes is a valid HKDF length");
|
||||||
|
BackupSecret(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BackupSecret {
|
||||||
|
/// The 32 bytes Custos hands the app.
|
||||||
|
pub fn from_bytes(b: [u8; 32]) -> BackupSecret {
|
||||||
|
BackupSecret(Zeroizing::new(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn expand(&self, info: &[u8]) -> Zeroizing<[u8; 32]> {
|
||||||
|
let mut out = Zeroizing::new([0u8; 32]);
|
||||||
|
Hkdf::<Sha256>::from_prk(self.0.as_ref())
|
||||||
|
.expect("32 bytes is a valid PRK")
|
||||||
|
.expand(info, out.as_mut())
|
||||||
|
.expect("32 bytes is a valid HKDF length");
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `nonce ‖ XChaCha20-Poly1305(seal key, plain, aad)`. The caller supplies a fresh random nonce.
|
||||||
|
pub fn seal(&self, nonce: &[u8; 24], aad: &[u8], plain: &[u8]) -> Vec<u8> {
|
||||||
|
let key = self.expand(SEAL_INFO);
|
||||||
|
let ct = XChaCha20Poly1305::new(key.as_ref().into())
|
||||||
|
.encrypt(XNonce::from_slice(nonce), Payload { msg: plain, aad })
|
||||||
|
.expect("encryption does not fail");
|
||||||
|
[nonce.as_slice(), &ct].concat()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The plaintext, or `None` if `sealed` was not sealed with this secret and `aad`.
|
||||||
|
pub fn open(&self, aad: &[u8], sealed: &[u8]) -> Option<Vec<u8>> {
|
||||||
|
if sealed.len() < 24 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let key = self.expand(SEAL_INFO);
|
||||||
|
XChaCha20Poly1305::new(key.as_ref().into())
|
||||||
|
.decrypt(XNonce::from_slice(&sealed[..24]), Payload { msg: &sealed[24..], aad })
|
||||||
|
.ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The seed of the backup mailbox's access key (a Tabellarius `MailboxKey`).
|
||||||
|
pub fn mailbox_seed(&self) -> Zeroizing<[u8; 32]> {
|
||||||
|
self.expand(MAILBOX_INFO)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for BackupSecret {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str("BackupSecret([redacted])")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
//! Subkey certificates (`TSC1`) and the match code (docs/TESSERA.md §4, §5).
|
||||||
|
|
||||||
|
use crate::keys::{RootSigner, SignError, verify_cert_sig};
|
||||||
|
use crate::{Id, PublicKey, Reader, Signature};
|
||||||
|
use data_encoding::BASE64URL_NOPAD;
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
pub const CERT_MAGIC: &[u8; 4] = b"TSC1";
|
||||||
|
const SKEW: u64 = 5 * 60;
|
||||||
|
const YEAR: u64 = 365 * 86_400;
|
||||||
|
|
||||||
|
/// What a cert will say, before the root signs it.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct CertRequest {
|
||||||
|
pub subkey: PublicKey,
|
||||||
|
pub app_id: Id,
|
||||||
|
pub purpose: Id,
|
||||||
|
/// Unix seconds, inclusive.
|
||||||
|
pub not_before: u64,
|
||||||
|
/// Unix seconds, exclusive.
|
||||||
|
pub not_after: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CertRequest {
|
||||||
|
/// The validity Custos issues: from five minutes ago (clock skew) for 365 days.
|
||||||
|
pub fn standard(subkey: PublicKey, app_id: Id, purpose: Id, now: u64) -> CertRequest {
|
||||||
|
CertRequest {
|
||||||
|
subkey,
|
||||||
|
app_id,
|
||||||
|
purpose,
|
||||||
|
not_before: now.saturating_sub(SKEW),
|
||||||
|
not_after: now.saturating_add(YEAR),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bytes the root signs (after `CERT_DOMAIN`): everything in the cert before `sig`.
|
||||||
|
pub fn tbs(&self, root: &PublicKey) -> Vec<u8> {
|
||||||
|
let mut out = Vec::with_capacity(4 + 32 + 32 + 66 + 16);
|
||||||
|
out.extend_from_slice(CERT_MAGIC);
|
||||||
|
out.extend_from_slice(root.as_bytes());
|
||||||
|
out.extend_from_slice(self.subkey.as_bytes());
|
||||||
|
self.app_id.encode(&mut out);
|
||||||
|
self.purpose.encode(&mut out);
|
||||||
|
out.extend_from_slice(&self.not_before.to_be_bytes());
|
||||||
|
out.extend_from_slice(&self.not_after.to_be_bytes());
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A subkey certified by a root.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct SubkeyCert {
|
||||||
|
root: PublicKey,
|
||||||
|
req: CertRequest,
|
||||||
|
sig: Signature,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum CertError {
|
||||||
|
#[error("malformed certificate: {0}")]
|
||||||
|
Malformed(&'static str),
|
||||||
|
#[error("the certificate belongs to another identity")]
|
||||||
|
WrongRoot,
|
||||||
|
#[error("the certificate's signature is not valid (tampered)")]
|
||||||
|
BadSignature,
|
||||||
|
#[error("the certificate is not valid yet")]
|
||||||
|
NotYetValid,
|
||||||
|
#[error("the certificate has expired")]
|
||||||
|
Expired,
|
||||||
|
#[error("the root did not sign: {0}")]
|
||||||
|
Sign(SignError),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Has `signer` certify `req`, and checks the signature it got back.
|
||||||
|
pub fn certify(signer: &impl RootSigner, req: &CertRequest) -> Result<SubkeyCert, CertError> {
|
||||||
|
if req.not_after <= req.not_before {
|
||||||
|
return Err(CertError::Malformed("not_after must be later than not_before"));
|
||||||
|
}
|
||||||
|
let root = signer.root_public();
|
||||||
|
let tbs = req.tbs(&root);
|
||||||
|
let sig = signer.sign_cert_tbs(&tbs).map_err(CertError::Sign)?;
|
||||||
|
if !verify_cert_sig(&root, &tbs, &sig) {
|
||||||
|
return Err(CertError::BadSignature);
|
||||||
|
}
|
||||||
|
Ok(SubkeyCert { root, req: req.clone(), sig })
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SubkeyCert {
|
||||||
|
pub fn root(&self) -> PublicKey {
|
||||||
|
self.root
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn subkey(&self) -> PublicKey {
|
||||||
|
self.req.subkey
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn app_id(&self) -> &Id {
|
||||||
|
&self.req.app_id
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn purpose(&self) -> &Id {
|
||||||
|
&self.req.purpose
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn not_before(&self) -> u64 {
|
||||||
|
self.req.not_before
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn not_after(&self) -> u64 {
|
||||||
|
self.req.not_after
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks the cert against the root the caller trusts, at `now` (Unix seconds).
|
||||||
|
pub fn verify(&self, root: &PublicKey, now: u64) -> Result<(), CertError> {
|
||||||
|
if self.root != *root {
|
||||||
|
return Err(CertError::WrongRoot);
|
||||||
|
}
|
||||||
|
if !verify_cert_sig(&self.root, &self.req.tbs(&self.root), &self.sig) {
|
||||||
|
return Err(CertError::BadSignature);
|
||||||
|
}
|
||||||
|
if now < self.req.not_before {
|
||||||
|
return Err(CertError::NotYetValid);
|
||||||
|
}
|
||||||
|
if now >= self.req.not_after {
|
||||||
|
return Err(CertError::Expired);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_bytes(&self) -> Vec<u8> {
|
||||||
|
let mut out = self.req.tbs(&self.root);
|
||||||
|
out.extend_from_slice(self.sig.as_bytes());
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_bytes(b: &[u8]) -> Result<SubkeyCert, CertError> {
|
||||||
|
let mut r = Reader::new(b);
|
||||||
|
let m = CertError::Malformed;
|
||||||
|
if r.take(4) != Some(CERT_MAGIC.as_slice()) {
|
||||||
|
return Err(m("not a TSC1 certificate"));
|
||||||
|
}
|
||||||
|
let root = PublicKey::from_bytes(r.array().ok_or(m("too short"))?);
|
||||||
|
let subkey = PublicKey::from_bytes(r.array().ok_or(m("too short"))?);
|
||||||
|
let app_id = Id::decode(&mut r).ok_or(m("invalid app id"))?;
|
||||||
|
let purpose = Id::decode(&mut r).ok_or(m("invalid purpose"))?;
|
||||||
|
let not_before = r.u64().ok_or(m("too short"))?;
|
||||||
|
let not_after = r.u64().ok_or(m("too short"))?;
|
||||||
|
let sig = Signature::from_bytes(r.array().ok_or(m("too short"))?);
|
||||||
|
if !r.is_empty() {
|
||||||
|
return Err(m("trailing bytes"));
|
||||||
|
}
|
||||||
|
if not_after <= not_before {
|
||||||
|
return Err(m("not_after must be later than not_before"));
|
||||||
|
}
|
||||||
|
Ok(SubkeyCert { root, req: CertRequest { subkey, app_id, purpose, not_before, not_after }, sig })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// base64url without padding, for JSON and QR codes.
|
||||||
|
pub fn to_text(&self) -> String {
|
||||||
|
BASE64URL_NOPAD.encode(&self.to_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_text(s: &str) -> Result<SubkeyCert, CertError> {
|
||||||
|
let b = BASE64URL_NOPAD.decode(s.as_bytes()).map_err(|_| CertError::Malformed("not base64url"))?;
|
||||||
|
SubkeyCert::from_bytes(&b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Six digits for `subkey`, shown by the app and by Custos: `u32_be(SHA-256("tessera match v1" ‖ subkey)[0..4])
|
||||||
|
/// mod 1 000 000`.
|
||||||
|
pub fn match_code(subkey: &PublicKey) -> String {
|
||||||
|
let h = Sha256::new().chain_update(b"tessera match v1").chain_update(subkey.as_bytes()).finalize();
|
||||||
|
let n = u32::from_be_bytes([h[0], h[1], h[2], h[3]]) % 1_000_000;
|
||||||
|
format!("{n:06}")
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
//! The hybrid logical clock (docs/TESSERA.md §6). Time is a parameter: Unix milliseconds.
|
||||||
|
|
||||||
|
/// A timestamp, ordered by `wall` then `logical`.
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
|
pub struct Hlc {
|
||||||
|
/// Unix milliseconds.
|
||||||
|
pub wall: u64,
|
||||||
|
pub logical: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Hlc {
|
||||||
|
pub fn to_bytes(&self) -> [u8; 12] {
|
||||||
|
let mut b = [0u8; 12];
|
||||||
|
b[..8].copy_from_slice(&self.wall.to_be_bytes());
|
||||||
|
b[8..].copy_from_slice(&self.logical.to_be_bytes());
|
||||||
|
b
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_bytes(b: &[u8; 12]) -> Hlc {
|
||||||
|
let (w, l) = b.split_at(8);
|
||||||
|
Hlc {
|
||||||
|
wall: u64::from_be_bytes(w.try_into().unwrap_or_default()),
|
||||||
|
logical: u32::from_be_bytes(l.try_into().unwrap_or_default()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum ClockError {
|
||||||
|
#[error("the other clock is too far ahead of this one")]
|
||||||
|
TooFarAhead,
|
||||||
|
#[error("the logical counter would overflow")]
|
||||||
|
Overflow,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One device's clock.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Clock {
|
||||||
|
last: Hlc,
|
||||||
|
max_drift_ms: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Clock {
|
||||||
|
/// A clock that accepts remote clocks up to five minutes ahead.
|
||||||
|
fn default() -> Clock {
|
||||||
|
Clock::with_max_drift(5 * 60 * 1000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Clock {
|
||||||
|
pub fn with_max_drift(max_drift_ms: u64) -> Clock {
|
||||||
|
Clock { last: Hlc::default(), max_drift_ms }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The last timestamp this clock produced.
|
||||||
|
pub fn last(&self) -> Hlc {
|
||||||
|
self.last
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A timestamp for a local event.
|
||||||
|
pub fn tick(&mut self, now: u64) -> Result<Hlc, ClockError> {
|
||||||
|
let wall = self.last.wall.max(now);
|
||||||
|
let logical =
|
||||||
|
if wall == self.last.wall { self.last.logical.checked_add(1).ok_or(ClockError::Overflow)? } else { 0 };
|
||||||
|
self.last = Hlc { wall, logical };
|
||||||
|
Ok(self.last)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the clock past a remote timestamp. Refuses one more than `max_drift` ahead of `now`, without
|
||||||
|
/// changing the clock.
|
||||||
|
pub fn observe(&mut self, remote: Hlc, now: u64) -> Result<Hlc, ClockError> {
|
||||||
|
if remote.wall > now.saturating_add(self.max_drift_ms) {
|
||||||
|
return Err(ClockError::TooFarAhead);
|
||||||
|
}
|
||||||
|
let last = self.last;
|
||||||
|
let wall = last.wall.max(remote.wall).max(now);
|
||||||
|
let base = match (wall == last.wall, wall == remote.wall) {
|
||||||
|
(true, true) => Some(last.logical.max(remote.logical)),
|
||||||
|
(true, false) => Some(last.logical),
|
||||||
|
(false, true) => Some(remote.logical),
|
||||||
|
(false, false) => None,
|
||||||
|
};
|
||||||
|
let logical = match base {
|
||||||
|
Some(l) => l.checked_add(1).ok_or(ClockError::Overflow)?,
|
||||||
|
None => 0,
|
||||||
|
};
|
||||||
|
self.last = Hlc { wall, logical };
|
||||||
|
Ok(self.last)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
//! Ids: app ids, purposes and the envelope's `app` (docs/TESSERA.md §2).
|
||||||
|
|
||||||
|
use std::fmt;
|
||||||
|
|
||||||
|
/// 1–32 bytes of `[a-z0-9-]`, not starting or ending with `-`: exactly one encoding per value.
|
||||||
|
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||||
|
pub struct Id(String);
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
#[error("an id is 1-32 characters of a-z, 0-9 and '-', not starting or ending with '-'")]
|
||||||
|
pub struct IdError;
|
||||||
|
|
||||||
|
impl Id {
|
||||||
|
pub fn new(s: &str) -> Result<Id, IdError> {
|
||||||
|
let ok = (1..=32).contains(&s.len())
|
||||||
|
&& s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
|
||||||
|
&& !s.starts_with('-')
|
||||||
|
&& !s.ends_with('-');
|
||||||
|
if ok { Ok(Id(s.to_owned())) } else { Err(IdError) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_str(&self) -> &str {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `str8`: one length byte, then the bytes.
|
||||||
|
pub(crate) fn encode(&self, out: &mut Vec<u8>) {
|
||||||
|
out.push(self.0.len() as u8);
|
||||||
|
out.extend_from_slice(self.0.as_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn decode(r: &mut crate::Reader) -> Option<Id> {
|
||||||
|
let n = r.u8()? as usize;
|
||||||
|
let s = std::str::from_utf8(r.take(n)?).ok()?;
|
||||||
|
Id::new(s).ok()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for Id {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str(&self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for Id {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "Id({})", self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
//! Keys: the root key and its derivation, subkeys, public keys and signatures (docs/TESSERA.md §3).
|
||||||
|
//!
|
||||||
|
//! The secret types ([`RootKey`], [`Subkey`]) have no method that returns their bytes, are not `Clone`,
|
||||||
|
//! and print `[redacted]`. `tests/surface.rs` locks this.
|
||||||
|
|
||||||
|
use crate::cert::CERT_MAGIC;
|
||||||
|
use data_encoding::BASE64URL_NOPAD;
|
||||||
|
use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
|
||||||
|
use hkdf::Hkdf;
|
||||||
|
use sha2::Sha256;
|
||||||
|
use std::fmt;
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
/// Prefix of every message a root signs: it can only ever sign certs.
|
||||||
|
pub const CERT_DOMAIN: &[u8] = b"tessera cert v1\0";
|
||||||
|
/// Prefix of every message a subkey signs as an event author.
|
||||||
|
pub const EVENT_DOMAIN: &[u8] = b"tessera event v1\0";
|
||||||
|
/// Prefix of what a subkey signs to vouch for a device's keys in a group (docs/TABELLARIUS.md §2).
|
||||||
|
pub const CREDENTIAL_DOMAIN: &[u8] = b"tessera credential v1\0";
|
||||||
|
/// Prefix of every revocation a root signs (docs/TESSERA.md §12): its second and only other statement.
|
||||||
|
pub const REVOKE_DOMAIN: &[u8] = b"tessera revoke v1\0";
|
||||||
|
|
||||||
|
const ROOT_SALT: &[u8] = b"tessera root v1";
|
||||||
|
const ROOT_INFO: &[u8] = b"ed25519";
|
||||||
|
const MNEMONIC_WORDS: usize = 24;
|
||||||
|
|
||||||
|
/// An Ed25519 public key: a root or a subkey.
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||||
|
pub struct PublicKey([u8; 32]);
|
||||||
|
|
||||||
|
impl PublicKey {
|
||||||
|
pub fn from_bytes(b: [u8; 32]) -> PublicKey {
|
||||||
|
PublicKey(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_bytes(&self) -> &[u8; 32] {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses the base64url form that `Display` prints.
|
||||||
|
pub fn from_text(s: &str) -> Option<PublicKey> {
|
||||||
|
let b = BASE64URL_NOPAD.decode(s.as_bytes()).ok()?;
|
||||||
|
Some(PublicKey(b.try_into().ok()?))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// base64url without padding.
|
||||||
|
impl fmt::Display for PublicKey {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str(&BASE64URL_NOPAD.encode(&self.0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for PublicKey {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "PublicKey({self})")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An Ed25519 signature.
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct Signature([u8; 64]);
|
||||||
|
|
||||||
|
impl Signature {
|
||||||
|
pub fn from_bytes(b: [u8; 64]) -> Signature {
|
||||||
|
Signature(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_bytes(&self) -> &[u8; 64] {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for Signature {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "Signature({}…)", BASE64URL_NOPAD.encode(&self.0[..6]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum MnemonicError {
|
||||||
|
#[error("a Domi recovery phrase has 24 words")]
|
||||||
|
WordCount,
|
||||||
|
#[error("the recovery phrase has a word that is not in the list, or a wrong checksum")]
|
||||||
|
Invalid,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum SignError {
|
||||||
|
#[error("the root signs only certificates that name it")]
|
||||||
|
NotACert,
|
||||||
|
#[error("{0}")]
|
||||||
|
Other(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What can sign certs with a root: [`RootKey`] here, the Custos vault in practice.
|
||||||
|
pub trait RootSigner {
|
||||||
|
fn root_public(&self) -> PublicKey;
|
||||||
|
/// Signs `CERT_DOMAIN ‖ tbs`. Refuses a `tbs` that does not start with `TSC1` and this root's key.
|
||||||
|
fn sign_cert_tbs(&self, tbs: &[u8]) -> Result<Signature, SignError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What can sign revocations with a root (v1.1): [`RootKey`] here, the Custos vault in practice.
|
||||||
|
pub trait RevokeSigner: RootSigner {
|
||||||
|
/// Signs `REVOKE_DOMAIN ‖ tbs`. Refuses a `tbs` that does not start with `TRV1` and this root's key.
|
||||||
|
fn sign_revocation_tbs(&self, tbs: &[u8]) -> Result<Signature, SignError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The root key, derived from a mnemonic (docs/TESSERA.md §3). For recovery and tests: the real one stays
|
||||||
|
/// in Custos.
|
||||||
|
pub struct RootKey(SigningKey);
|
||||||
|
|
||||||
|
impl RootKey {
|
||||||
|
/// Words are separated by any whitespace; case does not matter. Exactly 24 BIP39 English words.
|
||||||
|
pub fn from_mnemonic(phrase: &str) -> Result<RootKey, MnemonicError> {
|
||||||
|
let words: Vec<String> = phrase.split_whitespace().map(|w| w.to_lowercase()).collect();
|
||||||
|
let normalized = Zeroizing::new(words.join(" "));
|
||||||
|
drop(Zeroizing::new(words));
|
||||||
|
if normalized.split(' ').count() != MNEMONIC_WORDS {
|
||||||
|
return Err(MnemonicError::WordCount);
|
||||||
|
}
|
||||||
|
let m = bip39::Mnemonic::parse_in_normalized(bip39::Language::English, &normalized)
|
||||||
|
.map_err(|_| MnemonicError::Invalid)?;
|
||||||
|
let seed = Zeroizing::new(m.to_seed_normalized(""));
|
||||||
|
let mut secret = Zeroizing::new([0u8; 32]);
|
||||||
|
Hkdf::<Sha256>::new(Some(ROOT_SALT), seed.as_ref())
|
||||||
|
.expand(ROOT_INFO, secret.as_mut())
|
||||||
|
.map_err(|_| MnemonicError::Invalid)?;
|
||||||
|
Ok(RootKey(SigningKey::from_bytes(&secret)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn public(&self) -> PublicKey {
|
||||||
|
PublicKey(self.0.verifying_key().to_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The app's backup secret (docs/TESSERA.md §12): from the root secret, so the 24 words bring it back.
|
||||||
|
pub fn backup_secret(&self, app_id: &crate::Id) -> crate::BackupSecret {
|
||||||
|
crate::backup::derive(&Zeroizing::new(self.0.to_bytes()), app_id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RevokeSigner for RootKey {
|
||||||
|
fn sign_revocation_tbs(&self, tbs: &[u8]) -> Result<Signature, SignError> {
|
||||||
|
if !names_root_as(tbs, crate::revoke::REVOCATION_MAGIC, &self.public()) {
|
||||||
|
return Err(SignError::NotACert);
|
||||||
|
}
|
||||||
|
Ok(Signature(self.0.sign(&[REVOKE_DOMAIN, tbs].concat()).to_bytes()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RootSigner for RootKey {
|
||||||
|
fn root_public(&self) -> PublicKey {
|
||||||
|
self.public()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sign_cert_tbs(&self, tbs: &[u8]) -> Result<Signature, SignError> {
|
||||||
|
if !names_root(tbs, &self.public()) {
|
||||||
|
return Err(SignError::NotACert);
|
||||||
|
}
|
||||||
|
Ok(Signature(self.0.sign(&[CERT_DOMAIN, tbs].concat()).to_bytes()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for RootKey {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str("RootKey([redacted])")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `tbs` starts like a cert for `root`: `TSC1 ‖ root`. Custos' vault applies the same check.
|
||||||
|
pub(crate) fn names_root(tbs: &[u8], root: &PublicKey) -> bool {
|
||||||
|
names_root_as(tbs, CERT_MAGIC, root)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `tbs` starts `magic ‖ root`.
|
||||||
|
fn names_root_as(tbs: &[u8], magic: &[u8; 4], root: &PublicKey) -> bool {
|
||||||
|
tbs.len() > 36 && &tbs[..4] == magic && tbs[4..36] == root.0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An app's subkey. The app makes the 32-byte seed from the OS CSPRNG and keeps it in Custos.
|
||||||
|
pub struct Subkey(SigningKey);
|
||||||
|
|
||||||
|
impl Subkey {
|
||||||
|
pub fn from_seed(seed: &[u8; 32]) -> Subkey {
|
||||||
|
Subkey(SigningKey::from_bytes(seed))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn public(&self) -> PublicKey {
|
||||||
|
PublicKey(self.0.verifying_key().to_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Signs `EVENT_DOMAIN ‖ tbs`.
|
||||||
|
pub fn sign_event_tbs(&self, tbs: &[u8]) -> Signature {
|
||||||
|
Signature(self.0.sign(&[EVENT_DOMAIN, tbs].concat()).to_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Signs `CREDENTIAL_DOMAIN ‖ tbs`: vouches for keys this device uses in a group.
|
||||||
|
pub fn sign_credential_tbs(&self, tbs: &[u8]) -> Signature {
|
||||||
|
Signature(self.0.sign(&[CREDENTIAL_DOMAIN, tbs].concat()).to_bytes())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for Subkey {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str("Subkey([redacted])")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify(key: &PublicKey, domain: &[u8], tbs: &[u8], sig: &Signature) -> bool {
|
||||||
|
let Ok(vk) = VerifyingKey::from_bytes(&key.0) else { return false };
|
||||||
|
let sig = ed25519_dalek::Signature::from_bytes(&sig.0);
|
||||||
|
vk.verify_strict(&[domain, tbs].concat(), &sig).is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `sig` is `author`'s signature over `EVENT_DOMAIN ‖ tbs` (strict: no malleable signatures, no
|
||||||
|
/// weak keys).
|
||||||
|
pub fn verify_event_sig(author: &PublicKey, tbs: &[u8], sig: &Signature) -> bool {
|
||||||
|
verify(author, EVENT_DOMAIN, tbs, sig)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `sig` is `subkey`'s signature over `CREDENTIAL_DOMAIN ‖ tbs`.
|
||||||
|
pub fn verify_credential_sig(subkey: &PublicKey, tbs: &[u8], sig: &Signature) -> bool {
|
||||||
|
verify(subkey, CREDENTIAL_DOMAIN, tbs, sig)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn verify_revocation_sig(root: &PublicKey, tbs: &[u8], sig: &Signature) -> bool {
|
||||||
|
verify(root, REVOKE_DOMAIN, tbs, sig)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn verify_cert_sig(root: &PublicKey, tbs: &[u8], sig: &Signature) -> bool {
|
||||||
|
verify(root, CERT_DOMAIN, tbs, sig)
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
//! Tessera: the Domi identity (docs/TESSERA.md).
|
||||||
|
//!
|
||||||
|
//! - [`RootKey`]: the root Ed25519 key, derived from a 24-word BIP39 mnemonic. In practice it lives in the
|
||||||
|
//! Custos vault, which implements [`RootSigner`]; this type is for recovery and tests.
|
||||||
|
//! - [`SubkeyCert`]: a subkey for one app, certified by the root; [`certify`] makes one, `verify` checks it.
|
||||||
|
//! - [`match_code`]: six digits the app and Custos both show.
|
||||||
|
//! - [`Clock`] / [`Hlc`]: a hybrid logical clock; [`merge`]: the deterministic union of event logs.
|
||||||
|
//! - [`revoke`] / [`RevocationSet`]: withdrawing a subkey (v1.1); [`BackupSecret`]: sealing an app's backup.
|
||||||
|
//!
|
||||||
|
//! Pure: no I/O, no network, no clock. Time is always a parameter (Unix seconds for certs, milliseconds for
|
||||||
|
//! the clock).
|
||||||
|
|
||||||
|
mod backup;
|
||||||
|
mod cert;
|
||||||
|
mod hlc;
|
||||||
|
mod id;
|
||||||
|
mod keys;
|
||||||
|
mod merge;
|
||||||
|
mod revoke;
|
||||||
|
|
||||||
|
pub use backup::BackupSecret;
|
||||||
|
pub use cert::{CERT_MAGIC, CertError, CertRequest, SubkeyCert, certify, match_code};
|
||||||
|
pub use hlc::{Clock, ClockError, Hlc};
|
||||||
|
pub use id::{Id, IdError};
|
||||||
|
pub use keys::{
|
||||||
|
CERT_DOMAIN, CREDENTIAL_DOMAIN, EVENT_DOMAIN, MnemonicError, PublicKey, REVOKE_DOMAIN, RevokeSigner, RootKey,
|
||||||
|
RootSigner, SignError, Signature, Subkey, verify_credential_sig, verify_event_sig,
|
||||||
|
};
|
||||||
|
pub use merge::{Log, LogEvent, Merged, OrderKey, merge};
|
||||||
|
pub use revoke::{
|
||||||
|
REVOCATION_MAGIC, REVOCATION_PART_MAX, REVOCATION_PARTS_MAX, Revocation, RevocationError, RevocationSet, revoke,
|
||||||
|
};
|
||||||
|
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
/// SHA-256 of `bytes`: the hash in an event's order key.
|
||||||
|
pub fn hash(bytes: &[u8]) -> [u8; 32] {
|
||||||
|
Sha256::digest(bytes).into()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A cursor over bytes being decoded. Every read checks the length; nothing panics.
|
||||||
|
pub(crate) struct Reader<'a> {
|
||||||
|
bytes: &'a [u8],
|
||||||
|
pos: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Reader<'a> {
|
||||||
|
pub(crate) fn new(bytes: &'a [u8]) -> Self {
|
||||||
|
Reader { bytes, pos: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn take(&mut self, n: usize) -> Option<&'a [u8]> {
|
||||||
|
let end = self.pos.checked_add(n)?;
|
||||||
|
let s = self.bytes.get(self.pos..end)?;
|
||||||
|
self.pos = end;
|
||||||
|
Some(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn array<const N: usize>(&mut self) -> Option<[u8; N]> {
|
||||||
|
self.take(N)?.try_into().ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn u8(&mut self) -> Option<u8> {
|
||||||
|
Some(self.take(1)?[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn u64(&mut self) -> Option<u64> {
|
||||||
|
Some(u64::from_be_bytes(self.array()?))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn is_empty(&self) -> bool {
|
||||||
|
self.pos == self.bytes.len()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
//! The deterministic merge of event logs (docs/TESSERA.md §7).
|
||||||
|
|
||||||
|
use crate::{Hlc, PublicKey};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
/// Where an event sits in every log: by clock, then author, then the hash of its bytes.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
|
pub struct OrderKey {
|
||||||
|
pub hlc: Hlc,
|
||||||
|
pub author: PublicKey,
|
||||||
|
/// SHA-256 of the encoded event ([`crate::hash`]).
|
||||||
|
pub hash: [u8; 32],
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An event a log can hold. `order_key` must be derived from `encoded`, so equal bytes give equal keys.
|
||||||
|
pub trait LogEvent {
|
||||||
|
fn order_key(&self) -> OrderKey;
|
||||||
|
fn encoded(&self) -> &[u8];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verified events, each once, sorted by order key.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Log<E> {
|
||||||
|
events: Vec<E>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<E> Default for Log<E> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Log { events: Vec::new() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<E: LogEvent + Clone> Log<E> {
|
||||||
|
pub fn new() -> Log<E> {
|
||||||
|
Log::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A log read back from the app's own storage, whose events were verified when they arrived.
|
||||||
|
/// Sorts and de-duplicates them.
|
||||||
|
pub fn from_stored(events: Vec<E>) -> Log<E> {
|
||||||
|
let map: BTreeMap<OrderKey, E> = events.into_iter().map(|e| (e.order_key(), e)).collect();
|
||||||
|
Log { events: map.into_values().collect() }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn events(&self) -> &[E] {
|
||||||
|
&self.events
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.events.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.events.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contains(&self, hash: &[u8; 32]) -> bool {
|
||||||
|
self.events.iter().any(|e| e.order_key().hash == *hash)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `u32 length ‖ encoded event` for each event, in order.
|
||||||
|
pub fn to_bytes(&self) -> Vec<u8> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for e in &self.events {
|
||||||
|
let b = e.encoded();
|
||||||
|
out.extend_from_slice(&(b.len() as u32).to_be_bytes());
|
||||||
|
out.extend_from_slice(b);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The result of [`merge`].
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Merged<E, R> {
|
||||||
|
pub log: Log<E>,
|
||||||
|
/// How many events were new.
|
||||||
|
pub added: usize,
|
||||||
|
/// Events that failed `verify`, each with its reason. None of them is in `log`.
|
||||||
|
pub rejected: Vec<(E, R)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The union of `log` and the events of `batch` that pass `verify`, de-duplicated and ordered. Events
|
||||||
|
/// already in `log` are not verified again. Any order and any repetition of the same batches gives the same
|
||||||
|
/// log.
|
||||||
|
pub fn merge<E: LogEvent + Clone, R>(
|
||||||
|
log: &Log<E>,
|
||||||
|
batch: impl IntoIterator<Item = E>,
|
||||||
|
mut verify: impl FnMut(&E) -> Result<(), R>,
|
||||||
|
) -> Merged<E, R> {
|
||||||
|
let mut map: BTreeMap<OrderKey, E> = log.events.iter().map(|e| (e.order_key(), e.clone())).collect();
|
||||||
|
let mut added = 0;
|
||||||
|
let mut rejected = Vec::new();
|
||||||
|
for e in batch {
|
||||||
|
let key = e.order_key();
|
||||||
|
if map.contains_key(&key) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match verify(&e) {
|
||||||
|
Ok(()) => {
|
||||||
|
map.insert(key, e);
|
||||||
|
added += 1;
|
||||||
|
}
|
||||||
|
Err(why) => rejected.push((e, why)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Merged { log: Log { events: map.into_values().collect() }, added, rejected }
|
||||||
|
}
|
||||||
@@ -0,0 +1,227 @@
|
|||||||
|
//! Revocation (`TRV1`, docs/TESSERA.md §12, docs/V1_1.md §1): the root withdraws a subkey and names exactly
|
||||||
|
//! which of its events stay valid. Every other event by that subkey is rejected, whatever time it claims, so
|
||||||
|
//! a stolen subkey cannot backdate into its cert's validity.
|
||||||
|
|
||||||
|
use crate::keys::{RevokeSigner, SignError, verify_revocation_sig};
|
||||||
|
use crate::{PublicKey, Reader, Signature};
|
||||||
|
use data_encoding::BASE64URL_NOPAD;
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
|
pub const REVOCATION_MAGIC: &[u8; 4] = b"TRV1";
|
||||||
|
/// Hashes per statement: one statement fits in one event (256 KiB payload) with room to spare.
|
||||||
|
pub const REVOCATION_PART_MAX: usize = 7_000;
|
||||||
|
/// At most this many parts: 1.8 million events per revoked subkey per group.
|
||||||
|
pub const REVOCATION_PARTS_MAX: usize = 256;
|
||||||
|
|
||||||
|
/// One root-signed revocation statement (one part of it, if the list is long).
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Revocation {
|
||||||
|
root: PublicKey,
|
||||||
|
subkey: PublicKey,
|
||||||
|
revoked_at: u64,
|
||||||
|
part: u16,
|
||||||
|
parts: u16,
|
||||||
|
accepted: Vec<[u8; 32]>,
|
||||||
|
sig: Signature,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum RevocationError {
|
||||||
|
#[error("malformed revocation: {0}")]
|
||||||
|
Malformed(&'static str),
|
||||||
|
#[error("the revocation belongs to another identity")]
|
||||||
|
WrongRoot,
|
||||||
|
#[error("the revocation's root is not a member of this group")]
|
||||||
|
UnknownRoot,
|
||||||
|
#[error("the revocation's signature is not valid (tampered)")]
|
||||||
|
BadSignature,
|
||||||
|
#[error("the root did not sign: {0}")]
|
||||||
|
Sign(SignError),
|
||||||
|
#[error("too many events to keep in one revocation")]
|
||||||
|
TooLarge,
|
||||||
|
#[error("written by a revoked key, and not among the events its revocation kept")]
|
||||||
|
Revoked,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tbs(root: &PublicKey, subkey: &PublicKey, revoked_at: u64, part: u16, parts: u16, accepted: &[[u8; 32]]) -> Vec<u8> {
|
||||||
|
let mut out = Vec::with_capacity(4 + 64 + 8 + 4 + 4 + accepted.len() * 32);
|
||||||
|
out.extend_from_slice(REVOCATION_MAGIC);
|
||||||
|
out.extend_from_slice(root.as_bytes());
|
||||||
|
out.extend_from_slice(subkey.as_bytes());
|
||||||
|
out.extend_from_slice(&revoked_at.to_be_bytes());
|
||||||
|
out.extend_from_slice(&part.to_be_bytes());
|
||||||
|
out.extend_from_slice(&parts.to_be_bytes());
|
||||||
|
out.extend_from_slice(&(accepted.len() as u32).to_be_bytes());
|
||||||
|
for h in accepted {
|
||||||
|
out.extend_from_slice(h);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Has `signer` revoke `subkey` at `revoked_at` (Unix seconds), keeping the events whose hashes are in
|
||||||
|
/// `accepted` (deduplicated and sorted here). A long list comes back as several parts, each signed.
|
||||||
|
pub fn revoke(
|
||||||
|
signer: &impl RevokeSigner,
|
||||||
|
subkey: PublicKey,
|
||||||
|
revoked_at: u64,
|
||||||
|
accepted: Vec<[u8; 32]>,
|
||||||
|
) -> Result<Vec<Revocation>, RevocationError> {
|
||||||
|
let sorted: Vec<[u8; 32]> = accepted.into_iter().collect::<BTreeSet<_>>().into_iter().collect();
|
||||||
|
let chunks: Vec<&[[u8; 32]]> =
|
||||||
|
if sorted.is_empty() { vec![&[][..]] } else { sorted.chunks(REVOCATION_PART_MAX).collect() };
|
||||||
|
if chunks.len() > REVOCATION_PARTS_MAX {
|
||||||
|
return Err(RevocationError::TooLarge);
|
||||||
|
}
|
||||||
|
let root = signer.root_public();
|
||||||
|
let parts = chunks.len() as u16;
|
||||||
|
chunks
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, chunk)| {
|
||||||
|
let t = tbs(&root, &subkey, revoked_at, i as u16, parts, chunk);
|
||||||
|
let sig = signer.sign_revocation_tbs(&t).map_err(RevocationError::Sign)?;
|
||||||
|
let r = Revocation { root, subkey, revoked_at, part: i as u16, parts, accepted: chunk.to_vec(), sig };
|
||||||
|
r.verify(&root)?;
|
||||||
|
Ok(r)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Revocation {
|
||||||
|
pub fn root(&self) -> PublicKey {
|
||||||
|
self.root
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn subkey(&self) -> PublicKey {
|
||||||
|
self.subkey
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn revoked_at(&self) -> u64 {
|
||||||
|
self.revoked_at
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This part's hashes, sorted.
|
||||||
|
pub fn accepted(&self) -> &[[u8; 32]] {
|
||||||
|
&self.accepted
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bytes the root signs (after `REVOKE_DOMAIN`).
|
||||||
|
pub fn tbs(&self) -> Vec<u8> {
|
||||||
|
tbs(&self.root, &self.subkey, self.revoked_at, self.part, self.parts, &self.accepted)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks the statement against the root the caller trusts.
|
||||||
|
pub fn verify(&self, root: &PublicKey) -> Result<(), RevocationError> {
|
||||||
|
if self.root != *root {
|
||||||
|
return Err(RevocationError::WrongRoot);
|
||||||
|
}
|
||||||
|
if !verify_revocation_sig(&self.root, &self.tbs(), &self.sig) {
|
||||||
|
return Err(RevocationError::BadSignature);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_bytes(&self) -> Vec<u8> {
|
||||||
|
let mut out = self.tbs();
|
||||||
|
out.extend_from_slice(self.sig.as_bytes());
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// base64url without padding, for JSON (the Custos pipe).
|
||||||
|
pub fn to_text(&self) -> String {
|
||||||
|
BASE64URL_NOPAD.encode(&self.to_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_text(s: &str) -> Result<Revocation, RevocationError> {
|
||||||
|
let b = BASE64URL_NOPAD.decode(s.as_bytes()).map_err(|_| RevocationError::Malformed("not base64url"))?;
|
||||||
|
Revocation::from_bytes(&b)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strict: the magic, every length, sorted unique hashes, a part inside its count, no trailing bytes.
|
||||||
|
pub fn from_bytes(b: &[u8]) -> Result<Revocation, RevocationError> {
|
||||||
|
let m = RevocationError::Malformed;
|
||||||
|
let mut r = Reader::new(b);
|
||||||
|
if r.take(4) != Some(REVOCATION_MAGIC.as_slice()) {
|
||||||
|
return Err(m("not a TRV1 revocation"));
|
||||||
|
}
|
||||||
|
let root = PublicKey::from_bytes(r.array().ok_or(m("truncated"))?);
|
||||||
|
let subkey = PublicKey::from_bytes(r.array().ok_or(m("truncated"))?);
|
||||||
|
let revoked_at = r.u64().ok_or(m("truncated"))?;
|
||||||
|
let part = u16::from_be_bytes(r.array().ok_or(m("truncated"))?);
|
||||||
|
let parts = u16::from_be_bytes(r.array().ok_or(m("truncated"))?);
|
||||||
|
if parts == 0 || part >= parts || parts as usize > REVOCATION_PARTS_MAX {
|
||||||
|
return Err(m("a part outside its count"));
|
||||||
|
}
|
||||||
|
let count = u32::from_be_bytes(r.array().ok_or(m("truncated"))?) as usize;
|
||||||
|
if count > REVOCATION_PART_MAX {
|
||||||
|
return Err(m("too many hashes in one part"));
|
||||||
|
}
|
||||||
|
let mut accepted = Vec::with_capacity(count);
|
||||||
|
for _ in 0..count {
|
||||||
|
let h: [u8; 32] = r.array().ok_or(m("truncated"))?;
|
||||||
|
if accepted.last().is_some_and(|prev: &[u8; 32]| *prev >= h) {
|
||||||
|
return Err(m("hashes not sorted and unique"));
|
||||||
|
}
|
||||||
|
accepted.push(h);
|
||||||
|
}
|
||||||
|
let sig = Signature::from_bytes(r.array().ok_or(m("truncated"))?);
|
||||||
|
if !r.is_empty() {
|
||||||
|
return Err(m("trailing bytes"));
|
||||||
|
}
|
||||||
|
Ok(Revocation { root, subkey, revoked_at, part, parts, accepted, sig })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One statement being collected: its parts so far.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Statement {
|
||||||
|
parts: u16,
|
||||||
|
have: BTreeSet<u16>,
|
||||||
|
accepted: BTreeSet<[u8; 32]>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The revocations a group's log holds, applied to its events. The same statements give the same answers in
|
||||||
|
/// any order: parts of one statement add up, separate statements for one subkey keep only what all keep.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct RevocationSet {
|
||||||
|
/// (subkey, revoked_at, parts) → the statement's parts.
|
||||||
|
statements: BTreeMap<(PublicKey, u64, u16), Statement>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RevocationSet {
|
||||||
|
/// Adds one part, after checking it is signed by its root and that the root is one of the group's.
|
||||||
|
pub fn add(&mut self, r: Revocation, group_roots: &[PublicKey]) -> Result<(), RevocationError> {
|
||||||
|
if !group_roots.contains(&r.root) {
|
||||||
|
return Err(RevocationError::UnknownRoot);
|
||||||
|
}
|
||||||
|
r.verify(&r.root)?;
|
||||||
|
let s = self.statements.entry((r.subkey, r.revoked_at, r.parts)).or_default();
|
||||||
|
s.parts = r.parts;
|
||||||
|
s.have.insert(r.part);
|
||||||
|
s.accepted.extend(r.accepted);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn complete(&self, subkey: &PublicKey) -> impl Iterator<Item = &Statement> {
|
||||||
|
self.statements
|
||||||
|
.iter()
|
||||||
|
.filter(move |((k, _, _), s)| k == subkey && s.have.len() == s.parts as usize)
|
||||||
|
.map(|(_, s)| s)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a complete revocation of `subkey` is in force.
|
||||||
|
pub fn is_revoked(&self, subkey: &PublicKey) -> bool {
|
||||||
|
self.complete(subkey).next().is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the event `hash` by `author` stays valid: yes unless a complete revocation of `author` is in
|
||||||
|
/// force and does not list it (every one in force must list it).
|
||||||
|
pub fn check(&self, author: &PublicKey, hash: &[u8; 32]) -> Result<(), RevocationError> {
|
||||||
|
for s in self.complete(author) {
|
||||||
|
if !s.accepted.contains(hash) {
|
||||||
|
return Err(RevocationError::Revoked);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,332 @@
|
|||||||
|
//! The mandatory tests for tessera (docs/TESSERA.md). Written before the code.
|
||||||
|
|
||||||
|
use proptest::prelude::*;
|
||||||
|
use tessera::{
|
||||||
|
CertError, CertRequest, Clock, ClockError, Hlc, Id, Log, LogEvent, OrderKey, PublicKey, RootKey, RootSigner,
|
||||||
|
Subkey, SubkeyCert, certify, match_code, merge,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// `abandon` × 23 + `art`: the BIP39 mnemonic of 32 zero bytes.
|
||||||
|
const ZERO_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
|
||||||
|
abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art";
|
||||||
|
/// Its root public key (docs/TESSERA.md §9). CustosPublic pins the same value.
|
||||||
|
const ROOT_PUB_ZERO: &str = "vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs";
|
||||||
|
/// The match code of the subkey `07` × 32.
|
||||||
|
const MATCH_SEVENS: &str = "016810";
|
||||||
|
|
||||||
|
const DAY: u64 = 86_400;
|
||||||
|
const NOW: u64 = 1_793_000_000;
|
||||||
|
|
||||||
|
fn root() -> RootKey {
|
||||||
|
RootKey::from_mnemonic(ZERO_MNEMONIC).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn other_root() -> RootKey {
|
||||||
|
RootKey::from_mnemonic(
|
||||||
|
"legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful \
|
||||||
|
legal winner thank year wave sausage worth title",
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request(sub: &Subkey) -> CertRequest {
|
||||||
|
CertRequest {
|
||||||
|
subkey: sub.public(),
|
||||||
|
app_id: Id::new("fiscus").unwrap(),
|
||||||
|
purpose: Id::new("sync").unwrap(),
|
||||||
|
not_before: NOW - DAY,
|
||||||
|
not_after: NOW + 365 * DAY,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- mnemonic round trip ----------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_same_mnemonic_gives_the_same_root_every_time() {
|
||||||
|
let a = root().public();
|
||||||
|
for _ in 0..3 {
|
||||||
|
assert_eq!(root().public(), a);
|
||||||
|
}
|
||||||
|
assert_eq!(a.to_string(), ROOT_PUB_ZERO, "the pinned vector");
|
||||||
|
// Spacing and case do not change the words.
|
||||||
|
let messy = format!(" {} ", ZERO_MNEMONIC.to_uppercase().replace(' ', " "));
|
||||||
|
assert_eq!(RootKey::from_mnemonic(&messy).unwrap().public(), a);
|
||||||
|
assert_ne!(other_root().public(), a);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wrong_mnemonic_is_refused() {
|
||||||
|
let bad_checksum = ZERO_MNEMONIC.replace(" art", " abandon");
|
||||||
|
assert!(RootKey::from_mnemonic(&bad_checksum).is_err());
|
||||||
|
assert!(RootKey::from_mnemonic("abandon abandon").is_err());
|
||||||
|
assert!(RootKey::from_mnemonic(&ZERO_MNEMONIC.replace(" art", " notaword")).is_err());
|
||||||
|
// 12 words is a valid BIP39 mnemonic, but a Domi root is always 24.
|
||||||
|
let twelve = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
|
||||||
|
assert!(RootKey::from_mnemonic(twelve).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- certificates ----------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_valid_cert_passes_and_round_trips() {
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
let cert = certify(&root(), &request(&sub)).unwrap();
|
||||||
|
assert_eq!(cert.verify(&root().public(), NOW), Ok(()));
|
||||||
|
let back = SubkeyCert::from_bytes(&cert.to_bytes()).unwrap();
|
||||||
|
assert_eq!(back, cert);
|
||||||
|
assert_eq!(back.subkey(), sub.public());
|
||||||
|
assert_eq!(back.app_id().as_str(), "fiscus");
|
||||||
|
assert_eq!(back.purpose().as_str(), "sync");
|
||||||
|
assert_eq!(SubkeyCert::from_text(&cert.to_text()).unwrap(), cert);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn expired_and_not_yet_valid_certs_are_rejected() {
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
let cert = certify(&root(), &request(&sub)).unwrap();
|
||||||
|
let r = root().public();
|
||||||
|
assert_eq!(cert.verify(&r, NOW - DAY - 1), Err(CertError::NotYetValid));
|
||||||
|
assert_eq!(cert.verify(&r, NOW - DAY), Ok(()), "not_before is inclusive");
|
||||||
|
assert_eq!(cert.verify(&r, NOW + 365 * DAY - 1), Ok(()));
|
||||||
|
assert_eq!(cert.verify(&r, NOW + 365 * DAY), Err(CertError::Expired), "not_after is exclusive");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cert_from_another_root_is_rejected() {
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
let cert = certify(&other_root(), &request(&sub)).unwrap();
|
||||||
|
assert_eq!(cert.verify(&root().public(), NOW), Err(CertError::WrongRoot));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_tampered_byte_is_rejected() {
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
let cert = certify(&root(), &request(&sub)).unwrap();
|
||||||
|
let bytes = cert.to_bytes();
|
||||||
|
for i in 0..bytes.len() {
|
||||||
|
for bit in 0..8 {
|
||||||
|
let mut b = bytes.clone();
|
||||||
|
b[i] ^= 1 << bit;
|
||||||
|
if let Ok(c) = SubkeyCert::from_bytes(&b) {
|
||||||
|
assert!(c.verify(&root().public(), NOW).is_err(), "byte {i} bit {bit} accepted");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_signer_claiming_another_root_cannot_make_a_valid_cert() {
|
||||||
|
// A RootSigner whose public key does not match its signatures.
|
||||||
|
struct Liar(RootKey, PublicKey);
|
||||||
|
impl RootSigner for Liar {
|
||||||
|
fn root_public(&self) -> PublicKey {
|
||||||
|
self.1
|
||||||
|
}
|
||||||
|
fn sign_cert_tbs(&self, tbs: &[u8]) -> Result<tessera::Signature, tessera::SignError> {
|
||||||
|
self.0.sign_cert_tbs(tbs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
let liar = Liar(other_root(), root().public());
|
||||||
|
assert!(certify(&liar, &request(&sub)).is_err(), "certify checks the signature it got back");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_root_key_signs_only_cert_shaped_messages() {
|
||||||
|
assert!(root().sign_cert_tbs(b"pay 100 CZK to mallory").is_err());
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
// A tbs naming another root is refused too.
|
||||||
|
let tbs = request(&sub).tbs(&other_root().public());
|
||||||
|
assert!(root().sign_cert_tbs(&tbs).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn malformed_certs_are_rejected_on_decoding() {
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
let good = certify(&root(), &request(&sub)).unwrap().to_bytes();
|
||||||
|
assert!(SubkeyCert::from_bytes(&good[..good.len() - 1]).is_err());
|
||||||
|
let mut long = good.clone();
|
||||||
|
long.push(0);
|
||||||
|
assert!(SubkeyCert::from_bytes(&long).is_err(), "trailing bytes");
|
||||||
|
let mut magic = good.clone();
|
||||||
|
magic[0] = b'X';
|
||||||
|
assert!(SubkeyCert::from_bytes(&magic).is_err());
|
||||||
|
let mut empty_validity = request(&sub);
|
||||||
|
empty_validity.not_after = empty_validity.not_before;
|
||||||
|
assert!(certify(&root(), &empty_validity).is_err());
|
||||||
|
for bad in ["", "Fiscus", "-fiscus", "fiscus-", "fis cus", "fiscus/x", &"a".repeat(33)] {
|
||||||
|
assert!(Id::new(bad).is_err(), "{bad:?}");
|
||||||
|
}
|
||||||
|
assert!(Id::new(&"a".repeat(32)).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- match code ----------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn match_code_vector() {
|
||||||
|
let code = match_code(&PublicKey::from_bytes([7; 32]));
|
||||||
|
assert_eq!(code.len(), 6);
|
||||||
|
assert!(code.bytes().all(|b| b.is_ascii_digit()));
|
||||||
|
assert_eq!(code, MATCH_SEVENS);
|
||||||
|
assert_ne!(match_code(&PublicKey::from_bytes([8; 32])), code);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- secrets stay secret ----------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn event_and_credential_signatures_do_not_cross() {
|
||||||
|
let sub = Subkey::from_seed(&[1; 32]);
|
||||||
|
let sig = sub.sign_credential_tbs(b"keys");
|
||||||
|
assert!(tessera::verify_credential_sig(&sub.public(), b"keys", &sig));
|
||||||
|
assert!(!tessera::verify_event_sig(&sub.public(), b"keys", &sig), "a credential signature is never an event");
|
||||||
|
let ev = sub.sign_event_tbs(b"keys");
|
||||||
|
assert!(!tessera::verify_credential_sig(&sub.public(), b"keys", &ev));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn secret_types_print_redacted() {
|
||||||
|
let s = format!("{:?} {:?}", root(), Subkey::from_seed(&[1; 32]));
|
||||||
|
assert_eq!(s, "RootKey([redacted]) Subkey([redacted])");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- hybrid logical clock ----------
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_clock_never_goes_backwards() {
|
||||||
|
let mut c = Clock::default();
|
||||||
|
let a = c.tick(1000).unwrap();
|
||||||
|
let b = c.tick(1000).unwrap();
|
||||||
|
let d = c.tick(500).unwrap(); // the wall clock jumped back
|
||||||
|
let e = c.tick(2000).unwrap();
|
||||||
|
assert!(a < b && b < d && d < e);
|
||||||
|
assert_eq!(e, Hlc { wall: 2000, logical: 0 });
|
||||||
|
assert_eq!(Hlc::from_bytes(&e.to_bytes()), e);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_clock_follows_a_remote_clock_within_the_drift() {
|
||||||
|
let mut c = Clock::with_max_drift(60_000);
|
||||||
|
c.tick(1000).unwrap();
|
||||||
|
let remote = Hlc { wall: 5000, logical: 7 };
|
||||||
|
let seen = c.observe(remote, 1000).unwrap();
|
||||||
|
assert!(seen > remote);
|
||||||
|
assert!(c.tick(1000).unwrap() > seen);
|
||||||
|
assert_eq!(c.observe(Hlc { wall: 1000 + 60_001, logical: 0 }, 1000), Err(ClockError::TooFarAhead));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_logical_counter_does_not_wrap() {
|
||||||
|
let mut c = Clock::default();
|
||||||
|
c.observe(Hlc { wall: 10, logical: u32::MAX - 1 }, 10).unwrap();
|
||||||
|
assert_eq!(c.tick(10), Err(ClockError::Overflow));
|
||||||
|
// A later wall clock resets the counter.
|
||||||
|
assert_eq!(c.tick(11), Ok(Hlc { wall: 11, logical: 0 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- merge ----------
|
||||||
|
|
||||||
|
/// A minimal event: its bytes, an author and a clock. Valid unless `bad`.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
struct Ev {
|
||||||
|
bytes: Vec<u8>,
|
||||||
|
key: OrderKey,
|
||||||
|
bad: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ev {
|
||||||
|
fn new(author: u8, wall: u64, logical: u32, body: u8, bad: bool) -> Ev {
|
||||||
|
let bytes = vec![author, (wall % 256) as u8, logical as u8, body, bad as u8];
|
||||||
|
let key = OrderKey {
|
||||||
|
hlc: Hlc { wall, logical },
|
||||||
|
author: PublicKey::from_bytes([author; 32]),
|
||||||
|
hash: tessera::hash(&bytes),
|
||||||
|
};
|
||||||
|
Ev { bytes, key, bad }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LogEvent for Ev {
|
||||||
|
fn order_key(&self) -> OrderKey {
|
||||||
|
self.key
|
||||||
|
}
|
||||||
|
fn encoded(&self) -> &[u8] {
|
||||||
|
&self.bytes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check(e: &Ev) -> Result<(), &'static str> {
|
||||||
|
if e.bad { Err("bad signature") } else { Ok(()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn arb_events() -> impl Strategy<Value = Vec<Ev>> {
|
||||||
|
// Few authors and clocks, so ties on (hlc, author) happen and the hash decides.
|
||||||
|
prop::collection::vec((0u8..3, 0u64..4, 0u32..2, any::<u8>(), prop::bool::weighted(0.15)), 1..40)
|
||||||
|
.prop_map(|v| v.into_iter().map(|(a, w, l, b, bad)| Ev::new(a, w, l, b, bad)).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Merges `batches` into an empty log one after another.
|
||||||
|
fn merge_all(batches: &[Vec<Ev>]) -> Log<Ev> {
|
||||||
|
let mut log = Log::new();
|
||||||
|
for b in batches {
|
||||||
|
log = merge(&log, b.iter().cloned(), check).log;
|
||||||
|
}
|
||||||
|
log
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig::with_cases(256))]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn merge_is_order_independent_and_idempotent(
|
||||||
|
events in arb_events(),
|
||||||
|
split in prop::collection::vec(0usize..4, 40),
|
||||||
|
perm_seed in any::<u64>(),
|
||||||
|
dups in prop::collection::vec(any::<prop::sample::Index>(), 0..10),
|
||||||
|
) {
|
||||||
|
// Split into up to 4 batches, then shuffle the batches and the events in them, and duplicate some.
|
||||||
|
let mut batches: Vec<Vec<Ev>> = vec![Vec::new(); 4];
|
||||||
|
for (i, e) in events.iter().enumerate() {
|
||||||
|
batches[split[i % split.len()]].push(e.clone());
|
||||||
|
}
|
||||||
|
for d in &dups {
|
||||||
|
let e = d.get(&events).clone();
|
||||||
|
batches[d.index(4)].push(e);
|
||||||
|
}
|
||||||
|
let reference = merge_all(std::slice::from_ref(&events));
|
||||||
|
|
||||||
|
let mut shuffled = batches.clone();
|
||||||
|
let mut s = perm_seed;
|
||||||
|
for b in shuffled.iter_mut() {
|
||||||
|
for i in (1..b.len()).rev() {
|
||||||
|
s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||||
|
b.swap(i, (s >> 33) as usize % (i + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
shuffled.rotate_left((perm_seed % 4) as usize);
|
||||||
|
let merged = merge_all(&shuffled);
|
||||||
|
prop_assert_eq!(merged.to_bytes(), reference.to_bytes());
|
||||||
|
|
||||||
|
// Merging everything again changes nothing.
|
||||||
|
let again = merge(&merged, batches.concat(), check);
|
||||||
|
prop_assert_eq!(again.added, 0);
|
||||||
|
prop_assert_eq!(again.log.to_bytes(), reference.to_bytes());
|
||||||
|
|
||||||
|
// Only valid events, each once, in order-key order.
|
||||||
|
let keys: Vec<OrderKey> = merged.events().iter().map(|e| e.order_key()).collect();
|
||||||
|
prop_assert!(keys.windows(2).all(|w| w[0] < w[1]));
|
||||||
|
prop_assert!(merged.events().iter().all(|e| !e.bad));
|
||||||
|
let valid: std::collections::BTreeSet<_> = events.iter().filter(|e| !e.bad).map(|e| e.key.hash).collect();
|
||||||
|
prop_assert_eq!(merged.len(), valid.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejected_events_come_back_with_their_reason() {
|
||||||
|
let good = Ev::new(1, 1, 0, 1, false);
|
||||||
|
let bad = Ev::new(1, 2, 0, 2, true);
|
||||||
|
let m = merge(&Log::new(), vec![good.clone(), bad.clone(), bad.clone()], check);
|
||||||
|
assert_eq!(m.added, 1);
|
||||||
|
assert_eq!(m.log.len(), 1);
|
||||||
|
assert_eq!(m.rejected.len(), 2);
|
||||||
|
assert!(m.rejected.iter().all(|(e, why)| e.key == bad.key && *why == "bad signature"));
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
//! v1.1a: revocation (`TRV1`, docs/V1_1.md §1) and the backup secret (§3).
|
||||||
|
//!
|
||||||
|
//! - A revocation is root-signed in its own domain; the root's signer refuses to sign it as a cert and the
|
||||||
|
//! other way round.
|
||||||
|
//! - It keeps exactly the listed events of the revoked subkey; every other event by that subkey is
|
||||||
|
//! rejected, whatever time it claims. Unrelated authors are untouched.
|
||||||
|
//! - Split statements count only when complete; the result does not depend on the order they arrive in;
|
||||||
|
//! two statements for one subkey keep only what both keep.
|
||||||
|
//! - The backup secret is the same from the 24 words every time, differs per app, and seals so that only
|
||||||
|
//! the same secret opens.
|
||||||
|
|
||||||
|
use proptest::prelude::*;
|
||||||
|
use tessera::{
|
||||||
|
BackupSecret, CertRequest, Id, PublicKey, Revocation, RevocationError, RevocationSet, RevokeSigner, RootKey,
|
||||||
|
RootSigner, Subkey, hash, revoke,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn root(n: u8) -> RootKey {
|
||||||
|
let m = bip39::Mnemonic::from_entropy(&[n; 32]).unwrap();
|
||||||
|
RootKey::from_mnemonic(&m.to_string()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn h(n: u32) -> [u8; 32] {
|
||||||
|
hash(&n.to_be_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
const T: u64 = 1_793_700_000;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_revocation_round_trips_and_verifies_under_its_root() {
|
||||||
|
let r = root(1);
|
||||||
|
let sub = Subkey::from_seed(&[5; 32]).public();
|
||||||
|
let parts = revoke(&r, sub, T, vec![h(3), h(1), h(2), h(1)]).unwrap();
|
||||||
|
assert_eq!(parts.len(), 1);
|
||||||
|
let p = &parts[0];
|
||||||
|
assert_eq!((p.root(), p.subkey(), p.revoked_at()), (r.public(), sub, T));
|
||||||
|
assert_eq!(
|
||||||
|
p.accepted(),
|
||||||
|
&[h(1), h(2), h(3)].iter().copied().collect::<std::collections::BTreeSet<_>>().into_iter().collect::<Vec<_>>()
|
||||||
|
);
|
||||||
|
let back = Revocation::from_bytes(&p.to_bytes()).unwrap();
|
||||||
|
assert_eq!(&back, p);
|
||||||
|
assert!(back.verify(&r.public()).is_ok());
|
||||||
|
assert_eq!(back.verify(&root(2).public()), Err(RevocationError::WrongRoot));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_tampered_or_malformed_revocation_is_refused() {
|
||||||
|
let r = root(1);
|
||||||
|
let bytes = revoke(&r, Subkey::from_seed(&[5; 32]).public(), T, vec![h(1)]).unwrap()[0].to_bytes();
|
||||||
|
for i in [5, 40, 70, 80, bytes.len() - 1] {
|
||||||
|
let mut b = bytes.clone();
|
||||||
|
b[i] ^= 1;
|
||||||
|
let bad = Revocation::from_bytes(&b).map(|x| x.verify(&r.public()));
|
||||||
|
assert!(!matches!(bad, Ok(Ok(()))), "flip at {i} still verifies");
|
||||||
|
}
|
||||||
|
for cut in 0..bytes.len() {
|
||||||
|
assert!(Revocation::from_bytes(&bytes[..cut]).is_err(), "a truncation at {cut} decoded");
|
||||||
|
}
|
||||||
|
let mut extra = bytes.clone();
|
||||||
|
extra.push(0);
|
||||||
|
assert!(Revocation::from_bytes(&extra).is_err(), "trailing bytes");
|
||||||
|
let mut as_cert = bytes;
|
||||||
|
as_cert[..4].copy_from_slice(b"TSC1");
|
||||||
|
assert!(Revocation::from_bytes(&as_cert).is_err(), "a cert is not a revocation");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_root_signs_a_revocation_and_a_cert_only_in_their_own_domains() {
|
||||||
|
let r = root(1);
|
||||||
|
let sub = Subkey::from_seed(&[5; 32]).public();
|
||||||
|
let req = CertRequest::standard(sub, Id::new("fiscus").unwrap(), Id::new("sync").unwrap(), T);
|
||||||
|
let cert_tbs = req.tbs(&r.public());
|
||||||
|
assert!(r.sign_revocation_tbs(&cert_tbs).is_err(), "a cert's tbs is not signed as a revocation");
|
||||||
|
let rev_tbs = revoke(&r, sub, T, vec![]).unwrap()[0].tbs();
|
||||||
|
assert!(r.sign_cert_tbs(&rev_tbs).is_err(), "a revocation's tbs is not signed as a cert");
|
||||||
|
let other = revoke(&root(2), sub, T, vec![]).unwrap()[0].tbs();
|
||||||
|
assert!(r.sign_revocation_tbs(&other).is_err(), "a root signs only revocations that name it");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_the_listed_events_of_a_revoked_subkey_stay_valid() {
|
||||||
|
let r = root(1);
|
||||||
|
let lost = Subkey::from_seed(&[5; 32]).public();
|
||||||
|
let other = Subkey::from_seed(&[6; 32]).public();
|
||||||
|
let mut set = RevocationSet::default();
|
||||||
|
for p in revoke(&r, lost, T, vec![h(1), h(2)]).unwrap() {
|
||||||
|
set.add(p, &[r.public()]).unwrap();
|
||||||
|
}
|
||||||
|
assert!(set.check(&lost, &h(1)).is_ok());
|
||||||
|
assert!(set.check(&lost, &h(2)).is_ok());
|
||||||
|
assert!(set.check(&lost, &h(3)).is_err(), "written after, or backdated: rejected either way");
|
||||||
|
assert!(set.check(&other, &h(3)).is_ok(), "other authors are untouched");
|
||||||
|
assert!(set.is_revoked(&lost) && !set.is_revoked(&other));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_revocation_from_a_root_outside_the_group_is_refused() {
|
||||||
|
let lost = Subkey::from_seed(&[5; 32]).public();
|
||||||
|
let mut set = RevocationSet::default();
|
||||||
|
let p = revoke(&root(9), lost, T, vec![]).unwrap().remove(0);
|
||||||
|
assert_eq!(set.add(p, &[root(1).public()]), Err(RevocationError::UnknownRoot));
|
||||||
|
assert!(set.check(&lost, &h(1)).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_long_list_is_split_and_counts_only_when_complete() {
|
||||||
|
let r = root(1);
|
||||||
|
let lost = Subkey::from_seed(&[5; 32]).public();
|
||||||
|
let kept: Vec<[u8; 32]> = (0..tessera::REVOCATION_PART_MAX as u32 * 2 + 10).map(h).collect();
|
||||||
|
let parts = revoke(&r, lost, T, kept.clone()).unwrap();
|
||||||
|
assert_eq!(parts.len(), 3);
|
||||||
|
for p in &parts {
|
||||||
|
assert!(p.to_bytes().len() < 240 * 1024, "a part fits in one event");
|
||||||
|
}
|
||||||
|
let mut set = RevocationSet::default();
|
||||||
|
set.add(parts[0].clone(), &[r.public()]).unwrap();
|
||||||
|
set.add(parts[2].clone(), &[r.public()]).unwrap();
|
||||||
|
assert!(set.check(&lost, &h(u32::MAX)).is_ok(), "incomplete: not in force yet");
|
||||||
|
set.add(parts[1].clone(), &[r.public()]).unwrap();
|
||||||
|
assert!(set.check(&lost, &h(u32::MAX)).is_err(), "complete: in force");
|
||||||
|
assert!(kept.iter().all(|k| set.check(&lost, k).is_ok()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn two_revocations_of_one_subkey_keep_only_what_both_keep() {
|
||||||
|
let r = root(1);
|
||||||
|
let lost = Subkey::from_seed(&[5; 32]).public();
|
||||||
|
let mut set = RevocationSet::default();
|
||||||
|
for p in revoke(&r, lost, T, vec![h(1), h(2), h(3)]).unwrap() {
|
||||||
|
set.add(p, &[r.public()]).unwrap();
|
||||||
|
}
|
||||||
|
for p in revoke(&r, lost, T + 60, vec![h(2), h(3), h(4)]).unwrap() {
|
||||||
|
set.add(p, &[r.public()]).unwrap();
|
||||||
|
}
|
||||||
|
let kept: Vec<u32> = (1..=4).filter(|n| set.check(&lost, &h(*n)).is_ok()).collect();
|
||||||
|
assert_eq!(kept, vec![2, 3], "a later statement never widens what is kept");
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#[test]
|
||||||
|
fn the_result_does_not_depend_on_arrival_order(seed in any::<u64>(), keep in proptest::collection::vec(0u32..40, 0..30)) {
|
||||||
|
let r = root(1);
|
||||||
|
let lost = Subkey::from_seed(&[5; 32]).public();
|
||||||
|
let mut parts = revoke(&r, lost, T, keep.iter().map(|n| h(*n)).collect()).unwrap();
|
||||||
|
parts.extend(revoke(&r, lost, T + 1, (0..40).filter(|n| n % 3 != 0).map(h).collect()).unwrap());
|
||||||
|
let build = |order: &[Revocation]| {
|
||||||
|
let mut set = RevocationSet::default();
|
||||||
|
for p in order {
|
||||||
|
set.add(p.clone(), &[r.public()]).unwrap();
|
||||||
|
}
|
||||||
|
(0..40).map(|n| set.check(&lost, &h(n)).is_ok()).collect::<Vec<_>>()
|
||||||
|
};
|
||||||
|
let a = build(&parts);
|
||||||
|
let mut shuffled = parts.clone();
|
||||||
|
let mut s = seed;
|
||||||
|
for i in (1..shuffled.len()).rev() {
|
||||||
|
s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||||
|
shuffled.swap(i, (s >> 33) as usize % (i + 1));
|
||||||
|
}
|
||||||
|
prop_assert_eq!(a, build(&shuffled));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_backup_secret_comes_back_from_the_words_and_differs_per_app() {
|
||||||
|
let fiscus = Id::new("fiscus").unwrap();
|
||||||
|
let a = root(1).backup_secret(&fiscus);
|
||||||
|
let b = root(1).backup_secret(&fiscus);
|
||||||
|
let other_app = root(1).backup_secret(&Id::new("calenda").unwrap());
|
||||||
|
let other_person = root(2).backup_secret(&fiscus);
|
||||||
|
let nonce = [7u8; 24];
|
||||||
|
let sealed = a.seal(&nonce, b"aad", b"the self group's log");
|
||||||
|
assert_eq!(b.open(b"aad", &sealed).as_deref(), Some(b"the self group's log".as_slice()));
|
||||||
|
assert_eq!(b.open(b"other aad", &sealed), None);
|
||||||
|
assert_eq!(other_app.open(b"aad", &sealed), None);
|
||||||
|
assert_eq!(other_person.open(b"aad", &sealed), None);
|
||||||
|
assert!(!sealed.windows(4).any(|w| w == b"self"), "sealed, not readable");
|
||||||
|
assert_ne!(*a.mailbox_seed(), *other_app.mailbox_seed());
|
||||||
|
assert_eq!(*a.mailbox_seed(), *b.mailbox_seed());
|
||||||
|
// An app gets the 32 bytes from Custos; nothing reads them back out.
|
||||||
|
let from_custos = BackupSecret::from_bytes([1u8; 32]);
|
||||||
|
assert_eq!(from_custos.open(b"", &from_custos.seal(&nonce, b"", b"x")).as_deref(), Some(b"x".as_slice()));
|
||||||
|
assert_eq!(format!("{from_custos:?}"), "BackupSecret([redacted])");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_backup_secret_test_vector() {
|
||||||
|
// docs/TESSERA.md §12: the zero-entropy mnemonic, app "fiscus". Custos derives the same.
|
||||||
|
let s = root(0).backup_secret(&Id::new("fiscus").unwrap());
|
||||||
|
let mailbox = data_encoding::BASE64URL_NOPAD.encode(s.mailbox_seed().as_ref());
|
||||||
|
let sealed = data_encoding::BASE64URL_NOPAD.encode(&s.seal(&[0u8; 24], b"", b""));
|
||||||
|
assert_eq!((mailbox.as_str(), sealed.as_str()), (VECTOR_MAILBOX, VECTOR_SEALED_EMPTY));
|
||||||
|
}
|
||||||
|
|
||||||
|
const VECTOR_MAILBOX: &str = "IygCOrh-ibO6-KY5AXQ9Prl2SyPWQIyZZ-anffcbMCU";
|
||||||
|
const VECTOR_SEALED_EMPTY: &str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAci_JRbtsx5prR83KT9Y7LA";
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
fn _signer_bound(_: &impl RevokeSigner) {}
|
||||||
|
#[allow(dead_code)]
|
||||||
|
fn _root_signer(_: &impl RootSigner) {}
|
||||||
|
#[allow(dead_code)]
|
||||||
|
fn _key(_: PublicKey) {}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
//! No key export: no public API of tessera returns private key bytes.
|
||||||
|
//!
|
||||||
|
//! - Compile time: the secret types implement none of the traits that would hand out their bytes.
|
||||||
|
//! - The API surface is locked: every `pub fn` in `src/` is listed here. A new public function fails this
|
||||||
|
//! test until someone has checked that it returns no secret and added it to the list.
|
||||||
|
|
||||||
|
use static_assertions::assert_not_impl_any;
|
||||||
|
use tessera::{RootKey, Subkey};
|
||||||
|
|
||||||
|
assert_not_impl_any!(RootKey: Clone, AsRef<[u8]>, std::ops::Deref, Into<[u8; 32]>, Into<Vec<u8>>, std::fmt::Display);
|
||||||
|
assert_not_impl_any!(Subkey: Clone, AsRef<[u8]>, std::ops::Deref, Into<[u8; 32]>, Into<Vec<u8>>, std::fmt::Display);
|
||||||
|
|
||||||
|
/// Every public function, as `file: signature` with whitespace collapsed. Each returns only public data.
|
||||||
|
const SURFACE: &[&str] = &[
|
||||||
|
"backup.rs: pub fn from_bytes(b: [u8; 32]) -> BackupSecret",
|
||||||
|
"backup.rs: pub fn mailbox_seed(&self) -> Zeroizing<[u8; 32]>",
|
||||||
|
"backup.rs: pub fn open(&self, aad: &[u8], sealed: &[u8]) -> Option<Vec<u8>>",
|
||||||
|
"backup.rs: pub fn seal(&self, nonce: &[u8; 24], aad: &[u8], plain: &[u8]) -> Vec<u8>",
|
||||||
|
"cert.rs: pub fn app_id(&self) -> &Id",
|
||||||
|
"cert.rs: pub fn certify(signer: &impl RootSigner, req: &CertRequest) -> Result<SubkeyCert, CertError>",
|
||||||
|
"cert.rs: pub fn from_bytes(b: &[u8]) -> Result<SubkeyCert, CertError>",
|
||||||
|
"cert.rs: pub fn from_text(s: &str) -> Result<SubkeyCert, CertError>",
|
||||||
|
"cert.rs: pub fn match_code(subkey: &PublicKey) -> String",
|
||||||
|
"cert.rs: pub fn not_after(&self) -> u64",
|
||||||
|
"cert.rs: pub fn not_before(&self) -> u64",
|
||||||
|
"cert.rs: pub fn purpose(&self) -> &Id",
|
||||||
|
"cert.rs: pub fn root(&self) -> PublicKey",
|
||||||
|
"cert.rs: pub fn standard(subkey: PublicKey, app_id: Id, purpose: Id, now: u64) -> CertRequest",
|
||||||
|
"cert.rs: pub fn subkey(&self) -> PublicKey",
|
||||||
|
"cert.rs: pub fn tbs(&self, root: &PublicKey) -> Vec<u8>",
|
||||||
|
"cert.rs: pub fn to_bytes(&self) -> Vec<u8>",
|
||||||
|
"cert.rs: pub fn to_text(&self) -> String",
|
||||||
|
"cert.rs: pub fn verify(&self, root: &PublicKey, now: u64) -> Result<(), CertError>",
|
||||||
|
"hlc.rs: pub fn from_bytes(b: &[u8; 12]) -> Hlc",
|
||||||
|
"hlc.rs: pub fn last(&self) -> Hlc",
|
||||||
|
"hlc.rs: pub fn observe(&mut self, remote: Hlc, now: u64) -> Result<Hlc, ClockError>",
|
||||||
|
"hlc.rs: pub fn tick(&mut self, now: u64) -> Result<Hlc, ClockError>",
|
||||||
|
"hlc.rs: pub fn to_bytes(&self) -> [u8; 12]",
|
||||||
|
"hlc.rs: pub fn with_max_drift(max_drift_ms: u64) -> Clock",
|
||||||
|
"id.rs: pub fn as_str(&self) -> &str",
|
||||||
|
"id.rs: pub fn new(s: &str) -> Result<Id, IdError>",
|
||||||
|
"keys.rs: pub fn as_bytes(&self) -> &[u8; 32]",
|
||||||
|
"keys.rs: pub fn backup_secret(&self, app_id: &crate::Id) -> crate::BackupSecret",
|
||||||
|
"keys.rs: pub fn as_bytes(&self) -> &[u8; 64]",
|
||||||
|
"keys.rs: pub fn from_bytes(b: [u8; 32]) -> PublicKey",
|
||||||
|
"keys.rs: pub fn from_bytes(b: [u8; 64]) -> Signature",
|
||||||
|
"keys.rs: pub fn from_mnemonic(phrase: &str) -> Result<RootKey, MnemonicError>",
|
||||||
|
"keys.rs: pub fn from_seed(seed: &[u8; 32]) -> Subkey",
|
||||||
|
"keys.rs: pub fn from_text(s: &str) -> Option<PublicKey>",
|
||||||
|
"keys.rs: pub fn public(&self) -> PublicKey",
|
||||||
|
"keys.rs: pub fn public(&self) -> PublicKey",
|
||||||
|
"keys.rs: pub fn sign_credential_tbs(&self, tbs: &[u8]) -> Signature",
|
||||||
|
"keys.rs: pub fn sign_event_tbs(&self, tbs: &[u8]) -> Signature",
|
||||||
|
"keys.rs: pub fn verify_credential_sig(subkey: &PublicKey, tbs: &[u8], sig: &Signature) -> bool",
|
||||||
|
"keys.rs: pub fn verify_event_sig(author: &PublicKey, tbs: &[u8], sig: &Signature) -> bool",
|
||||||
|
"lib.rs: pub fn hash(bytes: &[u8]) -> [u8; 32]",
|
||||||
|
"merge.rs: pub fn contains(&self, hash: &[u8; 32]) -> bool",
|
||||||
|
"merge.rs: pub fn events(&self) -> &[E]",
|
||||||
|
"merge.rs: pub fn from_stored(events: Vec<E>) -> Log<E>",
|
||||||
|
"merge.rs: pub fn is_empty(&self) -> bool",
|
||||||
|
"merge.rs: pub fn len(&self) -> usize",
|
||||||
|
"merge.rs: pub fn merge<E: LogEvent + Clone, R>( log: &Log<E>, batch: impl IntoIterator<Item = E>, mut verify: impl FnMut(&E) -> Result<(), R>, ) -> Merged<E, R>",
|
||||||
|
"merge.rs: pub fn new() -> Log<E>",
|
||||||
|
"merge.rs: pub fn to_bytes(&self) -> Vec<u8>",
|
||||||
|
"revoke.rs: pub fn accepted(&self) -> &[[u8; 32]]",
|
||||||
|
"revoke.rs: pub fn add(&mut self, r: Revocation, group_roots: &[PublicKey]) -> Result<(), RevocationError>",
|
||||||
|
"revoke.rs: pub fn check(&self, author: &PublicKey, hash: &[u8; 32]) -> Result<(), RevocationError>",
|
||||||
|
"revoke.rs: pub fn from_bytes(b: &[u8]) -> Result<Revocation, RevocationError>",
|
||||||
|
"revoke.rs: pub fn from_text(s: &str) -> Result<Revocation, RevocationError>",
|
||||||
|
"revoke.rs: pub fn is_revoked(&self, subkey: &PublicKey) -> bool",
|
||||||
|
"revoke.rs: pub fn revoke( signer: &impl RevokeSigner, subkey: PublicKey, revoked_at: u64, accepted: Vec<[u8; 32]>, ) -> Result<Vec<Revocation>, RevocationError>",
|
||||||
|
"revoke.rs: pub fn revoked_at(&self) -> u64",
|
||||||
|
"revoke.rs: pub fn root(&self) -> PublicKey",
|
||||||
|
"revoke.rs: pub fn subkey(&self) -> PublicKey",
|
||||||
|
"revoke.rs: pub fn tbs(&self) -> Vec<u8>",
|
||||||
|
"revoke.rs: pub fn to_bytes(&self) -> Vec<u8>",
|
||||||
|
"revoke.rs: pub fn to_text(&self) -> String",
|
||||||
|
"revoke.rs: pub fn verify(&self, root: &PublicKey) -> Result<(), RevocationError>",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// `pub fn` signatures in `src/`, up to the opening brace, whitespace collapsed.
|
||||||
|
fn public_fns() -> Vec<String> {
|
||||||
|
let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for entry in std::fs::read_dir(&src).unwrap() {
|
||||||
|
let path = entry.unwrap().path();
|
||||||
|
let name = path.file_name().unwrap().to_string_lossy().into_owned();
|
||||||
|
let text = std::fs::read_to_string(&path).unwrap();
|
||||||
|
let mut rest = text.as_str();
|
||||||
|
while let Some(at) = rest.find("pub fn ") {
|
||||||
|
let sig_and_more = &rest[at..];
|
||||||
|
// The first `{` or `;` outside brackets (`[u8; 32]` has a `;` inside).
|
||||||
|
let mut depth = 0i32;
|
||||||
|
let end = sig_and_more
|
||||||
|
.char_indices()
|
||||||
|
.find(|&(_, c)| {
|
||||||
|
match c {
|
||||||
|
'[' | '(' => depth += 1,
|
||||||
|
']' | ')' => depth -= 1,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
depth == 0 && (c == '{' || c == ';')
|
||||||
|
})
|
||||||
|
.unwrap()
|
||||||
|
.0;
|
||||||
|
let sig: String = sig_and_more[..end].split_whitespace().collect::<Vec<_>>().join(" ");
|
||||||
|
out.push(format!("{name}: {sig}"));
|
||||||
|
rest = &sig_and_more[end..];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.sort();
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_public_surface_is_locked() {
|
||||||
|
let mut want: Vec<String> = SURFACE.iter().map(|s| s.to_string()).collect();
|
||||||
|
want.sort();
|
||||||
|
let got = public_fns();
|
||||||
|
let new: Vec<_> = got.iter().filter(|s| !want.contains(s)).collect();
|
||||||
|
let gone: Vec<_> = want.iter().filter(|s| !got.contains(s)).collect();
|
||||||
|
assert!(new.is_empty() && gone.is_empty(), "review the surface.\nnew: {new:#?}\ngone: {gone:#?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_public_data_comes_back_as_bytes() {
|
||||||
|
// The few functions that return raw bytes, and why each is public data.
|
||||||
|
let allowed = [
|
||||||
|
"pub fn as_bytes(&self) -> &[u8; 32]", // PublicKey
|
||||||
|
"pub fn as_bytes(&self) -> &[u8; 64]", // Signature
|
||||||
|
"pub fn hash(bytes: &[u8]) -> [u8; 32]", // SHA-256
|
||||||
|
"pub fn tbs(&self, root: &PublicKey) -> Vec<u8>", // the unsigned cert
|
||||||
|
"pub fn to_bytes(&self) -> Vec<u8>", // cert, log
|
||||||
|
"pub fn to_bytes(&self) -> [u8; 12]", // Hlc
|
||||||
|
"pub fn tbs(&self) -> Vec<u8>", // the unsigned revocation
|
||||||
|
"pub fn seal(&self, nonce: &[u8; 24], aad: &[u8], plain: &[u8]) -> Vec<u8>", // ciphertext
|
||||||
|
];
|
||||||
|
// The one secret that comes out, and why: the backup mailbox's access-key seed is a relay credential (it
|
||||||
|
// lets its holder fetch ciphertext, as an invite token's access key does), never an identity key.
|
||||||
|
let secret_ok = ["pub fn mailbox_seed(&self) -> Zeroizing<[u8; 32]>"];
|
||||||
|
for f in public_fns() {
|
||||||
|
let sig = f.split_once(": ").unwrap().1;
|
||||||
|
let returns_bytes = sig.contains("-> [u8") || sig.contains("-> &[u8") || sig.contains("-> Vec<u8>");
|
||||||
|
assert!(!returns_bytes || allowed.contains(&sig), "returns bytes: {f}");
|
||||||
|
assert!(
|
||||||
|
secret_ok.contains(&sig) || (!sig.contains("SigningKey") && !sig.contains("Zeroizing")),
|
||||||
|
"exposes a secret type: {f}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
# Tabellarius — the relay and MLS groups (design note, day 2)
|
||||||
|
|
||||||
|
*Tabellarius*: the Roman letter carrier. He carried sealed tablets and could not read them.
|
||||||
|
|
||||||
|
Written before the code. Every app syncs its own encrypted event log through one relay, between your own
|
||||||
|
devices and between people, without the relay being able to read anything or tell who is who.
|
||||||
|
|
||||||
|
## 1. Layers
|
||||||
|
|
||||||
|
```
|
||||||
|
AppEvent { kind, body } the app's change
|
||||||
|
→ TEV1 envelope (docs/TESSERA.md §8) signed by the app's subkey, carries its cert
|
||||||
|
→ TBA1 batch of envelopes one MLS application message
|
||||||
|
→ MLS PrivateMessage (OpenMLS) encrypted to the group's current epoch
|
||||||
|
→ relay mailbox ciphertext, seq, size, time — nothing else
|
||||||
|
```
|
||||||
|
|
||||||
|
**Deviation from the plan, on purpose.** The plan put the MLS ciphertext *inside* the envelope. But the
|
||||||
|
envelope carries the Tessera cert and the author's subkey in the clear, so a relay that stored envelopes would
|
||||||
|
learn who wrote what, and could link one person's mailboxes through their root key. The privacy rules win: the
|
||||||
|
envelope travels **inside** MLS. The relay stores only MLS ciphertext. Receivers still verify every envelope
|
||||||
|
on its own (`Envelope::verify` against the group members' roots), so an event stays attributable and
|
||||||
|
re-verifiable after it leaves MLS, for example in a history batch for a new device (§6).
|
||||||
|
|
||||||
|
## 2. Identity inside MLS
|
||||||
|
|
||||||
|
- **Ciphersuite** `MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519`. Handshake messages are encrypted
|
||||||
|
too (`PURE_CIPHERTEXT_WIRE_FORMAT_POLICY`): commits travel as PrivateMessages, so the relay does not learn
|
||||||
|
who added or removed whom.
|
||||||
|
- **MLS signature key**: a fresh Ed25519 key per device per group, generated by OpenMLS. The Tessera subkey
|
||||||
|
never leaves tessera (it has no byte export), so it cannot be the MLS key itself. Instead it vouches for it.
|
||||||
|
- **Credential** (`BasicCredential`, identity bytes, `TDC1`):
|
||||||
|
```
|
||||||
|
"TDC1" ‖ u16 len ‖ SubkeyCert ‖ mailbox_key (32) ‖ binding (64)
|
||||||
|
binding = Ed25519(subkey, "tessera credential v1\0" ‖ mls_signature_key ‖ mailbox_key) (Subkey::sign_credential_tbs)
|
||||||
|
```
|
||||||
|
A member is accepted only if its cert verifies under its root now, its cert is for the group's app, and the
|
||||||
|
binding signature by the cert's subkey covers its leaf's MLS signature key and mailbox key.
|
||||||
|
- **The group's roots** are the roots of its members' certs; `Envelope::verify` uses them. A **self group**
|
||||||
|
accepts only members whose root is the creator's root (your own devices).
|
||||||
|
- New members are checked when a commit adds them and, on joining, every member of the Welcome's tree.
|
||||||
|
A commit that adds an invalid member is not merged; it is reported as rejected.
|
||||||
|
|
||||||
|
## 3. The relay: mailboxes
|
||||||
|
|
||||||
|
A mailbox id is 32 bytes, base64url:
|
||||||
|
- a **group mailbox** is `SHA-256("tabellarius mailbox v1" ‖ MLS group id)`;
|
||||||
|
- an **invite mailbox** is 32 random bytes.
|
||||||
|
|
||||||
|
What the relay stores, and why (SQLite, nothing else):
|
||||||
|
|
||||||
|
| Table | Columns | Why |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| `messages` | `mailbox_id, seq, size, received_at, ciphertext` | the mail |
|
||||||
|
| `keys` | `key, mailbox_id` — `key` is **unique across all mailboxes** | who may read and write a mailbox |
|
||||||
|
| `acks` | `key, seq` | retention: what every member has fetched |
|
||||||
|
| `nonces` | `key, nonce, expires` (5 minutes) | replay protection |
|
||||||
|
|
||||||
|
No accounts, no IP addresses, no user agents, no app names, no certs. The relay's own logs are counts and
|
||||||
|
status codes, never ids or keys. Caddy's access log for this vhost is off.
|
||||||
|
|
||||||
|
### Requests
|
||||||
|
|
||||||
|
Every request except `GET /v1/health` is signed by a **random per-mailbox Ed25519 key**. A device makes a new
|
||||||
|
one for every group it joins and every invite. The relay never sees a Tessera key or cert, so it cannot link
|
||||||
|
mailboxes to each other or to a person. A key registered in one mailbox cannot be registered in another.
|
||||||
|
|
||||||
|
```
|
||||||
|
Tab-Key: base64url(public key)
|
||||||
|
Tab-Time: Unix seconds
|
||||||
|
Tab-Nonce: base64url(16 random bytes)
|
||||||
|
Tab-Sig: base64url(Ed25519("tabellarius request v1\0" ‖ METHOD ‖ "\n" ‖ path?query ‖ "\n" ‖ time ‖ "\n" ‖ nonce ‖ "\n" ‖ hex(SHA-256(body))))
|
||||||
|
```
|
||||||
|
|
||||||
|
| Check | Answer |
|
||||||
|
|:--|:--|
|
||||||
|
| any header missing or malformed | 401 `unsigned` |
|
||||||
|
| `|now − time| > 120 s` | 401 `stale` |
|
||||||
|
| bad signature | 401 `bad_signature` |
|
||||||
|
| key not registered in this mailbox (except `PUT` creating it) | 403 `unregistered_key` |
|
||||||
|
| nonce already seen for this key | 401 `replayed` |
|
||||||
|
| more than 120 requests a minute for this key | 429 `slow_down` |
|
||||||
|
|
||||||
|
A rejected request changes nothing and stores nothing (not even its nonce).
|
||||||
|
|
||||||
|
| Endpoint | What |
|
||||||
|
|:--|:--|
|
||||||
|
| `PUT /v1/mailboxes/{id}` | create; the signing key becomes its first key. 409 `exists`, 409 `key_in_use` |
|
||||||
|
| `POST /v1/mailboxes/{id}/keys` `{"key"}` | a member registers another member's key. 409 `key_in_use` |
|
||||||
|
| `DELETE /v1/mailboxes/{id}/keys/{key}` | deregister (removal, or leaving). The last key gone → the mailbox and its mail are deleted |
|
||||||
|
| `POST /v1/mailboxes/{id}/messages` `{"messages":[b64…]}` | append; at most 100 per batch, 300 KiB each, 2 MiB per request. A message already in the mailbox (same bytes) is not stored again; its seq is returned. → `{"seqs":[…]}` |
|
||||||
|
| `GET /v1/mailboxes/{id}/messages?after=N` | up to 200 messages with `seq > N` → `{"messages":[{"seq","data"}],"more"}` |
|
||||||
|
| `POST /v1/mailboxes/{id}/ack` `{"seq"}` | this key has everything up to `seq` |
|
||||||
|
| `GET /v1/health` | `ok`, unsigned |
|
||||||
|
| `GET /v1/live` | v1.1b: a WebSocket of notices `{"mailbox","seq"}`; each subscription is signed in the first message (docs/V1_1B.md §3) |
|
||||||
|
|
||||||
|
Every answer carries `Access-Control-Allow-Origin: *`, and `OPTIONS` answers a preflight, so a PWA on another
|
||||||
|
origin can call the relay (docs/V1_1B.md §4). Caddy strips `Origin`, `Referer` and `User-Agent` first.
|
||||||
|
|
||||||
|
### Retention (config values)
|
||||||
|
A message is deleted once **every key of its mailbox has acknowledged it and it is older than 30 days**
|
||||||
|
(`retention_acked_days`). Every message is deleted after **90 days** regardless (`retention_max_days`). The
|
||||||
|
plan said "30 days after the last ack"; the relay does not record when an ack happened, so it counts from
|
||||||
|
receipt. That can delete earlier than the plan for a member who acked late, never later than 90 days.
|
||||||
|
|
||||||
|
## 4. Invites
|
||||||
|
|
||||||
|
An invite is a capability: whoever holds the token can ask to join, and the inviter's device accepts any
|
||||||
|
**valid** credential (a valid cert for the group's app; for a self group, the same root).
|
||||||
|
|
||||||
|
1. The inviter's `invite(group)` creates an invite mailbox (its own fresh key) and registers a second fresh
|
||||||
|
key whose secret goes into the token. It also makes a one-time HPKE key pair.
|
||||||
|
2. Token: `tab1:` + base64url(`relay url ‖ invite mailbox ‖ access key secret ‖ inviter HPKE public key ‖ app`),
|
||||||
|
about 150 bytes, small enough for a QR code. It carries no identity.
|
||||||
|
3. The joiner's `join(token)` makes its MLS signature key, a group mailbox key and a KeyPackage with its
|
||||||
|
credential. It HPKE-seals the KeyPackage to the inviter's key (`info = "tabellarius invite v1"`) and posts it
|
||||||
|
to the invite mailbox. The relay never sees the credential.
|
||||||
|
4. The inviter's next `sync` opens it and checks the credential (§2). It then commits the Add to the group
|
||||||
|
mailbox, registers the joiner's mailbox key there, and posts `TIW1 ‖ seq ‖ Welcome` to the invite mailbox
|
||||||
|
(`seq`: where the joiner starts reading the group mailbox). Then it sends the group's history (§6).
|
||||||
|
5. The joiner's next `sync` reads the Welcome, checks every member, joins, and deregisters its invite key.
|
||||||
|
|
||||||
|
## 5. Sync, offline first
|
||||||
|
|
||||||
|
- `send(group, events)` seals each event in an envelope (HLC from the device clock), applies them to the local
|
||||||
|
log, encrypts one TBA1 batch per MLS message, and queues the ciphertext in the **outbox**. It never needs the
|
||||||
|
relay.
|
||||||
|
- `sync(group)`:
|
||||||
|
1. uploads the outbox;
|
||||||
|
2. pulls since the cursor; processes commits (credential checks, then merge) and application messages
|
||||||
|
(every envelope verified, then `tessera::merge`);
|
||||||
|
3. acks.
|
||||||
|
|
||||||
|
Messages it sent itself are recognised by hash and skipped. If the relay is unreachable, `sync` returns
|
||||||
|
`relay_ok: false` and changes nothing; the app shows "last synced" quietly.
|
||||||
|
- Rejected events and members come back in `SyncReport::rejected` with the reason, never half-applied.
|
||||||
|
- Group state (OpenMLS storage, keys, cursors, the log, the outbox) is saved through a `StateStore`. The file
|
||||||
|
store encrypts it (XChaCha20-Poly1305) with a 32-byte key **held in Custos**. The state never lies on disk in
|
||||||
|
the clear.
|
||||||
|
|
||||||
|
## 6. History for a new member
|
||||||
|
|
||||||
|
MLS gives a new member nothing from before it joined. A new device of yours must still see the whole log, so
|
||||||
|
after an Add the inviter sends the existing envelopes as ordinary TBA1 batches. Each envelope is still signed
|
||||||
|
by its author and verified by the receiver, and duplicates disappear in `merge`.
|
||||||
|
|
||||||
|
## 7. Removal
|
||||||
|
|
||||||
|
`remove(group, member)` commits a Remove and deregisters the member's mailbox key (it is in the member's
|
||||||
|
credential). The removed device can no longer fetch (403). Even with the ciphertext in hand, it cannot decrypt
|
||||||
|
anything from the next epoch on.
|
||||||
|
|
||||||
|
## 7a. v1.1: revocation, renewal, backup (docs/V1_1.md)
|
||||||
|
|
||||||
|
- **Revocation.**
|
||||||
|
- A `TRV1` statement (docs/TESSERA.md §12) travels as an event of kind `tessera.revoke`.
|
||||||
|
- `log()` leaves out every event a complete revocation rules out, and the revocations themselves.
|
||||||
|
- Events ruled out on arrival are reported in `SyncReport::rejected`.
|
||||||
|
- `revoke(group, statements)` announces, uploads, then removes the revoked leaves and deregisters their
|
||||||
|
mailbox keys.
|
||||||
|
- A device of the same person that sees a revocation in force removes the leaves on its next sync.
|
||||||
|
- **Who may remove whom.** A commit that removes some of another person's devices, while that person stays in
|
||||||
|
the group, needs that person's revocation in the log for each one; otherwise it is not applied. Removing
|
||||||
|
all of a person's devices removes the person, as in v0.2.
|
||||||
|
- **Renewal.**
|
||||||
|
- `renew(cert)` takes a new cert for the same subkey and commits a self-update with the new credential in
|
||||||
|
every group.
|
||||||
|
- A member's updated credential is checked like a new member's.
|
||||||
|
- A device whose cert has expired cannot be joined (the joiner checks every leaf), so renew before expiry.
|
||||||
|
- **The root-sealed backup.**
|
||||||
|
- `backup(secret)` uploads the self group's log to the backup mailbox: id = SHA-256(`tabellarius backup
|
||||||
|
v1` ‖ the access key's public key), access key from the secret's mailbox seed. It goes in 200 KiB parts,
|
||||||
|
each `seal(nonce, aad = "tabellarius backup v1", id ‖ part ‖ parts ‖ chunk)`: the relay sees ciphertext
|
||||||
|
of known sizes, no header.
|
||||||
|
- It acks the previous backups, so the relay drops them after its retention.
|
||||||
|
- An unchanged log is not uploaded again.
|
||||||
|
- `restore(secret)` returns the envelopes of the latest complete backup; `import(group, envelopes)`
|
||||||
|
verifies each at its own time and sends them into a new self group.
|
||||||
|
- **Retention:** the relay keeps every message at most 90 days, so a backup survives 90 days after its
|
||||||
|
last upload.
|
||||||
|
|
||||||
|
## 8. Known limits (v1)
|
||||||
|
|
||||||
|
- **Concurrent commits.** If two members commit in the same epoch, the one the relay ordered second is
|
||||||
|
dropped by the others. Its sender sees the conflict on the next sync, discards its own commit, and must redo
|
||||||
|
it. Day 2 tests commits sequentially.
|
||||||
|
- The relay sees **timing and sizes**: when a mailbox is written and fetched, and how large each message is.
|
||||||
|
Fetching several mailboxes from one connection links them by IP. Caddy drops access logs, but the network
|
||||||
|
path still sees it.
|
||||||
|
- A leaked invite token lets its holder join until the inviter's device accepts the first answer. One answer
|
||||||
|
per token is accepted; the token is dead afterwards.
|
||||||
|
- A browser sends a CORS preflight before each request (the URL changes with `?after=N`): twice the round
|
||||||
|
trips (docs/V1_1B.md Status).
|
||||||
|
- Live subscribe (v1.1b) tells a client *that* a mailbox has mail, never what. Native apps still poll; the
|
||||||
|
browser package listens.
|
||||||
+255
@@ -0,0 +1,255 @@
|
|||||||
|
# Tessera and the event envelope — design note (v1)
|
||||||
|
|
||||||
|
*A tessera hospitalis was a token broken between two families so they could recognise each other.*
|
||||||
|
|
||||||
|
Status: written before the code on day 1. Every format here is versioned by its magic; a change bumps it.
|
||||||
|
|
||||||
|
## 1. What it is for
|
||||||
|
|
||||||
|
One Domi identity per person, held in Custos. Every Domi app gets its **own subkey**, certified by that
|
||||||
|
identity, so no app ever creates long-term identity on its own. Apps then sign their events with the subkey;
|
||||||
|
anyone who knows the person's root public key can check that an event really came from one of their apps.
|
||||||
|
|
||||||
|
| Piece | Lives in | Holds secrets? |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| Root key | the Custos vault, never leaves it (CustosPublic `custos-vault`, `docs/IDENTITY.md` there) | yes |
|
||||||
|
| Root derivation, cert format, cert verification, match code, HLC, merge | `crates/tessera` | no, except in-memory `RootKey`/`Subkey` |
|
||||||
|
| Event envelope | `crates/envelope` | no |
|
||||||
|
| Asking Custos for a cert on Windows | `crates/custos-local` | no |
|
||||||
|
|
||||||
|
`tessera` and `envelope` are **pure**: no I/O, no network, no clock. Time is always a parameter.
|
||||||
|
|
||||||
|
## 2. Encoding primitives
|
||||||
|
|
||||||
|
All multi-byte integers are big-endian. `str8` = one length byte, then that many bytes. Text fields are
|
||||||
|
restricted ASCII so there is exactly one encoding of every value:
|
||||||
|
|
||||||
|
- **id** (`app_id`, `purpose`, envelope `app`): 1–32 bytes of `[a-z0-9-]`, not starting or ending with `-`.
|
||||||
|
|
||||||
|
Base64 in JSON and QR codes is **base64url without padding**.
|
||||||
|
|
||||||
|
## 3. The root key
|
||||||
|
|
||||||
|
```
|
||||||
|
entropy 32 bytes from the OS CSPRNG (Custos makes it; tessera only takes it as a parameter)
|
||||||
|
mnemonic BIP39, English, 24 words = bip39::Mnemonic::from_entropy(entropy)
|
||||||
|
seed BIP39 seed of the mnemonic with the empty passphrase (PBKDF2-HMAC-SHA512, 2048 rounds, 64 bytes)
|
||||||
|
root Ed25519 secret key = HKDF-SHA256(salt = "tessera root v1", ikm = seed, info = "ed25519")[0..32]
|
||||||
|
```
|
||||||
|
|
||||||
|
- The same mnemonic gives the same root public key, every time (test vector in §9).
|
||||||
|
- **Order (decided):** entropy → mnemonic shown **once** → root imported into the vault → entropy, seed and
|
||||||
|
mnemonic dropped (zeroized). A key that was created non-extractable first could never be backed up, so the
|
||||||
|
code makes the other order impossible: Custos' `Enrollment` is a typestate (`begin → show → confirm →
|
||||||
|
import`), and `import` exists only on the type that `show` returns.
|
||||||
|
- `tessera::RootKey::from_mnemonic` exists for recovery (v1.1) and tests. It has no method that returns the
|
||||||
|
secret; it can only sign certs and report its public key.
|
||||||
|
|
||||||
|
## 4. Subkey certificate (`TSC1`)
|
||||||
|
|
||||||
|
```
|
||||||
|
"TSC1" 4
|
||||||
|
root 32 the root public key that signs this cert
|
||||||
|
subkey 32 the subkey's Ed25519 public key
|
||||||
|
app_id str8 id; "device" is reserved for device subkeys
|
||||||
|
purpose str8 id, e.g. "sync"; for device subkeys "device"
|
||||||
|
not_before 8 u64 Unix seconds
|
||||||
|
not_after 8 u64 Unix seconds, > not_before
|
||||||
|
sig 64 Ed25519(root, "tessera cert v1\0" ‖ every byte above)
|
||||||
|
```
|
||||||
|
|
||||||
|
`tbs` ("to be signed") is every byte before `sig`. The domain prefix means the root can only ever sign
|
||||||
|
something that parses as a cert: Custos' vault refuses a `tbs` that does not start with `TSC1` and name its
|
||||||
|
own root.
|
||||||
|
|
||||||
|
`verify(cert, root, now)` checks, in this order, and returns the first failure:
|
||||||
|
|
||||||
|
| Check | Error |
|
||||||
|
|:--|:--|
|
||||||
|
| `cert.root == root` | `WrongRoot` |
|
||||||
|
| signature valid (`verify_strict`) | `BadSignature` (tampered) |
|
||||||
|
| `now >= not_before` | `NotYetValid` |
|
||||||
|
| `now < not_after` | `Expired` |
|
||||||
|
|
||||||
|
Decoding is strict: wrong magic, a wrong length, an invalid id, `not_after <= not_before` or trailing bytes
|
||||||
|
are errors.
|
||||||
|
|
||||||
|
**Validity Custos issues:** `not_before = now − 5 min` (clock skew between devices), `not_after = now + 365 days`.
|
||||||
|
Renewal and revocation are v1.1.
|
||||||
|
|
||||||
|
## 5. Match code
|
||||||
|
|
||||||
|
Six digits the app and Custos both show, so the person approves the key the app actually holds:
|
||||||
|
|
||||||
|
```
|
||||||
|
match = u32_be(SHA-256("tessera match v1" ‖ subkey_pub)[0..4]) mod 1 000 000, zero-padded to 6 digits
|
||||||
|
```
|
||||||
|
|
||||||
|
The code is not secret. Test vector in §9.
|
||||||
|
|
||||||
|
## 6. Hybrid logical clock
|
||||||
|
|
||||||
|
`Hlc { wall: u64 ms, logical: u32 }`, ordered by `wall` then `logical`; encoded as 12 bytes.
|
||||||
|
|
||||||
|
- `Clock::tick(now)`: `wall' = max(last.wall, now)`; `logical' = last.logical + 1` if `wall' == last.wall`,
|
||||||
|
else 0.
|
||||||
|
- `Clock::observe(remote, now)`: refuses `remote.wall > now + max_drift` (`TooFarAhead`); then
|
||||||
|
`wall' = max(last.wall, remote.wall, now)` and `logical'` per the HLC paper (the larger logical of the
|
||||||
|
clocks that hold `wall'`, plus one).
|
||||||
|
- A logical counter that would overflow is an error, never a wrap.
|
||||||
|
|
||||||
|
## 7. Merge
|
||||||
|
|
||||||
|
`merge(log, batch, verify) -> (log', rejected)`:
|
||||||
|
|
||||||
|
- Each event has an **order key** `(hlc, author, hash)`, where `hash = SHA-256(encoded event)`.
|
||||||
|
- Every event in `batch` is verified with the caller's `verify`; a failure goes to `rejected` with its
|
||||||
|
reason and is never inserted (the app logs it).
|
||||||
|
- `log'` = the union of `log` and the verified events, de-duplicated by `hash`, sorted by order key.
|
||||||
|
- The log's bytes are `u32 length ‖ encoded event` for each event in order. Merging the same batches in any
|
||||||
|
order, any number of times, gives byte-identical logs (property test).
|
||||||
|
|
||||||
|
The events already in `log` are not verified again: they were verified when they arrived.
|
||||||
|
|
||||||
|
## 8. The event envelope (`TEV1`)
|
||||||
|
|
||||||
|
```
|
||||||
|
"TEV1" 4
|
||||||
|
then exactly these fields, in this order, each as tag (1) ‖ length (u32) ‖ value:
|
||||||
|
1 app id
|
||||||
|
2 schema u32 (4 bytes): the version of the payload's schema
|
||||||
|
3 hlc 12 bytes
|
||||||
|
4 author 32 bytes: the subkey public key
|
||||||
|
5 cert a TSC1 cert (§4)
|
||||||
|
6 payload 0–256 KiB: MLS ciphertext from day 2; opaque here
|
||||||
|
7 sig 64 bytes: Ed25519(author, "tessera event v1\0" ‖ every byte before field 7)
|
||||||
|
```
|
||||||
|
|
||||||
|
Decoding is strict and total: it returns a whole `Envelope` or a typed error with a reason (`BadMagic`,
|
||||||
|
`UnknownField`, `FieldOutOfOrder`, `BadLength`, `Invalid`, `TrailingBytes`, `TooLarge`, …). An unknown tag is
|
||||||
|
`UnknownField`, a known tag in the wrong place is `FieldOutOfOrder`. Encoding is canonical: decoding and
|
||||||
|
encoding again gives the same bytes. A decoded envelope is not yet trusted.
|
||||||
|
|
||||||
|
`Envelope::verify(roots, now, max_drift)` checks:
|
||||||
|
|
||||||
|
| Check | Error |
|
||||||
|
|:--|:--|
|
||||||
|
| `author == cert.subkey` | `AuthorNotCert` |
|
||||||
|
| `cert.app_id == app` (app boundaries) | `WrongApp` |
|
||||||
|
| `cert.root` is one of the trusted `roots` (the group's members) | `UnknownRoot` |
|
||||||
|
| the cert is valid at the event's time (`hlc.wall / 1000`), §4 | `Cert(…)` |
|
||||||
|
| `hlc.wall <= now + max_drift` | `FromTheFuture` |
|
||||||
|
| the signature is valid (`verify_strict`) | `BadSignature` |
|
||||||
|
|
||||||
|
The cert is checked at the event's own time, so a log stays verifiable after a cert expires and rebuilding
|
||||||
|
from it is deterministic. The cost: whoever steals a subkey can backdate events into its validity. Revocation
|
||||||
|
(v1.1) closes this; until then validity is one year.
|
||||||
|
|
||||||
|
## 9. Test vectors
|
||||||
|
|
||||||
|
| Input | Output |
|
||||||
|
|:--|:--|
|
||||||
|
| entropy `00` × 32 | mnemonic `abandon` × 23 + `art` |
|
||||||
|
| that mnemonic | root public key in `crates/tessera/tests/mandatory.rs` (`ROOT_PUB_ZERO`), also pinned in CustosPublic |
|
||||||
|
| subkey public key `07` × 32 | match code in `crates/tessera/tests/mandatory.rs` |
|
||||||
|
|
||||||
|
## 10. Asking Custos for a cert (`custos-local`, Windows)
|
||||||
|
|
||||||
|
Custos' local API is the named pipe `\\.\pipe\custos-domi` (Custos `docs/02_app.md`; only the current
|
||||||
|
Windows user can open it; Custos identifies the caller by its executable). Day 1 adds one operation:
|
||||||
|
|
||||||
|
```
|
||||||
|
→ {"op":"subkey","app":"Fiscus Domi","app_id":"fiscus","purpose":"sync","subkey":"<base64url 32 bytes>"}
|
||||||
|
← {"ok":true,"cert":"<base64url TSC1>","match":"123456"}
|
||||||
|
← {"ok":false,"error":"denied"|"locked"|"no_identity"|"bad_request","message":"…"}
|
||||||
|
```
|
||||||
|
|
||||||
|
1. The app makes its subkey itself (`Subkey::from_seed` with 32 bytes from the OS CSPRNG) and keeps the seed
|
||||||
|
in Custos (`set domi://<app_id>/tessera-subkey`), never in a file.
|
||||||
|
2. It shows the match code of its subkey and sends the request.
|
||||||
|
3. Custos shows the app (program path and signer), the app id, the purpose and the match code. One click
|
||||||
|
approves. Custos signs the cert with the root, records it (Domi identity → apps), and answers.
|
||||||
|
|
||||||
|
No answer ever contains private key material: only the cert (public keys and a signature).
|
||||||
|
|
||||||
|
## 11. Not in v1
|
||||||
|
|
||||||
|
Revocation, renewal, recovery UI (v1.1), MLS and the relay (day 2), WASM (v1.1).
|
||||||
|
|
||||||
|
## 12. v1.1: revocation and the backup secret (docs/V1_1.md)
|
||||||
|
|
||||||
|
### Revocation (`TRV1`)
|
||||||
|
```
|
||||||
|
"TRV1" 4
|
||||||
|
root 32 the root that withdraws the subkey
|
||||||
|
subkey 32 the revoked subkey
|
||||||
|
revoked_at 8 u64 Unix seconds
|
||||||
|
part 2 u16, this part's index
|
||||||
|
parts 2 u16, how many parts the statement has (1..256)
|
||||||
|
count 4 u32, hashes in this part (0..7000)
|
||||||
|
hashes count×32 SHA-256 of each event by the subkey that stays valid: sorted, unique
|
||||||
|
sig 64 Ed25519(root, "tessera revoke v1\0" ‖ every byte above)
|
||||||
|
```
|
||||||
|
- The root signs it through `RevokeSigner::sign_revocation_tbs`, in its own domain. A signer refuses a `tbs`
|
||||||
|
that does not start `TRV1 ‖ its own root`, and the cert signer refuses a `TRV1`, so neither statement can
|
||||||
|
pass for the other.
|
||||||
|
- Decoding is strict: wrong magic, a part outside its count, unsorted or repeated hashes, a short field or
|
||||||
|
trailing bytes are errors.
|
||||||
|
- **`RevocationSet`** applies a group's statements:
|
||||||
|
- A statement counts once all its parts are in (parts add up).
|
||||||
|
- An event by a revoked subkey stays valid only if every complete statement for that subkey lists it, so a
|
||||||
|
later statement never widens what is kept.
|
||||||
|
- The answer does not depend on the order statements arrive in.
|
||||||
|
- Statements are accepted only from a root of the group.
|
||||||
|
|
||||||
|
### The backup secret
|
||||||
|
```
|
||||||
|
backup secret = HKDF-SHA256(salt "tessera backup v1", ikm = root secret (the Ed25519 seed, §3), info = app id)
|
||||||
|
seal key = HKDF-Expand(backup secret, "seal") XChaCha20-Poly1305: nonce (24) ‖ ciphertext
|
||||||
|
mailbox seed = HKDF-Expand(backup secret, "mailbox") the backup mailbox's Tabellarius access key
|
||||||
|
```
|
||||||
|
- Custos derives it (the root never leaves Custos) and hands an app only its own.
|
||||||
|
- `BackupSecret` has no method that returns the secret: it seals, opens, and gives the mailbox seed. That seed
|
||||||
|
is a relay credential of the kind invite tokens carry, the one exception in `tests/surface.rs`.
|
||||||
|
|
||||||
|
**Test vector** (the zero-entropy mnemonic of §9, app `fiscus`):
|
||||||
|
- mailbox seed: `IygCOrh-ibO6-KY5AXQ9Prl2SyPWQIyZZ-anffcbMCU`
|
||||||
|
- `seal(nonce = 24 zero bytes, aad = "", plain = "")`: `AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAci_JRbtsx5prR83KT9Y7LA`
|
||||||
|
|
||||||
|
### Custos' part (`custos-local`, three more pipe operations)
|
||||||
|
|
||||||
|
The person starts a revocation **in Custos** (Domi identity → a key → Revoke). Custos cannot call an app, so
|
||||||
|
each app asks, on every sync, whether there is anything to do:
|
||||||
|
|
||||||
|
```
|
||||||
|
→ {"op":"revocations","app":"Fiscus Domi","app_id":"fiscus"}
|
||||||
|
← {"ok":true,"revocations":[{"subkey":"<base64url>","revoked_at":1793000000,"statements":["<base64url TRV1>",…]|null}]}
|
||||||
|
|
||||||
|
→ {"op":"revoke","app":"Fiscus Domi","app_id":"fiscus","subkey":"<base64url>","revoked_at":1793000000,
|
||||||
|
"accepted":"<base64url: the kept events' SHA-256, 32 bytes each, concatenated>"}
|
||||||
|
← {"ok":true,"statements":["<base64url TRV1>",…]}
|
||||||
|
|
||||||
|
→ {"op":"backup_key","app":"Fiscus Domi","app_id":"fiscus"}
|
||||||
|
← {"ok":true,"secret":"<base64url, 32 bytes>"}
|
||||||
|
```
|
||||||
|
|
||||||
|
- **All three need the app's namespace grant** (`domi://<app_id>/…`, the one its subkey seed lives in), so an
|
||||||
|
app reaches only its own revocations and its own backup secret.
|
||||||
|
- **`revocations`** lists the revocations the person started for this app's subkeys and for device keys.
|
||||||
|
`statements` is `null` until a device of this app sent its list.
|
||||||
|
- **`revoke`** signs only a revocation the person started, at the `revoked_at` Custos chose (otherwise
|
||||||
|
`not_found`), and only once: a second call gets the statements already signed. The app sends the hashes of
|
||||||
|
every event by that subkey in all its groups (`Client::events_by_all`).
|
||||||
|
- **An app that does not answer:** Custos shows the revocation as waiting. A second, explicit click signs it
|
||||||
|
with an empty list, which throws away every event that key wrote (docs/V1_1.md decision 2). A device key
|
||||||
|
(`app_id` `device`) is signed at once with an empty list: in v1.1a no app log holds events by one.
|
||||||
|
- With the statements in hand the app calls `Client::apply_revocation`: in every group the key was in, it
|
||||||
|
announces them, removes the key's leaves and takes their mailbox keys off the relay. It skips a group that
|
||||||
|
already has them, so calling it on every sync is safe.
|
||||||
|
- **`backup_key`** gives the app its backup secret (above). The app keeps it as `BackupSecret` and calls
|
||||||
|
`Client::backup` after each sync and `Client::restore` on a new device.
|
||||||
|
- **Limits:** one pipe message is at most 1 MiB, so one `revoke` carries up to 24,000 kept events.
|
||||||
|
|
||||||
|
Custos' vault signs `TRV1` only for a key the person marked revoked, at that time (CustosPublic
|
||||||
|
docs/IDENTITY.md), so an app with the namespace grant can choose which events stay, not which key is
|
||||||
|
revoked.
|
||||||
+206
@@ -0,0 +1,206 @@
|
|||||||
|
# Fundamentum v1.1 — revocation, recovery, the browser, live sync (design note, proposals)
|
||||||
|
|
||||||
|
Written before any v1.1 code, so the open decisions can be made first. **(proposal)** marks my judgment;
|
||||||
|
each has an alternative and its cost. Nothing here changes v1's formats; every new structure is a new
|
||||||
|
magic with its own signing domain.
|
||||||
|
|
||||||
|
**The gate (roadmap):** lose a phone, revoke it, and recover everything from the 24 words, with no data loss.
|
||||||
|
|
||||||
|
v1.1 is too big for one session. Proposed split:
|
||||||
|
|
||||||
|
| Day | Contents |
|
||||||
|
|:--|:--|
|
||||||
|
| **v1.1a** | revocation (§1), renewal (§2), the root-sealed backup and recovery (§3), Custos UI for all three |
|
||||||
|
| **v1.1b** | a sans-IO client and its WASM build (§4), live subscribe on the relay (§5), the JS package for PWAs (§6) |
|
||||||
|
|
||||||
|
v1.1a alone passes the gate for the desktop apps. v1.1b is what the phone apps need.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Revocation
|
||||||
|
|
||||||
|
### What a lost phone holds
|
||||||
|
- One device subkey per Domi app it ran (`TSC1` certs for that app) and, in the browser, the device key from
|
||||||
|
day-1 pairing.
|
||||||
|
- For each group it was in: an MLS leaf, its signature key, the group state and a mailbox key.
|
||||||
|
|
||||||
|
Revoking it has to do three separate things:
|
||||||
|
1. **Readers stop trusting its signatures.** Nothing it signs from now on is accepted.
|
||||||
|
2. **It stops reading.** It leaves every MLS group, so it cannot decrypt future epochs.
|
||||||
|
3. **The relay stops serving it.** Its mailbox keys are deregistered.
|
||||||
|
|
||||||
|
### The revocation statement (`TRV1`)
|
||||||
|
```
|
||||||
|
"TRV1" 4
|
||||||
|
root 32 the root that certified the subkey
|
||||||
|
subkey 32 the revoked subkey
|
||||||
|
revoked_at 8 u64 Unix seconds, when the person revoked it
|
||||||
|
accepted u32 count ‖ count × 32 SHA-256 of every event by this subkey that stays valid, sorted
|
||||||
|
sig 64 Ed25519(root, "tessera revoke v1\0" ‖ every byte above)
|
||||||
|
```
|
||||||
|
- Custos signs it. Its vault refuses a `tbs` that does not start with `TRV1` and name its own root, exactly
|
||||||
|
as it does for `TSC1`, so the root still signs only things that parse as one of its two statements.
|
||||||
|
- It travels as an ordinary event (`kind = "tessera.revoke"`) in each group the subkey was in. Any device of
|
||||||
|
the same person sends it.
|
||||||
|
|
||||||
|
### Why a list of accepted events, not a time (proposal)
|
||||||
|
v1 checks a cert at the event's own time, so a thief who has the subkey can **backdate** an event to
|
||||||
|
before `revoked_at`, and a time cutoff would accept it. Instead, the revocation names exactly which of that
|
||||||
|
subkey's events stay valid: those already in the revoking device's log. Every other event by that subkey,
|
||||||
|
whenever it claims to be from, is rejected.
|
||||||
|
|
||||||
|
- This is deterministic: every device applies the same list once the logs converge.
|
||||||
|
- **The cost:** events the lost phone wrote but never synced are lost too. They exist only on the phone.
|
||||||
|
- Size: 32 bytes per kept event (1,000 events from one phone in one group = 32 KB, once).
|
||||||
|
- *Alternative:* a time cutoff (`revoked_at` only). Simpler and smaller, but it leaves the backdating hole open.
|
||||||
|
|
||||||
|
### Applying it (`tessera::merge`)
|
||||||
|
The verifier gets the group's revocations as a second input. Merging becomes two passes:
|
||||||
|
1. Collect every valid `TRV1` in the log: root-signed, by a root of the group, for a subkey that root certified.
|
||||||
|
2. Drop each event whose author is revoked and whose hash is not in that revocation's list. It goes to
|
||||||
|
`rejected` with the reason "revoked".
|
||||||
|
|
||||||
|
Revoking twice is idempotent: the lists are intersected, never widened.
|
||||||
|
|
||||||
|
### MLS and the relay
|
||||||
|
- **The revoking device:**
|
||||||
|
- commits a `Remove` of every leaf whose credential names a revoked subkey;
|
||||||
|
- deregisters the mailbox key in that credential (v0.2.0's `remove` does both);
|
||||||
|
- then sends the `TRV1` event.
|
||||||
|
- A member device that sees a valid `TRV1` before the `Remove` lands may commit the `Remove` itself, so a
|
||||||
|
revocation finishes even if the revoking device goes offline.
|
||||||
|
- **Shared groups:** another person's device in the group accepts a `Remove` of your leaf only with your
|
||||||
|
`TRV1` beside it (a member removing someone else needs a reason the others can verify). *(proposal)*
|
||||||
|
|
||||||
|
### In Custos
|
||||||
|
- **Domi identity → Devices → Revoke.** Custos groups certs by the label it recorded when it issued them
|
||||||
|
("Phone browser", "Fiscus on Mark's PC"), so one revoke covers every key of that device.
|
||||||
|
- The `accepted` list comes from the app's own log: Custos asks each app on this PC (pipe op `revoke`) for
|
||||||
|
that subkey's event hashes. An app that is not running cannot answer.
|
||||||
|
- **(Decision)** Revoke then: (a) waits until each app has answered, or (b) lets the person revoke with an
|
||||||
|
empty list for apps that did not answer. That throws away everything that phone wrote in those apps. I
|
||||||
|
propose (a), with (b) behind a second, explicit click.
|
||||||
|
|
||||||
|
## 2. Renewal
|
||||||
|
- Certs live 365 days. An app asks Custos for a fresh cert for the same subkey when 30 days are left (same
|
||||||
|
`subkey` op, one click, the same match code).
|
||||||
|
- An expired cert keeps its old events valid (they are checked at their own time); the subkey just signs
|
||||||
|
nothing new until renewed.
|
||||||
|
- No new format.
|
||||||
|
|
||||||
|
## 3. Recovery from the 24 words
|
||||||
|
|
||||||
|
`RootKey::from_mnemonic` already gives back the same root, so every group still trusts it. What is lost
|
||||||
|
with every device is the **data** and the **MLS state**.
|
||||||
|
|
||||||
|
- **Shared groups:** the other members still hold the group. They re-invite your new device; the credential
|
||||||
|
check passes because the root matches. Their copy of the log comes with the history (v0.2.0 §6).
|
||||||
|
- **Your self group** (your own devices only): if every device is gone, nobody holds it. Hence:
|
||||||
|
|
||||||
|
### The root-sealed backup (proposal)
|
||||||
|
- Custos derives, per app, a backup key and a backup mailbox from the **root secret**, never stored:
|
||||||
|
- `backup_key = HKDF(root secret, "tessera backup v1", app_id)`
|
||||||
|
- `mailbox access key = HKDF(root secret, "tessera backup mailbox v1", app_id)`
|
||||||
|
- The mailbox id is the hash of that key's public half.
|
||||||
|
- Both come back from the 24 words alone. Custos hands an app its own pair only (pipe op `backup_key`).
|
||||||
|
- Each desktop app, after a sync, uploads its self group's verified log: `TBK1 ‖ XChaCha20-Poly1305(backup_key,
|
||||||
|
envelopes)`. The relay keeps the latest few; they are ciphertext like everything else.
|
||||||
|
- **Recovery:**
|
||||||
|
1. Custos: "Restore from 24 words".
|
||||||
|
2. Each app asks for its backup pair, downloads the latest blob, verifies every envelope, opens a new self
|
||||||
|
group and sends the history into it.
|
||||||
|
3. Your other people re-invite you into shared groups.
|
||||||
|
- **Cost:** the relay can tell that one backup mailbox gets written now and then. It cannot tell whose it is
|
||||||
|
or what is in it, and it cannot link it to any group mailbox.
|
||||||
|
- *Alternative:* no backup. Recovery then works only if one device survives (an always-on node such as
|
||||||
|
fiscus-node counts). Simpler, but it fails the gate for anyone with one PC and one phone who loses both.
|
||||||
|
|
||||||
|
## 4. The client in the browser (WASM)
|
||||||
|
|
||||||
|
**The probe (2026-11-04)** answers the open point from the plan ("whether OpenMLS runs well in WASM"):
|
||||||
|
**it builds.** `tessera`, `envelope`, `tabellarius-proto` and OpenMLS 0.9 all compile for
|
||||||
|
`wasm32-unknown-unknown` once the browser's clock and randomness are switched on. The client itself stops
|
||||||
|
only at its HTTP transport. Details under "Probe" at the end. The client needs two changes:
|
||||||
|
- **Transport:** the client is blocking (`ureq`). Proposal: split it into a **sans-IO core** (a state machine
|
||||||
|
that says which request to make and consumes the answer) and two thin drivers: `ureq` (native, unchanged
|
||||||
|
API) and `fetch` (browser, async). The tests drive the core directly.
|
||||||
|
- **Signing:** in the browser the device subkey is a non-extractable WebCrypto key. Tessera gets a `Signer`
|
||||||
|
trait (`public`, `sign_event_tbs`, `sign_credential_tbs`), async in the browser. `Subkey` implements it on
|
||||||
|
native.
|
||||||
|
- **MLS keys:** OpenMLS makes its own signature key per group; in the browser it lives in the client state.
|
||||||
|
That state is encrypted with a non-extractable WebCrypto AES-GCM key and kept in IndexedDB (the same rule as
|
||||||
|
the desktop's Custos-held state key).
|
||||||
|
|
||||||
|
## 5. Live subscribe
|
||||||
|
|
||||||
|
- **`GET /v1/live`**, a WebSocket.
|
||||||
|
- The first message is a list of `(mailbox, after)`, each signed as a v0.2.0 request: a browser cannot set
|
||||||
|
headers on a WebSocket.
|
||||||
|
- The relay then sends `{"mailbox", "seq"}` whenever a message arrives, never the message. The client
|
||||||
|
fetches as today.
|
||||||
|
- **Limits:** 32 mailboxes per connection, 4 connections per mailbox key, idle timeout 10 minutes.
|
||||||
|
- **Privacy:** no worse than polling. One connection for several mailboxes links them by connection, as
|
||||||
|
fetching them from one IP already does. Apps that care open one connection per group.
|
||||||
|
- Caddy proxies it; the access log stays off.
|
||||||
|
|
||||||
|
## 6. The JS package (`@domi/fundamentum`)
|
||||||
|
|
||||||
|
- `wasm-bindgen` over the sans-IO core and the fetch driver, in the Fundamentum repo, served by each PWA
|
||||||
|
itself (Domi: nothing fetched from a CDN).
|
||||||
|
- The API mirrors the Rust one (`open`, `selfGroup`, `openGroup`, `invite`, `join`, `send`, `sync`, `log`,
|
||||||
|
`remove`, `revoke`) plus `subscribe(onChange)`.
|
||||||
|
|
||||||
|
## Decisions wanted before v1.1a starts
|
||||||
|
|
||||||
|
| # | Question | Proposal |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| 1 | Revocation keeps a list of accepted events (closes backdating) or uses a time cutoff | the list |
|
||||||
|
| 2 | Revoke while an app did not answer | wait; an explicit second click to drop its events |
|
||||||
|
| 3 | Another person's device may `Remove` your leaf only with your `TRV1` | yes, refined in v1.1a (below) |
|
||||||
|
| 4 | Root-sealed backup on the relay, so recovery works with every device lost | yes |
|
||||||
|
| 5 | Split v1.1 into v1.1a (revocation, renewal, recovery) and v1.1b (WASM, live, JS) | yes |
|
||||||
|
| 6 | The v1 gate (live relay, two real devices) before v1.1 starts, or in parallel | in parallel: v1.1a needs no server |
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
**v1.1a in the crates (Fundamentum v0.3.0):** `TRV1` and `RevocationSet`, `RevokeSigner`, `BackupSecret`
|
||||||
|
(tessera); `revoke`, `announce_revocation`, `events_by`, `renew`, `backup`, `restore`, `import` and the
|
||||||
|
removal rule (client). The gate's scenario passes against the in-process relay: a phone is revoked, its
|
||||||
|
later and backdated events are dropped on every device, and with every device lost the self group comes back
|
||||||
|
from the backup.
|
||||||
|
|
||||||
|
**Decision 3, refined while building it.** As written, it would also have stopped anyone removing a
|
||||||
|
*person* from a shared group, which v0.2 deliberately allows. The intent was to stop one person cutting off
|
||||||
|
another's device while that person stays. So:
|
||||||
|
- removing **some** of another person's devices needs their revocation for each one;
|
||||||
|
- removing **all** of them removes the person, as before.
|
||||||
|
|
||||||
|
**Custos' half (Fundamentum v0.3.1, CustosPublic v0.10.0, Custos 0.5.0):** the pipe ops `revocations`,
|
||||||
|
`revoke` and `backup_key` (docs/TESSERA.md §12); Domi identity → a key → **Revoke**, **Revoke without
|
||||||
|
waiting** (decision 2's second click) and **Restore from 24 words**. The vault signs `TRV1` only for a key
|
||||||
|
the person revoked, at the time they did. CustosPublic and Custos check the backup secret against the
|
||||||
|
test vector of §12.
|
||||||
|
|
||||||
|
**One change to §1 "In Custos":** Custos cannot call an app over the pipe, so the person starts the
|
||||||
|
revocation in Custos and each app asks on its next sync (`revocations`), then sends its list (`revoke`).
|
||||||
|
Device keys are signed at once with an empty list: no app log holds their events in v1.1a.
|
||||||
|
|
||||||
|
**Still to do for v1.1a:** each app, on every sync, calls `revocations_to_apply` → `apply_revocation`, then
|
||||||
|
`backup`; and offers `restore` on a new device. Then the gate by hand on two real devices.
|
||||||
|
|
||||||
|
## Probe
|
||||||
|
|
||||||
|
`cargo build --target wasm32-unknown-unknown`, rustc 1.94.1 from the server's nixpkgs-unstable pin
|
||||||
|
(`0726a0ec`), in WSL, on Fundamentum `95b7579` (v0.2.1). Not run in a browser yet: this shows the code
|
||||||
|
compiles, not that it works there.
|
||||||
|
|
||||||
|
| Crate | Result | Needs |
|
||||||
|
|:--|:--|:--|
|
||||||
|
| `tessera` | builds | nothing |
|
||||||
|
| `envelope` | builds | nothing |
|
||||||
|
| `tabellarius-proto` | builds | the browser random source (`getrandom` 0.2 `js`, 0.3 and 0.4 `wasm_js` + `--cfg getrandom_backend="wasm_js"`) |
|
||||||
|
| OpenMLS 0.9 + `openmls_rust_crypto`, `_basic_credential`, `_memory_storage` | builds | the same, plus OpenMLS's own `js` feature (time and randomness from JavaScript) |
|
||||||
|
| `tabellarius-client` | fails at `ring` (C code, via `ureq` → `rustls`) | the sans-IO split (§4): the browser build has no `ureq`, it talks through `fetch` |
|
||||||
|
|
||||||
|
The browser build therefore needs no change to the crypto, the formats or OpenMLS: only the transport and
|
||||||
|
a `Signer` for the WebCrypto device key.
|
||||||
+176
@@ -0,0 +1,176 @@
|
|||||||
|
# Fundamentum v1.1b — the client in the browser, live subscribe, the JS package (design note)
|
||||||
|
|
||||||
|
Written before the v1.1b code. It turns `docs/V1_1.md` §4–§6 (accepted with decision 5 on 2026-11-04) into
|
||||||
|
what gets built. **(choice)** marks where this note settles something §4–§6 left open; each says what
|
||||||
|
it costs. Nothing here changes a v1 or v1.1a format.
|
||||||
|
|
||||||
|
**The goal:** a PWA on a phone is a Domi device. It joins the self group, sends and reads verified events,
|
||||||
|
and hears about new mail without polling. Its device key and its state never leave the browser unencrypted.
|
||||||
|
|
||||||
|
Two releases:
|
||||||
|
|
||||||
|
| Release | Contents |
|
||||||
|
|:--|:--|
|
||||||
|
| **v0.4.0** | the client split into an async core and a blocking native driver (§1); `DeviceSigner` (§2); live subscribe on the relay (§3); CORS (§4) |
|
||||||
|
| **v0.5.0** | `crates/wasm` (fetch transport, WebCrypto signer) and the JS package `@domi/fundamentum` (§5), tested in a browser against a local relay |
|
||||||
|
|
||||||
|
## 1. One core, two drivers
|
||||||
|
|
||||||
|
§4 proposed a sans-IO state machine. **(choice)** The core is `async` code generic over a transport and a
|
||||||
|
signer, and Rust's `async` produces the state machine. A hand-written state machine for `sync` (several
|
||||||
|
mailboxes, `more` pages, invites, joins, acks) would duplicate every control path the client already has, and
|
||||||
|
every bug fix would have to be made twice.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
pub trait Transport {
|
||||||
|
/// `Err` only when the relay could not be reached (offline); any HTTP status is an `Ok` response.
|
||||||
|
fn send(&self, req: HttpRequest) -> impl Future<Output = Result<HttpResponse, String>>;
|
||||||
|
}
|
||||||
|
pub struct Core<T: Transport, S: DeviceSigner> { … } // every operation that talks to the relay or signs is `async`
|
||||||
|
pub struct Client(Core<Ureq, Subkey>); // native: the v0.3 API, unchanged, blocking
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Native** (`Client`): the API every app uses today keeps its exact signatures. Its transport (`ureq`)
|
||||||
|
and signer (`Subkey`) never wait, so each call polls the core's future exactly once. There is no executor
|
||||||
|
and no thread. The core never waits on anything else (no timers, no channels).
|
||||||
|
- **Browser** (`crates/wasm`): the same core over `fetch` and a WebCrypto signer, driven by the browser's
|
||||||
|
event loop through `wasm-bindgen-futures`.
|
||||||
|
- The tests stay as they are. They drive `Client`, so they test the core.
|
||||||
|
- `ureq` is a dependency only off `wasm32`. `EncryptedFileStore` is native only. The clock is a parameter
|
||||||
|
of `Core::open` (`std::time` panics in the browser).
|
||||||
|
- **Cost:** `Core` is generic, so a native app compiles one instance and the browser another. That is fine.
|
||||||
|
|
||||||
|
## 2. The device key in the browser
|
||||||
|
|
||||||
|
```rust
|
||||||
|
pub trait DeviceSigner {
|
||||||
|
fn public(&self) -> PublicKey;
|
||||||
|
fn sign_event_tbs(&self, tbs: &[u8]) -> impl Future<Output = Result<Signature, String>>; // EVENT_DOMAIN ‖ tbs
|
||||||
|
fn sign_credential_tbs(&self, tbs: &[u8]) -> impl Future<Output = Result<Signature, String>>; // CREDENTIAL_DOMAIN ‖ tbs
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- `tessera::Subkey` implements it (native).
|
||||||
|
- In the browser the private key is a **non-extractable** WebCrypto Ed25519 key, the one day-1 pairing
|
||||||
|
certified. Rust prepends the domain, and JavaScript calls `crypto.subtle.sign("Ed25519", key, message)`.
|
||||||
|
JavaScript never chooses the domain, so it cannot be tricked into signing one statement as another.
|
||||||
|
- `envelope` gains a two-step seal for a signer that cannot be called synchronously:
|
||||||
|
- `Envelope::to_be_signed(author, cert, schema, hlc, payload)` gives the bytes to sign.
|
||||||
|
- `Envelope::with_signature(tbs, sig)` finishes the envelope. It checks the signature against the author
|
||||||
|
before returning, so a broken signer cannot produce an envelope that others would drop.
|
||||||
|
- `seal` is unchanged.
|
||||||
|
- No hand-written crypto: Ed25519 is WebCrypto's in the browser and `ed25519-dalek` everywhere it is checked.
|
||||||
|
|
||||||
|
## 3. Live subscribe
|
||||||
|
|
||||||
|
As in V1_1 §5, with the details settled:
|
||||||
|
|
||||||
|
- **`GET /v1/live`** upgrades to a WebSocket.
|
||||||
|
- **Subscribing.** The client's first message (text, JSON) lists up to 32 subscriptions:
|
||||||
|
```json
|
||||||
|
{"subscribe": [{"mailbox": "<id>", "after": 17, "key": "…", "time": "…", "nonce": "…", "sig": "…"}]}
|
||||||
|
```
|
||||||
|
- Each one is signed like a request, with method `LIVE`, path `/v1/mailboxes/{id}/live?after={after}` and
|
||||||
|
an empty body. The relay checks it like any request: time, signature, registration in that mailbox,
|
||||||
|
replay, rate. A subscription that fails is answered `{"mailbox", "error"}`, and the others still count.
|
||||||
|
- A WebSocket from a browser cannot carry the `Tab-*` headers, which is why the signatures travel in the
|
||||||
|
message.
|
||||||
|
- **Notices.** The relay sends `{"mailbox", "seq"}` when that mailbox holds a message with a higher seq than
|
||||||
|
`after`. It sends one at once if there already is one, and then one per append. It never sends the
|
||||||
|
message itself; the client fetches as it does today. Notices only say "something is new": a client that
|
||||||
|
misses one loses nothing, because its next fetch starts from its cursor.
|
||||||
|
- **Removed keys.** A key deregistered while subscribed gets `{"mailbox", "error": "unregistered_key"}`, and
|
||||||
|
that subscription ends. The relay checks the registration again before every notice.
|
||||||
|
- **Keeping it open.** The client sends `{"ping": true}` at least every 5 minutes, and the relay answers
|
||||||
|
`{"pong": true}`. After **10 minutes** with nothing from the client, the relay closes the socket.
|
||||||
|
- **Limits:** 32 subscriptions per connection; **4 open subscriptions per mailbox key** (the 5th is refused
|
||||||
|
`too_many`). Rate counting is the same per key as for requests.
|
||||||
|
- **In memory only.** Nothing about a socket is stored or logged. One process-wide broadcast of
|
||||||
|
`(mailbox, seq)` feeds every socket. A socket that falls behind it is told to re-fetch everything it
|
||||||
|
watches (`{"mailbox", "seq": null}` for each).
|
||||||
|
- **The core is sans-IO here.** `Core::live_subscribe()` returns the signed first message for every active
|
||||||
|
group, and `Core::live_notice(text)` names the group that has mail. The drivers own the socket. The
|
||||||
|
browser package uses it; the native `Client` gets no socket yet (desktop apps keep polling).
|
||||||
|
- **Privacy:** no worse than polling, as V1_1 §5 says. A socket that watches several mailboxes links them,
|
||||||
|
as fetching them from one address already does. The JS package therefore opens one socket per group by
|
||||||
|
default.
|
||||||
|
|
||||||
|
## 4. CORS
|
||||||
|
|
||||||
|
A PWA at `fiscus.…` calling `tabellarius.…` needs CORS. **(choice)** The relay answers every request with
|
||||||
|
`Access-Control-Allow-Origin: *`, and a preflight (`OPTIONS`) with the methods, the `content-type` and
|
||||||
|
`tab-*` headers, and `max-age` one day.
|
||||||
|
- `*` is safe here because nothing is authorised by a cookie or by the origin. Every request is authorised
|
||||||
|
only by its signature, and browsers never send cookies to a `*` origin.
|
||||||
|
- **Caddy strips `Origin`, `Referer` and `User-Agent` before the relay sees them.** The relay never learns
|
||||||
|
which app a request came from. (The browser still sends `Origin`, so the TLS endpoint sees it, as it sees
|
||||||
|
the address. Caddy's access log stays off.)
|
||||||
|
- The CORS handling is ~20 lines in the relay, tested, not a new dependency.
|
||||||
|
- *Alternative:* proxy the relay under each app's own origin (`fiscus.…/tabellarius/`). No CORS, but every
|
||||||
|
app's vhost then knows which app talks to the relay, and the relay would need one configuration per app.
|
||||||
|
|
||||||
|
## 5. The JS package (`@domi/fundamentum`, v0.5.0)
|
||||||
|
|
||||||
|
- `crates/wasm` (`wasm-bindgen`) wraps `Core<Fetch, WebCryptoSigner>`. `packages/fundamentum` holds the
|
||||||
|
generated module and a small hand-written `index.js`. Each PWA serves it itself; nothing comes from a CDN.
|
||||||
|
- **API** (mirrors the Rust one):
|
||||||
|
- `Fundamentum.open({relay, cert, key, state})` takes the cert text, the non-extractable `CryptoKey` and
|
||||||
|
the previously saved state.
|
||||||
|
- Then: `selfGroup`, `openGroup`, `groups`, `invite`, `join`, `send`, `sync`, `log`, `members`, `remove`,
|
||||||
|
`applyRevocation`, `backup`, `restore`, `import`.
|
||||||
|
- `subscribe(onChange)` opens the sockets and runs `sync` when a notice arrives.
|
||||||
|
- **State:** after every call that changes it, the package hands the encrypted state to `onSave(bytes)`.
|
||||||
|
It is encrypted with a non-extractable WebCrypto AES-GCM key (V1_1 §4), and the app keeps it in IndexedDB.
|
||||||
|
- The plaintext exists only inside the page, which already holds the wasm memory that contains it. This
|
||||||
|
is the same trust boundary as the desktop app's process.
|
||||||
|
- **Calls are serialised:** the package queues them, so two `sync`s never run at once. If one still
|
||||||
|
overlaps, the core answers `busy` instead of panicking.
|
||||||
|
- **The browser build:** `wasm32-unknown-unknown`, with the browser's randomness (`getrandom` `wasm_js`)
|
||||||
|
and OpenMLS's `js` feature, built in WSL with nix (rustup targets are not installed on the dev machine). It
|
||||||
|
is checked by a test page against a local relay: a native CLI device and a browser device join one group,
|
||||||
|
exchange events both ways, and the browser hears the live notice.
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
**v0.4.0:**
|
||||||
|
- `Core<T, S>` with `Transport` and `DeviceSigner`. `Client` is the native driver, and its API is
|
||||||
|
unchanged.
|
||||||
|
- The two-step seal: `Envelope::to_be_signed` and `with_signature`.
|
||||||
|
- `/v1/live`, with `Core::live_subscribe` and `live_notice`.
|
||||||
|
- CORS, and Caddy stripping `Origin`, `Referer` and `User-Agent`.
|
||||||
|
|
||||||
|
Tested against the in-process relay:
|
||||||
|
- A core whose transport and signer really wait pairs and syncs with a native device.
|
||||||
|
- A device hears that its group has mail, and later that it was removed.
|
||||||
|
- The relay's checks and limits on subscriptions hold.
|
||||||
|
- The preflight works.
|
||||||
|
|
||||||
|
Not built for `wasm32` yet; that comes with `crates/wasm` in v0.5.0.
|
||||||
|
|
||||||
|
**v0.5.0:** `crates/wasm` and `packages/fundamentum` (`index.js`; `pkg/` is built by `build.sh` in
|
||||||
|
`nix develop .#wasm` and is not in git). The wasm module is 3.1 MB.
|
||||||
|
|
||||||
|
The browser check (packages/fundamentum/README.md) passed on 2026-11-04 in the desktop app's Chromium,
|
||||||
|
against a local relay, cross-origin:
|
||||||
|
- A native CLI device and a browser device joined one self group. The browser's credential and events were
|
||||||
|
signed by its non-extractable WebCrypto key; `exportKey` refused with `InvalidAccessError`.
|
||||||
|
- Events went both ways, and the browser heard the CLI's event live and synced it.
|
||||||
|
- The sealed state reopened to the same log. It does not show the group id, and a wrong AES key does not
|
||||||
|
open it.
|
||||||
|
|
||||||
|
**Seen while testing it:** a browser sends a CORS preflight (`OPTIONS`) before each relay request, because
|
||||||
|
the URL changes (`?after=N`) and preflights are cached per URL. That doubles the round trips. The answers
|
||||||
|
are small and unsigned, and do not count against the rate limit.
|
||||||
|
- *Possible later:* put `after` into a signed header so the URL stays the same. That would be a protocol
|
||||||
|
change.
|
||||||
|
|
||||||
|
**Not checked:**
|
||||||
|
- A real phone.
|
||||||
|
- WebKit/Firefox. Ed25519 in WebCrypto is recent there.
|
||||||
|
- The live server (it needs the `nixos-rebuild` for v0.4.0's relay).
|
||||||
|
|
||||||
|
## Not in v1.1b
|
||||||
|
- Pairing a phone end to end (the PWA asking the factor service for its cert, as day 1 did for the Custos web
|
||||||
|
vault). This needs the live server.
|
||||||
|
- A native WebSocket driver for desktop apps.
|
||||||
|
- Service-worker push while the PWA is closed: no third-party push service (Domi rule), so a closed PWA
|
||||||
|
syncs when it is opened.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
max_width = 120
|
||||||
|
use_small_heuristics = "Max"
|
||||||
Reference in New Issue
Block a user