protify 0.1.4

A Rust-first protobuf framework to generate packages from rust code, with validation included
Documentation
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
use super::*;

/// Well known string formats that a value should adhere to in order to be valid.
#[derive(Clone, Debug, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum WellKnownStrings {
	#[cfg(feature = "regex")]
	Email,
	Hostname,
	Ip,
	Ipv4,
	Ipv6,
	Uri,
	UriRef,
	Address,
	#[cfg(feature = "regex")]
	Ulid,
	#[cfg(feature = "regex")]
	Uuid,
	#[cfg(feature = "regex")]
	Tuuid,
	IpWithPrefixlen,
	Ipv4WithPrefixlen,
	Ipv6WithPrefixlen,
	IpPrefix,
	Ipv4Prefix,
	Ipv6Prefix,
	HostAndPort,
	#[cfg(feature = "regex")]
	HeaderNameLoose,
	#[cfg(feature = "regex")]
	HeaderNameStrict,
	#[cfg(feature = "regex")]
	HeaderValueLoose,
	#[cfg(feature = "regex")]
	HeaderValueStrict,
}

impl WellKnownStrings {
	#[inline(never)]
	#[cold]
	pub(crate) fn to_option(self) -> (FixedStr, OptionValue, bool) {
		let mut is_strict = false;

		let name = match self {
			#[cfg(feature = "regex")]
			Self::Ulid => "ulid",
			#[cfg(feature = "regex")]
			Self::Email => "email",
			Self::Hostname => "hostname",
			Self::Ip => "ip",
			Self::Ipv4 => "ipv4",
			Self::Ipv6 => "ipv6",
			Self::Uri => "uri",
			Self::UriRef => "uri_ref",
			Self::Address => "address",
			#[cfg(feature = "regex")]
			Self::Uuid => "uuid",
			#[cfg(feature = "regex")]
			Self::Tuuid => "tuuid",
			Self::IpWithPrefixlen => "ip_with_prefixlen",
			Self::Ipv4WithPrefixlen => "ipv4_with_prefixlen",
			Self::Ipv6WithPrefixlen => "ipv6_with_prefixlen",
			Self::IpPrefix => "ip_prefix",
			Self::Ipv4Prefix => "ipv4_prefix",
			Self::Ipv6Prefix => "ipv6_prefix",
			Self::HostAndPort => "host_and_port",
			#[cfg(feature = "regex")]
			Self::HeaderNameLoose
			| Self::HeaderNameStrict
			| Self::HeaderValueLoose
			| Self::HeaderValueStrict => "well_known_regex",
		};

		let value = match self {
			#[cfg(feature = "regex")]
			Self::HeaderNameLoose => OptionValue::Enum("KNOWN_REGEX_HTTP_HEADER_NAME".into()),
			#[cfg(feature = "regex")]
			Self::HeaderNameStrict => {
				is_strict = true;
				OptionValue::Enum("KNOWN_REGEX_HTTP_HEADER_NAME".into())
			}
			#[cfg(feature = "regex")]
			Self::HeaderValueLoose => OptionValue::Enum("KNOWN_REGEX_HTTP_HEADER_VALUE".into()),
			#[cfg(feature = "regex")]
			Self::HeaderValueStrict => {
				is_strict = true;
				OptionValue::Enum("KNOWN_REGEX_HTTP_HEADER_VALUE".into())
			}
			_ => OptionValue::Bool(true),
		};

		(name.into(), value, is_strict)
	}
}

use core::{
	net::{IpAddr, Ipv4Addr, Ipv6Addr},
	str::FromStr,
};

use ipnet::{IpNet, Ipv4Net, Ipv6Net};
#[cfg(feature = "regex")]
pub(crate) use regex_checks::*;

#[cfg(feature = "regex")]
mod regex_checks {
	use crate::Lazy;

	use regex::Regex;

