|
| 1 | +// Copyright 2020 Oxide Computer Company |
| 2 | + |
| 3 | +/*! |
| 4 | + * Example use of Dropshot with TLS enabled |
| 5 | + */ |
| 6 | + |
| 7 | +use dropshot::endpoint; |
| 8 | +use dropshot::ApiDescription; |
| 9 | +use dropshot::ConfigDropshot; |
| 10 | +use dropshot::ConfigLogging; |
| 11 | +use dropshot::ConfigLoggingLevel; |
| 12 | +use dropshot::ConfigTls; |
| 13 | +use dropshot::HttpError; |
| 14 | +use dropshot::HttpResponseOk; |
| 15 | +use dropshot::HttpResponseUpdatedNoContent; |
| 16 | +use dropshot::HttpServerStarter; |
| 17 | +use dropshot::RequestContext; |
| 18 | +use dropshot::TypedBody; |
| 19 | +use schemars::JsonSchema; |
| 20 | +use serde::Deserialize; |
| 21 | +use serde::Serialize; |
| 22 | +use std::io::Write; |
| 23 | +use std::sync::atomic::AtomicU64; |
| 24 | +use std::sync::atomic::Ordering; |
| 25 | +use std::sync::Arc; |
| 26 | +use tempfile::NamedTempFile; |
| 27 | + |
| 28 | +/* |
| 29 | + * This function would not be used in a normal application. It is used to |
| 30 | + * generate temporary keys and certificates for the purpose of this demo. |
| 31 | + */ |
| 32 | +fn generate_keys() -> Result<(NamedTempFile, NamedTempFile), String> { |
| 33 | + let keypair = |
| 34 | + rcgen::generate_simple_self_signed(vec!["localhost".to_string()]) |
| 35 | + .map_err(|e| e.to_string())?; |
| 36 | + let cert = keypair.serialize_pem().map_err(|e| e.to_string())?; |
| 37 | + let priv_key = keypair.serialize_private_key_pem(); |
| 38 | + |
| 39 | + let make_temp = || { |
| 40 | + tempfile::Builder::new() |
| 41 | + .prefix("dropshot-https-example-") |
| 42 | + .rand_bytes(5) |
| 43 | + .tempfile() |
| 44 | + }; |
| 45 | + |
| 46 | + let mut cert_file = |
| 47 | + make_temp().map_err(|_| "failed to create cert_file")?; |
| 48 | + cert_file |
| 49 | + .write(cert.as_bytes()) |
| 50 | + .map_err(|_| "failed to write cert_file")?; |
| 51 | + let mut key_file = make_temp().map_err(|_| "failed to create key_file")?; |
| 52 | + key_file |
| 53 | + .write(priv_key.as_bytes()) |
| 54 | + .map_err(|_| "failed to write key_file")?; |
| 55 | + Ok((cert_file, key_file)) |
| 56 | +} |
| 57 | + |
| 58 | +#[tokio::main] |
| 59 | +async fn main() -> Result<(), String> { |
| 60 | + /* |
| 61 | + * Begin by generating TLS certificates and keys. A normal application would |
| 62 | + * just pass the paths to these via ConfigDropshot. |
| 63 | + */ |
| 64 | + let (cert_file, key_file) = generate_keys()?; |
| 65 | + |
| 66 | + /* |
| 67 | + * We must specify a configuration with a bind address. We'll use 127.0.0.1 |
| 68 | + * since it's available and won't expose this server outside the host. We |
| 69 | + * request port 0, which allows the operating system to pick any available |
| 70 | + * port. |
| 71 | + * |
| 72 | + * In addition, we'll make this an HTTPS server. |
| 73 | + */ |
| 74 | + let config_dropshot = ConfigDropshot { |
| 75 | + tls: Some(ConfigTls { |
| 76 | + cert_file: cert_file.path().to_path_buf(), |
| 77 | + key_file: key_file.path().to_path_buf(), |
| 78 | + }), |
| 79 | + ..Default::default() |
| 80 | + }; |
| 81 | + |
| 82 | + /* |
| 83 | + * For simplicity, we'll configure an "info"-level logger that writes to |
| 84 | + * stderr assuming that it's a terminal. |
| 85 | + */ |
| 86 | + let config_logging = ConfigLogging::StderrTerminal { |
| 87 | + level: ConfigLoggingLevel::Info, |
| 88 | + }; |
| 89 | + let log = config_logging |
| 90 | + .to_logger("example-basic") |
| 91 | + .map_err(|error| format!("failed to create logger: {}", error))?; |
| 92 | + |
| 93 | + /* |
| 94 | + * Build a description of the API. |
| 95 | + */ |
| 96 | + let mut api = ApiDescription::new(); |
| 97 | + api.register(example_api_get_counter).unwrap(); |
| 98 | + api.register(example_api_put_counter).unwrap(); |
| 99 | + |
| 100 | + /* |
| 101 | + * The functions that implement our API endpoints will share this context. |
| 102 | + */ |
| 103 | + let api_context = ExampleContext::new(); |
| 104 | + |
| 105 | + /* |
| 106 | + * Set up the server. |
| 107 | + */ |
| 108 | + let server = |
| 109 | + HttpServerStarter::new(&config_dropshot, api, api_context, &log) |
| 110 | + .map_err(|error| format!("failed to create server: {}", error))? |
| 111 | + .start(); |
| 112 | + |
| 113 | + /* |
| 114 | + * Wait for the server to stop. Note that there's not any code to shut down |
| 115 | + * this server, so we should never get past this point. |
| 116 | + */ |
| 117 | + server.await |
| 118 | +} |
| 119 | + |
| 120 | +/** |
| 121 | + * Application-specific example context (state shared by handler functions) |
| 122 | + */ |
| 123 | +struct ExampleContext { |
| 124 | + /** counter that can be manipulated by requests to the HTTP API */ |
| 125 | + counter: AtomicU64, |
| 126 | +} |
| 127 | + |
| 128 | +impl ExampleContext { |
| 129 | + /** |
| 130 | + * Return a new ExampleContext. |
| 131 | + */ |
| 132 | + pub fn new() -> ExampleContext { |
| 133 | + ExampleContext { |
| 134 | + counter: AtomicU64::new(0), |
| 135 | + } |
| 136 | + } |
| 137 | +} |
| 138 | + |
| 139 | +/* |
| 140 | + * HTTP API interface |
| 141 | + */ |
| 142 | + |
| 143 | +/** |
| 144 | + * `CounterValue` represents the value of the API's counter, either as the |
| 145 | + * response to a GET request to fetch the counter or as the body of a PUT |
| 146 | + * request to update the counter. |
| 147 | + */ |
| 148 | +#[derive(Deserialize, Serialize, JsonSchema)] |
| 149 | +struct CounterValue { |
| 150 | + counter: u64, |
| 151 | +} |
| 152 | + |
| 153 | +/** |
| 154 | + * Fetch the current value of the counter. |
| 155 | + */ |
| 156 | +#[endpoint { |
| 157 | + method = GET, |
| 158 | + path = "/counter", |
| 159 | +}] |
| 160 | +async fn example_api_get_counter( |
| 161 | + rqctx: Arc<RequestContext<ExampleContext>>, |
| 162 | +) -> Result<HttpResponseOk<CounterValue>, HttpError> { |
| 163 | + let api_context = rqctx.context(); |
| 164 | + |
| 165 | + Ok(HttpResponseOk(CounterValue { |
| 166 | + counter: api_context.counter.load(Ordering::SeqCst), |
| 167 | + })) |
| 168 | +} |
| 169 | + |
| 170 | +/** |
| 171 | + * Update the current value of the counter. Note that the special value of 10 |
| 172 | + * is not allowed (just to demonstrate how to generate an error). |
| 173 | + */ |
| 174 | +#[endpoint { |
| 175 | + method = PUT, |
| 176 | + path = "/counter", |
| 177 | +}] |
| 178 | +async fn example_api_put_counter( |
| 179 | + rqctx: Arc<RequestContext<ExampleContext>>, |
| 180 | + update: TypedBody<CounterValue>, |
| 181 | +) -> Result<HttpResponseUpdatedNoContent, HttpError> { |
| 182 | + let api_context = rqctx.context(); |
| 183 | + let updated_value = update.into_inner(); |
| 184 | + |
| 185 | + if updated_value.counter == 10 { |
| 186 | + Err(HttpError::for_bad_request( |
| 187 | + Some(String::from("BadInput")), |
| 188 | + format!("do not like the number {}", updated_value.counter), |
| 189 | + )) |
| 190 | + } else { |
| 191 | + api_context.counter.store(updated_value.counter, Ordering::SeqCst); |
| 192 | + Ok(HttpResponseUpdatedNoContent()) |
| 193 | + } |
| 194 | +} |
0 commit comments