feat: with base

Signed-off-by: kjuulh <contact@kjuulh.io>
This commit is contained in:
Kasper Juul Hermansen 2023-10-22 16:55:48 +02:00
commit df74c70fa0
Signed by: kjuulh
GPG Key ID: 9AA7BC13CE474394
11 changed files with 4869 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
target/
.cuddle/

3818
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

40
Cargo.toml Normal file
View File

@ -0,0 +1,40 @@
[workspace]
members = ["crates/*"]
resolver = "2"
[workspace.dependencies]
nefarious-login = { path = "crates/nefarious-login" }
anyhow = { version = "1.0.71" }
tokio = { version = "1", features = ["full"] }
tracing = { version = "0.1", features = ["log"] }
clap = {version = "4.3.0", features = ["derive", "env"]}
async-trait = {version = "0.1.68", features = []}
axum = {version = "0.6.18", features = []}
axum-extra = {version = "0.7.4", features = ["cookie", "cookie-private"]}
axum-sessions = {version = "0.5.0", features = []}
async-sqlx-session = {version = "0.4.0", features = ["pg"]}
serde = {version = "1.0", features = []}
uuid = {version = "1.3.3", features = []}
sqlx = { version = "0.6.2", features = [
"runtime-tokio-rustls",
"postgres",
"migrate",
"uuid",
"offline",
"time",
"chrono",
] }
chrono = { version = "0.4.26", features = ["serde"] }
zitadel = { version = "3.3.1", features = ["axum"] }
tower = "0.4.13"
tower-http = { version = "0.4.0", features = ["cors", "trace"] }
oauth2 = "4.4.0"
openidconnect = "3.0.0"
pretty_assertions = "1.4.0"
sealed_test = "1.0.0"

1
crates/nefarious-login/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

View File

@ -0,0 +1,28 @@
[package]
name = "nefarious-login"
version = "0.1.0"
edition = "2021"
[dependencies]
clap.workspace = true
async-trait.workspace = true
axum.workspace = true
axum-extra.workspace = true
axum-sessions.workspace = true
serde.workspace = true
uuid.workspace = true
sqlx.workspace = true
anyhow.workspace = true
tracing.workspace = true
async-sqlx-session.workspace = true
zitadel.workspace = true
tower.workspace = true
tower-http.workspace = true
oauth2.workspace = true
openidconnect.workspace = true
[dev-dependencies]
tokio.workspace = true
pretty_assertions.workspace = true
sealed_test.workspace = true

View File

@ -0,0 +1,159 @@
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::{introspect, AuthorityAuthentication},
},
};
use crate::login::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())
.with_basic_auth(
&config.zitadel.client_id.clone().unwrap(),
&config.zitadel.client_secret.clone().unwrap(),
)
.build()
.await?;
Ok(IntrospectionService(Arc::new(ZitadelIntrospection::new(
res,
))))
}
}
impl Deref for IntrospectionService {
type Target = Arc<dyn Introspection + Send + Sync + 'static>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
pub struct ZitadelIntrospection {
state: IntrospectionState,
}
impl ZitadelIntrospection {
pub fn new(state: IntrospectionState) -> Self {
Self { state }
}
}
#[async_trait]
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)]
pub struct IntrospectionState {
pub(crate) config: IntrospectionConfig,
}
/// Configuration that must be inject into the axum application state. Used by the
/// [IntrospectionStateBuilder](super::IntrospectionStateBuilder). This struct is also used to create the [IntrospectionState](IntrospectionState)
#[derive(Debug, Clone)]
pub struct IntrospectionConfig {
pub authority: String,
pub authentication: AuthorityAuthentication,
pub introspection_uri: IntrospectionUrl,
}
impl FromRef<IntrospectionState> for IntrospectionConfig {
fn from_ref(input: &IntrospectionState) -> Self {
input.config.clone()
}
}
pub struct IntrospectionStateBuilder {
authority: String,
authentication: Option<AuthorityAuthentication>,
}
/// Builder for [IntrospectionConfig]
impl IntrospectionStateBuilder {
pub fn new(authority: &str) -> Self {
Self {
authority: authority.to_string(),
authentication: None,
}
}
pub fn with_basic_auth(
&mut self,
client_id: &str,
client_secret: &str,
) -> &mut IntrospectionStateBuilder {
self.authentication = Some(AuthorityAuthentication::Basic {
client_id: client_id.to_string(),
client_secret: client_secret.to_string(),
});
self
}
#[allow(dead_code)]
pub fn with_jwt_profile(&mut self, application: Application) -> &mut IntrospectionStateBuilder {
self.authentication = Some(AuthorityAuthentication::JWTProfile { application });
self
}
pub async fn build(&mut self) -> Result<IntrospectionState, IntrospectionStateBuilderError> {
let authentication = self
.authentication
.clone()
.ok_or(IntrospectionStateBuilderError::NoAuthSchema)?;
let metadata = discover(&self.authority)
.await
.map_err(|source| IntrospectionStateBuilderError::Discovery { source })?;
let introspection_uri = metadata
.additional_metadata()
.introspection_endpoint
.clone()
.ok_or(IntrospectionStateBuilderError::NoIntrospectionUrl)?;
Ok(IntrospectionState {
config: IntrospectionConfig {
authority: self.authority.clone(),
introspection_uri,
authentication,
},
})
}
}

