Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: remove the --devmode runtime option #1127

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 6 additions & 9 deletions common/auth/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,14 @@ pub fn is_default<D: Default + PartialEq>(d: &D) -> bool {
impl AuthConfigArguments {
pub fn split(
self,
devmode: bool,
defaults: bool,
) -> Result<Option<(AuthenticatorConfig, AuthorizerConfig)>, anyhow::Error> {
// disabled overrides devmode
if self.disabled {
return Ok(None);
}

// check for devmode
if devmode {
log::warn!("Running in developer mode");
return Ok(Some((AuthenticatorConfig::devmode(), Default::default())));
if defaults {
log::warn!("Running with default auth config");
return Ok(Some(Default::default()));
}

Ok(Some(match self.config {
Expand Down Expand Up @@ -96,7 +93,7 @@ mod tests {
use super::*;

#[test]
fn auth_disabled_devmode_false() {
fn auth_disabled_no_defaults() {
let args = AuthConfigArguments {
disabled: true,
config: None,
Expand All @@ -108,7 +105,7 @@ mod tests {
}

#[test]
fn auth_enabled_devmode_true() {
fn auth_enabled_with_defaults() {
let args = AuthConfigArguments {
disabled: false,
config: None,
Expand Down
11 changes: 5 additions & 6 deletions common/auth/src/authenticator/config.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{authenticator::default_scope_mappings, devmode};
use crate::{authenticator::default_scope_mappings, default};
use clap::ArgAction;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
Expand Down Expand Up @@ -31,15 +31,14 @@ pub struct AuthenticatorConfig {
pub clients: Vec<AuthenticatorClientConfig>,
}

impl AuthenticatorConfig {
/// Create settings when using `--devmode`.
pub fn devmode() -> Self {
impl Default for AuthenticatorConfig {
fn default() -> Self {
Self {
clients: devmode::CLIENT_IDS
clients: default::CLIENT_IDS
.iter()
.map(|client_id| AuthenticatorClientConfig {
client_id: client_id.to_string(),
issuer_url: devmode::issuer_url(),
issuer_url: default::issuer_url(),
scope_mappings: default_scope_mappings(),
additional_permissions: Default::default(),
required_audience: None,
Expand Down
46 changes: 0 additions & 46 deletions common/auth/src/client/provider/openid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@ use super::{
{Credentials, TokenProvider},
};
use crate::client::Expires;
use crate::devmode;
use anyhow::Context;
use core::fmt::{self, Debug, Formatter};
use std::time::Duration;
use std::{ops::Deref, sync::Arc};
use tokio::sync::RwLock;
use url::Url;
Expand Down Expand Up @@ -52,34 +50,10 @@ pub struct OpenIdTokenProviderConfigArguments {
pub tls_insecure: bool,
}

impl OpenIdTokenProviderConfigArguments {
pub fn devmode() -> OpenIdTokenProviderConfigArguments {
Self {
issuer_url: Some(devmode::issuer_url()),
client_id: Some(devmode::SERVICE_CLIENT_ID.to_string()),
client_secret: Some(devmode::SSO_CLIENT_SECRET.to_string()),
refresh_before: Duration::from_secs(30).into(),
tls_insecure: false,
}
}
}

impl OpenIdTokenProviderConfigArguments {
pub async fn into_provider(self) -> anyhow::Result<Arc<dyn TokenProvider>> {
OpenIdTokenProviderConfig::new_provider(OpenIdTokenProviderConfig::from_args(self)).await
}

pub async fn into_provider_or_devmode(
self,
devmode: bool,
) -> anyhow::Result<Arc<dyn TokenProvider>> {
let config = match devmode {
true => Some(OpenIdTokenProviderConfig::devmode()),
false => OpenIdTokenProviderConfig::from_args(self),
};

OpenIdTokenProviderConfig::new_provider(config).await
}
}

#[derive(Clone, Debug, PartialEq, Eq, clap::Args)]
Expand All @@ -92,33 +66,13 @@ pub struct OpenIdTokenProviderConfig {
}

impl OpenIdTokenProviderConfig {
pub fn devmode() -> Self {
Self {
issuer_url: devmode::issuer_url(),
client_id: devmode::SERVICE_CLIENT_ID.to_string(),
client_secret: devmode::SSO_CLIENT_SECRET.to_string(),
refresh_before: Duration::from_secs(30).into(),
tls_insecure: false,
}
}

pub async fn new_provider(config: Option<Self>) -> anyhow::Result<Arc<dyn TokenProvider>> {
Ok(match config {
Some(config) => Arc::new(OpenIdTokenProvider::with_config(config).await?),
None => Arc::new(()),
})
}

pub fn from_args_or_devmode(
arguments: OpenIdTokenProviderConfigArguments,
devmode: bool,
) -> Option<Self> {
match devmode {
true => Some(Self::devmode()),
false => Self::from_args(arguments),
}
}

pub fn from_args(arguments: OpenIdTokenProviderConfigArguments) -> Option<Self> {
match (
arguments.client_id,
Expand Down
12 changes: 6 additions & 6 deletions common/auth/src/devmode.rs → common/auth/src/default.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
/// The default issuer when using `--devmode`.
/// The default issuer url
pub const ISSUER_URL: &str = "http://localhost:8090/realms/trustify";

/// The default client id for the frontend
pub const FRONTEND_CLIENT_ID: &str = "frontend";

/// The default "service" client ID for devmode
/// The default "service" client ID
pub const SERVICE_CLIENT_ID: &str = "testing-manager";

pub const PUBLIC_CLIENT_IDS: &[&str] = &[FRONTEND_CLIENT_ID];
pub const CONFIDENTIAL_CLIENT_IDS: &[&str] = &["walker", "testing-user", SERVICE_CLIENT_ID];

/// The clients which will be accepted by services when running with `--devmode`.
/// The clients which will be accepted by services
///
/// This also includes the "testing" clients, as this allows running the testsuite against an
/// already spun-up set of services.
Expand All @@ -28,10 +28,10 @@ pub const SWAGGER_UI_CLIENT_ID: &str = FRONTEND_CLIENT_ID;
/// This is not a secret. Don't use this in production.
pub const SSO_CLIENT_SECRET: &str = "R8A6KFeyxJsMDBhjfHbpZTIF0GWt43HP";

/// Get the issuer URL for `--devmode`.
/// Get the issuer URL
///
/// This can be either the value of [`ISSUER_URL`], or it can be overridden using the environment
/// variable `ISSUER_URL`.
/// This can be either the value of [`ISSUER_URL`], or it can be
/// overridden using the environment variable `TRUSTD_ISSUER_URL`.
pub fn issuer_url() -> String {
std::env::var("TRUSTD_ISSUER_URL").unwrap_or_else(|_| ISSUER_URL.to_string())
}
Expand Down
2 changes: 1 addition & 1 deletion common/auth/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub mod auth;
pub mod authenticator;
pub mod authorizer;
pub mod client;
pub mod devmode;
pub mod default;

#[cfg(feature = "swagger")]
pub mod swagger_ui;
22 changes: 5 additions & 17 deletions common/auth/src/swagger_ui.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::devmode::{self, SWAGGER_UI_CLIENT_ID};
use crate::default::{self, SWAGGER_UI_CLIENT_ID};
use actix_web::dev::HttpServiceFactory;
use openid::{Client, Discovered, Provider, StandardClaims};
use std::sync::Arc;
Expand All @@ -11,7 +11,7 @@ use utoipa::openapi::{
};
use utoipa_swagger_ui::{oauth, Config, SwaggerUi};

#[derive(Clone, Debug, Default, clap::Args)]
#[derive(Clone, Debug, clap::Args)]
#[command(
rename_all_env = "SCREAMING_SNAKE_CASE",
next_help_heading = "Swagger UI OIDC"
Expand Down Expand Up @@ -44,12 +44,12 @@ pub struct SwaggerUiOidcConfig {
pub swagger_ui_oidc_client_id: String,
}

impl SwaggerUiOidcConfig {
pub fn devmode() -> Self {
impl Default for SwaggerUiOidcConfig {
fn default() -> Self {
Self {
tls_insecure: false,
ca_certificates: vec![],
swagger_ui_oidc_issuer_url: Some(devmode::issuer_url()),
swagger_ui_oidc_issuer_url: Some(default::issuer_url()),
swagger_ui_oidc_client_id: SWAGGER_UI_CLIENT_ID.to_string(),
}
}
Expand Down Expand Up @@ -98,18 +98,6 @@ impl SwaggerUiOidc {
}))
}

pub async fn from_devmode_or_config(
devmode: bool,
config: SwaggerUiOidcConfig,
) -> anyhow::Result<Option<Self>> {
let config = match devmode {
true => SwaggerUiOidcConfig::devmode(),
false => config,
};

Self::new(config).await
}

pub fn apply_to_schema(&self, openapi: &mut OpenApi) {
if let Some(components) = &mut openapi.components {
// The swagger UI OIDC client still is weird, let's use OAuth2
Expand Down
4 changes: 1 addition & 3 deletions server/src/embedded_oidc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use rand::Rng;
use std::time::Duration;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use trustify_auth::devmode::{
use trustify_auth::default::{
CONFIDENTIAL_CLIENT_IDS, ISSUER_URL, PUBLIC_CLIENT_IDS, SSO_CLIENT_SECRET,
};
use trustify_infrastructure::health::Check;
Expand Down Expand Up @@ -62,8 +62,6 @@ fn create(enabled: bool) -> anyhow::Result<Option<Server>> {
});
}

// take the devmode url and extract all information for building the server

let url = Url::parse(ISSUER_URL)?;
let port = url.port().unwrap_or(8090);
let mut path = url
Expand Down
42 changes: 16 additions & 26 deletions server/src/profile/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use trustify_auth::{
auth::AuthConfigArguments,
authenticator::Authenticator,
authorizer::Authorizer,
devmode::{FRONTEND_CLIENT_ID, ISSUER_URL, PUBLIC_CLIENT_IDS},
default::{FRONTEND_CLIENT_ID, ISSUER_URL, PUBLIC_CLIENT_IDS},
swagger_ui::{swagger_ui_with_auth, SwaggerUiOidc, SwaggerUiOidcConfig},
};
use trustify_common::{config::Database, db, model::BinaryByteSize};
Expand Down Expand Up @@ -53,9 +53,6 @@ use crate::embedded_oidc;
/// Run the API server
#[derive(clap::Args, Debug)]
pub struct Run {
#[arg(long, env)]
pub devmode: bool,

#[arg(long, env)]
pub sample_data: bool,

Expand Down Expand Up @@ -194,21 +191,16 @@ impl Run {

impl InitData {
async fn new(context: InitContext, run: Run) -> anyhow::Result<Self> {
// The devmode for the auth parts. This allows us to enable devmode for auth, but not
// for other parts.
#[allow(unused_mut)]
let mut auth_devmode = run.devmode;
let mut auth_embedded = false;

#[cfg(feature = "garage-door")]
let embedded_oidc = {
// When running with the embedded OIDC server, re-use devmode. Running the embedded OIDC
// without devmode doesn't make any sense. However, the pm-mode doesn't know about
// devmode. Also, enabling devmode might trigger other logic.
auth_devmode = run.embedded_oidc;
auth_embedded = run.embedded_oidc;
embedded_oidc::spawn(run.embedded_oidc).await?
};

let (authn, authz) = run.auth.split(auth_devmode)?.unzip();
let (authn, authz) = run.auth.split(auth_embedded)?.unzip();
let authenticator: Option<Arc<Authenticator>> =
Authenticator::from_config(authn).await?.map(Arc::new);
let authorizer = Authorizer::new(authz);
Expand All @@ -218,19 +210,19 @@ impl InitData {
}

let swagger_oidc = match authenticator.is_some() {
true => SwaggerUiOidc::from_devmode_or_config(auth_devmode, run.swagger_ui_oidc)
.await?
.map(Arc::new),
true => SwaggerUiOidc::new(if auth_embedded {
Default::default()
} else {
run.swagger_ui_oidc
})
.await?
.map(Arc::new),
false => None,
};

let db = db::Database::new(&run.database).await?;

if run.devmode {
db.migrate().await?;
}

if run.devmode || run.sample_data {
if run.sample_data {
sample_data(db.clone()).await?;
}

Expand All @@ -252,12 +244,10 @@ impl InitData {
.as_ref()
.cloned()
.unwrap_or_else(|| PathBuf::from("./.trustify/storage"));
if run.devmode {
create_dir_all(&storage).context(format!(
"Failed to create filesystem storage directory: {:?}",
run.storage.fs_path
))?;
}
create_dir_all(&storage).context(format!(
"Failed to create filesystem storage directory: {:?}",
run.storage.fs_path
))?;
DispatchBackend::Filesystem(
FileSystemBackend::new(storage, run.storage.compression).await?,
)
Expand Down
2 changes: 1 addition & 1 deletion server/src/profile/importer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use trustify_auth::{
auth::AuthConfigArguments,
authenticator::Authenticator,
authorizer::Authorizer,
devmode::{FRONTEND_CLIENT_ID, ISSUER_URL, PUBLIC_CLIENT_IDS},
default::{FRONTEND_CLIENT_ID, ISSUER_URL, PUBLIC_CLIENT_IDS},
swagger_ui::{swagger_ui_with_auth, SwaggerUiOidc, SwaggerUiOidcConfig},
};
use trustify_common::{config::Database, db, model::BinaryByteSize};
Expand Down
Loading