feat(auth): add authentication integration
Some checks failed
continuous-integration/drone/push Build is failing
Some checks failed
continuous-integration/drone/push Build is failing
Signed-off-by: kjuulh <contact@kjuulh.io>
This commit is contained in:
107
como_auth/src/auth.rs
Normal file
107
como_auth/src/auth.rs
Normal file
@@ -0,0 +1,107 @@
|
||||
use std::{ops::Deref, sync::Arc};
|
||||
|
||||
use anyhow::Context;
|
||||
use async_trait::async_trait;
|
||||
use axum::http::{header::SET_COOKIE, HeaderMap};
|
||||
use oauth2::url::Url;
|
||||
|
||||
use crate::{
|
||||
introspection::IntrospectionService,
|
||||
oauth::OAuth,
|
||||
session::{SessionService, User},
|
||||
AuthClap, AuthEngine,
|
||||
};
|
||||
|
||||
#[async_trait]
|
||||
pub trait Auth {
|
||||
async fn login(&self) -> anyhow::Result<Url>;
|
||||
async fn login_authorized(&self, code: &str, state: &str) -> anyhow::Result<(HeaderMap, Url)>;
|
||||
async fn get_user_from_session(&self, cookie: &str) -> anyhow::Result<User>;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AuthService(Arc<dyn Auth + Send + Sync + 'static>);
|
||||
|
||||
impl AuthService {
|
||||
pub async fn new(config: &AuthClap) -> anyhow::Result<Self> {
|
||||
match config.engine {
|
||||
AuthEngine::Noop => Ok(Self::new_noop()),
|
||||
AuthEngine::Zitadel => Ok(Self::new_zitadel()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_zitadel() -> Self {
|
||||
todo!()
|
||||
//Self(Arc::new(ZitadelAuthService {}))
|
||||
}
|
||||
|
||||
pub fn new_noop() -> Self {
|
||||
Self(Arc::new(NoopAuthService {}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for AuthService {
|
||||
type Target = Arc<dyn Auth + Send + Sync + 'static>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ZitadelAuthService {
|
||||
oauth: OAuth,
|
||||
introspection: IntrospectionService,
|
||||
session: SessionService,
|
||||
}
|
||||
pub static COOKIE_NAME: &str = "SESSION";
|
||||
|
||||
#[async_trait]
|
||||
impl Auth for ZitadelAuthService {
|
||||
async fn login(&self) -> anyhow::Result<Url> {
|
||||
let authorize_url = self.oauth.authorize_url().await?;
|
||||
|
||||
Ok(authorize_url)
|
||||
}
|
||||
async fn login_authorized(&self, code: &str, _state: &str) -> anyhow::Result<(HeaderMap, Url)> {
|
||||
let token = self.oauth.exchange(code).await?;
|
||||
let user_id = self.introspection.get_id_token(token.as_str()).await?;
|
||||
let cookie_value = self.session.insert_user("user", user_id.as_str()).await?;
|
||||
|
||||
let cookie = format!("{}={}; SameSite=Lax; Path=/", COOKIE_NAME, cookie_value);
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(SET_COOKIE, cookie.parse().unwrap());
|
||||
|
||||
Ok((
|
||||
headers,
|
||||
Url::parse("http://localhost:3000/dash/home")
|
||||
.context("failed to parse login_authorized zitadel return url")?,
|
||||
))
|
||||
}
|
||||
async fn get_user_from_session(&self, cookie: &str) -> anyhow::Result<User> {
|
||||
match self.session.get_user(cookie).await? {
|
||||
Some(u) => Ok(User { id: u }),
|
||||
None => Err(anyhow::anyhow!("failed to find user")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NoopAuthService {}
|
||||
|
||||
#[async_trait]
|
||||
impl Auth for NoopAuthService {
|
||||
async fn login(&self) -> anyhow::Result<Url> {
|
||||
todo!()
|
||||
}
|
||||
async fn login_authorized(
|
||||
&self,
|
||||
_code: &str,
|
||||
_state: &str,
|
||||
) -> anyhow::Result<(HeaderMap, Url)> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn get_user_from_session(&self, cookie: &str) -> anyhow::Result<User> {
|
||||
todo!()
|
||||
}
|
||||
}
|
@@ -1,12 +1,16 @@
|
||||
use std::sync::Arc;
|
||||
use std::{ops::Deref, sync::Arc};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use axum::extract::FromRef;
|
||||
use oauth2::TokenIntrospectionResponse;
|
||||
use openidconnect::IntrospectionUrl;
|
||||
use zitadel::{
|
||||
axum::introspection::IntrospectionStateBuilderError,
|
||||
credentials::Application,
|
||||
oidc::{discovery::discover, introspection::AuthorityAuthentication},
|
||||
oidc::{
|
||||
discovery::discover,
|
||||
introspection::{introspect, AuthorityAuthentication},
|
||||
},
|
||||
};
|
||||
|
||||
use crate::AuthClap;
|
||||
@@ -14,10 +18,10 @@ use crate::AuthClap;
|
||||
#[async_trait]
|
||||
pub trait Introspection {
|
||||
async fn get_user(&self) -> anyhow::Result<()>;
|
||||
async fn get_id_token(&self, token: &str) -> anyhow::Result<String>;
|
||||
}
|
||||
|
||||
pub struct IntrospectionService(Arc<dyn Introspection + Send + Sync + 'static>);
|
||||
|
||||
impl IntrospectionService {
|
||||
pub async fn new_zitadel(config: &AuthClap) -> anyhow::Result<Self> {
|
||||
let res = IntrospectionStateBuilder::new(&config.zitadel.authority_url.clone().unwrap())
|
||||
@@ -34,6 +38,14 @@ impl IntrospectionService {
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for IntrospectionService {
|
||||
type Target = Arc<dyn Introspection + Send + Sync + 'static>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ZitadelIntrospection {
|
||||
state: IntrospectionState,
|
||||
}
|
||||
@@ -49,6 +61,21 @@ impl Introspection for ZitadelIntrospection {
|
||||
async fn get_user(&self) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
async fn get_id_token(&self, token: &str) -> anyhow::Result<String> {
|
||||
let config = &self.state.config;
|
||||
let res = introspect(
|
||||
&config.introspection_uri,
|
||||
&config.authority,
|
||||
&config.authentication,
|
||||
token,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(res
|
||||
.sub()
|
||||
.ok_or(anyhow::anyhow!("could not find a userid (sub) in token"))?
|
||||
.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
@@ -1,8 +1,13 @@
|
||||
use oauth::{OAuth, ZitadelConfig};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
mod auth;
|
||||
mod introspection;
|
||||
mod oauth;
|
||||
mod session;
|
||||
|
||||
pub use auth::{Auth, AuthService};
|
||||
use session::SessionClap;
|
||||
|
||||
#[derive(clap::ValueEnum, Clone, PartialEq, Eq, Debug)]
|
||||
pub enum AuthEngine {
|
||||
@@ -10,6 +15,12 @@ pub enum AuthEngine {
|
||||
Zitadel,
|
||||
}
|
||||
|
||||
#[derive(clap::ValueEnum, Clone, PartialEq, Eq, Debug)]
|
||||
pub enum SessionBackend {
|
||||
InMemory,
|
||||
Postgresql,
|
||||
}
|
||||
|
||||
#[derive(clap::Args, Clone, PartialEq, Eq, Debug)]
|
||||
pub struct AuthClap {
|
||||
#[arg(
|
||||
@@ -22,8 +33,21 @@ pub struct AuthClap {
|
||||
]
|
||||
pub engine: AuthEngine,
|
||||
|
||||
#[arg(
|
||||
env = "SESSION_BACKEND",
|
||||
long = "session-backend",
|
||||
requires_ifs = [
|
||||
( "postgresql", "PostgresqlSessionClap" )
|
||||
],
|
||||
default_value = "in-memory" )
|
||||
]
|
||||
pub session_backend: SessionBackend,
|
||||
|
||||
#[clap(flatten)]
|
||||
pub zitadel: ZitadelClap,
|
||||
|
||||
#[clap(flatten)]
|
||||
pub session: SessionClap,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -105,7 +129,10 @@ impl AuthClap {
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::{AuthClap, AuthEngine, ZitadelClap};
|
||||
use crate::{
|
||||
session::{PostgresqlSessionClap, SessionClap},
|
||||
AuthClap, AuthEngine, SessionBackend, ZitadelClap,
|
||||
};
|
||||
use clap::Parser;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
@@ -141,6 +168,10 @@ mod test {
|
||||
token_url: None,
|
||||
authority_url: None,
|
||||
},
|
||||
session_backend: SessionBackend::InMemory,
|
||||
session: SessionClap {
|
||||
postgresql: PostgresqlSessionClap { conn: None }
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -163,6 +194,10 @@ mod test {
|
||||
token_url: None,
|
||||
authority_url: None,
|
||||
},
|
||||
session_backend: crate::SessionBackend::InMemory,
|
||||
session: crate::SessionClap {
|
||||
postgresql: PostgresqlSessionClap { conn: None }
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -195,6 +230,10 @@ mod test {
|
||||
token_url: Some("https://something".into()),
|
||||
authority_url: Some("https://something".into()),
|
||||
},
|
||||
session_backend: crate::SessionBackend::InMemory,
|
||||
session: crate::SessionClap {
|
||||
postgresql: PostgresqlSessionClap { conn: None }
|
||||
}
|
||||
},
|
||||
}
|
||||
);
|
||||
|
@@ -1,5 +1,8 @@
|
||||
use async_trait::async_trait;
|
||||
use oauth2::reqwest::async_http_client;
|
||||
use oauth2::url::Url;
|
||||
use oauth2::{basic::BasicClient, AuthUrl, ClientId, ClientSecret, RedirectUrl, TokenUrl};
|
||||
use oauth2::{AuthorizationCode, CsrfToken, Scope, TokenResponse};
|
||||
use std::ops::Deref;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -8,6 +11,8 @@ use crate::ZitadelClap;
|
||||
#[async_trait]
|
||||
pub trait OAuthClient {
|
||||
async fn get_token(&self) -> anyhow::Result<()>;
|
||||
async fn authorize_url(&self) -> anyhow::Result<Url>;
|
||||
async fn exchange(&self, code: &str) -> anyhow::Result<String>;
|
||||
}
|
||||
|
||||
pub struct OAuth(Arc<dyn OAuthClient + Send + Sync + 'static>);
|
||||
@@ -43,6 +48,13 @@ impl OAuthClient for NoopOAuthClient {
|
||||
async fn get_token(&self) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
async fn authorize_url(&self) -> anyhow::Result<Url> {
|
||||
Ok(Url::parse("http://localhost:3000/auth/zitadel").unwrap())
|
||||
}
|
||||
|
||||
async fn exchange(&self, code: &str) -> anyhow::Result<String> {
|
||||
Ok(String::new())
|
||||
}
|
||||
}
|
||||
|
||||
// -- Zitadel
|
||||
@@ -138,6 +150,26 @@ impl OAuthClient for ZitadelOAuthClient {
|
||||
async fn get_token(&self) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
async fn authorize_url(&self) -> anyhow::Result<Url> {
|
||||
let (auth_url, _csrf_token) = self
|
||||
.client
|
||||
.authorize_url(CsrfToken::new_random)
|
||||
.add_scope(Scope::new("identify".to_string()))
|
||||
.add_scope(Scope::new("openid".to_string()))
|
||||
.url();
|
||||
|
||||
Ok(auth_url)
|
||||
}
|
||||
|
||||
async fn exchange(&self, code: &str) -> anyhow::Result<String> {
|
||||
let token = self
|
||||
.client
|
||||
.exchange_code(AuthorizationCode::new(code.to_string()))
|
||||
.request_async(async_http_client)
|
||||
.await?;
|
||||
|
||||
Ok(token.access_token().secret().clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
108
como_auth/src/session.rs
Normal file
108
como_auth/src/session.rs
Normal file
@@ -0,0 +1,108 @@
|
||||
use std::{ops::Deref, sync::Arc};
|
||||
|
||||
use async_sqlx_session::PostgresSessionStore;
|
||||
use async_trait::async_trait;
|
||||
use axum_sessions::async_session::{Session as AxumSession, SessionStore as AxumSessionStore};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{AuthClap, SessionBackend};
|
||||
|
||||
#[derive(clap::Args, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SessionClap {
|
||||
#[clap(flatten)]
|
||||
pub postgresql: PostgresqlSessionClap,
|
||||
}
|
||||
|
||||
#[derive(clap::Args, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PostgresqlSessionClap {
|
||||
#[arg(env = "SESSION_POSTGRES_CONN", long = "session-postgres-conn")]
|
||||
pub conn: Option<String>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait Session {
|
||||
async fn insert_user(&self, id: &str, user_id: &str) -> anyhow::Result<String>;
|
||||
async fn get_user(&self, cookie: &str) -> anyhow::Result<Option<String>>;
|
||||
}
|
||||
|
||||
pub struct SessionService(Arc<dyn Session + Send + Sync + 'static>);
|
||||
impl SessionService {
|
||||
pub async fn new(config: &AuthClap) -> anyhow::Result<Self> {
|
||||
match config.session_backend {
|
||||
SessionBackend::InMemory => Ok(Self(Arc::new(InMemorySessionService {}))),
|
||||
SessionBackend::Postgresql => {
|
||||
Ok(Self(Arc::new(PostgresSessionService { store: todo!() })))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for SessionService {
|
||||
type Target = Arc<dyn Session + Send + Sync + 'static>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PostgresSessionService {
|
||||
store: PostgresSessionStore,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
pub struct User {
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Session for PostgresSessionService {
|
||||
async fn insert_user(&self, id: &str, user_id: &str) -> anyhow::Result<String> {
|
||||
let mut session = AxumSession::new();
|
||||
session.insert(
|
||||
"user",
|
||||
User {
|
||||
id: user_id.to_string(),
|
||||
},
|
||||
)?;
|
||||
|
||||
let cookie = self
|
||||
.store
|
||||
.store_session(session)
|
||||
.await?
|
||||
.ok_or(anyhow::anyhow!("failed to store session"))?;
|
||||
|
||||
Ok(cookie)
|
||||
}
|
||||
async fn get_user(&self, cookie: &str) -> anyhow::Result<Option<String>> {
|
||||
if let Some(session) = self.store.load_session(cookie.to_string()).await.unwrap() {
|
||||
if let Some(user) = session.get::<User>("user") {
|
||||
tracing::debug!(
|
||||
"UserFromSession: session decoded success, user_id={:?}",
|
||||
user.id
|
||||
);
|
||||
Ok(Some(user.id))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
} else {
|
||||
tracing::debug!(
|
||||
"UserIdFromSession: err session not exists in store, {}",
|
||||
cookie
|
||||
);
|
||||
Err(anyhow::anyhow!("No session found for cookie"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InMemorySessionService {}
|
||||
|
||||
#[async_trait]
|
||||
impl Session for InMemorySessionService {
|
||||
async fn insert_user(&self, id: &str, user_id: &str) -> anyhow::Result<String> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn get_user(&self, cookie: &str) -> anyhow::Result<Option<String>> {
|
||||
todo!()
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user