Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ jobs:
run: |
cargo clippy -p keygo-core --all-targets -- -D warnings
deps=$(cargo tree -p keygo-core -e normal --depth 1 --prefix none | tail -n +2 | cut -d' ' -f1 | sort | xargs)
[ "$deps" = "serde thiserror uuid" ] || { echo "unexpected keygo-core deps: $deps" >&2; exit 1; }
[ "$deps" = "base64 serde thiserror uuid" ] || { echo "unexpected keygo-core deps: $deps" >&2; exit 1; }
- name: keygo-server holds no crypto or client code
run: |
# Proves the pattern below still matches, so renaming the feature can't silently disable it.
Expand Down
1 change: 1 addition & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion rust/crates/keygo-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ crypto = [
serde = { workspace = true, features = ["derive"] }
thiserror.workspace = true
uuid.workspace = true
base64.workspace = true

aead = { version = "0.6.0", optional = true }
aes-gcm-siv = { version = "0.12.1", optional = true }
Expand All @@ -30,4 +31,4 @@ sha2 = { workspace = true, optional = true }
zeroize = { workspace = true, features = ["derive"], optional = true }

[dev-dependencies]
base64.workspace = true
serde_json.workspace = true
3 changes: 2 additions & 1 deletion rust/crates/keygo-core/src/crypto/cipher.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{KEY_LEN, NONCE_LEN, Sealed};
use crate::{KEY_LEN, NONCE_LEN, Sealed, TAG_LEN};
use aead::array::typenum::Unsigned;
use aead::{Aead, AeadCore, Generate, KeyInit, KeySizeUser, Nonce, Payload};
use aes_gcm_siv::Aes256GcmSiv;
Expand All @@ -10,6 +10,7 @@ pub type CipherKey = aead::Key<Cipher>;
// `sealed.rs` is compiled without the cipher, so it cannot ask it for these.
const _: () = assert!(KEY_LEN == <<Cipher as KeySizeUser>::KeySize as Unsigned>::USIZE);
const _: () = assert!(NONCE_LEN == <<Cipher as AeadCore>::NonceSize as Unsigned>::USIZE);
const _: () = assert!(TAG_LEN == <<Cipher as AeadCore>::TagSize as Unsigned>::USIZE);

impl<T: ?Sized> Sealed<T> {
pub(crate) fn seal(key: &CipherKey, plaintext: &[u8], aad: &[u8]) -> Result<Self, aead::Error> {
Expand Down
2 changes: 1 addition & 1 deletion rust/crates/keygo-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ pub use crypto::*;
pub use error::{CryptoError, CryptoResult};
pub use ids::{ItemId, NamespaceId, UserId, VaultId};
pub use keys::{AccountRootKey, BackupKey, ItemKey, NamespaceKey, RootKek, VaultKey};
pub use sealed::{KEY_LEN, NONCE_LEN, Sealed};
pub use sealed::{KEY_LEN, NONCE_LEN, Sealed, TAG_LEN};
126 changes: 126 additions & 0 deletions rust/crates/keygo-core/src/sealed.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
use crate::error::{CryptoError, CryptoResult};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::marker::PhantomData;

pub const KEY_LEN: usize = 32;
pub const NONCE_LEN: usize = 12;
pub const TAG_LEN: usize = 16;

pub struct Sealed<T: ?Sized> {
pub(crate) nonce: [u8; NONCE_LEN],
Expand Down Expand Up @@ -38,6 +42,53 @@ impl<T: ?Sized> Sealed<T> {
pub fn into_parts(self) -> (Vec<u8>, Vec<u8>) {
(self.nonce.to_vec(), self.ciphertext)
}

pub fn to_bytes(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(NONCE_LEN + self.ciphertext.len());
out.extend_from_slice(&self.nonce);
out.extend_from_slice(&self.ciphertext);
out
}

pub fn from_bytes(bytes: &[u8]) -> CryptoResult<Self> {
let (nonce, ciphertext) =
bytes
.split_first_chunk::<NONCE_LEN>()
.ok_or(CryptoError::InvalidNonceLength {
expected: NONCE_LEN,
got: bytes.len(),
})?;

Ok(Self {
nonce: *nonce,
ciphertext: ciphertext.to_vec(),
content: PhantomData,
})
}
}

impl<T: ?Sized> Serialize for Sealed<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
URL_SAFE_NO_PAD
.encode(self.to_bytes())
.serialize(serializer)
}
}

impl<'de, T: ?Sized> Deserialize<'de> for Sealed<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let data = String::deserialize(deserializer)?;
let data = URL_SAFE_NO_PAD
.decode(data)
.map_err(serde::de::Error::custom)?;
Self::from_bytes(&data).map_err(serde::de::Error::custom)
}
}

#[cfg(test)]
Expand Down Expand Up @@ -68,4 +119,79 @@ mod tests {
assert_eq!(wrapped.nonce(), [7; NONCE_LEN]);
assert_eq!(wrapped.ciphertext(), [1, 2, 3]);
}

