use crate::locked;
use crate::rfc3339;
use crate::session::{
SCRIPT_CLIENT_ID, StoredSession, kb_of_session_key, text_claim, token_expiry,
};
use crate::storage::{SessionStorage, StorageChange, StorageSubscription};
use serde_json::{Map, Value};
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;
include!(concat!(env!("OUT_DIR"), "/sign_in.rs"));
include!(concat!(env!("OUT_DIR"), "/owner_only.rs"));
pub const FILE_NAME: &str = "tokens.json";
#[cfg(windows)]
#[allow(unsafe_code)]
fn owner_only(directory: &Path) -> io::Result<()> {
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use std::ptr::{null, null_mut};
use windows_sys::Win32::Foundation::{HANDLE, LocalFree};
use windows_sys::Win32::Security::Authorization::{
ConvertSecurityDescriptorToStringSecurityDescriptorW, ConvertSidToStringSidW,
ConvertStringSecurityDescriptorToSecurityDescriptorW, GetNamedSecurityInfoW,
SDDL_REVISION_1, SE_FILE_OBJECT, SetNamedSecurityInfoW,
};
use windows_sys::Win32::Security::{
ACL, DACL_SECURITY_INFORMATION, GetSecurityDescriptorDacl, GetTokenInformation,
PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, TOKEN_USER, TokenUser,
};
const CURRENT_PROCESS_TOKEN: HANDLE = -4isize as HANDLE;
let wide = |text: &OsStr| text.encode_wide().chain([0]).collect::<Vec<u16>>();
unsafe {
unsafe fn taken(text: *mut u16) -> String {
let length = (0..)
.take_while(|&at| unsafe { *text.add(at) } != 0)
.count();
unsafe {
let taken = String::from_utf16_lossy(std::slice::from_raw_parts(text, length));
LocalFree(text.cast());
taken
}
}
unsafe fn written(descriptor: PSECURITY_DESCRIPTOR) -> io::Result<String> {
let mut text = null_mut();
unsafe {
if ConvertSecurityDescriptorToStringSecurityDescriptorW(
descriptor,
SDDL_REVISION_1,
DACL_SECURITY_INFORMATION,
&mut text,
null_mut(),
) == 0
{
return Err(io::Error::last_os_error());
}
Ok(taken(text))
}
}
fn in_any_order(list: &str) -> String {
let (flags, entries) = match list.find('(') {
Some(at) => list.split_at(at),
None => (list, ""),
};
let mut entries: Vec<&str> = entries.split_inclusive(')').collect();
entries.sort_unstable();
format!("{flags}{}", entries.concat())
}
let mut size = 0u32;
GetTokenInformation(CURRENT_PROCESS_TOKEN, TokenUser, null_mut(), 0, &mut size);
let mut user = vec![0u64; (size as usize).div_ceil(8)];
if GetTokenInformation(
CURRENT_PROCESS_TOKEN,
TokenUser,
user.as_mut_ptr().cast(),
size,
&mut size,
) == 0
{
return Err(io::Error::last_os_error());
}
let mut named = null_mut();
if ConvertSidToStringSidW((*user.as_ptr().cast::<TOKEN_USER>()).User.Sid, &mut named) == 0 {
return Err(io::Error::last_os_error());
}
let sddl = wide(OsStr::new(&owner_only_access_list(&taken(named))));
let mut descriptor: PSECURITY_DESCRIPTOR = null_mut();
if ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl.as_ptr(),
SDDL_REVISION_1,
&mut descriptor,
null_mut(),
) == 0
{
return Err(io::Error::last_os_error());
}
let name = wide(directory.as_os_str());
let kept = (|| {
let (mut dacl, mut held): (*mut ACL, PSECURITY_DESCRIPTOR) = (null_mut(), null_mut());
let failed = GetNamedSecurityInfoW(
name.as_ptr(),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
null_mut(),
null_mut(),
&mut dacl,
null_mut(),
&mut held,
);
if failed != 0 {
return Err(io::Error::from_raw_os_error(failed as i32));
}
let has = written(held);
LocalFree(held);
if in_any_order(&has?) == in_any_order(&written(descriptor)?) {
return Ok(());
}
let (mut present, mut defaulted) = (0, 0);
if GetSecurityDescriptorDacl(descriptor, &mut present, &mut dacl, &mut defaulted) == 0 {
return Err(io::Error::last_os_error());
}
match SetNamedSecurityInfoW(
name.as_ptr(),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
null_mut(),
null_mut(),
dacl,
null(),
) {
0 => Ok(()),
failed => Err(io::Error::from_raw_os_error(failed as i32)),
}
})();
LocalFree(descriptor);
kept
}
}
#[cfg(unix)]
fn owner_only(directory: &Path) -> io::Result<()> {
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(
directory,
fs::Permissions::from_mode(OWNER_ONLY_DIRECTORY_MODE),
)
}
fn owner_only_file() -> OpenOptions {
let mut options = OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(OWNER_ONLY_FILE_MODE);
}
options
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum System {
MacOs,
Windows,
Other,
}
impl System {
pub const fn of_this_build() -> System {
if cfg!(target_os = "macos") {
System::MacOs
} else if cfg!(windows) {
System::Windows
} else {
System::Other
}
}
pub fn named(name: &str) -> System {
match name {
"macos" => System::MacOs,
"windows" => System::Windows,
_ => System::Other,
}
}
}
pub fn state_dir(
system: System,
home: Option<&str>,
xdg_state_home: Option<&str>,
local_app_data: Option<&str>,
) -> Option<PathBuf> {
let home = home.filter(|home| !home.is_empty())?;
let under = |separator: char, base: &str, names: &[&str]| {
let mut dir = base.trim_end_matches(separator).to_owned();
for name in names {
dir.push(separator);
dir.push_str(name);
}
PathBuf::from(dir)
};
Some(match system {
System::MacOs => under('/', home, &["Library", "Application Support", "semiont"]),
System::Windows => match local_app_data.filter(|local| !local.is_empty()) {
Some(local) => under('\\', local, &["semiont"]),
None => under('\\', home, &["AppData", "Local", "semiont"]),
},
System::Other => match xdg_state_home.filter(|state| !state.is_empty()) {
Some(state) => under('/', state, &["semiont"]),
None => under('/', home, &[".local", "state", "semiont"]),
},
})
}
fn sign_in_of(member: &Value) -> Option<SignIn> {
serde_json::from_value(member.clone()).ok()
}
fn session_of(sign_in: &SignIn) -> Option<StoredSession> {
Some(StoredSession {
access: sign_in.token.clone(),
refresh: sign_in
.refresh_token
.clone()
.filter(|refresh| !refresh.is_empty())?,
client_id: SCRIPT_CLIENT_ID.to_owned(),
token_endpoint: sign_in.token_endpoint.clone(),
revocation_endpoint: sign_in.revocation_endpoint.clone(),
})
}
fn named_by(access: &str) -> Result<(Option<String>, String), &'static str> {
let issuer = text_claim(access, "iss").ok_or("its access token names no issuer")?;
Ok((text_claim(access, "email"), issuer))
}
fn entry_of(
session: &StoredSession,
email: Option<String>,
issuer: String,
now: SystemTime,
) -> Value {
serde_json::to_value(SignIn {
token: session.access.clone(),
refresh_token: Some(session.refresh.clone()),
email,
obtained_at: rfc3339::to_the_second(now),
expires_at: token_expiry(&session.access).map(rfc3339::to_the_second),
issuer,
token_endpoint: session.token_endpoint.clone(),
revocation_endpoint: session.revocation_endpoint.clone(),
})
.unwrap_or(Value::Null)
}
pub type OnFailure = Arc<dyn Fn(&str) + Send + Sync>;
pub struct SignInStore {
path: PathBuf,
rest: Arc<dyn SessionStorage>,
on_failure: OnFailure,
turn: Mutex<()>,
}
impl SignInStore {
pub fn at(
path: impl Into<PathBuf>,
rest: Arc<dyn SessionStorage>,
on_failure: OnFailure,
) -> SignInStore {
SignInStore {
path: path.into(),
rest,
on_failure,
turn: Mutex::new(()),
}
}
fn failed(&self, doing: &str, error: &io::Error) {
(self.on_failure)(&format!("{doing} {}: {error}", self.path.display()));
}
fn read(&self) -> io::Result<Map<String, Value>> {
let text = match fs::read_to_string(&self.path) {
Ok(text) => text,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Map::new()),
Err(error) => return Err(error),
};
serde_json::from_str(&text)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}
fn entry(&self, kb_id: &str) -> Option<Value> {
match self.read() {
Ok(mut document) => document.remove(kb_id),
Err(error) => {
self.failed("Could not read", &error);
None
}
}
}
fn change(
&self,
change: impl FnOnce(
&mut Map<String, Value>,
) -> (bool, Result<(), Box<dyn std::error::Error + Send + Sync>>),
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let _turn = locked(&self.turn);
let changed = (|| -> io::Result<Result<(), Box<dyn std::error::Error + Send + Sync>>> {
let directory = match self.path.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent,
_ => Path::new("."),
};
fs::create_dir_all(directory)?;
let lock = owner_only_file().open(self.path.with_extension("lock"))?;
lock.lock()?;
owner_only(directory)?;
let mut document = self.read()?;
let (changed, beneath) = change(&mut document);
if changed {
self.write(&document)?;
}
Ok(beneath)
})();
match changed {
Ok(beneath) => beneath,
Err(error) => {
self.failed("Could not change", &error);
Ok(())
}
}
}
fn write(&self, document: &Map<String, Value>) -> io::Result<()> {
let mut text = serde_json::to_string_pretty(document)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
text.push('\n');
let beside = self.path.with_extension("json.tmp");
let written = owner_only_file()
.open(&beside)
.and_then(|mut file| file.write_all(text.as_bytes()))
.and_then(|()| fs::rename(&beside, &self.path));
if written.is_err() {
let _ = fs::remove_file(&beside);
}
written
}
fn put(
&self,
document: &mut Map<String, Value>,
key: &str,
kb_id: &str,
next: Option<&str>,
renewed: Option<&SignIn>,
) -> (bool, Result<(), Box<dyn std::error::Error + Send + Sync>>) {
match (next, next.and_then(StoredSession::read)) {
(_, Some(session)) if session.client_id == SCRIPT_CLIENT_ID => {
let signed_in = match renewed {
Some(sign_in) => Ok((sign_in.email.clone(), sign_in.issuer.clone())),
None => named_by(&session.access),
};
match signed_in {
Ok((email, issuer)) => {
if let Err(refused) = self.rest.delete(key) {
return (false, Err(refused));
}
document.insert(
kb_id.to_owned(),
entry_of(&session, email, issuer, SystemTime::now()),
);
(true, Ok(()))
}
Err(lacking) => {
(self.on_failure)(&format!(
"The sign-in to {kb_id} was not kept: {lacking}"
));
(false, Ok(()))
}
}
}
(Some(next), _) => (false, self.rest.set(key, next)),
(None, _) => match self.rest.delete(key) {
Ok(()) => (document.remove(kb_id).is_some(), Ok(())),
Err(refused) => (false, Err(refused)),
},
}
}
}
impl SessionStorage for SignInStore {
fn get(&self, key: &str) -> Option<String> {
self.rest.get(key).or_else(|| {
let sign_in = sign_in_of(&self.entry(kb_of_session_key(key)?)?)?;
Some(session_of(&sign_in)?.written())
})
}
fn set(&self, key: &str, value: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
match kb_of_session_key(key) {
Some(kb_id) => {
self.change(|document| self.put(document, key, kb_id, Some(value), None))
}
None => self.rest.set(key, value),
}
}
fn delete(&self, key: &str) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
match kb_of_session_key(key) {
Some(kb_id) => self.change(|document| self.put(document, key, kb_id, None, None)),
None => self.rest.delete(key),
}
}
fn update(
&self,
key: &str,
change: &mut dyn FnMut(Option<&str>) -> Option<String>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let Some(kb_id) = kb_of_session_key(key) else {
return self.rest.update(key, change);
};
self.change(|document| {
let beneath = self.rest.get(key);
let sign_in = match beneath {
Some(_) => None,
None => document.get(kb_id).and_then(sign_in_of),
};
let held = sign_in
.as_ref()
.and_then(session_of)
.map(|session| session.written());
let renewed = sign_in.filter(|_| held.is_some());
let current = beneath.or(held);
let next = change(current.as_deref());
if next == current {
return (false, Ok(()));
}
self.put(document, key, kb_id, next.as_deref(), renewed.as_ref())
})
}
fn subscribe(&self, on_change: StorageChange) -> Option<StorageSubscription> {
self.rest.subscribe(on_change)
}
}