	static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
		Regex::new(r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$").expect("Failed to create email regex")
	});

	pub(crate) fn is_valid_email(s: &str) -> bool {
		EMAIL_REGEX.is_match(s)
	}

	static HTTP_HEADER_NAME_STRICT_REGEX: Lazy<Regex> =
		Lazy::new(|| Regex::new(r"^:?[0-9a-zA-Z!#$%&'*+-.^_|~`]+$").unwrap());

	static HTTP_HEADER_NAME_LOOSE_REGEX: Lazy<Regex> =
		Lazy::new(|| Regex::new(r"^[^\u0000\u000A\u000D]+$").unwrap());

	static HTTP_HEADER_VALUE_STRICT_REGEX: Lazy<Regex> =
		Lazy::new(|| Regex::new(r"^[^\x00-\x08\x0A-\x1F\x7F]*$").unwrap());

	static HTTP_HEADER_VALUE_LOOSE_REGEX: Lazy<Regex> =
		Lazy::new(|| Regex::new(r"^[^\u0000\u000A\u000D]*$").unwrap());

	#[must_use]
	pub(crate) fn is_valid_http_header_name(s: &str, strict: bool) -> bool {
		if s.is_empty() {
			return false;
		}

		let re = if strict {
			&HTTP_HEADER_NAME_STRICT_REGEX
		} else {
			&HTTP_HEADER_NAME_LOOSE_REGEX
		};

		re.is_match(s)
	}

	#[must_use]
	pub(crate) fn is_valid_http_header_value(s: &str, strict: bool) -> bool {
		if s.is_empty() {
			return false;
		}

		let re = if strict {
			&HTTP_HEADER_VALUE_STRICT_REGEX
		} else {
			&HTTP_HEADER_VALUE_LOOSE_REGEX
		};

		re.is_match(s)
	}

	pub(crate) fn is_valid_ulid(val: &str) -> bool {
		if val.is_empty() {
			return false;
		}

		static ULID_REGEX: Lazy<Regex> =
			// Case insensitive (?i), strict first char check
			Lazy::new(|| Regex::new(r"(?i)^[0-7][0-9A-HJKMNP-TV-Z]{25}$").unwrap());

		ULID_REGEX.is_match(val)
	}

	pub(crate) fn is_valid_uuid(s: &str) -> bool {
		static UUID_REGEX: Lazy<Regex> = Lazy::new(|| {
			Regex::new(r"^(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
				.unwrap()
		});

		if s.is_empty() {
			return false;
		}

		UUID_REGEX.is_match(s)
	}

	pub(crate) fn is_valid_tuuid(s: &str) -> bool {
		static TUUID_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"^(?i)[0-9a-f]{32}$").unwrap());

		if s.is_empty() {
			return false;
		}

		TUUID_REGEX.is_match(s)
	}
}

#[must_use]
pub(crate) fn is_valid_uri(s: &str) -> bool {
	fluent_uri::Uri::parse(s).is_ok()
}

#[must_use]
pub(crate) fn is_valid_uri_ref(s: &str) -> bool {
	fluent_uri::UriRef::parse(s).is_ok()
}

#[must_use]
pub(crate) fn is_valid_ip_prefix(s: &str) -> bool {
	match IpNet::from_str(s) {
		Ok(network) => {
			// .network() returns the first address in the subnet
			network.addr() == network.network()
		}
		Err(_) => false,
	}
}

#[must_use]
pub(crate) fn is_valid_ipv4_prefix(s: &str) -> bool {
	match Ipv4Net::from_str(s) {
		Ok(network) => network.addr() == network.network(),
		Err(_) => false,
	}
}

#[must_use]
pub(crate) fn is_valid_ipv6_prefix(s: &str) -> bool {
	match Ipv6Net::from_str(s) {
		Ok(network) => network.addr() == network.network(),
		Err(_) => false,
	}
}

#[must_use]
pub(crate) fn is_valid_ip_with_prefixlen(s: &str) -> bool {
	IpNet::from_str(s).is_ok()
}

