-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathvalidation.rs
More file actions
500 lines (452 loc) · 15 KB
/
Copy pathvalidation.rs
File metadata and controls
500 lines (452 loc) · 15 KB
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
/*
Keep this around for now, it could be useful, because it allows performing Kubernetes checks
before actually sending a request and waiting for it to fail.
Warning: You should be sure that Kubernetes enforces these rules for the request you are trying
to validate.
*/
// This is adapted from Kubernetes.
// See apimachinery/pkg/util/validation/validation.go, apimachinery/pkg/api/validation/generic.go and pkg/apis/core/validation/validation.go in the Kubernetes source
use std::{fmt::Display, sync::LazyLock};
use const_format::concatcp;
use regex::Regex;
use snafu::Snafu;
/// Minimal length required by RFC 1123 is 63. Up to 255 allowed, unsupported by k8s.
pub const RFC_1123_LABEL_MAX_LENGTH: usize = 63;
// This is a modified RFC 1123 format according to the Kubernetes specification, see https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#dns-label-names
pub const LOWERCASE_RFC_1123_LABEL_FMT: &str = "[a-z0-9]([-a-z0-9]*[a-z0-9])?";
const LOWERCASE_RFC_1123_LABEL_ERROR_MSG: &str = "a lowercase RFC 1123 label must consist of lower case alphanumeric characters or '-', and must start and end with an alphanumeric character";
// This is a RFC 1123 format, see https://www.rfc-editor.org/rfc/rfc1123
const RFC_1123_LABEL_FMT: &str = "[a-zA-Z0-9]([-a-zA-Z0-9]*[a-zA-Z0-9])?";
/// This is a subdomain's max length in DNS (RFC 1123)
pub const RFC_1123_SUBDOMAIN_MAX_LENGTH: usize = 253;
pub const LOWERCASE_RFC_1123_SUBDOMAIN_FMT: &str = concatcp!(
LOWERCASE_RFC_1123_LABEL_FMT,
"(\\.",
LOWERCASE_RFC_1123_LABEL_FMT,
")*"
);
const LOWERCASE_RFC_1123_SUBDOMAIN_ERROR_MSG: &str = "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character";
pub const DOMAIN_MAX_LENGTH: usize = RFC_1123_SUBDOMAIN_MAX_LENGTH;
/// String of one or multiple [`RFC_1123_LABEL_FMT`] separated by dots but also allowing a trailing dot
const DOMAIN_FMT: &str = concatcp!(RFC_1123_LABEL_FMT, "(\\.", RFC_1123_LABEL_FMT, ")*\\.?");
const DOMAIN_ERROR_MSG: &str = "a domain must consist of alphanumeric characters, '-' or '.', and must start with an alphanumeric character and end with an alphanumeric character or '.'";
// FIXME: According to https://www.rfc-editor.org/rfc/rfc1035#section-2.3.1 domain names must start with a letter
// (and not a number).
// This is a modified RFC 1035 format according to the Kubernetes specification, see https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#rfc-1035-label-names
pub const LOWERCASE_RFC_1035_LABEL_FMT: &str = "[a-z]([-a-z0-9]*[a-z0-9])?";
const LOWERCASE_RFC_1035_LABEL_ERROR_MSG: &str = "a DNS-1035 label must consist of lower case alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character";
// This is a label's max length in DNS (RFC 1035)
pub const RFC_1035_LABEL_MAX_LENGTH: usize = 63;
// Technically Kerberos allows more realm names
// (https://web.mit.edu/kerberos/krb5-1.21/doc/admin/realm_config.html#realm-name),
// however, these are embedded in a lot of configuration files and other strings,
// and will not always be quoted properly.
//
// Hence, restrict them to a reasonable subset. The convention is to use upper-case
// DNS hostnames, so allow all characters used there.
const KERBEROS_REALM_NAME_FMT: &str = "[-.a-zA-Z0-9]+";
const KERBEROS_REALM_NAME_ERROR_MSG: &str =
"Kerberos realm name must only contain alphanumeric characters, '-', and '.'";
// Lazily initialized regular expressions
pub(crate) static DOMAIN_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(&format!("^{DOMAIN_FMT}$")).expect("failed to compile domain regex")
});
static LOWERCASE_RFC_1123_LABEL_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(&format!("^{LOWERCASE_RFC_1123_LABEL_FMT}$"))
.expect("failed to compile RFC 1123 label regex")
});
static LOWERCASE_RFC_1123_SUBDOMAIN_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(&format!("^{LOWERCASE_RFC_1123_SUBDOMAIN_FMT}$"))
.expect("failed to compile RFC 1123 subdomain regex")
});
static LOWERCASE_RFC_1035_LABEL_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(&format!("^{LOWERCASE_RFC_1035_LABEL_FMT}$"))
.expect("failed to compile RFC 1035 label regex")
});
pub(crate) static KERBEROS_REALM_NAME_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(&format!("^{KERBEROS_REALM_NAME_FMT}$"))
.expect("failed to compile Kerberos realm name regex")
});
type Result<T = (), E = Errors> = std::result::Result<T, E>;
/// A collection of errors discovered during validation.
#[derive(Debug)]
pub struct Errors(Vec<Error>);
impl Display for Errors {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for (i, error) in self.0.iter().enumerate() {
let prefix = match i {
0 => "",
_ => ", ",
};
write!(f, "{prefix}{error}")?;
}
Ok(())
}
}
impl std::error::Error for Errors {}
/// A single validation error.
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(transparent)]
Regex { source: RegexError },
#[snafu(display("input is {length} bytes long but must be no more than {max_length}"))]
TooLong { length: usize, max_length: usize },
}
#[derive(Debug)]
pub struct RegexError {
/// The primary error message.
msg: &'static str,
/// The regex that the input must match.
regex: &'static str,
/// Examples of valid inputs (if non-empty).
examples: &'static [&'static str],
}
impl Display for RegexError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Self {
msg,
regex,
examples,
} = self;
write!(f, "{msg} (")?;
if !examples.is_empty() {
for (i, example) in examples.iter().enumerate() {
let prefix = match i {
0 => "e.g.",
_ => "or",
};
write!(f, "{prefix} {example:?}, ")?;
}
}
write!(f, "regex used for validation is {regex:?})")
}
}
impl std::error::Error for RegexError {}
/// Returns [`Ok`] if `value`'s length fits within `max_length`.
fn validate_str_length(value: &str, max_length: usize) -> Result<(), Error> {
if value.len() > max_length {
TooLongSnafu {
length: value.len(),
max_length,
}
.fail()
} else {
Ok(())
}
}
/// Returns [`Ok`] if `value` matches `regex`.
fn validate_str_regex(
value: &str,
regex: &'static Regex,
error_msg: &'static str,
examples: &'static [&'static str],
) -> Result<(), Error> {
if regex.is_match(value) {
Ok(())
} else {
Err(RegexError {
msg: error_msg,
regex: regex
.as_str()
// Clean up start/end-of-line markers
.trim_start_matches('^')
.trim_end_matches('$'),
examples,
}
.into())
}
}
/// Returns [`Ok`] if *all* validations are [`Ok`], otherwise returns all errors.
fn validate_all(validations: impl IntoIterator<Item = Result<(), Error>>) -> Result {
let errors = validations
.into_iter()
.filter_map(|res| res.err())
.collect::<Vec<_>>();
if errors.is_empty() {
Ok(())
} else {
Err(Errors(errors))
}
}
pub fn is_domain(value: &str) -> Result {
validate_all([
validate_str_length(value, DOMAIN_MAX_LENGTH),
validate_str_regex(
value,
&DOMAIN_REGEX,
DOMAIN_ERROR_MSG,
&[
"example.com",
"example.com.",
"cluster.local",
"cluster.local.",
],
),
])
}
/// Tests for a string that conforms to the kubernetes-specific definition of a label in DNS (RFC 1123)
/// used in Namespace names, see: [Kubernetes Docs](https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#dns-label-names)
/// Maximum label length supported by k8s is 63 characters (minimum required).
pub fn is_lowercase_rfc_1123_label(value: &str) -> Result {
validate_all([
validate_str_length(value, RFC_1123_LABEL_MAX_LENGTH),
validate_str_regex(
value,
&LOWERCASE_RFC_1123_LABEL_REGEX,
LOWERCASE_RFC_1123_LABEL_ERROR_MSG,
&["example-label", "1-label-1"],
),
])
}
/// Tests for a string that conforms to the kubernetes-specific definition of a subdomain in DNS (RFC 1123)
/// used in ConfigMap names, see [Kubernetes Docs](https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#dns-subdomain-names)
pub fn is_lowercase_rfc_1123_subdomain(value: &str) -> Result {
validate_all([
validate_str_length(value, RFC_1123_SUBDOMAIN_MAX_LENGTH),
validate_str_regex(
value,
&LOWERCASE_RFC_1123_SUBDOMAIN_REGEX,
LOWERCASE_RFC_1123_SUBDOMAIN_ERROR_MSG,
&["example.com"],
),
])
}
/// Tests for a string that conforms to the kubernetes-specific definition of a label in DNS (RFC 1035)
/// used in Service names, see: [Kubernetes Docs](https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#rfc-1035-label-names)
pub fn is_lowercase_rfc_1035_label(value: &str) -> Result {
validate_all([
validate_str_length(value, RFC_1035_LABEL_MAX_LENGTH),
validate_str_regex(
value,
&LOWERCASE_RFC_1035_LABEL_REGEX,
LOWERCASE_RFC_1035_LABEL_ERROR_MSG,
&["my-name", "abc-123"],
),
])
}
/// Tests whether a string looks like a reasonable Kerberos realm name.
///
/// This check is much stricter than krb5's own validation,
pub fn is_kerberos_realm_name(value: &str) -> Result {
validate_all([validate_str_regex(
value,
&KERBEROS_REALM_NAME_REGEX,
KERBEROS_REALM_NAME_ERROR_MSG,
&["EXAMPLE.COM"],
)])
}
// mask_trailing_dash replaces the final character of a string with a subdomain safe
// value if is a dash.
fn mask_trailing_dash(mut name: String) -> String {
if name.ends_with('-') {
name.pop();
name.push('a');
}
name
}
/// name_is_dns_label checks whether the passed in name is a valid DNS label
/// according to RFC 1035.
///
/// # Arguments
///
/// * `name` - is the name to check for validity
/// * `prefix` - indicates whether `name` is just a prefix (ending in a dash, which would otherwise not be legal at the end)
pub fn name_is_dns_label(name: &str, prefix: bool) -> Result {
let mut name = name.to_string();
if prefix {
name = mask_trailing_dash(name);
}
is_lowercase_rfc_1035_label(&name)
}
/// Validates a namespace name.
///
/// See [`name_is_dns_label`] for more information.
pub fn validate_namespace_name(name: &str, prefix: bool) -> Result {
name_is_dns_label(name, prefix)
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use super::*;
#[rstest]
#[case("")]
#[case("A")]
#[case("aBc")]
#[case("ABC")]
#[case("A1")]
#[case("A-1")]
#[case("1-A")]
#[case("-")]
#[case("a-")]
#[case("-a")]
#[case("1-")]
#[case("-1")]
#[case("_")]
#[case("a_")]
#[case("_a")]
#[case("a_b")]
#[case("1_")]
#[case("_1")]
#[case("1_2")]
#[case(".")]
#[case("a.")]
#[case(".a")]
#[case("a..b")]
#[case("1.")]
#[case(".1")]
#[case("1..2")]
#[case(" ")]
#[case("a ")]
#[case(" a")]
#[case("a b")]
#[case("1 ")]
#[case(" 1")]
#[case("1 2")]
#[case("A.a")]
#[case("aB.a")]
#[case("ab.A")]
#[case("A1.a")]
#[case("a1.A")]
#[case("A.1")]
#[case("aB.1")]
#[case("A1.1")]
#[case("0.A")]
#[case("01.A")]
#[case("012.A")]
#[case("1A.a")]
#[case("1a.A")]
#[case("1A.1")]
#[case("a.B.c.d.e")]
#[case("A.B.C.D.E")]
#[case("aa.bB.cc.dd.ee")]
#[case("AA.BB.CC.DD.EE")]
#[case("a@b")]
#[case("a,b")]
#[case("a_b")]
#[case("a;b")]
#[case("a:b")]
#[case("a%b")]
#[case("a?b")]
#[case("a$b")]
#[case(&"a".repeat(254))]
fn is_rfc_1123_subdomain_fail(#[case] value: &str) {
assert!(is_lowercase_rfc_1123_subdomain(value).is_err());
}
#[rstest]
#[case("a")]
#[case("ab")]
#[case("abc")]
#[case("a1")]
#[case("a-1")]
#[case("a--1--2--b")]
#[case("0")]
#[case("01")]
#[case("012")]
#[case("1a")]
#[case("1-a")]
#[case("1--a--b--2")]
#[case("a.a")]
#[case("ab.a")]
#[case("abc.a")]
#[case("a1.a")]
#[case("a-1.a")]
#[case("a--1--2--b.a")]
#[case("a.1")]
#[case("ab.1")]
#[case("abc.1")]
#[case("a1.1")]
#[case("a-1.1")]
#[case("a--1--2--b.1")]
#[case("0.a")]
#[case("01.a")]
#[case("012.a")]
#[case("1a.a")]
#[case("1-a.a")]
#[case("1--a--b--2")]
#[case("0.1")]
#[case("01.1")]
#[case("012.1")]
#[case("1a.1")]
#[case("1-a.1")]
#[case("1--a--b--2.1")]
#[case("a.b.c.d.e")]
#[case("aa.bb.cc.dd.ee")]
#[case("1.2.3.4.5")]
#[case("11.22.33.44.55")]
#[case(&"a".repeat(253))]
fn is_rfc_1123_subdomain_pass(#[case] value: &str) {
assert!(is_lowercase_rfc_1123_subdomain(value).is_ok());
// Every valid RFC1123 is also a valid domain
assert!(is_domain(value).is_ok());
}
#[rstest]
#[case("cluster.local")]
#[case("CLUSTER.LOCAL")]
#[case("cluster.local.")]
#[case("CLUSTER.LOCAL.")]
fn is_domain_pass(#[case] value: &str) {
assert!(is_domain(value).is_ok());
}
#[test]
fn test_mask_trailing_dash() {
assert_eq!(mask_trailing_dash("abc-".to_string()), "abca");
assert_eq!(mask_trailing_dash("abc".to_string()), "abc");
assert_eq!(mask_trailing_dash(String::new()), String::new());
assert_eq!(mask_trailing_dash("-".to_string()), "a");
}
#[rstest]
#[case("0")]
#[case("01")]
#[case("012")]
#[case("1a")]
#[case("1-a")]
#[case("1--a--b--2")]
#[case("")]
#[case("A")]
#[case("ABC")]
#[case("aBc")]
#[case("A1")]
#[case("A-1")]
#[case("1-A")]
#[case("-")]
#[case("a-")]
#[case("-a")]
#[case("1-")]
#[case("-1")]
#[case("_")]
#[case("a_")]
#[case("_a")]
#[case("a_b")]
#[case("1_")]
#[case("_1")]
#[case("1_2")]
#[case(".")]
#[case("a.")]
#[case(".a")]
#[case("a.b")]
#[case("1.")]
#[case(".1")]
#[case("1.2")]
#[case(" ")]
#[case("a ")]
#[case(" a")]
#[case("a b")]
#[case("1 ")]
#[case(" 1")]
#[case("1 2")]
#[case(&"a".repeat(64))]
fn is_rfc_1035_label_fail(#[case] value: &str) {
assert!(is_lowercase_rfc_1035_label(value).is_err());
}
#[rstest]
#[case("a")]
#[case("ab")]
#[case("abc")]
#[case("a1")]
#[case("a-1")]
#[case("a--1--2--b")]
#[case(&"a".repeat(63))]
fn is_rfc_1035_label_pass(#[case] value: &str) {
assert!(is_lowercase_rfc_1035_label(value).is_ok());
}
}