use std::fmt;
use std::sync::Arc;
use sew_proto::e2ee::ConsentState;
use sew_proto::id::Id;
use sew_proto::recording::{Recording, RecordingControls};
use sew_proto::voice::{MediaPolicy, VoiceJoinResponse, VoiceServerUpdated, VoiceState};
use tokio::sync::{mpsc, watch};
use crate::provider::{BoxFuture, CallCredential};
pub mod credential;
pub mod frame;
pub mod guard;
pub mod keys;
pub mod lkgcm;
pub mod mls;
pub mod session;
pub mod transport;
pub use credential::{Bearer, CredentialGrant, RenewAnswer, RenewRefused, SharedBearer};
pub use frame::{FrameCrypto, IvParts, OpenError, SealError, VideoFrameCodec};
pub use guard::{
KEY_PENDING_GRACE_MS, Leases, PublishGuard, PublishRefused, RecvGate, RecvRefused, SendGate,
SubscribeDecision, SubscribeGuard, SubscribeRefused, check_publish,
};
pub use keys::{MediaCounters, MediaKeys, MediaReport, PublishState, engine_caps};
pub use lkgcm::LkGcm;
pub use mls::{MlsKeys, SessionJoin};
pub use session::{KeyEnd, KeyError, KeySessionConfig, KeySessionEvent, MlsSession};
pub use transport::{KeyTransport, TransportError};
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct RemoteTrack {
pub sid: String,
pub encryption: i32,
pub mime: String,
pub audio: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Subscribe {
Yes,
NotYet,
No {
reason: String,
},
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum CryptoError {
#[error("no send key")]
NoSendKey,
#[error("no key")]
NoKey,
#[error("bad frame")]
BadFrame,
#[error("key not installed yet")]
KeyPending,
}
#[derive(Clone, Debug)]
#[allow(clippy::large_enum_variant)]
#[non_exhaustive]
pub enum E2eeEvent {
Active {
epoch: u64,
},
Refused {
code: String,
detail: String,
},
Warning {
code: String,
detail: String,
},
Members(Vec<(String, String)>),
VoiceStates(Vec<VoiceState>),
ServerUpdated(VoiceServerUpdated),
MediaPolicy(Box<MediaPolicy>),
CredentialLost,
Recording(Option<Box<Recording>>),
RecordingControls {
channel_id: Option<Id>,
controls: Option<RecordingControls>,
},
Ended {
reason: String,
},
KeysRemoved {
reason: String,
},
Security(crate::call::CallSecurity),
}
#[derive(Clone, Debug)]
pub struct E2eeEvents(pub(crate) mpsc::UnboundedSender<E2eeEvent>);
impl E2eeEvents {
pub fn send(&self, ev: E2eeEvent) -> bool {
self.0.send(ev).is_ok()
}
}
#[derive(Clone)]
pub struct CredentialHandle(pub(crate) watch::Receiver<Option<CallCredential>>);
impl fmt::Debug for CredentialHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CredentialHandle").finish_non_exhaustive()
}
}
impl CredentialHandle {
pub fn current(&self) -> Option<CallCredential> {
self.0.borrow().clone()
}
pub fn token(&self) -> Option<String> {
self.0.borrow().as_ref().map(|c| c.token.clone())
}
pub async fn changed(&mut self) -> Result<(), watch::error::RecvError> {
self.0.changed().await
}
}
#[derive(Clone)]
pub struct E2eeContext {
pub join: VoiceJoinResponse,
pub api_base: url::Url,
pub credential: CredentialHandle,
pub http: reqwest::Client,
pub tls: Arc<rustls::ClientConfig>,
pub app_id: String,
pub data_dir: std::path::PathBuf,
pub rejoin: Option<crate::provider::RejoinReason>,
}
impl fmt::Debug for E2eeContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("E2eeContext")
.field("room", &self.join.room)
.field("api_base", &self.api_base.as_str())
.field("app_id", &self.app_id)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("{code}: {detail}")]
pub struct E2eeError {
pub code: String,
pub detail: String,
}
pub trait KeySession: Send + Sync + 'static {
fn encrypt(
&self,
frame: &[u8],
ssrc: u32,
rtp_ts: u32,
out: &mut Vec<u8>,
) -> Result<(), CryptoError>;
fn encrypt_video(
&self,
codec: VideoFrameCodec,
frame: &[u8],
ssrc: u32,
rtp_ts: u32,
out: &mut Vec<u8>,
) -> Result<(), CryptoError> {
let _ = (codec, frame, ssrc, rtp_ts, out);
Err(CryptoError::NoSendKey)
}
fn decrypt(&self, sender: &str, frame: &[u8], out: &mut Vec<u8>) -> Result<(), CryptoError>;
fn decrypt_video(
&self,
sender: &str,
codec: crate::video::VideoCodec,
frame: &[u8],
out: &mut Vec<u8>,
) -> Result<(), CryptoError> {
let _ = (sender, codec, frame, out);
Err(CryptoError::NoKey)
}
fn may_subscribe(&self, publisher: &str, track: &RemoteTrack) -> Subscribe;
fn published(&self, track: &sew_lkproto::livekit::TrackInfo) -> bool {
let _ = track;
true
}
fn roster(&self, identities: &[String]) {
let _ = identities;
}
fn media_reconnected(&self, full: bool) {
let _ = full;
}
fn network_changed(&self) {}
fn recording(&self, recording_id: Option<Id>, my_consent: ConsentState) {
let _ = (recording_id, my_consent);
}
fn device_id(&self) -> Option<String> {
None
}
fn close(&self) -> BoxFuture<'_, ()>;
}
pub trait E2eeProvider: Send + Sync + 'static {
fn start(
&self,
ctx: E2eeContext,
events: E2eeEvents,
) -> BoxFuture<'_, Result<Arc<dyn KeySession>, E2eeError>>;
}
#[cfg(feature = "testing")]
pub use testing::StaticKeys;
#[cfg(feature = "testing")]
mod testing {
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use sew_lk_compat::e2ee::{Codec, FrameCryptor as _, FrameIv, FrameKey, LkGcmV1, SenderRing};
use super::{
CryptoError, E2eeContext, E2eeError, E2eeEvent, E2eeEvents, E2eeProvider, KeySession,
RemoteTrack, Subscribe, VideoFrameCodec,
};
use crate::provider::BoxFuture;
#[derive(Clone)]
pub struct StaticKeys {
ikm: [u8; 32],
}
impl std::fmt::Debug for StaticKeys {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("StaticKeys(TEST ONLY)")
}
}
impl StaticKeys {
pub fn new(ikm: [u8; 32]) -> StaticKeys {
StaticKeys { ikm }
}
}
struct Session {
ring: SenderRing,
counts: Mutex<HashMap<u32, u32>>,
}
impl KeySession for Session {
fn encrypt(
&self,
frame: &[u8],
ssrc: u32,
rtp_ts: u32,
out: &mut Vec<u8>,
) -> Result<(), CryptoError> {
let Some(key) = self.ring.get(0) else {
return Err(CryptoError::NoSendKey);
};
let send_count = {
let mut c = self.counts.lock().map_err(|_| CryptoError::NoSendKey)?;
let n = c
.entry(ssrc)
.or_insert_with(|| u32::from(rand::random::<u16>()));
*n = n.wrapping_add(1);
*n
};
let iv = FrameIv {
ssrc,
timestamp: rtp_ts,
send_count,
};
LkGcmV1
.encrypt(Codec::Opus, frame, key, 0, iv, out)
.map_err(|_| CryptoError::BadFrame)
}
fn encrypt_video(
&self,
codec: VideoFrameCodec,
frame: &[u8],
ssrc: u32,
rtp_ts: u32,
out: &mut Vec<u8>,
) -> Result<(), CryptoError> {
let Some(key) = self.ring.get(0) else {
return Err(CryptoError::NoSendKey);
};
let send_count = {
let mut c = self.counts.lock().map_err(|_| CryptoError::NoSendKey)?;
let n = c
.entry(ssrc)
.or_insert_with(|| u32::from(rand::random::<u16>()));
*n = n.wrapping_add(1);
*n
};
let iv = FrameIv {
ssrc,
timestamp: rtp_ts,
send_count,
};
let codec = match codec {
VideoFrameCodec::Vp8 => Codec::Vp8,
VideoFrameCodec::H264 => Codec::H264,
};
LkGcmV1
.encrypt(codec, frame, key, 0, iv, out)
.map_err(|_| CryptoError::BadFrame)
}
fn decrypt(
&self,
_sender: &str,
frame: &[u8],
out: &mut Vec<u8>,
) -> Result<(), CryptoError> {
LkGcmV1
.decrypt(Codec::Opus, frame, &self.ring, out)
.map(|_| ())
.map_err(|_| CryptoError::BadFrame)
}
fn decrypt_video(
&self,
_sender: &str,
codec: crate::video::VideoCodec,
frame: &[u8],
out: &mut Vec<u8>,
) -> Result<(), CryptoError> {
let codec = match codec {
crate::video::VideoCodec::Vp8 => Codec::Vp8,
crate::video::VideoCodec::H264 => Codec::H264,
};
let start = out.len();
match LkGcmV1.decrypt(codec, frame, &self.ring, out) {
Ok(info) if !info.empty && out.len() > start => Ok(()),
_ => {
out.truncate(start);
Err(CryptoError::BadFrame)
}
}
}
fn may_subscribe(&self, _publisher: &str, track: &RemoteTrack) -> Subscribe {
if track.encryption == sew_lk_compat::session::ENCRYPTION_GCM {
Subscribe::Yes
} else {
Subscribe::No {
reason: "not_encrypted".to_owned(),
}
}
}
fn close(&self) -> BoxFuture<'_, ()> {
Box::pin(async {})
}
}
impl E2eeProvider for StaticKeys {
fn start(
&self,
_ctx: E2eeContext,
events: E2eeEvents,
) -> BoxFuture<'_, Result<Arc<dyn KeySession>, E2eeError>> {
let ikm = self.ikm;
Box::pin(async move {
let mut ring = SenderRing::new();
ring.set(0, FrameKey::derive(&ikm));
let s: Arc<dyn KeySession> = Arc::new(Session {
ring,
counts: Mutex::new(HashMap::new()),
});
events.send(E2eeEvent::Active { epoch: 0 });
Ok(s)
})
}
}
}