Line data Source code
1 : use anyhow::{Result, bail};
2 : use camino::Utf8Path;
3 : use jsonwebtoken::EncodingKey;
4 : use std::fs;
5 : use utils::{
6 : auth::{Claims, Scope, encode_hadron_token_with_encoding_key},
7 : id::TenantId,
8 : };
9 : use uuid::Uuid;
10 :
11 : pub struct HadronTokenGenerator {
12 : encoding_key: EncodingKey,
13 : }
14 :
15 : impl HadronTokenGenerator {
16 0 : pub fn new(path: &Utf8Path) -> anyhow::Result<Self> {
17 0 : let key_data = match fs::read(path) {
18 0 : Ok(ok) => ok,
19 0 : Err(e) => bail!("Error reading private key file {path:?}. Error: {e}"),
20 : };
21 0 : let encoding_key = match EncodingKey::from_rsa_pem(&key_data) {
22 0 : Ok(ok) => ok,
23 0 : Err(e) => {
24 0 : bail!("Error reading private key file {path:?} as RSA private key. Error: {e}")
25 : }
26 : };
27 0 : Ok(Self { encoding_key })
28 0 : }
29 :
30 0 : pub fn generate_tenant_scope_token(&self, tenant_id: TenantId) -> Result<String> {
31 0 : let claims = Claims::new(Some(tenant_id), Scope::Tenant);
32 0 : self.internal_encode_token(&claims)
33 0 : }
34 :
35 0 : pub fn generate_tenant_endpoint_scope_token(&self, endpoint_id: Uuid) -> Result<String> {
36 0 : let claims = Claims::new_for_endpoint(endpoint_id);
37 0 : self.internal_encode_token(&claims)
38 0 : }
39 :
40 0 : pub fn generate_ps_sk_auth_token(&self) -> Result<String> {
41 0 : let claims = Claims {
42 0 : tenant_id: None,
43 0 : endpoint_id: None,
44 0 : scope: Scope::SafekeeperData,
45 0 : };
46 0 : self.internal_encode_token(&claims)
47 0 : }
48 :
49 0 : fn internal_encode_token(&self, claims: &Claims) -> Result<String> {
50 0 : encode_hadron_token_with_encoding_key(claims, &self.encoding_key)
51 0 : }
52 : }
|