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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
use log::info;
use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize};
use std::time;

const MACHINE_MAN_PREVIEW: &'static str =
    "application/vnd.github.machine-man-preview+json";

pub enum AuthError {
    JwtError(jsonwebtoken::errors::Error),
    InvalidHeaderValue(http::header::InvalidHeaderValue),
    ReqwestError(reqwest::Error),
    TimeError(time::SystemTimeError),
}

#[derive(Debug, Serialize)]
struct JwtClaims {
    /// The time that this JWT was issued
    iat: u64,
    // JWT expiration time
    exp: u64,
    // GitHub App's identifier number
    iss: u64,
}

impl JwtClaims {
    fn new(params: &GithubAuthParams) -> Result<JwtClaims, AuthError> {
        let now = time::SystemTime::now()
            .duration_since(time::UNIX_EPOCH)
            .map_err(AuthError::TimeError)?
            .as_secs();
        Ok(JwtClaims {
            // The time that this JWT was issued (now)
            iat: now,
            // JWT expiration time (1 minute from now)
            exp: now + 60,
            // GitHub App's identifier number
            iss: params.app_id,
        })
    }
}

/// This is the structure of the JSON object returned when requesting
/// an installation token.
#[derive(Debug, Deserialize)]
struct RawInstallationToken {
    token: String,
}

/// Use the app private key to generate a JWT and use the JWT to get
/// an installation token.
///
/// Reference:
/// developer.github.com/apps/building-github-apps/authenticating-with-github-apps
fn get_installation_token(
    client: &reqwest::Client,
    params: &GithubAuthParams,
) -> Result<RawInstallationToken, AuthError> {
    let claims = JwtClaims::new(params)?;
    let mut header = jsonwebtoken::Header::default();
    header.alg = jsonwebtoken::Algorithm::RS256;
    let token = jsonwebtoken::encode(&header, &claims, &params.private_key)
        .map_err(AuthError::JwtError)?;

    let url = format!(
        "https://api.github.com/app/installations/{}/access_tokens",
        params.installation_id
    );
    Ok(client
        .post(&url)
        .bearer_auth(token)
        .header("Accept", MACHINE_MAN_PREVIEW)
        .send()
        .map_err(AuthError::ReqwestError)?
        .error_for_status()
        .map_err(AuthError::ReqwestError)?
        .json()
        .map_err(AuthError::ReqwestError)?)
}

pub struct InstallationToken {
    pub client: reqwest::Client,
    token: String,
    fetch_time: time::SystemTime,
    params: GithubAuthParams,
}

impl InstallationToken {
    pub fn new(
        params: GithubAuthParams,
    ) -> Result<InstallationToken, AuthError> {
        let client = reqwest::Client::new();
        let raw = get_installation_token(&client, &params)?;
        Ok(InstallationToken {
            client,
            token: raw.token,
            fetch_time: time::SystemTime::now(),
            params: params.clone(),
        })
    }

    pub fn header(&mut self) -> Result<HeaderMap, AuthError> {
        self.refresh()?;
        let mut headers = HeaderMap::new();
        let val = format!("token {}", self.token);
        headers.insert(
            "Authorization",
            val.parse().map_err(AuthError::InvalidHeaderValue)?,
        );
        Ok(headers)
    }

    fn refresh(&mut self) -> Result<(), AuthError> {
        let elapsed = time::SystemTime::now()
            .duration_since(self.fetch_time)
            .map_err(AuthError::TimeError)?;
        // Installation tokens expire after 60 minutes. Refresh them
        // after 55 minutes to give ourselves a little wiggle room.
        if elapsed.as_secs() > (55 * 60) {
            info!("refreshing installation token");
            let raw = get_installation_token(&self.client, &self.params)?;
            self.token = raw.token;
            self.fetch_time = time::SystemTime::now();
        }
        Ok(())
    }
}

#[derive(Clone)]
pub struct GithubAuthParams {
    pub private_key: Vec<u8>,
    pub installation_id: u64,
    pub app_id: u64,
}