itsi-scheduler 0.1.5 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. checksums.yaml +4 -4
  2. data/Cargo.lock +120 -52
  3. data/README.md +57 -24
  4. data/Rakefile +0 -4
  5. data/ext/itsi_acme/Cargo.toml +86 -0
  6. data/ext/itsi_acme/examples/high_level.rs +63 -0
  7. data/ext/itsi_acme/examples/high_level_warp.rs +52 -0
  8. data/ext/itsi_acme/examples/low_level.rs +87 -0
  9. data/ext/itsi_acme/examples/low_level_axum.rs +66 -0
  10. data/ext/itsi_acme/src/acceptor.rs +81 -0
  11. data/ext/itsi_acme/src/acme.rs +354 -0
  12. data/ext/itsi_acme/src/axum.rs +86 -0
  13. data/ext/itsi_acme/src/cache.rs +39 -0
  14. data/ext/itsi_acme/src/caches/boxed.rs +80 -0
  15. data/ext/itsi_acme/src/caches/composite.rs +69 -0
  16. data/ext/itsi_acme/src/caches/dir.rs +106 -0
  17. data/ext/itsi_acme/src/caches/mod.rs +11 -0
  18. data/ext/itsi_acme/src/caches/no.rs +78 -0
  19. data/ext/itsi_acme/src/caches/test.rs +136 -0
  20. data/ext/itsi_acme/src/config.rs +172 -0
  21. data/ext/itsi_acme/src/https_helper.rs +69 -0
  22. data/ext/itsi_acme/src/incoming.rs +142 -0
  23. data/ext/itsi_acme/src/jose.rs +161 -0
  24. data/ext/itsi_acme/src/lib.rs +142 -0
  25. data/ext/itsi_acme/src/resolver.rs +59 -0
  26. data/ext/itsi_acme/src/state.rs +424 -0
  27. data/ext/itsi_error/Cargo.toml +1 -0
  28. data/ext/itsi_error/src/lib.rs +106 -7
  29. data/ext/itsi_error/target/debug/build/clang-sys-da71b0344e568175/out/common.rs +355 -0
  30. data/ext/itsi_error/target/debug/build/clang-sys-da71b0344e568175/out/dynamic.rs +276 -0
  31. data/ext/itsi_error/target/debug/build/clang-sys-da71b0344e568175/out/macros.rs +49 -0
  32. data/ext/itsi_error/target/debug/build/rb-sys-49f554618693db24/out/bindings-0.9.110-mri-arm64-darwin23-3.4.2.rs +8865 -0
  33. data/ext/itsi_error/target/debug/incremental/itsi_error-1mmt5sux7jb0i/s-h510z7m8v9-0bxu7yd.lock +0 -0
  34. data/ext/itsi_error/target/debug/incremental/itsi_error-2vn3jey74oiw0/s-h5113n0e7e-1v5qzs6.lock +0 -0
  35. data/ext/itsi_error/target/debug/incremental/itsi_error-37uv9dicz7awp/s-h510ykifhe-0tbnep2.lock +0 -0
  36. data/ext/itsi_error/target/debug/incremental/itsi_error-37uv9dicz7awp/s-h510yyocpj-0tz7ug7.lock +0 -0
  37. data/ext/itsi_error/target/debug/incremental/itsi_error-37uv9dicz7awp/s-h510z0xc8g-14ol18k.lock +0 -0
  38. data/ext/itsi_error/target/debug/incremental/itsi_error-3g5qf4y7d54uj/s-h5113n0e7d-1trk8on.lock +0 -0
  39. data/ext/itsi_error/target/debug/incremental/itsi_error-3lpfftm45d3e2/s-h510z7m8r3-1pxp20o.lock +0 -0
  40. data/ext/itsi_error/target/debug/incremental/itsi_error-3o4qownhl3d7n/s-h510ykifek-1uxasnk.lock +0 -0
  41. data/ext/itsi_error/target/debug/incremental/itsi_error-3o4qownhl3d7n/s-h510yyocki-11u37qm.lock +0 -0
  42. data/ext/itsi_error/target/debug/incremental/itsi_error-3o4qownhl3d7n/s-h510z0xc93-0pmy0zm.lock +0 -0
  43. data/ext/itsi_rb_helpers/Cargo.toml +1 -0
  44. data/ext/itsi_rb_helpers/src/heap_value.rs +18 -0
  45. data/ext/itsi_rb_helpers/src/lib.rs +63 -12
  46. data/ext/itsi_rb_helpers/target/debug/build/clang-sys-da71b0344e568175/out/common.rs +355 -0
  47. data/ext/itsi_rb_helpers/target/debug/build/clang-sys-da71b0344e568175/out/dynamic.rs +276 -0
  48. data/ext/itsi_rb_helpers/target/debug/build/clang-sys-da71b0344e568175/out/macros.rs +49 -0
  49. data/ext/itsi_rb_helpers/target/debug/build/rb-sys-eb9ed4ff3a60f995/out/bindings-0.9.110-mri-arm64-darwin23-3.4.2.rs +8865 -0
  50. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-040pxg6yhb3g3/s-h5113n7a1b-03bwlt4.lock +0 -0
  51. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-131g1u4dzkt1a/s-h51113xnh3-1eik1ip.lock +0 -0
  52. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-131g1u4dzkt1a/s-h5111704jj-0g4rj8x.lock +0 -0
  53. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-1q2d3drtxrzs5/s-h5113n79yl-0bxcqc5.lock +0 -0
  54. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-374a9h7ovycj0/s-h51113xoox-10de2hp.lock +0 -0
  55. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-374a9h7ovycj0/s-h5111704w7-0vdq7gq.lock +0 -0
  56. data/ext/itsi_scheduler/Cargo.toml +1 -1
  57. data/ext/itsi_scheduler/src/itsi_scheduler.rs +9 -3
  58. data/ext/itsi_scheduler/src/lib.rs +1 -0
  59. data/ext/itsi_server/Cargo.lock +2956 -0
  60. data/ext/itsi_server/Cargo.toml +73 -29
  61. data/ext/itsi_server/src/default_responses/mod.rs +11 -0
  62. data/ext/itsi_server/src/env.rs +43 -0
  63. data/ext/itsi_server/src/lib.rs +114 -75
  64. data/ext/itsi_server/src/prelude.rs +2 -0
  65. data/ext/itsi_server/src/{body_proxy → ruby_types/itsi_body_proxy}/big_bytes.rs +10 -5
  66. data/ext/itsi_server/src/{body_proxy/itsi_body_proxy.rs → ruby_types/itsi_body_proxy/mod.rs} +29 -8
  67. data/ext/itsi_server/src/ruby_types/itsi_grpc_call.rs +344 -0
  68. data/ext/itsi_server/src/ruby_types/itsi_grpc_response_stream/mod.rs +264 -0
  69. data/ext/itsi_server/src/ruby_types/itsi_http_request.rs +362 -0
  70. data/ext/itsi_server/src/{response/itsi_response.rs → ruby_types/itsi_http_response.rs} +84 -40
  71. data/ext/itsi_server/src/ruby_types/itsi_server/file_watcher.rs +233 -0
  72. data/ext/itsi_server/src/ruby_types/itsi_server/itsi_server_config.rs +565 -0
  73. data/ext/itsi_server/src/ruby_types/itsi_server.rs +86 -0
  74. data/ext/itsi_server/src/ruby_types/mod.rs +48 -0
  75. data/ext/itsi_server/src/server/{bind.rs → binds/bind.rs} +59 -24
  76. data/ext/itsi_server/src/server/binds/listener.rs +444 -0
  77. data/ext/itsi_server/src/server/binds/mod.rs +4 -0
  78. data/ext/itsi_server/src/server/{tls → binds/tls}/locked_dir_cache.rs +57 -19
  79. data/ext/itsi_server/src/server/{tls.rs → binds/tls.rs} +120 -31
  80. data/ext/itsi_server/src/server/byte_frame.rs +32 -0
  81. data/ext/itsi_server/src/server/http_message_types.rs +97 -0
  82. data/ext/itsi_server/src/server/io_stream.rs +2 -1
  83. data/ext/itsi_server/src/server/lifecycle_event.rs +3 -0
  84. data/ext/itsi_server/src/server/middleware_stack/middleware.rs +170 -0
  85. data/ext/itsi_server/src/server/middleware_stack/middlewares/allow_list.rs +63 -0
  86. data/ext/itsi_server/src/server/middleware_stack/middlewares/auth_api_key.rs +94 -0
  87. data/ext/itsi_server/src/server/middleware_stack/middlewares/auth_basic.rs +94 -0
  88. data/ext/itsi_server/src/server/middleware_stack/middlewares/auth_jwt.rs +343 -0
  89. data/ext/itsi_server/src/server/middleware_stack/middlewares/cache_control.rs +151 -0
  90. data/ext/itsi_server/src/server/middleware_stack/middlewares/compression.rs +316 -0
  91. data/ext/itsi_server/src/server/middleware_stack/middlewares/cors.rs +301 -0
  92. data/ext/itsi_server/src/server/middleware_stack/middlewares/csp.rs +193 -0
  93. data/ext/itsi_server/src/server/middleware_stack/middlewares/deny_list.rs +64 -0
  94. data/ext/itsi_server/src/server/middleware_stack/middlewares/error_response/default_responses.rs +192 -0
  95. data/ext/itsi_server/src/server/middleware_stack/middlewares/error_response.rs +171 -0
  96. data/ext/itsi_server/src/server/middleware_stack/middlewares/etag.rs +198 -0
  97. data/ext/itsi_server/src/server/middleware_stack/middlewares/header_interpretation.rs +82 -0
  98. data/ext/itsi_server/src/server/middleware_stack/middlewares/intrusion_protection.rs +209 -0
  99. data/ext/itsi_server/src/server/middleware_stack/middlewares/log_requests.rs +82 -0
  100. data/ext/itsi_server/src/server/middleware_stack/middlewares/max_body.rs +47 -0
  101. data/ext/itsi_server/src/server/middleware_stack/middlewares/mod.rs +116 -0
  102. data/ext/itsi_server/src/server/middleware_stack/middlewares/proxy.rs +411 -0
  103. data/ext/itsi_server/src/server/middleware_stack/middlewares/rate_limit.rs +142 -0
  104. data/ext/itsi_server/src/server/middleware_stack/middlewares/redirect.rs +55 -0
  105. data/ext/itsi_server/src/server/middleware_stack/middlewares/request_headers.rs +54 -0
  106. data/ext/itsi_server/src/server/middleware_stack/middlewares/response_headers.rs +51 -0
  107. data/ext/itsi_server/src/server/middleware_stack/middlewares/ruby_app.rs +126 -0
  108. data/ext/itsi_server/src/server/middleware_stack/middlewares/static_assets.rs +187 -0
  109. data/ext/itsi_server/src/server/middleware_stack/middlewares/static_response.rs +55 -0
  110. data/ext/itsi_server/src/server/middleware_stack/middlewares/string_rewrite.rs +173 -0
  111. data/ext/itsi_server/src/server/middleware_stack/middlewares/token_source.rs +31 -0
  112. data/ext/itsi_server/src/server/middleware_stack/mod.rs +381 -0
  113. data/ext/itsi_server/src/server/mod.rs +7 -5
  114. data/ext/itsi_server/src/server/process_worker.rs +65 -14
  115. data/ext/itsi_server/src/server/redirect_type.rs +26 -0
  116. data/ext/itsi_server/src/server/request_job.rs +11 -0
  117. data/ext/itsi_server/src/server/serve_strategy/cluster_mode.rs +150 -50
  118. data/ext/itsi_server/src/server/serve_strategy/mod.rs +9 -6
  119. data/ext/itsi_server/src/server/serve_strategy/single_mode.rs +399 -165
  120. data/ext/itsi_server/src/server/signal.rs +33 -26
  121. data/ext/itsi_server/src/server/size_limited_incoming.rs +107 -0
  122. data/ext/itsi_server/src/server/thread_worker.rs +218 -107
  123. data/ext/itsi_server/src/services/cache_store.rs +74 -0
  124. data/ext/itsi_server/src/services/itsi_http_service.rs +257 -0
  125. data/ext/itsi_server/src/services/mime_types.rs +1416 -0
  126. data/ext/itsi_server/src/services/mod.rs +6 -0
  127. data/ext/itsi_server/src/services/password_hasher.rs +83 -0
  128. data/ext/itsi_server/src/services/rate_limiter.rs +580 -0
  129. data/ext/itsi_server/src/services/static_file_server.rs +1340 -0
  130. data/ext/itsi_tracing/Cargo.toml +1 -0
  131. data/ext/itsi_tracing/src/lib.rs +362 -33
  132. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-0994n8rpvvt9m/s-h510hfz1f6-1kbycmq.lock +0 -0
  133. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-0bob7bf4yq34i/s-h5113125h5-0lh4rag.lock +0 -0
  134. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-2fcodulrxbbxo/s-h510h2infk-0hp5kjw.lock +0 -0
  135. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-2iak63r1woi1l/s-h510h2in4q-0kxfzw1.lock +0 -0
  136. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-2kk4qj9gn5dg2/s-h5113124kv-0enwon2.lock +0 -0
  137. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-2mwo0yas7dtw4/s-h510hfz1ha-1udgpei.lock +0 -0
  138. data/itsi-scheduler-100.png +0 -0
  139. data/lib/itsi/scheduler/version.rb +1 -1
  140. data/lib/itsi/scheduler.rb +11 -6
  141. metadata +117 -24
  142. data/CHANGELOG.md +0 -5
  143. data/CODE_OF_CONDUCT.md +0 -132
  144. data/LICENSE.txt +0 -21
  145. data/ext/itsi_error/src/from.rs +0 -71
  146. data/ext/itsi_server/extconf.rb +0 -6
  147. data/ext/itsi_server/src/body_proxy/mod.rs +0 -2
  148. data/ext/itsi_server/src/request/itsi_request.rs +0 -277
  149. data/ext/itsi_server/src/request/mod.rs +0 -1
  150. data/ext/itsi_server/src/response/mod.rs +0 -1
  151. data/ext/itsi_server/src/server/itsi_ca/itsi_ca.crt +0 -13
  152. data/ext/itsi_server/src/server/itsi_ca/itsi_ca.key +0 -5
  153. data/ext/itsi_server/src/server/itsi_server.rs +0 -244
  154. data/ext/itsi_server/src/server/listener.rs +0 -327
  155. /data/ext/itsi_server/src/server/{bind_protocol.rs → binds/bind_protocol.rs} +0 -0
