1use crate::{
18 error::{ErrorKind, ParseError, Result, WriteError, err},
19 host::{Host, HostPort, host_port},
20 text::{skip_ows, trim_ows},
21 write::{CountSink, Sink, reserve, write_decimal_u64},
22};
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
36pub enum OriginValue<'a> {
37 Null,
40 Origin(Origin<'a>),
42}
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
57pub struct Origin<'a> {
58 pub scheme: &'a [u8],
60 pub host: Host<'a>,
62 pub port: Option<u16>,
64}
65
66impl Origin<'_> {
67 #[must_use]
80 pub fn effective_port(&self) -> Option<u16> {
81 self.port.or_else(|| {
82 let s = self.scheme;
83 if s.eq_ignore_ascii_case(b"http") || s.eq_ignore_ascii_case(b"ws") {
84 Some(80)
85 } else if s.eq_ignore_ascii_case(b"https") || s.eq_ignore_ascii_case(b"wss") {
86 Some(443)
87 } else {
88 None
89 }
90 })
91 }
92
93 #[must_use]
109 pub fn same_origin(&self, other: &Origin<'_>) -> bool {
110 self.scheme.eq_ignore_ascii_case(other.scheme)
111 && self.host.eq_ignore_ascii_case(&other.host)
112 && self.effective_port() == other.effective_port()
113 }
114
115 pub fn write_to(&self, out: &mut impl Sink) -> core::result::Result<(), WriteError> {
135 let mut count = CountSink::new();
136 self.put(&mut count)?;
137 reserve(out, count.count())?;
138 self.put(out)
139 }
140
141 fn put(&self, out: &mut impl Sink) -> core::result::Result<(), WriteError> {
142 let mut scheme = [0u8; 32];
143 for chunk in self.scheme.chunks(scheme.len()) {
144 let dst = scheme.get_mut(..chunk.len()).unwrap_or(&mut []);
145 for (d, &c) in dst.iter_mut().zip(chunk) {
146 *d = c.to_ascii_lowercase();
147 }
148 out.put(dst)?;
149 }
150 out.put(b"://")?;
151 HostPort {
152 host: self.host,
153 port: None,
154 empty_port: false,
155 }
156 .write_to(out)?;
157 let default = Origin {
158 port: None,
159 ..*self
160 }
161 .effective_port();
162 if let Some(p) = self.port.filter(|&p| Some(p) != default) {
163 out.put(b":")?;
164 write_decimal_u64(u64::from(p), out)?;
165 }
166 Ok(())
167 }
168}
169
170pub fn parse_origin(value: &[u8]) -> Result<OriginValue<'_>> {
191 let lead = skip_ows(value);
192 let v = trim_ows(value);
193 if v == b"null" {
194 return Ok(OriginValue::Null);
195 }
196 let scheme_len = v
197 .iter()
198 .take_while(|&&b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'))
199 .count();
200 if scheme_len == 0 || !v.first().is_some_and(u8::is_ascii_alphabetic) {
201 return err(ErrorKind::InvalidOrigin, lead);
202 }
203 let scheme = v.get(..scheme_len).unwrap_or(&[]);
204 if v.get(scheme_len..scheme_len + 3) != Some(b"://") {
205 return err(ErrorKind::InvalidOrigin, lead + scheme_len);
206 }
207 let authority_at = scheme_len + 3;
208 let authority = v.get(authority_at..).unwrap_or(&[]);
209 if let Some(i) = authority
210 .iter()
211 .position(|&b| matches!(b, b'/' | b'?' | b'#'))
212 {
213 return err(ErrorKind::InvalidOrigin, lead + authority_at + i);
214 }
215 let hp = host_port(authority).map_err(|e: ParseError| e.shifted(lead + authority_at))?;
216 if hp.host.is_empty() || hp.empty_port {
217 return err(ErrorKind::InvalidOrigin, lead + authority_at);
218 }
219 Ok(OriginValue::Origin(Origin {
220 scheme,
221 host: hp.host,
222 port: hp.port,
223 }))
224}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229
230 fn o(v: &[u8]) -> Origin<'_> {
231 match parse_origin(v).unwrap() {
232 OriginValue::Origin(o) => o,
233 OriginValue::Null => panic!("null"),
234 }
235 }
236
237 #[test]
238 fn test_origin_edge_cases() {
239 let k = |v: &[u8]| parse_origin(v).unwrap_err().kind();
240 assert_eq!(k(b"Null"), ErrorKind::InvalidOrigin);
241 assert_eq!(o(b"https://a.com").port, None);
242 assert_eq!(o(b"https://a.com:443").port, Some(443));
243 assert_eq!(k(b"https://a.com/"), ErrorKind::InvalidOrigin);
244 assert_eq!(k(b"https://a.com:"), ErrorKind::InvalidOrigin);
245 assert_eq!(k(b"https://user@a.com"), ErrorKind::InvalidHost);
246 assert_eq!(o(b"HTTPS://A.COM").scheme, b"HTTPS");
247 assert_eq!(k(b"file://"), ErrorKind::InvalidOrigin);
248 assert_eq!(k(b"https:a.com"), ErrorKind::InvalidOrigin);
249 assert_eq!(k(b"1https://a.com"), ErrorKind::InvalidOrigin);
250 assert_eq!(k(b"https://a.com?x"), ErrorKind::InvalidOrigin);
251 assert_eq!(k(b""), ErrorKind::InvalidOrigin);
252 assert!(matches!(o(b"http://[::1]:8080").host, Host::V6(_)));
253 let long = [b"https://".as_slice(), &[b'a'; 4096]].concat();
254 assert!(parse_origin(&long).is_ok());
255 }
256
257 #[test]
258 fn test_origin_suffix_attack_not_same() {
259 let a = o(b"https://example.com");
260 assert!(!a.same_origin(&o(b"https://example.com.evil.test")));
261 assert!(!a.same_origin(&o(b"https://evilexample.com")));
262 assert!(!a.same_origin(&o(b"http://example.com")));
263 assert!(!a.same_origin(&o(b"https://example.com:8443")));
264 assert!(a.same_origin(&o(b"https://EXAMPLE.com:443")));
265 }
266
267 #[test]
268 fn test_origin_trailing_slash_refused() {
269 assert_eq!(
270 parse_origin(b"https://example.com/").unwrap_err().kind(),
271 ErrorKind::InvalidOrigin
272 );
273 }
274
275 #[test]
276 fn test_origin_write() {
277 let mut buf = [0u8; 64];
278 let mut out = crate::SliceSink::new(&mut buf);
279 o(b"HTTP://[::1]:8080").write_to(&mut out).unwrap();
280 assert_eq!(out.written(), b"http://[::1]:8080");
281 assert_eq!(o(b"x-app://a").effective_port(), None);
282 }
283}