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

remove github services for devcontainers #12

Merged
merged 2 commits into from
Jul 12, 2024
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
18 changes: 1 addition & 17 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,6 @@ jobs:
build:
name: 'Rust Build'
runs-on: ubuntu-latest
services:
postgres:
image: postgres:12.19-alpine3.20
ports:
- 5432:5432
env:
POSTGRES_DB: demo
POSTGRES_USER: demo
POSTGRES_PASSWORD: demo_password
vault:
image: hashicorp/vault:1.17.1
ports:
- 8200:8200
options: --cap-add=IPC_LOCK
env:
VAULT_DEV_ROOT_TOKEN_ID: 'root-token'
steps:
- name: Check out code
uses: actions/checkout@v4
Expand All @@ -55,7 +39,7 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: clippy
# args: -- -D warnings
args: -- -D warnings
- name: Unit and Integration Tests
uses: actions-rs/cargo@v1
env:
Expand Down
6 changes: 4 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,17 @@ clap = { version = "4.5.8", features = ["derive"] }
env_logger = "0.11.3"
lazy_static = "1.5.0"
log = "0.4.22"
postgres = "0.19.7"
rand = "0.9.0-alpha.1"
serde = { version = "1.0.203", features = ["derive"] }
serde_yaml = "0.9.34+deprecated"
tokio = { version = "1.38.0", features = ["macros", "rt"] }
vaultrs = "0.7.2"
rand = "0.9.0-alpha.1"
postgres = "0.19.7"

