use std::{
collections::HashSet,
env,
io::{BufReader, Cursor},
path::{Path, PathBuf},
};
#[cfg(unix)]
use async_fs::unix::OpenOptionsExt as _;
use cookie_store::{CookieStore, RawCookie};
use futures_util::AsyncWriteExt as _;
use serde::{Deserialize, Serialize};
use tez::{HeaderName, HeaderValue, Response, header};
use crate::{
args::Args,
command_auth::Credentials,
error::{Error, Result},
};
const MAX_SESSION_SIZE: u64 = 16 * 1024 * 1024;
const SESSION_FILE_VERSION: u8 = 1;
pub(crate) struct Session {
path: Option<PathBuf>,
read_only: bool,
dirty: bool,
contents: StoredSession,
}
#[derive(Deserialize, Serialize)]
struct StoredSession {
#[serde(default = "session_file_version")]
version: u8,
#[serde(default)]
headers: Vec<StoredHeader>,
#[serde(default)]
auth: Option<Credentials>,
#[serde(default = "empty_cookies")]
cookies: serde_json::Value,
}
impl Default for StoredSession {
fn default() -> Self {
Self {
version: SESSION_FILE_VERSION,
headers: Vec::new(),
auth: None,
cookies: empty_cookies(),
}
}
}
#[derive(Deserialize, Serialize)]
struct StoredHeader {
name: String,
value: String,
}
impl Session {
pub(crate) async fn open(args: &Args, url: &str) -> Result<Self> {
let (specification, read_only) = match (&args.session, &args.session_read_only) {
(Some(value), None) => (Some(value.as_str()), false),
(None, Some(value)) => (Some(value.as_str()), true),
(None, None) => (None, false),
(Some(_), Some(_)) => unreachable!("clap rejects conflicting session options"),
};
let Some(specification) = specification else {
return Ok(Self::empty());
};
let path = session_path(specification, url)?;
let contents = match async_fs::metadata(&path).await {
Ok(metadata) => {
if metadata.len() > MAX_SESSION_SIZE {
return Err(Error::usage("session file is too large"));
}
let bytes = async_fs::read(&path)
.await
.map_err(|_| Error::usage("session file could not be read"))?;
let contents = serde_json::from_slice::<StoredSession>(&bytes)
.map_err(|_| Error::usage("session file is invalid"))?;
validate(&contents)?;
contents
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => StoredSession {
version: SESSION_FILE_VERSION,
..StoredSession::default()
},
Err(_) => return Err(Error::usage("session file could not be read")),
};
Ok(Self {
path: Some(path),
read_only,
dirty: false,
contents,
})
}
pub(crate) fn headers(&self) -> Result<Vec<(HeaderName, HeaderValue)>> {
self.contents
.headers
.iter()
.map(|header| {
let name = header
.name
.parse::<HeaderName>()
.map_err(|_| Error::usage("session header name is invalid"))?;
let value = HeaderValue::try_from(header.value.as_str())
.map_err(|_| Error::usage("session header value is invalid"))?;
Ok((name, value))
})
.collect()
}
pub(crate) fn auth(&self) -> Option<Credentials> {
self.contents.auth.clone()
}
pub(crate) fn cookie_header(&self, url: &str) -> Option<HeaderValue> {
let url = url::Url::parse(url).ok()?;
let store = cookie_store(&self.contents.cookies).ok()?;
let values = store
.get_request_values(&url)
.map(|(name, value)| format!("{name}={value}"))
.collect::<Vec<_>>();
HeaderValue::try_from(values.join("; "))
.ok()
.filter(|_| !values.is_empty())
}
pub(crate) fn remember(
&mut self,
headers: impl IntoIterator<Item = (String, Option<String>)>,
auth: Option<&Credentials>,
) {
if self.path.is_none() || self.read_only {
return;
}
let headers = headers.into_iter().collect::<Vec<_>>();
let touched = headers
.iter()
.map(|(name, _)| name.as_str())
.collect::<HashSet<_>>();
self.contents
.headers
.retain(|header| !touched.contains(header.name.as_str()));
let mut replacements = Vec::new();
for (name, value) in headers {
match value {
Some(value) => replacements.push(StoredHeader { name, value }),
None => replacements.retain(|header: &StoredHeader| header.name != name),
}
}
self.contents.headers.extend(replacements);
if let Some(auth) = auth {
self.contents.auth = Some(auth.clone());
}
self.dirty = true;
}
pub(crate) fn store_response(&mut self, response: &Response) {
if self.path.is_none() || self.read_only {
return;
}
let cookies = response
.headers()
.get_all(header::SET_COOKIE)
.iter()
.filter_map(|value| value.to_str().ok())
.filter_map(|value| RawCookie::parse(value.to_owned()).ok())
.collect::<Vec<_>>();
if cookies.is_empty() {
return;
}
if let Ok(mut store) = cookie_store(&self.contents.cookies) {
if let Ok(url) = url::Url::parse(&response.url().to_string()) {
store.store_response_cookies(cookies.into_iter(), &url);
} else {
return;
}
if let Ok(cookies) = stored_cookies(&store) {
self.contents.cookies = cookies;
self.dirty = true;
}
}
}
pub(crate) async fn save(&mut self) -> Result<()> {
if !self.dirty || self.read_only {
return Ok(());
}
let Some(path) = &self.path else {
return Ok(());
};
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.ok_or_else(|| Error::usage("session path has no parent directory"))?;
async_fs::create_dir_all(parent)
.await
.map_err(|_| Error::usage("session directory could not be created"))?;
let bytes = serde_json::to_vec_pretty(&self.contents)
.map_err(|_| Error::usage("session file could not be written"))?;
write_session_file(path, &bytes).await?;
self.dirty = false;
Ok(())
}
fn empty() -> Self {
Self {
path: None,
read_only: true,
dirty: false,
contents: StoredSession {
version: SESSION_FILE_VERSION,
..StoredSession::default()
},
}
}
}
fn validate(contents: &StoredSession) -> Result<()> {
if contents.version != SESSION_FILE_VERSION {
return Err(Error::usage("session file version is unsupported"));
}
let _ = cookie_store(&contents.cookies)?;
for header in &contents.headers {
let _ = header
.name
.parse::<HeaderName>()
.map_err(|_| Error::usage("session header name is invalid"))?;
let _ = HeaderValue::try_from(header.value.as_str())
.map_err(|_| Error::usage("session header value is invalid"))?;
}
Ok(())
}
fn cookie_store(cookies: &serde_json::Value) -> Result<CookieStore> {
let bytes =
serde_json::to_vec(cookies).map_err(|_| Error::usage("session cookies are invalid"))?;
cookie_store::serde::json::load_all(BufReader::new(Cursor::new(bytes)))
.map_err(|_| Error::usage("session cookies are invalid"))
}
fn stored_cookies(store: &CookieStore) -> Result<serde_json::Value> {
let mut bytes = Vec::new();
cookie_store::serde::json::save_incl_expired_and_nonpersistent(store, &mut bytes)
.map_err(|_| Error::usage("session cookies could not be saved"))?;
serde_json::from_slice(&bytes).map_err(|_| Error::usage("session cookies could not be saved"))
}
fn empty_cookies() -> serde_json::Value {
serde_json::Value::Array(Vec::new())
}
const fn session_file_version() -> u8 {
SESSION_FILE_VERSION
}
fn session_path(specification: &str, url: &str) -> Result<PathBuf> {
let path = Path::new(specification);
if path.is_absolute() || specification.contains(['/', '\\']) || specification.starts_with('.') {
return Ok(path.to_path_buf());
}
if specification.is_empty()
|| !specification
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
{
return Err(Error::usage(
"session name may contain only letters, numbers, '-' and '_'",
));
}
let url = url::Url::parse(url).map_err(|_| Error::usage("session URL is invalid"))?;
let scheme = filesystem_component(url.scheme());
let host = normalized_host(&url)?;
let host = filesystem_component(&host);
let port = url
.port_or_known_default()
.ok_or_else(|| Error::usage("session URL has no effective port"))?;
Ok(config_directory()?
.join("tez")
.join("sessions")
.join(scheme)
.join(host)
.join(filesystem_component(&port.to_string()))
.join(format!("{specification}.json")))
}
fn normalized_host(url: &url::Url) -> Result<String> {
match url.host() {
Some(url::Host::Domain(host)) => {
let host = host.trim_end_matches('.');
if host.is_empty() {
Err(Error::usage("session URL has no host"))
} else {
Ok(host.to_ascii_lowercase())
}
}
Some(url::Host::Ipv4(address)) => Ok(address.to_string()),
Some(url::Host::Ipv6(address)) => Ok(address.to_string()),
None => Err(Error::usage("session URL has no host")),
}
}
fn filesystem_component(value: &str) -> String {
const HEX: &[u8; 16] = b"0123456789ABCDEF";
let mut encoded = String::with_capacity(value.len() + 1);
encoded.push('_');
for byte in value.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.') {
encoded.push(char::from(byte));
} else {
encoded.push('%');
encoded.push(char::from(HEX[usize::from(byte >> 4)]));
encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
}
}
encoded
}
fn config_directory() -> Result<PathBuf> {
if let Some(directory) = env::var_os("XDG_CONFIG_HOME").filter(|value| !value.is_empty()) {
return Ok(PathBuf::from(directory));
}
if let Some(home) = env::var_os("HOME").filter(|value| !value.is_empty()) {
return Ok(PathBuf::from(home).join(".config"));
}
#[cfg(windows)]
if let Some(directory) = env::var_os("APPDATA").filter(|value| !value.is_empty()) {
return Ok(PathBuf::from(directory));
}
Err(Error::usage("session directory could not be determined"))
}
async fn write_session_file(path: &Path, bytes: &[u8]) -> Result<()> {
let directory = path
.parent()
.filter(|directory| !directory.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let name = path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("session");
let (temporary, mut file) = create_session_file(directory, name).await?;
let written = async {
file.write_all(bytes)
.await
.map_err(|_| Error::usage("session file could not be written"))?;
file.flush()
.await
.map_err(|_| Error::usage("session file could not be written"))?;
file.sync_all()
.await
.map_err(|_| Error::usage("session file could not be written"))
}
.await;
drop(file);
if let Err(error) = written {
let _ = async_fs::remove_file(&temporary).await;
return Err(error);
}
if async_fs::rename(&temporary, path).await.is_err() {
let _ = async_fs::remove_file(&temporary).await;
return Err(Error::usage("session file could not be written"));
}
Ok(())
}
async fn create_session_file(directory: &Path, name: &str) -> Result<(PathBuf, async_fs::File)> {
for _ in 0..16 {
let temporary = directory.join(format!(".{name}.{:016x}.tmp", fastrand::u64(..)));
let mut options = async_fs::OpenOptions::new();
options.create_new(true).write(true);
#[cfg(unix)]
options.mode(0o600);
match options.open(&temporary).await {
Ok(file) => return Ok((temporary, file)),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(_) => return Err(Error::usage("session file could not be written")),
}
}
Err(Error::usage("session file could not be written"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn named_sessions_are_scoped_by_normalized_origin() {
let canonical = session_path("work", "https://example.com/api").unwrap();
let explicit_default = session_path("work", "https://EXAMPLE.COM.:443/other").unwrap();
let http = session_path("work", "http://example.com/api").unwrap();
let alternate_port = session_path("work", "https://example.com:8443/api").unwrap();
assert!(
canonical.ends_with(
Path::new("tez")
.join("sessions")
.join("_https")
.join("_example.com")
.join("_443")
.join("work.json")
)
);
assert_eq!(canonical, explicit_default);
assert_ne!(canonical, http);
assert_ne!(canonical, alternate_port);
}
#[test]
fn named_session_origin_components_are_filesystem_safe() {
let path = session_path("work", "https://[2001:db8::1]/api").unwrap();
let host = path
.parent()
.and_then(Path::parent)
.and_then(Path::file_name)
.and_then(|value| value.to_str())
.unwrap();
assert_eq!(host, "_2001%3Adb8%3A%3A1");
assert!(!host.contains([':', '/', '\\']));
}
#[test]
fn explicit_session_paths_are_retained() {
for specification in ["../work", "sessions/work.json", ".work"] {
assert_eq!(
session_path(specification, "https://example.com").unwrap(),
PathBuf::from(specification)
);
}
assert!(session_path("work name", "https://example.com").is_err());
}
#[test]
fn cookies_include_session_cookies_when_saved() {
let mut store = CookieStore::default();
let url = url::Url::parse("https://example.com/").unwrap();
let cookie = RawCookie::parse("sid=tez; Path=/".to_owned()).unwrap();
store.store_response_cookies(std::iter::once(cookie), &url);
let stored = stored_cookies(&store).unwrap();
let restored = cookie_store(&stored).unwrap();
assert_eq!(
restored.get_request_values(&url).collect::<Vec<_>>(),
[("sid", "tez")]
);
}
#[test]
fn invalid_session_headers_are_rejected() {
let session = StoredSession {
version: SESSION_FILE_VERSION,
headers: vec![StoredHeader {
name: "bad header".to_owned(),
value: "value".to_owned(),
}],
..StoredSession::default()
};
assert!(validate(&session).is_err());
}
#[test]
fn a_later_unset_removes_a_same_invocation_header() {
let mut session = Session {
path: Some(PathBuf::from("session.json")),
read_only: false,
dirty: false,
contents: StoredSession {
headers: vec![StoredHeader {
name: "x-session".to_owned(),
value: "saved".to_owned(),
}],
..StoredSession::default()
},
};
session.remember(
[
("x-session".to_owned(), Some("first".to_owned())),
("x-session".to_owned(), Some("second".to_owned())),
("x-session".to_owned(), None),
],
None,
);
assert!(session.contents.headers.is_empty());
}
#[cfg(unix)]
#[tokio::test]
async fn new_session_files_are_private() {
use std::os::unix::fs::PermissionsExt as _;
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("session.json");
write_session_file(&path, b"session").await.unwrap();
let mode = std::fs::metadata(path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
}
#[cfg(unix)]
#[tokio::test]
async fn existing_session_files_are_atomically_replaced_with_private_files() {
use std::os::unix::fs::PermissionsExt as _;
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("session.json");
std::fs::write(&path, b"old session").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
write_session_file(&path, b"new session").await.unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"new session");
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
}
}