Repository navigation
Expand file tree
/
Copy pathredirect.rs
More file actions
310 lines (283 loc) · 10.2 KB
/
Copy pathredirect.rs
File metadata and controls
310 lines (283 loc) · 10.2 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
use std::collections::BTreeSet;
use std::fmt;
use std::time::Duration;
use originweave_core::Origin;
use crate::{DestinationError, FreshResolutionSnapshot};
/// The largest redirect chain accepted by the destination kernel.
pub const MAX_REDIRECT_HOPS: u8 = 20;
/// A lowercase SHA-256 digest of one complete canonical redirect target URI.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RedirectTargetDigest {
canonical: String,
}
impl RedirectTargetDigest {
/// Parse `sha256:` followed by exactly 64 lowercase hexadecimal digits.
pub fn parse(input: &str) -> Result<Self, RedirectTargetDigestError> {
let Some(hexadecimal) = input.strip_prefix("sha256:") else {
return Err(RedirectTargetDigestError::InvalidFormat);
};
if hexadecimal.len() != 64
|| !hexadecimal
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
{
return Err(RedirectTargetDigestError::InvalidFormat);
}
Ok(Self {
canonical: input.to_owned(),
})
}
/// Return the canonical redirect-target digest.
#[must_use]
pub fn as_str(&self) -> &str {
&self.canonical
}
}
/// A validation error for a redirect-target digest.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RedirectTargetDigestError {
/// The value was not a canonical lowercase SHA-256 identifier.
InvalidFormat,
}
impl fmt::Display for RedirectTargetDigestError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidFormat => formatter.write_str(
"redirect target digest must be sha256: followed by 64 lowercase hexadecimal digits",
),
}
}
}
impl std::error::Error for RedirectTargetDigestError {}
/// A deterministic reason that redirect authorization failed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RedirectError {
/// The configured maximum was zero or exceeded [`MAX_REDIRECT_HOPS`].
InvalidMaximumHops {
/// The rejected maximum hop count.
maximum_hops: u8,
},
/// The redirect chain reached its configured maximum.
RedirectLimitExceeded,
/// The target origin was not present in the explicit read-origin grant.
OriginNotGranted {
/// The ungranted target origin.
origin: Origin,
},
/// The supplied resolution snapshot belongs to another origin.
ResolutionOriginMismatch {
/// The redirect target origin.
target_origin: Origin,
/// The origin bound to the resolution snapshot.
resolution_origin: Origin,
},
/// The supplied resolution authority is not fresh at the requested use time.
ResolutionFreshnessDenied {
/// The destination-layer freshness failure.
error: DestinationError,
},
/// An HTTPS request attempted to redirect to HTTP.
InsecureSchemeDowngrade {
/// The secure source origin.
source_origin: Origin,
/// The insecure target origin.
target_origin: Origin,
},
/// The complete canonical target URI already appeared in the chain.
RedirectCycle {
/// The repeated target digest.
target_digest: RedirectTargetDigest,
},
}
impl fmt::Display for RedirectError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidMaximumHops { maximum_hops } => write!(
formatter,
"redirect maximum {maximum_hops} is outside 1..={MAX_REDIRECT_HOPS}",
),
Self::RedirectLimitExceeded => formatter.write_str("redirect limit exceeded"),
Self::OriginNotGranted { origin } => {
write!(formatter, "redirect target origin is not granted: {origin}")
}
Self::ResolutionOriginMismatch {
target_origin,
resolution_origin,
} => write!(
formatter,
"redirect resolution origin {resolution_origin} does not match target {target_origin}",
),
Self::ResolutionFreshnessDenied { error } => {
write!(formatter, "redirect resolution freshness denied: {error}")
}
Self::InsecureSchemeDowngrade {
source_origin,
target_origin,
} => write!(
formatter,
"insecure redirect downgrade from {source_origin} to {target_origin}",
),
Self::RedirectCycle { target_digest } => write!(
formatter,
"redirect target was already visited: {}",
target_digest.as_str(),
),
}
}
}
impl std::error::Error for RedirectError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::ResolutionFreshnessDenied { error } => Some(error),
_ => None,
}
}
}
/// Stateful redirect authorization for one bounded navigation chain.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RedirectGuard {
current_origin: Origin,
maximum_hops: u8,
hop_count: u8,
seen_targets: BTreeSet<RedirectTargetDigest>,
}
impl RedirectGuard {
/// Start a redirect chain at one approved origin and canonical target URI.
pub fn new(
initial_origin: Origin,
initial_target_digest: RedirectTargetDigest,
maximum_hops: u8,
) -> Result<Self, RedirectError> {
if maximum_hops == 0 || maximum_hops > MAX_REDIRECT_HOPS {
return Err(RedirectError::InvalidMaximumHops { maximum_hops });
}
Ok(Self {
current_origin: initial_origin,
maximum_hops,
hop_count: 0,
seen_targets: BTreeSet::from([initial_target_digest]),
})
}
/// Return the origin that currently owns the redirect chain.
#[must_use]
pub const fn current_origin(&self) -> &Origin {
&self.current_origin
}
/// Return the number of authorized redirects already consumed.
#[must_use]
pub const fn hop_count(&self) -> u8 {
self.hop_count
}
/// Return the configured maximum redirect count.
#[must_use]
pub const fn maximum_hops(&self) -> u8 {
self.maximum_hops
}
/// Authorize the next redirect after origin, DNS policy, and freshness evaluation.
///
/// `current_time` must come from the same trusted monotonic clock domain as
/// `target_resolution`. Freshness is checked before any redirect-chain state
/// is advanced.
pub fn authorize_redirect(
&mut self,
target_origin: Origin,
target_digest: RedirectTargetDigest,
target_resolution: &FreshResolutionSnapshot,
current_time: Duration,
readable_origins: &BTreeSet<Origin>,
) -> Result<RedirectEvidence, RedirectError> {
if self.hop_count >= self.maximum_hops {
return Err(RedirectError::RedirectLimitExceeded);
}
if !readable_origins.contains(&target_origin) {
return Err(RedirectError::OriginNotGranted {
origin: target_origin,
});
}
if target_resolution.origin() != &target_origin {
return Err(RedirectError::ResolutionOriginMismatch {
target_origin,
resolution_origin: target_resolution.origin().clone(),
});
}
validate_resolution_freshness(target_resolution, current_time)
.map_err(|error| RedirectError::ResolutionFreshnessDenied { error })?;
if is_https(&self.current_origin) && !is_https(&target_origin) {
return Err(RedirectError::InsecureSchemeDowngrade {
source_origin: self.current_origin.clone(),
target_origin,
});
}
if self.seen_targets.contains(&target_digest) {
return Err(RedirectError::RedirectCycle { target_digest });
}
let evidence = RedirectEvidence {
hop_number: self.hop_count + 1,
source_origin: self.current_origin.clone(),
target_origin: target_origin.clone(),
target_digest: target_digest.clone(),
approved_address_count: target_resolution.addresses().len(),
};
self.hop_count += 1;
self.current_origin = target_origin;
self.seen_targets.insert(target_digest);
Ok(evidence)
}
}
fn validate_resolution_freshness(
target_resolution: &FreshResolutionSnapshot,
current_time: Duration,
) -> Result<(), DestinationError> {
if current_time < target_resolution.approved_at() {
return Err(DestinationError::ResolutionUseBeforeApproval {
approved_at: target_resolution.approved_at(),
current_time,
});
}
if current_time >= target_resolution.valid_until() {
return Err(DestinationError::ResolutionApprovalExpired {
valid_until: target_resolution.valid_until(),
current_time,
});
}
Ok(())
}
fn is_https(origin: &Origin) -> bool {
origin.as_str().starts_with("https://")
}
/// Credential-free evidence for one approved redirect hop.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RedirectEvidence {
hop_number: u8,
source_origin: Origin,
target_origin: Origin,
target_digest: RedirectTargetDigest,
approved_address_count: usize,
}
impl RedirectEvidence {
/// Return the one-based redirect hop number.
#[must_use]
pub const fn hop_number(&self) -> u8 {
self.hop_number
}
/// Return the origin that emitted the redirect.
#[must_use]
pub const fn source_origin(&self) -> &Origin {
&self.source_origin
}
/// Return the separately authorized redirect target origin.
#[must_use]
pub const fn target_origin(&self) -> &Origin {
&self.target_origin
}
/// Return the digest of the complete canonical target URI.
#[must_use]
pub const fn target_digest(&self) -> &RedirectTargetDigest {
&self.target_digest
}
/// Return the number of addresses approved for the redirect target.
#[must_use]
pub const fn approved_address_count(&self) -> usize {
self.approved_address_count
}
}