proksi 0.10.0

A batteries-included reverse proxy with automatic HTTPS using Cloudflare Pingora and Let's Encrypt.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use serde::{Deserialize, Serialize};

use crate::config::{RouteCache, RouteHeader, RoutePlugin, RouteUpstream};

/// Requests of a host matching a path, and how they are handled
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Location {
    /// Path pattern (`/api`, `/users/:id`, `/*`)
    pub path: String,
    /// Match only the path itself instead of the path and everything below it.
    /// Set for routes converted from `routes = [...]`, which matched exactly.
    #[serde(default)]
    pub exact: bool,
    #[serde(default)]
    pub upstreams: Vec<RouteUpstream>,
    pub headers: Option<RouteHeader>,
    pub plugins: Option<Vec<RoutePlugin>>,
    pub cache: Option<RouteCache>,
    /// Timeouts of the location's requests, instead of `server.timeouts`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeouts: Option<LocationTimeouts>,
    /// How the path sent to upstreams is changed
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rewrite: Option<PathRewrite>,
}

/// `rewrite { ... }` in a location: the path sent to upstreams, instead of the request's
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PathRewrite {
    /// Removed from the start of the path (only at a segment boundary: `/api` from `/api/users`,
    /// not from `/apis`)
    pub strip_prefix: Option<String>,
    /// Added to the start of the path, after `strip_prefix`
    pub add_prefix: Option<String>,
    /// A regular expression the path is matched against, replaced by `replace`
    #[serde(rename = "match")]
    pub pattern: Option<String>,
    /// What a path matching `match` becomes (`$1`, `${name}` for its groups)
    pub replace: Option<String>,
}

/// Compiled patterns are limited, as they can come from a store anyone with access writes to
const PATTERN_SIZE_LIMIT: usize = 1 << 20;

impl PathRewrite {
    /// Checks the settings and compiles the pattern, once (when the location is built)
    pub fn compile(&self) -> Result<CompiledRewrite, String> {
        for (name, prefix) in [
            ("strip_prefix", &self.strip_prefix),
            ("add_prefix", &self.add_prefix),
        ] {
            if let Some(prefix) = prefix {
                if !prefix.starts_with('/') || prefix.contains(['?', '#']) {
                    return Err(format!(
                        "`{name}` must be a path starting with `/`, not {prefix:?}"
                    ));
                }
            }
        }
        let prefixes = self.strip_prefix.is_some() || self.add_prefix.is_some();
        let pattern = match (&self.pattern, &self.replace) {
            (None, None) if !prefixes => {
                return Err(
                    "`rewrite` needs `strip_prefix` or `add_prefix`, or `match` and `replace`"
                        .to_string(),
                );
            }
            (None, None) => None,
            (Some(_), None) | (None, Some(_)) => {
                return Err("`match` and `replace` go together".to_string());
            }
            (Some(_), Some(_)) if prefixes => {
                return Err(
                    "`match` and `replace` can't be combined with `strip_prefix` or `add_prefix`"
                        .to_string(),
                );
            }
            (Some(pattern), Some(_)) => Some(
                regex::RegexBuilder::new(pattern)
                    .size_limit(PATTERN_SIZE_LIMIT)
                    .build()
                    .map_err(|err| format!("invalid `match`: {err}"))?,
            ),
        };
        Ok(CompiledRewrite {
            settings: self.clone(),
            pattern,
        })
    }
}

/// A location's [`PathRewrite`], with its pattern compiled
#[derive(Debug, Clone)]
pub struct CompiledRewrite {
    settings: PathRewrite,
    pattern: Option<regex::Regex>,
}

impl CompiledRewrite {
    /// The path (and query) sent to upstreams for `path` and `query`
    pub fn apply(&self, path: &str, query: Option<&str>) -> String {
        let mut rewritten = match (&self.pattern, &self.settings.replace) {
            (Some(pattern), Some(replace)) => {
                let replaced = pattern.replace(path, replace.as_str());
                if replaced.starts_with('/') {
                    replaced.into_owned()
                } else {
                    format!("/{replaced}")
                }
            }
            _ => self.prefixes(path),
        };
        if let Some(query) = query {
            rewritten.push('?');
            rewritten.push_str(query);
        }
        rewritten
    }

    fn prefixes(&self, path: &str) -> String {
        let mut path = path;
        if let Some(prefix) = self
            .settings
            .strip_prefix
            .as_deref()
            .map(|p| p.trim_end_matches('/'))
        {
            if let Some(rest) = path.strip_prefix(prefix) {
                if rest.is_empty() || rest.starts_with('/') {
                    path = rest;
                }
            }
        }
        match self
            .settings
            .add_prefix
            .as_deref()
            .map(|p| p.trim_end_matches('/'))
        {
            Some(prefix) if path.is_empty() || path == "/" => {
                if prefix.is_empty() {
                    "/".to_string()
                } else {
                    prefix.to_string()
                }
            }
            Some(prefix) => format!("{prefix}{path}"),
            None if path.is_empty() => "/".to_string(),
            None => path.to_string(),
        }
    }
}

