Skip to main content

countersign_protocol/
destination.rs

1use std::collections::HashSet;
2use std::fmt;
3use std::str::FromStr;
4
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6use thiserror::Error;
7
8#[derive(Clone, Debug, Error, PartialEq, Eq)]
9pub enum PolicyError {
10    #[error("expected an HTTPS DNS authority")]
11    InvalidHost,
12    #[error("expected a decimal port from 1 to 65535")]
13    InvalidPort,
14    #[error("CONNECT requires an explicit port")]
15    MissingPort,
16    #[error("a destination entry needs a nonempty ID and a positive version")]
17    InvalidEntry,
18    #[error("duplicate destination entry ID")]
19    DuplicateId,
20    #[error("duplicate canonical destination pattern")]
21    DuplicatePattern,
22    #[error("whole-wildcard approval requires a wildcard destination")]
23    InvalidApprovalMode,
24}
25
26/// A concrete HTTPS origin, represented on the wire as an A-label name and port.
27#[derive(Clone, Debug, Hash, PartialEq, Eq)]
28pub struct Origin {
29    host: String,
30    port: u16,
31}
32
33impl Origin {
34    /// An omitted HTTPS port becomes 443. Use `parse_connect` on CONNECT targets.
35    pub fn parse(authority: &str) -> Result<Self, PolicyError> {
36        let (host, port) = match authority.split_once(':') {
37            Some((host, text)) => {
38                if text.starts_with('0') || !text.bytes().all(|b| b.is_ascii_digit()) {
39                    return Err(PolicyError::InvalidPort);
40                }
41                let port = text.parse::<u16>().map_err(|_| PolicyError::InvalidPort)?;
42                (host, port)
43            }
44            None => (authority, 443),
45        };
46
47        // Strip one optional DNS root dot. IDNA's strict profile checks STD3,
48        // A-label validity, label/total length, and empty/interior root labels.
49        let host = host.strip_suffix('.').unwrap_or(host);
50        let host = idna::domain_to_ascii_strict(host).map_err(|_| PolicyError::InvalidHost)?;
51
52        // URL stacks can interpret decimal, octal, hex and shortened IPv4 syntax
53        // differently from system resolvers. Deny numeric-ending domains before DNS.
54        let last = host.rsplit('.').next().unwrap_or_default();
55        let numeric = last.bytes().all(|b| b.is_ascii_digit());
56        let hex = last
57            .strip_prefix("0x")
58            .is_some_and(|n| n.bytes().all(|b| b.is_ascii_hexdigit()));
59        if numeric || hex {
60            return Err(PolicyError::InvalidHost);
61        }
62        Ok(Self { host, port })
63    }
64
65    pub fn parse_connect(authority: &str) -> Result<Self, PolicyError> {
66        if !authority.contains(':') {
67            return Err(PolicyError::MissingPort);
68        }
69        Self::parse(authority)
70    }
71
72    pub fn host(&self) -> &str {
73        &self.host
74    }
75
76    pub fn port(&self) -> u16 {
77        self.port
78    }
79}
80
81impl FromStr for Origin {
82    type Err = PolicyError;
83
84    fn from_str(s: &str) -> Result<Self, Self::Err> {
85        Self::parse(s)
86    }
87}
88
89impl fmt::Display for Origin {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        write!(f, "{}:{}", self.host, self.port)
92    }
93}
94
95impl Serialize for Origin {
96    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
97        serializer.collect_str(self)
98    }
99}
100
101impl<'de> Deserialize<'de> for Origin {
102    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
103        String::deserialize(deserializer)?
104            .parse()
105            .map_err(serde::de::Error::custom)
106    }
107}
108
109#[derive(Clone, Debug, Hash, PartialEq, Eq)]
110pub enum DestinationPattern {
111    Exact(Origin),
112    /// Origin holds the suffix and port. Matches exactly one additional DNS label.
113    Wildcard(Origin),
114}
115
116impl DestinationPattern {
117    pub fn parse(pattern: &str) -> Result<Self, PolicyError> {
118        match pattern.strip_prefix("*.") {
119            Some(suffix) => Origin::parse(suffix).map(Self::Wildcard),
120            None => Origin::parse(pattern).map(Self::Exact),
121        }
122    }
123
124    fn bare_origin(&self) -> &Origin {
125        match self {
126            Self::Exact(origin) | Self::Wildcard(origin) => origin,
127        }
128    }
129
130    pub fn matches(&self, target: &Origin) -> bool {
131        match self {
132            Self::Exact(exact) => exact == target,
133            Self::Wildcard(suffix) => {
134                suffix.port() == target.port()
135                    && target
136                        .host()
137                        .split_once('.')
138                        .is_some_and(|(_, rest)| rest == suffix.host())
139            }
140        }
141    }
142}
143
144impl fmt::Display for DestinationPattern {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        match self {
147            Self::Exact(origin) => write!(f, "{origin}"),
148            Self::Wildcard(suffix) => write!(f, "*.{suffix}"),
149        }
150    }
151}
152
153impl Serialize for DestinationPattern {
154    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
155        serializer.collect_str(self)
156    }
157}
158
159impl<'de> Deserialize<'de> for DestinationPattern {
160    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
161        Self::parse(&String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
162    }
163}
164
165#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
166#[serde(rename_all = "snake_case")]
167pub enum ApprovalMode {
168    #[default]
169    ExactHost,
170    WholeWildcard,
171}
172
173#[derive(Clone, Debug, PartialEq, Eq)]
174pub struct DestinationEntry {
175    id: String,
176    version: u64,
177    pattern: DestinationPattern,
178    approval: ApprovalMode,
179}
180
181impl DestinationEntry {
182    pub fn new(
183        id: impl Into<String>,
184        version: u64,
185        pattern: &str,
186        approval: ApprovalMode,
187    ) -> Result<Self, PolicyError> {
188        let id = id.into();
189        if id.trim().is_empty() || id.chars().any(char::is_control) || version == 0 {
190            return Err(PolicyError::InvalidEntry);
191        }
192        let pattern = DestinationPattern::parse(pattern)?;
193        if approval == ApprovalMode::WholeWildcard
194            && matches!(pattern, DestinationPattern::Exact(_))
195        {
196            return Err(PolicyError::InvalidApprovalMode);
197        }
198        Ok(Self {
199            id,
200            version,
201            pattern,
202            approval,
203        })
204    }
205
206    pub fn id(&self) -> &str {
207        &self.id
208    }
209
210    pub fn version(&self) -> u64 {
211        self.version
212    }
213
214    pub fn pattern(&self) -> &DestinationPattern {
215        &self.pattern
216    }
217
218    pub fn approval_mode(&self) -> ApprovalMode {
219        self.approval
220    }
221
222    /// RFC 5280 DNS subtree for the sidecar CA. The Gateway still enforces the exact pattern and port.
223    pub fn constraint_dns_name(&self) -> &str {
224        self.pattern.bare_origin().host()
225    }
226}
227
228/// Destination portion of an approval or grant. The Broker separately binds the
229/// authenticated owner, workload, certificate and lifetime.
230#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
231#[serde(deny_unknown_fields)]
232pub struct DestinationScope {
233    entry_id: String,
234    entry_version: u64,
235    pattern: DestinationPattern,
236}
237
238impl DestinationScope {
239    pub fn entry_id(&self) -> &str {
240        &self.entry_id
241    }
242
243    pub fn entry_version(&self) -> u64 {
244        self.entry_version
245    }
246
247    pub fn pattern(&self) -> &DestinationPattern {
248        &self.pattern
249    }
250}
251
252#[derive(Clone, Debug, Default)]
253pub struct DestinationPolicy {
254    entries: Vec<DestinationEntry>,
255}
256
257impl DestinationPolicy {
258    pub fn new(entries: Vec<DestinationEntry>) -> Result<Self, PolicyError> {
259        let mut ids = HashSet::new();
260        let mut patterns = HashSet::new();
261        for entry in &entries {
262            if !ids.insert(&entry.id) {
263                return Err(PolicyError::DuplicateId);
264            }
265            if !patterns.insert(&entry.pattern) {
266                return Err(PolicyError::DuplicatePattern);
267            }
268        }
269        Ok(Self { entries })
270    }
271
272    pub fn entries(&self) -> &[DestinationEntry] {
273        &self.entries
274    }
275
276    pub fn resolve(&self, origin: &Origin) -> Option<&DestinationEntry> {
277        self.entries
278            .iter()
279            .filter(|entry| entry.pattern.matches(origin))
280            .max_by_key(|entry| matches!(entry.pattern, DestinationPattern::Exact(_)))
281    }
282
283    pub fn scope_for(&self, origin: &Origin) -> Option<DestinationScope> {
284        let entry = self.resolve(origin)?;
285        let pattern = match entry.approval {
286            ApprovalMode::ExactHost => DestinationPattern::Exact(origin.clone()),
287            ApprovalMode::WholeWildcard => entry.pattern.clone(),
288        };
289        Some(DestinationScope {
290            entry_id: entry.id.clone(),
291            entry_version: entry.version,
292            pattern,
293        })
294    }
295
296    /// Re-resolve the current winning rule. A wildcard grant never overrides a
297    /// more specific entry, even if that entry appeared after grant creation.
298    pub fn covers(&self, grant: &DestinationScope, target: &Origin) -> bool {
299        self.scope_for(target).as_ref() == Some(grant)
300    }
301}