[dev-dependencies]
assert_cmd = "2.0.14"
predicates = "3.1.0"
reqwest = { version = "0.12.5", features = ["json"] }
serde_json = "1.0.120"
testcontainers = { version = "0.20.0", features = ["blocking"] }
testcontainers-modules = { version = "0.8.0", features = ["blocking", "postgres"] }
10 changes: 8 additions & 2 deletions DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,15 @@ Cargo makes it easy to run the project's unit and integration tests:
cargo tests
```

**Note that the integration tests need active Vault and PostgreSQL connections, as described [here](#environment-setup).**
**Note that the integration tests make use of [testcontainers](https://testcontainers.com) in order to spin up ArgoCD, Vault and PostgreSQL.**

Cargo will automatically discover and execute the tests defined within the project.
#### A Note for Windows Users

If testcontainers fail to connect to your Docker socket on Windows, add the below environment variable to the test command:

```shell
DOCKER_HOST=tcp://localhost:2375 cargo test
```

### Running the CLI

Expand Down
Empty file modified dev/podman.sh
100755 → 100644
Empty file.
3 changes: 2 additions & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,15 @@ pub(crate) fn read_config(config_path: PathBuf) -> Config {

let mut config_data: String = String::new();
let mut config_file: File = File::open(config_path)
.expect(format!("Failed to read configuration file: '{path_string}'").as_str());
.unwrap_or_else(|_| panic!("Failed to read configuration file: '{path_string}'"));
config_file
.read_to_string(&mut config_data)
.expect("Failed to read configuration file");

serde_yaml::from_str(&config_data).expect("Failed to parse configuration")
}

#[cfg(test)]
mod tests {
use super::*;

Expand Down
7 changes: 4 additions & 3 deletions src/vault.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use vaultrs::kv2;

use crate::config::{Config, VaultConfig};

const VAULT_TOKEN: &'static str = "VAULT_TOKEN";
const VAULT_TOKEN: &str = "VAULT_TOKEN";

#[derive(Debug, Deserialize, Serialize)]
pub(crate) struct VaultStructure {
Expand Down Expand Up @@ -67,7 +67,7 @@ impl Vault {
self.rt.block_on(kv2::read(
&self.vault_client,
"secret",
&*self.vault_config.path,
&self.vault_config.path,
))
}

Expand All @@ -78,7 +78,7 @@ impl Vault {
self.rt.block_on(kv2::set(
&self.vault_client,
"secret",
&*self.vault_config.path,
&self.vault_config.path,
&vault_structure,
))
}
Expand All @@ -99,6 +99,7 @@ fn get_vault_client(config: &Config) -> VaultClient {
vault_client
}

#[cfg(test)]
mod tests {
use super::*;
use crate::config::PostgresConfig;
Expand Down
29 changes: 17 additions & 12 deletions src/workflow.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use std::fmt::format;

use log::{debug, trace};
use vaultrs::auth::userpass::user::update_password;

use crate::cli::RotateArgs;
use crate::config::Config;
Expand All @@ -21,7 +18,7 @@
let vault_path = config.vault.clone().path;
let mut secret: VaultStructure = vault
.read_secret()
.expect(format!("Failed to read path '{vault_path}' - did you init Vault?").as_str());
.unwrap_or_else(|_| panic!("Failed to read path '{vault_path}' - did you init Vault?"));

if secret.postgresql_active_user != secret.postgresql_user_1
&& secret.postgresql_active_user != secret.postgresql_user_2
Expand Down Expand Up @@ -55,11 +52,19 @@

fn switch_active_user(secret: &mut VaultStructure) {
if secret.postgresql_active_user == secret.postgresql_user_1 {
secret.postgresql_active_user = secret.postgresql_user_2.clone();
secret.postgresql_active_user_password = secret.postgresql_user_2_password.clone()
secret
.postgresql_active_user
.clone_from(&secret.postgresql_user_2);
secret
.postgresql_active_user_password
.clone_from(&secret.postgresql_user_2_password);
} else {
secret.postgresql_active_user = secret.postgresql_user_1.clone();
secret.postgresql_active_user_password = secret.postgresql_user_1_password.clone()
secret
.postgresql_active_user
.clone_from(&secret.postgresql_user_1);
secret
.postgresql_active_user_password
.clone_from(&secret.postgresql_user_1_password);
}

trace!("Switched active and passive user in Vault secret (locally)")
Expand All @@ -73,26 +78,26 @@
let (passive_user, passive_user_password) =
if secret.postgresql_active_user == secret.postgresql_user_1 {
let original_password = secret.postgresql_user_2_password.clone();
secret.postgresql_user_2_password = new_password.clone();
secret.postgresql_user_2_password.clone_from(&new_password);
(secret.postgresql_user_2.clone(), original_password)
} else {
let original_password = secret.postgresql_user_1_password.clone();
secret.postgresql_user_1_password = new_password.clone();
secret.postgresql_user_1_password.clone_from(&new_password);
(secret.postgresql_user_1.clone(), original_password)
};

let mut conn = db.connect_for_user(passive_user.clone(), passive_user_password);
let query = format!("ALTER ROLE {passive_user} WITH PASSWORD '{new_password}'");

conn.execute(query.as_str(), &[])
.expect(format!("Failed to update password of '{passive_user}'").as_str());
.unwrap_or_else(|_| panic!("Failed to update password of '{passive_user}'"));

debug!("Successfully rotated PostgreSQL password of passive user");
}

#[cfg(test)]
mod tests {
use super::*;
use postgres::Client;

#[test]
fn switch_active_user_user1_active() {
Expand Down Expand Up @@ -157,7 +162,7 @@
}

fn create_vault_structure_active_user_2() -> VaultStructure {
let mut secret = VaultStructure {

Check warning on line 165 in src/workflow.rs

View workflow job for this annotation

GitHub Actions / Rust Build

variable does not need to be mutable
postgresql_active_user: "user2".to_string(),
postgresql_active_user_password: "password2".to_string(),
postgresql_user_1: "user1".to_string(),
Expand Down
44 changes: 44 additions & 0 deletions tests/common/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use std::env::temp_dir;
use std::fs::File;
use std::io::Write;

use testcontainers::{
core::{IntoContainerPort, WaitFor},
Container, GenericImage, ImageExt,
};
use testcontainers_modules::postgres::Postgres;
use testcontainers_modules::testcontainers::runners::SyncRunner;

pub(crate) fn postgres_container() -> Container<Postgres> {

Check warning on line 12 in tests/common/mod.rs

View workflow job for this annotation

GitHub Actions / Rust Build

function `postgres_container` is never used
Postgres::default()
.with_env_var("POSTGRES_DB", "demo")
.with_env_var("POSTGRES_USER", "demo")
.with_env_var("POSTGRES_PASSWORD", "demo_password")
.start()
.expect("PostgreSQL database started")
}

pub(crate) fn vault_container() -> Container<GenericImage> {
GenericImage::new("hashicorp/vault", "1.17.1")
.with_exposed_port(8200.tcp())
.with_wait_for(WaitFor::message_on_stdout(
"==> Vault server started! Log data will stream in below",
))
.with_env_var("VAULT_DEV_ROOT_TOKEN_ID", "root-token")
.start()
.expect("Vault started")
}

pub(crate) fn write_string_to_tempfile(content: &str) -> String {
let mut dir = temp_dir();
let filename = format!("temp_file_{}", rand::random::<u64>());

dir.push(filename);

let mut file = File::create(dir.clone()).expect("Failed to create tmp file");

file.write_all(content.as_bytes())
.expect("Failed to write into tmp file");

dir.to_string_lossy().to_string()
}
29 changes: 26 additions & 3 deletions tests/init_vault.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,37 @@ use reqwest::{Client, Response};
use serde_json::Value;
use tokio::runtime::{Builder, Runtime};

mod common;

lazy_static! {
static ref BIN_PATH: PathBuf = cargo_bin(env!("CARGO_PKG_NAME"));
}

#[test]
fn init_vault_new_path() {
let vault_container = common::vault_container();

let vault_host = vault_container.get_host().unwrap();
let vault_port = vault_container.get_host_port_ipv4(8200).unwrap();

Command::new(&*BIN_PATH)
.arg("init-vault")
.arg("-c")
.arg("tests/resources/init_vault/new_path.yml")
.arg(common::write_string_to_tempfile(
format!(
// language=yaml
"
postgres:
host: 'localhost'
port: 5432
database: 'demo'
vault:
address: 'http://{vault_host}:{vault_port}'
path: 'init/vault/new/path'
"
)
.as_str(),
))
.env("VAULT_TOKEN", "root-token")
.assert()
.success()
Expand All @@ -27,10 +48,10 @@ fn init_vault_new_path() {
));

let client = Client::new();
let url = "http://localhost:8200/v1/secret/data/init/vault/new/path";
let url = format!("http://{vault_host}:{vault_port}/v1/secret/data/init/vault/new/path");

let rt: Runtime = create_tokio_runtime();
let json = read_secret_as_json(client, url, rt);
let json = read_secret_as_json(client, url.as_str(), rt);

assert_json_value_equals(&json, "postgresql_active_user", "TBD");
assert_json_value_equals(&json, "postgresql_active_user_password", "TBD");
Expand All @@ -42,6 +63,8 @@ fn init_vault_new_path() {

#[test]
fn init_vault_invalid_url() {
common::vault_container();

Command::new(&*BIN_PATH)
.arg("init-vault")
.arg("-c")
Expand Down
7 changes: 0 additions & 7 deletions tests/resources/init_vault/new_path.yml

This file was deleted.

7 changes: 0 additions & 7 deletions tests/resources/rotate/invalid_initialized_secret.yml

This file was deleted.

7 changes: 0 additions & 7 deletions tests/resources/rotate/non_existing_secret.yml

This file was deleted.

7 changes: 0 additions & 7 deletions tests/resources/rotate/secrets.yml

This file was deleted.

Loading
Loading