Skip to content
Merged
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[workspace.package]
edition = "2021"
edition = "2024"
license-file = "LICENSE.md"
homepage = "https://defguard.net/"
repository = "https://github.com/DefGuard/defguard"
Expand Down
14 changes: 7 additions & 7 deletions crates/defguard/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,29 @@ use std::{

use bytes::Bytes;
use defguard_core::{
SERVER_CONFIG, VERSION,
auth::failed_login::FailedLoginMap,
config::{Command, DefGuardConfig},
db::{
init_db, models::settings::initialize_current_settings, AppEvent, GatewayEvent, Settings,
User,
AppEvent, GatewayEvent, Settings, User, init_db,
models::settings::initialize_current_settings,
},
enterprise::{
activity_log_stream::activity_log_stream_manager::run_activity_log_stream_manager,
license::{run_periodic_license_check, set_cached_license, License},
license::{License, run_periodic_license_check, set_cached_license},
limits::update_counts,
},
events::{ApiEvent, BidiStreamEvent, GrpcEvent, InternalEvent},
grpc::{run_grpc_bidi_stream, run_grpc_server, GatewayMap, WorkerState},
grpc::{GatewayMap, WorkerState, run_grpc_bidi_stream, run_grpc_server},
init_dev_env, init_vpn_location,
mail::{run_mail_handler, Mail},
mail::{Mail, run_mail_handler},
run_web_server,
utility_thread::run_utility_thread,
wireguard_peer_disconnect::run_periodic_peer_disconnect,
wireguard_stats_purge::run_periodic_stats_purge,
SERVER_CONFIG, VERSION,
};
use defguard_event_logger::{message::EventLoggerMessage, run_event_logger};
use defguard_event_router::{run_event_router, RouterReceiverSet};
use defguard_event_router::{RouterReceiverSet, run_event_router};
use secrecy::ExposeSecret;
use tokio::sync::{broadcast, mpsc::unbounded_channel};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
Expand Down
10 changes: 5 additions & 5 deletions crates/defguard_core/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,20 @@ use axum::{
};
use axum_client_ip::InsecureClientIp;
use axum_extra::{
extract::cookie::CookieJar,
headers::{authorization::Bearer, Authorization},
TypedHeader,
extract::cookie::CookieJar,
headers::{Authorization, authorization::Bearer},
};
use jsonwebtoken::{
decode, encode, errors::Error as JWTError, DecodingKey, EncodingKey, Header, Validation,
DecodingKey, EncodingKey, Header, Validation, decode, encode, errors::Error as JWTError,
};
use serde::{Deserialize, Serialize};

use crate::{
appstate::AppState,
db::{
models::group::Permission, Group, Id, OAuth2AuthorizedApp, OAuth2Token, Session,
SessionState, User,
Group, Id, OAuth2AuthorizedApp, OAuth2Token, Session, SessionState, User,
models::group::Permission,
},
enterprise::{db::models::api_tokens::ApiToken, is_enterprise_enabled},
error::WebError,
Expand Down
32 changes: 22 additions & 10 deletions crates/defguard_core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ use std::net::IpAddr;
use clap::{Args, Parser, Subcommand};
use humantime::Duration;
use ipnetwork::IpNetwork;
use openidconnect::{core::CoreRsaPrivateSigningKey, JsonWebKeyId};
use openidconnect::{JsonWebKeyId, core::CoreRsaPrivateSigningKey};
use reqwest::Url;
use rsa::{
RsaPrivateKey,
pkcs1::{DecodeRsaPrivateKey, EncodeRsaPrivateKey},
pkcs8::{DecodePrivateKey, LineEnding},
traits::PublicKeyParts,
RsaPrivateKey,
};
use secrecy::{ExposeSecret, SecretString};

Expand Down Expand Up @@ -311,8 +311,10 @@ mod tests {

#[test]
fn test_generate_rp_id() {
env::remove_var("DEFGUARD_WEBAUTHN_RP_ID");
env::set_var("DEFGUARD_URL", "https://defguard.example.com");
unsafe {
env::remove_var("DEFGUARD_WEBAUTHN_RP_ID");
env::set_var("DEFGUARD_URL", "https://defguard.example.com");
}

let config = DefGuardConfig::new();

Expand All @@ -321,7 +323,9 @@ mod tests {
Some("defguard.example.com".to_string())
);

env::set_var("DEFGUARD_WEBAUTHN_RP_ID", "example.com");
unsafe {
env::set_var("DEFGUARD_WEBAUTHN_RP_ID", "example.com");
}

let config = DefGuardConfig::new();

Expand All @@ -330,8 +334,10 @@ mod tests {

#[test]
fn test_generate_cookie_domain() {
env::remove_var("DEFGUARD_COOKIE_DOMAIN");
env::set_var("DEFGUARD_URL", "https://defguard.example.com");
unsafe {
env::remove_var("DEFGUARD_COOKIE_DOMAIN");
env::set_var("DEFGUARD_URL", "https://defguard.example.com");
}

let config = DefGuardConfig::new();

Expand All @@ -340,7 +346,9 @@ mod tests {
Some("defguard.example.com".to_string())
);

env::set_var("DEFGUARD_COOKIE_DOMAIN", "example.com");
unsafe {
env::set_var("DEFGUARD_COOKIE_DOMAIN", "example.com");
}

let config = DefGuardConfig::new();

Expand All @@ -349,14 +357,18 @@ mod tests {

#[test]
fn test_callback_url() {
env::set_var("DEFGUARD_URL", "https://defguard.example.com");
unsafe {
env::set_var("DEFGUARD_URL", "https://defguard.example.com");
}
let config = DefGuardConfig::new();
assert_eq!(
config.callback_url().as_str(),
"https://defguard.example.com/auth/callback"
);

env::set_var("DEFGUARD_URL", "https://defguard.example.com:8443/path");
unsafe {
env::set_var("DEFGUARD_URL", "https://defguard.example.com:8443/path");
}
let config = DefGuardConfig::new();
assert_eq!(
config.callback_url().as_str(),
Expand Down
2 changes: 1 addition & 1 deletion crates/defguard_core/src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ pub async fn init_db(host: &str, port: u16, name: &str, user: &str, password: &s
}

pub use models::{
MFAInfo, UserDetails, UserInfo,
device::{AddDevice, Device},
group::Group,
oauth2authorizedapp::OAuth2AuthorizedApp,
Expand All @@ -40,7 +41,6 @@ pub use models::{
webhook::{AppEvent, HWKeyUserData, WebHook},
wireguard::{GatewayEvent, WireguardNetwork},
yubikey::YubiKey,
MFAInfo, UserDetails, UserInfo,
};

#[cfg(test)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ use chrono::NaiveDateTime;

use crate::{
db::{
Device, Group, Id, MFAMethod, User, WebAuthn, WebHook, WireguardNetwork,
models::{
authentication_key::{AuthenticationKey, AuthenticationKeyType},
oauth2client::OAuth2Client,
},
Device, Group, Id, MFAMethod, User, WebAuthn, WebHook, WireguardNetwork,
},
enterprise::db::models::{
activity_log_stream::{ActivityLogStream, ActivityLogStreamType},
Expand Down
2 changes: 1 addition & 1 deletion crates/defguard_core/src/db/models/auth_code.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use chrono::Utc;
use model_derive::Model;
use sqlx::{query_as, Error as SqlxError, PgPool};
use sqlx::{Error as SqlxError, PgPool, query_as};

use crate::{
db::{Id, NoId},
Expand Down
2 changes: 1 addition & 1 deletion crates/defguard_core/src/db/models/authentication_key.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use model_derive::Model;
use sqlx::{query_as, Error as SqlxError, PgExecutor, Type};
use sqlx::{Error as SqlxError, PgExecutor, Type, query_as};

use crate::db::{Id, NoId};

Expand Down
22 changes: 11 additions & 11 deletions crates/defguard_core/src/db/models/device.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
use std::{fmt, net::IpAddr};

use base64::{prelude::BASE64_STANDARD, Engine};
use base64::{Engine, prelude::BASE64_STANDARD};
#[cfg(test)]
use chrono::NaiveDate;
use chrono::{NaiveDateTime, Utc};
use ipnetwork::IpNetwork;
use model_derive::Model;
#[cfg(test)]
use rand::{
Rng,
distributions::{Alphanumeric, DistString, Standard},
prelude::Distribution,
Rng,
};
use sqlx::{
postgres::types::PgInterval, query, query_as, Error as SqlxError, FromRow, PgConnection,
PgExecutor, PgPool, Type,
Error as SqlxError, FromRow, PgConnection, PgExecutor, PgPool, Type,
postgres::types::PgInterval, query, query_as,
};
use thiserror::Error;
use utoipa::ToSchema;

use super::{
error::ModelError,
wireguard::{NetworkAddressError, WireguardNetwork, WIREGUARD_MAX_HANDSHAKE},
wireguard::{NetworkAddressError, WIREGUARD_MAX_HANDSHAKE, WireguardNetwork},
};
use crate::{
db::{Id, NoId, User},
AsCsv, KEY_LENGTH,
db::{Id, NoId, User},
};

#[derive(Serialize, ToSchema)]
Expand Down Expand Up @@ -103,10 +103,10 @@ impl fmt::Display for Device<Id> {
impl Distribution<Device<Id>> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Device<Id> {
Device {
id: rng.gen(),
id: rng.r#gen(),
name: Alphanumeric.sample_string(rng, 8),
wireguard_pubkey: Alphanumeric.sample_string(rng, 32),
user_id: rng.gen(),
user_id: rng.r#gen(),
created: NaiveDate::from_ymd_opt(
rng.gen_range(2000..2026),
rng.gen_range(1..13),
Expand All @@ -124,9 +124,9 @@ impl Distribution<Device<Id>> for Standard {
_ => DeviceType::User,
},
description: rng
.gen::<bool>()
.r#gen::<bool>()
.then_some(Alphanumeric.sample_string(rng, 20)),
configured: rng.gen(),
configured: rng.r#gen(),
}
}
}
Expand Down Expand Up @@ -1012,7 +1012,7 @@ mod test {
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};

use super::*;
use crate::db::{setup_pool, User};
use crate::db::{User, setup_pool};

impl Device<Id> {
/// Create new device and assign IP in a given network
Expand Down
2 changes: 1 addition & 1 deletion crates/defguard_core/src/db/models/device_login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::fmt;

use chrono::{NaiveDateTime, Utc};
use model_derive::Model;
use sqlx::{query_as, Error as SqlxError, PgPool};
use sqlx::{Error as SqlxError, PgPool, query_as};

use crate::db::{Id, NoId};

Expand Down
6 changes: 3 additions & 3 deletions crates/defguard_core/src/db/models/enrollment.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
use chrono::{NaiveDateTime, TimeDelta, Utc};
use reqwest::Url;
use sqlx::{query, query_as, Error as SqlxError, PgConnection, PgExecutor, PgPool};
use sqlx::{Error as SqlxError, PgConnection, PgExecutor, PgPool, query, query_as};
use tera::{Context, Tera};
use thiserror::Error;
use tokio::sync::mpsc::UnboundedSender;
use tonic::{Code, Status};

use super::{settings::Settings, User};
use super::{User, settings::Settings};
use crate::{
VERSION,
db::Id,
mail::Mail,
random::gen_alphanumeric,
server_config,
templates::{self, TemplateError},
VERSION,
};

pub static ENROLLMENT_TOKEN_TYPE: &str = "ENROLLMENT";
Expand Down
26 changes: 15 additions & 11 deletions crates/defguard_core/src/db/models/group.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::fmt;

use model_derive::Model;
use sqlx::{query, query_as, query_scalar, Error as SqlxError, FromRow, PgConnection, PgExecutor};
use sqlx::{Error as SqlxError, FromRow, PgConnection, PgExecutor, query, query_as, query_scalar};
use utoipa::ToSchema;

use crate::db::{models::error::ModelError, Id, NoId, User, WireguardNetwork};
use crate::db::{Id, NoId, User, WireguardNetwork, models::error::ModelError};

#[derive(Debug)]
pub enum Permission {
Expand Down Expand Up @@ -300,7 +300,7 @@ mod test {
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};

use super::*;
use crate::db::{setup_pool, User};
use crate::db::{User, setup_pool};

#[sqlx::test]
async fn test_group(_: PgPoolOptions, options: PgConnectOptions) {
Expand Down Expand Up @@ -367,19 +367,23 @@ mod test {
.unwrap();
user.add_to_group(&pool, &group).await.unwrap();
assert!(!user.is_admin(&pool).await.unwrap());
assert!(!group
.has_permission(&pool, Permission::IsAdmin)
.await
.unwrap());
assert!(
!group
.has_permission(&pool, Permission::IsAdmin)
.await
.unwrap()
);
group
.set_permission(&pool, Permission::IsAdmin, true)
.await
.unwrap();

assert!(group
.has_permission(&pool, Permission::IsAdmin)
.await
.unwrap());
assert!(
group
.has_permission(&pool, Permission::IsAdmin)
.await
.unwrap()
);
assert!(user.is_admin(&pool).await.unwrap());
let groups = Group::find_by_permission(&pool, Permission::IsAdmin)
.await
Expand Down
2 changes: 1 addition & 1 deletion crates/defguard_core/src/db/models/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub mod yubikey;

use std::collections::HashSet;

use sqlx::{query_as, Error as SqlxError, PgConnection, PgPool};
use sqlx::{Error as SqlxError, PgConnection, PgPool, query_as};
use utoipa::ToSchema;

use self::{
Expand Down
2 changes: 1 addition & 1 deletion crates/defguard_core/src/db/models/oauth2authorizedapp.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use model_derive::Model;
use sqlx::{query_as, Error as SqlxError, PgPool};
use sqlx::{Error as SqlxError, PgPool, query_as};

use crate::db::{Id, NoId};

Expand Down
2 changes: 1 addition & 1 deletion crates/defguard_core/src/db/models/oauth2client.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use model_derive::Model;
use sqlx::{query_as, Error as SqlxError, PgPool};
use sqlx::{Error as SqlxError, PgPool, query_as};

use super::NewOpenIDClient;
use crate::{
Expand Down
2 changes: 1 addition & 1 deletion crates/defguard_core/src/db/models/oauth2token.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use chrono::{TimeDelta, Utc};
use sqlx::{query, query_as, Error as SqlxError, PgPool};
use sqlx::{Error as SqlxError, PgPool, query, query_as};

use crate::{db::Id, random::gen_alphanumeric, server_config};

Expand Down
2 changes: 1 addition & 1 deletion crates/defguard_core/src/db/models/polling_token.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use chrono::{NaiveDateTime, Utc};
use model_derive::Model;
use sqlx::{query_as, Error as SqlxError, PgExecutor, PgPool};
use sqlx::{Error as SqlxError, PgExecutor, PgPool, query_as};

use crate::{
db::{Id, NoId},
Expand Down
Loading