#[must_use]
pub(crate) fn is_valid_ipv4_with_prefixlen(s: &str) -> bool {
	Ipv4Net::from_str(s).is_ok()
}

#[must_use]
pub(crate) fn is_valid_ipv6_with_prefixlen(s: &str) -> bool {
	Ipv6Net::from_str(s).is_ok()
}

#[must_use]
pub(crate) fn is_valid_ip(s: &str) -> bool {
	IpAddr::from_str(s).is_ok()
}

#[must_use]
pub(crate) fn is_valid_ipv4(s: &str) -> bool {
	Ipv4Addr::from_str(s).is_ok()
}

#[must_use]
pub(crate) fn is_valid_ipv6(s: &str) -> bool {
	Ipv6Addr::from_str(s).is_ok()
}

#[must_use]
pub(crate) fn is_valid_address(s: &str) -> bool {
	is_valid_hostname(s) || is_valid_ip(s)
}

#[must_use]
pub(crate) fn is_valid_hostname(hostname: &str) -> bool {
	let s = hostname.strip_suffix('.').unwrap_or(hostname);
	if s.len() > 253 {
		return false;
	}

	// Split the hostname into labels.
	let labels: Vec<&str> = s.split('.').collect();

	let last_label = match labels.last() {
		Some(label) => *label,
		None => return false, // Handles empty string case
	};

	// Iterate and validate each label.
	for label in labels {
		// Rule: Each label can be 1 to 63 characters.
		if label.is_empty() || label.len() > 63 {
			return false;
		}

		// Rule: A label can contain hyphens, but must not start or end with one.
		if label.starts_with('-') || label.ends_with('-') {
			return false;
		}

		// Rule: Each label can be alphanumeric characters or hyphens.
		if !label
			.chars()
			.all(|c| c.is_ascii_alphanumeric() || c == '-')
		{
			return false;
		}
	}

	// Rule: The right-most label must not be digits only.
	if last_label.chars().all(|c| c.is_ascii_digit()) {
		return false;
	}

	true
}

#[must_use]
pub(crate) fn is_valid_port(port_str: &str) -> bool {
	// Port must not be empty.
	if port_str.is_empty() {
		return false;
	}
	// Cannot have leading zeros (unless it's just "0").
	if port_str.len() > 1 && port_str.starts_with('0') {
		return false;
	}
	// Try to parse as a u16, which covers the 0-65535 range automatically.
	port_str.parse::<u16>().is_ok()
}

