Skip to main content

libsignal_service/grpc/
mod.rs

1use std::time::Duration;
2
3use base64::prelude::*;
4use prost::Message;
5use tonic::{
6    codegen::GrpcMethod,
7    metadata::{Ascii, MetadataValue},
8    service::{interceptor::InterceptedService, Interceptor},
9    transport::{Certificate, Channel, ClientTlsConfig, Endpoint},
10    Code, Request, Status,
11};
12
13use crate::{
14    configuration::{self, ServiceConfiguration},
15    push_service::{HttpAuth, ServiceError},
16};
17
18pub use libsignal_net_grpc::proto;
19
20pub type ChatChannel = InterceptedService<Channel, ChatInterceptor>;
21
22/// Adds Basic auth on the authenticated channel and logs every call.
23#[derive(Clone)]
24pub struct ChatInterceptor {
25    authorization: Option<MetadataValue<Ascii>>,
26}
27
28impl Interceptor for ChatInterceptor {
29    fn call(
30        &mut self,
31        mut request: Request<()>,
32    ) -> Result<Request<()>, Status> {
33        if let Some(method) = request.extensions().get::<GrpcMethod>() {
34            tracing::debug!(
35                service = method.service(),
36                method = method.method(),
37                authenticated = self.authorization.is_some(),
38                "gRPC call"
39            );
40        }
41        if let Some(authorization) = &self.authorization {
42            request
43                .metadata_mut()
44                .insert("authorization", authorization.clone());
45        }
46        Ok(request)
47    }
48}
49
50impl ChatInterceptor {
51    fn unauthenticated() -> Self {
52        Self {
53            authorization: None,
54        }
55    }
56
57    fn authenticated(auth: &HttpAuth) -> Result<Self, ServiceError> {
58        let token = BASE64_STANDARD
59            .encode(format!("{}:{}", auth.username, auth.password));
60        let value = format!("Basic {token}").parse().map_err(|_| {
61            ServiceError::InvalidFrame {
62                reason: "credentials are not valid header characters",
63            }
64        })?;
65        Ok(Self {
66            authorization: Some(value),
67        })
68    }
69}
70
71/// Lazily-connected HTTP/2 channels to the chat server's gRPC endpoint.
72///
73/// Authenticated and unauthenticated calls use separate connections, as libsignal does.
74#[derive(Clone)]
75pub struct GrpcChannels {
76    authenticated: Option<ChatChannel>,
77    unauthenticated: ChatChannel,
78}
79
80impl GrpcChannels {
81    pub fn new(
82        cfg: &ServiceConfiguration,
83        credentials: Option<&HttpAuth>,
84        user_agent: &str,
85    ) -> Result<Self, ServiceError> {
86        let endpoint = endpoint(cfg, user_agent)?;
87        let unauthenticated = InterceptedService::new(
88            endpoint.connect_lazy(),
89            ChatInterceptor::unauthenticated(),
90        );
91        let authenticated = credentials
92            .map(|auth| {
93                Ok::<_, ServiceError>(InterceptedService::new(
94                    endpoint.connect_lazy(),
95                    ChatInterceptor::authenticated(auth)?,
96                ))
97            })
98            .transpose()?;
99
100        Ok(Self {
101            authenticated,
102            unauthenticated,
103        })
104    }
105
106    pub fn authenticated(&self) -> Result<ChatChannel, ServiceError> {
107        self.authenticated.clone().ok_or(ServiceError::Unauthorized)
108    }
109
110    pub fn unauthenticated(&self) -> ChatChannel {
111        self.unauthenticated.clone()
112    }
113}
114
115fn endpoint(
116    cfg: &ServiceConfiguration,
117    user_agent: &str,
118) -> Result<Endpoint, ServiceError> {
119    let url = configuration::Endpoint::Grpc.into_url(cfg)?;
120    let host = url.host_str().ok_or(ServiceError::InvalidFrame {
121        reason: "gRPC URL has no host",
122    })?;
123    let tls = ClientTlsConfig::new()
124        .ca_certificates(
125            cfg.certificate_authorities
126                .iter()
127                .map(Certificate::from_pem),
128        )
129        .domain_name(host);
130    Ok(Endpoint::from_shared(url.to_string())?
131        .tls_config(tls)?
132        .user_agent(user_agent)?
133        .connect_timeout(Duration::from_secs(10))
134        .http2_keep_alive_interval(Duration::from_secs(30))
135        .keep_alive_while_idle(true))
136}
137
138const RETRY_INFO_TYPE_URL: &str = "type.googleapis.com/google.rpc.RetryInfo";
139
140impl From<Status> for ServiceError {
141    fn from(status: Status) -> Self {
142        tracing::debug!(code = ?status.code(), message = status.message(), "gRPC call failed");
143        match status.code() {
144            Code::Unauthenticated | Code::PermissionDenied => {
145                ServiceError::Unauthorized
146            },
147            Code::NotFound => ServiceError::NotFoundError,
148            Code::ResourceExhausted => ServiceError::RateLimitExceeded {
149                retry_after: retry_after(&status),
150            },
151            _ => ServiceError::Grpc(Box::new(status)),
152        }
153    }
154}
155
156fn retry_after(status: &Status) -> Option<chrono::Duration> {
157    let details = proto::google::rpc::Status::decode(status.details()).ok()?;
158    let info = details
159        .details
160        .iter()
161        .find(|any| any.type_url == RETRY_INFO_TYPE_URL)?;
162    let delay = proto::google::rpc::RetryInfo::decode(info.value.as_slice())
163        .ok()?
164        .retry_delay?;
165    Some(
166        chrono::Duration::seconds(delay.seconds)
167            + chrono::Duration::nanoseconds(delay.nanos.into()),
168    )
169}