fn json(value: &str) -> String {
format!(r#""{value}""#)
}

fn parse(value: &str) -> serde_json::Result<Sealed<[u8]>> {
serde_json::from_str(&json(value))
}

#[test]
fn bytes_are_the_nonce_then_the_ciphertext() {
let sealed = Sealed::<[u8]>::from_parts(&[7; NONCE_LEN], vec![1, 2, 3]).unwrap();
assert_eq!(
sealed.to_bytes(),
[[7; NONCE_LEN].as_slice(), &[1, 2, 3]].concat()
);
}

#[test]
fn bytes_round_trip() {
let bytes = [[7; NONCE_LEN].as_slice(), &[1, 2, 3]].concat();
let sealed = Sealed::<[u8]>::from_bytes(&bytes).unwrap();

assert_eq!(sealed.nonce(), [7; NONCE_LEN]);
assert_eq!(sealed.ciphertext(), [1, 2, 3]);
assert_eq!(sealed.to_bytes(), bytes);
}

#[test]
fn from_bytes_rejects_a_blob_too_short_for_a_nonce() {
assert!(matches!(
Sealed::<[u8]>::from_bytes(&[7; NONCE_LEN - 1]),
Err(CryptoError::InvalidNonceLength {
expected: NONCE_LEN,
got: 11,
})
));
}

/// The wire form is API identity: changing this string breaks every client and stored blob.
#[test]
fn json_form_is_pinned() {
let sealed = Sealed::<[u8]>::from_parts(&[7; NONCE_LEN], vec![1, 2, 3]).unwrap();
assert_eq!(
serde_json::to_string(&sealed).unwrap(),
json("BwcHBwcHBwcHBwcHAQID"),
);
}

#[test]
fn json_round_trip() {
let parsed = parse("BwcHBwcHBwcHBwcHAQID").unwrap();
assert_eq!(parsed.into_parts(), (vec![7; NONCE_LEN], vec![1, 2, 3]));
}

#[test]
fn json_uses_the_url_safe_alphabet() {
let parsed = parse("BwcHBwcHBwcHBwcH-w").unwrap();
assert_eq!(parsed.ciphertext(), [0xfb]);
}

#[test]
fn json_rejects_the_standard_alphabet() {
assert!(parse("BwcHBwcHBwcHBwcH+w").is_err());
}

#[test]
fn json_rejects_padding() {
assert!(parse("BwcHBwcHBwcHBwcH-w==").is_err());
}

#[test]
fn json_rejects_a_blob_too_short_for_a_nonce() {
assert!(parse("BwcHBwcHBwcHBwc").is_err());
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions rust/crates/keygo-server/migrations/20261014141017_init.sql
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ create table users
created_at timestamptz not null default now()
);

create table key_bundles
(
user_id uuid primary key references users on delete cascade,
wrapped_ark bytea not null, -- nonce ‖ ct, 60 B
updated_at timestamptz not null default now()
);

create table devices
(
id uuid primary key,
Expand Down
16 changes: 15 additions & 1 deletion rust/crates/keygo-server/src/api/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::domain::UsernameError;
use crate::domain::{InvalidBlob, UsernameError};
use axum::extract::rejection::JsonRejection;
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
Expand Down Expand Up @@ -137,6 +137,12 @@ impl HttpError for JsonRejection {
}
}

impl HttpError for InvalidBlob {
fn code(&self) -> ErrorCode {
ErrorCode::InvalidRequest
}
}

impl HttpError for UsernameError {
fn code(&self) -> ErrorCode {
ErrorCode::InvalidUsername
Expand Down Expand Up @@ -195,6 +201,14 @@ mod tests {
assert_eq!(body["code"], "invalid_request");
}

#[tokio::test]
async fn invalid_blobs_are_invalid_requests() {
let (status, body) = render(InvalidBlob).await;

assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(body["code"], "invalid_request");
}

#[tokio::test]
async fn invalid_usernames_are_bad_requests() {
let (status, body) = render(UsernameError::TooShort).await;
Expand Down
9 changes: 6 additions & 3 deletions rust/crates/keygo-server/src/api/routes/auth/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::api::dpop::SingleUseDpopProof;
use crate::api::routes::auth::handshake::StartResponse;
use crate::api::routes::auth::session::Session;
use crate::api::{AppState, Json, ServerResult};
use crate::domain::{DeviceClaim, LoginId, UserId, Username};
use crate::domain::{DeviceClaim, KeyBundle, LoginId, UserId, Username};
use crate::service::login::{self, FinishLogin, StartLogin};
use axum::Router;
use axum::extract::State;
Expand Down Expand Up @@ -49,6 +49,7 @@ struct FinishRequest {
struct FinishResponse {
user_id: UserId,
username: Username,
key_bundle: KeyBundle,
session: Session,
}

Expand All @@ -71,6 +72,7 @@ async fn finish(
Ok(Json(FinishResponse {
user_id: finished.user_id,
username: finished.username,
key_bundle: finished.key_bundle,
session: finished.session.into(),
}))
}
Expand All @@ -79,8 +81,8 @@ async fn finish(
mod tests {
use super::*;
use crate::testing::{
PASSWORD, app_state, count, device_json, post_to, post_with_proof, proof_post, prover,
register, replayable_post, send,
PASSWORD, app_state, count, device_json, key_bundle_json, post_to, post_with_proof,
proof_post, prover, register, replayable_post, send,
};
use axum::http::StatusCode;
use keygo_opaque::CredentialResponse;
Expand Down Expand Up @@ -135,6 +137,7 @@ mod tests {
assert_eq!(status, StatusCode::OK);
assert_eq!(finished["user_id"], user_id.as_uuid().to_string());
assert_eq!(finished["username"], "ada");
assert_eq!(finished["key_bundle"], key_bundle_json());
assert_eq!(state.login_states.count(), 0);
}

Expand Down
Loading
Loading