Skip to content

Commit

Permalink
feat(api): support google oidc
Browse files Browse the repository at this point in the history
  • Loading branch information
ymgyt committed Mar 17, 2024
1 parent 92b1f01 commit c7c81fd
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 9 deletions.
72 changes: 63 additions & 9 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/synd_api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ name = "synd-api"
path = "src/main.rs"

[dependencies]
synd-auth = { path = "../synd_auth", version = "0.1.4" }
synd-feed = { path = "../synd_feed", version = "0.1.5" }
synd-o11y = { path = "../synd_o11y", version = "0.1.4" }

Expand Down
33 changes: 33 additions & 0 deletions crates/synd_api/src/serve/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::time::Duration;

use futures_util::future::BoxFuture;
use moka::future::Cache;
use synd_auth::jwt::google::JwtService as GoogleJwtService;
use tracing::warn;

use crate::{
Expand All @@ -13,6 +14,7 @@ use crate::{
#[derive(Clone)]
pub struct Authenticator {
github: GithubClient,
google: GoogleJwtService,
cache: Cache<String, Principal>,
}

Expand All @@ -25,6 +27,7 @@ impl Authenticator {

Ok(Self {
github: GithubClient::new()?,
google: GoogleJwtService::default(),
cache,
})
}
Expand Down Expand Up @@ -63,6 +66,36 @@ impl Authenticator {
}
}
}
(Some("google"), Some(id_token)) => {
if let Some(principal) = self.cache.get(id_token).await {
tracing::info!("Principal cache hit");
return Ok(principal);
}

match self.google.decode_id_token(id_token).await {
Ok(claims) => {
if !claims.email_verified {
warn!("Google jwt claims email is not verified");
return Err(());
}
let principal = Principal::User(User::from_email(claims.email));

self.cache
.insert(id_token.to_owned(), principal.clone())
.await;

Ok(principal)
}
Err(err) => {
// Id a lot of intentional invalid id tokens are sent
// google's api limit will be exceeded.
// To prevent this, it is necessary to cache the currently valid kids
// and discard jwt headers with other kids.
warn!("Failed to authenticate google: {err}");
Err(())
}
}
}
_ => Err(()),
}
}
Expand Down

0 comments on commit c7c81fd

Please sign in to comment.