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.9.2")] 98 #![doc(issue_tracker_base_url = "https://github.com/hyperium/tonic/issues/")] 99 100 pub use layer::GrpcWebLayer; 101 pub use service::{GrpcWebService, ResponseFuture}; 102 103 mod call; 104 mod layer; 105 mod service; 106 107 use http::header::HeaderName; 108 use std::time::Duration; 109 use tonic::{body::BoxBody, server::NamedService}; 110 use tower_http::cors::{AllowOrigin, CorsLayer}; 111 use tower_layer::Layer; 112 use tower_service::Service; 113 114 const DEFAULT_MAX_AGE: Duration = Duration::from_secs(24 * 60 * 60); 115 const DEFAULT_EXPOSED_HEADERS: [&str; 3] = 116 ["grpc-status", "grpc-message", "grpc-status-details-bin"]; 117 const DEFAULT_ALLOW_HEADERS: [&str; 4] = 118 ["x-grpc-web", "content-type", "x-user-agent", "grpc-timeout"]; 119 120 type BoxError = Box<dyn std::error::Error + Send + Sync>; 121 122 /// Enable a tonic service to handle grpc-web requests with the default configuration. 123 /// 124 /// You can customize the CORS configuration composing the [`GrpcWebLayer`] with the cors layer of your choice. 125 pub fn enable<S>(service: S) -> CorsGrpcWeb<S> 126 where 127 S: Service<http::Request<hyper::Body>, Response = http::Response<BoxBody>>, 128 S: Clone + Send + 'static, 129 S::Future: Send + 'static, 130 S::Error: Into<BoxError> + Send, 131 { 132 let cors = CorsLayer::new() 133 .allow_origin(AllowOrigin::mirror_request()) 134 .allow_credentials(true) 135 .max_age(DEFAULT_MAX_AGE) 136 .expose_headers( 137 DEFAULT_EXPOSED_HEADERS 138 .iter() 139 .cloned() 140 .map(HeaderName::from_static) 141 .collect::<Vec<HeaderName>>(), 142 ) 143 .allow_headers( 144 DEFAULT_ALLOW_HEADERS 145 .iter() 146 .cloned() 147 .map(HeaderName::from_static) 148 .collect::<Vec<HeaderName>>(), 149 ); 150 151 tower_layer::layer_fn(|s| CorsGrpcWeb(cors.layer(s))).layer(GrpcWebService::new(service)) 152 } 153 154 /// A newtype wrapper around [`GrpcWebLayer`] and [`tower_http::cors::CorsLayer`] to allow 155 /// `tonic_web::enable` to implement the [`NamedService`] trait. 156 #[derive(Debug, Clone)] 157 pub struct CorsGrpcWeb<S>(tower_http::cors::Cors<GrpcWebService<S>>); 158 159 impl<S> Service<http::Request<hyper::Body>> for CorsGrpcWeb<S> 160 where 161 S: Service<http::Request<hyper::Body>, Response = http::Response<BoxBody>>, 162 S: Clone + Send + 'static, 163 S::Future: Send + 'static, 164 S::Error: Into<BoxError> + Send, 165 { 166 type Response = S::Response; 167 type Error = S::Error; 168 type Future = 169 <tower_http::cors::Cors<GrpcWebService<S>> as Service<http::Request<hyper::Body>>>::Future; 170 171 fn poll_ready( 172 &mut self, 173 cx: &mut std::task::Context<'_>, 174 ) -> std::task::Poll<Result<(), Self::Error>> { 175 self.0.poll_ready(cx) 176 } 177 178 fn call(&mut self, req: http::Request<hyper::Body>) -> Self::Future { 179 self.0.call(req) 180 } 181 } 182 183 impl<S> NamedService for CorsGrpcWeb<S> 184 where 185 S: NamedService, 186 { 187 const NAME: &'static str = S::NAME; 188 } 189 190 pub(crate) mod util { 191 pub(crate) mod base64 { 192 use base64::{ 193 alphabet, 194 engine::{ 195 general_purpose::{GeneralPurpose, GeneralPurposeConfig}, 196 DecodePaddingMode, 197 }, 198 }; 199 200 pub(crate) const STANDARD: GeneralPurpose = GeneralPurpose::new( 201 &alphabet::STANDARD, 202 GeneralPurposeConfig::new() 203 .with_encode_padding(true) 204 .with_decode_padding_mode(DecodePaddingMode::Indifferent), 205 ); 206 } 207 } 208