/// Timeouts of a location's requests (`timeouts { ... }` in a host or location), in seconds,
/// overriding the ones of `server.timeouts`
// Named like `server.timeouts`
#[allow(clippy::struct_field_names)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LocationTimeouts {
    /// How long each read of a request body (or websocket message) can wait
    pub read_secs: Option<u64>,
    /// How long each write of a response can wait for the client to read
    pub write_secs: Option<u64>,
    /// Toward the location's upstreams
    pub upstream: Option<UpstreamTimeouts>,
}

impl LocationTimeouts {
    /// These timeouts, with the ones they don't set taken from `defaults` (the host's)
    pub fn or(self, defaults: Option<Self>) -> Self {
        let defaults = defaults.unwrap_or_default();
        Self {
            read_secs: self.read_secs.or(defaults.read_secs),
            write_secs: self.write_secs.or(defaults.write_secs),
            upstream: match self.upstream {
                Some(upstream) => Some(upstream.or(defaults.upstream)),
                None => defaults.upstream,
            },
        }
    }
}

/// Timeouts toward upstreams (`upstream { ... }` in `timeouts`), in seconds
// Named like `server.timeouts`
#[allow(clippy::struct_field_names)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UpstreamTimeouts {
    /// How long to wait for an upstream to accept a connection
    pub connect_secs: Option<u64>,
    /// How long the TLS handshake with an HTTPS upstream can take, after connecting
    pub tls_secs: Option<u64>,
    /// How long each read of a response can wait, including for its headers
    pub read_secs: Option<u64>,
    /// How long each write of a request can wait for the upstream to read
    pub write_secs: Option<u64>,
    /// How long a connection is kept open between requests, to be reused
    pub idle_secs: Option<u64>,
}

impl UpstreamTimeouts {
    /// These timeouts, with the ones they don't set taken from `defaults`
    pub fn or(self, defaults: Option<Self>) -> Self {
        let defaults = defaults.unwrap_or_default();
        Self {
            connect_secs: self.connect_secs.or(defaults.connect_secs),
            tls_secs: self.tls_secs.or(defaults.tls_secs),
            read_secs: self.read_secs.or(defaults.read_secs),
            write_secs: self.write_secs.or(defaults.write_secs),
            idle_secs: self.idle_secs.or(defaults.idle_secs),
        }
    }
}

impl Location {
    /// Path patterns matched by this location: the path and everything below it
    /// (`/api` matches `/api`, `/api/` and `/api/users`, not `/apis`)
    pub fn patterns(&self) -> Vec<String> {
        if self.exact || self.path.ends_with(['*', '+']) {
            return vec![self.path.clone()];
        }
        let base = self.path.trim_end_matches('/');
        vec![self.path.clone(), format!("{base}/*")]
    }
}

#[cfg(test)]
mod tests {
    use super::Location;

    fn location(path: &str, exact: bool) -> Location {
        Location {
            path: path.to_string(),
            exact,
            upstreams: vec![],
            headers: None,
            plugins: None,
            cache: None,
            timeouts: None,
            rewrite: None,
        }
    }

    #[test]
    fn test_location_patterns_match_the_path_and_below() {
        assert_eq!(
            location("/v1/session", false).patterns(),
            vec!["/v1/session", "/v1/session/*"]
        );
        assert_eq!(location("/", false).patterns(), vec!["/", "/*"]);
        assert_eq!(location("/api/", false).patterns(), vec!["/api/", "/api/*"]);
    }

    #[test]
    fn test_location_patterns_with_wildcards_or_exact() {
        assert_eq!(location("/*", false).patterns(), vec!["/*"]);
        assert_eq!(
            location("/files/:path*", false).patterns(),
            vec!["/files/:path*"]
        );
        assert_eq!(
            location("/files/:path+", false).patterns(),
            vec!["/files/:path+"]
        );
        assert_eq!(location("/auth", true).patterns(), vec!["/auth"]);
    }

