From 9bf334bedbc4b0cc3ce32fcd3baef27d3072f194 Mon Sep 17 00:00:00 2001 From: tv Date: Thu, 19 Nov 2026 20:11:05 +0000 Subject: federated nodes: a party's keys log in as the party, for federation work A party's people work with the federation by signing as the party, with a key of its set; what they need of a node is to read and to put events, which a node's users, its operators, may do with every power besides. POST /auth/login/party takes a challenge (POST /auth/challenge) signed with one of the keys that sign for the party (fold::State::signing_keys: those its current version names, and its key set as it counts), for the namespace continuum-login, armored or as the federation spells a signature (keys::signer, keys::verifies_in: the federation's checks, but for the namespace), and answers a token as the party. Logins by key are counted per party as per user (challenge::take_with, shared with logging in by a registry's keys). The token names the key (Claims::party). Such a session does federation work alone (api::access::federated): what --store-readers do, and POST /events; anything else is 403. Every request checks that the key still signs for the party: once a version or the party's key set drops it, 401. A build from before reads no token naming a key, as its claims deny fields they don't know, so never takes a party's session for a user's; and only the node that issued it takes it, as every token in a federated swarm. --- CHANGELOG.md | 6 ++ docs/guides/federation/running-a-node.md | 9 ++ docs/openapi.yaml | 38 ++++++++- src/access/challenge.rs | 34 ++++++-- src/access/token.rs | 38 +++++++++ src/api/access.rs | 62 ++++++++++---- src/api/login.rs | 81 ++++++++++++++++++ src/api/mod.rs | 93 +++++++++++---------- src/federation/fold.rs | 16 ++++ src/federation/keys.rs | 136 ++++++++++++++++++++++++------- 10 files changed, 414 insertions(+), 99 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a4b6e56..c0c3c75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ it from the release before ([`docs/operations.md`](docs/operations.md), ## Unreleased +* A party's keys log in to every federated node without a password, as the party + (`POST /auth/login/party`): a session that reads and puts events and checks forks, and + does nothing else ([`docs/guides/federation/running-a-node.md`](docs/guides/federation/running-a-node.md), + [Its API](docs/guides/federation/running-a-node.md#its-api); + [`src/api/login.rs`](src/api/login.rs), [`src/api/access.rs`](src/api/access.rs)). + * A federated node's users named in `--store-readers` read the federation there and do nothing else; its other users are its operators, as all were ([`docs/guides/federation/running-a-node.md`](docs/guides/federation/running-a-node.md), diff --git a/docs/guides/federation/running-a-node.md b/docs/guides/federation/running-a-node.md index e08a47e..ea51f8a 100644 --- a/docs/guides/federation/running-a-node.md +++ b/docs/guides/federation/running-a-node.md @@ -71,6 +71,15 @@ alone, so that a party listing many nodes can't be all of a node's neighbours. what an operator does to the store (`/admin/events/…`): for an application, or someone watching, that needn't act for the node. A token is taken by the node that issued it only, and gives what its user may do. +* **A party's keys** log in to every node holding the store, without a password: a + challenge (`POST /auth/challenge`) signed with one of the keys that sign for the party + there (those its current version names, or of its key set as it counts), for the + namespace `continuum-login`, gives a token as the party (`POST /auth/login/party`). + Such a session does federation work alone: what a reader does, and putting events + (`POST /events`), while that key signs for the party (`401` once it doesn't). So a + party's people, each with a key of its set, work with the federation through any node + that holds it, as no operator has to let them in, and with nothing of an operator's + powers. * **The events** (`docs/openapi.yaml`, Events): `GET /events` (the store's ID, its checkpoint, its heads, how many events it took, the node's party, and whether it votes for it by itself), `POST /events` (an event, whoever signed it), `GET /events/{id}`, diff --git a/docs/openapi.yaml b/docs/openapi.yaml index a64c739..797c46f 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -902,6 +902,42 @@ paths: '409': { description: No user registry, which holds the keys. } '503': { description: Not ready yet. } + /auth/login/party: + post: + tags: [Auth, Events] + summary: Log in as a party, by one of its keys (federation) + description: | + On a node holding a federated store (`federation` feature): a challenge + (`POST /auth/challenge`) signed by one of the keys that sign for the party there, + those its current version names or of its key set as it counts, for the namespace + `continuum-login` (an ECDSA signature's `s` low, as for events). A token as the + party (`login: party`): a party's session, which does federation work alone, + reading the events API, putting events and checking forks, while that key signs + for the party (`401` once it doesn't); anything else is `403`. The node that + issued it alone takes it. No authentication: the signature proves the party. + security: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [party, challenge, signature] + properties: + party: { type: string } + challenge: { type: string } + signature: { type: string, description: 'Armored, as `ssh-keygen -Y sign -n continuum-login` writes it, or its blob in base64.' } + responses: + '200': + description: The token. + content: + application/json: + schema: { $ref: '#/components/schemas/TokenAnswer' } + '400': { description: A request that isn't one. } + '401': { description: 'Not a challenge of this node, expired or used, or not signed by a key that signs for the party, or no party of the current version (the message says which).' } + '409': { description: No federated store here. } + '503': { description: Not ready yet. } + /auth/session: post: tags: [Auth] @@ -1038,7 +1074,7 @@ paths: get: tags: [Auth] summary: Who you are here - description: The swarm, the user, how it proved it (`htpasswd`, `header`, `token`), its registry entry's capabilities (`caps`), what this request may do (`may`, a list of capabilities; with a token that says less, what both give), and its token's claims if it came with one. + description: The swarm, the user, how it proved it (`htpasswd`, `header`, `token`), its registry entry's capabilities (`caps`), what this request may do (`may`, a list of capabilities; with a token that says less, what both give), and its token's claims if it came with one (of a party's session, `party`: the key it logged in with). responses: '200': description: Who. diff --git a/src/access/challenge.rs b/src/access/challenge.rs index e61ea85..8df0f08 100644 --- a/src/access/challenge.rs +++ b/src/access/challenge.rs @@ -78,6 +78,31 @@ pub(crate) fn take( now: u64, used: &mut Used, per_user: usize, +) -> Result<(), String> { + take_with(key, challenge, user, now, used, per_user, |challenge| { + let signer = sshsig::verify(signature, NAMESPACE, challenge.as_bytes())?; + let entry = registry::user(doc, user).ok_or_else(|| format!("no user {user}"))?; + if entry.disabled { + return Err(format!("{user} is disabled")); + } + if !entry.keys.values().any(|known| *known == signer) { + return Err(format!("{user} has no key {}", signer.fingerprint())); + } + Ok(()) + }) +} + +/// Takes `challenge` as a login of `user`, where `check` says that `user` signed it: a +/// challenge of `key`'s node, unexpired at `now`, not used before (then used, in `used`), +/// with fewer than `per_user` of `user`'s own still remembered. Why not, if not. +pub(crate) fn take_with( + key: &NodeKey, + challenge: &str, + user: &str, + now: u64, + used: &mut Used, + per_user: usize, + check: impl FnOnce(&str) -> Result<(), String>, ) -> Result<(), String> { let mut parts = challenge.split('.'); let (Some(PREFIX), Some(payload), Some(signed), None) = @@ -116,14 +141,7 @@ pub(crate) fn take( if used.0.len() >= MAX_USED { return Err("too many logins by key at once: try again in a while".to_owned()); } - let signer = sshsig::verify(signature, NAMESPACE, challenge.as_bytes())?; - let entry = registry::user(doc, user).ok_or_else(|| format!("no user {user}"))?; - if entry.disabled { - return Err(format!("{user} is disabled")); - } - if !entry.keys.values().any(|known| *known == signer) { - return Err(format!("{user} has no key {}", signer.fingerprint())); - } + check(challenge)?; used.0.insert(payload.nonce, (payload.exp, user.to_owned())); Ok(()) } diff --git a/src/access/token.rs b/src/access/token.rs index 0920410..650a5c4 100644 --- a/src/access/token.rs +++ b/src/access/token.rs @@ -58,6 +58,13 @@ pub(crate) struct Claims { /// Less than the user may do: only what these allow too. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) limit: Option>, + /// Of a party's session, on a node holding a federated store: the key, as the + /// federation spells it, that `user`, the party, logged in with + /// (`api::login::login_party`). Such a token does federation work alone, while that + /// key signs for the party (`api::access::federated`); a build from before it reads + /// none (`deny_unknown_fields`), so never takes it for its user's. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) party: Option, } /// `claims`, signed by `key`, as a token. @@ -243,6 +250,7 @@ mod tests { session_exp: 10_000, login_exp: 10_000, limit: None, + party: None, } } @@ -251,6 +259,36 @@ mod tests { change(doc, |tx| store::write_path(tx, &path, &json!({})).unwrap()); } + /// A party's session names the key it logged in with, which a token of a user's + /// leaves out: a build from before it reads none (its claims deny fields it doesn't + /// know), so never takes it for its user's. + #[test] + fn a_partys_session_names_its_key() { + let key = NodeKey::from_seed([1; 32]); + let mut doc = Document::new(); + member(&mut doc, &key); + let party = Claims { + user: "tv".to_owned(), + login: "party".to_owned(), + party: Some("ssh-ed25519 AAAA".to_owned()), + ..claims(&key) + }; + let token = issue(&key, &party); + assert_eq!(verify(&doc, &token, "s", 1_500), Ok(party)); + let (_, payload) = token.split_once('.').unwrap(); + let (payload, _) = payload.split_once('.').unwrap(); + let payload = String::from_utf8(BASE64URL.decode(payload).unwrap()).unwrap(); + assert!( + payload.contains(r#""party":"ssh-ed25519 AAAA""#), + "{payload}" + ); + let user = issue(&key, &claims(&key)); + let (_, payload) = user.split_once('.').unwrap(); + let (payload, _) = payload.split_once('.').unwrap(); + let payload = String::from_utf8(BASE64URL.decode(payload).unwrap()).unwrap(); + assert!(!payload.contains("party"), "{payload}"); + } + #[test] fn issued_and_taken() { let key = NodeKey::from_seed([1; 32]); diff --git a/src/api/access.rs b/src/api/access.rs index 47e24ba..339d9de 100644 --- a/src/api/access.rs +++ b/src/api/access.rs @@ -394,33 +394,61 @@ pub(crate) async fn authorize( } /// On a node holding a federated store, what its users who aren't its operators may do: a -/// user of `--store-readers` reads the federation (`federation_work`), and nothing else. -/// Its other users are its operators, who may do everything. The answer refusing the -/// request, where it is refused. +/// party's session (a token from a party's key, `login::login_party`) does federation work +/// (`federation_work`), putting events too, while the key it logged in with signs for +/// the party (`fold::State::signing_keys`); a user of `--store-readers` reads the +/// federation; and neither does anything else. Its other users are its operators, who may +/// do everything. The answer refusing the request, where it is refused. #[cfg(feature = "federation")] fn federated(state: &AppState, request: &Request, user: &str) -> Option { - if !state.store_readers.contains(user) { + let party_key = request + .extensions() + .get::() + .and_then(|token| token.claims.party.clone()); + if party_key.is_none() && !state.store_readers.contains(user) { return None; } - if state.holding.with(|_| ()).is_none() { - return Some(error_response( - StatusCode::FORBIDDEN, - format!("{user} reads a federated store here alone, and this node holds none"), - None, - )); + let signs = state.holding.with(|store| { + let read = store.state(); + party_key + .as_ref() + .is_none_or(|key| read.signing_keys(user, read.current()).contains(key)) + }); + let refused = |status: StatusCode, why: String| { + debug!(user = %user, method = %request.method(), path = %request.uri().path(), reason = %why, "Refused a request of a party or a reader"); + Some(error_response(status, why, None)) + }; + match signs { + None => { + return refused( + StatusCode::FORBIDDEN, + format!("{user} works with a federated store here alone, and this node holds none"), + ); + } + Some(false) => { + return refused( + StatusCode::UNAUTHORIZED, + format!("the key {user} logged in with signs for it no more: log in again"), + ); + } + Some(true) => {} } - if federation_work(request.method(), request.uri().path(), false) { + let puts = party_key.is_some(); + if federation_work(request.method(), request.uri().path(), puts) { return None; } - debug!(user = %user, method = %request.method(), path = %request.uri().path(), "Refused a reader's request that doesn't read the federation"); - Some(error_response( - StatusCode::FORBIDDEN, + let why = if puts { + format!( + "a session of {user}, a party, does federation work alone: reading and putting \ + events (docs/guides/federation/running-a-node.md, Its API)" + ) + } else { format!( "{user} reads the federation here, and does nothing else (--store-readers; \ docs/guides/federation/running-a-node.md, Its API)" - ), - None, - )) + ) + }; + refused(StatusCode::FORBIDDEN, why) } /// Whether a request is federation work: reading the events API (`GET` and `HEAD` of diff --git a/src/api/login.rs b/src/api/login.rs index 0658a69..ffcf9b8 100644 --- a/src/api/login.rs +++ b/src/api/login.rs @@ -8,6 +8,9 @@ //! * `POST /auth/challenge` and `POST /auth/login/key`, without a password: a challenge //! to sign with one of the user's keys, then the same token for it, signed //! (`access::challenge`). +//! * `POST /auth/login/party`, without a password, on a node holding a federated store: a +//! token as a party, for a challenge signed with one of the keys that sign for it there, +//! which does federation work alone (`login_party`). //! * `POST /auth/refresh`, with a token: a new one for the same login, signed by this //! node, optionally narrower still (`limit`, within the token's). //! * `POST /auth/logout`: every token of the user, of every login, no longer taken @@ -279,6 +282,7 @@ fn new_login( session_exp, login_exp: session_exp, limit, + party: None, } } @@ -322,6 +326,82 @@ pub(crate) struct KeyLogin { limit: Option>, } +/// A party's login by one of its keys (`POST /auth/login/party`). +#[cfg(feature = "federation")] +#[derive(Deserialize)] +pub(crate) struct PartyLogin { + party: String, + challenge: String, + /// Armored, as `ssh-keygen -Y sign -n continuum-login` writes it, or its blob in base64. + signature: String, +} + +/// `POST /auth/login/party`: on a node holding a federated store, a token as `party` for a +/// challenge signed with one of the keys that sign for it there, as its current version +/// and its key set say (`fold::State::signing_keys`), as `ssh-keygen -Y sign -n +/// continuum-login` signs, an ECDSA signature's `s` low (`401` if not, saying why): a +/// party's session, which does federation work alone, while that key signs for the +/// party (`api::access::federated`). `409` on a node holding none. +#[cfg(feature = "federation")] +pub(crate) async fn login_party( + State(state): State, + Json(request): Json, +) -> Result { + let (swarm, now) = issuing(&state).await?; + let key = state + .node_key + .as_ref() + .ok_or(ApiError(StatusCode::SERVICE_UNAVAILABLE, None))?; + let party = request.party.as_str(); + let keys = state + .holding + .with(|store| { + let read = store.state(); + read.signing_keys(party, read.current()) + }) + .ok_or_else(|| { + ApiError( + StatusCode::CONFLICT, + Some("no federated store here, whose parties' keys log in".to_owned()), + ) + })?; + let signer = { + let mut used = state.challenges.lock_or_recover(); + let mut signer = None; + challenge::take_with( + key, + &request.challenge, + &format!("party {party}"), + now, + &mut used, + state.key_logins_per_user, + |challenge| { + if keys.is_empty() { + return Err(format!("{party} is no party of the current version")); + } + let found = crate::federation::keys::signer( + &keys, + challenge::NAMESPACE, + &request.signature, + challenge.as_bytes(), + ) + .ok_or_else(|| format!("signed by none of the keys that sign for {party}"))?; + signer = Some(found.to_owned()); + Ok(()) + }, + ) + .map_err(|why| { + debug!(party = %party, reason = %why, "Refused a party's login"); + ApiError(StatusCode::UNAUTHORIZED, Some(why)) + })?; + signer + }; + let mut claims = new_login(&state, swarm, now, party, "party", None, None); + claims.party = signer; + info!(party = %party, login = "party", session = %claims.session, "A party logged in"); + answer(&state, &claims) +} + /// `POST /auth/login/key`: a token, as `POST /auth/login` gives one, for a challenge /// signed by one of the user's keys (`401` if not, saying why); `409` in a swarm without /// a registry, which holds no keys. @@ -745,6 +825,7 @@ pub(crate) async fn whoami( "session": token.claims.session, "sessionExpiresAt": token.claims.session_exp, "limit": token.claims.limit, + "party": token.claims.party, }) }); Json(json!({ diff --git a/src/api/mod.rs b/src/api/mod.rs index d91c434..c4265fb 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -44,7 +44,8 @@ use crate::state::AppState; /// Builds the complete HTTP router. Everything except the API description (`/swagger-ui`, /// `/openapi.yaml`), `/health`, `/ready` and logging in by key (`/auth/challenge`, -/// `/auth/login/key`, which prove the user themselves) is authenticated. +/// `/auth/login/key`, `/auth/login/party`, which prove the user themselves) is +/// authenticated. pub(crate) fn router(state: AppState, auth_state: AuthState, debug_api: bool) -> Router { let mut api: Router = Router::new() .route("/store", get(store::get_store_root)) @@ -118,48 +119,54 @@ pub(crate) fn router(state: AppState, auth_state: AuthState, debug_api: bool) -> } // Inside authentication, which finds the user: what the user may do. - api.layer(middleware::from_fn_with_state( - state.clone(), - access::authorize, - )) - .layer(middleware::from_fn_with_state( - auth_state.clone(), - basic_auth, - )) - // Who has a password here (`/auth/keys`: a user's last key goes only then). - .layer(axum::Extension(auth_state)) - // A stream answered to a token ends with it (expired, revoked, its session ended). - .layer(middleware::from_fn_with_state( - state.clone(), - login::streams_end, - )) - // Outside authentication: a token, if the request brings one, names the user. - .layer(middleware::from_fn_with_state(state.clone(), login::bearer)) - // Outermost: pages of other origins, and their preflights, which bring no - // credentials. - .layer(middleware::from_fn_with_state(state.clone(), cors::cors)) - // The hand-written spec (`docs/openapi.yaml`), and the Swagger UI showing it. - .merge( - // Relative to the UI's page (`/swagger-ui/`), so it is found behind a proxy that - // serves the API under a path of its own too. - SwaggerUi::new("/swagger-ui").config(utoipa_swagger_ui::Config::from("../openapi.yaml")), - ) - .route("/openapi.yaml", get(openapi_spec)) - // Logging in by key: a challenge, and the token for it signed, without a password. - .route("/auth/challenge", axum::routing::post(login::challenge)) - .route("/auth/login/key", axum::routing::post(login::login_key)) - .route("/health", get(health::node_health)) - // To log in to the dashboard on, and the dashboard's page, without authentication - // (they hold nothing). - .route("/login", get(dashboard_login)) - .route("/admin/dashboard", get(dashboard_page)) - .route("/ready", get(health::ready)) - // Outermost, so authentication failures get the error body too. - .layer(middleware::from_fn(json_errors)) - .layer(middleware::from_fn(relative_redirects)) - // A line per request, as it is answered. - .layer(middleware::from_fn(request_log::log_requests)) - .with_state(state) + let router = api + .layer(middleware::from_fn_with_state( + state.clone(), + access::authorize, + )) + .layer(middleware::from_fn_with_state( + auth_state.clone(), + basic_auth, + )) + // Who has a password here (`/auth/keys`: a user's last key goes only then). + .layer(axum::Extension(auth_state)) + // A stream answered to a token ends with it (expired, revoked, its session ended). + .layer(middleware::from_fn_with_state( + state.clone(), + login::streams_end, + )) + // Outside authentication: a token, if the request brings one, names the user. + .layer(middleware::from_fn_with_state(state.clone(), login::bearer)) + // Outermost: pages of other origins, and their preflights, which bring no + // credentials. + .layer(middleware::from_fn_with_state(state.clone(), cors::cors)) + // The hand-written spec (`docs/openapi.yaml`), and the Swagger UI showing it. + .merge( + // Relative to the UI's page (`/swagger-ui/`), so it is found behind a proxy that + // serves the API under a path of its own too. + SwaggerUi::new("/swagger-ui") + .config(utoipa_swagger_ui::Config::from("../openapi.yaml")), + ) + .route("/openapi.yaml", get(openapi_spec)) + // Logging in by key: a challenge, and the token for it signed, without a password. + .route("/auth/challenge", axum::routing::post(login::challenge)) + .route("/auth/login/key", axum::routing::post(login::login_key)); + // A party's login by its key, on a node holding a federated store. + #[cfg(feature = "federation")] + let router = router.route("/auth/login/party", axum::routing::post(login::login_party)); + router + .route("/health", get(health::node_health)) + // To log in to the dashboard on, and the dashboard's page, without authentication + // (they hold nothing). + .route("/login", get(dashboard_login)) + .route("/admin/dashboard", get(dashboard_page)) + .route("/ready", get(health::ready)) + // Outermost, so authentication failures get the error body too. + .layer(middleware::from_fn(json_errors)) + .layer(middleware::from_fn(relative_redirects)) + // A line per request, as it is answered. + .layer(middleware::from_fn(request_log::log_requests)) + .with_state(state) } /// The HTTP router of a node that only relays (`--relay-only`): its figures and the log diff --git a/src/federation/fold.rs b/src/federation/fold.rs index 46dad27..dbe8d4f 100644 --- a/src/federation/fold.rs +++ b/src/federation/fold.rs @@ -221,6 +221,22 @@ impl State { self.latest(&candidates) } + /// The keys that sign for `party` by `current`, whatever they sign: those its version + /// names, and those of its key set as it counts; none where it is no party of it. + pub(crate) fn signing_keys(&self, party: &str, current: &Version) -> Vec { + let mut keys = current + .parties + .get(party) + .map(|given| given.keys.clone()) + .unwrap_or_default(); + for key in self.keys_of(party, current) { + if !keys.contains(&key) { + keys.push(key); + } + } + keys + } + /// The keys of `party` by `current`: those of its key set, or those its version names. pub(crate) fn keys_of(&self, party: &str, current: &Version) -> Vec { let Some(given) = current.parties.get(party) else { diff --git a/src/federation/keys.rs b/src/federation/keys.rs index aff7792..cf0f366 100644 --- a/src/federation/keys.rs +++ b/src/federation/keys.rs @@ -135,6 +135,12 @@ pub(crate) fn node_of(key: &Key) -> Option { /// Whether `sig` is `key`'s signature of `message`, spelled as the federation spells one. pub(crate) fn verifies(key: &Key, sig: &str, message: &[u8]) -> bool { + verifies_in(NAMESPACE, key, sig, message) +} + +/// Whether `sig` is `key`'s signature of `message` for `namespace`, spelled as the +/// federation spells one but for its namespace: a party's login (`access::challenge`). +pub(crate) fn verifies_in(namespace: &str, key: &Key, sig: &str, message: &[u8]) -> bool { let Ok(blob) = BASE64.decode(sig) else { return false; }; @@ -143,23 +149,23 @@ pub(crate) fn verifies(key: &Key, sig: &str, message: &[u8]) -> bool { } // The blob reads back to itself: what signing with this key writes around its // signature, all that follows what it writes around none. - let Some(signature) = blob.get(written(key, &[]).len()..) else { + let Some(signature) = blob.get(written(namespace, key, &[]).len()..) else { return false; }; - if blob != written(key, signature) { + if blob != written(namespace, key, signature) { return false; } match key { Key::Ed25519(public) => { - sshsig::verify_blob(&blob, NAMESPACE, message).is_ok_and(|signer| signer == *public) + sshsig::verify_blob(&blob, namespace, message).is_ok_and(|signer| signer == *public) } - Key::P256(point) => p256_verifies(point, signature, message), + Key::P256(point) => p256_verifies(namespace, point, signature, message), } } /// Whether `signature`, `r` and `s` as SSH's mpints, is the P-256 key `point`'s of -/// `message`, spelled one way: each mpint its shortest, `s` low. -fn p256_verifies(point: &[u8; 65], signature: &[u8], message: &[u8]) -> bool { +/// `message` for `namespace`, spelled one way: each mpint its shortest, `s` low. +fn p256_verifies(namespace: &str, point: &[u8; 65], signature: &[u8], message: &[u8]) -> bool { let Some(parsed) = ecdsa_signature(signature) else { return false; }; @@ -167,7 +173,7 @@ fn p256_verifies(point: &[u8; 65], signature: &[u8], message: &[u8]) -> bool { return false; } p256::ecdsa::VerifyingKey::from_sec1_bytes(point) - .is_ok_and(|key| key.verify(&signed(message), &parsed).is_ok()) + .is_ok_and(|key| key.verify(&signed(namespace, message), &parsed).is_ok()) } /// An ECDSA signature from `r` and `s`, SSH's mpints, where each is an integer from 1 to @@ -207,10 +213,35 @@ fn mpints(signature: &p256::ecdsa::Signature) -> Vec { out } +/// Of `keys`, as the federation spells them, the one whose signature of `message` for +/// `namespace` `signature` is: spelled as the federation spells one but for its namespace, +/// or armored, as `ssh-keygen -Y sign` writes it. None where it is none of theirs. +pub(crate) fn signer<'a>( + keys: &'a [String], + namespace: &str, + signature: &str, + message: &[u8], +) -> Option<&'a str> { + let signature = signature.trim(); + let sig = if signature.starts_with("-----BEGIN") { + BASE64.encode(sshsig::dearmor(signature).ok()?) + } else { + signature.to_owned() + }; + keys.iter() + .find(|line| key(line).is_some_and(|key| verifies_in(namespace, &key, &sig, message))) + .map(String::as_str) +} + /// `message` signed with `key`, as the federation spells a signature: what /// `ssh-keygen -Y sign -n continuum-federation` makes, unarmored. pub(crate) fn sign(key: &SigningKey, message: &[u8]) -> String { - let blob = sshsig::dearmor(&sshsig::sign(key, NAMESPACE, message)) + sign_in(NAMESPACE, key, message) +} + +/// As `sign`, for `namespace`. +pub(crate) fn sign_in(namespace: &str, key: &SigningKey, message: &[u8]) -> String { + let blob = sshsig::dearmor(&sshsig::sign(key, namespace, message)) .expect("a signature made here dearmors"); BASE64.encode(blob) } @@ -219,14 +250,24 @@ pub(crate) fn sign(key: &SigningKey, message: &[u8]) -> String { /// signature: what `ssh-keygen -Y sign -n continuum-federation` makes through the agent, /// unarmored, an ECDSA signature's `s` made low. pub(crate) fn sign_through(socket: &Path, key: &Key, message: &[u8]) -> Result { - let answer = super::agent::sign(socket, &key.blob(), &signed(message)) + sign_through_in(NAMESPACE, socket, key, message) +} + +/// As `sign_through`, for `namespace`. +pub(crate) fn sign_through_in( + namespace: &str, + socket: &Path, + key: &Key, + message: &[u8], +) -> Result { + let answer = super::agent::sign(socket, &key.blob(), &signed(namespace, message)) .map_err(|why| format!("{}: {why}", key.line()))?; - from_agent(key, &answer, message) + from_agent(namespace, key, &answer, message) } -/// The federation's signature of `message` by `key` from `answer`, the signature the agent -/// made of what SSHSIG signs, as SSH encodes one. -fn from_agent(key: &Key, answer: &[u8], message: &[u8]) -> Result { +/// The signature of `message` for `namespace` by `key` from `answer`, the signature the +/// agent made of what SSHSIG signs, as SSH encodes one. +fn from_agent(namespace: &str, key: &Key, answer: &[u8], message: &[u8]) -> Result { let mut reader = Reader(answer); if reader.string()? != key.kind().as_bytes() { return Err(format!("the agent's signature isn't an {} one", key.kind())); @@ -241,34 +282,35 @@ fn from_agent(key: &Key, answer: &[u8], message: &[u8]) -> Result Vec { +/// What a signature of `message` for `namespace` is made over: SSHSIG's signed data, hashed +/// with `sha512`. +fn signed(namespace: &str, message: &[u8]) -> Vec { sshsig::signed_data( - NAMESPACE.as_bytes(), + namespace.as_bytes(), b"", b"sha512", &Sha512::digest(message), ) } -/// The SSHSIG blob of a signature by `key`, of version 1, for the federation's namespace, -/// its reserved field empty, hashed with `sha512`: as `ssh-keygen` writes it around -/// `signature`, the key type's own. -fn written(key: &Key, signature: &[u8]) -> Vec { +/// The SSHSIG blob of a signature by `key`, of version 1, for `namespace`, its reserved +/// field empty, hashed with `sha512`: as `ssh-keygen` writes it around `signature`, the +/// key type's own. +fn written(namespace: &str, key: &Key, signature: &[u8]) -> Vec { let mut inner = Vec::new(); string(&mut inner, key.kind().as_bytes()); string(&mut inner, signature); let mut blob = b"SSHSIG".to_vec(); blob.extend_from_slice(&1u32.to_be_bytes()); string(&mut blob, &key.blob()); - string(&mut blob, NAMESPACE.as_bytes()); + string(&mut blob, namespace.as_bytes()); string(&mut blob, b""); string(&mut blob, b"sha512"); string(&mut blob, &inner); @@ -281,7 +323,7 @@ fn written(key: &Key, signature: &[u8]) -> Vec { #[cfg(test)] pub(crate) fn respelled(key: &Key, sig: &str) -> [String; 2] { let blob = BASE64.decode(sig).expect("base64"); - let rs = &blob[written(key, &[]).len()..]; + let rs = &blob[written(NAMESPACE, key, &[]).len()..]; let (r, s) = ecdsa_signature(rs).expect("r and s").split_scalars(); let high = p256::ecdsa::Signature::from_scalars(r, -s).expect("a signature"); let mut reader = Reader(rs); @@ -289,7 +331,7 @@ pub(crate) fn respelled(key: &Key, sig: &str) -> [String; 2] { let mut longer = Vec::new(); string(&mut longer, &[&[0], r].concat()); string(&mut longer, s); - [mpints(&high), longer].map(|numbers| BASE64.encode(written(key, &numbers))) + [mpints(&high), longer].map(|numbers| BASE64.encode(written(NAMESPACE, key, &numbers))) } #[cfg(test)] @@ -368,6 +410,36 @@ mod tests { assert!(!verifies(&public(&key), &elsewhere, b"an event")); } + /// Of a party's keys, the one that signed a login, for the login's namespace: spelled + /// as the federation spells a signature, or armored as `ssh-keygen` writes it; none + /// for another namespace, an event's included, or by another key. + #[test] + fn the_key_a_login_is_signed_with() { + let (tv, laptop) = (signer(6), signer(7)); + let keys = [public(&tv).line(), public(&laptop).line()]; + let login = "continuum-login"; + let sig = sign_in(login, &laptop, b"cc1.challenge"); + assert_eq!( + super::signer(&keys, login, &sig, b"cc1.challenge"), + Some(keys[1].as_str()) + ); + let armored = sshsig::sign(&laptop, login, b"cc1.challenge"); + assert_eq!( + super::signer(&keys, login, &armored, b"cc1.challenge"), + Some(keys[1].as_str()) + ); + assert_eq!(super::signer(&keys, login, &sig, b"cc1.other"), None); + let event = sign(&laptop, b"cc1.challenge"); + assert_eq!(super::signer(&keys, login, &event, b"cc1.challenge"), None); + let stranger = sign_in(login, &signer(8), b"cc1.challenge"); + assert_eq!( + super::signer(&keys, login, &stranger, b"cc1.challenge"), + None + ); + assert!(verifies_in(login, &public(&laptop), &sig, b"cc1.challenge")); + assert!(!verifies(&public(&laptop), &sig, b"cc1.challenge")); + } + #[test] fn a_signature_with_a_reserved_field_is_none() { let key = signer(5); @@ -399,7 +471,7 @@ mod tests { /// The `r` and `s` of `sig`, a signature by `key` as the federation spells one. fn rs<'a>(key: &Key, sig: &'a [u8]) -> &'a [u8] { - &sig[written(key, &[]).len()..] + &sig[written(NAMESPACE, key, &[]).len()..] } #[test] @@ -410,7 +482,7 @@ mod tests { let blob = BASE64.decode(&sig).expect("base64"); let ours = ecdsa_signature(rs(&key, &blob)).expect("r and s"); let refused = |rs: &[u8]| { - let other = BASE64.encode(written(&key, rs)); + let other = BASE64.encode(written(NAMESPACE, &key, rs)); assert!(!verifies(&key, &other, &message)); assert!(Event::read(ECDSA_WRITE.replace(&sig, &other).as_bytes()).is_none()); }; @@ -421,7 +493,11 @@ mod tests { unreachable!("an ECDSA key") }; let verifying = p256::ecdsa::VerifyingKey::from_sec1_bytes(&point).expect("a point"); - assert!(verifying.verify(&signed(&message), &twin).is_ok()); + assert!( + verifying + .verify(&signed(NAMESPACE, &message), &twin) + .is_ok() + ); assert_ne!(twin, ours); assert_eq!(twin.normalize_s(), ours); refused(&mpints(&twin)); @@ -532,7 +608,7 @@ mod tests { message.as_bytes(), ); if let Key::P256(_) = key { - let data = signed(message.as_bytes()); + let data = signed(NAMESPACE, message.as_bytes()); let high = (0..64) .map(|_| { super::super::agent::sign(&socket, &key.blob(), &data).expect("signed") @@ -545,7 +621,7 @@ mod tests { }) .expect("a high `s` among 64 signatures"); checked( - &from_agent(&key, &high, message.as_bytes()).expect("made low"), + &from_agent(NAMESPACE, &key, &high, message.as_bytes()).expect("made low"), message.as_bytes(), ); } -- cgit v1.3.1