Auto merge of #14345 - servo:cookies-host, r=jdm

Rewrite test_redirect_from_x_to_y_provides_y_cookies_from_y.

<!-- Reviewable:start -->
This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/servo/servo/14345)
<!-- Reviewable:end -->
This commit is contained in:
bors-servo 2016-11-23 08:55:54 -08:00 committed by GitHub
commit bc1e18c29e
2 changed files with 69 additions and 57 deletions

View file

@ -8,9 +8,10 @@ use std::env;
use std::fs::File; use std::fs::File;
use std::io::{BufReader, Read}; use std::io::{BufReader, Read};
use std::net::IpAddr; use std::net::IpAddr;
use std::sync::Mutex;
lazy_static! { lazy_static! {
static ref HOST_TABLE: Option<HashMap<String, IpAddr>> = create_host_table(); static ref HOST_TABLE: Mutex<Option<HashMap<String, IpAddr>>> = Mutex::new(create_host_table());
} }
fn create_host_table() -> Option<HashMap<String, IpAddr>> { fn create_host_table() -> Option<HashMap<String, IpAddr>> {
@ -34,13 +35,17 @@ fn create_host_table() -> Option<HashMap<String, IpAddr>> {
return Some(parse_hostsfile(&lines)); return Some(parse_hostsfile(&lines));
} }
pub fn replace_host_table(table: HashMap<String, IpAddr>) {
*HOST_TABLE.lock().unwrap() = Some(table);
}
pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> { pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> {
let mut host_table = HashMap::new(); let mut host_table = HashMap::new();
for line in hostsfile_content.split('\n') { for line in hostsfile_content.split('\n') {
let ip_host: Vec<&str> = line.trim().split(|c: char| c == ' ' || c == '\t').collect(); let mut ip_host = line.trim().split(|c: char| c == ' ' || c == '\t');
if ip_host.len() > 1 { if let Some(ip) = ip_host.next() {
if let Ok(address) = ip_host[0].parse::<IpAddr>() { if let Ok(address) = ip.parse::<IpAddr>() {
for token in ip_host.iter().skip(1) { for token in ip_host {
if token.as_bytes()[0] == b'#' { if token.as_bytes()[0] == b'#' {
break; break;
} }
@ -53,7 +58,7 @@ pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> {
} }
pub fn replace_hosts(url: &ServoUrl) -> ServoUrl { pub fn replace_hosts(url: &ServoUrl) -> ServoUrl {
HOST_TABLE.as_ref().map_or_else(|| url.clone(), |host_table| { HOST_TABLE.lock().unwrap().as_ref().map_or_else(|| url.clone(), |host_table| {
host_replacement(host_table, url) host_replacement(host_table, url)
}) })
} }

View file

@ -20,6 +20,7 @@ use hyper::method::Method;
use hyper::mime::{Mime, SubLevel, TopLevel}; use hyper::mime::{Mime, SubLevel, TopLevel};
use hyper::server::{Request as HyperRequest, Response as HyperResponse}; use hyper::server::{Request as HyperRequest, Response as HyperResponse};
use hyper::status::StatusCode; use hyper::status::StatusCode;
use hyper::uri::RequestUri;
use make_server; use make_server;
use msg::constellation_msg::{PipelineId, TEST_PIPELINE_ID}; use msg::constellation_msg::{PipelineId, TEST_PIPELINE_ID};
use net::cookie::Cookie; use net::cookie::Cookie;
@ -31,11 +32,13 @@ use net::test::{HttpRequest, HttpRequestFactory, HttpState, LoadError, UIProvide
use net::test::{HttpResponse, LoadErrorType}; use net::test::{HttpResponse, LoadErrorType};
use net_traits::{CookieSource, IncludeSubdomains, LoadContext, LoadData}; use net_traits::{CookieSource, IncludeSubdomains, LoadContext, LoadData};
use net_traits::{CustomResponse, LoadOrigin, Metadata, NetworkError, ReferrerPolicy}; use net_traits::{CustomResponse, LoadOrigin, Metadata, NetworkError, ReferrerPolicy};
use net_traits::hosts::replace_host_table;
use net_traits::request::{Request, RequestInit, CredentialsMode, Destination}; use net_traits::request::{Request, RequestInit, CredentialsMode, Destination};
use net_traits::response::ResponseBody; use net_traits::response::ResponseBody;
use new_fetch_context; use new_fetch_context;
use servo_url::ServoUrl; use servo_url::ServoUrl;
use std::borrow::Cow; use std::borrow::Cow;
use std::collections::HashMap;
use std::io::{self, Cursor, Read, Write}; use std::io::{self, Cursor, Read, Write};
use std::rc::Rc; use std::rc::Rc;
use std::sync::{Arc, Mutex, RwLock, mpsc}; use std::sync::{Arc, Mutex, RwLock, mpsc};
@ -1386,75 +1389,79 @@ fn test_load_errors_when_cancelled() {
#[test] #[test]
fn test_redirect_from_x_to_y_provides_y_cookies_from_y() { fn test_redirect_from_x_to_y_provides_y_cookies_from_y() {
let url_x = ServoUrl::parse("http://mozilla.com").unwrap(); let shared_url_y = Arc::new(Mutex::new(None::<ServoUrl>));
let url_y = ServoUrl::parse("http://mozilla.org").unwrap(); let shared_url_y_clone = shared_url_y.clone();
let handler = move |request: HyperRequest, mut response: HyperResponse| {
struct Factory; let path = match request.uri {
RequestUri::AbsolutePath(path) => path,
impl HttpRequestFactory for Factory { uri => panic!("Unexpected uri: {:?}", uri),
type R = MockRequest; };
if path == "/com/" {
fn create(&self, url: ServoUrl, _: Method, headers: Headers) -> Result<MockRequest, LoadError> { assert_eq!(request.headers.get(),
if url.domain().unwrap() == "mozilla.com" { Some(&CookieHeader(vec![CookiePair::new("mozillaIsNot".to_owned(), "dotOrg".to_owned())])));
let mut expected_headers_x = Headers::new(); let location = shared_url_y.lock().unwrap().as_ref().unwrap().to_string();
expected_headers_x.set_raw("Cookie".to_owned(), response.headers_mut().set(Location(location));
vec![<[_]>::to_vec("mozillaIsNot=dotCom".as_bytes())]); *response.status_mut() = StatusCode::MovedPermanently;
assert_headers_included(&expected_headers_x, &headers); response.send(b"").unwrap();
} else if path == "/org/" {
Ok(MockRequest::new( assert_eq!(request.headers.get(),
ResponseType::Redirect("http://mozilla.org".to_owned()))) Some(&CookieHeader(vec![CookiePair::new("mozillaIs".to_owned(), "theBest".to_owned())])));
} else if url.domain().unwrap() == "mozilla.org" { response.send(b"Yay!").unwrap();
let mut expected_headers_y = Headers::new(); } else {
expected_headers_y.set_raw( panic!("unexpected path {:?}", path)
"Cookie".to_owned(),
vec![<[_]>::to_vec("mozillaIs=theBest".as_bytes())]);
assert_headers_included(&expected_headers_y, &headers);
Ok(MockRequest::new(
ResponseType::Text(<[_]>::to_vec("Yay!".as_bytes()))))
} else {
panic!("unexpected host {:?}", url)
}
} }
} };
let (mut server, url) = make_server(handler);
let port = url.port().unwrap();
let load_data = LoadData::new(LoadContext::Browsing, url_x.clone(), &HttpTest); assert_eq!(url.host_str(), Some("localhost"));
let ip = "127.0.0.1".parse().unwrap();
let mut host_table = HashMap::new();
host_table.insert("mozilla.com".to_owned(), ip);
host_table.insert("mozilla.org".to_owned(), ip);
let http_state = HttpState::new(); replace_host_table(host_table);
let ui_provider = TestProvider::new();
let url_x = ServoUrl::parse(&format!("http://mozilla.com:{}/com/", port)).unwrap();
let url_y = ServoUrl::parse(&format!("http://mozilla.org:{}/org/", port)).unwrap();
*shared_url_y_clone.lock().unwrap() = Some(url_y.clone());
let context = new_fetch_context(None);
{ {
let mut cookie_jar = http_state.cookie_jar.write().unwrap(); let mut cookie_jar = context.state.cookie_jar.write().unwrap();
let cookie_x_url = url_x.clone();
let cookie_x = Cookie::new_wrapped( let cookie_x = Cookie::new_wrapped(
CookiePair::new("mozillaIsNot".to_owned(), "dotCom".to_owned()), CookiePair::new("mozillaIsNot".to_owned(), "dotOrg".to_owned()),
&cookie_x_url, &url_x,
CookieSource::HTTP CookieSource::HTTP
).unwrap(); ).unwrap();
cookie_jar.push(cookie_x, CookieSource::HTTP); cookie_jar.push(cookie_x, CookieSource::HTTP);
let cookie_y_url = url_y.clone();
let cookie_y = Cookie::new_wrapped( let cookie_y = Cookie::new_wrapped(
CookiePair::new("mozillaIs".to_owned(), "theBest".to_owned()), CookiePair::new("mozillaIs".to_owned(), "theBest".to_owned()),
&cookie_y_url, &url_y,
CookieSource::HTTP CookieSource::HTTP
).unwrap(); ).unwrap();
cookie_jar.push(cookie_y, CookieSource::HTTP); cookie_jar.push(cookie_y, CookieSource::HTTP);
} }
match load(&load_data, let request = Request::from_init(RequestInit {
&ui_provider, &http_state, url: url_x.clone(),
None, method: Method::Get,
&Factory, destination: Destination::Document,
DEFAULT_USER_AGENT.into(), origin: url_x.clone(),
&CancellationListener::new(None), None) { pipeline_id: Some(TEST_PIPELINE_ID),
Err(e) => panic!("expected to follow a redirect {:?}", e), credentials_mode: CredentialsMode::Include,
Ok(mut lr) => { .. RequestInit::default()
let response = read_response(&mut lr); });
assert_eq!(response, "Yay!".to_owned()); let response = fetch(Rc::new(request), &mut None, &context);
}
} let _ = server.close();
let response = response.to_actual();
assert!(response.status.unwrap().is_success());
assert_eq!(*response.body.lock().unwrap(),
ResponseBody::Done(b"Yay!".to_vec()));
} }
#[test] #[test]