    #[test]
    fn test_rewrites_the_path() {
        let rewrite = |strip: Option<&str>, add: Option<&str>| {
            super::PathRewrite {
                strip_prefix: strip.map(ToString::to_string),
                add_prefix: add.map(ToString::to_string),
                ..Default::default()
            }
            .compile()
            .unwrap()
        };
        let strip = rewrite(Some("/api"), None);
        assert_eq!(strip.apply("/api/users", Some("page=2")), "/users?page=2");
        assert_eq!(strip.apply("/api", None), "/");
        assert_eq!(strip.apply("/api/", None), "/");
        // Only at a segment boundary
        assert_eq!(strip.apply("/apis", None), "/apis");
        assert_eq!(strip.apply("/other", None), "/other");
        // A trailing slash in the prefix is the same prefix
        assert_eq!(
            rewrite(Some("/api/"), None).apply("/api/users", None),
            "/users"
        );

        let both = rewrite(Some("/api"), Some("/v2"));
        assert_eq!(both.apply("/api/users", None), "/v2/users");
        assert_eq!(both.apply("/api", Some("x=1")), "/v2?x=1");
        assert_eq!(
            rewrite(None, Some("/v2/")).apply("/users", None),
            "/v2/users"
        );
        assert_eq!(rewrite(None, Some("/")).apply("/users", None), "/users");
    }

    #[test]
    fn test_invalid_rewrites() {
        let rewrite = |strip: Option<&str>, add: Option<&str>| super::PathRewrite {
            strip_prefix: strip.map(ToString::to_string),
            add_prefix: add.map(ToString::to_string),
            ..Default::default()
        };
        assert!(rewrite(None, None).compile().is_err());
        assert!(rewrite(Some("api"), None).compile().is_err());
        assert!(rewrite(None, Some("/v2?x=1")).compile().is_err());
        assert!(rewrite(Some("/api"), Some("/v2")).compile().is_ok());

        let regex = |pattern: Option<&str>, replace: Option<&str>| super::PathRewrite {
            pattern: pattern.map(ToString::to_string),
            replace: replace.map(ToString::to_string),
            ..Default::default()
        };
        assert!(regex(Some("^/a/(\\d+)$"), None).compile().is_err());
        assert!(regex(Some("^/a/(\\d+"), Some("/b/$1"))
            .compile()
            .err()
            .unwrap()
            .starts_with("invalid `match`"));
        // Too large once compiled
        assert!(regex(Some("\\w{1000}{1000}"), Some("/")).compile().is_err());
        let mut combined = regex(Some("^/a$"), Some("/b"));
        combined.strip_prefix = Some("/a".to_string());
        assert!(combined.compile().is_err());
    }

    #[test]
    fn test_rewrites_with_regular_expressions() {
        let rewrite = super::PathRewrite {
            pattern: Some("^/users/(?P<id>\\d+)/profile$".to_string()),
            replace: Some("/profiles/${id}".to_string()),
            ..Default::default()
        }
        .compile()
        .unwrap();
        assert_eq!(
            rewrite.apply("/users/42/profile", Some("tab=posts")),
            "/profiles/42?tab=posts"
        );
        assert_eq!(rewrite.apply("/users/42", None), "/users/42");

        // Paths become absolute
        let relative = super::PathRewrite {
            pattern: Some("^/old/(.*)$".to_string()),
            replace: Some("$1".to_string()),
            ..Default::default()
        }
        .compile()
        .unwrap();
        assert_eq!(relative.apply("/old/page", None), "/page");
    }

    /// Cost of rewriting a path, per request: `cargo test --release -- --ignored rewrite_overhead
    /// --nocapture`
    #[test]
    #[ignore = "measures time"]
    fn rewrite_overhead() {
        let iterations = 1_000_000;
        let measure = |name: &str, rewrite: Option<super::CompiledRewrite>| {
            let started = std::time::Instant::now();
            for i in 0..iterations {
                let path = if i % 2 == 0 { "/users/42/profile" } else { "/users/42/posts" };
                let rewritten = match &rewrite {
                    Some(rewrite) => rewrite.apply(path, Some("tab=1")),
                    None => path.to_string(),
                };
                std::hint::black_box(rewritten);
            }
            let per = started.elapsed() / iterations;
            println!("{name}: {per:?} per request");
        };
        let compile = |rewrite: super::PathRewrite| Some(rewrite.compile().unwrap());

        measure("no rewrite", None);
        measure(
            "prefixes",
            compile(super::PathRewrite {
                strip_prefix: Some("/users".to_string()),
                add_prefix: Some("/v2".to_string()),
                ..Default::default()
            }),
        );
        measure(
            "regex",
            compile(super::PathRewrite {
                pattern: Some("^/users/(\\d+)/profile$".to_string()),
                replace: Some("/profiles/$1".to_string()),
                ..Default::default()
            }),
        );
        measure(
            "regex, named groups",
            compile(super::PathRewrite {
                pattern: Some("^/(?P<kind>[a-z]+)/(?P<id>\\d+)/(?P<rest>.*)$".to_string()),
                replace: Some("/api/${kind}/${rest}/${id}".to_string()),
                ..Default::default()
            }),
        );
    }
}