#[must_use]
pub(crate) fn is_valid_host_and_port(s: &str) -> bool {
	if s.is_empty() {
		return false;
	}

	if let Some((host_part, port_part)) = s.rsplit_once(':') {
		// Is the host part a bracketed IPv6 address? e.g., `[::1]:8080`
		if let Some(ip_part) = host_part
			.strip_prefix('[')
			.and_then(|s| s.strip_suffix(']'))
		{
			return ip_part.parse::<Ipv6Addr>().is_ok() && is_valid_port(port_part);
		}

		// Otherwise, the host must be a regular hostname or an IP address.
		// `IpAddr` will handle both IPv4 and unbracketed IPv6.
		let is_host_valid = host_part.parse::<IpAddr>().is_ok() || is_valid_hostname(host_part);
		return is_host_valid && is_valid_port(port_part);
	}

	false
}

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

	#[test]
	fn uris() {
		assert!(is_valid_uri(
			"https://middleeathtracker.com/hobbits?location=isengard"
		));

		assert!(!is_valid_uri(
			"https://middleeathtracker.com/hobbits?location isengard"
		));
	}

	#[test]
	fn name() {
		let ipv4_prefix = "192.168.0.0/16";
		let ipv4_with_prefixlen = "192.168.1.1/16";
		let ipv6_prefix = "2a01:c00::/24";
		let ipv6_with_prefixlen = "2a01:c23:7b6d:a900:1de7:5cbe:d8d2:f4a1/24";

		assert!(is_valid_ip_with_prefixlen(ipv4_with_prefixlen));
		assert!(is_valid_ip_with_prefixlen(ipv6_with_prefixlen));
		assert!(is_valid_ipv4_with_prefixlen(ipv4_with_prefixlen));
		assert!(!is_valid_ipv4_with_prefixlen(ipv6_with_prefixlen));
		assert!(is_valid_ipv6_with_prefixlen(ipv6_with_prefixlen));
		assert!(!is_valid_ipv6_with_prefixlen(ipv4_with_prefixlen));

		assert!(is_valid_ip_prefix(ipv4_prefix));
		assert!(is_valid_ip_prefix(ipv6_prefix));
		assert!(is_valid_ipv4_prefix(ipv4_prefix));
		assert!(!is_valid_ipv4_prefix(ipv6_prefix));
		assert!(!is_valid_ipv4_prefix(ipv4_with_prefixlen));
		assert!(is_valid_ipv6_prefix(ipv6_prefix));
		assert!(!is_valid_ipv6_prefix(ipv4_prefix));
		assert!(!is_valid_ipv6_prefix(ipv6_with_prefixlen));
	}

	#[test]
	fn network_identifiers() {
		let ipv4 = "192.168.1.1";
		let ipv6 = "2a01:c23:7b6d:a900:1de7:5cbe:d8d2:f4a1";

		assert!(is_valid_ip(ipv4));
		assert!(is_valid_ip(ipv6));
		assert!(is_valid_ipv4(ipv4));
		assert!(!is_valid_ipv4(ipv6));
		assert!(is_valid_ipv6(ipv6));
		assert!(!is_valid_ipv6(ipv4));

		assert!(is_valid_address("obiwan.force.com"));
		assert!(is_valid_address(ipv4));
		assert!(is_valid_address(ipv6));

		assert!(is_valid_host_and_port("obiwan.force:8080"));
		assert!(is_valid_host_and_port("192.168.1.120:3000"));
		assert!(is_valid_host_and_port("[2001:0DB8:ABCD:0012::F1]:3000"));

		assert!(!is_valid_host_and_port("obiwan.force"));
		assert!(!is_valid_host_and_port("192.168.1.120"));
		assert!(!is_valid_host_and_port("2001:0DB8:ABCD:0012::F1"));

		assert!(is_valid_hostname("obiwan.force.com"));
		assert!(!is_valid_hostname("-anakin.darkforce.com"));
		assert!(!is_valid_hostname("anakin.darkforce.com-"));
		assert!(!is_valid_hostname("anakin.darkforce.0"));
	}

	#[cfg(feature = "regex")]
	mod regex_tests {
		use super::*;

		#[test]
		fn identifiers() {
			use super::{is_valid_email, is_valid_tuuid, is_valid_uuid};

			assert!(is_valid_email("obiwan@force.com"));
			assert!(!is_valid_email("anakin@dark@force.com"));

			assert!(is_valid_uuid("d3b8f2d5-7e10-4c6e-8a1a-3b9c7d4f6e2c"));
			assert!(!is_valid_uuid("d3b8f2d57e104c6e8a1a3b9c7d4f6e2c"));

			assert!(is_valid_tuuid("d3b8f2d57e104c6e8a1a3b9c7d4f6e2c"));
			assert!(!is_valid_tuuid("d3b8f2d5-7e10-4c6e-8a1a-3b9c7d4f6e2c"))
		}

		#[test]
		fn headers() {
			use super::{is_valid_http_header_name, is_valid_http_header_value};

			assert!(is_valid_http_header_name("content-type", true));
			assert!(is_valid_http_header_name(":authority", true));

			assert!(!is_valid_http_header_name("content type", true));
			assert!(!is_valid_http_header_name("X-My@Header", true));
			assert!(!is_valid_http_header_name("X-Héader", true));
			assert!(!is_valid_http_header_name("", true));

			assert!(is_valid_http_header_name("X-My@Header", false));
			assert!(is_valid_http_header_name("X-Héader", false));

			assert!(!is_valid_http_header_name("Header\u{0000}WithNul", false));
			assert!(!is_valid_http_header_name("Header\nWithNewline", false));
			assert!(!is_valid_http_header_name("header\rwithcr", false));
			assert!(!is_valid_http_header_name("", false));

			assert!(is_valid_http_header_value(
				"application/json; charset=uft-8",
				true
			));

			assert!(!is_valid_http_header_value(
				"value\u{0000}with\u{0000}nul",
				true
			));
			assert!(!is_valid_http_header_value(
				"value\u{0007}with\u{0007}bell",
				true
			));
			assert!(!is_valid_http_header_value(
				"value\u{000B}with\u{000B}vt",
				true
			));
			assert!(!is_valid_http_header_value(
				"value\u{007F}with\u{007F}del",
				true
			));

			assert!(!is_valid_http_header_value(
				"value\u{0000}with\u{0000}nul",
				false
			));
			assert!(!is_valid_http_header_value("value\nwith\nnewline", false));
			assert!(!is_valid_http_header_value("value\rwith\rcr", false));
		}

		#[test]
		fn test_valid_ulids() {
			// A standard generated ULID
			assert!(is_valid_ulid("01AN4Z07BY79KA1307SR9X4MV3"));

			// The absolute minimum ULID (Time 0, Random 0)
			assert!(is_valid_ulid("00000000000000000000000000"));

			// The absolute maximum ULID (Time limit, Random max)
			// Note: Must start with 7, not Z
			assert!(is_valid_ulid("7ZZZZZZZZZZZZZZZZZZZZZZZZZ"));
		}

		#[test]
		fn test_case_insensitivity() {
			// Lowercase should work
			assert!(is_valid_ulid("01an4z07by79ka1307sr9x4mv3"));
			// Mixed case should work
			assert!(is_valid_ulid("01An4z07bY79kA1307sR9x4mV3"));
		}

		#[test]
		fn test_invalid_length() {
			// Empty
			assert!(!is_valid_ulid(""));

			// Too short (25 chars)
			assert!(!is_valid_ulid("01AN4Z07BY79KA1307SR9X4MV"));

			// Too long (27 chars)
			assert!(!is_valid_ulid("01AN4Z07BY79KA1307SR9X4MV33"));
		}

		#[test]
		fn test_excluded_characters() {
			// Crockford Base32 excludes I, L, O, U to avoid confusion

			// Contains I
			assert!(!is_valid_ulid("01AN4Z07BY79KA1307SR9X4MVI"));
			// Contains L
			assert!(!is_valid_ulid("01AN4Z07BY79KA1307SR9X4MVL"));
			// Contains O
			assert!(!is_valid_ulid("01AN4Z07BY79KA1307SR9X4MVO"));
			// Contains U
			assert!(!is_valid_ulid("01AN4Z07BY79KA1307SR9X4MVU"));
		}

		#[test]
		fn test_invalid_symbols() {
			// Hyphens are not allowed in canonical ULIDs
			assert!(!is_valid_ulid("01AN4Z07-Y79KA1307SR9X4MV3"));
			// Other symbols
			assert!(!is_valid_ulid("01AN4Z07BY79KA1307SR9X4MV@"));
		}

		#[test]
		fn test_timestamp_overflow() {
			// The first character maps to the top bits of the 48-bit timestamp.
			// It can only be 0-7.
			// 8 would imply a timestamp larger than 48 bits allow.

			// Starts with 8 (Invalid)
			assert!(!is_valid_ulid("80000000000000000000000000"));

			// Starts with 9 (Invalid)
			assert!(!is_valid_ulid("90000000000000000000000000"));

			// Starts with A (Invalid)
			assert!(!is_valid_ulid("A0000000000000000000000000"));

			// Starts with Z (Invalid)
			assert!(!is_valid_ulid("Z0000000000000000000000000"));
		}
	}
}