libtea_core/error.rs
1//! Protocol errors for parsing and validation.
2//!
3//! These errors describe malformed or non-conforming TEA data. They are not
4//! transport failures.
5
6use thiserror::Error;
7
8/// Escape control characters so server-supplied text is safe to print.
9///
10/// C0 controls (including ESC, BEL, and CR), DEL, C1 controls (including the
11/// single-character CSI `U+009B` and OSC `U+009D`), and the bidirectional
12/// override/isolate characters (`U+202A..=U+202E`, `U+2066..=U+2069`) become
13/// `\uXXXX`. Tab and newline are kept. Other text is returned unchanged. A
14/// backslash sequence that the server itself sent cannot be told apart from an
15/// escape.
16///
17/// `libtea-client` applies this to server text it puts into
18/// [`ModelError`] and its own error type, and `libtea-cli` applies it to
19/// everything it prints.
20#[must_use]
21pub fn escape_control_chars(text: &str) -> String {
22 let mut out = String::with_capacity(text.len());
23 for c in text.chars() {
24 let escape = match c {
25 '\t' | '\n' => false,
26 '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' => true,
27 c => c.is_control(),
28 };
29 if escape {
30 out.push_str(&format!("\\u{:04x}", u32::from(c)));
31 } else {
32 out.push(c);
33 }
34 }
35 out
36}
37
38/// Failure while parsing or validating a Transparency Exchange Identifier.
39#[derive(Debug, Error, Clone, PartialEq, Eq)]
40#[non_exhaustive]
41pub enum TeiError {
42 /// The input was empty.
43 #[error("TEI is empty")]
44 Empty,
45 /// The input used the legacy `urn:tei:` form, which this crate does not parse.
46 #[error(
47 "the legacy `urn:tei:` form is not supported; use `tei://<domain-name>/<type>/<unique-identifier>`"
48 )]
49 LegacyUrn,
50 /// The scheme was not the exact lowercase string `tei`.
51 #[error("TEI scheme must be the lowercase string `tei`")]
52 Scheme,
53 /// The TEI did not have the form `tei://domain/type/identifier`.
54 #[error("TEI must be `tei://<domain-name>/<type>/<unique-identifier>`")]
55 Structure,
56 /// A domain name was missing or not an ASCII DNS name.
57 #[error("TEI domain name is not an ASCII DNS name without a port")]
58 Domain,
59 /// The type segment was not lowercase ASCII starting with a letter.
60 #[error("TEI type must be lowercase ASCII letters and digits, starting with a letter")]
61 Type,
62 /// The unique-identifier segment was empty or contained a slash.
63 #[error("TEI unique identifier must be one path segment and must not contain `/`")]
64 Identifier,
65 /// A percent-escape was truncated or not hexadecimal.
66 #[error("TEI unique identifier contains an invalid percent-escape")]
67 PercentEncoding,
68 /// The identifier failed the registered type's syntax.
69 #[error("TEI identifier is not valid for type `{tei_type}`: {reason}")]
70 #[non_exhaustive]
71 Registry {
72 /// Registered TEI type that rejected the identifier.
73 tei_type: String,
74 /// Why the identifier failed that type's syntax.
75 reason: String,
76 },
77}
78
79/// Failure while parsing a TEA model, discovery document, or version.
80#[derive(Debug, Error, Clone, PartialEq, Eq)]
81#[non_exhaustive]
82pub enum ModelError {
83 /// JSON was not valid.
84 #[error("JSON parse error: {}", escape_control_chars(.0))]
85 Json(String),
86 /// A field violated a normative constraint.
87 ///
88 /// The message can quote server text; `Display` escapes control characters
89 /// ([`escape_control_chars`]).
90 #[error("{}", escape_control_chars(.0))]
91 Invalid(String),
92}
93
94impl From<serde_json::Error> for ModelError {
95 fn from(value: serde_json::Error) -> Self {
96 Self::Json(value.to_string())
97 }
98}
99
100/// Failure of destination policy checks that do not contact the network.
101#[derive(Debug, Error, Clone, PartialEq, Eq)]
102#[non_exhaustive]
103pub enum PolicyError {
104 /// The URL used a scheme other than `https`, or `http` outside an explicit exception.
105 #[error("URL scheme is not allowed: {0}")]
106 Scheme(String),
107 /// The URL contained userinfo.
108 #[error("URL must not contain userinfo")]
109 Userinfo,
110 /// The URL contained a query or fragment where a base URL forbids them.
111 #[error("URL must not contain a query or fragment")]
112 QueryOrFragment,
113 /// The host was missing.
114 #[error("URL is missing a host")]
115 Host,
116 /// A trailing slash was present on an API base.
117 #[error("API base URL must not have a trailing slash")]
118 TrailingSlash,
119 /// The resolved or literal address is not an acceptable destination.
120 #[error("destination address is not allowed: {0}")]
121 Destination(String),
122 /// The hostname is a well-known metadata or local name.
123 #[error("hostname is not allowed: {0}")]
124 Hostname(String),
125}