use std::fmt;
use percent_encoding::percent_decode_str;
use serde::Serialize;
use serde_json::Value;
use url::Url;
pub const CREDENTIALS_METHOD: &str = "Target.setProxyCredentials";
pub const CREATE_CONTEXT_METHOD: &str = "Target.createBrowserContext";
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
InvalidServer {
server: String,
reason: String,
},
MissingServer,
Unauthenticated {
server: String,
},
UnsupportedScheme {
server: String,
},
UndecodableCredential {
field: &'static str,
},
TooLong {
field: &'static str,
len: usize,
max: usize,
},
RegistrationRefused {
detail: String,
},
MissingMainFrame {
detail: String,
},
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::InvalidServer { server, reason } => {
write!(f, "unparseable proxy server {server:?}: {reason}")
}
Error::MissingServer => f.write_str("proxy requires a server"),
Error::Unauthenticated { server } => write!(
f,
"per-context preregistration needs a username and password; an \
unauthenticated proxy ({server}) can be passed straight to the driver"
),
Error::UnsupportedScheme { server } => write!(
f,
"credential preregistration requires an HTTP(S) proxy, got {server}"
),
Error::UndecodableCredential { field } => write!(
f,
"the {field} in the proxy URL percent-decodes to bytes that are not UTF-8; \
pass it as an explicit credential instead of embedding it in the URL"
),
Error::TooLong { field, len, max } => {
write!(
f,
"{field} is {len} bytes; the browser accepts at most {max}"
)
}
Error::RegistrationRefused { detail } => {
write!(f, "proxy credential registration refused: {detail}")
}
Error::MissingMainFrame { detail } => {
write!(
f,
"this page session named no main frame, so main-frame and subframe \
lifecycle cannot be told apart: {detail}"
)
}
}
}
}
impl std::error::Error for Error {}
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct ProxySpec {
server: String,
username: Option<String>,
password: Option<String>,
}
impl fmt::Debug for ProxySpec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProxySpec")
.field("server", &self.server)
.field("username", &self.username)
.field("password", &self.password.as_ref().map(|_| "<redacted>"))
.finish()
}
}
impl ProxySpec {
pub fn new(
server: impl AsRef<str>,
username: Option<&str>,
password: Option<&str>,
) -> Result<Self> {
let username = username.map(str::to_string);
let password = password.map(str::to_string);
let server = server.as_ref();
if username.is_none() && password.is_none() && server.contains('@') {
return ProxySpec::parse(server);
}
Ok(ProxySpec {
server: normalize_server(server)?,
username,
password,
})
}
pub fn parse(url: &str) -> Result<Self> {
let raw = url.trim();
let scheme_len = scheme_prefix_len(raw);
let rest = &raw[scheme_len..];
let authority_len = rest.find(['/', '?', '#']).unwrap_or(rest.len());
let authority = &rest[..authority_len];
let (username, password, server) = match authority.rfind('@') {
None => (None, None, raw.to_string()),
Some(at) => {
let cred = &authority[..at];
let (user, pass) = match cred.find(':') {
None => (decode(cred, "username")?, None),
Some(colon) => (
decode(&cred[..colon], "username")?,
Some(decode(&cred[colon + 1..], "password")?),
),
};
let mut server = String::with_capacity(raw.len());
server.push_str(&raw[..scheme_len]);
server.push_str(&raw[scheme_len + at + 1..]);
(Some(user), pass, server)
}
};
Ok(ProxySpec {
server: normalize_server(&server)?,
username,
password,
})
}
pub fn server(&self) -> &str {
&self.server
}
pub fn username(&self) -> Option<&str> {
self.username.as_deref()
}
pub fn password(&self) -> Option<&str> {
self.password.as_deref()
}
pub fn authenticated(&self) -> bool {
self.username.as_deref().is_some_and(|u| !u.is_empty()) && self.password.is_some()
}
pub fn credentials_params(&self) -> CredentialsParams<'_> {
CredentialsParams {
proxy_server: &self.server,
username: self.username.as_deref().unwrap_or(""),
password: self.password.as_deref().unwrap_or(""),
credentials_id: None,
}
}
pub fn create_context_params(&self) -> CreateContextParams<'_> {
CreateContextParams {
proxy_server: &self.server,
proxy_credentials_id: None,
}
}
pub fn check_registrable(&self) -> Result<()> {
if !self.authenticated() {
return Err(Error::Unauthenticated {
server: self.server.clone(),
});
}
if !(self.server.starts_with("http://") || self.server.starts_with("https://")) {
return Err(Error::UnsupportedScheme {
server: self.server.clone(),
});
}
check_len("server", self.server.len(), MAX_SERVER_BYTES)?;
check_len(
"username",
self.username.as_deref().unwrap_or("").len(),
MAX_CREDENTIAL_BYTES,
)?;
check_len(
"password",
self.password.as_deref().unwrap_or("").len(),
MAX_CREDENTIAL_BYTES,
)?;
Ok(())
}
}
#[derive(Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CredentialsParams<'a> {
pub proxy_server: &'a str,
pub username: &'a str,
pub password: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
pub credentials_id: Option<&'a str>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateContextParams<'a> {
pub proxy_server: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
pub proxy_credentials_id: Option<&'a str>,
}
impl fmt::Debug for CredentialsParams<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CredentialsParams")
.field("proxy_server", &self.proxy_server)
.field("username", &self.username)
.field("password", &"<redacted>")
.field("credentials_id", &self.credentials_id)
.finish()
}
}
impl<'a> CredentialsParams<'a> {
pub fn with_credentials_id(mut self, id: &'a str) -> Self {
self.credentials_id = Some(id);
self
}
pub fn to_value(self) -> Value {
let mut params = serde_json::json!({
"proxyServer": self.proxy_server,
"username": self.username,
"password": self.password,
});
if let Some(id) = self.credentials_id {
params["credentialsId"] = Value::String(id.to_string());
}
params
}
}
impl<'a> CreateContextParams<'a> {
pub fn with_credentials_id(mut self, id: &'a str) -> Self {
self.proxy_credentials_id = Some(id);
self
}
pub fn to_value(self) -> Value {
let mut params = serde_json::json!({ "proxyServer": self.proxy_server });
if let Some(id) = self.proxy_credentials_id {
params["proxyCredentialsId"] = Value::String(id.to_string());
}
params
}
}
const MAX_SERVER_BYTES: usize = 2048;
const MAX_CREDENTIAL_BYTES: usize = 1024;
impl std::str::FromStr for ProxySpec {
type Err = Error;
fn from_str(url: &str) -> Result<Self> {
ProxySpec::parse(url)
}
}
impl TryFrom<&str> for ProxySpec {
type Error = Error;
fn try_from(url: &str) -> Result<Self> {
ProxySpec::parse(url)
}
}
impl fmt::Display for ProxySpec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.server)
}
}
pub trait IntoProxySpec {
fn into_proxy_spec(self) -> Result<ProxySpec>;
}
impl IntoProxySpec for ProxySpec {
fn into_proxy_spec(self) -> Result<ProxySpec> {
Ok(self)
}
}
impl IntoProxySpec for &ProxySpec {
fn into_proxy_spec(self) -> Result<ProxySpec> {
Ok(self.clone())
}
}
impl IntoProxySpec for &str {
fn into_proxy_spec(self) -> Result<ProxySpec> {
ProxySpec::parse(self)
}
}
impl IntoProxySpec for &String {
fn into_proxy_spec(self) -> Result<ProxySpec> {
ProxySpec::parse(self)
}
}
impl IntoProxySpec for String {
fn into_proxy_spec(self) -> Result<ProxySpec> {
ProxySpec::parse(&self)
}
}
impl<S, U, P> IntoProxySpec for (S, U, P)
where
S: AsRef<str>,
U: Into<String>,
P: Into<String>,
{
fn into_proxy_spec(self) -> Result<ProxySpec> {
let username = self.1.into();
let password = self.2.into();
ProxySpec::new(self.0, Some(&username), Some(&password))
}
}
pub fn normalize_server(server: &str) -> Result<String> {
let raw = server.trim();
if raw.is_empty() {
return Err(Error::MissingServer);
}
let scheme_len = scheme_prefix_len(raw);
let with_scheme = if scheme_len > 0 {
raw.to_string()
} else {
if raw.contains("://") {
return Err(Error::InvalidServer {
server: redact_userinfo(raw),
reason: "a scheme is present but unreadable — check for a leading \
invisible character"
.to_string(),
});
}
format!("http://{raw}")
};
let url = Url::parse(&with_scheme).map_err(|e| Error::InvalidServer {
server: redact_userinfo(server),
reason: e.to_string(),
})?;
let host = url.host_str().ok_or_else(|| Error::InvalidServer {
server: redact_userinfo(server),
reason: "no host".to_string(),
})?;
if host.is_empty() {
return Err(Error::InvalidServer {
server: redact_userinfo(server),
reason: "empty host".to_string(),
});
}
Ok(match url.port() {
Some(port) => format!("{}://{}:{}", url.scheme(), host, port),
None => format!("{}://{}", url.scheme(), host),
})
}
pub fn parse_proxy(proxy: impl IntoProxySpec) -> Result<ProxySpec> {
proxy.into_proxy_spec()
}
pub fn check_registration(result: &Value) -> Result<()> {
match result.get("error") {
Some(err) if !err.is_null() => Err(Error::RegistrationRefused {
detail: err.to_string(),
}),
_ => Ok(()),
}
}
fn redact_userinfo(server: &str) -> String {
let scheme_len = scheme_prefix_len(server);
let rest = &server[scheme_len..];
let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
match rest[..authority_end].rfind('@') {
Some(at) => format!("{}<redacted>@{}", &server[..scheme_len], &rest[at + 1..]),
None => server.to_string(),
}
}
fn check_len(field: &'static str, len: usize, max: usize) -> Result<()> {
if len > max {
return Err(Error::TooLong { field, len, max });
}
Ok(())
}
fn scheme_prefix_len(s: &str) -> usize {
let bytes = s.as_bytes();
if bytes.is_empty() || !bytes[0].is_ascii_alphabetic() {
return 0;
}
let mut i = 1;
while i < bytes.len()
&& (bytes[i].is_ascii_alphanumeric() || matches!(bytes[i], b'+' | b'-' | b'.'))
{
i += 1;
}
if s[i..].starts_with("://") {
i + 3
} else {
0
}
}
fn decode(s: &str, field: &'static str) -> Result<String> {
percent_decode_str(s)
.decode_utf8()
.map(|decoded| decoded.into_owned())
.map_err(|_| Error::UndecodableCredential { field })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scheme_prefix_needs_the_slashes() {
assert_eq!(scheme_prefix_len("http://gw"), 7);
assert_eq!(scheme_prefix_len("HTTP://gw"), 7);
assert_eq!(scheme_prefix_len("socks5://gw"), 9);
assert_eq!(scheme_prefix_len("gw:12321"), 0); assert_eq!(scheme_prefix_len("1http://gw"), 0);
assert_eq!(scheme_prefix_len(""), 0);
}
#[test]
fn credentials_render_empty_when_absent() {
let spec = ProxySpec::parse("http://gw:12321").unwrap();
let params = spec.credentials_params();
assert_eq!(params.username, "");
assert_eq!(params.password, "");
assert_eq!(params.proxy_server, "http://gw:12321");
}
#[test]
fn an_invisible_character_before_the_scheme_is_an_error_not_a_new_host() {
let bom = ProxySpec::parse("\u{feff}http://gw.example.com:12321");
assert!(matches!(bom, Err(Error::InvalidServer { .. })), "{bom:?}");
assert!(ProxySpec::parse("\"http://gw:1\"").is_err());
assert_eq!(
ProxySpec::parse("gw.example.com:12321").unwrap().server(),
"http://gw.example.com:12321"
);
}
#[test]
fn a_password_never_reaches_a_log_line() {
let spec = ProxySpec::parse("http://user:hunter2@gw:12321").unwrap();
let rendered = format!("{spec:?}");
assert!(!rendered.contains("hunter2"), "{rendered}");
assert!(rendered.contains("<redacted>"), "{rendered}");
assert!(rendered.contains("user"), "the username is not the secret");
let params = format!("{:?}", spec.credentials_params());
assert!(!params.contains("hunter2"), "{params}");
assert_eq!(spec.credentials_params().to_value()["password"], "hunter2");
}
#[test]
fn an_unparseable_server_does_not_echo_its_credentials() {
let via_parse = ProxySpec::parse("http://user:hunter2@gw:notaport")
.unwrap_err()
.to_string();
assert!(!via_parse.contains("hunter2"), "{via_parse}");
let direct = normalize_server("http://user:hunter2@gw:notaport")
.unwrap_err()
.to_string();
assert!(!direct.contains("hunter2"), "{direct}");
assert!(direct.contains("<redacted>"), "{direct}");
}
#[test]
fn check_registration_only_trips_on_an_error_member() {
assert!(check_registration(&serde_json::json!({})).is_ok());
assert!(check_registration(&serde_json::json!({"error": null})).is_ok());
assert!(check_registration(&serde_json::json!({"browserContextId": "x"})).is_ok());
assert!(matches!(
check_registration(&serde_json::json!({"error": {"code": -32000}})),
Err(Error::RegistrationRefused { .. })
));
}
}