iwlink 0.1.1

IntelliWallet Link - encrypted phone to computer protocol for IntelliWallet for Browser
Documentation
//! Timing rules for requests and grants.
//!
//! The phone enforces these; the helper uses the same constants so the two
//! never disagree about when something has expired.
//!
//! - A **pending request** waits up to [`PENDING_TTL_SECS`] for the user to
//!   pick up the phone, unlock it and approve.
//! - An approved fill with several matching logins opens a **grant**: the
//!   browser may reveal one of the offered logins within [`GRANT_TTL_SECS`].
//!   A grant is single use and bound to its request and its candidate list.
//!
//! Times are unix seconds passed in by the caller.

/// How long a request waits for the user.
pub const PENDING_TTL_SECS: i64 = 120;

/// How long a grant to pick one of several logins lasts.
pub const GRANT_TTL_SECS: i64 = 60;

/// Whether a request created at `created_at` has expired at `now`.
///
/// A creation time in the future (a clock that moved backwards, or a
/// tampered notification payload) counts as expired rather than as fresh.
pub fn is_pending_expired(created_at: i64, now: i64) -> bool {
    now < created_at || now - created_at >= PENDING_TTL_SECS
}

/// Permission to reveal one login out of an approved candidate list.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Grant {
    request_id: String,
    items: Vec<String>,
    expires_at: i64,
    used: bool,
}

impl Grant {
    pub fn new(request_id: &str, items: Vec<String>, now: i64) -> Grant {
        Grant {
            request_id: request_id.to_owned(),
            items,
            expires_at: now.saturating_add(GRANT_TTL_SECS),
            used: false,
        }
    }

    pub fn request_id(&self) -> &str {
        &self.request_id
    }

    /// Seconds left, for the `Candidates` message.
    pub fn ttl_secs(&self, now: i64) -> u32 {
        (self.expires_at - now).clamp(0, GRANT_TTL_SECS) as u32
    }

    pub fn is_expired(&self, now: i64) -> bool {
        now >= self.expires_at
    }

    /// Whether this grant is finished with: expired or already used.
    pub fn is_spent(&self, now: i64) -> bool {
        self.used || self.is_expired(now)
    }

    /// Use the grant for `item` of `request_id`. Returns `false`, and leaves
    /// the grant untouched, when the request differs, the item was not offered,
    /// the grant expired, or it was already used.
    pub fn consume(&mut self, request_id: &str, item: &str, now: i64) -> bool {
        if self.is_spent(now)
            || self.request_id != request_id
            || !self.items.iter().any(|i| i == item)
        {
            return false;
        }
        self.used = true;
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn grant() -> Grant {
        Grant::new("r1", vec!["a".into(), "b".into()], 1_000)
    }

    #[test]
    fn consumes_once() {
        let mut g = grant();
        assert!(g.consume("r1", "b", 1_010));
        assert!(!g.consume("r1", "b", 1_011), "single use");
        assert!(!g.consume("r1", "a", 1_011), "single use across items");
    }

    #[test]
    fn refuses_other_requests_and_items() {
        let mut g = grant();
        assert!(!g.consume("r2", "a", 1_001));
        assert!(!g.consume("r1", "c", 1_001));
        assert!(
            g.consume("r1", "a", 1_001),
            "failed attempts did not spend it"
        );
    }

    #[test]
    fn expires() {
        let mut g = grant();
        assert_eq!(g.ttl_secs(1_000), 60);
        assert_eq!(g.ttl_secs(1_059), 1);
        assert!(!g.consume("r1", "a", 1_000 + GRANT_TTL_SECS));
        assert_eq!(g.ttl_secs(5_000), 0);
    }

    #[test]
    fn pending_expiry() {
        assert!(!is_pending_expired(1_000, 1_000));
        assert!(!is_pending_expired(1_000, 1_000 + PENDING_TTL_SECS - 1));
        assert!(is_pending_expired(1_000, 1_000 + PENDING_TTL_SECS));
        assert!(is_pending_expired(1_000, 999), "future creation time");
    }
}