pcs_external/external/mod.rs
1//! gRPC client for PCS External API.
2//!
3//! # Usage
4//!
5//! ```no_run
6//! # async fn example() -> Result<(), pcs_external::Error> {
7//! use pcs_external::external::{connect, auth_request};
8//! use pcs_external::external::proto::{
9//! external_channel_service_client::ExternalChannelServiceClient,
10//! ExtCreateChannelReq, ExtChannelType, ExtStorageMode,
11//! };
12//!
13//! let channel = connect("http://localhost:3203").await?;
14//! let mut client = ExternalChannelServiceClient::new(channel);
15//!
16//! let req = auth_request("pk_live_abc123", ExtCreateChannelReq {
17//! name: "test.ctx".into(),
18//! r#type: ExtChannelType::Group.into(),
19//! storage_mode: ExtStorageMode::Buffered.into(),
20//! ..Default::default()
21//! })?;
22//! let _resp = client.create_channel(req).await;
23//! # Ok(())
24//! # }
25//! ```
26
27pub mod proto;
28
29use std::future::Future;
30use std::pin::Pin;
31use std::task::{Context, Poll};
32use std::time::Duration;
33
34use tonic::transport::Channel;
35
36use crate::error::Error;
37
38/// A gRPC channel that prepends an optional path prefix to all requests.
39///
40/// When the API URL includes a path (e.g., `https://api.ppoppo.com/ext`),
41/// all gRPC method paths are prefixed (e.g., `/ext/chat.external.ExternalMessageService/Method`).
42/// This enables GKE Ingress path-based routing where `/ext` maps to the External API backend.
43///
44/// When the URL has no path (e.g., `https://api.ppoppo.com`), requests pass through unchanged.
45#[derive(Clone)]
46pub struct ExternalChannel {
47 inner: Channel,
48 prefix: String,
49}
50
51/// Connect to the PCS External API with automatic TLS and path prefix support.
52///
53/// When the URL starts with `https://`, TLS is configured using webpki root certificates.
54/// When the URL contains a path (e.g., `/ext`), it's extracted and prepended to all
55/// gRPC method paths for compatibility with path-based reverse proxy routing.
56///
57/// Default timeouts: 10s connect, 30s request.
58///
59/// # Examples
60///
61/// ```no_run
62/// # async fn example() -> Result<(), pcs_external::Error> {
63/// // Direct connection (no path prefix)
64/// let channel = pcs_external::connect("http://localhost:3203").await?;
65///
66/// // With path prefix for GKE Ingress routing
67/// let channel = pcs_external::connect("https://api.ppoppo.com/ext").await?;
68/// // gRPC paths become: /ext/chat.external.ExternalMessageService/Method
69/// # Ok(())
70/// # }
71/// ```
72pub async fn connect(api_url: &str) -> Result<ExternalChannel, Error> {
73 // Parse URL to extract optional path prefix
74 let uri: http::Uri = api_url
75 .parse()
76 .map_err(|e| Error::External(format!("Invalid API URL '{api_url}': {e}")))?;
77
78 let raw_path = uri.path().trim_end_matches('/');
79 let prefix = if raw_path.is_empty() || raw_path == "/" {
80 String::new()
81 } else {
82 raw_path.to_string()
83 };
84
85 // H5 — pre-validate the prefix at connect time so that `Service::call`
86 // can never silently fall back to an unprefixed URI. We construct a
87 // representative gRPC method path and confirm the prepended URI parses.
88 if !prefix.is_empty() {
89 let probe = format!("{prefix}/chat.external.SmokeTest/Method");
90 probe
91 .parse::<http::uri::PathAndQuery>()
92 .map_err(|e| Error::InvalidPathPrefix {
93 prefix: prefix.clone(),
94 reason: e.to_string(),
95 })?;
96 }
97
98 // Build base URL (scheme + authority) for tonic Endpoint, stripping the path
99 let base_url = if prefix.is_empty() {
100 api_url.to_string()
101 } else {
102 let scheme = uri.scheme_str().unwrap_or("https");
103 let authority = uri
104 .authority()
105 .map(|a| a.as_str())
106 .ok_or_else(|| Error::External(format!("Missing authority in URL: {api_url}")))?;
107 format!("{scheme}://{authority}")
108 };
109
110 let endpoint = tonic::transport::Endpoint::from_shared(base_url.clone())
111 .map_err(|e| Error::External(format!("Invalid API URL '{base_url}': {e}")))?
112 .connect_timeout(Duration::from_secs(10))
113 .timeout(Duration::from_secs(30));
114
115 let endpoint = if api_url.starts_with("https://") {
116 endpoint
117 .tls_config(tonic::transport::ClientTlsConfig::new().with_enabled_roots())
118 .map_err(|e| Error::External(format!("TLS configuration failed: {e}")))?
119 } else {
120 endpoint
121 };
122
123 let channel = endpoint
124 .connect()
125 .await
126 .map_err(|e| Error::External(format!("Failed to connect to {base_url}: {e}")))?;
127
128 Ok(ExternalChannel {
129 inner: channel,
130 prefix,
131 })
132}
133
134/// Wrap a request body with Bearer API key authentication metadata.
135///
136/// All PCS External API calls require an API key in the `Authorization` header.
137/// This helper creates a `tonic::Request<T>` with the key pre-attached.
138///
139/// # Errors
140///
141/// Returns [`Error::InvalidApiKey`] if `api_key` contains characters that are
142/// not valid HTTP header values (CR, LF, NUL, non-visible ASCII). The previous
143/// `parse().ok()` path silently sent the request without auth, surfacing as a
144/// confusing `Unauthenticated` from PCS instead of a local config error.
145///
146/// # Example
147///
148/// ```no_run
149/// # use pcs_external::external::auth_request;
150/// # use pcs_external::external::proto::ExtGetOrCreateDmReq;
151/// # fn try_main() -> Result<(), pcs_external::Error> {
152/// let req = auth_request("pk_live_abc123", ExtGetOrCreateDmReq {
153/// target_ppnum: "77712345678".into(),
154/// })?;
155/// # Ok(()) }
156/// ```
157pub fn auth_request<T>(api_key: &str, body: T) -> Result<tonic::Request<T>, Error> {
158 let value = format!("Bearer {api_key}")
159 .parse::<tonic::metadata::MetadataValue<_>>()
160 .map_err(|_| Error::InvalidApiKey)?;
161 let mut req = tonic::Request::new(body);
162 req.metadata_mut().insert("authorization", value);
163 Ok(req)
164}
165
166// Implement tower Service for ExternalChannel using the same request/response
167// types as tonic::transport::Channel. In tonic 0.14, Channel uses tonic::body::Body.
168impl tower_service::Service<http::Request<tonic::body::Body>> for ExternalChannel {
169 type Response = http::Response<tonic::body::Body>;
170 type Error = tonic::transport::Error;
171 type Future =
172 Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
173
174 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
175 tower_service::Service::poll_ready(&mut self.inner, cx)
176 }
177
178 fn call(&mut self, mut req: http::Request<tonic::body::Body>) -> Self::Future {
179 if !self.prefix.is_empty() && !prepend_path_prefix(&mut req, &self.prefix) {
180 // Pre-validated at connect(). Reaching here means a request URI
181 // arrived in a shape that breaks the prefixed form. Short-circuit
182 // by sending a request that the underlying Channel will reject,
183 // rather than silently routing to the wrong backend. Returning
184 // a 400-shaped Response would require a Body construction; we
185 // route through inner with the *unprefixed* URI overridden to
186 // a known-bad path so the server returns 404 deterministically.
187 // (Service::Error is tonic::transport::Error which we cannot
188 // synthesize from outside the crate.)
189 *req.uri_mut() = "/__pcs_external_invalid_path__".parse().unwrap_or_else(|_| {
190 req.uri().clone()
191 });
192 }
193 let fut = tower_service::Service::call(&mut self.inner, req);
194 Box::pin(fut)
195 }
196}
197
198#[cfg(test)]
199#[allow(clippy::unwrap_used)]
200mod tests {
201 use super::*;
202
203 #[test]
204 fn auth_request_accepts_normal_key() {
205 let req = auth_request("pk_live_abc123", ()).unwrap();
206 let auth = req.metadata().get("authorization").unwrap();
207 assert_eq!(auth, "Bearer pk_live_abc123");
208 }
209
210 #[test]
211 fn auth_request_rejects_newline_in_key() {
212 // Header injection attempt — must NOT silently strip auth and send.
213 let result = auth_request("pk_live_abc\r\nX-Injected: bad", ());
214 assert!(matches!(result, Err(Error::InvalidApiKey)));
215 }
216
217 #[test]
218 fn auth_request_rejects_nul_in_key() {
219 let result = auth_request("pk_live_abc\0nul", ());
220 assert!(matches!(result, Err(Error::InvalidApiKey)));
221 }
222}
223
224/// Prepend a path prefix to the request URI.
225///
226/// Transforms `/chat.external.ExternalMessageService/Method`
227/// into `/ext/chat.external.ExternalMessageService/Method`.
228///
229/// Returns `true` on success. Returns `false` only if the path-prefixed URI
230/// fails to parse — `connect()` validates the prefix at construction so this
231/// path is unreachable in normal flows. If it does happen (e.g., a request
232/// arrives with an unusually malformed path), the caller short-circuits the
233/// request with a `400` so it never silently routes to the wrong backend.
234fn prepend_path_prefix(req: &mut http::Request<tonic::body::Body>, prefix: &str) -> bool {
235 let pq_str = req
236 .uri()
237 .path_and_query()
238 .map(|pq| pq.as_str())
239 .unwrap_or("/");
240 let new_path = format!("{prefix}{pq_str}");
241 let Ok(new_pq) = new_path.parse::<http::uri::PathAndQuery>() else {
242 return false;
243 };
244 let mut parts = req.uri().clone().into_parts();
245 parts.path_and_query = Some(new_pq);
246 let Ok(new_uri) = http::Uri::from_parts(parts) else {
247 return false;
248 };
249 *req.uri_mut() = new_uri;
250 true
251}