depot/rust/passgen/src/service_account.rs

42 lines
1.2 KiB
Rust

use std::path::PathBuf;
use anyhow::Result;
use google_walletobjects1::oauth2::authenticator::{
Authenticator, DefaultHyperClient, HyperClientBuilder,
};
use google_walletobjects1::oauth2::{read_service_account_key, ServiceAccountAuthenticator};
use jwt_simple::algorithms::RS256KeyPair;
use serde::Deserialize;
pub struct ServiceAccount {
pub service_account_name: String,
pub authenticator: Authenticator<<DefaultHyperClient as HyperClientBuilder>::Connector>,
pub key_pair: RS256KeyPair,
}
#[derive(Deserialize)]
struct ServiceAccountJSON {
// We omit a lot of fields we don't care about.
/// Service Account email
client_email: String,
/// RSA private key
private_key: String,
}
pub async fn load_service_account(path: &PathBuf) -> Result<ServiceAccount> {
let creds = read_service_account_key(path).await?;
let sa = ServiceAccountAuthenticator::builder(creds).build().await?;
let sa_data = tokio::fs::read(path).await?;
let sa_parsed: ServiceAccountJSON = serde_json::from_slice(&sa_data[..])?;
let key_pair = RS256KeyPair::from_pem(&sa_parsed.private_key)?;
Ok(ServiceAccount {
service_account_name: sa_parsed.client_email,
authenticator: sa,
key_pair,
})
}