aoc-toolkit 0.1.0-alpha.3

A toolkit for solving Advent of Code problems
Documentation
use keyring::v1::{Entry, Error};
use std::env::{self, VarError};
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};

use super::cache;
use super::error::ClientError;
use super::http::session_cookie;
use sha2::{Digest, Sha256};

const SERVICE: &str = "dev.kyrboforge.aoc-toolkit";
const ACCOUNT: &str = "adventofcode.com";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionSource {
    Environment,
    Dotenv,
    CredentialStore,
}

pub(crate) struct SessionStore;

impl SessionStore {
    fn entry() -> Result<Entry, ClientError> {
        Entry::new(SERVICE, ACCOUNT).map_err(|_| ClientError::CredentialStore)
    }

    pub(crate) fn load() -> Result<Option<String>, ClientError> {
        match Self::entry()?.get_password() {
            Ok(token) => Ok(Some(token)),
            Err(Error::NoEntry) => Ok(None),
            Err(_) => Err(ClientError::CredentialStore),
        }
    }

    #[cfg(feature = "cli")]
    pub(crate) fn save(token: &str) -> Result<(), ClientError> {
        session_cookie(token)?;

        Self::entry()?
            .set_password(token)
            .map_err(|_| ClientError::CredentialStore)
    }

    #[cfg(feature = "cli")]
    pub(crate) fn delete() -> Result<(), ClientError> {
        match Self::entry()?.delete_credential() {
            Ok(()) | Err(Error::NoEntry) => Ok(()),
            Err(_) => Err(ClientError::CredentialStore),
        }
    }

    fn account_path(root: &Path, token: &str) -> PathBuf {
        let fingerprint = format!("{:x}", Sha256::digest(token.as_bytes()));

        root.join("sessions").join(format!("{fingerprint}.txt"))
    }

    pub(super) fn known_account(root: &Path, token: &str) -> Result<Option<u64>, ClientError> {
        let path = Self::account_path(root, token);

        let content = match fs::read_to_string(&path) {
            Ok(content) => content,

            Err(error) if error.kind() == ErrorKind::NotFound => {
                return Ok(None);
            }

            Err(source) => {
                return Err(cache::io_error(&path, source));
            }
        };

        let account_id = content
            .trim()
            .parse::<u64>()
            .ok()
            .filter(|id| *id != 0)
            .ok_or(ClientError::AccountIdentityUnavailable)?;

        Ok(Some(account_id))
    }

    pub(super) fn remember_account_at(
        root: &Path,
        token: &str,
        account_id: u64,
    ) -> Result<(), ClientError> {
        session_cookie(token)?;

        if account_id == 0 {
            return Err(ClientError::AccountIdentityUnavailable);
        }

        let _guard = cache::lock(&root.join("sessions.lock"))?;

        match Self::known_account(root, token)? {
            Some(existing) if existing != account_id => Err(ClientError::AccountIdentityMismatch),

            Some(_) => Ok(()),

            None => cache::store(&Self::account_path(root, token), &account_id.to_string()),
        }
    }

    #[cfg(feature = "cli")]
    pub(crate) fn remember_account(token: &str, account_id: u64) -> Result<(), ClientError> {
        Self::remember_account_at(&cache::root()?, token, account_id)
    }
}

fn read_override() -> Result<Option<(String, SessionSource)>, ClientError> {
    match env::var("SESSION_ID") {
        Ok(token) => {
            return Ok(Some((token, SessionSource::Environment)));
        }

        Err(VarError::NotPresent) => {}

        Err(VarError::NotUnicode(_)) => {
            return Err(ClientError::InvalidSession);
        }
    }

    let entries = match dotenvy::dotenv_iter() {
        Ok(entries) => entries,

        Err(error) if error.not_found() => {
            return Ok(None);
        }

        Err(_) => {
            return Err(ClientError::InvalidSessionConfiguration);
        }
    };

    let mut session = None;

    for entry in entries {
        let (key, value) = entry.map_err(|_| ClientError::InvalidSessionConfiguration)?;

        if key == "SESSION_ID" && session.is_none() {
            session = Some((value, SessionSource::Dotenv));
        }
    }

    Ok(session)
}

fn resolve_with(
    session_override: Option<(String, SessionSource)>,
    load_stored: impl FnOnce() -> Result<Option<String>, ClientError>,
) -> Result<Option<(String, SessionSource)>, ClientError> {
    let session = match session_override {
        Some(session) => Some(session),

        None => load_stored()?.map(|token| (token, SessionSource::CredentialStore)),
    };

    if let Some((token, _)) = &session {
        session_cookie(token)?;
    }

    Ok(session)
}

pub(crate) fn resolve_session() -> Result<Option<(String, SessionSource)>, ClientError> {
    resolve_with(read_override()?, SessionStore::load)
}

pub(super) fn get_session() -> Result<String, ClientError> {
    resolve_session()?
        .map(|(token, _)| token)
        .ok_or(ClientError::MissingSession)
}

#[cfg(test)]
mod tests;