@@ -0,0 +1,172 @@
1
+ use crate::acme::{
2
+ ExternalAccountKey, LETS_ENCRYPT_PRODUCTION_DIRECTORY, LETS_ENCRYPT_STAGING_DIRECTORY,
3
+ };
4
+ use crate::caches::{BoxedErrCache, CompositeCache, NoCache};
5
+ use crate::{AccountCache, Cache, CertCache};
6
+ use crate::{AcmeState, Incoming};
7
+ use futures::Stream;
8
+ use rustls::{ClientConfig, RootCertStore};
9
+ use std::convert::Infallible;
10
+ use std::fmt::Debug;
11
+ use std::sync::Arc;
12
+ use tokio::io::{AsyncRead, AsyncWrite};
13
+ use webpki_roots::TLS_SERVER_ROOTS;
14
+
15
+ /// Configuration for an ACME resolver.
16
+ ///
17
+ /// The type parameters represent the error types for the certificate cache and account cache.
18
+ pub struct AcmeConfig<EC: Debug, EA: Debug = EC> {
19
+ pub(crate) client_config: Arc<ClientConfig>,
20
+ pub(crate) directory_url: String,
21
+ pub(crate) domains: Vec<String>,
22
+ pub(crate) contact: Vec<String>,
23
+ pub(crate) cache: Box<dyn Cache<EC = EC, EA = EA>>,
24
+ pub(crate) eab: Option<ExternalAccountKey>,
25
+ }
26
+
27
+ impl AcmeConfig<Infallible, Infallible> {
28
+ /// Creates a new [AcmeConfig] instance.
29
+ ///
30
+ /// The new [AcmeConfig] instance will initially have no cache, and its type parameters for
31
+ /// error types will be `Infallible` since the cache cannot return an error. The methods to set
32
+ /// a cache will change the error types to match those returned by the supplied cache.
33
+ ///
34
+ /// ```rust
35
+ /// # use tokio_rustls_acme::AcmeConfig;
36
+ /// use tokio_rustls_acme::caches::DirCache;
37
+ /// let config = AcmeConfig::new(["example.com"]).cache(DirCache::new("./rustls_acme_cache"));
38
+ /// ```
39
+ ///
40
+ /// Due to limited support for type parameter inference in Rust (see
41
+ /// [RFC213](https://github.com/rust-lang/rfcs/blob/master/text/0213-defaulted-type-params.md)),
42
+ /// [AcmeConfig::new] is not (yet) generic over the [AcmeConfig]'s type parameters.
43
+ /// An uncached instance of [AcmeConfig] with particular type parameters can be created using
44
+ /// [NoCache].
45
+ ///
46
+ /// ```rust
47
+ /// # use tokio_rustls_acme::AcmeConfig;
48
+ /// use tokio_rustls_acme::caches::NoCache;
49
+ /// # type EC = std::io::Error;
50
+ /// # type EA = EC;
51
+ /// let config: AcmeConfig<EC, EA> = AcmeConfig::new(["example.com"]).cache(NoCache::new());
52
+ /// ```
53
+ ///
54
+ pub fn new(domains: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
55
+ let mut root_store = RootCertStore::empty();
56
+ root_store.extend(
57
+ TLS_SERVER_ROOTS
58
+ .iter()
59
+ .map(|ta| rustls::pki_types::TrustAnchor {
60
+ subject: ta.subject.clone(),
61
+ subject_public_key_info: ta.subject_public_key_info.clone(),
62
+ name_constraints: ta.name_constraints.clone(),
63
+ }),
64
+ );
65
+ let client_config = Arc::new(
66
+ ClientConfig::builder()
67
+ .with_root_certificates(root_store)
68
+ .with_no_client_auth(),
69
+ );
70
+ AcmeConfig {
71
+ client_config,
72
+ directory_url: LETS_ENCRYPT_STAGING_DIRECTORY.into(),
73
+ domains: domains.into_iter().map(|s| s.as_ref().into()).collect(),
74
+ contact: vec![],
75
+ cache: Box::new(NoCache::new()),
76
+ eab: None,
77
+ }
78
+ }
79
+ }
80
+
81
+ impl<EC: 'static + Debug, EA: 'static + Debug> AcmeConfig<EC, EA> {
82
+ /// Set custom `rustls::ClientConfig` for ACME API calls.
83
+ pub fn client_tls_config(mut self, client_config: Arc<ClientConfig>) -> Self {
84
+ self.client_config = client_config;
85
+ self
86
+ }
87
+ pub fn directory(mut self, directory_url: impl AsRef<str>) -> Self {
88
+ self.directory_url = directory_url.as_ref().into();
89
+ self
90
+ }
91
+ pub fn directory_lets_encrypt(mut self, production: bool) -> Self {
92
+ self.directory_url = match production {
93
+ true => LETS_ENCRYPT_PRODUCTION_DIRECTORY,
94
+ false => LETS_ENCRYPT_STAGING_DIRECTORY,
95
+ }
96
+ .into();
97
+ self
98
+ }
99
+ pub fn domains(mut self, contact: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
100
+ self.domains = contact.into_iter().map(|s| s.as_ref().into()).collect();
101
+ self
102
+ }
103
+ pub fn domains_push(mut self, contact: impl AsRef<str>) -> Self {
104
+ self.domains.push(contact.as_ref().into());
105
+ self
106
+ }
107
+
108
+ pub fn external_account_binding(mut self, kid: impl AsRef<str>, key: impl AsRef<[u8]>) -> Self {
109
+ self.eab = Some(ExternalAccountKey::new(kid.as_ref().into(), key.as_ref()));
110
+ self
111
+ }
112
+
113
+ /// Provide a list of contacts for the account.
114
+ ///
115
+ /// Note that email addresses must include a `mailto:` prefix.
116
+ pub fn contact(mut self, contact: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
117
+ self.contact = contact.into_iter().map(|s| s.as_ref().into()).collect();
118
+ self
119
+ }
120
+
121
+ /// Provide a contact for the account.
122
+ ///
123
+ /// Note that an email address must include a `mailto:` prefix.
124
+ pub fn contact_push(mut self, contact: impl AsRef<str>) -> Self {
125
+ self.contact.push(contact.as_ref().into());
126
+ self
127
+ }
128
+
129
+ pub fn cache<C: 'static + Cache>(self, cache: C) -> AcmeConfig<C::EC, C::EA> {
130
+ AcmeConfig {
131
+ client_config: self.client_config,
132
+ directory_url: self.directory_url,
133
+ domains: self.domains,
134
+ contact: self.contact,
135
+ cache: Box::new(cache),
136
+ eab: self.eab,
137
+ }
138
+ }
139
+ pub fn cache_compose<CC: 'static + CertCache, CA: 'static + AccountCache>(
140
+ self,
141
+ cert_cache: CC,
142
+ account_cache: CA,
143
+ ) -> AcmeConfig<CC::EC, CA::EA> {
144
+ self.cache(CompositeCache::new(cert_cache, account_cache))
145
+ }
146
+ pub fn cache_with_boxed_err<C: 'static + Cache>(self, cache: C) -> AcmeConfig<Box<dyn Debug>> {
147
+ self.cache(BoxedErrCache::new(cache))
148
+ }
149
+ pub fn cache_option<C: 'static + Cache>(self, cache: Option<C>) -> AcmeConfig<C::EC, C::EA> {
150
+ match cache {
151
+ Some(cache) => self.cache(cache),
152
+ None => self.cache(NoCache::<C::EC, C::EA>::new()),
153
+ }
154
+ }
155
+ pub fn state(self) -> AcmeState<EC, EA> {
156
+ AcmeState::new(self)
157
+ }
158
+ /// Turn a stream of TCP connections into a stream of TLS connections.
159
+ ///
160
+ /// Specify supported protocol names in `alpn_protocols`, most preferred first. If emtpy (`Vec::new()`), we don't do ALPN.
161
+ pub fn incoming<
162
+ TCP: AsyncRead + AsyncWrite + Unpin,
163
+ ETCP,
164
+ ITCP: Stream<Item = Result<TCP, ETCP>> + Unpin,
165
+ >(
166
+ self,
167
+ tcp_incoming: ITCP,
168
+ alpn_protocols: Vec<Vec<u8>>,
169
+ ) -> Incoming<TCP, ETCP, ITCP, EC, EA> {
170
+ self.state().incoming(tcp_incoming, alpn_protocols)
171
+ }
172
+ }
@@ -0,0 +1,69 @@
1
+ use rustls::{pki_types::InvalidDnsNameError, ClientConfig};
2
+ use thiserror::Error;
3
+
4
+ pub use reqwest::Response;
5
+
6
+ #[derive(Copy, Clone)]
7
+ pub enum Method {
8
+ Post,
9
+ Get,
10
+ Head,
11
+ }
12
+
13
+ impl From<Method> for reqwest::Method {
14
+ fn from(m: Method) -> Self {
15
+ match m {
16
+ Method::Post => reqwest::Method::POST,
17
+ Method::Get => reqwest::Method::GET,
18
+ Method::Head => reqwest::Method::HEAD,
19
+ }
20
+ }
21
+ }
22
+
23
+ pub(crate) async fn https(
24
+ client_config: &ClientConfig,
25
+ url: impl AsRef<str>,
26
+ method: Method,
27
+ body: Option<String>,
28
+ ) -> Result<Response, HttpsRequestError> {
29
+ let method: reqwest::Method = method.into();
30
+ let client = reqwest::ClientBuilder::new()
31
+ .use_preconfigured_tls(client_config.clone())
32
+ .build()?;
33
+ let mut request = client.request(method, url.as_ref());
34
+ if let Some(body) = body {
35
+ request = request
36
+ .body(body)
37
+ .header("Content-Type", "application/jose+json");
38
+ }
39
+
40
+ let response = request.send().await?;
41
+ let status = response.status();
42
+ if !status.is_success() {
43
+ return Err(HttpsRequestError::Non2xxStatus {
44
+ status_code: status.into(),
45
+ body: response.text().await?,
46
+ });
47
+ }
48
+ Ok(response)
49
+ }
50
+
51
+ impl From<reqwest::Error> for HttpsRequestError {
52
+ fn from(e: reqwest::Error) -> Self {
53
+ Self::Http(e.into())
54
+ }
55
+ }
56
+
57
+ #[derive(Error, Debug)]
58
+ pub enum HttpsRequestError {
59
+ #[error("io error: {0:?}")]
60
+ Io(#[from] std::io::Error),
61
+ #[error("invalid dns name: {0:?}")]
62
+ InvalidDnsName(#[from] InvalidDnsNameError),
63
+ #[error("http error: {0:?}")]
64
+ Http(Box<dyn std::error::Error + Send + Sync + 'static>),
65
+ #[error("non 2xx http status: {status_code} {body:?}")]
66
+ Non2xxStatus { status_code: u16, body: String },
67
+ #[error("could not determine host from url")]
68
+ UndefinedHost,
69
+ }
@@ -0,0 +1,142 @@
1
+ use crate::acceptor::{AcmeAccept, AcmeAcceptor};
2
+ use crate::AcmeState;
3
+ use futures::stream::{FusedStream, FuturesUnordered};
4
+ use futures::Stream;
5
+ use rustls::ServerConfig;
6
+ use std::fmt::Debug;
7
+ use std::pin::Pin;
8
+ use std::sync::Arc;
9
+ use std::task::{Context, Poll};
10
+ use tokio::io::{AsyncRead, AsyncWrite};
11
+ use tokio_rustls::{server::TlsStream, Accept};
12
+
13
+ pub struct Incoming<
14
+ TCP: AsyncRead + AsyncWrite + Unpin,
15
+ ETCP,
16
+ ITCP: Stream<Item = Result<TCP, ETCP>> + Unpin,
17
+ EC: Debug + 'static,
18
+ EA: Debug + 'static,
19
+ > {
20
+ state: AcmeState<EC, EA>,
21
+ acceptor: AcmeAcceptor,
22
+ rustls_config: Arc<ServerConfig>,
23
+ tcp_incoming: Option<ITCP>,
24
+ acme_accepting: FuturesUnordered<AcmeAccept<TCP>>,
25
+ tls_accepting: FuturesUnordered<Accept<TCP>>,
26
+ }
27
+
28
+ impl<
29
+ TCP: AsyncRead + AsyncWrite + Unpin,
30
+ ETCP,
31
+ ITCP: Stream<Item = Result<TCP, ETCP>> + Unpin,
32
+ EC: Debug + 'static,
33
+ EA: Debug + 'static,
34
+ > Unpin for Incoming<TCP, ETCP, ITCP, EC, EA>
35
+ {
36
+ }
37
+
38
+ impl<
39
+ TCP: AsyncRead + AsyncWrite + Unpin,
40
+ ETCP,
41
+ ITCP: Stream<Item = Result<TCP, ETCP>> + Unpin,
42
+ EC: Debug + 'static,
43
+ EA: Debug + 'static,
44
+ > Incoming<TCP, ETCP, ITCP, EC, EA>
45
+ {
46
+ pub fn new(
47
+ tcp_incoming: ITCP,
48
+ state: AcmeState<EC, EA>,
49
+ acceptor: AcmeAcceptor,
50
+ alpn_protocols: Vec<Vec<u8>>,
51
+ ) -> Self {
52
+ let mut config = ServerConfig::builder()
53
+ .with_no_client_auth()
54
+ .with_cert_resolver(state.resolver());
55
+ config.alpn_protocols = alpn_protocols;
56
+ Self {
57
+ state,
58
+ acceptor,
59
+ rustls_config: Arc::new(config),
60
+ tcp_incoming: Some(tcp_incoming),
61
+ acme_accepting: FuturesUnordered::new(),
62
+ tls_accepting: FuturesUnordered::new(),
63
+ }
64
+ }
65
+ }
66
+
67
+ impl<
68
+ TCP: AsyncRead + AsyncWrite + Unpin,
69
+ ETCP,
70
+ ITCP: Stream<Item = Result<TCP, ETCP>> + Unpin,
71
+ EC: Debug + 'static,
72
+ EA: Debug + 'static,
73
+ > Stream for Incoming<TCP, ETCP, ITCP, EC, EA>
74
+ {
75
+ type Item = Result<TlsStream<TCP>, ETCP>;
76
+
77
+ fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
78
+ loop {
79
+ match Pin::new(&mut self.state).poll_next(cx) {
80
+ Poll::Ready(Some(event)) => {
81
+ match event {
82
+ Ok(ok) => log::info!("event: {:?}", ok),
83
+ Err(err) => log::error!("event: {:?}", err),
84
+ }
85
+ continue;
86
+ }
87
+ Poll::Ready(None) => unreachable!(),
88
+ Poll::Pending => {}
89
+ }
90
+ match Pin::new(&mut self.acme_accepting).poll_next(cx) {
91
+ Poll::Ready(Some(Ok(Some(tls)))) => self
92
+ .tls_accepting
93
+ .push(tls.into_stream(self.rustls_config.clone())),
94
+ Poll::Ready(Some(Ok(None))) => {
95
+ log::info!("received TLS-ALPN-01 validation request");
96
+ continue;
97
+ }
98
+ Poll::Ready(Some(Err(err))) => {
99
+ log::error!("tls accept failed, {:?}", err);
100
+ continue;
101
+ }
102
+ Poll::Ready(None) | Poll::Pending => {}
103
+ }
104
+ match Pin::new(&mut self.tls_accepting).poll_next(cx) {
105
+ Poll::Ready(Some(Ok(tls))) => return Poll::Ready(Some(Ok(tls))),
106
+ Poll::Ready(Some(Err(err))) => {
107
+ log::error!("tls accept failed, {:?}", err);
108
+ continue;
109
+ }
110
+ Poll::Ready(None) | Poll::Pending => {}
111
+ }
112
+ let tcp_incoming = match &mut self.tcp_incoming {
113
+ Some(tcp_incoming) => tcp_incoming,
114
+ None => match self.is_terminated() {
115
+ true => return Poll::Ready(None),
116
+ false => return Poll::Pending,
117
+ },
118
+ };
119
+ match Pin::new(tcp_incoming).poll_next(cx) {
120
+ Poll::Ready(Some(Ok(tcp))) => self.acme_accepting.push(self.acceptor.accept(tcp)),
121
+ Poll::Ready(Some(Err(err))) => return Poll::Ready(Some(Err(err))),
122
+ Poll::Ready(None) => drop(self.tcp_incoming.as_mut()),
123
+ Poll::Pending => return Poll::Pending,
124
+ }
125
+ }
126
+ }
127
+ }
128
+
129
+ impl<
130
+ TCP: AsyncRead + AsyncWrite + Unpin,
131
+ ETCP,
132
+ ITCP: Stream<Item = Result<TCP, ETCP>> + Unpin,
133
+ EC: Debug + 'static,
134
+ EA: Debug + 'static,
135
+ > FusedStream for Incoming<TCP, ETCP, ITCP, EC, EA>
136
+ {
137
+ fn is_terminated(&self) -> bool {
138
+ self.tcp_incoming.is_none()
139
+ && self.acme_accepting.is_terminated()
140
+ && self.tls_accepting.is_terminated()
141
+ }
142
+ }
@@ -0,0 +1,161 @@
1
+ use base64::engine::general_purpose::URL_SAFE_NO_PAD;
2
+ use base64::Engine;
3
+ use ring::digest::{digest, Digest, SHA256};
4
+ use ring::rand::SystemRandom;
5
+ use ring::signature::{EcdsaKeyPair, KeyPair};
6
+ use serde::Serialize;
7
+ use thiserror::Error;
8
+
9
+ pub(crate) fn sign(
10
+ key: &EcdsaKeyPair,
11
+ kid: Option<&str>,
12
+ nonce: String,
13
+ url: &str,
14
+ payload: &str,
15
+ ) -> Result<String, JoseError> {
16
+ let jwk = match kid {
17
+ None => Some(Jwk::new(key)),
18
+ Some(_) => None,
19
+ };
20
+ let protected = Protected::base64(jwk, kid, Some(nonce.as_ref()), url)?;
21
+ let payload = URL_SAFE_NO_PAD.encode(payload);
22
+ let combined = format!("{}.{}", &protected, &payload);
23
+ let signature = key.sign(&SystemRandom::new(), combined.as_bytes())?;
24
+ let signature = URL_SAFE_NO_PAD.encode(signature.as_ref());
25
+ let body = Body {
26
+ protected,
27
+ payload,
28
+ signature,
29
+ };
30
+ Ok(serde_json::to_string(&body)?)
31
+ }
32
+
33
+ pub(crate) fn sign_eab(
34
+ key: &EcdsaKeyPair,
35
+ eab_key: &ring::hmac::Key,
36
+ kid: &str,
37
+ url: &str,
38
+ ) -> Result<Body, JoseError> {
39
+ let protected = Protected::hmac_base64(kid, url)?;
40
+ let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&Jwk::new(key))?);
41
+ let combined = format!("{}.{}", &protected, &payload);
42
+ let signature = ring::hmac::sign(eab_key, combined.as_bytes());
43
+ let signature = URL_SAFE_NO_PAD.encode(signature.as_ref());
44
+ let body = Body {
45
+ protected,
46
+ payload,
47
+ signature,
48
+ };
49
+ Ok(body)
50
+ }
51
+
52
+ pub(crate) fn key_authorization_sha256(
53
+ key: &EcdsaKeyPair,
54
+ token: &str,
55
+ ) -> Result<Digest, JoseError> {
56
+ let jwk = Jwk::new(key);
57
+ let key_authorization = format!("{}.{}", token, jwk.thumb_sha256_base64()?);
58
+ Ok(digest(&SHA256, key_authorization.as_bytes()))
59
+ }
60
+
61
+ #[derive(Serialize)]
62
+ pub(crate) struct Body {
63
+ protected: String,
64
+ payload: String,
65
+ signature: String,
66
+ }
67
+
68
+ #[derive(Serialize)]
69
+ struct Protected<'a> {
70
+ alg: &'static str,
71
+ #[serde(skip_serializing_if = "Option::is_none")]
72
+ jwk: Option<Jwk>,
73
+ #[serde(skip_serializing_if = "Option::is_none")]
74
+ kid: Option<&'a str>,
75
+ #[serde(skip_serializing_if = "Option::is_none")]
76
+ nonce: Option<&'a str>,
77
+ url: &'a str,
78
+ }
79
+
80
+ impl<'a> Protected<'a> {
81
+ fn base64(
82
+ jwk: Option<Jwk>,
83
+ kid: Option<&'a str>,
84
+ nonce: Option<&'a str>,
85
+ url: &'a str,
86
+ ) -> Result<String, JoseError> {
87
+ let protected = Self {
88
+ alg: "ES256",
89
+ jwk,
90
+ kid,
91
+ nonce,
92
+ url,
93
+ };
94
+ let protected = serde_json::to_vec(&protected)?;
95
+ Ok(URL_SAFE_NO_PAD.encode(protected))
96
+ }
97
+
98
+ fn hmac_base64(kid: &'a str, url: &'a str) -> Result<String, JoseError> {
99
+ let protected = Self {
100
+ alg: "HS256",
101
+ jwk: None,
102
+ kid: Some(kid),
103
+ nonce: None,
104
+ url,
105
+ };
106
+ let protected = serde_json::to_vec(&protected)?;
107
+ Ok(URL_SAFE_NO_PAD.encode(protected))
108
+ }
109
+ }
110
+
111
+ #[derive(Serialize)]
112
+ struct Jwk {
113
+ alg: &'static str,
114
+ crv: &'static str,
115
+ kty: &'static str,
116
+ #[serde(rename = "use")]
117
+ u: &'static str,
118
+ x: String,
119
+ y: String,
120
+ }
121
+
122
+ impl Jwk {
123
+ pub(crate) fn new(key: &EcdsaKeyPair) -> Self {
124
+ let (x, y) = key.public_key().as_ref()[1..].split_at(32);
125
+ Self {
126
+ alg: "ES256",
127
+ crv: "P-256",
128
+ kty: "EC",
129
+ u: "sig",
130
+ x: URL_SAFE_NO_PAD.encode(x),
131
+ y: URL_SAFE_NO_PAD.encode(y),
132
+ }
133
+ }
134
+ pub(crate) fn thumb_sha256_base64(&self) -> Result<String, JoseError> {
135
+ let jwk_thumb = JwkThumb {
136
+ crv: self.crv,
137
+ kty: self.kty,
138
+ x: &self.x,
139
+ y: &self.y,
140
+ };
141
+ let json = serde_json::to_vec(&jwk_thumb)?;
142
+ let hash = digest(&SHA256, &json);
143
+ Ok(URL_SAFE_NO_PAD.encode(hash))
144
+ }
145
+ }
146
+
147
+ #[derive(Serialize)]
148
+ struct JwkThumb<'a> {
149
+ crv: &'a str,
150
+ kty: &'a str,
151
+ x: &'a str,
152
+ y: &'a str,
153
+ }
154
+
155
+ #[derive(Error, Debug)]
156
+ pub enum JoseError {
157
+ #[error("json serialization failed: {0}")]
158
+ Json(#[from] serde_json::Error),
159
+ #[error("crypto error: {0}")]
160
+ Crypto(#[from] ring::error::Unspecified),
161
+ }
@@ -0,0 +1,142 @@
1
+ //! An easy-to-use, async compatible [ACME] client library using [rustls] with [ring].
2
+ //! The validation mechanism used is tls-alpn-01, which allows serving acme challenge responses and
3
+ //! regular TLS traffic on the same port.
4
+ //!
5
+ //! Is designed to use the tokio runtime, if you need support for other runtimes take a look
6
+ //! at the original implementation [rustls-acme](https://github.com/FlorianUekermann/rustls-acme).
7
+ //!
8
+ //! No persistent tasks are spawned under the hood and the certificate acquisition/renewal process
9
+ //! is folded into the streams and futures being polled by the library user.
10
+ //!
11
+ //! The goal is to provide a [Let's Encrypt](https://letsencrypt.org/) compatible TLS serving and
12
+ //! certificate management using a simple and flexible stream based API.
13
+ //!
14
+ //! This crate uses [ring] as [rustls]'s backend, instead of [aws-lc-rs]. This generally makes it
15
+ //! much easier to compile. If you'd like to use [aws-lc-rs] as [rustls]'s backend, we're open to
16
+ //! contributions with the necessary `Cargo.toml` changes and feature-flags to enable you to do so.
17
+ //!
18
+ //! To use tokio-rustls-acme add the following lines to your `Cargo.toml`:
19
+ //!
20
+ //! ```toml
21
+ //! [dependencies]
22
+ //! tokio-rustls-acme = "*"
23
+ //! ```
24
+ //!
25
+ //! ## High-level API
26
+ //!
27
+ //! The high-level API consists of a single stream [Incoming] of incoming TLS connection.
28
+ //! Polling the next future of the stream takes care of acquisition and renewal of certificates, as
29
+ //! well as accepting TLS connections, which are handed over to the caller on success.
30
+ //!
31
+ //! ```rust,no_run
32
+ //! use tokio::io::AsyncWriteExt;
33
+ //! use futures::StreamExt;
34
+ //! use tokio_rustls_acme::{AcmeConfig, caches::DirCache};
35
+ //! use tokio_stream::wrappers::TcpListenerStream;
36
+ //!
37
+ //! #[tokio::main]
38
+ //! async fn main() {
39
+ //! simple_logger::init_with_level(log::Level::Info).unwrap();
40
+ //!
41
+ //! let tcp_listener = tokio::net::TcpListener::bind("[::]:443").await.unwrap();
42
+ //! let tcp_incoming = TcpListenerStream::new(tcp_listener);
43
+ //!
44
+ //! let mut tls_incoming = AcmeConfig::new(["example.com"])
45
+ //! .contact_push("mailto:admin@example.com")
46
+ //! .cache(DirCache::new("./rustls_acme_cache"))
47
+ //! .incoming(tcp_incoming, Vec::new());
48
+ //!
49
+ //! while let Some(tls) = tls_incoming.next().await {
50
+ //! let mut tls = tls.unwrap();
51
+ //! tokio::spawn(async move {
52
+ //! tls.write_all(HELLO).await.unwrap();
53
+ //! tls.shutdown().await.unwrap();
54
+ //! });
55
+ //! }
56
+ //! }
57
+ //!
58
+ //! const HELLO: &'static [u8] = br#"HTTP/1.1 200 OK
59
+ //! Content-Length: 11
60
+ //! Content-Type: text/plain; charset=utf-8
61
+ //!
62
+ //! Hello Tls!"#;
63
+ //! ```
64
+ //!
65
+ //! `examples/high_level.rs` implements a "Hello Tls!" server similar to the one above, which accepts
66
+ //! domain, port and cache directory parameters.
67
+ //!
68
+ //! Note that all examples use the let's encrypt staging directory by default.
69
+ //! The production directory imposes strict rate limits, which are easily exhausted accidentally
70
+ //! during testing and development.
71
+ //! For testing with the staging directory you may open `https://<your domain>:<port>` in a browser
72
+ //! that allows TLS connections to servers signed by an untrusted CA (in Firefox click "Advanced..."
73
+ //! -> "Accept the Risk and Continue").
74
+ //!
75
+ //! ## Low-level Rustls API
76
+ //!
77
+ //! For users who may want to interact with [rustls] or [tokio_rustls]
78
+ //! directly, the library exposes the underlying certificate management [AcmeState] as well as a
79
+ //! matching resolver [ResolvesServerCertAcme] which implements the [rustls::server::ResolvesServerCert] trait.
80
+ //! See the server_low_level example on how to use the low-level API directly with [tokio_rustls].
81
+ //!
82
+ //! ## Account and certificate caching
83
+ //!
84
+ //! A production server using the let's encrypt production directory must implement both account and
85
+ //! certificate caching to avoid exhausting the let's encrypt API rate limits.
86
+ //! A file based cache using a cache directory is provided by [caches::DirCache].
87
+ //! Caches backed by other persistence layers may be implemented using the [Cache] trait,
88
+ //! or the underlying [CertCache], [AccountCache] traits (contributions welcome).
89
+ //! [caches::CompositeCache] provides a wrapper to combine two implementors of [CertCache] and
90
+ //! [AccountCache] into a single [Cache].
91
+ //!
92
+ //! Note, that the error type parameters of the cache carries over to some other types in this
93
+ //! crate via the [AcmeConfig] they are added to.
94
+ //! If you want to avoid different specializations based on cache type use the
95
+ //! [AcmeConfig::cache_with_boxed_err] method to construct the an [AcmeConfig] object.
96
+ //!
97
+ //!
98
+ //! ## The acme module
99
+ //!
100
+ //! The underlying implementation of an async acme client may be useful to others and is exposed as
101
+ //! a module. It is incomplete (contributions welcome) and not covered by any stability
102
+ //! promises.
103
+ //!
104
+ //! ## Special thanks
105
+ //!
106
+ //! This crate was inspired by the [autocert](https://golang.org/x/crypto/acme/autocert/)
107
+ //! package for [Go](https://golang.org).
108
+ //!
109
+ //! The original implementation of this crate can be found at [FlorianUekermann/rustls-acme](https://github.com/FlorianUekermann/rustls-acme/commits/main), this is just a version focused on supporting only tokio.
110
+ //!
111
+ //! This crate also builds on the excellent work of the authors of
112
+ //! [rustls],
113
+ //! [tokio-rustls](https://github.com/tokio-rs/tls/tree/master/tokio-rustls) and many others.
114
+ //!
115
+ //! [ACME]: https://en.wikipedia.org/wiki/Automatic_Certificate_Management_Environment
116
+ //! [ring]: https://github.com/briansmith/ring
117
+ //! [rustls]: https://github.com/ctz/rustls
118
+ //! [aws-lc-rs]: https://github.com/aws/aws-lc-rs
119
+
120
+ #![cfg_attr(docsrs, feature(doc_auto_cfg))]
121
+
122
+ mod acceptor;
123
+ pub mod acme;
124
+ #[cfg(feature = "axum")]
125
+ pub mod axum;
126
+ mod cache;
127
+ pub mod caches;
128
+ mod config;
129
+ mod https_helper;
130
+ mod incoming;
131
+ mod jose;
132
+ mod resolver;
133
+ mod state;
134
+
135
+ pub use tokio_rustls;
136
+
137
+ pub use acceptor::*;
138
+ pub use cache::*;
139
+ pub use config::*;
140
+ pub use incoming::*;
141
+ pub use resolver::*;
142
+ pub use state::*;