View File

@ -0,0 +1,267 @@
pub mod introspection;
pub mod login;
pub mod oauth;
pub mod session;
pub mod auth {
use std::{ops::Deref, sync::Arc};
use anyhow::Context;
use async_trait::async_trait;
use axum::http::{header::SET_COOKIE, HeaderMap};
use oauth2::{
basic::BasicClient, reqwest::async_http_client, url::Url, AuthUrl, AuthorizationCode,
ClientId, ClientSecret, CsrfToken, RedirectUrl, Scope, TokenResponse, TokenUrl,
};
use crate::{
introspection::IntrospectionService,
login::{
config::{AuthEngine, ZitadelClap},
AuthClap,
},
oauth::{OAuth, ZitadelConfig},
session::{SessionService, User},
};
#[async_trait]
pub trait Auth {
async fn login(&self) -> anyhow::Result<Url>;
async fn login_token(&self, user: &str, password: &str) -> anyhow::Result<String>;
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, session: SessionService) -> anyhow::Result<Self> {
match config.engine {
AuthEngine::Noop => Ok(Self::new_noop()),
AuthEngine::Zitadel => {
let oauth: OAuth = ZitadelConfig::try_from(config.zitadel.clone())?.into();
let introspection: IntrospectionService =
IntrospectionService::new_zitadel(config).await?;
Ok(Self::new_zitadel(oauth, introspection, session))
}
}
}
pub fn new_zitadel(
oauth: OAuth,
introspection: IntrospectionService,
session: SessionService,
) -> Self {
Self(Arc::new(ZitadelAuthService {
oauth,
introspection,
session,
}))
}
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 login_token(&self, _user: &str, password: &str) -> anyhow::Result<String> {
self.introspection.get_id_token(password).await
}
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 login_token(&self, _user: &str, _password: &str) -> anyhow::Result<String> {
todo!()
}
async fn get_user_from_session(&self, _cookie: &str) -> anyhow::Result<User> {
todo!()
}
}
}
#[cfg(test)]
mod test {
use clap::Parser;
use pretty_assertions::assert_eq;
use crate::{
login::{
config::{AuthEngine, ZitadelClap},
AuthClap,
},
session::{PostgresqlSessionClap, SessionBackend, SessionClap},
};
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(clap::Subcommand, Clone, Debug, Eq, PartialEq)]
pub enum Commands {
One {
#[clap(flatten)]
options: AuthClap,
},
}
#[test]
fn test_command_parse_as_default_noop() {
let cli: Cli = Cli::parse_from(&["base", "one"]);
assert_eq!(
cli.command,
Commands::One {
options: AuthClap {
engine: AuthEngine::Noop,
zitadel: ZitadelClap {
auth_url: None,
client_id: None,
client_secret: None,
redirect_url: None,
token_url: None,
authority_url: None,
},
session_backend: SessionBackend::InMemory,
session: SessionClap {
postgresql: PostgresqlSessionClap { conn: None }
}
}
}
);
}
#[test]
fn test_command_parse_as_noop() {
let cli: Cli = Cli::parse_from(&["base", "one", "--auth-engine", "noop"]);
assert_eq!(
cli.command,
Commands::One {
options: AuthClap {
engine: AuthEngine::Noop,
zitadel: ZitadelClap {
auth_url: None,
client_id: None,
client_secret: None,
redirect_url: None,
token_url: None,
authority_url: None,
},
session_backend: SessionBackend::InMemory,
session: SessionClap {
postgresql: PostgresqlSessionClap { conn: None }
}
}
}
);
}
#[test]
fn test_command_parse_as_zitadel() {
let cli: Cli = Cli::parse_from(&[
"base",
"one",
"--auth-engine=zitadel",
"--zitadel-client-id=something",
"--zitadel-client-secret=something",
"--zitadel-auth-url=https://something",
"--zitadel-redirect-url=https://something",
"--zitadel-token-url=https://something",
"--zitadel-authority-url=https://something",
]);
assert_eq!(
cli.command,
Commands::One {
options: AuthClap {
engine: AuthEngine::Zitadel,
zitadel: ZitadelClap {
auth_url: Some("https://something".into()),
client_id: Some("something".into()),
client_secret: Some("something".into()),
redirect_url: Some("https://something".into()),
token_url: Some("https://something".into()),
authority_url: Some("https://something".into()),
},
session_backend: SessionBackend::InMemory,
session: SessionClap {
postgresql: PostgresqlSessionClap { conn: None }
}
},
}
);
}
}

