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

Add login-prefix config option for created logins #29

Merged
merged 2 commits into from
Jan 29, 2022
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
94 changes: 94 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Based on https://github.com/actions-rs/meta/blob/master/recipes/quickstart.md
#
# While our "example" application has the platform-specific code,
# for simplicity we are compiling and testing everything on the Ubuntu environment only.
# For multi-OS testing see the `cross.yml` workflow.

on: [push, pull_request]

name: Tests

jobs:
check:
name: Check ${{ matrix.db_feature }} (${{ matrix.os }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest]
rust: [stable]
db_feature: [db-sled, db-redis, db-mongo]
steps:
- name: Checkout sources
uses: actions/checkout@v2

- name: Install toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: ${{ matrix.rust }}
override: true

- name: Run cargo check
uses: actions-rs/cargo@v1
with:
command: check
args: --no-default-features --features=secure-auth,${{ matrix.db_feature }},crates-io-mirroring

test:
name: Test ${{ matrix.db_feature }} (${{ matrix.os }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest]
rust: [stable]
db_feature: [db-sled, db-redis, db-mongo]
steps:
- name: Checkout sources
uses: actions/checkout@v2

- name: Install toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: ${{ matrix.rust }}
override: true

- name: Run cargo test
uses: actions-rs/cargo@v1
with:
command: test
args: --no-default-features --features=secure-auth,${{ matrix.db_feature }},crates-io-mirroring

lints:
name: Lints (${{ matrix.os }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest]
steps:
- name: Checkout sources
uses: actions/checkout@v2

- name: Install stable toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true
components: rustfmt, clippy

- name: Run cargo fmt
uses: actions-rs/cargo@v1
with:
command: fmt
args: --all -- --check

- name: Run cargo clippy
uses: actions-rs/cargo@v1
continue-on-error: true # Set until the lints are fixed separately
with:
command: clippy
args: -- -D warnings
8 changes: 8 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ impl CrateFilesConfig {

#[derive(Debug, Clone, Deserialize)]
pub struct DbConfig {
#[serde(default = "DbConfig::login_prefix_default")]
pub login_prefix: String,

#[cfg(feature = "db-sled")]
#[serde(default = "DbConfig::db_dir_path_default")]
pub db_dir_path: PathBuf,
Expand All @@ -92,6 +95,7 @@ pub struct DbConfig {
impl Default for DbConfig {
fn default() -> DbConfig {
DbConfig {
login_prefix: DbConfig::login_prefix_default(),
#[cfg(feature = "db-sled")]
db_dir_path: DbConfig::db_dir_path_default(),
#[cfg(feature = "db-redis")]
Expand All @@ -103,6 +107,10 @@ impl Default for DbConfig {
}

impl DbConfig {
fn login_prefix_default() -> String {
"ktra-secure-auth:".to_owned()
}

#[cfg(feature = "db-sled")]
fn db_dir_path_default() -> PathBuf {
PathBuf::from("db")
Expand Down
8 changes: 7 additions & 1 deletion src/db_manager/mongo_db_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ struct EntryMap {
pub struct MongoDbManager {
client: Client,
database_name: String,
login_prefix: String,
}

#[async_trait]
Expand Down Expand Up @@ -79,13 +80,18 @@ impl DbManager for MongoDbManager {
let db_manager = MongoDbManager {
client,
database_name,
login_prefix: config.login_prefix.clone(),
};
Ok(db_manager)
};

initialization.map_err(Error::Db).await
}

async fn get_login_prefix(&self) -> Result<&str, Error> {
Ok(&self.login_prefix)
}

#[tracing::instrument(skip(self, user_id, name))]
async fn can_edit_owners(&self, user_id: u32, name: &str) -> Result<bool, Error> {
check_crate_name(&name)?;
Expand Down Expand Up @@ -233,7 +239,7 @@ impl DbManager for MongoDbManager {
#[tracing::instrument(skip(self, name))]
async fn user_by_username(&self, name: &str) -> Result<User, Error> {
let name = name.to_owned();
let login = format!("ktra-secure-auth:{}", name);
let login = format!("{}{}", self.login_prefix, name);
let collection = self
.client
.database(&self.database_name)
Expand Down
12 changes: 10 additions & 2 deletions src/db_manager/redis_db_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const TOKENS_KEY: &str = "ktra:__TOKENS__";

pub struct RedisDbManager {
client: Client,
login_prefix: String,
}

#[async_trait]
Expand All @@ -42,13 +43,20 @@ impl DbManager for RedisDbManager {
connection.set(SCHEMA_VERSION_KEY, &SCHEMA_VERSION).await?;
}

let db_manager = RedisDbManager { client };
let db_manager = RedisDbManager {
client,
login_prefix: config.login_prefix.clone(),
};
Ok(db_manager)
};

initialization.map_err(Error::Db).await
}

async fn get_login_prefix(&self) -> Result<&str, Error> {
Ok(&self.login_prefix)
}

#[tracing::instrument(skip(self, user_id, name))]
async fn can_edit_owners(&self, user_id: u32, name: &str) -> Result<bool, Error> {
check_crate_name(&name)?;
Expand Down Expand Up @@ -134,7 +142,7 @@ impl DbManager for RedisDbManager {
#[tracing::instrument(skip(self, name))]
async fn user_by_username(&self, name: &str) -> Result<User, Error> {
let name = name.into();
let login = format!("ktra-secure-auth:{}", name);
let login = format!("{}{}", self.login_prefix, name);
let mut users: Vec<User> = self.deserialize(USERS_KEY).await?.unwrap_or_default();

users.sort_by_key(|u| u.login.clone());
Expand Down
12 changes: 10 additions & 2 deletions src/db_manager/sled_db_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const OLD_TOKENS_KEY: &str = "tokens";

pub struct SledDbManager {
tree: Db,
login_prefix: String,
}

#[async_trait]
Expand All @@ -48,11 +49,18 @@ impl DbManager for SledDbManager {
tree.flush_async().map_err(Error::Db).await?;
}

let db_manager = SledDbManager { tree };
let db_manager = SledDbManager {
tree,
login_prefix: config.login_prefix.clone(),
};

Ok(db_manager)
}

async fn get_login_prefix(&self) -> Result<&str, Error> {
Ok(&self.login_prefix)
}

#[tracing::instrument(skip(self, user_id, name))]
async fn can_edit_owners(&self, user_id: u32, name: &str) -> Result<bool, Error> {
check_crate_name(&name)?;
Expand Down Expand Up @@ -136,7 +144,7 @@ impl DbManager for SledDbManager {
#[tracing::instrument(skip(self, name))]
async fn user_by_username(&self, name: &str) -> Result<User, Error> {
let name = name.into();
let login = format!("ktra-secure-auth:{}", name);
let login = format!("{}{}", self.login_prefix, name);
let mut users: Vec<User> = self.deserialize(USERS_KEY)?.unwrap_or_default();

users.sort_by_key(|u| u.login.clone());
Expand Down
1 change: 1 addition & 0 deletions src/db_manager/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use semver::Version;
#[async_trait]
pub trait DbManager: Send + Sync + Sized {
async fn new(confg: &DbConfig) -> Result<Self, Error>;
async fn get_login_prefix(&self) -> Result<&str, Error>;

async fn can_edit_owners(&self, user_id: u32, name: &str) -> Result<bool, Error>;
async fn owners(&self, name: &str) -> Result<Vec<User>, Error>;
Expand Down
5 changes: 5 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ fn matches() -> ArgMatches<'static> {
(@arg DL_DIR_PATH: --("dl-dir-path") +takes_value "Sets the crate files directory")
(@arg CACHE_DIR_PATH: --("cache-dir-path") +takes_value "Sets the crates.io cache files directory (needs `crates-io-mirroring` feature)")
(@arg DL_PATH: --("dl-path") +takes_value ... "Sets a crate files download path")
(@arg LOGIN_PREFIX: --("login-prefix") +takes_value "Sets the prefix to registered users on the registry.")
(@arg DB_DIR_PATH: --("db-dir-path") +takes_value "Sets a database directory (needs `db-sled` feature)")
(@arg REDIS_URL: --("redis-url") + takes_value "Sets a Redis URL (needs `db-redis` feature)")
(@arg MONGODB_URL: --("mongodb-url") + takes_value "Sets a MongoDB URL (needs `db-mongo` feature)")
Expand Down Expand Up @@ -220,6 +221,10 @@ async fn main() -> anyhow::Result<()> {
config.crate_files_config.dl_path = dl_path;
}

if let Some(login_prefix) = matches.value_of("LOGIN_PREFIX") {
config.db_config.login_prefix = login_prefix.into();
}

#[cfg(feature = "db-sled")]
if let Some(db_dir_path) = matches.value_of("DB_DIR_PATH").map(PathBuf::from) {
config.db_config.db_dir_path = db_dir_path;
Expand Down
2 changes: 1 addition & 1 deletion src/post.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ async fn handle_new_user(
.map_ok(|user_id| user_id.map(|u| u + 1).unwrap_or(0))
.map_err(warp::reject::custom)
.await?;
let login_id = format!("ktra-secure-auth:{}", name);
let login_id = format!("{}{}", db_manager.get_login_prefix().await?, name);
let user = User::new(user_id, login_id, Some(name));

db_manager
Expand Down