1 //! grpc-web protocol translation for [`tonic`] services. 2 //! 3 //! [`tonic_web`] enables tonic servers to handle requests from [grpc-web] clients directly, 4 //! without the need of an external proxy. It achieves this by wrapping individual tonic services 5 //! with a [tower] service that performs the translation between protocols and handles `cors` 6 //! requests. 7 //! 8 //! ## Enabling tonic services 9 //! 10 //! The easiest way to get started, is to call the [`enable`] function with your tonic service 11 //! and allow the tonic server to accept HTTP/1.1 requests: 12 //! 13 //! ```ignore 14 //! #[tokio::main] 15 //! async fn main() -> Result<(), Box<dyn std::error::Error>> { 16 //! let addr = "[::1]:50051".parse().unwrap(); 17 //! let greeter = GreeterServer::new(MyGreeter::default()); 18 //! 19 //! Server::builder() 20 //! .accept_http1(true) 21 //! .add_service(tonic_web::enable(greeter)) 22 //! .serve(addr) 23 //! .await?; 24 //! 25 //! Ok(()) 26 //! } 27 //! ``` 28 //! This will apply a default configuration that works well with grpc-web clients out of the box. 29 //! 30 //! You can customize the CORS configuration composing the [`GrpcWebLayer`] with the cors layer of your choice. 31 //! 32 //! ```ignore 33 //! #[tokio::main] 34 //! async fn main() -> Result<(), Box<dyn std::error::Error>> { 35 //! let addr = "[::1]:50051".parse().unwrap(); 36 //! let greeter = GreeterServer::new(MyGreeter::default()); 37 //! 38 //! Server::builder() 39 //! .accept_http1(true) 40 //! // This will apply the gRPC-Web translation layer 41 //! .layer(GrpcWebLayer::new()) 42 //! .add_service(greeter) 43 //! .serve(addr) 44 //! .await?; 45 //! 46 //! Ok(()) 47 //! } 48 //! ``` 49 //! 50 //! Alternatively, if you have a tls enabled server, you could skip setting `accept_http1` to `true`. 51 //! This works because the browser will handle `ALPN`. 52 //! 53 //! ```ignore 54 //! #[tokio::main] 55 //! async fn main() -> Result<(), Box<dyn std::error::Error>> { 56 //! let cert = tokio::fs::read("server.pem").await?; 57 //! let key = tokio::fs::read("server.key").await?; 58 //! let identity = Identity::from_pem(cert, key); 59 //! 60 //! let addr = "[::1]:50051".parse().unwrap(); 61 //! let greeter = GreeterServer::new(MyGreeter::default()); 62 //! 63 //! // No need to enable HTTP/1 64 //! Server::builder() 65 //! .tls_config(ServerTlsConfig::new().identity(identity))? 66 //! .add_service(tonic_web::enable(greeter)) 67 //! .serve(addr) 68 //! .await?; 69 //! 70 //! Ok(()) 71 //! } 72 //! ``` 73 //! 74 //! ## Limitations 75 //! 76 //! * `tonic_web` is designed to work with grpc-web-compliant clients only. It is not expected to 77 //! handle arbitrary HTTP/x.x requests or bespoke protocols. 78 //! * Similarly, the cors support implemented by this crate will *only* handle grpc-web and 79 //! grpc-web preflight requests. 80 //! * Currently, grpc-web clients can only perform `unary` and `server-streaming` calls. These 81 //! are the only requests this crate is designed to handle. Support for client and bi-directional 82 //! streaming will be officially supported when clients do. 83 //! * There is no support for web socket transports. 84 //! 85 //! 86 //! [`tonic`]: https://github.com/hyperium/tonic 87 //! [`tonic_web`]: https://github.com/hyperium/tonic 88 //! [grpc-web]: https://github.com/grpc/grpc-web 89 //! [tower]: https://github.com/tower-rs/tower 90 //! [`enable`]: crate::enable() 91 #![warn( 92 missing_debug_implementations, 93 missing_docs, 94 rust_2018_idioms, 95 unreachable_pub 96 )] 97 #![doc(html_root_url = "https://docs.rs/tonic-web/0.11.0")] 98 #![doc(issue_tracker_base_url = "https://github.com/hyperium/tonic/issues/")] 99 100 pub use call::GrpcWebCall; 101 pub use client::{GrpcWebClientLayer, GrpcWebClientService}; 102 pub use layer::GrpcWebLayer; 103 pub use service::{GrpcWebService, ResponseFuture}; 104 105 mod call; 106 mod client; 107 mod layer; 108 mod service; 109 110 use http::header::HeaderName; 111 use std::time::Duration; 112 use tonic::{body::BoxBody, server::NamedService}; 113 use tower_http::cors::{AllowOrigin, CorsLayer}; 114 use tower_layer::Layer; 115 use tower_service::Service; 116 117 const DEFAULT_MAX_AGE: Duration = Duration::from_secs(24 * 60 * 60); 118 const DEFAULT_EXPOSED_HEADERS: [&str; 3] = 119 ["grpc-status", "grpc-message", "grpc-status-details-bin"]; 120 const DEFAULT_ALLOW_HEADERS: [&str; 4] = 121 ["x-grpc-web", "content-type", "x-user-agent", "grpc-timeout"]; 122 123 type BoxError = Box<dyn std::error::Error + Send + Sync>; 124 125 /// Enable a tonic service to handle grpc-web requests with the default configuration. 126 /// 127 /// You can customize the CORS configuration composing the [`GrpcWebLayer`] with the cors layer of your choice. 128 pub fn enable<S>(service: S) -> CorsGrpcWeb<S> 129 where 130 S: Service<http::Request<hyper::Body>, Response = http::Response<BoxBody>>, 131 S: Clone + Send + 'static, 132 S::Future: Send + 'static, 133 S::Error: Into<BoxError> + Send, 134 { 135 let cors = CorsLayer::new() 136 .allow_origin(AllowOrigin::mirror_request()) 137 .allow_credentials(true) 138 .max_age(DEFAULT_MAX_AGE) 139 .expose_headers( 140 DEFAULT_EXPOSED_HEADERS 141 .iter() 142 .cloned() 143 .map(HeaderName::from_static) 144 .collect::<Vec<HeaderName>>(), 145 ) 146 .allow_headers( 147 DEFAULT_ALLOW_HEADERS 148 .iter() 149 .cloned() 150 .map(HeaderName::from_static) 151 .collect::<Vec<HeaderName>>(), 152 ); 153 154 tower_layer::layer_fn(|s| CorsGrpcWeb(cors.layer(s))).layer(GrpcWebService::new(service)) 155 } 156 157 /// A newtype wrapper around [`GrpcWebLayer`] and [`tower_http::cors::CorsLayer`] to allow 158 /// `tonic_web::enable` to implement the [`NamedService`] trait. 159 #[derive(Debug, Clone)] 160 pub struct CorsGrpcWeb<S>(tower_http::cors::Cors<GrpcWebService<S>>); 161 162 impl<S> Service<http::Request<hyper::Body>> for CorsGrpcWeb<S> 163 where 164 S: Service<http::Request<hyper::Body>, Response = http::Response<BoxBody>>, 165 S: Clone + Send + 'static, 166 S::Future: Send + 'static, 167 S::Error: Into<BoxError> + Send, 168 { 169 type Response = S::Response; 170 type Error = S::Error; 171 type Future = 172 <tower_http::cors::Cors<GrpcWebService<S>> as Service<http::Request<hyper::Body>>>::Future; 173 174 fn poll_ready( 175 &mut self, 176 cx: &mut std::task::Context<'_>, 177 ) -> std::task::Poll<Result<(), Self::Error>> { 178 self.0.poll_ready(cx) 179 } 180 181 fn call(&mut self, req: http::Request<hyper::Body>) -> Self::Future { 182 self.0.call(req) 183 } 184 } 185 186 impl<S> NamedService for CorsGrpcWeb<S> 187 where 188 S: NamedService, 189 { 190 const NAME: &'static str = S::NAME; 191 } 192 193 pub(crate) mod util { 194 pub(crate) mod base64 { 195 use base64::{ 196 alphabet, 197 engine::{ 198 general_purpose::{GeneralPurpose, GeneralPurposeConfig}, 199 DecodePaddingMode, 200 }, 201 }; 202 203 pub(crate) const STANDARD: GeneralPurpose = GeneralPurpose::new( 204 &alphabet::STANDARD, 205 GeneralPurposeConfig::new() 206 .with_encode_padding(true) 207 .with_decode_padding_mode(DecodePaddingMode::Indifferent), 208 ); 209 } 210 } 211