1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
//! Authorization. INCOMPLETE AND UNSTABLE.

use std::convert::TryInto;

use async_trait::async_trait;
use futures::TryFutureExt;

use tc_error::*;
use tc_transact::TxnId;
use tcgeneric::{NetworkTime, TCPathBuf};

use crate::gateway::Gateway;
use crate::scalar::{Link, Value};

pub type Actor = rjwt::Actor<Value>;
pub type Claims = rjwt::Claims<Link, Value, Vec<Scope>>;
pub type Scope = TCPathBuf;
pub type Token = rjwt::Token<Link, Value, Vec<Scope>>;

/// A `Txn`'s authorization.
pub struct Request {
    token: String,
    claims: Claims,
    txn_id: TxnId,
}

impl Request {
    /// Construct a new `Request`.
    pub fn new(txn_id: TxnId, token: String, claims: Claims) -> Self {
        Self {
            token,
            claims,
            txn_id,
        }
    }

    pub fn expires(&self) -> TCResult<NetworkTime> {
        self.claims
            .expires()
            .try_into()
            .map_err(|e| TCError::bad_request("invalid auth token expiry", e))
    }

    /// Return this request's authorizations.
    pub fn scopes(&self) -> &Claims {
        &self.claims
    }

    /// Return this request's JSON web token (cf. the [`rjwt`] crate)
    pub fn token(&self) -> &str {
        &self.token
    }

    pub fn txn_id(&self) -> &TxnId {
        &self.txn_id
    }
}

/// Struct responsible for resolving JWT auth identities (cf. the [`rjwt`] crate).
pub struct Resolver<'a> {
    gateway: &'a Gateway,
    host: &'a Link,
    txn_id: &'a TxnId,
}

impl<'a> Resolver<'a> {
    /// Construct a new `Resolver`.
    pub fn new(gateway: &'a Gateway, host: &'a Link, txn_id: &'a TxnId) -> Self {
        Self {
            gateway,
            host,
            txn_id,
        }
    }
}

#[async_trait]
impl<'a> rjwt::Resolve for Resolver<'a> {
    type Host = Link;
    type ActorId = Value;
    type Claims = Vec<Scope>;

    fn host(&self) -> Link {
        self.host.clone()
    }

    async fn resolve(&self, host: &Link, actor_id: &Value) -> Result<Actor, rjwt::Error> {
        let public_key: String = self
            .gateway
            .fetch(&self.txn_id, host, actor_id)
            .map_err(|e| rjwt::Error::new(rjwt::ErrorKind::Fetch, e))
            .await?;

        let public_key = base64::decode(&public_key).map_err(|e| {
            rjwt::Error::new(
                rjwt::ErrorKind::Format,
                format!("invalid public key {} for {}: {}", &public_key, actor_id, e),
            )
        })?;

        Actor::with_public_key(actor_id.clone(), &public_key)
    }
}