1 parent
9c305f2a4d
commit
21261db8ef
185 files changed
+52751
-217
No files matched your search
Vendored
+686
@@ -0,0 +1,686 @@
|
||||
//! Shared transport configuration and access to every application service.
|
||||
//!
|
||||
//! The schema does not specify a transport authentication scheme. Metadata and
|
||||
//! bearer authentication are therefore opt-in. Sessions embedded in protobuf
|
||||
//! messages remain explicit fields controlled by the caller.
|
||||
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
fmt,
|
||||
sync::{Arc, RwLock},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use tonic::{
|
||||
metadata::{Ascii, KeyAndValueRef, MetadataMap, MetadataValue},
|
||||
service::{interceptor::InterceptedService, Interceptor},
|
||||
transport::{Channel, ClientTlsConfig, Endpoint},
|
||||
Request, Status,
|
||||
};
|
||||
|
||||
use crate::api::{
|
||||
addon::user_addon_service_client::UserAddonServiceClient,
|
||||
integration::integration_user_service_client::IntegrationUserServiceClient,
|
||||
login::login_service_client::LoginServiceClient,
|
||||
management::user::user_management_service_client::UserManagementServiceClient,
|
||||
messengerconnector::messenger_connector_client_service_client::MessengerConnectorClientServiceClient,
|
||||
synchronization::synchronization_service_client::SynchronizationServiceClient,
|
||||
tschat::chat_requests_client::ChatRequestsClient,
|
||||
user::user_account_service_client::UserAccountServiceClient,
|
||||
};
|
||||
use crate::push::push_service_client::PushServiceClient;
|
||||
|
||||
/// Errors raised while configuring or connecting a client.
|
||||
///
|
||||
/// RPC failures themselves are returned as [`tonic::Status`] by generated clients.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ClientError {
|
||||
/// The endpoint or TLS configuration was invalid, or the connection failed.
|
||||
#[error("gRPC transport error: {0}")]
|
||||
Transport(#[from] tonic::transport::Error),
|
||||
/// A URL must identify an HTTP(S) origin rather than a service path.
|
||||
#[error("invalid endpoint: {0}")]
|
||||
InvalidEndpoint(&'static str),
|
||||
/// Bearer tokens must be nonempty and contain only visible ASCII without spaces.
|
||||
#[error("bearer token must be nonempty visible ASCII without spaces")]
|
||||
InvalidBearerToken,
|
||||
/// A panic occurred while shared metadata was being changed.
|
||||
#[error("shared request metadata lock is poisoned")]
|
||||
MetadataLockPoisoned,
|
||||
}
|
||||
|
||||
/// Metadata shared by all service handles derived from an [`ApiClient`].
|
||||
///
|
||||
/// Changes affect subsequent calls, including calls made through already-created
|
||||
/// service handles. They do not change an active push stream. Debug output never
|
||||
/// includes metadata values. Explicit per-request metadata overrides defaults.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct SharedMetadata(Arc<RwLock<MetadataMap>>);
|
||||
|
||||
impl SharedMetadata {
|
||||
/// Create a shared metadata store, preserving duplicate and binary entries.
|
||||
pub fn new(metadata: MetadataMap) -> Self {
|
||||
Self(Arc::new(RwLock::new(metadata)))
|
||||
}
|
||||
|
||||
/// Read a snapshot. The returned map may contain credentials.
|
||||
pub fn snapshot(&self) -> Result<MetadataMap, ClientError> {
|
||||
self.0
|
||||
.read()
|
||||
.map(|map| map.clone())
|
||||
.map_err(|_| ClientError::MetadataLockPoisoned)
|
||||
}
|
||||
|
||||
/// Atomically replace all default metadata.
|
||||
pub fn replace(&self, metadata: MetadataMap) -> Result<(), ClientError> {
|
||||
*self
|
||||
.0
|
||||
.write()
|
||||
.map_err(|_| ClientError::MetadataLockPoisoned)? = metadata;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set or rotate an optional bearer token while keeping other metadata.
|
||||
///
|
||||
/// The value is marked sensitive. Pass the token without the `Bearer ` prefix.
|
||||
pub fn set_bearer_token(&self, token: impl AsRef<str>) -> Result<(), ClientError> {
|
||||
let value = bearer_value(token.as_ref())?;
|
||||
self.0
|
||||
.write()
|
||||
.map_err(|_| ClientError::MetadataLockPoisoned)?
|
||||
.insert("authorization", value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove the default authorization header.
|
||||
pub fn clear_bearer_token(&self) -> Result<(), ClientError> {
|
||||
self.0
|
||||
.write()
|
||||
.map_err(|_| ClientError::MetadataLockPoisoned)?
|
||||
.remove("authorization");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for SharedMetadata {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("SharedMetadata").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
fn bearer_value(token: &str) -> Result<MetadataValue<Ascii>, ClientError> {
|
||||
if token.is_empty() || !token.bytes().all(|byte| byte.is_ascii_graphic()) {
|
||||
return Err(ClientError::InvalidBearerToken);
|
||||
}
|
||||
let mut value: MetadataValue<Ascii> = format!("Bearer {token}")
|
||||
.parse()
|
||||
.map_err(|_| ClientError::InvalidBearerToken)?;
|
||||
value.set_sensitive(true);
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// The interceptor used by the configured generated service clients.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RequestInterceptor {
|
||||
metadata: SharedMetadata,
|
||||
timeout: Option<Duration>,
|
||||
}
|
||||
|
||||
impl RequestInterceptor {
|
||||
/// Create an interceptor for a generated client or another compatible service.
|
||||
pub fn new(metadata: SharedMetadata, timeout: Option<Duration>) -> Self {
|
||||
Self { metadata, timeout }
|
||||
}
|
||||
}
|
||||
|
||||
impl Interceptor for RequestInterceptor {
|
||||
fn call(&mut self, mut request: Request<()>) -> Result<Request<()>, Status> {
|
||||
let defaults = self
|
||||
.metadata
|
||||
.0
|
||||
.read()
|
||||
.map_err(|_| Status::internal("shared request metadata is unavailable"))?;
|
||||
// Capture the original keys before appending, so duplicate default values
|
||||
// survive while any explicit per-request value overrides the entire key.
|
||||
let supplied: HashSet<String> = request
|
||||
.metadata()
|
||||
.iter()
|
||||
.map(|entry| match entry {
|
||||
KeyAndValueRef::Ascii(key, _) => key.as_str().to_owned(),
|
||||
KeyAndValueRef::Binary(key, _) => key.as_str().to_owned(),
|
||||
})
|
||||
.collect();
|
||||
for entry in defaults.iter() {
|
||||
match entry {
|
||||
KeyAndValueRef::Ascii(key, value) if !supplied.contains(key.as_str()) => {
|
||||
request.metadata_mut().append(key.clone(), value.clone());
|
||||
}
|
||||
KeyAndValueRef::Binary(key, value) if !supplied.contains(key.as_str()) => {
|
||||
request
|
||||
.metadata_mut()
|
||||
.append_bin(key.clone(), value.clone());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !request.metadata().contains_key("grpc-timeout") {
|
||||
if let Some(timeout) = self.timeout {
|
||||
request.set_timeout(timeout);
|
||||
}
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
}
|
||||
|
||||
/// Channel type used by every service getter on [`ApiClient`].
|
||||
pub type InterceptedChannel = InterceptedService<Channel, RequestInterceptor>;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct CallOptions {
|
||||
request_timeout: Option<Duration>,
|
||||
stream_timeout: Option<Duration>,
|
||||
max_decoding_message_size: Option<usize>,
|
||||
max_encoding_message_size: Option<usize>,
|
||||
#[cfg(feature = "gzip")]
|
||||
send_gzip: bool,
|
||||
#[cfg(feature = "gzip")]
|
||||
accept_gzip: bool,
|
||||
}
|
||||
|
||||
/// Builder for shared transport, request metadata, and message limits.
|
||||
///
|
||||
/// An HTTPS URL enables certificate validation using native trust roots. A
|
||||
/// custom [`ClientTlsConfig`] can supply a private CA and an mTLS identity.
|
||||
/// No application credentials or request deadlines are set by default.
|
||||
#[derive(Debug)]
|
||||
#[must_use = "call connect, connect_lazy, or build_with_channel to create the client"]
|
||||
pub struct ClientBuilder {
|
||||
endpoint: Endpoint,
|
||||
metadata: SharedMetadata,
|
||||
options: CallOptions,
|
||||
}
|
||||
|
||||
impl ClientBuilder {
|
||||
/// Build from an absolute `http://` or `https://` origin URL.
|
||||
///
|
||||
/// The default connection timeout is ten seconds. Protobuf service paths
|
||||
/// are generated from the schema, so URL path prefixes are rejected.
|
||||
pub fn new(endpoint: impl Into<String>) -> Result<Self, ClientError> {
|
||||
let mut endpoint = Endpoint::from_shared(endpoint.into())?;
|
||||
validate_endpoint(&endpoint)?;
|
||||
if endpoint.uri().scheme_str() == Some("https") {
|
||||
endpoint = endpoint.tls_config(ClientTlsConfig::new().with_native_roots())?;
|
||||
}
|
||||
endpoint = endpoint.connect_timeout(Duration::from_secs(10));
|
||||
Ok(Self::from_endpoint(endpoint))
|
||||
}
|
||||
|
||||
/// Use a preconfigured tonic endpoint without changing its transport options.
|
||||
///
|
||||
/// The caller is responsible for configuring TLS and validating this endpoint.
|
||||
/// This is an escape hatch for advanced flow control, origin, and executor
|
||||
/// settings that are not exposed directly by this builder.
|
||||
pub fn from_endpoint(endpoint: Endpoint) -> Self {
|
||||
Self {
|
||||
endpoint,
|
||||
metadata: SharedMetadata::default(),
|
||||
options: CallOptions::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the TLS settings, including trust roots, server name, or mTLS identity.
|
||||
pub fn tls_config(mut self, config: ClientTlsConfig) -> Result<Self, ClientError> {
|
||||
self.endpoint = self.endpoint.tls_config(config)?;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Set the connection-establishment timeout.
|
||||
pub fn connect_timeout(mut self, timeout: Duration) -> Self {
|
||||
self.endpoint = self.endpoint.connect_timeout(timeout);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set a default `grpc-timeout` for unary calls.
|
||||
///
|
||||
/// Per-request deadlines override this value. This uses
|
||||
/// [`Request::set_timeout`]: the channel limits response setup and sends the
|
||||
/// deadline to the server. Push calls are unaffected; use
|
||||
/// [`Self::stream_timeout`] to opt into a push deadline.
|
||||
pub fn request_timeout(mut self, timeout: Duration) -> Self {
|
||||
self.options.request_timeout = Some(timeout);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the push RPC's `grpc-timeout`. No stream deadline is set by default.
|
||||
///
|
||||
/// The channel limits response setup; enforcement after stream establishment
|
||||
/// depends on the server. This is not an inactivity timeout between messages.
|
||||
/// For a client-side receive timeout, wrap `stream.message()` in
|
||||
/// `tokio::time::timeout`.
|
||||
pub fn stream_timeout(mut self, timeout: Duration) -> Self {
|
||||
self.options.stream_timeout = Some(timeout);
|
||||
self
|
||||
}
|
||||
|
||||
/// Replace all default request metadata. Per-request values take precedence.
|
||||
pub fn metadata(mut self, metadata: MetadataMap) -> Self {
|
||||
self.metadata = SharedMetadata::new(metadata);
|
||||
self
|
||||
}
|
||||
|
||||
/// Reuse an existing metadata store for coordinated credential rotation.
|
||||
pub fn shared_metadata(mut self, metadata: SharedMetadata) -> Self {
|
||||
self.metadata = metadata;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set optional bearer authentication, without changing other metadata.
|
||||
///
|
||||
/// This also updates the shared store if [`Self::shared_metadata`] was used.
|
||||
pub fn bearer_token(self, token: impl AsRef<str>) -> Result<Self, ClientError> {
|
||||
self.metadata.set_bearer_token(token)?;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Set the maximum decoded response size in bytes for all service clients.
|
||||
///
|
||||
/// If unset, tonic's default limit is retained (4 MiB).
|
||||
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.options.max_decoding_message_size = Some(limit);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the maximum encoded request size in bytes for all service clients.
|
||||
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.options.max_encoding_message_size = Some(limit);
|
||||
self
|
||||
}
|
||||
|
||||
/// Enable or disable compression of outgoing requests. Disabled by default.
|
||||
#[cfg(feature = "gzip")]
|
||||
pub fn send_gzip(mut self, enabled: bool) -> Self {
|
||||
self.options.send_gzip = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Advertise support for gzip responses. Disabled by default.
|
||||
#[cfg(feature = "gzip")]
|
||||
pub fn accept_gzip(mut self, enabled: bool) -> Self {
|
||||
self.options.accept_gzip = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set TCP keepalive probe idle time, or disable it with `None`.
|
||||
pub fn tcp_keepalive(mut self, interval: Option<Duration>) -> Self {
|
||||
self.endpoint = self.endpoint.tcp_keepalive(interval);
|
||||
self
|
||||
}
|
||||
|
||||
/// Enable or disable TCP_NODELAY.
|
||||
pub fn tcp_nodelay(mut self, enabled: bool) -> Self {
|
||||
self.endpoint = self.endpoint.tcp_nodelay(enabled);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the HTTP/2 ping interval. Coordinate this with the server's policy.
|
||||
pub fn http2_keep_alive_interval(mut self, interval: Duration) -> Self {
|
||||
self.endpoint = self.endpoint.http2_keep_alive_interval(interval);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the maximum wait for a keepalive ping acknowledgement.
|
||||
pub fn keep_alive_timeout(mut self, timeout: Duration) -> Self {
|
||||
self.endpoint = self.endpoint.keep_alive_timeout(timeout);
|
||||
self
|
||||
}
|
||||
|
||||
/// Send HTTP/2 keepalive pings even when no RPC is active.
|
||||
pub fn keep_alive_while_idle(mut self, enabled: bool) -> Self {
|
||||
self.endpoint = self.endpoint.keep_alive_while_idle(enabled);
|
||||
self
|
||||
}
|
||||
|
||||
/// Override the user-agent prefix used by tonic.
|
||||
pub fn user_agent(mut self, user_agent: impl AsRef<str>) -> Result<Self, ClientError> {
|
||||
self.endpoint = self.endpoint.user_agent(user_agent.as_ref())?;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Establish the shared channel now. Requires a Tokio runtime.
|
||||
pub async fn connect(self) -> Result<ApiClient, ClientError> {
|
||||
let channel = self.endpoint.connect().await?;
|
||||
Ok(self.build_with_channel(channel))
|
||||
}
|
||||
|
||||
/// Defer connection until the first RPC. Requires a Tokio runtime.
|
||||
pub fn connect_lazy(self) -> ApiClient {
|
||||
let channel = self.endpoint.connect_lazy();
|
||||
self.build_with_channel(channel)
|
||||
}
|
||||
|
||||
/// Apply request settings to a caller-provided channel.
|
||||
///
|
||||
/// The builder's endpoint, TLS, connection, and keepalive options are ignored;
|
||||
/// the supplied channel owns those settings. Useful for custom connectors.
|
||||
pub fn build_with_channel(self, channel: Channel) -> ApiClient {
|
||||
ApiClient {
|
||||
channel,
|
||||
metadata: self.metadata,
|
||||
options: self.options,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_endpoint(endpoint: &Endpoint) -> Result<(), ClientError> {
|
||||
let uri = endpoint.uri();
|
||||
if !matches!(uri.scheme_str(), Some("http" | "https")) || uri.host().is_none() {
|
||||
return Err(ClientError::InvalidEndpoint(
|
||||
"expected an absolute http:// or https:// origin",
|
||||
));
|
||||
}
|
||||
if uri
|
||||
.authority()
|
||||
.is_some_and(|authority| authority.as_str().contains('@'))
|
||||
{
|
||||
return Err(ClientError::InvalidEndpoint(
|
||||
"use request metadata for credentials instead of URL user information",
|
||||
));
|
||||
}
|
||||
if !matches!(uri.path(), "" | "/") || uri.query().is_some() {
|
||||
return Err(ClientError::InvalidEndpoint(
|
||||
"service URL paths and query strings are not supported",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A cloneable collection of the nine application service clients.
|
||||
///
|
||||
/// All service handles share one multiplexed channel. Cloning the facade or a
|
||||
/// generated handle is inexpensive; separate handles support concurrent calls.
|
||||
/// No RPC is retried automatically and no body/session fields are injected.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ApiClient {
|
||||
channel: Channel,
|
||||
metadata: SharedMetadata,
|
||||
options: CallOptions,
|
||||
}
|
||||
|
||||
macro_rules! service_getter {
|
||||
($method:ident, $client:ident, $stream:literal, $description:literal) => {
|
||||
#[doc = $description]
|
||||
pub fn $method(&self) -> $client<InterceptedChannel> {
|
||||
let timeout = if $stream {
|
||||
self.options.stream_timeout
|
||||
} else {
|
||||
self.options.request_timeout
|
||||
};
|
||||
let mut client = $client::with_interceptor(
|
||||
self.channel.clone(),
|
||||
RequestInterceptor::new(self.metadata.clone(), timeout),
|
||||
);
|
||||
if let Some(limit) = self.options.max_decoding_message_size {
|
||||
client = client.max_decoding_message_size(limit);
|
||||
}
|
||||
if let Some(limit) = self.options.max_encoding_message_size {
|
||||
client = client.max_encoding_message_size(limit);
|
||||
}
|
||||
#[cfg(feature = "gzip")]
|
||||
{
|
||||
if self.options.send_gzip {
|
||||
client = client.send_compressed(tonic::codec::CompressionEncoding::Gzip);
|
||||
}
|
||||
if self.options.accept_gzip {
|
||||
client = client.accept_compressed(tonic::codec::CompressionEncoding::Gzip);
|
||||
}
|
||||
}
|
||||
client
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl ApiClient {
|
||||
/// Create a configuration builder for the supplied HTTP(S) origin.
|
||||
pub fn builder(endpoint: impl Into<String>) -> Result<ClientBuilder, ClientError> {
|
||||
ClientBuilder::new(endpoint)
|
||||
}
|
||||
|
||||
/// Connect with the default settings and no transport credentials.
|
||||
pub async fn connect(endpoint: impl Into<String>) -> Result<Self, ClientError> {
|
||||
Self::builder(endpoint)?.connect().await
|
||||
}
|
||||
|
||||
/// Wrap an existing channel with empty metadata and default message limits.
|
||||
///
|
||||
/// For custom request settings, use [`ClientBuilder::build_with_channel`].
|
||||
pub fn from_channel(channel: Channel) -> Self {
|
||||
Self {
|
||||
channel,
|
||||
metadata: SharedMetadata::default(),
|
||||
options: CallOptions::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Access the shared metadata store for credential rotation or replacement.
|
||||
pub fn metadata(&self) -> SharedMetadata {
|
||||
self.metadata.clone()
|
||||
}
|
||||
|
||||
/// Clone the underlying channel for advanced generated-client usage.
|
||||
///
|
||||
/// A raw channel does not apply this facade's metadata or message options.
|
||||
pub fn channel(&self) -> Channel {
|
||||
self.channel.clone()
|
||||
}
|
||||
|
||||
service_getter!(
|
||||
login,
|
||||
LoginServiceClient,
|
||||
false,
|
||||
"Get the login, session, token, and account lifecycle client."
|
||||
);
|
||||
service_getter!(
|
||||
user,
|
||||
UserAccountServiceClient,
|
||||
false,
|
||||
"Get the user account, avatar, file, and voice-server client."
|
||||
);
|
||||
service_getter!(
|
||||
management,
|
||||
UserManagementServiceClient,
|
||||
false,
|
||||
"Get the user-management, badge, OAuth, and community client."
|
||||
);
|
||||
service_getter!(
|
||||
chat,
|
||||
ChatRequestsClient,
|
||||
false,
|
||||
"Get the contacts, identifiers, and chat-session client."
|
||||
);
|
||||
service_getter!(
|
||||
synchronization,
|
||||
SynchronizationServiceClient,
|
||||
false,
|
||||
"Get the item synchronization client."
|
||||
);
|
||||
service_getter!(
|
||||
integration,
|
||||
IntegrationUserServiceClient,
|
||||
false,
|
||||
"Get the account integration and subscription client."
|
||||
);
|
||||
service_getter!(
|
||||
messenger,
|
||||
MessengerConnectorClientServiceClient,
|
||||
false,
|
||||
"Get the messenger-account connector client."
|
||||
);
|
||||
service_getter!(
|
||||
addon,
|
||||
UserAddonServiceClient,
|
||||
false,
|
||||
"Get the add-on download client."
|
||||
);
|
||||
service_getter!(
|
||||
push,
|
||||
PushServiceClient,
|
||||
true,
|
||||
"Get the server-streaming push client. Unary deadlines do not apply."
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn merges_ascii_binary_and_duplicate_metadata() {
|
||||
let mut defaults = MetadataMap::new();
|
||||
defaults.append("x-tag", "one".parse().unwrap());
|
||||
defaults.append("x-tag", "two".parse().unwrap());
|
||||
defaults.append_bin("x-payload-bin", MetadataValue::from_bytes(&[0, 255]));
|
||||
defaults.append_bin("x-payload-bin", MetadataValue::from_bytes(&[1, 254]));
|
||||
let mut interceptor = RequestInterceptor::new(SharedMetadata::new(defaults), None);
|
||||
let result = interceptor.call(Request::new(())).unwrap();
|
||||
assert_eq!(result.metadata().get_all("x-tag").iter().count(), 2);
|
||||
let binary: Vec<_> = result
|
||||
.metadata()
|
||||
.get_all_bin("x-payload-bin")
|
||||
.iter()
|
||||
.map(|value| value.to_bytes().unwrap())
|
||||
.collect();
|
||||
assert_eq!(binary.len(), 2);
|
||||
assert_eq!(binary[0].as_ref(), &[0, 255]);
|
||||
assert_eq!(binary[1].as_ref(), &[1, 254]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn per_request_metadata_overrides_entire_default_key() {
|
||||
let mut defaults = MetadataMap::new();
|
||||
defaults.append("x-tag", "default-one".parse().unwrap());
|
||||
defaults.append("x-tag", "default-two".parse().unwrap());
|
||||
defaults.insert_bin("x-data-bin", MetadataValue::from_bytes(b"default"));
|
||||
let mut request = Request::new(());
|
||||
request
|
||||
.metadata_mut()
|
||||
.insert("x-tag", "explicit".parse().unwrap());
|
||||
request
|
||||
.metadata_mut()
|
||||
.insert_bin("x-data-bin", MetadataValue::from_bytes(b"explicit"));
|
||||
let mut interceptor = RequestInterceptor::new(SharedMetadata::new(defaults), None);
|
||||
let result = interceptor.call(request).unwrap();
|
||||
assert_eq!(result.metadata().get_all("x-tag").iter().count(), 1);
|
||||
assert_eq!(result.metadata().get("x-tag").unwrap(), "explicit");
|
||||
assert_eq!(
|
||||
result
|
||||
.metadata()
|
||||
.get_bin("x-data-bin")
|
||||
.unwrap()
|
||||
.to_bytes()
|
||||
.unwrap()
|
||||
.as_ref(),
|
||||
b"explicit"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bearer_rotation_reaches_existing_interceptor_and_preserves_other_headers() {
|
||||
let mut defaults = MetadataMap::new();
|
||||
defaults.insert("x-project", "demo".parse().unwrap());
|
||||
let shared = SharedMetadata::new(defaults);
|
||||
let mut interceptor = RequestInterceptor::new(shared.clone(), None);
|
||||
shared.set_bearer_token("first").unwrap();
|
||||
let first = interceptor.call(Request::new(())).unwrap();
|
||||
assert_eq!(
|
||||
first.metadata().get("authorization").unwrap(),
|
||||
"Bearer first"
|
||||
);
|
||||
assert!(first
|
||||
.metadata()
|
||||
.get("authorization")
|
||||
.unwrap()
|
||||
.is_sensitive());
|
||||
shared.set_bearer_token("second").unwrap();
|
||||
let second = interceptor.call(Request::new(())).unwrap();
|
||||
assert_eq!(
|
||||
second.metadata().get("authorization").unwrap(),
|
||||
"Bearer second"
|
||||
);
|
||||
assert_eq!(second.metadata().get("x-project").unwrap(), "demo");
|
||||
assert!(!format!("{shared:?}").contains("second"));
|
||||
shared.clear_bearer_token().unwrap();
|
||||
assert!(!interceptor
|
||||
.call(Request::new(()))
|
||||
.unwrap()
|
||||
.metadata()
|
||||
.contains_key("authorization"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_bearer_does_not_replace_working_credentials() {
|
||||
let shared = SharedMetadata::default();
|
||||
shared.set_bearer_token("valid").unwrap();
|
||||
for invalid in ["", "has space", "injected\r\nheader", "non-ascii-é"] {
|
||||
assert!(matches!(
|
||||
shared.set_bearer_token(invalid),
|
||||
Err(ClientError::InvalidBearerToken)
|
||||
));
|
||||
}
|
||||
assert_eq!(
|
||||
shared.snapshot().unwrap().get("authorization").unwrap(),
|
||||
"Bearer valid"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_deadline_is_added_and_explicit_deadline_wins() {
|
||||
let mut interceptor =
|
||||
RequestInterceptor::new(SharedMetadata::default(), Some(Duration::from_secs(30)));
|
||||
let result = interceptor.call(Request::new(())).unwrap();
|
||||
let mut expected = Request::new(());
|
||||
expected.set_timeout(Duration::from_secs(30));
|
||||
assert_eq!(
|
||||
result.metadata().get("grpc-timeout").unwrap(),
|
||||
expected.metadata().get("grpc-timeout").unwrap()
|
||||
);
|
||||
let mut explicit = Request::new(());
|
||||
explicit.set_timeout(Duration::from_secs(2));
|
||||
let deadline = explicit.metadata().get("grpc-timeout").unwrap().clone();
|
||||
let result = interceptor.call(explicit).unwrap();
|
||||
assert_eq!(result.metadata().get("grpc-timeout").unwrap(), deadline);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_timeout_or_auth_is_added_by_default() {
|
||||
let mut interceptor = RequestInterceptor::new(SharedMetadata::default(), None);
|
||||
assert!(interceptor
|
||||
.call(Request::new(()))
|
||||
.unwrap()
|
||||
.metadata()
|
||||
.is_empty());
|
||||
let builder = ClientBuilder::new("http://localhost:50051")
|
||||
.unwrap()
|
||||
.request_timeout(Duration::from_secs(5));
|
||||
assert_eq!(
|
||||
builder.options.request_timeout,
|
||||
Some(Duration::from_secs(5))
|
||||
);
|
||||
assert_eq!(builder.options.stream_timeout, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endpoint_validation_rejects_non_origins() {
|
||||
for invalid in [
|
||||
"ftp://example.com",
|
||||
"example.com",
|
||||
"http://example.com/api",
|
||||
"https://example.com?token=x",
|
||||
] {
|
||||
assert!(
|
||||
ClientBuilder::new(invalid).is_err(),
|
||||
"unexpected valid URL: {invalid}"
|
||||
);
|
||||
}
|
||||
assert!(ClientBuilder::new("http://localhost:50051/").is_ok());
|
||||
}
|
||||
}
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
#![doc = include_str!("../README.md")]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
/// Generated protobuf packages. Original package names and RPC routes are preserved.
|
||||
#[allow(clippy::all, rustdoc::broken_intra_doc_links, non_camel_case_types)]
|
||||
pub mod proto {
|
||||
include!(concat!(env!("OUT_DIR"), "/packages.rs"));
|
||||
}
|
||||
|
||||
/// Local account serialization messages (proto2 presence is preserved).
|
||||
pub use proto::com::teamspeak::account::proto as account;
|
||||
/// Main application namespace (login, user, management, chat, sync, integrations).
|
||||
pub use proto::com::teamspeak::myteamspeak::proto as api;
|
||||
/// Streaming push transport messages and client.
|
||||
pub use proto::com::teamspeak::push::proto as push;
|
||||
/// Local synchronization serialization messages.
|
||||
pub use proto::com::teamspeak::sync::proto as sync;
|
||||
|
||||
pub mod client;
|
||||
#[cfg(feature = "reflection")]
|
||||
pub mod reflection;
|
||||
pub mod session;
|
||||
pub mod wire;
|
||||
|
||||
pub use client::{ApiClient, ClientError};
|
||||
pub use prost;
|
||||
pub use prost_types;
|
||||
pub use session::{SessionRequest, SessionToken};
|
||||
pub use tonic;
|
||||
|
||||
/// Includes imports and all schemas enabled for this build; suitable for reflection.
|
||||
pub const FILE_DESCRIPTOR_SET: &[u8] =
|
||||
include_bytes!(concat!(env!("OUT_DIR"), "/api_descriptor.bin"));
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
//! Runtime schema inspection, dynamic protobuf messages, and protobuf JSON.
|
||||
//!
|
||||
//! The JSON helpers use the protobuf JSON mapping: field names are lower camel
|
||||
//! case, byte fields are base64, 64-bit integers are strings, and enums use their
|
||||
//! schema names. Embedded `google.protobuf.Any` values are resolved against the
|
||||
//! bundled descriptors. Unknown JSON fields are rejected by default.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use prost::{Message, Name};
|
||||
use prost_reflect::ReflectMessage;
|
||||
pub use prost_reflect::{
|
||||
DescriptorPool, DeserializeOptions, DynamicMessage, MessageDescriptor, SerializeOptions,
|
||||
};
|
||||
|
||||
/// An error resolving, decoding, or converting a protobuf message.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ReflectionError {
|
||||
/// The bundled descriptor set does not contain the requested message.
|
||||
#[error("protobuf message `{0}` is not present in the bundled descriptors")]
|
||||
UnknownMessage(String),
|
||||
/// A dynamic message was converted to a different protobuf message type.
|
||||
#[error("protobuf message type mismatch: expected `{expected}`, got `{actual}`")]
|
||||
TypeMismatch {
|
||||
/// Fully qualified protobuf name of the requested Rust type.
|
||||
expected: String,
|
||||
/// Fully qualified protobuf name of the dynamic message.
|
||||
actual: String,
|
||||
},
|
||||
/// The protobuf wire representation could not be decoded.
|
||||
#[error("cannot decode protobuf message `{message_name}`: {source}")]
|
||||
Decode {
|
||||
/// Fully qualified protobuf message name.
|
||||
message_name: String,
|
||||
/// Original protobuf decoding error.
|
||||
#[source]
|
||||
source: prost::DecodeError,
|
||||
},
|
||||
/// Protobuf JSON encoding or decoding failed.
|
||||
#[error("protobuf JSON conversion failed: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
/// Returns the shared descriptors for all bundled application schemas and imports.
|
||||
///
|
||||
/// Initialize once, then reuse this pool for message, service, method, field, and
|
||||
/// enum inspection. This does not contact a server or enable a reflection RPC.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if the descriptor set embedded when this crate was built is invalid.
|
||||
pub fn descriptor_pool() -> &'static DescriptorPool {
|
||||
static POOL: OnceLock<DescriptorPool> = OnceLock::new();
|
||||
POOL.get_or_init(|| {
|
||||
DescriptorPool::decode(crate::FILE_DESCRIPTOR_SET)
|
||||
.expect("the descriptor set embedded at build time must be valid")
|
||||
})
|
||||
}
|
||||
|
||||
/// Looks up a fully qualified protobuf message name, with an optional leading dot.
|
||||
pub fn message_descriptor(full_name: &str) -> Result<MessageDescriptor, ReflectionError> {
|
||||
let name = full_name.strip_prefix('.').unwrap_or(full_name);
|
||||
descriptor_pool()
|
||||
.get_message_by_name(name)
|
||||
.ok_or_else(|| ReflectionError::UnknownMessage(full_name.to_owned()))
|
||||
}
|
||||
|
||||
/// Decodes protobuf wire bytes using the message's fully qualified schema name.
|
||||
///
|
||||
/// Unknown wire fields are retained in the returned dynamic message. Conversion
|
||||
/// to generated Rust types or JSON may discard those unknown fields.
|
||||
pub fn decode_dynamic(
|
||||
full_name: &str,
|
||||
bytes: impl AsRef<[u8]>,
|
||||
) -> Result<DynamicMessage, ReflectionError> {
|
||||
let descriptor = message_descriptor(full_name)?;
|
||||
let message_name = descriptor.full_name().to_owned();
|
||||
DynamicMessage::decode(descriptor, bytes.as_ref()).map_err(|source| ReflectionError::Decode {
|
||||
message_name,
|
||||
source,
|
||||
})
|
||||
}
|
||||
|
||||
/// Converts a generated Rust message into a dynamic message using its schema name.
|
||||
pub fn to_dynamic<M: Message + Name>(message: &M) -> Result<DynamicMessage, ReflectionError> {
|
||||
decode_dynamic(&M::full_name(), message.encode_to_vec())
|
||||
}
|
||||
|
||||
/// Converts a dynamic message to its corresponding generated Rust type.
|
||||
///
|
||||
/// The fully qualified protobuf names must match; a wire-compatible but different
|
||||
/// type is rejected. Unknown wire fields are discarded by generated Rust types.
|
||||
pub fn from_dynamic<M: Message + Name + Default>(
|
||||
message: &DynamicMessage,
|
||||
) -> Result<M, ReflectionError> {
|
||||
let expected = M::full_name();
|
||||
let actual = message.descriptor().full_name().to_owned();
|
||||
if actual != expected {
|
||||
return Err(ReflectionError::TypeMismatch { expected, actual });
|
||||
}
|
||||
message
|
||||
.transcode_to()
|
||||
.map_err(|source| ReflectionError::Decode {
|
||||
message_name: expected,
|
||||
source,
|
||||
})
|
||||
}
|
||||
|
||||
/// Serializes a generated message using the standard protobuf JSON mapping.
|
||||
pub fn to_json<M: Message + Name>(message: &M) -> Result<String, ReflectionError> {
|
||||
Ok(serde_json::to_string(&to_dynamic(message)?)?)
|
||||
}
|
||||
|
||||
/// Serializes a generated message as pretty-printed protobuf JSON.
|
||||
pub fn to_json_pretty<M: Message + Name>(message: &M) -> Result<String, ReflectionError> {
|
||||
Ok(serde_json::to_string_pretty(&to_dynamic(message)?)?)
|
||||
}
|
||||
|
||||
/// Serializes a generated message with explicitly chosen protobuf JSON options.
|
||||
///
|
||||
/// Some options, such as emitting numeric 64-bit values, depart from the standard
|
||||
/// mapping. Use [`to_json`] for the standard representation.
|
||||
pub fn to_json_with_options<M: Message + Name>(
|
||||
message: &M,
|
||||
options: &SerializeOptions,
|
||||
) -> Result<String, ReflectionError> {
|
||||
let mut bytes = Vec::new();
|
||||
to_dynamic(message)?
|
||||
.serialize_with_options(&mut serde_json::Serializer::new(&mut bytes), options)?;
|
||||
// A JSON serializer produces valid UTF-8 by construction.
|
||||
Ok(String::from_utf8(bytes).expect("JSON output must be valid UTF-8"))
|
||||
}
|
||||
|
||||
/// Parses one complete protobuf JSON document into a generated message.
|
||||
///
|
||||
/// Both schema field names and their JSON names are accepted. Unknown fields,
|
||||
/// unknown symbolic enum names, and trailing content are rejected.
|
||||
pub fn from_json<M: Message + Name + Default>(json: &str) -> Result<M, ReflectionError> {
|
||||
from_json_with_options(json, &DeserializeOptions::new())
|
||||
}
|
||||
|
||||
/// Parses protobuf JSON with explicit decoding options.
|
||||
pub fn from_json_with_options<M: Message + Name + Default>(
|
||||
json: &str,
|
||||
options: &DeserializeOptions,
|
||||
) -> Result<M, ReflectionError> {
|
||||
from_dynamic(&dynamic_from_json_with_options(
|
||||
&M::full_name(),
|
||||
json,
|
||||
options,
|
||||
)?)
|
||||
}
|
||||
|
||||
/// Parses protobuf JSON into a dynamic message identified by its schema name.
|
||||
pub fn dynamic_from_json(full_name: &str, json: &str) -> Result<DynamicMessage, ReflectionError> {
|
||||
dynamic_from_json_with_options(full_name, json, &DeserializeOptions::new())
|
||||
}
|
||||
|
||||
/// Parses protobuf JSON into a dynamic message with explicit decoding options.
|
||||
pub fn dynamic_from_json_with_options(
|
||||
full_name: &str,
|
||||
json: &str,
|
||||
options: &DeserializeOptions,
|
||||
) -> Result<DynamicMessage, ReflectionError> {
|
||||
let descriptor = message_descriptor(full_name)?;
|
||||
let mut deserializer = serde_json::Deserializer::from_str(json);
|
||||
let message = DynamicMessage::deserialize_with_options(descriptor, &mut deserializer, options)?;
|
||||
deserializer.end()?;
|
||||
Ok(message)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::api::{LoginData, LoginSession};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn descriptors_are_cached_and_include_service_methods() {
|
||||
assert!(std::ptr::eq(descriptor_pool(), descriptor_pool()));
|
||||
let service = descriptor_pool()
|
||||
.get_service_by_name("com.teamspeak.myteamspeak.proto.login.LoginService")
|
||||
.unwrap();
|
||||
let method = service
|
||||
.methods()
|
||||
.find(|method| method.name() == "login")
|
||||
.unwrap();
|
||||
assert_eq!(method.input().full_name(), LoginData::full_name());
|
||||
assert_eq!(method.output().full_name(), LoginSession::full_name());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_uses_schema_enum_names_and_camel_case_fields() {
|
||||
let message = LoginData {
|
||||
email: "person@example.invalid".into(),
|
||||
skip_session: true,
|
||||
origin: 1,
|
||||
device_id: "device-1".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let value: serde_json::Value = serde_json::from_str(&to_json(&message).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
value,
|
||||
json!({
|
||||
"email": "person@example.invalid",
|
||||
"skipSession": true,
|
||||
"origin": "WEBSITE",
|
||||
"deviceId": "device-1",
|
||||
})
|
||||
);
|
||||
assert_eq!(from_json::<LoginData>(&value.to_string()).unwrap(), message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_encodes_bytes_and_full_precision_int64() {
|
||||
let message = LoginSession {
|
||||
key: vec![0, 1, 2, 255],
|
||||
purge: i64::MAX,
|
||||
error: 200,
|
||||
..Default::default()
|
||||
};
|
||||
let value: serde_json::Value = serde_json::from_str(&to_json(&message).unwrap()).unwrap();
|
||||
assert_eq!(value["key"], "AAEC/w==");
|
||||
assert_eq!(value["purge"], "9223372036854775807");
|
||||
assert_eq!(value["error"], "ERROR_LOGIN_OK");
|
||||
assert_eq!(
|
||||
from_json::<LoginSession>(&value.to_string()).unwrap(),
|
||||
message
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_numeric_enum_values_survive_json() {
|
||||
let message: LoginData = from_json(r#"{"origin":9237}"#).unwrap();
|
||||
assert_eq!(message.origin, 9237);
|
||||
assert_eq!(to_json(&message).unwrap(), r#"{"origin":9237}"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parser_accepts_original_field_names() {
|
||||
let message: LoginData = from_json(r#"{"device_id":"device-2"}"#).unwrap();
|
||||
assert_eq!(message.device_id, "device-2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_json_is_rejected_without_ignoring_trailing_content() {
|
||||
for input in [
|
||||
r#"{"origin":"UNDEFINED_ORIGIN"}"#,
|
||||
r#"{"email":false}"#,
|
||||
r#"{} {}"#,
|
||||
r#"{"unknownField":true}"#,
|
||||
] {
|
||||
assert!(from_json::<LoginData>(input).is_err(), "accepted {input}");
|
||||
}
|
||||
assert!(from_json::<LoginSession>(r#"{"purge":"9223372036854775808"}"#).is_err());
|
||||
assert!(from_json::<LoginSession>(r#"{"key":"%%%"}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caller_can_explicitly_accept_unknown_json_fields() {
|
||||
let message = from_json_with_options::<LoginData>(
|
||||
r#"{"email":"test@example.invalid","future":true}"#,
|
||||
&DeserializeOptions::new().deny_unknown_fields(false),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(message.email, "test@example.invalid");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_decoding_preserves_unknown_wire_fields() {
|
||||
// LoginData.email = "a" followed by unknown varint field 100 = 1.
|
||||
let wire = [0x0a, 0x01, b'a', 0xa0, 0x06, 0x01];
|
||||
let dynamic = decode_dynamic(&format!(".{}", LoginData::full_name()), wire).unwrap();
|
||||
assert_eq!(dynamic.unknown_fields().count(), 1);
|
||||
assert_eq!(dynamic.encode_to_vec(), wire);
|
||||
let typed: LoginData = from_dynamic(&dynamic).unwrap();
|
||||
assert_eq!(typed.email, "a");
|
||||
assert_eq!(typed.encode_to_vec(), [0x0a, 0x01, b'a']);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_conversion_checks_message_identity() {
|
||||
let dynamic = to_dynamic(&LoginData::default()).unwrap();
|
||||
assert!(matches!(
|
||||
from_dynamic::<LoginSession>(&dynamic),
|
||||
Err(ReflectionError::TypeMismatch { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_dynamic("missing.Message", []),
|
||||
Err(ReflectionError::UnknownMessage(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_dynamic(&LoginData::full_name(), [0x0a, 0xff]),
|
||||
Err(ReflectionError::Decode { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_any_payload_uses_embedded_descriptors() {
|
||||
let input = json!({
|
||||
"payload": {
|
||||
"@type": "type.googleapis.com/com.teamspeak.myteamspeak.proto.push.AuthTokenUsed",
|
||||
"idHash": "hash-123"
|
||||
}
|
||||
});
|
||||
let dynamic = dynamic_from_json(
|
||||
"com.teamspeak.myteamspeak.proto.push.PushNotification",
|
||||
&input.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(serde_json::to_value(&dynamic).unwrap(), input);
|
||||
let message: crate::api::push::PushNotification = from_dynamic(&dynamic).unwrap();
|
||||
assert_eq!(
|
||||
from_json::<crate::api::push::PushNotification>(&input.to_string()).unwrap(),
|
||||
message
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&to_json(&message).unwrap()).unwrap(),
|
||||
input
|
||||
);
|
||||
let payload = message.payload.unwrap();
|
||||
assert_eq!(
|
||||
payload.type_url,
|
||||
"type.googleapis.com/com.teamspeak.myteamspeak.proto.push.AuthTokenUsed"
|
||||
);
|
||||
let decoded = crate::api::push::AuthTokenUsed::decode(payload.value.as_slice()).unwrap();
|
||||
assert_eq!(decoded.id_hash, "hash-123");
|
||||
}
|
||||
}
|
||||
+360
@@ -0,0 +1,360 @@
|
||||
//! Session credentials and helpers for session-bearing request bodies.
|
||||
//!
|
||||
//! The schemas put sessions in protobuf fields. These helpers do not infer an
|
||||
//! HTTP authorization header or copy sessions into unrelated nested messages.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use crate::api;
|
||||
|
||||
/// A nonempty session credential. Its [`Debug`](fmt::Debug) output is redacted.
|
||||
///
|
||||
/// This wrapper does not encrypt or zeroize its allocation. Generated protobuf
|
||||
/// requests have ordinary `String` fields and their `Debug` output can include
|
||||
/// credentials, so avoid logging complete request and response bodies.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct SessionToken(String);
|
||||
|
||||
impl SessionToken {
|
||||
/// Wrap an existing credential without changing its contents.
|
||||
///
|
||||
/// Only the empty string is rejected: the schema specifies no other token
|
||||
/// syntax, and whitespace or other characters are therefore not normalized.
|
||||
pub fn new(value: impl Into<String>) -> Result<Self, SessionError> {
|
||||
let value = value.into();
|
||||
if value.is_empty() {
|
||||
Err(SessionError::EmptyToken)
|
||||
} else {
|
||||
Ok(Self(value))
|
||||
}
|
||||
}
|
||||
|
||||
/// Access the credential for an API that requires its string value.
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Explicitly expose the credential. Equivalent to [`Self::as_str`].
|
||||
pub fn expose_secret(&self) -> &str {
|
||||
self.as_str()
|
||||
}
|
||||
|
||||
/// Consume this wrapper and return the credential.
|
||||
pub fn into_inner(self) -> String {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for SessionToken {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str("SessionToken([REDACTED])")
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&api::LoginSession> for SessionToken {
|
||||
type Error = SessionError;
|
||||
|
||||
/// Require `ERROR_LOGIN_OK`, then require a nonempty session credential.
|
||||
///
|
||||
/// A successful login with `skipSession` can legitimately omit a session;
|
||||
/// that response cannot be converted into a session credential.
|
||||
fn try_from(response: &api::LoginSession) -> Result<Self, Self::Error> {
|
||||
check_common_status("login", response.error, api::ErrorCommon::ErrorLoginOk)?;
|
||||
Self::new(response.session.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<String> for SessionToken {
|
||||
type Error = SessionError;
|
||||
|
||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||
Self::new(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for SessionToken {
|
||||
type Error = SessionError;
|
||||
|
||||
fn try_from(value: &str) -> Result<Self, Self::Error> {
|
||||
Self::new(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&SessionToken> for api::Session {
|
||||
fn from(token: &SessionToken) -> Self {
|
||||
Self {
|
||||
session: token.as_str().to_owned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&SessionToken> for api::user::Session {
|
||||
fn from(token: &SessionToken) -> Self {
|
||||
Self {
|
||||
session: token.as_str().to_owned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An API-level error from the common login/session status enum.
|
||||
///
|
||||
/// The raw integer is retained, including values introduced by newer servers.
|
||||
/// It is separate from a gRPC transport status, which may still be successful.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("{operation} returned API status {code}")]
|
||||
pub struct CommonStatusError {
|
||||
/// The operation whose expected success status was absent.
|
||||
pub operation: &'static str,
|
||||
/// The unmodified protobuf enum integer returned by the server.
|
||||
pub code: i32,
|
||||
}
|
||||
|
||||
impl CommonStatusError {
|
||||
/// Resolve a known status without mapping unknown values to zero.
|
||||
pub fn known_code(&self) -> Option<api::ErrorCommon> {
|
||||
api::ErrorCommon::try_from(self.code).ok()
|
||||
}
|
||||
|
||||
/// The original protobuf enum name, if the supplied schemas define it.
|
||||
pub fn code_name(&self) -> Option<&'static str> {
|
||||
self.known_code().map(|code| code.as_str_name())
|
||||
}
|
||||
}
|
||||
|
||||
/// Failure to create a usable session credential.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum SessionError {
|
||||
/// The credential was absent or empty.
|
||||
#[error("the session credential is empty")]
|
||||
EmptyToken,
|
||||
/// The server did not return the operation's success status.
|
||||
#[error(transparent)]
|
||||
Api(#[from] CommonStatusError),
|
||||
}
|
||||
|
||||
fn check_common_status(
|
||||
operation: &'static str,
|
||||
code: i32,
|
||||
expected: api::ErrorCommon,
|
||||
) -> Result<(), CommonStatusError> {
|
||||
if code == expected as i32 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CommonStatusError { operation, code })
|
||||
}
|
||||
}
|
||||
|
||||
/// Require `ERROR_SESSION_OK` (102) from `LoginService.session`.
|
||||
pub fn validate_session_status(response: &api::LoginStatus) -> Result<(), CommonStatusError> {
|
||||
check_common_status("session", response.error, api::ErrorCommon::ErrorSessionOk)
|
||||
}
|
||||
|
||||
/// Require `ERROR_SESSION_DELETED_OK` (204) from `LoginService.deleteSession`.
|
||||
///
|
||||
/// This is a separate check because successful session validation and deletion
|
||||
/// have different status values in the supplied schemas.
|
||||
pub fn validate_deleted_session_status(
|
||||
response: &api::LoginStatus,
|
||||
) -> Result<(), CommonStatusError> {
|
||||
check_common_status(
|
||||
"deleteSession",
|
||||
response.error,
|
||||
api::ErrorCommon::ErrorSessionDeletedOk,
|
||||
)
|
||||
}
|
||||
|
||||
/// Set a request's schema-defined session field while preserving other fields.
|
||||
///
|
||||
/// Implemented for all application request/body messages with a direct string
|
||||
/// `session` or `session_id` field, and for the explicitly supported wrappers
|
||||
/// whose nested request carries the session. This does not recursively modify
|
||||
/// every session-looking field (for example a chat `shared_session_id`).
|
||||
pub trait SessionRequest: Sized {
|
||||
/// Replace the request's session credential.
|
||||
fn set_session(&mut self, token: &SessionToken);
|
||||
|
||||
/// Set the credential and return the request for fluent construction.
|
||||
fn with_session(mut self, token: &SessionToken) -> Self {
|
||||
self.set_session(token);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! session_field {
|
||||
($($message:path => $field:ident),+ $(,)?) => {
|
||||
$(
|
||||
impl SessionRequest for $message {
|
||||
fn set_session(&mut self, token: &SessionToken) {
|
||||
self.$field = token.as_str().to_owned();
|
||||
}
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
session_field! {
|
||||
api::Session => session,
|
||||
api::integration::RequestIntegrationUserStatus => session,
|
||||
api::integration::RequestBindData => session,
|
||||
api::integration::RequestUnbindData => session,
|
||||
api::integration::UserIntegrationSubscriptionInfoRequest => session_id,
|
||||
api::messengerconnector::RequestCreateMessengerAccountRequest => session,
|
||||
api::namedserver::User => session,
|
||||
api::namedserver::NamedServer => session,
|
||||
api::tschat::AuthenticatedUser => session,
|
||||
api::user::UserData => session,
|
||||
api::user::Session => session,
|
||||
api::user::BadgeCode => session,
|
||||
api::user::RequestContactsAvatarInfoRequest => session,
|
||||
api::user::SpawnVoiceServerLocationRequest => session,
|
||||
api::user::VoiceServerRequest => session,
|
||||
api::user::RequestUploadAvatarRequest => session,
|
||||
api::user::RequestDeleteAvatarInfoRequest => session,
|
||||
api::user::AvatarSignedUrlRequest => session,
|
||||
api::user::EmailChange => session,
|
||||
api::user::ResetAccountRequest => session,
|
||||
api::user::UpdateUserDescriptionRequest => session,
|
||||
api::user::UploadFileRequest => session,
|
||||
api::user::DownloadFileRequest => session,
|
||||
api::user::UpdateTwoFactorAuthTypeRequest => session,
|
||||
api::user::TwoFactorAuthTypeRequest => session,
|
||||
api::user::TwoFactorAuthTypeOtpConfirmationRequest => session,
|
||||
api::user::RegisterFirebasePush => session,
|
||||
api::user::AccountDataRequest => session,
|
||||
api::management::user::Request => session,
|
||||
api::management::user::BadgeCodesRequest => session,
|
||||
api::management::user::EmailChange => session,
|
||||
api::management::user::AssignBadgeRequest => session,
|
||||
api::management::user::UserRenameRequest => session,
|
||||
api::management::user::AddBadgeRequest => session,
|
||||
api::management::user::OAuthClientRequest => session,
|
||||
api::management::user::SearchTerm => session,
|
||||
api::management::user::PermissionRequest => session,
|
||||
api::management::user::TsCommunityRequest => session,
|
||||
api::management::user::RenameAllowanceRequest => session,
|
||||
api::management::user::BadgeStatisticsRequest => session,
|
||||
api::management::user::UserStatisticsRequest => session,
|
||||
api::synchronization::SyncRequestItemClasses => session,
|
||||
}
|
||||
|
||||
macro_rules! nested_session {
|
||||
($($message:path => $field:ident),+ $(,)?) => {
|
||||
$(
|
||||
impl SessionRequest for $message {
|
||||
fn set_session(&mut self, token: &SessionToken) {
|
||||
self.$field.get_or_insert_with(Default::default).set_session(token);
|
||||
}
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
nested_session! {
|
||||
api::user::NewUserPublicKeyData => session,
|
||||
api::tschat::GroupSessionRequest => user,
|
||||
api::tschat::MoveRequest => user,
|
||||
api::tschat::ContactRequest => user,
|
||||
api::tschat::ContactRequestList => user,
|
||||
api::tschat::IdentifierRequest => user,
|
||||
api::management::user::UpdateBadgeRequest => add_badge_request,
|
||||
api::management::user::TsCommunityListRequest => request,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn login_requires_explicit_success_and_nonempty_token() {
|
||||
let mut response = api::LoginSession {
|
||||
session: "credential".into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(matches!(
|
||||
SessionToken::try_from(&response),
|
||||
Err(SessionError::Api(CommonStatusError { code: 0, .. }))
|
||||
));
|
||||
response.error = api::ErrorCommon::ErrorLoginOk as i32;
|
||||
assert_eq!(
|
||||
SessionToken::try_from(&response).unwrap().as_str(),
|
||||
"credential"
|
||||
);
|
||||
response.session.clear();
|
||||
assert_eq!(
|
||||
SessionToken::try_from(&response),
|
||||
Err(SessionError::EmptyToken)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redaction_does_not_normalize_credentials() {
|
||||
let token = SessionToken::new(" secret with spaces ").unwrap();
|
||||
assert_eq!(token.as_str(), " secret with spaces ");
|
||||
let rendered = format!("{token:?}");
|
||||
assert!(!rendered.contains("secret"));
|
||||
assert!(rendered.contains("REDACTED"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_checks_preserve_unknown_codes_and_distinguish_deletion() {
|
||||
let unknown = api::LoginStatus {
|
||||
error: 98_765,
|
||||
..Default::default()
|
||||
};
|
||||
let error = validate_session_status(&unknown).unwrap_err();
|
||||
assert_eq!(error.code, 98_765);
|
||||
assert_eq!(error.known_code(), None);
|
||||
assert_eq!(error.code_name(), None);
|
||||
|
||||
let deleted = api::LoginStatus {
|
||||
error: api::ErrorCommon::ErrorSessionDeletedOk as i32,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(validate_deleted_session_status(&deleted).is_ok());
|
||||
let error = validate_session_status(&deleted).unwrap_err();
|
||||
assert_eq!(error.code_name(), Some("ERROR_SESSION_DELETED_OK"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_authentication_preserves_existing_request_data() {
|
||||
let token = SessionToken::new("new-session").unwrap();
|
||||
let request = api::tschat::GroupSessionRequest {
|
||||
user: Some(api::tschat::AuthenticatedUser {
|
||||
session: "old-session".into(),
|
||||
matrix_id: "matrix-user".into(),
|
||||
}),
|
||||
group_sessions: vec![api::tschat::GroupSession {
|
||||
shared_session_id: "unrelated-group-session".into(),
|
||||
..Default::default()
|
||||
}],
|
||||
}
|
||||
.with_session(&token);
|
||||
let user = request.user.unwrap();
|
||||
assert_eq!(user.session, "new-session");
|
||||
assert_eq!(user.matrix_id, "matrix-user");
|
||||
assert_eq!(
|
||||
request.group_sessions[0].shared_session_id,
|
||||
"unrelated-group-session"
|
||||
);
|
||||
|
||||
let request = api::user::NewUserPublicKeyData::default().with_session(&token);
|
||||
assert_eq!(request.session.unwrap().session, "new-session");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_id_and_oneof_fields_are_handled_without_replacement() {
|
||||
let token = SessionToken::new("token").unwrap();
|
||||
let request = api::integration::UserIntegrationSubscriptionInfoRequest::default()
|
||||
.with_session(&token);
|
||||
assert_eq!(request.session_id, "token");
|
||||
|
||||
let identifier =
|
||||
api::management::user::request::RequestOneof::Email("owner@example.test".into());
|
||||
let request = api::management::user::Request {
|
||||
request_oneof: Some(identifier.clone()),
|
||||
..Default::default()
|
||||
}
|
||||
.with_session(&token);
|
||||
assert_eq!(request.request_oneof, Some(identifier));
|
||||
}
|
||||
}
|
||||
Vendored
+151
@@ -0,0 +1,151 @@
|
||||
//! Protobuf binary encoding, checked `Any` envelopes, and opt-in push decoding.
|
||||
|
||||
use prost::{Message, Name};
|
||||
|
||||
/// Serialize a protobuf message to its ordinary, non-length-delimited bytes.
|
||||
pub fn encode<M: Message>(message: &M) -> Vec<u8> {
|
||||
message.encode_to_vec()
|
||||
}
|
||||
|
||||
/// Decode ordinary protobuf bytes into a caller-selected message type.
|
||||
///
|
||||
/// Protobuf itself is not self-describing. A successful decode does not prove
|
||||
/// that the sender intended the selected type; use [`unpack_any`] when an `Any`
|
||||
/// envelope is available.
|
||||
pub fn decode<M: Message + Default>(bytes: impl AsRef<[u8]>) -> Result<M, prost::DecodeError> {
|
||||
M::decode(bytes.as_ref())
|
||||
}
|
||||
|
||||
/// Pack a generated message with the conventional `type.googleapis.com` prefix.
|
||||
pub fn pack_any<M: Message + Name>(message: &M) -> prost_types::Any {
|
||||
pack_any_with_prefix(message, "type.googleapis.com")
|
||||
}
|
||||
|
||||
/// Pack a message using a caller-supplied type URL prefix.
|
||||
///
|
||||
/// Trailing slashes on `prefix` are normalized. The prefix is not dereferenced
|
||||
/// or validated as a network address. The final URL segment is the fully
|
||||
/// qualified protobuf message name supplied by [`Name`].
|
||||
pub fn pack_any_with_prefix<M: Message + Name>(message: &M, prefix: &str) -> prost_types::Any {
|
||||
prost_types::Any {
|
||||
type_url: format!("{}/{}", prefix.trim_end_matches('/'), M::full_name()),
|
||||
value: encode(message),
|
||||
}
|
||||
}
|
||||
|
||||
/// Failure to unpack an `Any` envelope.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum AnyError {
|
||||
/// The type URL did not contain `/` followed by the expected full name.
|
||||
#[error("Any type URL {actual:?} does not identify {expected}")]
|
||||
TypeMismatch {
|
||||
/// The fully qualified protobuf name expected by the caller.
|
||||
expected: String,
|
||||
/// The unmodified type URL from the envelope.
|
||||
actual: String,
|
||||
},
|
||||
/// The name matched, but the binary message could not be decoded.
|
||||
#[error("invalid Any payload: {0}")]
|
||||
Decode(#[from] prost::DecodeError),
|
||||
}
|
||||
|
||||
/// Check the full protobuf type name before decoding an `Any` envelope.
|
||||
///
|
||||
/// Custom URL prefixes are accepted, as required by `google.protobuf.Any`:
|
||||
/// only the segment after the last `/` identifies the message type. A bare
|
||||
/// message name without `/` is rejected. No URL is fetched.
|
||||
pub fn unpack_any<M: Message + Name + Default>(any: &prost_types::Any) -> Result<M, AnyError> {
|
||||
let expected = M::full_name();
|
||||
if any.type_url.rsplit_once('/').map(|(_, name)| name) != Some(expected.as_str()) {
|
||||
return Err(AnyError::TypeMismatch {
|
||||
expected,
|
||||
actual: any.type_url.clone(),
|
||||
});
|
||||
}
|
||||
Ok(decode(&any.value)?)
|
||||
}
|
||||
|
||||
/// Decode a push transport payload as a message type selected by the caller.
|
||||
///
|
||||
/// `PushService.Message.payload` is opaque `bytes`: the supplied schema gives
|
||||
/// no framing, compression, encryption, or payload-type contract. Use this
|
||||
/// helper only when your application defines the payload as ordinary protobuf
|
||||
/// bytes of `M`. Unknown protobuf fields can make an incorrect type appear to
|
||||
/// decode successfully, so decoding is not a type check.
|
||||
pub fn decode_push_payload<M: Message + Default>(
|
||||
message: &crate::push::Message,
|
||||
) -> Result<M, prost::DecodeError> {
|
||||
decode(&message.payload)
|
||||
}
|
||||
|
||||
/// Opt in to treating push bytes as an application `PushNotification` envelope.
|
||||
///
|
||||
/// This relationship is **not guaranteed by the schemas**. Call this only when
|
||||
/// your server specifies it. Then use [`unpack_any`] on the notification's
|
||||
/// optional `payload` to validate and decode its concrete message type.
|
||||
pub fn decode_push_notification(
|
||||
message: &crate::push::Message,
|
||||
) -> Result<crate::api::push::PushNotification, prost::DecodeError> {
|
||||
decode_push_payload(message)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::api;
|
||||
|
||||
#[test]
|
||||
fn any_roundtrip_accepts_custom_prefix_but_checks_the_type_name() {
|
||||
let message = api::Session {
|
||||
session: "token".into(),
|
||||
};
|
||||
let any = pack_any_with_prefix(&message, "https://schema.example.test/types/");
|
||||
assert_eq!(
|
||||
any.type_url,
|
||||
"https://schema.example.test/types/com.teamspeak.myteamspeak.proto.Session"
|
||||
);
|
||||
assert_eq!(unpack_any::<api::Session>(&any).unwrap(), message);
|
||||
// This other Session has identical wire fields, but a different full
|
||||
// protobuf name. Decoding bytes alone would not catch that mistake.
|
||||
assert!(matches!(
|
||||
unpack_any::<api::user::Session>(&any),
|
||||
Err(AnyError::TypeMismatch { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_envelopes_and_payloads_are_rejected() {
|
||||
let mut any = pack_any(&api::Session::default());
|
||||
any.type_url = api::Session::full_name();
|
||||
assert!(matches!(
|
||||
unpack_any::<api::Session>(&any),
|
||||
Err(AnyError::TypeMismatch { .. })
|
||||
));
|
||||
|
||||
any.type_url = format!("type.googleapis.com/{}", api::Session::full_name());
|
||||
any.value = vec![0x0a, 0x02, 0x41]; // string claims two bytes, only one follows.
|
||||
assert!(matches!(
|
||||
unpack_any::<api::Session>(&any),
|
||||
Err(AnyError::Decode(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opt_in_push_decoding_supports_checked_nested_any() {
|
||||
let notification = api::push::SimpleNotification {
|
||||
r#type: 1,
|
||||
relogin_neccessary: true,
|
||||
};
|
||||
let envelope = api::push::PushNotification {
|
||||
payload: Some(pack_any(¬ification)),
|
||||
};
|
||||
let push_message = crate::push::Message {
|
||||
payload: encode(&envelope),
|
||||
};
|
||||
let decoded = decode_push_notification(&push_message).unwrap();
|
||||
assert_eq!(
|
||||
unpack_any::<api::push::SimpleNotification>(&decoded.payload.unwrap()).unwrap(),
|
||||
notification,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user