View File

@ -0,0 +1,123 @@
use crate::session::{SessionBackend, SessionClap};
use self::config::{AuthEngine, ZitadelClap};
#[derive(clap::Args, Clone, PartialEq, Eq, Debug)]
pub struct AuthClap {
#[arg(
env = "AUTH_ENGINE",
long = "auth-engine",
requires_ifs = [
( "zitadel", "ZitadelClap" )
],
default_value = "noop" )
]
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,
}
pub mod config {
use serde::{Deserialize, Serialize};
use crate::oauth::{OAuth, ZitadelConfig};
use super::AuthClap;
#[derive(clap::ValueEnum, Clone, PartialEq, Eq, Debug)]
pub enum AuthEngine {
Noop,
Zitadel,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthConfigFile {
zitadel: Option<ZitadelClap>,
}
#[derive(clap::Args, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[group(requires_all = ["auth_url", "client_id", "client_secret", "redirect_url", "token_url", "authority_url"])]
pub struct ZitadelClap {
#[arg(env = "ZITADEL_AUTH_URL", long = "zitadel-auth-url")]
pub auth_url: Option<String>,
#[arg(env = "ZITADEL_CLIENT_ID", long = "zitadel-client-id")]
pub client_id: Option<String>,
#[arg(env = "ZITADEL_CLIENT_SECRET", long = "zitadel-client-secret")]
pub client_secret: Option<String>,
#[arg(env = "ZITADEL_REDIRECT_URL", long = "zitadel-redirect-url")]
pub redirect_url: Option<String>,
#[arg(env = "ZITADEL_AUTHORITY_URL", long = "zitadel-authority-url")]
pub authority_url: Option<String>,
#[arg(env = "ZITADEL_TOKEN_URL", long = "zitadel-token-url")]
pub token_url: Option<String>,
}
impl TryFrom<AuthClap> for OAuth {
type Error = anyhow::Error;
fn try_from(value: AuthClap) -> Result<Self, Self::Error> {
match value.engine {
AuthEngine::Noop => Ok(OAuth::new_noop()),
AuthEngine::Zitadel => Ok(OAuth::from(ZitadelConfig::try_from(value.zitadel)?)),
}
}
}
impl AuthClap {
pub fn merge(&mut self, config: AuthConfigFile) -> &mut Self {
if let Some(zitadel) = config.zitadel {
if let Some(auth_url) = zitadel.auth_url {
if let Some(_) = self.zitadel.auth_url {
_ = self.zitadel.auth_url.replace(auth_url);
}
}
if let Some(client_id) = zitadel.client_id {
if let Some(_) = self.zitadel.client_id {
_ = self.zitadel.client_id.replace(client_id);
}
}
if let Some(client_secret) = zitadel.client_secret {
if let Some(_) = self.zitadel.client_secret {
_ = self.zitadel.client_secret.replace(client_secret);
}
}
if let Some(redirect_url) = zitadel.redirect_url {
if let Some(_) = self.zitadel.redirect_url {
_ = self.zitadel.redirect_url.replace(redirect_url);
}
}
if let Some(authority_url) = zitadel.authority_url {
if let Some(_) = self.zitadel.authority_url {
_ = self.zitadel.authority_url.replace(authority_url);
}
}
if let Some(token_url) = zitadel.token_url {
if let Some(_) = self.zitadel.token_url {
_ = self.zitadel.token_url.replace(token_url);
}
}
}
self
}
}
}

View File

@ -0,0 +1,298 @@
use std::{ops::Deref, sync::Arc};
use anyhow::Context;
use async_trait::async_trait;
use axum::http::{header::SET_COOKIE, HeaderMap};
use oauth2::{
basic::BasicClient, reqwest::async_http_client, url::Url, AuthUrl, AuthorizationCode, ClientId,
ClientSecret, CsrfToken, RedirectUrl, Scope, TokenResponse, TokenUrl,
};
use crate::{
introspection::IntrospectionService,
login::{
config::{AuthEngine, ZitadelClap},
AuthClap,
},
session::{SessionService, User},
};
#[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>);
impl OAuth {
pub fn new_zitadel(config: ZitadelConfig) -> Self {
Self(Arc::new(ZitadelOAuthClient::from(config)))
}
pub fn new_noop() -> Self {
Self(Arc::new(NoopOAuthClient {}))
}
}
impl Deref for OAuth {
type Target = Arc<dyn OAuthClient + Send + Sync + 'static>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<ZitadelConfig> for OAuth {
fn from(value: ZitadelConfig) -> Self {
Self::new_zitadel(value)
}
}
// -- Noop
#[derive(clap::Args, Clone)]
pub struct NoopOAuthClient;
#[async_trait]
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
#[derive(Clone)]
pub struct ZitadelConfig {
auth_url: String,
client_id: String,
client_secret: String,
redirect_url: String,
token_url: String,
authority_url: String,
}
pub struct ZitadelOAuthClient {
client: BasicClient,
}
impl ZitadelOAuthClient {
pub fn new(
client_id: impl Into<String>,
client_secret: impl Into<String>,
redirect_url: impl Into<String>,
auth_url: impl Into<String>,
token_url: impl Into<String>,
authority_url: impl Into<String>,
) -> Self {
Self {
client: Self::oauth_client(ZitadelConfig {
client_id: client_id.into(),
client_secret: client_secret.into(),
redirect_url: redirect_url.into(),
auth_url: auth_url.into(),
token_url: token_url.into(),
authority_url: authority_url.into(),
}),
}
}
fn oauth_client(config: ZitadelConfig) -> BasicClient {
BasicClient::new(
ClientId::new(config.client_id),
Some(ClientSecret::new(config.client_secret)),
AuthUrl::new(config.auth_url).unwrap(),
Some(TokenUrl::new(config.token_url).unwrap()),
)
.set_redirect_uri(RedirectUrl::new(config.redirect_url).unwrap())
}
}
impl From<ZitadelConfig> for ZitadelOAuthClient {
fn from(value: ZitadelConfig) -> Self {
Self::new(
value.client_id,
value.client_secret,
value.redirect_url,
value.auth_url,
value.token_url,
value.authority_url,
)
}
}
impl TryFrom<ZitadelClap> for ZitadelConfig {
type Error = anyhow::Error;
fn try_from(value: ZitadelClap) -> Result<Self, Self::Error> {
Ok(Self {
auth_url: value
.auth_url
.ok_or(anyhow::anyhow!("auth_url was not set"))?,
client_id: value
.client_id
.ok_or(anyhow::anyhow!("client_id was not set"))?,
client_secret: value
.client_secret
.ok_or(anyhow::anyhow!("client_secret was not set"))?,
redirect_url: value
.redirect_url
.ok_or(anyhow::anyhow!("redirect_url was not set"))?,
token_url: value
.token_url
.ok_or(anyhow::anyhow!("token_url was not set"))?,
authority_url: value
.authority_url
.ok_or(anyhow::anyhow!("authority_url was not set"))?,
})
}
}
#[async_trait]
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)]
mod tests {
use clap::Parser;
use sealed_test::prelude::*;
use crate::login::config::ZitadelClap;
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
#[clap(flatten)]
options: ZitadelClap,
}
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
pub struct CliSubCommand {
#[command(subcommand)]
command: Commands,
}
#[derive(clap::Subcommand, Clone, Debug, Eq, PartialEq)]
pub enum Commands {
One {
#[clap(flatten)]
options: ZitadelClap,
},
}
#[tokio::test]
async fn test_parse_clap_zitadel() {
let cli: Cli = Cli::parse_from(&[
"base",
"--zitadel-client-id=something",
"--zitadel-client-secret=something",
"--zitadel-auth-url=https://something",
"--zitadel-redirect-url=https://something",
"--zitadel-token-url=https://something",
"--zitadel-authority-url=https://something",
]);
println!("{:?}", cli.options);
pretty_assertions::assert_eq!(
cli.options,
ZitadelClap {
auth_url: Some("https://something".into()),
client_id: Some("something".into()),
client_secret: Some("something".into()),
redirect_url: Some("https://something".into()),
token_url: Some("https://something".into()),
authority_url: Some("https://something".into()),
}
);
}
#[test]
fn test_parse_clap_zitadel_fails_require_all() {
let cli = CliSubCommand::try_parse_from(&[
"base",
"one",
// "--zitadel-client-id=something", // We want to trigger missing variable
"--zitadel-client-secret=something",
"--zitadel-auth-url=https://something",
"--zitadel-redirect-url=https://something",
"--zitadel-token-url=https://something",
"--zitadel-authority-url=https://something",
]);
pretty_assertions::assert_eq!(cli.is_err(), true);
}
#[sealed_test]
fn test_parse_clap_env_zitadel() {
std::env::set_var("ZITADEL_CLIENT_ID", "something");
std::env::set_var("ZITADEL_CLIENT_SECRET", "something");
std::env::set_var("ZITADEL_AUTH_URL", "https://something");
std::env::set_var("ZITADEL_REDIRECT_URL", "https://something");
std::env::set_var("ZITADEL_TOKEN_URL", "https://something");
std::env::set_var("ZITADEL_AUTHORITY_URL", "https://something");
let cli = CliSubCommand::parse_from(&["base", "one"]);
pretty_assertions::assert_eq!(
cli.command,
Commands::One {
options: ZitadelClap {
auth_url: Some("https://something".into()),
client_id: Some("something".into()),
client_secret: Some("something".into()),
redirect_url: Some("https://something".into()),
token_url: Some("https://something".into()),
authority_url: Some("https://something".into()),
}
}
);
}
#[test]
fn test_parse_clap_defaults_to_noop() {
let cli = CliSubCommand::parse_from(&["base", "one"]);
pretty_assertions::assert_eq!(
cli.command,
Commands::One {
options: ZitadelClap {
auth_url: None,
client_id: None,
client_secret: None,
redirect_url: None,
token_url: None,
authority_url: None,
},
}
);
}
}

View File

@ -0,0 +1,126 @@
#[derive(clap::ValueEnum, Clone, PartialEq, Eq, Debug)]
pub enum SessionBackend {
InMemory,
Postgresql,
}
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::login::AuthClap;
#[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 => {
let postgres_session = PostgresSessionStore::new(
config
.session
.postgresql
.conn
.as_ref()
.expect("SESSION_POSTGRES_CONN to be set"),
)
.await?;
Ok(Self(Arc::new(PostgresSessionService {
store: postgres_session,
})))
}
}
}
}
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!()
}
}

7
cuddle.yaml Normal file
View File

@ -0,0 +1,7 @@
# yaml-language-server: $schema=https://git.front.kjuulh.io/kjuulh/cuddle/raw/branch/main/schemas/base.json
base: "git@git.front.kjuulh.io:kjuulh/cuddle-base.git"
vars:
service: "nefarious-login"
registry: kasperhermansen