geth/crates/geth-discovery/src/lib.rs

244 lines
7.4 KiB
Rust
Raw Normal View History

2026-05-18 04:03:52 +02:00
use geth_crypto::AgentKey;
2026-05-16 14:24:21 +02:00
use geth_types::{AgentId, NodeId, UnixMillis};
2026-05-15 15:08:20 +02:00
use serde::{Deserialize, Serialize};
2026-05-16 14:24:21 +02:00
pub const PEER_CARD_SIGNATURE_NAMESPACE: &str = "geth.peer-card.v1@geth.local";
2026-05-15 15:08:20 +02:00
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerCard {
2026-05-16 14:24:21 +02:00
pub node_id: NodeId,
pub agent_id: AgentId,
pub endpoints: Vec<EndpointCandidate>,
pub issued_at: UnixMillis,
pub signature: SignatureMetadata,
}
impl PeerCard {
2026-05-18 04:03:52 +02:00
pub fn signed(
node_id: NodeId,
agent_key: &AgentKey,
endpoints: Vec<EndpointCandidate>,
issued_at: UnixMillis,
) -> Result<Self, DiscoveryError> {
let agent_id = agent_key.agent_id();
let payload = PeerCardSigningPayload {
node_id: node_id.clone(),
agent_id: agent_id.clone(),
endpoints: endpoints.clone(),
issued_at,
};
let signature = agent_key.sign_canonical(PEER_CARD_SIGNATURE_NAMESPACE, &payload)?;
Ok(Self {
node_id,
agent_id: agent_id.clone(),
endpoints,
issued_at,
signature: SignatureMetadata {
namespace: PEER_CARD_SIGNATURE_NAMESPACE.to_owned(),
signer: agent_id.to_string(),
public_key: agent_key.public_key_hex(),
signature: hex::encode(signature),
},
})
}
2026-05-16 14:24:21 +02:00
pub fn validate_candidate(&self) -> Result<(), DiscoveryError> {
if self.endpoints.is_empty() {
return Err(DiscoveryError::MissingEndpoint);
}
2026-05-18 04:03:52 +02:00
self.verify_signature()
}
pub fn verify_signature(&self) -> Result<(), DiscoveryError> {
2026-05-16 14:24:21 +02:00
if self.signature.namespace != PEER_CARD_SIGNATURE_NAMESPACE {
return Err(DiscoveryError::InvalidSignatureNamespace(
self.signature.namespace.clone(),
));
}
2026-05-18 04:03:52 +02:00
if self.signature.signer.is_empty()
|| self.signature.public_key.is_empty()
|| self.signature.signature.is_empty()
{
2026-05-16 14:24:21 +02:00
return Err(DiscoveryError::UnsignedPeerCard);
}
2026-05-18 04:03:52 +02:00
if self.signature.signer != self.agent_id.as_str() {
return Err(DiscoveryError::SignerMismatch {
signer: self.signature.signer.clone(),
agent: self.agent_id.to_string(),
});
}
let public_key = hex::decode(&self.signature.public_key)?;
let fingerprint = geth_crypto::key_fingerprint(&public_key);
if fingerprint != self.signature.signer {
return Err(DiscoveryError::SignerPublicKeyMismatch {
signer: self.signature.signer.clone(),
fingerprint,
});
}
let signature = hex::decode(&self.signature.signature)?;
geth_crypto::verify_canonical(
&public_key,
PEER_CARD_SIGNATURE_NAMESPACE,
&self.signing_payload(),
&signature,
)?;
2026-05-16 14:24:21 +02:00
Ok(())
}
2026-05-18 04:03:52 +02:00
fn signing_payload(&self) -> PeerCardSigningPayload {
PeerCardSigningPayload {
node_id: self.node_id.clone(),
agent_id: self.agent_id.clone(),
endpoints: self.endpoints.clone(),
issued_at: self.issued_at,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct PeerCardSigningPayload {
node_id: NodeId,
agent_id: AgentId,
endpoints: Vec<EndpointCandidate>,
issued_at: UnixMillis,
2026-05-16 14:24:21 +02:00
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EndpointCandidate {
pub endpoint_id: String,
pub relay_url: Option<String>,
2026-05-18 12:09:50 +02:00
#[serde(default)]
pub direct_addresses: Vec<String>,
2026-05-16 14:24:21 +02:00
pub source: DiscoverySource,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SignatureMetadata {
pub namespace: String,
pub signer: String,
2026-05-18 04:03:52 +02:00
#[serde(default)]
pub public_key: String,
2026-05-16 14:24:21 +02:00
pub signature: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DiscoverySource {
Manual,
Mdns,
PeerExchange,
Imported,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiscoveredPeer {
pub card: PeerCard,
pub discovered_at: UnixMillis,
pub source: DiscoverySource,
pub trust_state: CandidateTrustState,
}
impl DiscoveredPeer {
pub fn candidate(
card: PeerCard,
discovered_at: UnixMillis,
source: DiscoverySource,
) -> Result<Self, DiscoveryError> {
card.validate_candidate()?;
Ok(Self {
card,
discovered_at,
source,
trust_state: CandidateTrustState::CandidateOnly,
})
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CandidateTrustState {
CandidateOnly,
2026-05-15 15:08:20 +02:00
}
pub trait DiscoveryBackend {
2026-05-16 14:24:21 +02:00
fn candidates(&self) -> Result<Vec<DiscoveredPeer>, DiscoveryError>;
}
#[derive(Debug, thiserror::Error)]
pub enum DiscoveryError {
#[error("peer card has no endpoint candidates")]
MissingEndpoint,
#[error("peer card is missing signature metadata")]
UnsignedPeerCard,
#[error("invalid peer card signature namespace: {0}")]
InvalidSignatureNamespace(String),
2026-05-18 04:03:52 +02:00
#[error("peer card signer {signer} does not match agent {agent}")]
SignerMismatch { signer: String, agent: String },
#[error("peer card signer {signer} does not match public key fingerprint {fingerprint}")]
SignerPublicKeyMismatch { signer: String, fingerprint: String },
#[error("invalid peer card hex: {0}")]
Hex(#[from] hex::FromHexError),
#[error("peer card signature error: {0}")]
Crypto(#[from] geth_crypto::CryptoError),
2026-05-15 15:08:20 +02:00
}
#[must_use]
pub fn discovery_is_untrusted_note() -> &'static str {
"discovery returns candidate peers only and never grants trust or authorization"
}
2026-05-16 14:24:21 +02:00
#[cfg(test)]
mod tests {
use super::*;
fn signed_card() -> PeerCard {
2026-05-18 04:03:52 +02:00
let key = AgentKey::generate();
let agent_id = key.agent_id();
PeerCard::signed(
format!("node:{agent_id}").into(),
&key,
vec![EndpointCandidate {
2026-05-16 14:24:21 +02:00
endpoint_id: "endpoint:iroh".to_owned(),
relay_url: None,
2026-05-18 12:09:50 +02:00
direct_addresses: vec!["127.0.0.1:12345".to_owned()],
2026-05-16 14:24:21 +02:00
source: DiscoverySource::Manual,
}],
2026-05-18 04:03:52 +02:00
UnixMillis(1),
)
.expect("signed card")
2026-05-16 14:24:21 +02:00
}
#[test]
fn signed_peer_card_is_valid_candidate() {
signed_card()
.validate_candidate()
.expect("valid signed candidate");
}
#[test]
fn discovered_peer_is_candidate_only() {
let peer = DiscoveredPeer::candidate(signed_card(), UnixMillis(2), DiscoverySource::Mdns)
.expect("candidate");
assert_eq!(peer.trust_state, CandidateTrustState::CandidateOnly);
}
#[test]
fn unsigned_peer_card_is_not_valid_candidate() {
let mut card = signed_card();
card.signature.signature.clear();
assert!(matches!(
card.validate_candidate(),
Err(DiscoveryError::UnsignedPeerCard)
));
}
2026-05-18 04:03:52 +02:00
#[test]
fn tampered_peer_card_signature_is_rejected() {
let mut card = signed_card();
card.endpoints[0].endpoint_id = "endpoint:tampered".to_owned();
assert!(matches!(
card.validate_candidate(),
Err(DiscoveryError::Crypto(geth_crypto::CryptoError::Verify))
));
}
2026-05-16 14:24:21 +02:00
}