mirror of
https://github.com/moghtech/komodo.git
synced 2026-11-02 08:29:18 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c6f38cafb | ||
|
|
4a03eba99a | ||
|
|
79fe078e3b | ||
|
|
6be032fcd4 | ||
|
|
d0c94278ec | ||
|
|
03ae7268fd | ||
|
|
f443294818 | ||
|
|
2202835d86 | ||
|
|
98fbc7a506 | ||
|
|
8ee89296e1 | ||
|
|
989c3d2d01 | ||
|
|
dc72883b90 | ||
|
|
e99364430f | ||
|
|
e106e38cd9 | ||
|
|
e4d0c56e49 | ||
|
|
7427a158f4 | ||
|
|
b926f89954 | ||
|
|
e666a22f08 | ||
|
|
4107f779a5 | ||
|
|
828d6cdfed | ||
|
|
fe82400a99 | ||
|
|
e37fc6adde | ||
|
|
c21c8f99ae | ||
|
|
78a63f92bb | ||
|
|
ce67655021 | ||
|
|
2ccecf38f2 | ||
|
|
1ddae31aad | ||
|
|
097fbefa63 | ||
|
|
b51442a661 | ||
|
|
a21d49d224 | ||
|
|
c99a33880e | ||
|
|
6ee55262ba | ||
|
|
878b9b55bb | ||
|
|
af6193f83a | ||
|
|
b8fefddd8b | ||
|
|
7f490f5bf2 | ||
|
|
efa7c13286 | ||
|
|
f913be7a0b | ||
|
|
35901ef7ea | ||
|
|
5b938490fc | ||
|
|
a7326a0116 | ||
|
|
877bda91d7 | ||
|
|
439a091e50 | ||
|
|
b0e89f4963 | ||
|
|
b1e4b55ba1 | ||
|
|
d4a1891c70 | ||
|
|
9db7592d7e | ||
|
|
84fb603951 | ||
|
|
55bac0dd13 | ||
|
|
b143f42363 | ||
|
|
007efd136a | ||
|
|
b329767f9e | ||
|
|
b4231957d5 | ||
|
|
b4dc446f95 | ||
|
|
c92515cecc | ||
|
|
f3712feea2 | ||
|
|
0e81d17860 | ||
|
|
c3f1557b83 | ||
|
|
5f88e4b436 | ||
|
|
473c6b3867 | ||
|
|
c10edaa5d1 |
Generated
+534
-98
File diff suppressed because it is too large
Load Diff
+15
-11
@@ -3,7 +3,7 @@ resolver = "2"
|
||||
members = ["bin/*", "lib/*", "client/core/rs", "client/periphery/rs"]
|
||||
|
||||
[workspace.package]
|
||||
version = "1.9.0"
|
||||
version = "1.11.0"
|
||||
edition = "2021"
|
||||
authors = ["mbecker20 <becker.maxh@gmail.com>"]
|
||||
license = "GPL-3.0-or-later"
|
||||
@@ -15,7 +15,7 @@ monitor_client = { path = "client/core/rs" }
|
||||
|
||||
[workspace.dependencies]
|
||||
# LOCAL
|
||||
monitor_client = "1.9.0"
|
||||
monitor_client = "1.11.0"
|
||||
periphery_client = { path = "client/periphery/rs" }
|
||||
formatting = { path = "lib/formatting" }
|
||||
command = { path = "lib/command" }
|
||||
@@ -29,19 +29,19 @@ slack = { version = "0.1.0", package = "slack_client_rs" }
|
||||
derive_default_builder = "0.1.8"
|
||||
derive_empty_traits = "0.1.0"
|
||||
merge_config_files = "0.1.5"
|
||||
async_timing_util = "0.1.14"
|
||||
async_timing_util = "1.0.0"
|
||||
partial_derive2 = "0.4.3"
|
||||
derive_variants = "1.0.0"
|
||||
mongo_indexed = "0.3.0"
|
||||
resolver_api = "1.1.0"
|
||||
mongo_indexed = "1.0.0"
|
||||
resolver_api = "1.1.1"
|
||||
toml_pretty = "1.1.2"
|
||||
parse_csl = "0.1.0"
|
||||
mungos = "0.5.6"
|
||||
mungos = "1.0.0"
|
||||
svi = "1.0.1"
|
||||
|
||||
# ASYNC
|
||||
tokio = { version = "1.38.0", features = ["full"] }
|
||||
reqwest = { version = "0.12.4", features = ["json"] }
|
||||
reqwest = { version = "0.12.5", features = ["json"] }
|
||||
tokio-util = "0.7.11"
|
||||
futures = "0.3.30"
|
||||
futures-util = "0.3.30"
|
||||
@@ -57,7 +57,7 @@ tokio-tungstenite = "0.23.1"
|
||||
ordered_hash_map = { version = "0.4.0", features = ["serde"] }
|
||||
serde = { version = "1.0.203", features = ["derive"] }
|
||||
strum = { version = "0.26.2", features = ["derive"] }
|
||||
serde_json = "1.0.117"
|
||||
serde_json = "1.0.118"
|
||||
toml = "0.8.14"
|
||||
|
||||
# ERROR
|
||||
@@ -78,8 +78,9 @@ dotenv = "0.15.0"
|
||||
envy = "0.4.2"
|
||||
|
||||
# CRYPTO
|
||||
uuid = { version = "1.8.0", features = ["v4", "fast-rng", "serde"] }
|
||||
uuid = { version = "1.9.1", features = ["v4", "fast-rng", "serde"] }
|
||||
urlencoding = "2.1.3"
|
||||
nom_pem = "4.0.0"
|
||||
bcrypt = "0.15.1"
|
||||
base64 = "0.22.1"
|
||||
hmac = "0.12.1"
|
||||
@@ -93,12 +94,15 @@ bollard = "0.16.1"
|
||||
sysinfo = "0.30.12"
|
||||
|
||||
# CLOUD
|
||||
aws-config = "1.5.1"
|
||||
aws-sdk-ec2 = "1.51.1"
|
||||
aws-config = "1.5.3"
|
||||
aws-sdk-ec2 = "1.53.0"
|
||||
aws-sdk-ecr = "1.33.0"
|
||||
|
||||
# MISC
|
||||
derive_builder = "0.20.0"
|
||||
typeshare = "1.0.3"
|
||||
octorust = "0.7.0"
|
||||
colored = "2.1.0"
|
||||
regex = "1.10.5"
|
||||
bson = "2.11.0"
|
||||
|
||||
|
||||
@@ -45,9 +45,11 @@ axum-extra.workspace = true
|
||||
tower-http.workspace = true
|
||||
serde_json.workspace = true
|
||||
typeshare.workspace = true
|
||||
octorust.workspace = true
|
||||
tracing.workspace = true
|
||||
reqwest.workspace = true
|
||||
futures.workspace = true
|
||||
nom_pem.workspace = true
|
||||
anyhow.workspace = true
|
||||
dotenv.workspace = true
|
||||
bcrypt.workspace = true
|
||||
@@ -56,6 +58,7 @@ tokio.workspace = true
|
||||
tower.workspace = true
|
||||
serde.workspace = true
|
||||
strum.workspace = true
|
||||
regex.workspace = true
|
||||
axum.workspace = true
|
||||
toml.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::{collections::HashSet, time::Duration};
|
||||
use std::{collections::HashSet, future::IntoFuture, time::Duration};
|
||||
|
||||
use anyhow::{anyhow, Context};
|
||||
use formatting::{format_serror, muted};
|
||||
@@ -145,8 +145,10 @@ impl Resolve<RunBuild, (User, Update)> for State {
|
||||
"get builder",
|
||||
format_serror(&e.context("failed to get builder").into()),
|
||||
));
|
||||
return handle_early_return(update, build.id, build.name)
|
||||
.await;
|
||||
return handle_early_return(
|
||||
update, build.id, build.name, false,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -172,7 +174,7 @@ impl Resolve<RunBuild, (User, Update)> for State {
|
||||
cleanup_builder_instance(periphery, cleanup_data, &mut update)
|
||||
.await;
|
||||
info!("builder cleaned up");
|
||||
return handle_early_return(update, build.id, build.name).await
|
||||
return handle_early_return(update, build.id, build.name, true).await
|
||||
},
|
||||
};
|
||||
|
||||
@@ -196,6 +198,9 @@ impl Resolve<RunBuild, (User, Update)> for State {
|
||||
// Interpolate variables / secrets into build args
|
||||
let mut global_replacers = HashSet::new();
|
||||
let mut secret_replacers = HashSet::new();
|
||||
let mut secret_replacers_for_log = HashSet::new();
|
||||
|
||||
// Interpolate into build args
|
||||
for arg in &mut build.config.build_args {
|
||||
// first pass - global variables
|
||||
let (res, more_replacers) = svi::interpolate_variables(
|
||||
@@ -214,10 +219,40 @@ impl Resolve<RunBuild, (User, Update)> for State {
|
||||
false,
|
||||
)
|
||||
.context("failed to interpolate core secrets")?;
|
||||
secret_replacers_for_log.extend(
|
||||
more_replacers.iter().map(|(_, variable)| variable.clone()),
|
||||
);
|
||||
secret_replacers.extend(more_replacers);
|
||||
arg.value = res;
|
||||
}
|
||||
|
||||
// Interpolate into secret args
|
||||
for arg in &mut build.config.secret_args {
|
||||
// first pass - global variables
|
||||
let (res, more_replacers) = svi::interpolate_variables(
|
||||
&arg.value,
|
||||
&variables,
|
||||
svi::Interpolator::DoubleBrackets,
|
||||
false,
|
||||
)
|
||||
.context("failed to interpolate global variables")?;
|
||||
global_replacers.extend(more_replacers);
|
||||
// second pass - core secrets
|
||||
let (res, more_replacers) = svi::interpolate_variables(
|
||||
&res,
|
||||
&core_config.secrets,
|
||||
svi::Interpolator::DoubleBrackets,
|
||||
false,
|
||||
)
|
||||
.context("failed to interpolate core secrets")?;
|
||||
secret_replacers_for_log.extend(
|
||||
more_replacers.into_iter().map(|(_, variable)| variable),
|
||||
);
|
||||
// Secret args don't need to be in replacers sent to periphery.
|
||||
// The secret args don't end up in the command like build args do.
|
||||
arg.value = res;
|
||||
}
|
||||
|
||||
// Show which variables were interpolated
|
||||
if !global_replacers.is_empty() {
|
||||
update.push_simple_log(
|
||||
@@ -229,12 +264,12 @@ impl Resolve<RunBuild, (User, Update)> for State {
|
||||
.join("\n"),
|
||||
);
|
||||
}
|
||||
if !secret_replacers.is_empty() {
|
||||
if !secret_replacers_for_log.is_empty() {
|
||||
update.push_simple_log(
|
||||
"interpolate core secrets",
|
||||
secret_replacers
|
||||
.iter()
|
||||
.map(|(_, variable)| format!("<span class=\"text-muted-foreground\">replaced:</span> {variable}"))
|
||||
secret_replacers_for_log
|
||||
.into_iter()
|
||||
.map(|variable| format!("<span class=\"text-muted-foreground\">replaced:</span> {variable}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
);
|
||||
@@ -253,7 +288,7 @@ impl Resolve<RunBuild, (User, Update)> for State {
|
||||
update.push_error_log("build cancelled", String::from("user cancelled build during docker build"));
|
||||
cleanup_builder_instance(periphery, cleanup_data, &mut update)
|
||||
.await;
|
||||
return handle_early_return(update, build.id, build.name).await
|
||||
return handle_early_return(update, build.id, build.name, true).await
|
||||
},
|
||||
};
|
||||
|
||||
@@ -288,7 +323,6 @@ impl Resolve<RunBuild, (User, Update)> for State {
|
||||
"info.last_built_at": monitor_timestamp(),
|
||||
}
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -320,12 +354,11 @@ impl Resolve<RunBuild, (User, Update)> for State {
|
||||
// don't hold response up for user
|
||||
tokio::spawn(async move {
|
||||
handle_post_build_redeploy(&build.id).await;
|
||||
info!("post build redeploy handled");
|
||||
});
|
||||
} else {
|
||||
warn!("build unsuccessful, alerting...");
|
||||
let target = update.target.clone();
|
||||
let version = update.version;
|
||||
let err = update.logs.iter().find(|l| !l.success).cloned();
|
||||
tokio::spawn(async move {
|
||||
let alert = Alert {
|
||||
id: Default::default(),
|
||||
@@ -337,7 +370,6 @@ impl Resolve<RunBuild, (User, Update)> for State {
|
||||
data: AlertData::BuildFailed {
|
||||
id: build.id,
|
||||
name: build.name,
|
||||
err,
|
||||
version,
|
||||
},
|
||||
};
|
||||
@@ -354,6 +386,7 @@ async fn handle_early_return(
|
||||
mut update: Update,
|
||||
build_id: String,
|
||||
build_name: String,
|
||||
is_cancel: bool,
|
||||
) -> anyhow::Result<Update> {
|
||||
update.finalize();
|
||||
// Need to manually update the update before cache refresh,
|
||||
@@ -371,10 +404,10 @@ async fn handle_early_return(
|
||||
refresh_build_state_cache().await;
|
||||
}
|
||||
update_update(update.clone()).await?;
|
||||
if !update.success {
|
||||
if !update.success && !is_cancel {
|
||||
warn!("build unsuccessful, alerting...");
|
||||
let target = update.target.clone();
|
||||
let version = update.version;
|
||||
let err = update.logs.iter().find(|l| !l.success).cloned();
|
||||
tokio::spawn(async move {
|
||||
let alert = Alert {
|
||||
id: Default::default(),
|
||||
@@ -387,7 +420,6 @@ async fn handle_early_return(
|
||||
id: build_id,
|
||||
name: build_name,
|
||||
version,
|
||||
err,
|
||||
},
|
||||
};
|
||||
send_alerts(&[alert]).await
|
||||
@@ -406,24 +438,28 @@ pub async fn validate_cancel_build(
|
||||
let db = db_client().await;
|
||||
|
||||
let (latest_build, latest_cancel) = tokio::try_join!(
|
||||
db.updates.find_one(
|
||||
doc! {
|
||||
db.updates
|
||||
.find_one(doc! {
|
||||
"operation": "RunBuild",
|
||||
"target.id": &build.id,
|
||||
},
|
||||
FindOneOptions::builder()
|
||||
.sort(doc! { "start_ts": -1 })
|
||||
.build(),
|
||||
),
|
||||
db.updates.find_one(
|
||||
doc! {
|
||||
},)
|
||||
.with_options(
|
||||
FindOneOptions::builder()
|
||||
.sort(doc! { "start_ts": -1 })
|
||||
.build()
|
||||
)
|
||||
.into_future(),
|
||||
db.updates
|
||||
.find_one(doc! {
|
||||
"operation": "CancelBuild",
|
||||
"target.id": &build.id,
|
||||
},
|
||||
FindOneOptions::builder()
|
||||
.sort(doc! { "start_ts": -1 })
|
||||
.build(),
|
||||
)
|
||||
},)
|
||||
.with_options(
|
||||
FindOneOptions::builder()
|
||||
.sort(doc! { "start_ts": -1 })
|
||||
.build()
|
||||
)
|
||||
.into_future()
|
||||
)?;
|
||||
|
||||
match (latest_build, latest_cancel) {
|
||||
|
||||
@@ -181,7 +181,6 @@ async fn update_last_pulled_time(repo_name: &str) {
|
||||
.update_one(
|
||||
doc! { "name": repo_name },
|
||||
doc! { "$set": { "info.last_pulled_at": monitor_timestamp() } },
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
if let Err(e) = res {
|
||||
|
||||
@@ -36,12 +36,9 @@ impl Resolve<LaunchServer, (User, Update)> for State {
|
||||
if db_client()
|
||||
.await
|
||||
.servers
|
||||
.find_one(
|
||||
doc! {
|
||||
"name": &name
|
||||
},
|
||||
None,
|
||||
)
|
||||
.find_one(doc! {
|
||||
"name": &name
|
||||
})
|
||||
.await
|
||||
.context("failed to query db for servers")?
|
||||
.is_some()
|
||||
|
||||
@@ -14,7 +14,7 @@ use resolver_api::Resolve;
|
||||
|
||||
use crate::{
|
||||
config::core_config,
|
||||
helpers::query::get_resource_ids_for_non_admin,
|
||||
helpers::query::get_resource_ids_for_user,
|
||||
state::{db_client, State},
|
||||
};
|
||||
|
||||
@@ -28,13 +28,13 @@ impl Resolve<ListAlerts, User> for State {
|
||||
) -> anyhow::Result<ListAlertsResponse> {
|
||||
let mut query = query.unwrap_or_default();
|
||||
if !user.admin && !core_config().transparent_mode {
|
||||
let server_ids = get_resource_ids_for_non_admin(
|
||||
&user.id,
|
||||
let server_ids = get_resource_ids_for_user(
|
||||
&user,
|
||||
ResourceTargetVariant::Server,
|
||||
)
|
||||
.await?;
|
||||
let deployment_ids = get_resource_ids_for_non_admin(
|
||||
&user.id,
|
||||
let deployment_ids = get_resource_ids_for_user(
|
||||
&user,
|
||||
ResourceTargetVariant::Deployment,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use std::str::FromStr;
|
||||
|
||||
use anyhow::Context;
|
||||
use mongo_indexed::Document;
|
||||
use monitor_client::{
|
||||
api::read::*,
|
||||
entities::{
|
||||
@@ -10,12 +9,11 @@ use monitor_client::{
|
||||
user::User,
|
||||
},
|
||||
};
|
||||
use mungos::mongodb::bson::{doc, oid::ObjectId};
|
||||
use mungos::mongodb::bson::doc;
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::{
|
||||
config::core_config,
|
||||
helpers::query::get_resource_ids_for_non_admin,
|
||||
helpers::query::get_resource_ids_for_user,
|
||||
resource,
|
||||
state::{db_client, State},
|
||||
};
|
||||
@@ -61,26 +59,21 @@ impl Resolve<GetAlertersSummary, User> for State {
|
||||
GetAlertersSummary {}: GetAlertersSummary,
|
||||
user: User,
|
||||
) -> anyhow::Result<GetAlertersSummaryResponse> {
|
||||
let query = if user.admin || core_config().transparent_mode {
|
||||
None
|
||||
} else {
|
||||
let ids = get_resource_ids_for_non_admin(
|
||||
&user.id,
|
||||
ResourceTargetVariant::Alerter,
|
||||
)
|
||||
.await?
|
||||
.into_iter()
|
||||
.flat_map(|id| ObjectId::from_str(&id))
|
||||
.collect::<Vec<_>>();
|
||||
let query = doc! {
|
||||
let query = match get_resource_ids_for_user(
|
||||
&user,
|
||||
ResourceTargetVariant::Alerter,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Some(ids) => doc! {
|
||||
"_id": { "$in": ids }
|
||||
};
|
||||
Some(query)
|
||||
},
|
||||
None => Document::new(),
|
||||
};
|
||||
let total = db_client()
|
||||
.await
|
||||
.alerters
|
||||
.count_documents(query, None)
|
||||
.count_documents(query)
|
||||
.await
|
||||
.context("failed to count all alerter documents")?;
|
||||
let res = GetAlertersSummaryResponse {
|
||||
|
||||
@@ -10,6 +10,7 @@ use monitor_client::{
|
||||
api::read::*,
|
||||
entities::{
|
||||
build::{Build, BuildActionState, BuildListItem, BuildState},
|
||||
config::core::CoreConfig,
|
||||
permission::PermissionLevel,
|
||||
update::UpdateStatus,
|
||||
user::User,
|
||||
@@ -25,7 +26,9 @@ use resolver_api::{Resolve, ResolveToString};
|
||||
use crate::{
|
||||
config::core_config,
|
||||
resource,
|
||||
state::{action_states, build_state_cache, db_client, State},
|
||||
state::{
|
||||
action_states, build_state_cache, db_client, github_client, State,
|
||||
},
|
||||
};
|
||||
|
||||
impl Resolve<GetBuild, User> for State {
|
||||
@@ -147,16 +150,13 @@ impl Resolve<GetBuildMonthlyStats, User> for State {
|
||||
let mut build_updates = db_client()
|
||||
.await
|
||||
.updates
|
||||
.find(
|
||||
doc! {
|
||||
"start_ts": {
|
||||
"$gte": open_ts,
|
||||
"$lt": close_ts
|
||||
},
|
||||
"operation": Operation::RunBuild.to_string(),
|
||||
.find(doc! {
|
||||
"start_ts": {
|
||||
"$gte": open_ts,
|
||||
"$lt": close_ts
|
||||
},
|
||||
None,
|
||||
)
|
||||
"operation": Operation::RunBuild.to_string(),
|
||||
})
|
||||
.await
|
||||
.context("failed to get updates cursor")?;
|
||||
|
||||
@@ -310,3 +310,76 @@ impl Resolve<ListCommonBuildExtraArgs, User> for State {
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve<GetBuildWebhookEnabled, User> for State {
|
||||
async fn resolve(
|
||||
&self,
|
||||
GetBuildWebhookEnabled { build }: GetBuildWebhookEnabled,
|
||||
user: User,
|
||||
) -> anyhow::Result<GetBuildWebhookEnabledResponse> {
|
||||
let Some(github) = github_client() else {
|
||||
return Ok(GetBuildWebhookEnabledResponse {
|
||||
managed: false,
|
||||
enabled: false,
|
||||
});
|
||||
};
|
||||
|
||||
let build = resource::get_check_permissions::<Build>(
|
||||
&build,
|
||||
&user,
|
||||
PermissionLevel::Read,
|
||||
)
|
||||
.await?;
|
||||
|
||||
if build.config.repo.is_empty() {
|
||||
return Ok(GetBuildWebhookEnabledResponse {
|
||||
managed: false,
|
||||
enabled: false,
|
||||
});
|
||||
}
|
||||
|
||||
let mut split = build.config.repo.split('/');
|
||||
let owner = split.next().context("Build repo has no owner")?;
|
||||
|
||||
let Some(github) = github.get(owner) else {
|
||||
return Ok(GetBuildWebhookEnabledResponse {
|
||||
managed: false,
|
||||
enabled: false,
|
||||
});
|
||||
};
|
||||
|
||||
let repo =
|
||||
split.next().context("Build repo has no repo after the /")?;
|
||||
|
||||
let github_repos = github.repos();
|
||||
|
||||
let webhooks = github_repos
|
||||
.list_all_webhooks(owner, repo)
|
||||
.await
|
||||
.context("failed to list all webhooks on repo")?
|
||||
.body;
|
||||
|
||||
let CoreConfig {
|
||||
host,
|
||||
github_webhook_base_url,
|
||||
..
|
||||
} = core_config();
|
||||
|
||||
let host = github_webhook_base_url.as_ref().unwrap_or(host);
|
||||
let url = format!("{host}/listener/github/build/{}", build.id);
|
||||
|
||||
for webhook in webhooks {
|
||||
if webhook.active && webhook.config.url == url {
|
||||
return Ok(GetBuildWebhookEnabledResponse {
|
||||
managed: true,
|
||||
enabled: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(GetBuildWebhookEnabledResponse {
|
||||
managed: true,
|
||||
enabled: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::{collections::HashSet, str::FromStr};
|
||||
use std::collections::HashSet;
|
||||
|
||||
use anyhow::Context;
|
||||
use mongo_indexed::Document;
|
||||
use monitor_client::{
|
||||
api::read::{self, *},
|
||||
entities::{
|
||||
@@ -10,12 +11,12 @@ use monitor_client::{
|
||||
user::User,
|
||||
},
|
||||
};
|
||||
use mungos::mongodb::bson::{doc, oid::ObjectId};
|
||||
use mungos::mongodb::bson::doc;
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::{
|
||||
config::core_config,
|
||||
helpers::query::get_resource_ids_for_non_admin,
|
||||
helpers::query::get_resource_ids_for_user,
|
||||
resource,
|
||||
state::{db_client, State},
|
||||
};
|
||||
@@ -61,26 +62,21 @@ impl Resolve<GetBuildersSummary, User> for State {
|
||||
GetBuildersSummary {}: GetBuildersSummary,
|
||||
user: User,
|
||||
) -> anyhow::Result<GetBuildersSummaryResponse> {
|
||||
let query = if user.admin || core_config().transparent_mode {
|
||||
None
|
||||
} else {
|
||||
let ids = get_resource_ids_for_non_admin(
|
||||
&user.id,
|
||||
ResourceTargetVariant::Builder,
|
||||
)
|
||||
.await?
|
||||
.into_iter()
|
||||
.flat_map(|id| ObjectId::from_str(&id))
|
||||
.collect::<Vec<_>>();
|
||||
let query = doc! {
|
||||
let query = match get_resource_ids_for_user(
|
||||
&user,
|
||||
ResourceTargetVariant::Builder,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Some(ids) => doc! {
|
||||
"_id": { "$in": ids }
|
||||
};
|
||||
Some(query)
|
||||
},
|
||||
None => Document::new(),
|
||||
};
|
||||
let total = db_client()
|
||||
.await
|
||||
.builders
|
||||
.count_documents(query, None)
|
||||
.count_documents(query)
|
||||
.await
|
||||
.context("failed to count all builder documents")?;
|
||||
let res = GetBuildersSummaryResponse {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use std::time::Instant;
|
||||
use std::{sync::OnceLock, time::Instant};
|
||||
|
||||
use anyhow::anyhow;
|
||||
use anyhow::{anyhow, Context};
|
||||
use axum::{middleware, routing::post, Extension, Router};
|
||||
use axum_extra::{headers::ContentType, TypedHeader};
|
||||
use monitor_client::{api::read::*, entities::user::User};
|
||||
use resolver_api::{derive::Resolver, Resolve, Resolver};
|
||||
use resolver_api::{derive::Resolver, ResolveToString, Resolver};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serror::Json;
|
||||
use typeshare::typeshare;
|
||||
@@ -37,17 +37,21 @@ mod variable;
|
||||
#[resolver_args(User)]
|
||||
#[serde(tag = "type", content = "params")]
|
||||
enum ReadRequest {
|
||||
#[to_string_resolver]
|
||||
GetVersion(GetVersion),
|
||||
#[to_string_resolver]
|
||||
GetCoreInfo(GetCoreInfo),
|
||||
#[to_string_resolver]
|
||||
GetAvailableAwsEcrLabels(GetAvailableAwsEcrLabels),
|
||||
|
||||
// ==== USER ====
|
||||
ListUsers(ListUsers),
|
||||
GetUsername(GetUsername),
|
||||
GetPermissionLevel(GetPermissionLevel),
|
||||
FindUser(FindUser),
|
||||
ListUsers(ListUsers),
|
||||
ListApiKeys(ListApiKeys),
|
||||
ListApiKeysForServiceUser(ListApiKeysForServiceUser),
|
||||
ListPermissions(ListPermissions),
|
||||
GetPermissionLevel(GetPermissionLevel),
|
||||
ListUserTargetPermissions(ListUserTargetPermissions),
|
||||
|
||||
// ==== USER GROUP ====
|
||||
@@ -66,15 +70,13 @@ enum ReadRequest {
|
||||
|
||||
// ==== SERVER TEMPLATE ====
|
||||
GetServerTemplate(GetServerTemplate),
|
||||
GetServerTemplatesSummary(GetServerTemplatesSummary),
|
||||
ListServerTemplates(ListServerTemplates),
|
||||
ListFullServerTemplates(ListFullServerTemplates),
|
||||
GetServerTemplatesSummary(GetServerTemplatesSummary),
|
||||
|
||||
// ==== SERVER ====
|
||||
GetServersSummary(GetServersSummary),
|
||||
GetServer(GetServer),
|
||||
ListServers(ListServers),
|
||||
ListFullServers(ListFullServers),
|
||||
GetServerState(GetServerState),
|
||||
GetPeripheryVersion(GetPeripheryVersion),
|
||||
GetDockerContainers(GetDockerContainers),
|
||||
@@ -84,27 +86,30 @@ enum ReadRequest {
|
||||
GetHistoricalServerStats(GetHistoricalServerStats),
|
||||
GetAvailableAccounts(GetAvailableAccounts),
|
||||
GetAvailableSecrets(GetAvailableSecrets),
|
||||
ListServers(ListServers),
|
||||
ListFullServers(ListFullServers),
|
||||
|
||||
// ==== DEPLOYMENT ====
|
||||
GetDeploymentsSummary(GetDeploymentsSummary),
|
||||
GetDeployment(GetDeployment),
|
||||
ListDeployments(ListDeployments),
|
||||
ListFullDeployments(ListFullDeployments),
|
||||
GetDeploymentContainer(GetDeploymentContainer),
|
||||
GetDeploymentActionState(GetDeploymentActionState),
|
||||
GetDeploymentStats(GetDeploymentStats),
|
||||
GetLog(GetLog),
|
||||
SearchLog(SearchLog),
|
||||
ListDeployments(ListDeployments),
|
||||
ListFullDeployments(ListFullDeployments),
|
||||
ListCommonDeploymentExtraArgs(ListCommonDeploymentExtraArgs),
|
||||
|
||||
// ==== BUILD ====
|
||||
GetBuildsSummary(GetBuildsSummary),
|
||||
GetBuild(GetBuild),
|
||||
ListBuilds(ListBuilds),
|
||||
ListFullBuilds(ListFullBuilds),
|
||||
GetBuildActionState(GetBuildActionState),
|
||||
GetBuildMonthlyStats(GetBuildMonthlyStats),
|
||||
GetBuildVersions(GetBuildVersions),
|
||||
GetBuildWebhookEnabled(GetBuildWebhookEnabled),
|
||||
ListBuilds(ListBuilds),
|
||||
ListFullBuilds(ListFullBuilds),
|
||||
ListCommonBuildExtraArgs(ListCommonBuildExtraArgs),
|
||||
#[to_string_resolver]
|
||||
ListGithubOrganizations(ListGithubOrganizations),
|
||||
@@ -114,23 +119,25 @@ enum ReadRequest {
|
||||
// ==== REPO ====
|
||||
GetReposSummary(GetReposSummary),
|
||||
GetRepo(GetRepo),
|
||||
GetRepoActionState(GetRepoActionState),
|
||||
GetRepoWebhooksEnabled(GetRepoWebhooksEnabled),
|
||||
ListRepos(ListRepos),
|
||||
ListFullRepos(ListFullRepos),
|
||||
GetRepoActionState(GetRepoActionState),
|
||||
|
||||
// ==== SYNC ====
|
||||
GetResourceSyncsSummary(GetResourceSyncsSummary),
|
||||
GetResourceSync(GetResourceSync),
|
||||
GetResourceSyncActionState(GetResourceSyncActionState),
|
||||
GetSyncWebhooksEnabled(GetSyncWebhooksEnabled),
|
||||
ListResourceSyncs(ListResourceSyncs),
|
||||
ListFullResourceSyncs(ListFullResourceSyncs),
|
||||
GetResourceSyncActionState(GetResourceSyncActionState),
|
||||
|
||||
// ==== BUILDER ====
|
||||
GetBuildersSummary(GetBuildersSummary),
|
||||
GetBuilder(GetBuilder),
|
||||
GetBuilderAvailableAccounts(GetBuilderAvailableAccounts),
|
||||
ListBuilders(ListBuilders),
|
||||
ListFullBuilders(ListFullBuilders),
|
||||
GetBuilderAvailableAccounts(GetBuilderAvailableAccounts),
|
||||
|
||||
// ==== ALERTER ====
|
||||
GetAlertersSummary(GetAlertersSummary),
|
||||
@@ -199,28 +206,32 @@ async fn handler(
|
||||
Ok((TypedHeader(ContentType::json()), res?))
|
||||
}
|
||||
|
||||
impl Resolve<GetVersion, User> for State {
|
||||
#[instrument(name = "GetVersion", level = "debug", skip(self))]
|
||||
async fn resolve(
|
||||
fn version() -> &'static String {
|
||||
static VERSION: OnceLock<String> = OnceLock::new();
|
||||
VERSION.get_or_init(|| {
|
||||
serde_json::to_string(&GetVersionResponse {
|
||||
version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
})
|
||||
.context("failed to serialize GetVersionResponse")
|
||||
.unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
impl ResolveToString<GetVersion, User> for State {
|
||||
async fn resolve_to_string(
|
||||
&self,
|
||||
GetVersion {}: GetVersion,
|
||||
_: User,
|
||||
) -> anyhow::Result<GetVersionResponse> {
|
||||
Ok(GetVersionResponse {
|
||||
version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
})
|
||||
) -> anyhow::Result<String> {
|
||||
Ok(version().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve<GetCoreInfo, User> for State {
|
||||
#[instrument(name = "GetCoreInfo", level = "debug", skip(self))]
|
||||
async fn resolve(
|
||||
&self,
|
||||
GetCoreInfo {}: GetCoreInfo,
|
||||
_: User,
|
||||
) -> anyhow::Result<GetCoreInfoResponse> {
|
||||
fn core_info() -> &'static String {
|
||||
static CORE_INFO: OnceLock<String> = OnceLock::new();
|
||||
CORE_INFO.get_or_init(|| {
|
||||
let config = core_config();
|
||||
Ok(GetCoreInfoResponse {
|
||||
let info = GetCoreInfoResponse {
|
||||
title: config.title.clone(),
|
||||
monitoring_interval: config.monitoring_interval,
|
||||
github_webhook_base_url: config
|
||||
@@ -229,16 +240,50 @@ impl Resolve<GetCoreInfo, User> for State {
|
||||
.unwrap_or_else(|| config.host.clone()),
|
||||
transparent_mode: config.transparent_mode,
|
||||
ui_write_disabled: config.ui_write_disabled,
|
||||
})
|
||||
github_webhook_owners: config
|
||||
.github_webhook_app
|
||||
.installations
|
||||
.iter()
|
||||
.map(|i| i.namespace.to_string())
|
||||
.collect(),
|
||||
};
|
||||
serde_json::to_string(&info)
|
||||
.context("failed to serialize GetCoreInfoResponse")
|
||||
.unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
impl ResolveToString<GetCoreInfo, User> for State {
|
||||
async fn resolve_to_string(
|
||||
&self,
|
||||
GetCoreInfo {}: GetCoreInfo,
|
||||
_: User,
|
||||
) -> anyhow::Result<String> {
|
||||
Ok(core_info().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve<GetAvailableAwsEcrLabels, User> for State {
|
||||
async fn resolve(
|
||||
fn ecr_labels() -> &'static String {
|
||||
static ECR_LABELS: OnceLock<String> = OnceLock::new();
|
||||
ECR_LABELS.get_or_init(|| {
|
||||
serde_json::to_string(
|
||||
&core_config()
|
||||
.aws_ecr_registries
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.context("failed to serialize ecr registries")
|
||||
.unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
impl ResolveToString<GetAvailableAwsEcrLabels, User> for State {
|
||||
async fn resolve_to_string(
|
||||
&self,
|
||||
GetAvailableAwsEcrLabels {}: GetAvailableAwsEcrLabels,
|
||||
_: User,
|
||||
) -> anyhow::Result<GetAvailableAwsEcrLabelsResponse> {
|
||||
Ok(core_config().aws_ecr_registries.keys().cloned().collect())
|
||||
) -> anyhow::Result<String> {
|
||||
Ok(ecr_labels().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ impl Resolve<GetPermissionLevel, User> for State {
|
||||
return Ok(PermissionLevel::Write);
|
||||
}
|
||||
let (variant, id) = target.extract_variant_id();
|
||||
get_user_permission_on_resource(&user.id, variant, id).await
|
||||
get_user_permission_on_resource(&user, variant, id).await
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ use anyhow::Context;
|
||||
use monitor_client::{
|
||||
api::read::*,
|
||||
entities::{
|
||||
config::core::CoreConfig,
|
||||
permission::PermissionLevel,
|
||||
repo::{Repo, RepoActionState, RepoListItem, RepoState},
|
||||
user::User,
|
||||
@@ -10,8 +11,9 @@ use monitor_client::{
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::{
|
||||
config::core_config,
|
||||
resource,
|
||||
state::{action_states, repo_state_cache, State},
|
||||
state::{action_states, github_client, repo_state_cache, State},
|
||||
};
|
||||
|
||||
impl Resolve<GetRepo, User> for State {
|
||||
@@ -118,3 +120,86 @@ impl Resolve<GetReposSummary, User> for State {
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve<GetRepoWebhooksEnabled, User> for State {
|
||||
async fn resolve(
|
||||
&self,
|
||||
GetRepoWebhooksEnabled { repo }: GetRepoWebhooksEnabled,
|
||||
user: User,
|
||||
) -> anyhow::Result<GetRepoWebhooksEnabledResponse> {
|
||||
let Some(github) = github_client() else {
|
||||
return Ok(GetRepoWebhooksEnabledResponse {
|
||||
managed: false,
|
||||
clone_enabled: false,
|
||||
pull_enabled: false,
|
||||
});
|
||||
};
|
||||
|
||||
let repo = resource::get_check_permissions::<Repo>(
|
||||
&repo,
|
||||
&user,
|
||||
PermissionLevel::Read,
|
||||
)
|
||||
.await?;
|
||||
|
||||
if repo.config.repo.is_empty() {
|
||||
return Ok(GetRepoWebhooksEnabledResponse {
|
||||
managed: false,
|
||||
clone_enabled: false,
|
||||
pull_enabled: false,
|
||||
});
|
||||
}
|
||||
|
||||
let mut split = repo.config.repo.split('/');
|
||||
let owner = split.next().context("Repo repo has no owner")?;
|
||||
|
||||
let Some(github) = github.get(owner) else {
|
||||
return Ok(GetRepoWebhooksEnabledResponse {
|
||||
managed: false,
|
||||
clone_enabled: false,
|
||||
pull_enabled: false,
|
||||
});
|
||||
};
|
||||
|
||||
let repo_name =
|
||||
split.next().context("Repo repo has no repo after the /")?;
|
||||
|
||||
let github_repos = github.repos();
|
||||
|
||||
let webhooks = github_repos
|
||||
.list_all_webhooks(owner, repo_name)
|
||||
.await
|
||||
.context("failed to list all webhooks on repo")?
|
||||
.body;
|
||||
|
||||
let CoreConfig {
|
||||
host,
|
||||
github_webhook_base_url,
|
||||
..
|
||||
} = core_config();
|
||||
|
||||
let host = github_webhook_base_url.as_ref().unwrap_or(host);
|
||||
let clone_url =
|
||||
format!("{host}/listener/github/repo/{}/clone", repo.id);
|
||||
let pull_url =
|
||||
format!("{host}/listener/github/repo/{}/pull", repo.id);
|
||||
|
||||
let mut clone_enabled = false;
|
||||
let mut pull_enabled = false;
|
||||
|
||||
for webhook in webhooks {
|
||||
if webhook.active && webhook.config.url == clone_url {
|
||||
clone_enabled = true
|
||||
}
|
||||
if webhook.active && webhook.config.url == pull_url {
|
||||
pull_enabled = true
|
||||
}
|
||||
}
|
||||
|
||||
Ok(GetRepoWebhooksEnabledResponse {
|
||||
managed: true,
|
||||
clone_enabled,
|
||||
pull_enabled,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use std::str::FromStr;
|
||||
|
||||
use anyhow::Context;
|
||||
use mongo_indexed::Document;
|
||||
use monitor_client::{
|
||||
api::read::*,
|
||||
entities::{
|
||||
@@ -8,11 +7,11 @@ use monitor_client::{
|
||||
update::ResourceTargetVariant, user::User,
|
||||
},
|
||||
};
|
||||
use mungos::mongodb::bson::{doc, oid::ObjectId};
|
||||
use mungos::mongodb::bson::doc;
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::{
|
||||
helpers::query::get_resource_ids_for_non_admin,
|
||||
helpers::query::get_resource_ids_for_user,
|
||||
resource,
|
||||
state::{db_client, State},
|
||||
};
|
||||
@@ -58,26 +57,21 @@ impl Resolve<GetServerTemplatesSummary, User> for State {
|
||||
GetServerTemplatesSummary {}: GetServerTemplatesSummary,
|
||||
user: User,
|
||||
) -> anyhow::Result<GetServerTemplatesSummaryResponse> {
|
||||
let query = if user.admin {
|
||||
None
|
||||
} else {
|
||||
let ids = get_resource_ids_for_non_admin(
|
||||
&user.id,
|
||||
ResourceTargetVariant::ServerTemplate,
|
||||
)
|
||||
.await?
|
||||
.into_iter()
|
||||
.flat_map(|id| ObjectId::from_str(&id))
|
||||
.collect::<Vec<_>>();
|
||||
let query = doc! {
|
||||
let query = match get_resource_ids_for_user(
|
||||
&user,
|
||||
ResourceTargetVariant::ServerTemplate,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
Some(ids) => doc! {
|
||||
"_id": { "$in": ids }
|
||||
};
|
||||
Some(query)
|
||||
},
|
||||
None => Document::new(),
|
||||
};
|
||||
let total = db_client()
|
||||
.await
|
||||
.server_templates
|
||||
.count_documents(query, None)
|
||||
.count_documents(query)
|
||||
.await
|
||||
.context("failed to count all server template documents")?;
|
||||
let res = GetServerTemplatesSummaryResponse {
|
||||
|
||||
@@ -2,6 +2,7 @@ use anyhow::Context;
|
||||
use monitor_client::{
|
||||
api::read::*,
|
||||
entities::{
|
||||
config::core::CoreConfig,
|
||||
permission::PermissionLevel,
|
||||
sync::{
|
||||
PendingSyncUpdatesData, ResourceSync, ResourceSyncActionState,
|
||||
@@ -13,8 +14,11 @@ use monitor_client::{
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::{
|
||||
config::core_config,
|
||||
resource,
|
||||
state::{action_states, resource_sync_state_cache, State},
|
||||
state::{
|
||||
action_states, github_client, resource_sync_state_cache, State,
|
||||
},
|
||||
};
|
||||
|
||||
impl Resolve<GetResourceSync, User> for State {
|
||||
@@ -137,3 +141,86 @@ impl Resolve<GetResourceSyncsSummary, User> for State {
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve<GetSyncWebhooksEnabled, User> for State {
|
||||
async fn resolve(
|
||||
&self,
|
||||
GetSyncWebhooksEnabled { sync }: GetSyncWebhooksEnabled,
|
||||
user: User,
|
||||
) -> anyhow::Result<GetSyncWebhooksEnabledResponse> {
|
||||
let Some(github) = github_client() else {
|
||||
return Ok(GetSyncWebhooksEnabledResponse {
|
||||
managed: false,
|
||||
refresh_enabled: false,
|
||||
sync_enabled: false,
|
||||
});
|
||||
};
|
||||
|
||||
let sync = resource::get_check_permissions::<ResourceSync>(
|
||||
&sync,
|
||||
&user,
|
||||
PermissionLevel::Read,
|
||||
)
|
||||
.await?;
|
||||
|
||||
if sync.config.repo.is_empty() {
|
||||
return Ok(GetSyncWebhooksEnabledResponse {
|
||||
managed: false,
|
||||
refresh_enabled: false,
|
||||
sync_enabled: false,
|
||||
});
|
||||
}
|
||||
|
||||
let mut split = sync.config.repo.split('/');
|
||||
let owner = split.next().context("Sync repo has no owner")?;
|
||||
|
||||
let Some(github) = github.get(owner) else {
|
||||
return Ok(GetSyncWebhooksEnabledResponse {
|
||||
managed: false,
|
||||
refresh_enabled: false,
|
||||
sync_enabled: false,
|
||||
});
|
||||
};
|
||||
|
||||
let repo_name =
|
||||
split.next().context("Repo repo has no repo after the /")?;
|
||||
|
||||
let github_repos = github.repos();
|
||||
|
||||
let webhooks = github_repos
|
||||
.list_all_webhooks(owner, repo_name)
|
||||
.await
|
||||
.context("failed to list all webhooks on repo")?
|
||||
.body;
|
||||
|
||||
let CoreConfig {
|
||||
host,
|
||||
github_webhook_base_url,
|
||||
..
|
||||
} = core_config();
|
||||
|
||||
let host = github_webhook_base_url.as_ref().unwrap_or(host);
|
||||
let refresh_url =
|
||||
format!("{host}/listener/github/sync/{}/refresh", sync.id);
|
||||
let sync_url =
|
||||
format!("{host}/listener/github/sync/{}/sync", sync.id);
|
||||
|
||||
let mut refresh_enabled = false;
|
||||
let mut sync_enabled = false;
|
||||
|
||||
for webhook in webhooks {
|
||||
if webhook.active && webhook.config.url == refresh_url {
|
||||
refresh_enabled = true
|
||||
}
|
||||
if webhook.active && webhook.config.url == sync_url {
|
||||
sync_enabled = true
|
||||
}
|
||||
}
|
||||
|
||||
Ok(GetSyncWebhooksEnabledResponse {
|
||||
managed: true,
|
||||
refresh_enabled,
|
||||
sync_enabled,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,7 +230,10 @@ impl Resolve<ExportResourcesToToml, User> for State {
|
||||
// replace server id of builder
|
||||
if let BuilderConfig::Server(config) = &mut builder.config {
|
||||
config.server_id.clone_from(
|
||||
names.servers.get(&id).unwrap_or(&String::new()),
|
||||
names
|
||||
.servers
|
||||
.get(&config.server_id)
|
||||
.unwrap_or(&String::new()),
|
||||
)
|
||||
}
|
||||
res
|
||||
@@ -309,7 +312,7 @@ impl Resolve<ExportResourcesToToml, User> for State {
|
||||
};
|
||||
}
|
||||
|
||||
add_user_groups(user_groups, &mut res, &user)
|
||||
add_user_groups(user_groups, &mut res, &names, &user)
|
||||
.await
|
||||
.context("failed to add user groups")?;
|
||||
|
||||
@@ -421,6 +424,8 @@ struct ResourceNames {
|
||||
deployments: HashMap<String, String>,
|
||||
procedures: HashMap<String, String>,
|
||||
syncs: HashMap<String, String>,
|
||||
alerters: HashMap<String, String>,
|
||||
templates: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl ResourceNames {
|
||||
@@ -475,6 +480,18 @@ impl ResourceNames {
|
||||
.into_iter()
|
||||
.map(|t| (t.id, t.name))
|
||||
.collect::<HashMap<_, _>>(),
|
||||
alerters: find_collect(&db.alerters, None, None)
|
||||
.await
|
||||
.context("failed to get all alerters")?
|
||||
.into_iter()
|
||||
.map(|t| (t.id, t.name))
|
||||
.collect::<HashMap<_, _>>(),
|
||||
templates: find_collect(&db.server_templates, None, None)
|
||||
.await
|
||||
.context("failed to get all server templates")?
|
||||
.into_iter()
|
||||
.map(|t| (t.id, t.name))
|
||||
.collect::<HashMap<_, _>>(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -482,6 +499,7 @@ impl ResourceNames {
|
||||
async fn add_user_groups(
|
||||
user_groups: Vec<String>,
|
||||
res: &mut ResourcesToml,
|
||||
names: &ResourceNames,
|
||||
user: &User,
|
||||
) -> anyhow::Result<()> {
|
||||
let db = db_client().await;
|
||||
@@ -509,9 +527,43 @@ async fn add_user_groups(
|
||||
)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|permission| PermissionToml {
|
||||
target: permission.resource_target,
|
||||
level: permission.level,
|
||||
.map(|mut permission| {
|
||||
match &mut permission.resource_target {
|
||||
ResourceTarget::Build(id) => {
|
||||
*id = names.builds.get(id).cloned().unwrap_or_default()
|
||||
}
|
||||
ResourceTarget::Builder(id) => {
|
||||
*id = names.builders.get(id).cloned().unwrap_or_default()
|
||||
}
|
||||
ResourceTarget::Deployment(id) => {
|
||||
*id =
|
||||
names.deployments.get(id).cloned().unwrap_or_default()
|
||||
}
|
||||
ResourceTarget::Server(id) => {
|
||||
*id = names.servers.get(id).cloned().unwrap_or_default()
|
||||
}
|
||||
ResourceTarget::Repo(id) => {
|
||||
*id = names.repos.get(id).cloned().unwrap_or_default()
|
||||
}
|
||||
ResourceTarget::Alerter(id) => {
|
||||
*id = names.alerters.get(id).cloned().unwrap_or_default()
|
||||
}
|
||||
ResourceTarget::Procedure(id) => {
|
||||
*id =
|
||||
names.procedures.get(id).cloned().unwrap_or_default()
|
||||
}
|
||||
ResourceTarget::ServerTemplate(id) => {
|
||||
*id = names.templates.get(id).cloned().unwrap_or_default()
|
||||
}
|
||||
ResourceTarget::ResourceSync(id) => {
|
||||
*id = names.syncs.get(id).cloned().unwrap_or_default()
|
||||
}
|
||||
ResourceTarget::System(_) => {}
|
||||
}
|
||||
PermissionToml {
|
||||
target: permission.resource_target,
|
||||
level: permission.level,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
res.user_groups.push(UserGroupToml {
|
||||
@@ -521,6 +573,7 @@ async fn add_user_groups(
|
||||
.into_iter()
|
||||
.filter_map(|user_id| usernames.get(&user_id).cloned())
|
||||
.collect(),
|
||||
all: ug.all,
|
||||
permissions,
|
||||
});
|
||||
}
|
||||
|
||||
+101
-35
@@ -29,7 +29,7 @@ use resolver_api::Resolve;
|
||||
|
||||
use crate::{
|
||||
config::core_config,
|
||||
helpers::query::get_resource_ids_for_non_admin,
|
||||
helpers::query::get_resource_ids_for_user,
|
||||
resource,
|
||||
state::{db_client, State},
|
||||
};
|
||||
@@ -45,58 +45,124 @@ impl Resolve<ListUpdates, User> for State {
|
||||
let query = if user.admin || core_config().transparent_mode {
|
||||
query
|
||||
} else {
|
||||
let server_ids = get_resource_ids_for_non_admin(
|
||||
&user.id,
|
||||
let server_query = get_resource_ids_for_user(
|
||||
&user,
|
||||
ResourceTargetVariant::Server,
|
||||
)
|
||||
.await?;
|
||||
let deployment_ids = get_resource_ids_for_non_admin(
|
||||
&user.id,
|
||||
.await?
|
||||
.map(|ids| {
|
||||
doc! {
|
||||
"target.type": "Server", "target.id": { "$in": ids }
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| doc! { "target.type": "Server" });
|
||||
|
||||
let deployment_query = get_resource_ids_for_user(
|
||||
&user,
|
||||
ResourceTargetVariant::Deployment,
|
||||
)
|
||||
.await?;
|
||||
let build_ids = get_resource_ids_for_non_admin(
|
||||
&user.id,
|
||||
.await?
|
||||
.map(|ids| {
|
||||
doc! {
|
||||
"target.type": "Deployment", "target.id": { "$in": ids }
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| doc! { "target.type": "Deployment" });
|
||||
|
||||
let build_query = get_resource_ids_for_user(
|
||||
&user,
|
||||
ResourceTargetVariant::Build,
|
||||
)
|
||||
.await?;
|
||||
let repo_ids = get_resource_ids_for_non_admin(
|
||||
&user.id,
|
||||
ResourceTargetVariant::Repo,
|
||||
)
|
||||
.await?;
|
||||
let procedure_ids = get_resource_ids_for_non_admin(
|
||||
&user.id,
|
||||
.await?
|
||||
.map(|ids| {
|
||||
doc! {
|
||||
"target.type": "Build", "target.id": { "$in": ids }
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| doc! { "target.type": "Build" });
|
||||
|
||||
let repo_query =
|
||||
get_resource_ids_for_user(&user, ResourceTargetVariant::Repo)
|
||||
.await?
|
||||
.map(|ids| {
|
||||
doc! {
|
||||
"target.type": "Repo", "target.id": { "$in": ids }
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| doc! { "target.type": "Repo" });
|
||||
|
||||
let procedure_query = get_resource_ids_for_user(
|
||||
&user,
|
||||
ResourceTargetVariant::Procedure,
|
||||
)
|
||||
.await?;
|
||||
let builder_ids = get_resource_ids_for_non_admin(
|
||||
&user.id,
|
||||
.await?
|
||||
.map(|ids| {
|
||||
doc! {
|
||||
"target.type": "Procedure", "target.id": { "$in": ids }
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| doc! { "target.type": "Procedure" });
|
||||
|
||||
let builder_query = get_resource_ids_for_user(
|
||||
&user,
|
||||
ResourceTargetVariant::Builder,
|
||||
)
|
||||
.await?;
|
||||
let alerter_ids = get_resource_ids_for_non_admin(
|
||||
&user.id,
|
||||
.await?
|
||||
.map(|ids| {
|
||||
doc! {
|
||||
"target.type": "Builder", "target.id": { "$in": ids }
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| doc! { "target.type": "Builder" });
|
||||
|
||||
let alerter_query = get_resource_ids_for_user(
|
||||
&user,
|
||||
ResourceTargetVariant::Alerter,
|
||||
)
|
||||
.await?;
|
||||
let server_template_ids = get_resource_ids_for_non_admin(
|
||||
&user.id,
|
||||
.await?
|
||||
.map(|ids| {
|
||||
doc! {
|
||||
"target.type": "Alerter", "target.id": { "$in": ids }
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| doc! { "target.type": "Alerter" });
|
||||
|
||||
let server_template_query = get_resource_ids_for_user(
|
||||
&user,
|
||||
ResourceTargetVariant::ServerTemplate,
|
||||
)
|
||||
.await?;
|
||||
.await?
|
||||
.map(|ids| {
|
||||
doc! {
|
||||
"target.type": "ServerTemplate", "target.id": { "$in": ids }
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| doc! { "target.type": "ServerTemplate" });
|
||||
|
||||
let resource_sync_query = get_resource_ids_for_user(
|
||||
&user,
|
||||
ResourceTargetVariant::ResourceSync,
|
||||
)
|
||||
.await?
|
||||
.map(|ids| {
|
||||
doc! {
|
||||
"target.type": "ResourceSync", "target.id": { "$in": ids }
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| doc! { "target.type": "ResourceSync" });
|
||||
|
||||
let mut query = query.unwrap_or_default();
|
||||
query.extend(doc! {
|
||||
"$or": [
|
||||
{ "target.type": "Server", "target.id": { "$in": &server_ids } },
|
||||
{ "target.type": "Deployment", "target.id": { "$in": &deployment_ids } },
|
||||
{ "target.type": "Build", "target.id": { "$in": &build_ids } },
|
||||
{ "target.type": "Repo", "target.id": { "$in": &repo_ids } },
|
||||
{ "target.type": "Procedure", "target.id": { "$in": &procedure_ids } },
|
||||
{ "target.type": "Builder", "target.id": { "$in": &builder_ids } },
|
||||
{ "target.type": "Alerter", "target.id": { "$in": &alerter_ids } },
|
||||
{ "target.type": "ServerTemplate", "target.id": { "$in": &server_template_ids } },
|
||||
server_query,
|
||||
build_query,
|
||||
deployment_query,
|
||||
repo_query,
|
||||
procedure_query,
|
||||
alerter_query,
|
||||
builder_query,
|
||||
server_template_query,
|
||||
resource_sync_query,
|
||||
]
|
||||
});
|
||||
query.into()
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
use anyhow::{anyhow, Context};
|
||||
use monitor_client::{
|
||||
api::read::{
|
||||
GetUsername, GetUsernameResponse, ListApiKeys,
|
||||
ListApiKeysForServiceUser, ListApiKeysForServiceUserResponse,
|
||||
ListApiKeysResponse, ListUsers, ListUsersResponse,
|
||||
FindUser, FindUserResponse, GetUsername, GetUsernameResponse,
|
||||
ListApiKeys, ListApiKeysForServiceUser,
|
||||
ListApiKeysForServiceUserResponse, ListApiKeysResponse,
|
||||
ListUsers, ListUsersResponse,
|
||||
},
|
||||
entities::user::{User, UserConfig},
|
||||
};
|
||||
@@ -14,7 +15,10 @@ use mungos::{
|
||||
};
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::state::{db_client, State};
|
||||
use crate::{
|
||||
helpers::query::get_user,
|
||||
state::{db_client, State},
|
||||
};
|
||||
|
||||
impl Resolve<GetUsername, User> for State {
|
||||
async fn resolve(
|
||||
@@ -40,6 +44,19 @@ impl Resolve<GetUsername, User> for State {
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve<FindUser, User> for State {
|
||||
async fn resolve(
|
||||
&self,
|
||||
FindUser { user }: FindUser,
|
||||
admin: User,
|
||||
) -> anyhow::Result<FindUserResponse> {
|
||||
if !admin.admin {
|
||||
return Err(anyhow!("This method is admin only."));
|
||||
}
|
||||
get_user(&user).await
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve<ListUsers, User> for State {
|
||||
async fn resolve(
|
||||
&self,
|
||||
@@ -87,22 +104,21 @@ impl Resolve<ListApiKeys, User> for State {
|
||||
impl Resolve<ListApiKeysForServiceUser, User> for State {
|
||||
async fn resolve(
|
||||
&self,
|
||||
ListApiKeysForServiceUser { user_id }: ListApiKeysForServiceUser,
|
||||
ListApiKeysForServiceUser { user }: ListApiKeysForServiceUser,
|
||||
admin: User,
|
||||
) -> anyhow::Result<ListApiKeysForServiceUserResponse> {
|
||||
if !admin.admin {
|
||||
return Err(anyhow!("This method is admin only."));
|
||||
}
|
||||
let user = find_one_by_id(&db_client().await.users, &user_id)
|
||||
.await
|
||||
.context("failed to query db for users")?
|
||||
.context("user at id not found")?;
|
||||
|
||||
let user = get_user(&user).await?;
|
||||
|
||||
let UserConfig::Service { .. } = user.config else {
|
||||
return Err(anyhow!("Given user is not service user"));
|
||||
};
|
||||
let api_keys = find_collect(
|
||||
&db_client().await.api_keys,
|
||||
doc! { "user_id": user_id },
|
||||
doc! { "user_id": &user.id },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -37,7 +37,7 @@ impl Resolve<GetUserGroup, User> for State {
|
||||
db_client()
|
||||
.await
|
||||
.user_groups
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query db for user groups")?
|
||||
.context("no UserGroup found with given name or id")
|
||||
|
||||
+19
-32
@@ -11,10 +11,7 @@ use monitor_client::{
|
||||
PushRecentlyViewedResponse, SetLastSeenUpdate,
|
||||
SetLastSeenUpdateResponse,
|
||||
},
|
||||
entities::{
|
||||
api_key::ApiKey, monitor_timestamp, update::ResourceTarget,
|
||||
user::User,
|
||||
},
|
||||
entities::{api_key::ApiKey, monitor_timestamp, user::User},
|
||||
};
|
||||
use mungos::{by_id::update_one_by_id, mongodb::bson::to_bson};
|
||||
use resolver_api::{derive::Resolver, Resolve, Resolver};
|
||||
@@ -90,33 +87,21 @@ impl Resolve<PushRecentlyViewed, User> for State {
|
||||
) -> anyhow::Result<PushRecentlyViewedResponse> {
|
||||
let user = get_user(&user.id).await?;
|
||||
|
||||
let (recents, id, field) = match resource {
|
||||
ResourceTarget::Server(id) => {
|
||||
(user.recent_servers, id, "recent_servers")
|
||||
let (resource_type, id) = resource.extract_variant_id();
|
||||
let update = match user.recents.get(&resource_type) {
|
||||
Some(recents) => {
|
||||
let mut recents = recents
|
||||
.iter()
|
||||
.filter(|_id| !id.eq(*_id))
|
||||
.take(RECENTLY_VIEWED_MAX - 1)
|
||||
.collect::<VecDeque<_>>();
|
||||
recents.push_front(id);
|
||||
doc! { format!("recents.{resource_type}"): to_bson(&recents)? }
|
||||
}
|
||||
ResourceTarget::Deployment(id) => {
|
||||
(user.recent_deployments, id, "recent_deployments")
|
||||
None => {
|
||||
doc! { format!("recents.{resource_type}"): [id] }
|
||||
}
|
||||
ResourceTarget::Build(id) => {
|
||||
(user.recent_builds, id, "recent_builds")
|
||||
}
|
||||
ResourceTarget::Repo(id) => {
|
||||
(user.recent_repos, id, "recent_repos")
|
||||
}
|
||||
ResourceTarget::Procedure(id) => {
|
||||
(user.recent_procedures, id, "recent_procedures")
|
||||
}
|
||||
_ => return Ok(PushRecentlyViewedResponse {}),
|
||||
};
|
||||
|
||||
let mut recents = recents
|
||||
.into_iter()
|
||||
.filter(|_id| !id.eq(_id))
|
||||
.take(RECENTLY_VIEWED_MAX - 1)
|
||||
.collect::<VecDeque<_>>();
|
||||
recents.push_front(id);
|
||||
let update = doc! { field: to_bson(&recents)? };
|
||||
|
||||
update_one_by_id(
|
||||
&db_client().await.users,
|
||||
&user.id,
|
||||
@@ -124,7 +109,9 @@ impl Resolve<PushRecentlyViewed, User> for State {
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.with_context(|| format!("failed to update {field}"))?;
|
||||
.with_context(|| {
|
||||
format!("failed to update recents.{resource_type}")
|
||||
})?;
|
||||
|
||||
Ok(PushRecentlyViewedResponse {})
|
||||
}
|
||||
@@ -187,7 +174,7 @@ impl Resolve<CreateApiKey, User> for State {
|
||||
db_client()
|
||||
.await
|
||||
.api_keys
|
||||
.insert_one(api_key, None)
|
||||
.insert_one(api_key)
|
||||
.await
|
||||
.context("failed to create api key on db")?;
|
||||
Ok(CreateApiKeyResponse { key, secret })
|
||||
@@ -208,7 +195,7 @@ impl Resolve<DeleteApiKey, User> for State {
|
||||
let client = db_client().await;
|
||||
let key = client
|
||||
.api_keys
|
||||
.find_one(doc! { "key": &key }, None)
|
||||
.find_one(doc! { "key": &key })
|
||||
.await
|
||||
.context("failed at db query")?
|
||||
.context("no api key with key found")?;
|
||||
@@ -217,7 +204,7 @@ impl Resolve<DeleteApiKey, User> for State {
|
||||
}
|
||||
client
|
||||
.api_keys
|
||||
.delete_one(doc! { "key": key.key }, None)
|
||||
.delete_one(doc! { "key": key.key })
|
||||
.await
|
||||
.context("failed to delete api key from db")?;
|
||||
Ok(DeleteApiKeyResponse {})
|
||||
|
||||
@@ -1,10 +1,24 @@
|
||||
use anyhow::{anyhow, Context};
|
||||
use monitor_client::{
|
||||
api::write::*,
|
||||
entities::{build::Build, permission::PermissionLevel, user::User},
|
||||
entities::{
|
||||
build::{Build, PartialBuildConfig},
|
||||
config::core::CoreConfig,
|
||||
permission::PermissionLevel,
|
||||
user::User,
|
||||
NoData,
|
||||
},
|
||||
};
|
||||
use octorust::types::{
|
||||
ReposCreateWebhookRequest, ReposCreateWebhookRequestConfig,
|
||||
};
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::{resource, state::State};
|
||||
use crate::{
|
||||
config::core_config,
|
||||
resource,
|
||||
state::{github_client, State},
|
||||
};
|
||||
|
||||
impl Resolve<CreateBuild, User> for State {
|
||||
#[instrument(name = "CreateBuild", skip(self, user))]
|
||||
@@ -56,3 +70,175 @@ impl Resolve<UpdateBuild, User> for State {
|
||||
resource::update::<Build>(&id, config, &user).await
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve<CreateBuildWebhook, User> for State {
|
||||
#[instrument(name = "CreateBuildWebhook", skip(self, user))]
|
||||
async fn resolve(
|
||||
&self,
|
||||
CreateBuildWebhook { build }: CreateBuildWebhook,
|
||||
user: User,
|
||||
) -> anyhow::Result<CreateBuildWebhookResponse> {
|
||||
let Some(github) = github_client() else {
|
||||
return Err(anyhow!(
|
||||
"github_webhook_app is not configured in core config toml"
|
||||
));
|
||||
};
|
||||
|
||||
let build = resource::get_check_permissions::<Build>(
|
||||
&build,
|
||||
&user,
|
||||
PermissionLevel::Write,
|
||||
)
|
||||
.await?;
|
||||
|
||||
if build.config.repo.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"No repo configured, can't create webhook"
|
||||
));
|
||||
}
|
||||
|
||||
let mut split = build.config.repo.split('/');
|
||||
let owner = split.next().context("Build repo has no owner")?;
|
||||
|
||||
let Some(github) = github.get(owner) else {
|
||||
return Err(anyhow!(
|
||||
"Cannot manage repo webhooks under owner {owner}"
|
||||
));
|
||||
};
|
||||
|
||||
let repo =
|
||||
split.next().context("Build repo has no repo after the /")?;
|
||||
|
||||
let github_repos = github.repos();
|
||||
|
||||
// First make sure the webhook isn't already created (inactive ones are ignored)
|
||||
let webhooks = github_repos
|
||||
.list_all_webhooks(owner, repo)
|
||||
.await
|
||||
.context("failed to list all webhooks on repo")?
|
||||
.body;
|
||||
|
||||
let CoreConfig {
|
||||
host,
|
||||
github_webhook_base_url,
|
||||
github_webhook_secret,
|
||||
..
|
||||
} = core_config();
|
||||
|
||||
let host = github_webhook_base_url.as_ref().unwrap_or(host);
|
||||
let url = format!("{host}/listener/github/build/{}", build.id);
|
||||
|
||||
for webhook in webhooks {
|
||||
if webhook.active && webhook.config.url == url {
|
||||
return Ok(NoData {});
|
||||
}
|
||||
}
|
||||
|
||||
// Now good to create the webhook
|
||||
let request = ReposCreateWebhookRequest {
|
||||
active: Some(true),
|
||||
config: Some(ReposCreateWebhookRequestConfig {
|
||||
url,
|
||||
secret: github_webhook_secret.to_string(),
|
||||
content_type: String::from("json"),
|
||||
insecure_ssl: None,
|
||||
digest: Default::default(),
|
||||
token: Default::default(),
|
||||
}),
|
||||
events: vec![String::from("push")],
|
||||
name: String::from("web"),
|
||||
};
|
||||
github_repos
|
||||
.create_webhook(owner, repo, &request)
|
||||
.await
|
||||
.context("failed to create webhook")?;
|
||||
|
||||
if !build.config.webhook_enabled {
|
||||
self
|
||||
.resolve(
|
||||
UpdateBuild {
|
||||
id: build.id,
|
||||
config: PartialBuildConfig {
|
||||
webhook_enabled: Some(true),
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
user,
|
||||
)
|
||||
.await
|
||||
.context("failed to update build to enable webhook")?;
|
||||
}
|
||||
|
||||
Ok(NoData {})
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve<DeleteBuildWebhook, User> for State {
|
||||
#[instrument(name = "DeleteBuildWebhook", skip(self, user))]
|
||||
async fn resolve(
|
||||
&self,
|
||||
DeleteBuildWebhook { build }: DeleteBuildWebhook,
|
||||
user: User,
|
||||
) -> anyhow::Result<DeleteBuildWebhookResponse> {
|
||||
let Some(github) = github_client() else {
|
||||
return Err(anyhow!(
|
||||
"github_webhook_app is not configured in core config toml"
|
||||
));
|
||||
};
|
||||
|
||||
let build = resource::get_check_permissions::<Build>(
|
||||
&build,
|
||||
&user,
|
||||
PermissionLevel::Write,
|
||||
)
|
||||
.await?;
|
||||
|
||||
if build.config.repo.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"No repo configured, can't delete webhook"
|
||||
));
|
||||
}
|
||||
|
||||
let mut split = build.config.repo.split('/');
|
||||
let owner = split.next().context("Build repo has no owner")?;
|
||||
|
||||
let Some(github) = github.get(owner) else {
|
||||
return Err(anyhow!(
|
||||
"Cannot manage repo webhooks under owner {owner}"
|
||||
));
|
||||
};
|
||||
|
||||
let repo =
|
||||
split.next().context("Build repo has no repo after the /")?;
|
||||
|
||||
let github_repos = github.repos();
|
||||
|
||||
let webhooks = github_repos
|
||||
.list_all_webhooks(owner, repo)
|
||||
.await
|
||||
.context("failed to list all webhooks on repo")?
|
||||
.body;
|
||||
|
||||
let CoreConfig {
|
||||
host,
|
||||
github_webhook_base_url,
|
||||
..
|
||||
} = core_config();
|
||||
|
||||
let host = github_webhook_base_url.as_ref().unwrap_or(host);
|
||||
let url = format!("{host}/listener/github/build/{}", build.id);
|
||||
|
||||
for webhook in webhooks {
|
||||
if webhook.active && webhook.config.url == url {
|
||||
github_repos
|
||||
.delete_webhook(owner, repo, webhook.id)
|
||||
.await
|
||||
.context("failed to delete webhook")?;
|
||||
return Ok(NoData {});
|
||||
}
|
||||
}
|
||||
|
||||
// No webhook to delete, all good
|
||||
Ok(NoData {})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ pub enum WriteRequest {
|
||||
|
||||
// ==== PERMISSIONS ====
|
||||
UpdateUserBasePermissions(UpdateUserBasePermissions),
|
||||
UpdatePermissionOnResourceType(UpdatePermissionOnResourceType),
|
||||
UpdatePermissionOnTarget(UpdatePermissionOnTarget),
|
||||
|
||||
// ==== DESCRIPTION ====
|
||||
@@ -75,6 +76,8 @@ pub enum WriteRequest {
|
||||
CopyBuild(CopyBuild),
|
||||
DeleteBuild(DeleteBuild),
|
||||
UpdateBuild(UpdateBuild),
|
||||
CreateBuildWebhook(CreateBuildWebhook),
|
||||
DeleteBuildWebhook(DeleteBuildWebhook),
|
||||
|
||||
// ==== BUILDER ====
|
||||
CreateBuilder(CreateBuilder),
|
||||
@@ -93,6 +96,8 @@ pub enum WriteRequest {
|
||||
CopyRepo(CopyRepo),
|
||||
DeleteRepo(DeleteRepo),
|
||||
UpdateRepo(UpdateRepo),
|
||||
CreateRepoWebhook(CreateRepoWebhook),
|
||||
DeleteRepoWebhook(DeleteRepoWebhook),
|
||||
|
||||
// ==== ALERTER ====
|
||||
CreateAlerter(CreateAlerter),
|
||||
@@ -112,6 +117,8 @@ pub enum WriteRequest {
|
||||
DeleteResourceSync(DeleteResourceSync),
|
||||
UpdateResourceSync(UpdateResourceSync),
|
||||
RefreshResourceSyncPending(RefreshResourceSyncPending),
|
||||
CreateSyncWebhook(CreateSyncWebhook),
|
||||
DeleteSyncWebhook(DeleteSyncWebhook),
|
||||
|
||||
// ==== TAG ====
|
||||
CreateTag(CreateTag),
|
||||
|
||||
@@ -3,8 +3,10 @@ use std::str::FromStr;
|
||||
use anyhow::{anyhow, Context};
|
||||
use monitor_client::{
|
||||
api::write::{
|
||||
UpdatePermissionOnTarget, UpdatePermissionOnTargetResponse,
|
||||
UpdateUserBasePermissions, UpdateUserBasePermissionsResponse,
|
||||
UpdatePermissionOnResourceType,
|
||||
UpdatePermissionOnResourceTypeResponse, UpdatePermissionOnTarget,
|
||||
UpdatePermissionOnTargetResponse, UpdateUserBasePermissions,
|
||||
UpdateUserBasePermissionsResponse,
|
||||
},
|
||||
entities::{
|
||||
permission::{UserTarget, UserTargetVariant},
|
||||
@@ -41,6 +43,7 @@ impl Resolve<UpdateUserBasePermissions, User> for State {
|
||||
if !admin.admin {
|
||||
return Err(anyhow!("this method is admin only"));
|
||||
}
|
||||
|
||||
let user = find_one_by_id(&db_client().await.users, &user_id)
|
||||
.await
|
||||
.context("failed to query mongo for user")?
|
||||
@@ -73,6 +76,73 @@ impl Resolve<UpdateUserBasePermissions, User> for State {
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve<UpdatePermissionOnResourceType, User> for State {
|
||||
#[instrument(
|
||||
name = "UpdatePermissionOnResourceType",
|
||||
skip(self, admin)
|
||||
)]
|
||||
async fn resolve(
|
||||
&self,
|
||||
UpdatePermissionOnResourceType {
|
||||
user_target,
|
||||
resource_type,
|
||||
permission,
|
||||
}: UpdatePermissionOnResourceType,
|
||||
admin: User,
|
||||
) -> anyhow::Result<UpdatePermissionOnResourceTypeResponse> {
|
||||
if !admin.admin {
|
||||
return Err(anyhow!("this method is admin only"));
|
||||
}
|
||||
|
||||
// Some extra checks if user target is an actual User
|
||||
if let UserTarget::User(user_id) = &user_target {
|
||||
let user = get_user(user_id).await?;
|
||||
if user.admin {
|
||||
return Err(anyhow!(
|
||||
"cannot use this method to update other admins permissions"
|
||||
));
|
||||
}
|
||||
if !user.enabled {
|
||||
return Err(anyhow!("user not enabled"));
|
||||
}
|
||||
}
|
||||
|
||||
let (user_target_variant, user_target_id) =
|
||||
extract_user_target_with_validation(&user_target).await?;
|
||||
|
||||
let id = ObjectId::from_str(&user_target_id)
|
||||
.context("id is not ObjectId")?;
|
||||
let field = format!("all.{resource_type}");
|
||||
let filter = doc! { "_id": id };
|
||||
let update = doc! { "$set": { &field: permission.as_ref() } };
|
||||
|
||||
match user_target_variant {
|
||||
UserTargetVariant::User => {
|
||||
db_client()
|
||||
.await
|
||||
.users
|
||||
.update_one(filter, update)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!("failed to set {field}: {permission} on db")
|
||||
})?;
|
||||
}
|
||||
UserTargetVariant::UserGroup => {
|
||||
db_client()
|
||||
.await
|
||||
.user_groups
|
||||
.update_one(filter, update)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!("failed to set {field}: {permission} on db")
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(UpdatePermissionOnResourceTypeResponse {})
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve<UpdatePermissionOnTarget, User> for State {
|
||||
#[instrument(name = "UpdatePermissionOnTarget", skip(self, admin))]
|
||||
async fn resolve(
|
||||
@@ -129,8 +199,8 @@ impl Resolve<UpdatePermissionOnTarget, User> for State {
|
||||
"level": permission.as_ref(),
|
||||
}
|
||||
},
|
||||
UpdateOptions::builder().upsert(true).build(),
|
||||
)
|
||||
.with_options(UpdateOptions::builder().upsert(true).build())
|
||||
.await?;
|
||||
|
||||
Ok(UpdatePermissionOnTargetResponse {})
|
||||
@@ -150,7 +220,7 @@ async fn extract_user_target_with_validation(
|
||||
let id = db_client()
|
||||
.await
|
||||
.users
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query db for users")?
|
||||
.context("no matching user found")?
|
||||
@@ -165,7 +235,7 @@ async fn extract_user_target_with_validation(
|
||||
let id = db_client()
|
||||
.await
|
||||
.user_groups
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query db for user_groups")?
|
||||
.context("no matching user_group found")?
|
||||
@@ -192,7 +262,7 @@ async fn extract_resource_target_with_validation(
|
||||
let id = db_client()
|
||||
.await
|
||||
.builds
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query db for builds")?
|
||||
.context("no matching build found")?
|
||||
@@ -207,7 +277,7 @@ async fn extract_resource_target_with_validation(
|
||||
let id = db_client()
|
||||
.await
|
||||
.builders
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query db for builders")?
|
||||
.context("no matching builder found")?
|
||||
@@ -222,7 +292,7 @@ async fn extract_resource_target_with_validation(
|
||||
let id = db_client()
|
||||
.await
|
||||
.deployments
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query db for deployments")?
|
||||
.context("no matching deployment found")?
|
||||
@@ -237,7 +307,7 @@ async fn extract_resource_target_with_validation(
|
||||
let id = db_client()
|
||||
.await
|
||||
.servers
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query db for servers")?
|
||||
.context("no matching server found")?
|
||||
@@ -252,7 +322,7 @@ async fn extract_resource_target_with_validation(
|
||||
let id = db_client()
|
||||
.await
|
||||
.repos
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query db for repos")?
|
||||
.context("no matching repo found")?
|
||||
@@ -267,7 +337,7 @@ async fn extract_resource_target_with_validation(
|
||||
let id = db_client()
|
||||
.await
|
||||
.alerters
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query db for alerters")?
|
||||
.context("no matching alerter found")?
|
||||
@@ -282,7 +352,7 @@ async fn extract_resource_target_with_validation(
|
||||
let id = db_client()
|
||||
.await
|
||||
.procedures
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query db for procedures")?
|
||||
.context("no matching procedure found")?
|
||||
@@ -297,7 +367,7 @@ async fn extract_resource_target_with_validation(
|
||||
let id = db_client()
|
||||
.await
|
||||
.server_templates
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query db for server templates")?
|
||||
.context("no matching server template found")?
|
||||
@@ -312,7 +382,7 @@ async fn extract_resource_target_with_validation(
|
||||
let id = db_client()
|
||||
.await
|
||||
.resource_syncs
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query db for resource syncs")?
|
||||
.context("no matching resource sync found")?
|
||||
|
||||
@@ -1,10 +1,24 @@
|
||||
use anyhow::{anyhow, Context};
|
||||
use monitor_client::{
|
||||
api::write::*,
|
||||
entities::{permission::PermissionLevel, repo::Repo, user::User},
|
||||
entities::{
|
||||
config::core::CoreConfig,
|
||||
permission::PermissionLevel,
|
||||
repo::{PartialRepoConfig, Repo},
|
||||
user::User,
|
||||
NoData,
|
||||
},
|
||||
};
|
||||
use octorust::types::{
|
||||
ReposCreateWebhookRequest, ReposCreateWebhookRequestConfig,
|
||||
};
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::{resource, state::State};
|
||||
use crate::{
|
||||
config::core_config,
|
||||
resource,
|
||||
state::{github_client, State},
|
||||
};
|
||||
|
||||
impl Resolve<CreateRepo, User> for State {
|
||||
#[instrument(name = "CreateRepo", skip(self, user))]
|
||||
@@ -56,3 +70,190 @@ impl Resolve<UpdateRepo, User> for State {
|
||||
resource::update::<Repo>(&id, config, &user).await
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve<CreateRepoWebhook, User> for State {
|
||||
#[instrument(name = "CreateRepoWebhook", skip(self, user))]
|
||||
async fn resolve(
|
||||
&self,
|
||||
CreateRepoWebhook { repo, action }: CreateRepoWebhook,
|
||||
user: User,
|
||||
) -> anyhow::Result<CreateRepoWebhookResponse> {
|
||||
let Some(github) = github_client() else {
|
||||
return Err(anyhow!(
|
||||
"github_webhook_app is not configured in core config toml"
|
||||
));
|
||||
};
|
||||
|
||||
let repo = resource::get_check_permissions::<Repo>(
|
||||
&repo,
|
||||
&user,
|
||||
PermissionLevel::Write,
|
||||
)
|
||||
.await?;
|
||||
|
||||
if repo.config.repo.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"No repo configured, can't create webhook"
|
||||
));
|
||||
}
|
||||
|
||||
let mut split = repo.config.repo.split('/');
|
||||
let owner = split.next().context("Repo repo has no owner")?;
|
||||
|
||||
let Some(github) = github.get(owner) else {
|
||||
return Err(anyhow!(
|
||||
"Cannot manage repo webhooks under owner {owner}"
|
||||
));
|
||||
};
|
||||
|
||||
let repo_name =
|
||||
split.next().context("Repo repo has no repo after the /")?;
|
||||
|
||||
let github_repos = github.repos();
|
||||
|
||||
// First make sure the webhook isn't already created (inactive ones are ignored)
|
||||
let webhooks = github_repos
|
||||
.list_all_webhooks(owner, repo_name)
|
||||
.await
|
||||
.context("failed to list all webhooks on repo")?
|
||||
.body;
|
||||
|
||||
let CoreConfig {
|
||||
host,
|
||||
github_webhook_base_url,
|
||||
github_webhook_secret,
|
||||
..
|
||||
} = core_config();
|
||||
|
||||
let host = github_webhook_base_url.as_ref().unwrap_or(host);
|
||||
let url = match action {
|
||||
RepoWebhookAction::Clone => {
|
||||
format!("{host}/listener/github/repo/{}/clone", repo.id)
|
||||
}
|
||||
RepoWebhookAction::Pull => {
|
||||
format!("{host}/listener/github/repo/{}/pull", repo.id)
|
||||
}
|
||||
};
|
||||
|
||||
for webhook in webhooks {
|
||||
if webhook.active && webhook.config.url == url {
|
||||
return Ok(NoData {});
|
||||
}
|
||||
}
|
||||
|
||||
// Now good to create the webhook
|
||||
let request = ReposCreateWebhookRequest {
|
||||
active: Some(true),
|
||||
config: Some(ReposCreateWebhookRequestConfig {
|
||||
url,
|
||||
secret: github_webhook_secret.to_string(),
|
||||
content_type: String::from("json"),
|
||||
insecure_ssl: None,
|
||||
digest: Default::default(),
|
||||
token: Default::default(),
|
||||
}),
|
||||
events: vec![String::from("push")],
|
||||
name: String::from("web"),
|
||||
};
|
||||
github_repos
|
||||
.create_webhook(owner, repo_name, &request)
|
||||
.await
|
||||
.context("failed to create webhook")?;
|
||||
|
||||
if !repo.config.webhook_enabled {
|
||||
self
|
||||
.resolve(
|
||||
UpdateRepo {
|
||||
id: repo.id,
|
||||
config: PartialRepoConfig {
|
||||
webhook_enabled: Some(true),
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
user,
|
||||
)
|
||||
.await
|
||||
.context("failed to update repo to enable webhook")?;
|
||||
}
|
||||
|
||||
Ok(NoData {})
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve<DeleteRepoWebhook, User> for State {
|
||||
#[instrument(name = "DeleteRepoWebhook", skip(self, user))]
|
||||
async fn resolve(
|
||||
&self,
|
||||
DeleteRepoWebhook { repo, action }: DeleteRepoWebhook,
|
||||
user: User,
|
||||
) -> anyhow::Result<DeleteRepoWebhookResponse> {
|
||||
let Some(github) = github_client() else {
|
||||
return Err(anyhow!(
|
||||
"github_webhook_app is not configured in core config toml"
|
||||
));
|
||||
};
|
||||
|
||||
let repo = resource::get_check_permissions::<Repo>(
|
||||
&repo,
|
||||
&user,
|
||||
PermissionLevel::Write,
|
||||
)
|
||||
.await?;
|
||||
|
||||
if repo.config.repo.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"No repo configured, can't create webhook"
|
||||
));
|
||||
}
|
||||
|
||||
let mut split = repo.config.repo.split('/');
|
||||
let owner = split.next().context("Repo repo has no owner")?;
|
||||
|
||||
let Some(github) = github.get(owner) else {
|
||||
return Err(anyhow!(
|
||||
"Cannot manage repo webhooks under owner {owner}"
|
||||
));
|
||||
};
|
||||
|
||||
let repo_name =
|
||||
split.next().context("Repo repo has no repo after the /")?;
|
||||
|
||||
let github_repos = github.repos();
|
||||
|
||||
// First make sure the webhook isn't already created (inactive ones are ignored)
|
||||
let webhooks = github_repos
|
||||
.list_all_webhooks(owner, repo_name)
|
||||
.await
|
||||
.context("failed to list all webhooks on repo")?
|
||||
.body;
|
||||
|
||||
let CoreConfig {
|
||||
host,
|
||||
github_webhook_base_url,
|
||||
..
|
||||
} = core_config();
|
||||
|
||||
let host = github_webhook_base_url.as_ref().unwrap_or(host);
|
||||
let url = match action {
|
||||
RepoWebhookAction::Clone => {
|
||||
format!("{host}/listener/github/repo/{}/clone", repo.id)
|
||||
}
|
||||
RepoWebhookAction::Pull => {
|
||||
format!("{host}/listener/github/repo/{}/pull", repo.id)
|
||||
}
|
||||
};
|
||||
|
||||
for webhook in webhooks {
|
||||
if webhook.active && webhook.config.url == url {
|
||||
github_repos
|
||||
.delete_webhook(owner, repo_name, webhook.id)
|
||||
.await
|
||||
.context("failed to delete webhook")?;
|
||||
return Ok(NoData {});
|
||||
}
|
||||
}
|
||||
|
||||
// No webhook to delete, all good
|
||||
Ok(NoData {})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,17 +51,14 @@ impl Resolve<CreateServiceUser, User> for State {
|
||||
create_server_permissions: false,
|
||||
create_build_permissions: false,
|
||||
last_update_view: 0,
|
||||
recent_servers: Vec::new(),
|
||||
recent_deployments: Vec::new(),
|
||||
recent_builds: Vec::new(),
|
||||
recent_repos: Vec::new(),
|
||||
recent_procedures: Vec::new(),
|
||||
recents: Default::default(),
|
||||
all: Default::default(),
|
||||
updated_at: monitor_timestamp(),
|
||||
};
|
||||
user.id = db_client()
|
||||
.await
|
||||
.users
|
||||
.insert_one(&user, None)
|
||||
.insert_one(&user)
|
||||
.await
|
||||
.context("failed to create service user on db")?
|
||||
.inserted_id
|
||||
@@ -91,7 +88,7 @@ impl Resolve<UpdateServiceUserDescription, User> for State {
|
||||
let db = db_client().await;
|
||||
let service_user = db
|
||||
.users
|
||||
.find_one(doc! { "username": &username }, None)
|
||||
.find_one(doc! { "username": &username })
|
||||
.await
|
||||
.context("failed to query db for user")?
|
||||
.context("no user with given username")?;
|
||||
@@ -102,12 +99,11 @@ impl Resolve<UpdateServiceUserDescription, User> for State {
|
||||
.update_one(
|
||||
doc! { "username": &username },
|
||||
doc! { "$set": { "config.data.description": description } },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to update user on db")?;
|
||||
db.users
|
||||
.find_one(doc! { "username": &username }, None)
|
||||
.find_one(doc! { "username": &username })
|
||||
.await
|
||||
.context("failed to query db for user")?
|
||||
.context("user with username not found")
|
||||
@@ -155,7 +151,7 @@ impl Resolve<DeleteApiKeyForServiceUser, User> for State {
|
||||
let db = db_client().await;
|
||||
let api_key = db
|
||||
.api_keys
|
||||
.find_one(doc! { "key": &key }, None)
|
||||
.find_one(doc! { "key": &key })
|
||||
.await
|
||||
.context("failed to query db for api key")?
|
||||
.context("did not find matching api key")?;
|
||||
@@ -168,7 +164,7 @@ impl Resolve<DeleteApiKeyForServiceUser, User> for State {
|
||||
return Err(anyhow!("user is not service user"));
|
||||
};
|
||||
db.api_keys
|
||||
.delete_one(doc! { "key": key }, None)
|
||||
.delete_one(doc! { "key": key })
|
||||
.await
|
||||
.context("failed to delete api key on db")?;
|
||||
Ok(DeleteApiKeyForServiceUserResponse {})
|
||||
|
||||
+203
-13
@@ -8,6 +8,7 @@ use monitor_client::{
|
||||
alerter::Alerter,
|
||||
build::Build,
|
||||
builder::Builder,
|
||||
config::core::CoreConfig,
|
||||
monitor_timestamp,
|
||||
permission::PermissionLevel,
|
||||
procedure::Procedure,
|
||||
@@ -15,21 +16,26 @@ use monitor_client::{
|
||||
server::{stats::SeverityLevel, Server},
|
||||
server_template::ServerTemplate,
|
||||
sync::{
|
||||
PendingSyncUpdates, PendingSyncUpdatesData,
|
||||
PendingSyncUpdatesDataErr, PendingSyncUpdatesDataOk,
|
||||
ResourceSync,
|
||||
PartialResourceSyncConfig, PendingSyncUpdates,
|
||||
PendingSyncUpdatesData, PendingSyncUpdatesDataErr,
|
||||
PendingSyncUpdatesDataOk, ResourceSync,
|
||||
},
|
||||
update::ResourceTarget,
|
||||
user::User,
|
||||
NoData,
|
||||
},
|
||||
};
|
||||
use mungos::{
|
||||
by_id::update_one_by_id,
|
||||
mongodb::bson::{doc, to_document},
|
||||
};
|
||||
use octorust::types::{
|
||||
ReposCreateWebhookRequest, ReposCreateWebhookRequestConfig,
|
||||
};
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::{
|
||||
config::core_config,
|
||||
helpers::{
|
||||
alert::send_alerts,
|
||||
query::get_id_to_tags,
|
||||
@@ -39,7 +45,7 @@ use crate::{
|
||||
},
|
||||
},
|
||||
resource,
|
||||
state::{db_client, State},
|
||||
state::{db_client, github_client, State},
|
||||
};
|
||||
|
||||
impl Resolve<CreateResourceSync, User> for State {
|
||||
@@ -262,14 +268,11 @@ impl Resolve<RefreshResourceSyncPending, User> for State {
|
||||
let Some(existing) = db_client()
|
||||
.await
|
||||
.alerts
|
||||
.find_one(
|
||||
doc! {
|
||||
"resolved": false,
|
||||
"target.type": "ResourceSync",
|
||||
"target.id": &id,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.find_one(doc! {
|
||||
"resolved": false,
|
||||
"target.type": "ResourceSync",
|
||||
"target.id": &id,
|
||||
})
|
||||
.await
|
||||
.context("failed to query db for alert")
|
||||
.inspect_err(|e| warn!("{e:#}"))
|
||||
@@ -290,7 +293,7 @@ impl Resolve<RefreshResourceSyncPending, User> for State {
|
||||
resolved_ts: None,
|
||||
};
|
||||
db.alerts
|
||||
.insert_one(&alert, None)
|
||||
.insert_one(&alert)
|
||||
.await
|
||||
.context("failed to open existing pending resource sync updates alert")
|
||||
.inspect_err(|e| warn!("{e:#}"))
|
||||
@@ -323,3 +326,190 @@ impl Resolve<RefreshResourceSyncPending, User> for State {
|
||||
crate::resource::get::<ResourceSync>(&sync.id).await
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve<CreateSyncWebhook, User> for State {
|
||||
#[instrument(name = "CreateSyncWebhook", skip(self, user))]
|
||||
async fn resolve(
|
||||
&self,
|
||||
CreateSyncWebhook { sync, action }: CreateSyncWebhook,
|
||||
user: User,
|
||||
) -> anyhow::Result<CreateSyncWebhookResponse> {
|
||||
let Some(github) = github_client() else {
|
||||
return Err(anyhow!(
|
||||
"github_webhook_app is not configured in core config toml"
|
||||
));
|
||||
};
|
||||
|
||||
let sync = resource::get_check_permissions::<ResourceSync>(
|
||||
&sync,
|
||||
&user,
|
||||
PermissionLevel::Write,
|
||||
)
|
||||
.await?;
|
||||
|
||||
if sync.config.repo.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"No repo configured, can't create webhook"
|
||||
));
|
||||
}
|
||||
|
||||
let mut split = sync.config.repo.split('/');
|
||||
let owner = split.next().context("Sync repo has no owner")?;
|
||||
|
||||
let Some(github) = github.get(owner) else {
|
||||
return Err(anyhow!(
|
||||
"Cannot manage repo webhooks under owner {owner}"
|
||||
));
|
||||
};
|
||||
|
||||
let repo =
|
||||
split.next().context("Repo repo has no repo after the /")?;
|
||||
|
||||
let github_repos = github.repos();
|
||||
|
||||
// First make sure the webhook isn't already created (inactive ones are ignored)
|
||||
let webhooks = github_repos
|
||||
.list_all_webhooks(owner, repo)
|
||||
.await
|
||||
.context("failed to list all webhooks on repo")?
|
||||
.body;
|
||||
|
||||
let CoreConfig {
|
||||
host,
|
||||
github_webhook_base_url,
|
||||
github_webhook_secret,
|
||||
..
|
||||
} = core_config();
|
||||
|
||||
let host = github_webhook_base_url.as_ref().unwrap_or(host);
|
||||
let url = match action {
|
||||
SyncWebhookAction::Refresh => {
|
||||
format!("{host}/listener/github/sync/{}/refresh", sync.id)
|
||||
}
|
||||
SyncWebhookAction::Sync => {
|
||||
format!("{host}/listener/github/sync/{}/sync", sync.id)
|
||||
}
|
||||
};
|
||||
|
||||
for webhook in webhooks {
|
||||
if webhook.active && webhook.config.url == url {
|
||||
return Ok(NoData {});
|
||||
}
|
||||
}
|
||||
|
||||
// Now good to create the webhook
|
||||
let request = ReposCreateWebhookRequest {
|
||||
active: Some(true),
|
||||
config: Some(ReposCreateWebhookRequestConfig {
|
||||
url,
|
||||
secret: github_webhook_secret.to_string(),
|
||||
content_type: String::from("json"),
|
||||
insecure_ssl: None,
|
||||
digest: Default::default(),
|
||||
token: Default::default(),
|
||||
}),
|
||||
events: vec![String::from("push")],
|
||||
name: String::from("web"),
|
||||
};
|
||||
github_repos
|
||||
.create_webhook(owner, repo, &request)
|
||||
.await
|
||||
.context("failed to create webhook")?;
|
||||
|
||||
if !sync.config.webhook_enabled {
|
||||
self
|
||||
.resolve(
|
||||
UpdateResourceSync {
|
||||
id: sync.id,
|
||||
config: PartialResourceSyncConfig {
|
||||
webhook_enabled: Some(true),
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
user,
|
||||
)
|
||||
.await
|
||||
.context("failed to update sync to enable webhook")?;
|
||||
}
|
||||
|
||||
Ok(NoData {})
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve<DeleteSyncWebhook, User> for State {
|
||||
#[instrument(name = "DeleteSyncWebhook", skip(self, user))]
|
||||
async fn resolve(
|
||||
&self,
|
||||
DeleteSyncWebhook { sync, action }: DeleteSyncWebhook,
|
||||
user: User,
|
||||
) -> anyhow::Result<DeleteSyncWebhookResponse> {
|
||||
let Some(github) = github_client() else {
|
||||
return Err(anyhow!(
|
||||
"github_webhook_app is not configured in core config toml"
|
||||
));
|
||||
};
|
||||
|
||||
let sync = resource::get_check_permissions::<ResourceSync>(
|
||||
&sync,
|
||||
&user,
|
||||
PermissionLevel::Write,
|
||||
)
|
||||
.await?;
|
||||
|
||||
if sync.config.repo.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"No repo configured, can't create webhook"
|
||||
));
|
||||
}
|
||||
|
||||
let mut split = sync.config.repo.split('/');
|
||||
let owner = split.next().context("Sync repo has no owner")?;
|
||||
|
||||
let Some(github) = github.get(owner) else {
|
||||
return Err(anyhow!(
|
||||
"Cannot manage repo webhooks under owner {owner}"
|
||||
));
|
||||
};
|
||||
|
||||
let repo =
|
||||
split.next().context("Sync repo has no repo after the /")?;
|
||||
|
||||
let github_repos = github.repos();
|
||||
|
||||
// First make sure the webhook isn't already created (inactive ones are ignored)
|
||||
let webhooks = github_repos
|
||||
.list_all_webhooks(owner, repo)
|
||||
.await
|
||||
.context("failed to list all webhooks on repo")?
|
||||
.body;
|
||||
|
||||
let CoreConfig {
|
||||
host,
|
||||
github_webhook_base_url,
|
||||
..
|
||||
} = core_config();
|
||||
|
||||
let host = github_webhook_base_url.as_ref().unwrap_or(host);
|
||||
let url = match action {
|
||||
SyncWebhookAction::Refresh => {
|
||||
format!("{host}/listener/github/sync/{}/refresh", sync.id)
|
||||
}
|
||||
SyncWebhookAction::Sync => {
|
||||
format!("{host}/listener/github/sync/{}/sync", sync.id)
|
||||
}
|
||||
};
|
||||
|
||||
for webhook in webhooks {
|
||||
if webhook.active && webhook.config.url == url {
|
||||
github_repos
|
||||
.delete_webhook(owner, repo, webhook.id)
|
||||
.await
|
||||
.context("failed to delete webhook")?;
|
||||
return Ok(NoData {});
|
||||
}
|
||||
}
|
||||
|
||||
// No webhook to delete, all good
|
||||
Ok(NoData {})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ impl Resolve<CreateTag, User> for State {
|
||||
tag.id = db_client()
|
||||
.await
|
||||
.tags
|
||||
.insert_one(&tag, None)
|
||||
.insert_one(&tag)
|
||||
.await
|
||||
.context("failed to create tag on db")?
|
||||
.inserted_id
|
||||
|
||||
@@ -29,13 +29,14 @@ impl Resolve<CreateUserGroup, User> for State {
|
||||
let user_group = UserGroup {
|
||||
id: Default::default(),
|
||||
users: Default::default(),
|
||||
all: Default::default(),
|
||||
updated_at: monitor_timestamp(),
|
||||
name,
|
||||
};
|
||||
let db = db_client().await;
|
||||
let id = db
|
||||
.user_groups
|
||||
.insert_one(user_group, None)
|
||||
.insert_one(user_group)
|
||||
.await
|
||||
.context("failed to create UserGroup on db")?
|
||||
.inserted_id
|
||||
@@ -99,7 +100,7 @@ impl Resolve<DeleteUserGroup, User> for State {
|
||||
.delete_many(doc! {
|
||||
"user_target.type": "UserGroup",
|
||||
"user_target.id": id,
|
||||
}, None)
|
||||
})
|
||||
.await
|
||||
.context("failed to clean up UserGroups permissions. User Group has been deleted")?;
|
||||
|
||||
@@ -125,7 +126,7 @@ impl Resolve<AddUserToUserGroup, User> for State {
|
||||
};
|
||||
let user = db
|
||||
.users
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query mongo for users")?
|
||||
.context("no matching user found")?;
|
||||
@@ -138,12 +139,11 @@ impl Resolve<AddUserToUserGroup, User> for State {
|
||||
.update_one(
|
||||
filter.clone(),
|
||||
doc! { "$addToSet": { "users": &user.id } },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to add user to group on db")?;
|
||||
db.user_groups
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query db for UserGroups")?
|
||||
.context("no user group with given id")
|
||||
@@ -171,7 +171,7 @@ impl Resolve<RemoveUserFromUserGroup, User> for State {
|
||||
};
|
||||
let user = db
|
||||
.users
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query mongo for users")?
|
||||
.context("no matching user found")?;
|
||||
@@ -184,12 +184,11 @@ impl Resolve<RemoveUserFromUserGroup, User> for State {
|
||||
.update_one(
|
||||
filter.clone(),
|
||||
doc! { "$pull": { "users": &user.id } },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to add user to group on db")?;
|
||||
db.user_groups
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query db for UserGroups")?
|
||||
.context("no user group with given id")
|
||||
@@ -229,15 +228,11 @@ impl Resolve<SetUsersInUserGroup, User> for State {
|
||||
Err(_) => doc! { "name": &user_group },
|
||||
};
|
||||
db.user_groups
|
||||
.update_one(
|
||||
filter.clone(),
|
||||
doc! { "$set": { "users": users } },
|
||||
None,
|
||||
)
|
||||
.update_one(filter.clone(), doc! { "$set": { "users": users } })
|
||||
.await
|
||||
.context("failed to add user to group on db")?;
|
||||
.context("failed to set users on user group")?;
|
||||
db.user_groups
|
||||
.find_one(filter, None)
|
||||
.find_one(filter)
|
||||
.await
|
||||
.context("failed to query db for UserGroups")?
|
||||
.context("no user group with given id")
|
||||
|
||||
@@ -44,7 +44,7 @@ impl Resolve<CreateVariable, User> for State {
|
||||
db_client()
|
||||
.await
|
||||
.variables
|
||||
.insert_one(&variable, None)
|
||||
.insert_one(&variable)
|
||||
.await
|
||||
.context("failed to create variable on db")?;
|
||||
|
||||
@@ -86,7 +86,6 @@ impl Resolve<UpdateVariableValue, User> for State {
|
||||
.update_one(
|
||||
doc! { "name": &name },
|
||||
doc! { "$set": { "value": &value } },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to update variable value on db")?;
|
||||
@@ -127,7 +126,6 @@ impl Resolve<UpdateVariableDescription, User> for State {
|
||||
.update_one(
|
||||
doc! { "name": &name },
|
||||
doc! { "$set": { "description": &description } },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to update variable description on db")?;
|
||||
@@ -148,7 +146,7 @@ impl Resolve<DeleteVariable, User> for State {
|
||||
db_client()
|
||||
.await
|
||||
.variables
|
||||
.delete_one(doc! { "name": &name }, None)
|
||||
.delete_one(doc! { "name": &name })
|
||||
.await
|
||||
.context("failed to delete variable on db")?;
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ use anyhow::{anyhow, Context};
|
||||
use axum::{
|
||||
extract::Query, response::Redirect, routing::get, Router,
|
||||
};
|
||||
use mongo_indexed::Document;
|
||||
use monitor_client::entities::{
|
||||
monitor_timestamp,
|
||||
user::{User, UserConfig},
|
||||
@@ -66,7 +67,7 @@ async fn callback(
|
||||
let db_client = db_client().await;
|
||||
let user = db_client
|
||||
.users
|
||||
.find_one(doc! { "config.data.github_id": &github_id }, None)
|
||||
.find_one(doc! { "config.data.github_id": &github_id })
|
||||
.await
|
||||
.context("failed at find user query from mongo")?;
|
||||
let jwt = match user {
|
||||
@@ -76,7 +77,7 @@ async fn callback(
|
||||
None => {
|
||||
let ts = monitor_timestamp();
|
||||
let no_users_exist =
|
||||
db_client.users.find_one(None, None).await?.is_none();
|
||||
db_client.users.find_one(Document::new()).await?.is_none();
|
||||
let user = User {
|
||||
id: Default::default(),
|
||||
username: github_user.login,
|
||||
@@ -86,11 +87,8 @@ async fn callback(
|
||||
create_build_permissions: no_users_exist,
|
||||
updated_at: ts,
|
||||
last_update_view: 0,
|
||||
recent_servers: Vec::new(),
|
||||
recent_deployments: Vec::new(),
|
||||
recent_builds: Vec::new(),
|
||||
recent_repos: Vec::new(),
|
||||
recent_procedures: Vec::new(),
|
||||
recents: Default::default(),
|
||||
all: Default::default(),
|
||||
config: UserConfig::Github {
|
||||
github_id,
|
||||
avatar: github_user.avatar_url,
|
||||
@@ -98,7 +96,7 @@ async fn callback(
|
||||
};
|
||||
let user_id = db_client
|
||||
.users
|
||||
.insert_one(user, None)
|
||||
.insert_one(user)
|
||||
.await
|
||||
.context("failed to create user on mongo")?
|
||||
.inserted_id
|
||||
|
||||
@@ -3,6 +3,7 @@ use async_timing_util::unix_timestamp_ms;
|
||||
use axum::{
|
||||
extract::Query, response::Redirect, routing::get, Router,
|
||||
};
|
||||
use mongo_indexed::Document;
|
||||
use monitor_client::entities::user::{User, UserConfig};
|
||||
use mungos::mongodb::bson::doc;
|
||||
use reqwest::StatusCode;
|
||||
@@ -75,7 +76,7 @@ async fn callback(
|
||||
let db_client = db_client().await;
|
||||
let user = db_client
|
||||
.users
|
||||
.find_one(doc! { "config.data.google_id": &google_id }, None)
|
||||
.find_one(doc! { "config.data.google_id": &google_id })
|
||||
.await
|
||||
.context("failed at find user query from mongo")?;
|
||||
let jwt = match user {
|
||||
@@ -85,7 +86,7 @@ async fn callback(
|
||||
None => {
|
||||
let ts = unix_timestamp_ms() as i64;
|
||||
let no_users_exist =
|
||||
db_client.users.find_one(None, None).await?.is_none();
|
||||
db_client.users.find_one(Document::new()).await?.is_none();
|
||||
let user = User {
|
||||
id: Default::default(),
|
||||
username: google_user
|
||||
@@ -101,11 +102,8 @@ async fn callback(
|
||||
create_build_permissions: no_users_exist,
|
||||
updated_at: ts,
|
||||
last_update_view: 0,
|
||||
recent_servers: Vec::new(),
|
||||
recent_deployments: Vec::new(),
|
||||
recent_builds: Vec::new(),
|
||||
recent_repos: Vec::new(),
|
||||
recent_procedures: Vec::new(),
|
||||
recents: Default::default(),
|
||||
all: Default::default(),
|
||||
config: UserConfig::Google {
|
||||
google_id,
|
||||
avatar: google_user.picture,
|
||||
@@ -113,7 +111,7 @@ async fn callback(
|
||||
};
|
||||
let user_id = db_client
|
||||
.users
|
||||
.insert_one(user, None)
|
||||
.insert_one(user)
|
||||
.await
|
||||
.context("failed to create user on mongo")?
|
||||
.inserted_id
|
||||
|
||||
@@ -3,6 +3,7 @@ use std::str::FromStr;
|
||||
use anyhow::{anyhow, Context};
|
||||
use async_timing_util::unix_timestamp_ms;
|
||||
use axum::http::HeaderMap;
|
||||
use mongo_indexed::Document;
|
||||
use monitor_client::{
|
||||
api::auth::{
|
||||
CreateLocalUser, CreateLocalUserResponse, LoginLocalUser,
|
||||
@@ -46,7 +47,7 @@ impl Resolve<CreateLocalUser, HeaderMap> for State {
|
||||
let no_users_exist = db_client()
|
||||
.await
|
||||
.users
|
||||
.find_one(None, None)
|
||||
.find_one(Document::new())
|
||||
.await?
|
||||
.is_none();
|
||||
|
||||
@@ -61,18 +62,15 @@ impl Resolve<CreateLocalUser, HeaderMap> for State {
|
||||
create_build_permissions: no_users_exist,
|
||||
updated_at: ts,
|
||||
last_update_view: 0,
|
||||
recent_servers: Vec::new(),
|
||||
recent_deployments: Vec::new(),
|
||||
recent_builds: Vec::new(),
|
||||
recent_repos: Vec::new(),
|
||||
recent_procedures: Vec::new(),
|
||||
recents: Default::default(),
|
||||
all: Default::default(),
|
||||
config: UserConfig::Local { password },
|
||||
};
|
||||
|
||||
let user_id = db_client()
|
||||
.await
|
||||
.users
|
||||
.insert_one(user, None)
|
||||
.insert_one(user)
|
||||
.await
|
||||
.context("failed to create user")?
|
||||
.inserted_id
|
||||
@@ -102,7 +100,7 @@ impl Resolve<LoginLocalUser, HeaderMap> for State {
|
||||
let user = db_client()
|
||||
.await
|
||||
.users
|
||||
.find_one(doc! { "username": &username }, None)
|
||||
.find_one(doc! { "username": &username })
|
||||
.await
|
||||
.context("failed at db query for users")?
|
||||
.with_context(|| {
|
||||
|
||||
@@ -127,7 +127,7 @@ pub async fn auth_api_key_get_user_id(
|
||||
let key = db_client()
|
||||
.await
|
||||
.api_keys
|
||||
.find_one(doc! { "key": key }, None)
|
||||
.find_one(doc! { "key": key })
|
||||
.await
|
||||
.context("failed to query db")?
|
||||
.context("no api key matching key")?;
|
||||
|
||||
+33
-2
@@ -4,8 +4,9 @@ use anyhow::Context;
|
||||
use merge_config_files::parse_config_file;
|
||||
use monitor_client::entities::{
|
||||
config::core::{
|
||||
AwsCredentials, CoreConfig, Env, HetznerCredentials, MongoConfig,
|
||||
OauthCredentials,
|
||||
AwsCredentials, CoreConfig, Env, GithubWebhookAppConfig,
|
||||
GithubWebhookAppInstallationConfig, HetznerCredentials,
|
||||
MongoConfig, OauthCredentials,
|
||||
},
|
||||
logger::LogConfig,
|
||||
};
|
||||
@@ -45,6 +46,27 @@ pub fn core_config() -> &'static CoreConfig {
|
||||
.unwrap_or_else(|e| {
|
||||
panic!("failed at parsing config at {config_path} | {e:#}")
|
||||
});
|
||||
let installations = match (env.monitor_github_webhook_app_installations_ids, env.monitor_github_webhook_app_installations_namespaces) {
|
||||
(Some(ids), Some(namespaces)) => {
|
||||
if ids.len() != namespaces.len() {
|
||||
panic!("MONITOR_GITHUB_WEBHOOK_APP_INSTALLATIONS_IDS length and MONITOR_GITHUB_WEBHOOK_APP_INSTALLATIONS_NAMESPACES length mismatch. Got {ids:?} and {namespaces:?}")
|
||||
}
|
||||
ids
|
||||
.into_iter()
|
||||
.zip(namespaces)
|
||||
.map(|(id, namespace)| GithubWebhookAppInstallationConfig {
|
||||
id,
|
||||
namespace
|
||||
})
|
||||
.collect()
|
||||
},
|
||||
(Some(_), None) | (None, Some(_)) => {
|
||||
panic!("Got only one of MONITOR_GITHUB_WEBHOOK_APP_INSTALLATIONS_IDS or MONITOR_GITHUB_WEBHOOK_APP_INSTALLATIONS_NAMESPACES, both MUST be provided");
|
||||
}
|
||||
(None, None) => {
|
||||
config.github_webhook_app.installations
|
||||
}
|
||||
};
|
||||
// recreating CoreConfig here makes sure we apply all env overrides.
|
||||
CoreConfig {
|
||||
title: env.monitor_title.unwrap_or(config.title),
|
||||
@@ -109,6 +131,15 @@ pub fn core_config() -> &'static CoreConfig {
|
||||
.monitor_github_oauth_secret
|
||||
.unwrap_or(config.github_oauth.secret),
|
||||
},
|
||||
github_webhook_app: GithubWebhookAppConfig {
|
||||
app_id: env
|
||||
.monitor_github_webhook_app_app_id
|
||||
.unwrap_or(config.github_webhook_app.app_id),
|
||||
pk_path: env
|
||||
.monitor_github_webhook_app_pk_path
|
||||
.unwrap_or(config.github_webhook_app.pk_path),
|
||||
installations,
|
||||
},
|
||||
aws: AwsCredentials {
|
||||
access_key_id: env
|
||||
.monitor_aws_access_key_id
|
||||
|
||||
+1
-1
@@ -112,7 +112,7 @@ impl DbClient {
|
||||
}
|
||||
}
|
||||
|
||||
async fn resource_collection<T>(
|
||||
async fn resource_collection<T: Send + Sync>(
|
||||
db: &Database,
|
||||
collection_name: &str,
|
||||
) -> anyhow::Result<Collection<T>> {
|
||||
|
||||
@@ -19,20 +19,18 @@ pub async fn send_alerts(alerts: &[Alert]) {
|
||||
return;
|
||||
}
|
||||
|
||||
let alerters = match find_collect(
|
||||
let Ok(alerters) = find_collect(
|
||||
&db_client().await.alerters,
|
||||
doc! { "config.enabled": true },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(alerters) => alerters,
|
||||
Err(e) => {
|
||||
error!(
|
||||
"ERROR sending alerts | failed to get alerters from db | {e:#}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
.inspect_err(|e| {
|
||||
error!(
|
||||
"ERROR sending alerts | failed to get alerters from db | {e:#}"
|
||||
)
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let handles =
|
||||
@@ -337,7 +335,7 @@ async fn send_slack_alert(
|
||||
}
|
||||
AlertData::ResourceSyncPendingUpdates { id, name } => {
|
||||
let text =
|
||||
format!("{level} | There are pending resource sync updates");
|
||||
format!("{level} | Pending resource sync updates on {name}");
|
||||
let blocks = vec![
|
||||
Block::header(text.clone()),
|
||||
Block::section(format!(
|
||||
@@ -350,29 +348,12 @@ async fn send_slack_alert(
|
||||
];
|
||||
(text, blocks.into())
|
||||
}
|
||||
AlertData::BuildFailed {
|
||||
id,
|
||||
name,
|
||||
version,
|
||||
err,
|
||||
} => {
|
||||
AlertData::BuildFailed { id, name, version } => {
|
||||
let text = format!("{level} | Build {name} has failed");
|
||||
let err = err
|
||||
.as_ref()
|
||||
.map(|log| {
|
||||
let stdout = (!log.stdout.is_empty())
|
||||
.then(|| format!("\nstdout: {}", log.stdout))
|
||||
.unwrap_or_default();
|
||||
let stderr = (!log.stderr.is_empty())
|
||||
.then(|| format!("\nstderr: {}", log.stderr))
|
||||
.unwrap_or_default();
|
||||
format!("\nfailed at stage: {}{stdout}{stderr}", log.stage)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let blocks = vec![
|
||||
Block::header(text.clone()),
|
||||
Block::section(format!(
|
||||
"build id: *{id}*\nbuild name: *{name}*\nversion: v{version}{err}",
|
||||
"build id: *{id}*\nbuild name: *{name}*\nversion: v{version}",
|
||||
)),
|
||||
Block::section(resource_link(ResourceTargetVariant::Build, id))
|
||||
];
|
||||
|
||||
@@ -62,7 +62,6 @@ where
|
||||
}
|
||||
}
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to remove resource from users recently viewed")
|
||||
@@ -104,15 +103,12 @@ pub async fn create_permission<T>(
|
||||
if let Err(e) = db_client()
|
||||
.await
|
||||
.permissions
|
||||
.insert_one(
|
||||
Permission {
|
||||
id: Default::default(),
|
||||
user_target: UserTarget::User(user.id.clone()),
|
||||
resource_target: target.clone(),
|
||||
level,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.insert_one(Permission {
|
||||
id: Default::default(),
|
||||
user_target: UserTarget::User(user.id.clone()),
|
||||
resource_target: target.clone(),
|
||||
level,
|
||||
})
|
||||
.await
|
||||
{
|
||||
error!("failed to create permission for {target:?} | {e:#}");
|
||||
|
||||
@@ -68,12 +68,9 @@ async fn prune_stats() -> anyhow::Result<()> {
|
||||
let res = db_client()
|
||||
.await
|
||||
.stats
|
||||
.delete_many(
|
||||
doc! {
|
||||
"ts": { "$lt": delete_before_ts }
|
||||
},
|
||||
None,
|
||||
)
|
||||
.delete_many(doc! {
|
||||
"ts": { "$lt": delete_before_ts }
|
||||
})
|
||||
.await?;
|
||||
info!("deleted {} stats from db", res.deleted_count);
|
||||
Ok(())
|
||||
@@ -89,12 +86,9 @@ async fn prune_alerts() -> anyhow::Result<()> {
|
||||
let res = db_client()
|
||||
.await
|
||||
.alerts
|
||||
.delete_many(
|
||||
doc! {
|
||||
"ts": { "$lt": delete_before_ts }
|
||||
},
|
||||
None,
|
||||
)
|
||||
.delete_many(doc! {
|
||||
"ts": { "$lt": delete_before_ts }
|
||||
})
|
||||
.await?;
|
||||
info!("deleted {} alerts from db", res.deleted_count);
|
||||
Ok(())
|
||||
|
||||
+117
-44
@@ -11,11 +11,11 @@ use monitor_client::entities::{
|
||||
tag::Tag,
|
||||
update::{ResourceTargetVariant, Update},
|
||||
user::{admin_service_user, User},
|
||||
user_group::UserGroup,
|
||||
variable::Variable,
|
||||
Operation,
|
||||
};
|
||||
use mungos::{
|
||||
by_id::find_one_by_id,
|
||||
find::find_collect,
|
||||
mongodb::{
|
||||
bson::{doc, oid::ObjectId, Document},
|
||||
@@ -26,14 +26,18 @@ use mungos::{
|
||||
use crate::{config::core_config, resource, state::db_client};
|
||||
|
||||
#[instrument(level = "debug")]
|
||||
pub async fn get_user(user_id: &str) -> anyhow::Result<User> {
|
||||
if let Some(user) = admin_service_user(user_id) {
|
||||
// user: Id or username
|
||||
pub async fn get_user(user: &str) -> anyhow::Result<User> {
|
||||
if let Some(user) = admin_service_user(user) {
|
||||
return Ok(user);
|
||||
}
|
||||
find_one_by_id(&db_client().await.users, user_id)
|
||||
db_client()
|
||||
.await
|
||||
.users
|
||||
.find_one(id_or_username_filter(user))
|
||||
.await
|
||||
.context("failed to query mongo for user")?
|
||||
.with_context(|| format!("no user found with id {user_id}"))
|
||||
.with_context(|| format!("no user found with {user}"))
|
||||
}
|
||||
|
||||
#[instrument(level = "debug")]
|
||||
@@ -89,7 +93,7 @@ pub async fn get_tag(id_or_name: &str) -> anyhow::Result<Tag> {
|
||||
db_client()
|
||||
.await
|
||||
.tags
|
||||
.find_one(query, None)
|
||||
.find_one(query)
|
||||
.await
|
||||
.context("failed to query mongo for tag")?
|
||||
.with_context(|| format!("no tag found matching {id_or_name}"))
|
||||
@@ -120,10 +124,10 @@ pub async fn get_id_to_tags(
|
||||
}
|
||||
|
||||
#[instrument(level = "debug")]
|
||||
pub async fn get_user_user_group_ids(
|
||||
pub async fn get_user_user_groups(
|
||||
user_id: &str,
|
||||
) -> anyhow::Result<Vec<String>> {
|
||||
let res = find_collect(
|
||||
) -> anyhow::Result<Vec<UserGroup>> {
|
||||
find_collect(
|
||||
&db_client().await.user_groups,
|
||||
doc! {
|
||||
"users": user_id
|
||||
@@ -131,50 +135,84 @@ pub async fn get_user_user_group_ids(
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to query db for user groups")?
|
||||
.into_iter()
|
||||
.map(|ug| ug.id)
|
||||
.collect();
|
||||
.context("failed to query db for user groups")
|
||||
}
|
||||
|
||||
#[instrument(level = "debug")]
|
||||
pub async fn get_user_user_group_ids(
|
||||
user_id: &str,
|
||||
) -> anyhow::Result<Vec<String>> {
|
||||
let res = get_user_user_groups(user_id)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|ug| ug.id)
|
||||
.collect();
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
/// Returns Vec of all queries on permissions that match against the user
|
||||
/// or any user groups that the user is a part of.
|
||||
/// Result used with Mongodb '$or'.
|
||||
#[instrument(level = "debug")]
|
||||
pub async fn user_target_query(
|
||||
pub fn user_target_query(
|
||||
user_id: &str,
|
||||
user_groups: &[UserGroup],
|
||||
) -> anyhow::Result<Vec<Document>> {
|
||||
let mut user_target_query = vec![
|
||||
doc! { "user_target.type": "User", "user_target.id": user_id },
|
||||
];
|
||||
let user_groups = get_user_user_group_ids(user_id)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|ug_id| {
|
||||
doc! {
|
||||
"user_target.type": "UserGroup", "user_target.id": ug_id,
|
||||
}
|
||||
});
|
||||
let user_groups = user_groups.iter().map(|ug| {
|
||||
doc! {
|
||||
"user_target.type": "UserGroup", "user_target.id": &ug.id,
|
||||
}
|
||||
});
|
||||
user_target_query.extend(user_groups);
|
||||
Ok(user_target_query)
|
||||
}
|
||||
|
||||
#[instrument(level = "debug")]
|
||||
pub async fn get_user_permission_on_resource(
|
||||
user_id: &str,
|
||||
user: &User,
|
||||
resource_variant: ResourceTargetVariant,
|
||||
resource_id: &str,
|
||||
) -> anyhow::Result<PermissionLevel> {
|
||||
let lowest_permission = if core_config().transparent_mode {
|
||||
if user.admin {
|
||||
return Ok(PermissionLevel::Write);
|
||||
}
|
||||
|
||||
// Start with base of Read or None
|
||||
let mut base = if core_config().transparent_mode {
|
||||
PermissionLevel::Read
|
||||
} else {
|
||||
PermissionLevel::None
|
||||
};
|
||||
|
||||
// Overlay users base on resource variant
|
||||
if let Some(level) = user.all.get(&resource_variant).cloned() {
|
||||
if level > base {
|
||||
base = level;
|
||||
}
|
||||
}
|
||||
if base == PermissionLevel::Write {
|
||||
// No reason to keep going if already Write at this point.
|
||||
return Ok(PermissionLevel::Write);
|
||||
}
|
||||
|
||||
// Overlay any user groups base on resource variant
|
||||
let groups = get_user_user_groups(&user.id).await?;
|
||||
for group in &groups {
|
||||
if let Some(level) = group.all.get(&resource_variant).cloned() {
|
||||
if level > base {
|
||||
base = level;
|
||||
}
|
||||
}
|
||||
}
|
||||
if base == PermissionLevel::Write {
|
||||
// No reason to keep going if already Write at this point.
|
||||
return Ok(PermissionLevel::Write);
|
||||
}
|
||||
|
||||
// Overlay any specific permissions
|
||||
let permission = find_collect(
|
||||
&db_client().await.permissions,
|
||||
doc! {
|
||||
"$or": user_target_query(user_id).await?,
|
||||
"$or": user_target_query(&user.id, &groups)?,
|
||||
"resource_target.type": resource_variant.as_ref(),
|
||||
"resource_target.id": resource_id
|
||||
},
|
||||
@@ -184,7 +222,7 @@ pub async fn get_user_permission_on_resource(
|
||||
.context("failed to query db for permissions")?
|
||||
.into_iter()
|
||||
// get the max permission user has between personal / any user groups
|
||||
.fold(lowest_permission, |level, permission| {
|
||||
.fold(base, |level, permission| {
|
||||
if permission.level > level {
|
||||
permission.level
|
||||
} else {
|
||||
@@ -194,15 +232,39 @@ pub async fn get_user_permission_on_resource(
|
||||
Ok(permission)
|
||||
}
|
||||
|
||||
/// Returns None if still no need to filter by resource id (eg transparent mode, group membership with all access).
|
||||
#[instrument(level = "debug")]
|
||||
pub async fn get_resource_ids_for_non_admin(
|
||||
user_id: &str,
|
||||
pub async fn get_resource_ids_for_user(
|
||||
user: &User,
|
||||
resource_type: ResourceTargetVariant,
|
||||
) -> anyhow::Result<Vec<String>> {
|
||||
let permissions = find_collect(
|
||||
) -> anyhow::Result<Option<Vec<ObjectId>>> {
|
||||
// Check admin or transparent mode
|
||||
if user.admin || core_config().transparent_mode {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Check user 'all' on variant
|
||||
if let Some(level) = user.all.get(&resource_type).cloned() {
|
||||
if level > PermissionLevel::None {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
|
||||
// Check user groups 'all' on variant
|
||||
let groups = get_user_user_groups(&user.id).await?;
|
||||
for group in &groups {
|
||||
if let Some(level) = group.all.get(&resource_type).cloned() {
|
||||
if level > PermissionLevel::None {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get specific ids
|
||||
let ids = find_collect(
|
||||
&db_client().await.permissions,
|
||||
doc! {
|
||||
"$or": user_target_query(user_id).await?,
|
||||
"$or": user_target_query(&user.id, &groups)?,
|
||||
"resource_target.type": resource_type.as_ref(),
|
||||
"level": { "$in": ["Read", "Execute", "Write"] }
|
||||
},
|
||||
@@ -213,8 +275,12 @@ pub async fn get_resource_ids_for_non_admin(
|
||||
.into_iter()
|
||||
.map(|p| p.resource_target.extract_variant_id().1.to_string())
|
||||
// collect into hashset first to remove any duplicates
|
||||
.collect::<HashSet<_>>();
|
||||
Ok(permissions.into_iter().collect())
|
||||
.collect::<HashSet<_>>()
|
||||
.into_iter()
|
||||
.flat_map(|id| ObjectId::from_str(&id))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Ok(Some(ids))
|
||||
}
|
||||
|
||||
pub fn id_or_name_filter(id_or_name: &str) -> Document {
|
||||
@@ -224,6 +290,13 @@ pub fn id_or_name_filter(id_or_name: &str) -> Document {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn id_or_username_filter(id_or_username: &str) -> Document {
|
||||
match ObjectId::from_str(id_or_username) {
|
||||
Ok(id) => doc! { "_id": id },
|
||||
Err(_) => doc! { "username": id_or_username },
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_global_variables(
|
||||
) -> anyhow::Result<HashMap<String, String>> {
|
||||
Ok(
|
||||
@@ -240,7 +313,7 @@ pub async fn get_variable(name: &str) -> anyhow::Result<Variable> {
|
||||
db_client()
|
||||
.await
|
||||
.variables
|
||||
.find_one(doc! { "name": &name }, None)
|
||||
.find_one(doc! { "name": &name })
|
||||
.await
|
||||
.context("failed at call to db")?
|
||||
.with_context(|| {
|
||||
@@ -256,12 +329,12 @@ pub async fn get_latest_update(
|
||||
db_client()
|
||||
.await
|
||||
.updates
|
||||
.find_one(
|
||||
doc! {
|
||||
"target.type": resource_type.as_ref(),
|
||||
"target.id": id,
|
||||
"operation": operation.as_ref()
|
||||
},
|
||||
.find_one(doc! {
|
||||
"target.type": resource_type.as_ref(),
|
||||
"target.id": id,
|
||||
"operation": operation.as_ref()
|
||||
})
|
||||
.with_options(
|
||||
FindOneOptions::builder()
|
||||
.sort(doc! { "start_ts": -1 })
|
||||
.build(),
|
||||
|
||||
@@ -7,18 +7,19 @@ use monitor_client::{
|
||||
read::ListUserTargetPermissions,
|
||||
write::{
|
||||
CreateUserGroup, DeleteUserGroup, SetUsersInUserGroup,
|
||||
UpdatePermissionOnTarget,
|
||||
UpdatePermissionOnResourceType, UpdatePermissionOnTarget,
|
||||
},
|
||||
},
|
||||
entities::{
|
||||
permission::UserTarget,
|
||||
permission::{PermissionLevel, UserTarget},
|
||||
sync::SyncUpdate,
|
||||
toml::{PermissionToml, UserGroupToml},
|
||||
update::{Log, ResourceTarget},
|
||||
update::{Log, ResourceTarget, ResourceTargetVariant},
|
||||
user::sync_user,
|
||||
},
|
||||
};
|
||||
use mungos::find::find_collect;
|
||||
use regex::Regex;
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::state::{db_client, State};
|
||||
@@ -28,7 +29,7 @@ use super::resource::AllResourcesById;
|
||||
pub struct UpdateItem {
|
||||
user_group: UserGroupToml,
|
||||
update_users: bool,
|
||||
update_permissions: bool,
|
||||
all_diff: HashMap<ResourceTargetVariant, PermissionLevel>,
|
||||
}
|
||||
|
||||
pub struct DeleteItem {
|
||||
@@ -72,19 +73,49 @@ pub async fn get_updates_for_view(
|
||||
.collect::<HashMap<_, _>>();
|
||||
|
||||
for mut user_group in user_groups {
|
||||
user_group
|
||||
.permissions
|
||||
.retain(|p| p.level > PermissionLevel::None);
|
||||
|
||||
user_group.permissions = expand_user_group_permissions(
|
||||
user_group.permissions,
|
||||
all_resources,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"failed to expand user group {} permissions",
|
||||
user_group.name
|
||||
)
|
||||
})?;
|
||||
|
||||
let original = match map.get(&user_group.name).cloned() {
|
||||
Some(original) => original,
|
||||
None => {
|
||||
update.to_create += 1;
|
||||
update.log.push_str(&format!(
|
||||
"\n\n{}: user group: {}\n{}: {:?}\n{}: {:?}",
|
||||
colored("CREATE", Color::Green),
|
||||
colored(&user_group.name, Color::Green),
|
||||
muted("users"),
|
||||
user_group.users,
|
||||
muted("permissions"),
|
||||
user_group.permissions,
|
||||
));
|
||||
if user_group.all.is_empty() {
|
||||
update.log.push_str(&format!(
|
||||
"\n\n{}: user group: {}\n{}: {:#?}\n{}: {:#?}",
|
||||
colored("CREATE", Color::Green),
|
||||
colored(&user_group.name, Color::Green),
|
||||
muted("users"),
|
||||
user_group.users,
|
||||
muted("permissions"),
|
||||
user_group.permissions,
|
||||
));
|
||||
} else {
|
||||
update.log.push_str(&format!(
|
||||
"\n\n{}: user group: {}\n{}: {:#?}\n{}: {:#?}\n{}: {:#?}",
|
||||
colored("CREATE", Color::Green),
|
||||
colored(&user_group.name, Color::Green),
|
||||
muted("users"),
|
||||
user_group.users,
|
||||
muted("base permissions"),
|
||||
user_group.all,
|
||||
muted("permissions"),
|
||||
user_group.permissions,
|
||||
));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
@@ -107,6 +138,7 @@ pub async fn get_updates_for_view(
|
||||
.await
|
||||
.context("failed to query for existing UserGroup permissions")?
|
||||
.into_iter()
|
||||
.filter(|p| p.level > PermissionLevel::None)
|
||||
.map(|mut p| {
|
||||
// replace the ids with names
|
||||
match &mut p.resource_target {
|
||||
@@ -185,22 +217,27 @@ pub async fn get_updates_for_view(
|
||||
original_users.sort();
|
||||
user_group.users.sort();
|
||||
|
||||
let all_diff = diff_group_all(&original.all, &user_group.all);
|
||||
|
||||
user_group.permissions.sort_by(sort_permissions);
|
||||
original_permissions.sort_by(sort_permissions);
|
||||
|
||||
let update_users = user_group.users != original_users;
|
||||
let update_all = !all_diff.is_empty();
|
||||
let update_permissions =
|
||||
user_group.permissions != original_permissions;
|
||||
|
||||
// only add log after diff detected
|
||||
if update_users || update_permissions {
|
||||
if update_users || update_all || update_permissions {
|
||||
update.to_update += 1;
|
||||
update.log.push_str(&format!(
|
||||
"\n\n{}: user group: '{}'\n-------------------",
|
||||
colored("UPDATE", Color::Blue),
|
||||
bold(&user_group.name),
|
||||
));
|
||||
|
||||
let mut lines = Vec::<String>::new();
|
||||
|
||||
if update_users {
|
||||
let adding = user_group
|
||||
.users
|
||||
@@ -230,12 +267,36 @@ pub async fn get_updates_for_view(
|
||||
muted("adding"),
|
||||
))
|
||||
}
|
||||
|
||||
if update_all {
|
||||
let updates = all_diff
|
||||
.into_iter()
|
||||
.map(|(variant, (orig, incoming))| {
|
||||
format!(
|
||||
"{}: {} {} {}",
|
||||
bold(variant),
|
||||
colored(orig, Color::Red),
|
||||
muted("->"),
|
||||
colored(incoming, Color::Green)
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
lines.push(format!(
|
||||
"{}: 'base permission'\n{updates}",
|
||||
muted("field"),
|
||||
))
|
||||
}
|
||||
|
||||
if update_permissions {
|
||||
let adding = user_group
|
||||
.permissions
|
||||
.iter()
|
||||
.filter(|permission| {
|
||||
!original_permissions.contains(permission)
|
||||
// add if original has no exising permission on the target
|
||||
!original_permissions
|
||||
.iter()
|
||||
.any(|p| p.target == permission.target)
|
||||
})
|
||||
.map(|permission| format!("{permission:?}"))
|
||||
.collect::<Vec<_>>();
|
||||
@@ -244,10 +305,35 @@ pub async fn get_updates_for_view(
|
||||
} else {
|
||||
colored(&adding.join(", "), Color::Green)
|
||||
};
|
||||
let updating = user_group
|
||||
.permissions
|
||||
.iter()
|
||||
.filter(|permission| {
|
||||
// update if original has exising permission on the target with different level
|
||||
let Some(level) = original_permissions
|
||||
.iter()
|
||||
.find(|p| p.target == permission.target)
|
||||
.map(|p| p.level)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
permission.level != level
|
||||
})
|
||||
.map(|permission| format!("{permission:?}"))
|
||||
.collect::<Vec<_>>();
|
||||
let updating = if updating.is_empty() {
|
||||
String::from("None")
|
||||
} else {
|
||||
colored(&updating.join(", "), Color::Blue)
|
||||
};
|
||||
let removing = original_permissions
|
||||
.iter()
|
||||
.filter(|permission| {
|
||||
!user_group.permissions.contains(permission)
|
||||
// remove if incoming has no permission on the target
|
||||
!user_group
|
||||
.permissions
|
||||
.iter()
|
||||
.any(|p| p.target == permission.target)
|
||||
})
|
||||
.map(|permission| format!("{permission:?}"))
|
||||
.collect::<Vec<_>>();
|
||||
@@ -257,12 +343,14 @@ pub async fn get_updates_for_view(
|
||||
colored(&removing.join(", "), Color::Red)
|
||||
};
|
||||
lines.push(format!(
|
||||
"{}: 'permissions'\n{}: {removing}\n{}: {adding}",
|
||||
"{}: 'permissions'\n{}: {removing}\n{}: {updating}\n{}: {adding}",
|
||||
muted("field"),
|
||||
muted("removing"),
|
||||
muted("updating"),
|
||||
muted("adding"),
|
||||
))
|
||||
}
|
||||
|
||||
update.log.push('\n');
|
||||
update.log.push_str(&lines.join("\n-------------------\n"));
|
||||
}
|
||||
@@ -326,6 +414,22 @@ pub async fn get_updates_for_execution(
|
||||
.collect::<HashMap<_, _>>();
|
||||
|
||||
for mut user_group in user_groups {
|
||||
user_group
|
||||
.permissions
|
||||
.retain(|p| p.level > PermissionLevel::None);
|
||||
|
||||
user_group.permissions = expand_user_group_permissions(
|
||||
user_group.permissions,
|
||||
all_resources,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"failed to expand user group {} permissions",
|
||||
user_group.name
|
||||
)
|
||||
})?;
|
||||
|
||||
let original = match map.get(&user_group.name).cloned() {
|
||||
Some(original) => original,
|
||||
None => {
|
||||
@@ -352,6 +456,7 @@ pub async fn get_updates_for_execution(
|
||||
.await
|
||||
.context("failed to query for existing UserGroup permissions")?
|
||||
.into_iter()
|
||||
.filter(|p| p.level > PermissionLevel::None)
|
||||
.map(|mut p| {
|
||||
// replace the ids with names
|
||||
match &mut p.resource_target {
|
||||
@@ -430,19 +535,55 @@ pub async fn get_updates_for_execution(
|
||||
original_users.sort();
|
||||
user_group.users.sort();
|
||||
|
||||
let all_diff = diff_group_all(&original.all, &user_group.all);
|
||||
|
||||
user_group.permissions.sort_by(sort_permissions);
|
||||
original_permissions.sort_by(sort_permissions);
|
||||
|
||||
let update_users = user_group.users != original_users;
|
||||
let update_permissions =
|
||||
user_group.permissions != original_permissions;
|
||||
|
||||
// only push update after failed diff
|
||||
if update_users || update_permissions {
|
||||
// Extend permissions with any existing that have no target in incoming
|
||||
let to_remove = original_permissions
|
||||
.iter()
|
||||
.filter(|permission| {
|
||||
!user_group
|
||||
.permissions
|
||||
.iter()
|
||||
.any(|p| p.target == permission.target)
|
||||
})
|
||||
.map(|permission| PermissionToml {
|
||||
target: permission.target.clone(),
|
||||
level: PermissionLevel::None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
user_group.permissions.extend(to_remove);
|
||||
|
||||
// remove any permissions that already exist on original
|
||||
user_group.permissions.retain(|permission| {
|
||||
let Some(level) = original_permissions
|
||||
.iter()
|
||||
.find(|p| p.target == permission.target)
|
||||
.map(|p| p.level)
|
||||
else {
|
||||
// not in original, keep it
|
||||
return true;
|
||||
};
|
||||
// keep it if level doesn't match
|
||||
level != permission.level
|
||||
});
|
||||
|
||||
// only push update after diff detected
|
||||
if update_users
|
||||
|| !all_diff.is_empty()
|
||||
|| !user_group.permissions.is_empty()
|
||||
{
|
||||
to_update.push(UpdateItem {
|
||||
user_group,
|
||||
update_users,
|
||||
update_permissions,
|
||||
all_diff: all_diff
|
||||
.into_iter()
|
||||
.map(|(k, (_, v))| (k, v))
|
||||
.collect(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -516,6 +657,13 @@ pub async fn run_updates(
|
||||
&mut has_error,
|
||||
)
|
||||
.await;
|
||||
run_update_all(
|
||||
user_group.name.clone(),
|
||||
user_group.all,
|
||||
&mut log,
|
||||
&mut has_error,
|
||||
)
|
||||
.await;
|
||||
run_update_permissions(
|
||||
user_group.name,
|
||||
user_group.permissions,
|
||||
@@ -529,7 +677,7 @@ pub async fn run_updates(
|
||||
for UpdateItem {
|
||||
user_group,
|
||||
update_users,
|
||||
update_permissions,
|
||||
all_diff,
|
||||
} in to_update
|
||||
{
|
||||
if update_users {
|
||||
@@ -541,7 +689,16 @@ pub async fn run_updates(
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if update_permissions {
|
||||
if !all_diff.is_empty() {
|
||||
run_update_all(
|
||||
user_group.name.clone(),
|
||||
all_diff,
|
||||
&mut log,
|
||||
&mut has_error,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if !user_group.permissions.is_empty() {
|
||||
run_update_permissions(
|
||||
user_group.name,
|
||||
user_group.permissions,
|
||||
@@ -616,6 +773,41 @@ async fn set_users(
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_update_all(
|
||||
user_group: String,
|
||||
all_diff: HashMap<ResourceTargetVariant, PermissionLevel>,
|
||||
log: &mut String,
|
||||
has_error: &mut bool,
|
||||
) {
|
||||
for (resource_type, permission) in all_diff {
|
||||
if let Err(e) = State
|
||||
.resolve(
|
||||
UpdatePermissionOnResourceType {
|
||||
user_target: UserTarget::UserGroup(user_group.clone()),
|
||||
resource_type,
|
||||
permission,
|
||||
},
|
||||
sync_user().to_owned(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
*has_error = true;
|
||||
log.push_str(&format!(
|
||||
"\n{}: failed to set base permissions on {resource_type} in group {} | {e:#}",
|
||||
colored("ERROR", Color::Red),
|
||||
bold(&user_group)
|
||||
))
|
||||
} else {
|
||||
log.push_str(&format!(
|
||||
"\n{}: {} user group '{}' base permissions on {resource_type}",
|
||||
muted("INFO"),
|
||||
colored("updated", Color::Blue),
|
||||
bold(&user_group)
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_update_permissions(
|
||||
user_group: String,
|
||||
permissions: Vec<PermissionToml>,
|
||||
@@ -636,17 +828,188 @@ async fn run_update_permissions(
|
||||
{
|
||||
*has_error = true;
|
||||
log.push_str(&format!(
|
||||
"\n{}: failed to set permssion in group {} | target: {target:?} | {e:#}",
|
||||
"\n{}: failed to set permission in group {} | target: {target:?} | {e:#}",
|
||||
colored("ERROR", Color::Red),
|
||||
bold(&user_group)
|
||||
))
|
||||
} else {
|
||||
log.push_str(&format!(
|
||||
"\n{}: {} user group '{}' permissions",
|
||||
"\n{}: {} user group '{}' permissions | {}: {target:?} | {}: {level}",
|
||||
muted("INFO"),
|
||||
colored("updated", Color::Blue),
|
||||
bold(&user_group)
|
||||
bold(&user_group),
|
||||
muted("target"),
|
||||
muted("level")
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Expands any regex defined targets into the full list
|
||||
async fn expand_user_group_permissions(
|
||||
permissions: Vec<PermissionToml>,
|
||||
all_resources: &AllResourcesById,
|
||||
) -> anyhow::Result<Vec<PermissionToml>> {
|
||||
let mut expanded =
|
||||
Vec::<PermissionToml>::with_capacity(permissions.capacity());
|
||||
|
||||
for permission in permissions {
|
||||
let (variant, id) = permission.target.extract_variant_id();
|
||||
if id.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if id.starts_with('\\') && id.ends_with('\\') {
|
||||
let inner = &id[1..(id.len() - 1)];
|
||||
let regex = Regex::new(inner)
|
||||
.with_context(|| format!("invalid regex. got: {inner}"))?;
|
||||
match variant {
|
||||
ResourceTargetVariant::Build => {
|
||||
let permissions = all_resources
|
||||
.builds
|
||||
.values()
|
||||
.filter(|resource| regex.is_match(&resource.name))
|
||||
.map(|resource| PermissionToml {
|
||||
target: ResourceTarget::Build(resource.name.clone()),
|
||||
level: permission.level,
|
||||
});
|
||||
expanded.extend(permissions);
|
||||
}
|
||||
ResourceTargetVariant::Builder => {
|
||||
let permissions = all_resources
|
||||
.builders
|
||||
.values()
|
||||
.filter(|resource| regex.is_match(&resource.name))
|
||||
.map(|resource| PermissionToml {
|
||||
target: ResourceTarget::Builder(resource.name.clone()),
|
||||
level: permission.level,
|
||||
});
|
||||
expanded.extend(permissions);
|
||||
}
|
||||
ResourceTargetVariant::Deployment => {
|
||||
let permissions = all_resources
|
||||
.deployments
|
||||
.values()
|
||||
.filter(|resource| regex.is_match(&resource.name))
|
||||
.map(|resource| PermissionToml {
|
||||
target: ResourceTarget::Deployment(
|
||||
resource.name.clone(),
|
||||
),
|
||||
level: permission.level,
|
||||
});
|
||||
expanded.extend(permissions);
|
||||
}
|
||||
ResourceTargetVariant::Server => {
|
||||
let permissions = all_resources
|
||||
.servers
|
||||
.values()
|
||||
.filter(|resource| regex.is_match(&resource.name))
|
||||
.map(|resource| PermissionToml {
|
||||
target: ResourceTarget::Server(resource.name.clone()),
|
||||
level: permission.level,
|
||||
});
|
||||
expanded.extend(permissions);
|
||||
}
|
||||
ResourceTargetVariant::Repo => {
|
||||
let permissions = all_resources
|
||||
.repos
|
||||
.values()
|
||||
.filter(|resource| regex.is_match(&resource.name))
|
||||
.map(|resource| PermissionToml {
|
||||
target: ResourceTarget::Repo(resource.name.clone()),
|
||||
level: permission.level,
|
||||
});
|
||||
expanded.extend(permissions);
|
||||
}
|
||||
ResourceTargetVariant::Alerter => {
|
||||
let permissions = all_resources
|
||||
.alerters
|
||||
.values()
|
||||
.filter(|resource| regex.is_match(&resource.name))
|
||||
.map(|resource| PermissionToml {
|
||||
target: ResourceTarget::Alerter(resource.name.clone()),
|
||||
level: permission.level,
|
||||
});
|
||||
expanded.extend(permissions);
|
||||
}
|
||||
ResourceTargetVariant::Procedure => {
|
||||
let permissions = all_resources
|
||||
.procedures
|
||||
.values()
|
||||
.filter(|resource| regex.is_match(&resource.name))
|
||||
.map(|resource| PermissionToml {
|
||||
target: ResourceTarget::Procedure(
|
||||
resource.name.clone(),
|
||||
),
|
||||
level: permission.level,
|
||||
});
|
||||
expanded.extend(permissions);
|
||||
}
|
||||
ResourceTargetVariant::ServerTemplate => {
|
||||
let permissions = all_resources
|
||||
.templates
|
||||
.values()
|
||||
.filter(|resource| regex.is_match(&resource.name))
|
||||
.map(|resource| PermissionToml {
|
||||
target: ResourceTarget::ServerTemplate(
|
||||
resource.name.clone(),
|
||||
),
|
||||
level: permission.level,
|
||||
});
|
||||
expanded.extend(permissions);
|
||||
}
|
||||
ResourceTargetVariant::ResourceSync => {
|
||||
let permissions = all_resources
|
||||
.syncs
|
||||
.values()
|
||||
.filter(|resource| regex.is_match(&resource.name))
|
||||
.map(|resource| PermissionToml {
|
||||
target: ResourceTarget::ResourceSync(
|
||||
resource.name.clone(),
|
||||
),
|
||||
level: permission.level,
|
||||
});
|
||||
expanded.extend(permissions);
|
||||
}
|
||||
ResourceTargetVariant::System => {}
|
||||
}
|
||||
} else {
|
||||
// No regex
|
||||
expanded.push(permission);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(expanded)
|
||||
}
|
||||
|
||||
type AllDiff =
|
||||
HashMap<ResourceTargetVariant, (PermissionLevel, PermissionLevel)>;
|
||||
|
||||
/// diffs user_group.all
|
||||
fn diff_group_all(
|
||||
original: &HashMap<ResourceTargetVariant, PermissionLevel>,
|
||||
incoming: &HashMap<ResourceTargetVariant, PermissionLevel>,
|
||||
) -> AllDiff {
|
||||
let mut to_update = HashMap::new();
|
||||
|
||||
// need to compare both forward and backward because either hashmap could be sparse.
|
||||
|
||||
// forward direction
|
||||
for (variant, level) in incoming {
|
||||
let original_level = original.get(variant).unwrap_or_default();
|
||||
if level == original_level {
|
||||
continue;
|
||||
}
|
||||
to_update.insert(*variant, (*original_level, *level));
|
||||
}
|
||||
|
||||
// backward direction
|
||||
for (variant, level) in original {
|
||||
let incoming_level = incoming.get(variant).unwrap_or_default();
|
||||
if level == incoming_level {
|
||||
continue;
|
||||
}
|
||||
to_update.insert(*variant, (*level, *incoming_level));
|
||||
}
|
||||
|
||||
to_update
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ pub async fn add_update(
|
||||
update.id = db_client()
|
||||
.await
|
||||
.updates
|
||||
.insert_one(&update, None)
|
||||
.insert_one(&update)
|
||||
.await
|
||||
.context("failed to insert update into db")?
|
||||
.inserted_id
|
||||
|
||||
@@ -1,425 +0,0 @@
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use anyhow::{anyhow, Context};
|
||||
use axum::{extract::Path, http::HeaderMap, routing::post, Router};
|
||||
use hex::ToHex;
|
||||
use hmac::{Hmac, Mac};
|
||||
use monitor_client::{
|
||||
api::{execute, write::RefreshResourceSyncPending},
|
||||
entities::{
|
||||
build::Build, procedure::Procedure, repo::Repo,
|
||||
sync::ResourceSync, user::github_user,
|
||||
},
|
||||
};
|
||||
use resolver_api::Resolve;
|
||||
use serde::Deserialize;
|
||||
use sha2::Sha256;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::Instrument;
|
||||
|
||||
use crate::{
|
||||
config::core_config,
|
||||
helpers::{
|
||||
cache::Cache, random_duration, update::init_execution_update,
|
||||
},
|
||||
resource,
|
||||
state::State,
|
||||
};
|
||||
|
||||
type HmacSha256 = Hmac<Sha256>;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Id {
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct IdBranch {
|
||||
id: String,
|
||||
branch: String,
|
||||
}
|
||||
|
||||
pub fn router() -> Router {
|
||||
Router::new()
|
||||
.route(
|
||||
"/build/:id",
|
||||
post(
|
||||
|Path(Id { id }), headers: HeaderMap, body: String| async move {
|
||||
tokio::spawn(async move {
|
||||
let span = info_span!("build_webhook", id);
|
||||
async {
|
||||
let res = handle_build_webhook(id.clone(), headers, body).await;
|
||||
if let Err(e) = res {
|
||||
warn!("failed to run build webook for build {id} | {e:#}");
|
||||
}
|
||||
}
|
||||
.instrument(span)
|
||||
.await
|
||||
});
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/repo/:id/clone",
|
||||
post(
|
||||
|Path(Id { id }), headers: HeaderMap, body: String| async move {
|
||||
tokio::spawn(async move {
|
||||
let span = info_span!("repo_clone_webhook", id);
|
||||
async {
|
||||
let res = handle_repo_clone_webhook(id.clone(), headers, body).await;
|
||||
if let Err(e) = res {
|
||||
warn!("failed to run repo clone webook for repo {id} | {e:#}");
|
||||
}
|
||||
}
|
||||
.instrument(span)
|
||||
.await
|
||||
});
|
||||
},
|
||||
)
|
||||
)
|
||||
.route(
|
||||
"/repo/:id/pull",
|
||||
post(
|
||||
|Path(Id { id }), headers: HeaderMap, body: String| async move {
|
||||
tokio::spawn(async move {
|
||||
let span = info_span!("repo_pull_webhook", id);
|
||||
async {
|
||||
let res = handle_repo_pull_webhook(id.clone(), headers, body).await;
|
||||
if let Err(e) = res {
|
||||
warn!("failed to run repo pull webook for repo {id} | {e:#}");
|
||||
}
|
||||
}
|
||||
.instrument(span)
|
||||
.await
|
||||
});
|
||||
},
|
||||
)
|
||||
)
|
||||
.route(
|
||||
"/procedure/:id/:branch",
|
||||
post(
|
||||
|Path(IdBranch { id, branch }), headers: HeaderMap, body: String| async move {
|
||||
tokio::spawn(async move {
|
||||
let span = info_span!("procedure_webhook", id, branch);
|
||||
async {
|
||||
let res = handle_procedure_webhook(
|
||||
id.clone(),
|
||||
branch,
|
||||
headers,
|
||||
body
|
||||
).await;
|
||||
if let Err(e) = res {
|
||||
warn!("failed to run procedure webook for procedure {id} | {e:#}");
|
||||
}
|
||||
}
|
||||
.instrument(span)
|
||||
.await
|
||||
});
|
||||
},
|
||||
)
|
||||
)
|
||||
.route(
|
||||
"/sync/:id/refresh",
|
||||
post(
|
||||
|Path(Id { id }), headers: HeaderMap, body: String| async move {
|
||||
tokio::spawn(async move {
|
||||
let span = info_span!("sync_refresh_webhook", id);
|
||||
async {
|
||||
let res = handle_sync_refresh_webhook(
|
||||
id.clone(),
|
||||
headers,
|
||||
body
|
||||
).await;
|
||||
if let Err(e) = res {
|
||||
warn!("failed to run sync webook for sync {id} | {e:#}");
|
||||
}
|
||||
}
|
||||
.instrument(span)
|
||||
.await
|
||||
});
|
||||
},
|
||||
)
|
||||
)
|
||||
.route(
|
||||
"/sync/:id/sync",
|
||||
post(
|
||||
|Path(Id { id }), headers: HeaderMap, body: String| async move {
|
||||
tokio::spawn(async move {
|
||||
let span = info_span!("sync_execute_webhook", id);
|
||||
async {
|
||||
let res = handle_sync_execute_webhook(
|
||||
id.clone(),
|
||||
headers,
|
||||
body
|
||||
).await;
|
||||
if let Err(e) = res {
|
||||
warn!("failed to run sync webook for sync {id} | {e:#}");
|
||||
}
|
||||
}
|
||||
.instrument(span)
|
||||
.await
|
||||
});
|
||||
},
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
async fn handle_build_webhook(
|
||||
build_id: String,
|
||||
headers: HeaderMap,
|
||||
body: String,
|
||||
) -> anyhow::Result<()> {
|
||||
// Acquire and hold lock to make a task queue for
|
||||
// subsequent listener calls on same resource.
|
||||
// It would fail if we let it go through from action state busy.
|
||||
let lock = build_locks().get_or_insert_default(&build_id).await;
|
||||
let _lock = lock.lock().await;
|
||||
|
||||
verify_gh_signature(headers, &body).await?;
|
||||
let request_branch = extract_branch(&body)?;
|
||||
let build = resource::get::<Build>(&build_id).await?;
|
||||
if !build.config.webhook_enabled {
|
||||
return Err(anyhow!("build does not have webhook enabled"));
|
||||
}
|
||||
if request_branch != build.config.branch {
|
||||
return Err(anyhow!("request branch does not match expected"));
|
||||
}
|
||||
let user = github_user().to_owned();
|
||||
let req = crate::api::execute::ExecuteRequest::RunBuild(
|
||||
execute::RunBuild { build: build_id },
|
||||
);
|
||||
let update = init_execution_update(&req, &user).await?;
|
||||
let crate::api::execute::ExecuteRequest::RunBuild(req) = req else {
|
||||
unreachable!()
|
||||
};
|
||||
State.resolve(req, (user, update)).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_repo_clone_webhook(
|
||||
repo_id: String,
|
||||
headers: HeaderMap,
|
||||
body: String,
|
||||
) -> anyhow::Result<()> {
|
||||
// Acquire and hold lock to make a task queue for
|
||||
// subsequent listener calls on same resource.
|
||||
// It would fail if we let it go through from action state busy.
|
||||
let lock = repo_locks().get_or_insert_default(&repo_id).await;
|
||||
let _lock = lock.lock().await;
|
||||
|
||||
verify_gh_signature(headers, &body).await?;
|
||||
let request_branch = extract_branch(&body)?;
|
||||
let repo = resource::get::<Repo>(&repo_id).await?;
|
||||
if !repo.config.webhook_enabled {
|
||||
return Err(anyhow!("repo does not have webhook enabled"));
|
||||
}
|
||||
if request_branch != repo.config.branch {
|
||||
return Err(anyhow!("request branch does not match expected"));
|
||||
}
|
||||
let user = github_user().to_owned();
|
||||
let req = crate::api::execute::ExecuteRequest::CloneRepo(
|
||||
execute::CloneRepo { repo: repo_id },
|
||||
);
|
||||
let update = init_execution_update(&req, &user).await?;
|
||||
let crate::api::execute::ExecuteRequest::CloneRepo(req) = req
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
State.resolve(req, (user, update)).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_repo_pull_webhook(
|
||||
repo_id: String,
|
||||
headers: HeaderMap,
|
||||
body: String,
|
||||
) -> anyhow::Result<()> {
|
||||
// Acquire and hold lock to make a task queue for
|
||||
// subsequent listener calls on same resource.
|
||||
// It would fail if we let it go through from action state busy.
|
||||
let lock = repo_locks().get_or_insert_default(&repo_id).await;
|
||||
let _lock = lock.lock().await;
|
||||
|
||||
verify_gh_signature(headers, &body).await?;
|
||||
let request_branch = extract_branch(&body)?;
|
||||
let repo = resource::get::<Repo>(&repo_id).await?;
|
||||
if !repo.config.webhook_enabled {
|
||||
return Err(anyhow!("repo does not have webhook enabled"));
|
||||
}
|
||||
if request_branch != repo.config.branch {
|
||||
return Err(anyhow!("request branch does not match expected"));
|
||||
}
|
||||
let user = github_user().to_owned();
|
||||
let req = crate::api::execute::ExecuteRequest::PullRepo(
|
||||
execute::PullRepo { repo: repo_id },
|
||||
);
|
||||
let update = init_execution_update(&req, &user).await?;
|
||||
let crate::api::execute::ExecuteRequest::PullRepo(req) = req else {
|
||||
unreachable!()
|
||||
};
|
||||
State.resolve(req, (user, update)).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_procedure_webhook(
|
||||
procedure_id: String,
|
||||
target_branch: String,
|
||||
headers: HeaderMap,
|
||||
body: String,
|
||||
) -> anyhow::Result<()> {
|
||||
// Acquire and hold lock to make a task queue for
|
||||
// subsequent listener calls on same resource.
|
||||
// It would fail if we let it go through from action state busy.
|
||||
let lock =
|
||||
procedure_locks().get_or_insert_default(&procedure_id).await;
|
||||
let _lock = lock.lock().await;
|
||||
|
||||
verify_gh_signature(headers, &body).await?;
|
||||
let request_branch = extract_branch(&body)?;
|
||||
if request_branch != target_branch {
|
||||
return Err(anyhow!("request branch does not match expected"));
|
||||
}
|
||||
let procedure = resource::get::<Procedure>(&procedure_id).await?;
|
||||
if !procedure.config.webhook_enabled {
|
||||
return Err(anyhow!("procedure does not have webhook enabled"));
|
||||
}
|
||||
let user = github_user().to_owned();
|
||||
let req = crate::api::execute::ExecuteRequest::RunProcedure(
|
||||
execute::RunProcedure {
|
||||
procedure: procedure_id,
|
||||
},
|
||||
);
|
||||
let update = init_execution_update(&req, &user).await?;
|
||||
let crate::api::execute::ExecuteRequest::RunProcedure(req) = req
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
State.resolve(req, (user, update)).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_sync_refresh_webhook(
|
||||
sync_id: String,
|
||||
headers: HeaderMap,
|
||||
body: String,
|
||||
) -> anyhow::Result<()> {
|
||||
// Acquire and hold lock to make a task queue for
|
||||
// subsequent listener calls on same resource.
|
||||
// It would fail if we let it go through from action state busy.
|
||||
let lock = sync_locks().get_or_insert_default(&sync_id).await;
|
||||
let _lock = lock.lock().await;
|
||||
|
||||
verify_gh_signature(headers, &body).await?;
|
||||
let request_branch = extract_branch(&body)?;
|
||||
let sync = resource::get::<ResourceSync>(&sync_id).await?;
|
||||
if !sync.config.webhook_enabled {
|
||||
return Err(anyhow!("sync does not have webhook enabled"));
|
||||
}
|
||||
if request_branch != sync.config.branch {
|
||||
return Err(anyhow!("request branch does not match expected"));
|
||||
}
|
||||
let user = github_user().to_owned();
|
||||
State
|
||||
.resolve(RefreshResourceSyncPending { sync: sync_id }, user)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_sync_execute_webhook(
|
||||
sync_id: String,
|
||||
headers: HeaderMap,
|
||||
body: String,
|
||||
) -> anyhow::Result<()> {
|
||||
// Acquire and hold lock to make a task queue for
|
||||
// subsequent listener calls on same resource.
|
||||
// It would fail if we let it go through from action state busy.
|
||||
let lock = sync_locks().get_or_insert_default(&sync_id).await;
|
||||
let _lock = lock.lock().await;
|
||||
|
||||
verify_gh_signature(headers, &body).await?;
|
||||
let request_branch = extract_branch(&body)?;
|
||||
let sync = resource::get::<ResourceSync>(&sync_id).await?;
|
||||
if !sync.config.webhook_enabled {
|
||||
return Err(anyhow!("sync does not have webhook enabled"));
|
||||
}
|
||||
if request_branch != sync.config.branch {
|
||||
return Err(anyhow!("request branch does not match expected"));
|
||||
}
|
||||
let user = github_user().to_owned();
|
||||
let req =
|
||||
crate::api::execute::ExecuteRequest::RunSync(execute::RunSync {
|
||||
sync: sync_id,
|
||||
});
|
||||
let update = init_execution_update(&req, &user).await?;
|
||||
let crate::api::execute::ExecuteRequest::RunSync(req) = req else {
|
||||
unreachable!()
|
||||
};
|
||||
State.resolve(req, (user, update)).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[instrument(skip_all)]
|
||||
async fn verify_gh_signature(
|
||||
headers: HeaderMap,
|
||||
body: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
// wait random amount of time
|
||||
tokio::time::sleep(random_duration(0, 500)).await;
|
||||
|
||||
let signature = headers.get("x-hub-signature-256");
|
||||
if signature.is_none() {
|
||||
return Err(anyhow!("no signature in headers"));
|
||||
}
|
||||
let signature = signature.unwrap().to_str();
|
||||
if signature.is_err() {
|
||||
return Err(anyhow!("failed to unwrap signature"));
|
||||
}
|
||||
let signature = signature.unwrap().replace("sha256=", "");
|
||||
let mut mac = HmacSha256::new_from_slice(
|
||||
core_config().github_webhook_secret.as_bytes(),
|
||||
)
|
||||
.expect("github webhook | failed to create hmac sha256");
|
||||
mac.update(body.as_bytes());
|
||||
let expected = mac.finalize().into_bytes().encode_hex::<String>();
|
||||
if signature == expected {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!("signature does not equal expected"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct GithubWebhookBody {
|
||||
#[serde(rename = "ref")]
|
||||
branch: String,
|
||||
}
|
||||
|
||||
fn extract_branch(body: &str) -> anyhow::Result<String> {
|
||||
let branch = serde_json::from_str::<GithubWebhookBody>(body)
|
||||
.context("failed to parse github request body")?
|
||||
.branch
|
||||
.replace("refs/heads/", "");
|
||||
Ok(branch)
|
||||
}
|
||||
|
||||
type ListenerLockCache = Cache<String, Arc<Mutex<()>>>;
|
||||
|
||||
fn build_locks() -> &'static ListenerLockCache {
|
||||
static BUILD_LOCKS: OnceLock<ListenerLockCache> = OnceLock::new();
|
||||
BUILD_LOCKS.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
fn repo_locks() -> &'static ListenerLockCache {
|
||||
static REPO_LOCKS: OnceLock<ListenerLockCache> = OnceLock::new();
|
||||
REPO_LOCKS.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
fn procedure_locks() -> &'static ListenerLockCache {
|
||||
static BUILD_LOCKS: OnceLock<ListenerLockCache> = OnceLock::new();
|
||||
BUILD_LOCKS.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
fn sync_locks() -> &'static ListenerLockCache {
|
||||
static SYNC_LOCKS: OnceLock<ListenerLockCache> = OnceLock::new();
|
||||
SYNC_LOCKS.get_or_init(Default::default)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use axum::http::HeaderMap;
|
||||
use monitor_client::{
|
||||
api::execute::RunBuild,
|
||||
entities::{build::Build, user::github_user},
|
||||
};
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::{
|
||||
api::execute::ExecuteRequest,
|
||||
helpers::update::init_execution_update, resource, state::State,
|
||||
};
|
||||
|
||||
use super::{extract_branch, verify_gh_signature, ListenerLockCache};
|
||||
|
||||
fn build_locks() -> &'static ListenerLockCache {
|
||||
static BUILD_LOCKS: OnceLock<ListenerLockCache> = OnceLock::new();
|
||||
BUILD_LOCKS.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
pub async fn handle_build_webhook(
|
||||
build_id: String,
|
||||
headers: HeaderMap,
|
||||
body: String,
|
||||
) -> anyhow::Result<()> {
|
||||
// Acquire and hold lock to make a task queue for
|
||||
// subsequent listener calls on same resource.
|
||||
// It would fail if we let it go through from action state busy.
|
||||
let lock = build_locks().get_or_insert_default(&build_id).await;
|
||||
let _lock = lock.lock().await;
|
||||
|
||||
verify_gh_signature(headers, &body).await?;
|
||||
let request_branch = extract_branch(&body)?;
|
||||
let build = resource::get::<Build>(&build_id).await?;
|
||||
if !build.config.webhook_enabled {
|
||||
return Err(anyhow!("build does not have webhook enabled"));
|
||||
}
|
||||
if request_branch != build.config.branch {
|
||||
return Err(anyhow!("request branch does not match expected"));
|
||||
}
|
||||
let user = github_user().to_owned();
|
||||
let req = ExecuteRequest::RunBuild(RunBuild { build: build_id });
|
||||
let update = init_execution_update(&req, &user).await?;
|
||||
let ExecuteRequest::RunBuild(req) = req else {
|
||||
unreachable!()
|
||||
};
|
||||
State.resolve(req, (user, update)).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{anyhow, Context};
|
||||
use axum::{extract::Path, http::HeaderMap, routing::post, Router};
|
||||
use hex::ToHex;
|
||||
use hmac::{Hmac, Mac};
|
||||
use serde::Deserialize;
|
||||
use sha2::Sha256;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::Instrument;
|
||||
|
||||
use crate::{
|
||||
config::core_config,
|
||||
helpers::{cache::Cache, random_duration},
|
||||
};
|
||||
|
||||
mod build;
|
||||
mod procedure;
|
||||
mod repo;
|
||||
mod sync;
|
||||
|
||||
type HmacSha256 = Hmac<Sha256>;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Id {
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct IdBranch {
|
||||
id: String,
|
||||
branch: String,
|
||||
}
|
||||
|
||||
pub fn router() -> Router {
|
||||
Router::new()
|
||||
.route(
|
||||
"/build/:id",
|
||||
post(
|
||||
|Path(Id { id }), headers: HeaderMap, body: String| async move {
|
||||
tokio::spawn(async move {
|
||||
let span = info_span!("build_webhook", id);
|
||||
async {
|
||||
let res = build::handle_build_webhook(id.clone(), headers, body).await;
|
||||
if let Err(e) = res {
|
||||
warn!("failed to run build webook for build {id} | {e:#}");
|
||||
}
|
||||
}
|
||||
.instrument(span)
|
||||
.await
|
||||
});
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/repo/:id/clone",
|
||||
post(
|
||||
|Path(Id { id }), headers: HeaderMap, body: String| async move {
|
||||
tokio::spawn(async move {
|
||||
let span = info_span!("repo_clone_webhook", id);
|
||||
async {
|
||||
let res = repo::handle_repo_clone_webhook(id.clone(), headers, body).await;
|
||||
if let Err(e) = res {
|
||||
warn!("failed to run repo clone webook for repo {id} | {e:#}");
|
||||
}
|
||||
}
|
||||
.instrument(span)
|
||||
.await
|
||||
});
|
||||
},
|
||||
)
|
||||
)
|
||||
.route(
|
||||
"/repo/:id/pull",
|
||||
post(
|
||||
|Path(Id { id }), headers: HeaderMap, body: String| async move {
|
||||
tokio::spawn(async move {
|
||||
let span = info_span!("repo_pull_webhook", id);
|
||||
async {
|
||||
let res = repo::handle_repo_pull_webhook(id.clone(), headers, body).await;
|
||||
if let Err(e) = res {
|
||||
warn!("failed to run repo pull webook for repo {id} | {e:#}");
|
||||
}
|
||||
}
|
||||
.instrument(span)
|
||||
.await
|
||||
});
|
||||
},
|
||||
)
|
||||
)
|
||||
.route(
|
||||
"/procedure/:id/:branch",
|
||||
post(
|
||||
|Path(IdBranch { id, branch }), headers: HeaderMap, body: String| async move {
|
||||
tokio::spawn(async move {
|
||||
let span = info_span!("procedure_webhook", id, branch);
|
||||
async {
|
||||
let res = procedure::handle_procedure_webhook(
|
||||
id.clone(),
|
||||
branch,
|
||||
headers,
|
||||
body
|
||||
).await;
|
||||
if let Err(e) = res {
|
||||
warn!("failed to run procedure webook for procedure {id} | {e:#}");
|
||||
}
|
||||
}
|
||||
.instrument(span)
|
||||
.await
|
||||
});
|
||||
},
|
||||
)
|
||||
)
|
||||
.route(
|
||||
"/sync/:id/refresh",
|
||||
post(
|
||||
|Path(Id { id }), headers: HeaderMap, body: String| async move {
|
||||
tokio::spawn(async move {
|
||||
let span = info_span!("sync_refresh_webhook", id);
|
||||
async {
|
||||
let res = sync::handle_sync_refresh_webhook(
|
||||
id.clone(),
|
||||
headers,
|
||||
body
|
||||
).await;
|
||||
if let Err(e) = res {
|
||||
warn!("failed to run sync webook for sync {id} | {e:#}");
|
||||
}
|
||||
}
|
||||
.instrument(span)
|
||||
.await
|
||||
});
|
||||
},
|
||||
)
|
||||
)
|
||||
.route(
|
||||
"/sync/:id/sync",
|
||||
post(
|
||||
|Path(Id { id }), headers: HeaderMap, body: String| async move {
|
||||
tokio::spawn(async move {
|
||||
let span = info_span!("sync_execute_webhook", id);
|
||||
async {
|
||||
let res = sync::handle_sync_execute_webhook(
|
||||
id.clone(),
|
||||
headers,
|
||||
body
|
||||
).await;
|
||||
if let Err(e) = res {
|
||||
warn!("failed to run sync webook for sync {id} | {e:#}");
|
||||
}
|
||||
}
|
||||
.instrument(span)
|
||||
.await
|
||||
});
|
||||
},
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
#[instrument(skip_all)]
|
||||
async fn verify_gh_signature(
|
||||
headers: HeaderMap,
|
||||
body: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
// wait random amount of time
|
||||
tokio::time::sleep(random_duration(0, 500)).await;
|
||||
|
||||
let signature = headers.get("x-hub-signature-256");
|
||||
if signature.is_none() {
|
||||
return Err(anyhow!("no signature in headers"));
|
||||
}
|
||||
let signature = signature.unwrap().to_str();
|
||||
if signature.is_err() {
|
||||
return Err(anyhow!("failed to unwrap signature"));
|
||||
}
|
||||
let signature = signature.unwrap().replace("sha256=", "");
|
||||
let mut mac = HmacSha256::new_from_slice(
|
||||
core_config().github_webhook_secret.as_bytes(),
|
||||
)
|
||||
.expect("github webhook | failed to create hmac sha256");
|
||||
mac.update(body.as_bytes());
|
||||
let expected = mac.finalize().into_bytes().encode_hex::<String>();
|
||||
if signature == expected {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!("signature does not equal expected"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct GithubWebhookBody {
|
||||
#[serde(rename = "ref")]
|
||||
branch: String,
|
||||
}
|
||||
|
||||
fn extract_branch(body: &str) -> anyhow::Result<String> {
|
||||
let branch = serde_json::from_str::<GithubWebhookBody>(body)
|
||||
.context("failed to parse github request body")?
|
||||
.branch
|
||||
.replace("refs/heads/", "");
|
||||
Ok(branch)
|
||||
}
|
||||
|
||||
type ListenerLockCache = Cache<String, Arc<Mutex<()>>>;
|
||||
@@ -0,0 +1,55 @@
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use axum::http::HeaderMap;
|
||||
use monitor_client::{
|
||||
api::execute::RunProcedure,
|
||||
entities::{procedure::Procedure, user::github_user},
|
||||
};
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::{
|
||||
api::execute::ExecuteRequest,
|
||||
helpers::update::init_execution_update, resource, state::State,
|
||||
};
|
||||
|
||||
use super::{extract_branch, verify_gh_signature, ListenerLockCache};
|
||||
|
||||
fn procedure_locks() -> &'static ListenerLockCache {
|
||||
static BUILD_LOCKS: OnceLock<ListenerLockCache> = OnceLock::new();
|
||||
BUILD_LOCKS.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
pub async fn handle_procedure_webhook(
|
||||
procedure_id: String,
|
||||
target_branch: String,
|
||||
headers: HeaderMap,
|
||||
body: String,
|
||||
) -> anyhow::Result<()> {
|
||||
// Acquire and hold lock to make a task queue for
|
||||
// subsequent listener calls on same resource.
|
||||
// It would fail if we let it go through from action state busy.
|
||||
let lock =
|
||||
procedure_locks().get_or_insert_default(&procedure_id).await;
|
||||
let _lock = lock.lock().await;
|
||||
|
||||
verify_gh_signature(headers, &body).await?;
|
||||
let request_branch = extract_branch(&body)?;
|
||||
if request_branch != target_branch {
|
||||
return Err(anyhow!("request branch does not match expected"));
|
||||
}
|
||||
let procedure = resource::get::<Procedure>(&procedure_id).await?;
|
||||
if !procedure.config.webhook_enabled {
|
||||
return Err(anyhow!("procedure does not have webhook enabled"));
|
||||
}
|
||||
let user = github_user().to_owned();
|
||||
let req = ExecuteRequest::RunProcedure(RunProcedure {
|
||||
procedure: procedure_id,
|
||||
});
|
||||
let update = init_execution_update(&req, &user).await?;
|
||||
let ExecuteRequest::RunProcedure(req) = req else {
|
||||
unreachable!()
|
||||
};
|
||||
State.resolve(req, (user, update)).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use axum::http::HeaderMap;
|
||||
use monitor_client::{
|
||||
api::execute::{CloneRepo, PullRepo},
|
||||
entities::{repo::Repo, user::github_user},
|
||||
};
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::{
|
||||
helpers::update::init_execution_update, resource, state::State,
|
||||
};
|
||||
|
||||
use super::{extract_branch, verify_gh_signature, ListenerLockCache};
|
||||
|
||||
fn repo_locks() -> &'static ListenerLockCache {
|
||||
static REPO_LOCKS: OnceLock<ListenerLockCache> = OnceLock::new();
|
||||
REPO_LOCKS.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
pub async fn handle_repo_clone_webhook(
|
||||
repo_id: String,
|
||||
headers: HeaderMap,
|
||||
body: String,
|
||||
) -> anyhow::Result<()> {
|
||||
// Acquire and hold lock to make a task queue for
|
||||
// subsequent listener calls on same resource.
|
||||
// It would fail if we let it go through from action state busy.
|
||||
let lock = repo_locks().get_or_insert_default(&repo_id).await;
|
||||
let _lock = lock.lock().await;
|
||||
|
||||
verify_gh_signature(headers, &body).await?;
|
||||
let request_branch = extract_branch(&body)?;
|
||||
let repo = resource::get::<Repo>(&repo_id).await?;
|
||||
if !repo.config.webhook_enabled {
|
||||
return Err(anyhow!("repo does not have webhook enabled"));
|
||||
}
|
||||
if request_branch != repo.config.branch {
|
||||
return Err(anyhow!("request branch does not match expected"));
|
||||
}
|
||||
let user = github_user().to_owned();
|
||||
let req =
|
||||
crate::api::execute::ExecuteRequest::CloneRepo(CloneRepo {
|
||||
repo: repo_id,
|
||||
});
|
||||
let update = init_execution_update(&req, &user).await?;
|
||||
let crate::api::execute::ExecuteRequest::CloneRepo(req) = req
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
State.resolve(req, (user, update)).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn handle_repo_pull_webhook(
|
||||
repo_id: String,
|
||||
headers: HeaderMap,
|
||||
body: String,
|
||||
) -> anyhow::Result<()> {
|
||||
// Acquire and hold lock to make a task queue for
|
||||
// subsequent listener calls on same resource.
|
||||
// It would fail if we let it go through from action state busy.
|
||||
let lock = repo_locks().get_or_insert_default(&repo_id).await;
|
||||
let _lock = lock.lock().await;
|
||||
|
||||
verify_gh_signature(headers, &body).await?;
|
||||
let request_branch = extract_branch(&body)?;
|
||||
let repo = resource::get::<Repo>(&repo_id).await?;
|
||||
if !repo.config.webhook_enabled {
|
||||
return Err(anyhow!("repo does not have webhook enabled"));
|
||||
}
|
||||
if request_branch != repo.config.branch {
|
||||
return Err(anyhow!("request branch does not match expected"));
|
||||
}
|
||||
let user = github_user().to_owned();
|
||||
let req = crate::api::execute::ExecuteRequest::PullRepo(PullRepo {
|
||||
repo: repo_id,
|
||||
});
|
||||
let update = init_execution_update(&req, &user).await?;
|
||||
let crate::api::execute::ExecuteRequest::PullRepo(req) = req else {
|
||||
unreachable!()
|
||||
};
|
||||
State.resolve(req, (user, update)).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use axum::http::HeaderMap;
|
||||
use monitor_client::{
|
||||
api::{execute::RunSync, write::RefreshResourceSyncPending},
|
||||
entities::{sync::ResourceSync, user::github_user},
|
||||
};
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::{
|
||||
api::execute::ExecuteRequest,
|
||||
helpers::update::init_execution_update, resource, state::State,
|
||||
};
|
||||
|
||||
use super::{extract_branch, verify_gh_signature, ListenerLockCache};
|
||||
|
||||
fn sync_locks() -> &'static ListenerLockCache {
|
||||
static SYNC_LOCKS: OnceLock<ListenerLockCache> = OnceLock::new();
|
||||
SYNC_LOCKS.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
pub async fn handle_sync_refresh_webhook(
|
||||
sync_id: String,
|
||||
headers: HeaderMap,
|
||||
body: String,
|
||||
) -> anyhow::Result<()> {
|
||||
// Acquire and hold lock to make a task queue for
|
||||
// subsequent listener calls on same resource.
|
||||
// It would fail if we let it go through from action state busy.
|
||||
let lock = sync_locks().get_or_insert_default(&sync_id).await;
|
||||
let _lock = lock.lock().await;
|
||||
|
||||
verify_gh_signature(headers, &body).await?;
|
||||
let request_branch = extract_branch(&body)?;
|
||||
let sync = resource::get::<ResourceSync>(&sync_id).await?;
|
||||
if !sync.config.webhook_enabled {
|
||||
return Err(anyhow!("sync does not have webhook enabled"));
|
||||
}
|
||||
if request_branch != sync.config.branch {
|
||||
return Err(anyhow!("request branch does not match expected"));
|
||||
}
|
||||
let user = github_user().to_owned();
|
||||
State
|
||||
.resolve(RefreshResourceSyncPending { sync: sync_id }, user)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn handle_sync_execute_webhook(
|
||||
sync_id: String,
|
||||
headers: HeaderMap,
|
||||
body: String,
|
||||
) -> anyhow::Result<()> {
|
||||
// Acquire and hold lock to make a task queue for
|
||||
// subsequent listener calls on same resource.
|
||||
// It would fail if we let it go through from action state busy.
|
||||
let lock = sync_locks().get_or_insert_default(&sync_id).await;
|
||||
let _lock = lock.lock().await;
|
||||
|
||||
verify_gh_signature(headers, &body).await?;
|
||||
let request_branch = extract_branch(&body)?;
|
||||
let sync = resource::get::<ResourceSync>(&sync_id).await?;
|
||||
if !sync.config.webhook_enabled {
|
||||
return Err(anyhow!("sync does not have webhook enabled"));
|
||||
}
|
||||
if request_branch != sync.config.branch {
|
||||
return Err(anyhow!("request branch does not match expected"));
|
||||
}
|
||||
let user = github_user().to_owned();
|
||||
let req = ExecuteRequest::RunSync(RunSync { sync: sync_id });
|
||||
let update = init_execution_update(&req, &user).await?;
|
||||
let ExecuteRequest::RunSync(req) = req else {
|
||||
unreachable!()
|
||||
};
|
||||
State.resolve(req, (user, update)).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -74,7 +74,7 @@ pub async fn alert_deployments(
|
||||
return;
|
||||
}
|
||||
send_alerts(&alerts).await;
|
||||
let res = db_client().await.alerts.insert_many(alerts, None).await;
|
||||
let res = db_client().await.alerts.insert_many(alerts).await;
|
||||
if let Err(e) = res {
|
||||
error!("failed to record deployment status alerts to db | {e:#}");
|
||||
}
|
||||
|
||||
@@ -146,8 +146,8 @@ pub async fn alert_servers(
|
||||
SeverityLevel::Warning | SeverityLevel::Critical,
|
||||
Some(mut alert),
|
||||
) => {
|
||||
// modify alert level
|
||||
if alert.level != health.cpu {
|
||||
// modify alert level only if it has increased
|
||||
if alert.level < health.cpu {
|
||||
alert.level = health.cpu;
|
||||
alert.data = AlertData::ServerCpu {
|
||||
id: server_status.id.clone(),
|
||||
@@ -194,7 +194,7 @@ pub async fn alert_servers(
|
||||
ts,
|
||||
resolved: false,
|
||||
resolved_ts: None,
|
||||
level: health.cpu,
|
||||
level: health.mem,
|
||||
target: ResourceTarget::Server(server_status.id.clone()),
|
||||
data: AlertData::ServerMem {
|
||||
id: server_status.id.clone(),
|
||||
@@ -218,7 +218,8 @@ pub async fn alert_servers(
|
||||
SeverityLevel::Warning | SeverityLevel::Critical,
|
||||
Some(mut alert),
|
||||
) => {
|
||||
if alert.level != health.mem {
|
||||
// modify alert level only if it has increased
|
||||
if alert.level < health.mem {
|
||||
alert.level = health.mem;
|
||||
alert.data = AlertData::ServerMem {
|
||||
id: server_status.id.clone(),
|
||||
@@ -299,6 +300,7 @@ pub async fn alert_servers(
|
||||
SeverityLevel::Warning | SeverityLevel::Critical,
|
||||
Some(mut alert),
|
||||
) => {
|
||||
// Disk is persistent, update alert if health changes regardless of direction
|
||||
if *health != alert.level {
|
||||
let disk =
|
||||
server_status.stats.as_ref().and_then(|stats| {
|
||||
@@ -357,7 +359,7 @@ async fn open_alerts(alerts: &[(Alert, SendAlerts)]) {
|
||||
let open = || async {
|
||||
let ids = db
|
||||
.alerts
|
||||
.insert_many(alerts.iter().map(|(alert, _)| alert), None)
|
||||
.insert_many(alerts.iter().map(|(alert, _)| alert))
|
||||
.await?
|
||||
.inserted_ids
|
||||
.into_iter()
|
||||
@@ -468,7 +470,6 @@ async fn resolve_alerts(alerts: &[(Alert, SendAlerts)]) {
|
||||
"resolved_ts": monitor_timestamp()
|
||||
}
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to resolve alerts on db")
|
||||
|
||||
@@ -30,8 +30,7 @@ pub async fn record_server_stats(ts: i64) {
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if !records.is_empty() {
|
||||
let res =
|
||||
db_client().await.stats.insert_many(records, None).await;
|
||||
let res = db_client().await.stats.insert_many(records).await;
|
||||
if let Err(e) = res {
|
||||
error!("failed to record server stats | {e:#}");
|
||||
}
|
||||
|
||||
@@ -137,7 +137,6 @@ impl super::MonitorResource for Builder {
|
||||
mungos::update::Update::Set(
|
||||
doc! { "config.builder.params.builder_id": "" },
|
||||
),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to update_many builds on database")?;
|
||||
|
||||
@@ -33,7 +33,7 @@ use crate::{
|
||||
helpers::{
|
||||
create_permission, flatten_document,
|
||||
query::{
|
||||
get_resource_ids_for_non_admin, get_tag,
|
||||
get_resource_ids_for_user, get_tag,
|
||||
get_user_permission_on_resource, id_or_name_filter,
|
||||
},
|
||||
update::{add_update, make_update},
|
||||
@@ -187,7 +187,7 @@ pub async fn get<T: MonitorResource>(
|
||||
) -> anyhow::Result<Resource<T::Config, T::Info>> {
|
||||
T::coll()
|
||||
.await
|
||||
.find_one(id_or_name_filter(id_or_name), None)
|
||||
.find_one(id_or_name_filter(id_or_name))
|
||||
.await
|
||||
.context("failed to query db for resource")?
|
||||
.with_context(|| {
|
||||
@@ -211,7 +211,7 @@ pub async fn get_check_permissions<T: MonitorResource>(
|
||||
return Ok(resource);
|
||||
}
|
||||
let permissions = get_user_permission_on_resource(
|
||||
&user.id,
|
||||
user,
|
||||
T::resource_type(),
|
||||
&resource.id,
|
||||
)
|
||||
@@ -265,13 +265,9 @@ async fn list_full_for_user_using_document<T: MonitorResource>(
|
||||
mut filters: Document,
|
||||
user: &User,
|
||||
) -> anyhow::Result<Vec<Resource<T::Config, T::Info>>> {
|
||||
if !user.admin && !core_config().transparent_mode {
|
||||
let ids =
|
||||
get_resource_ids_for_non_admin(&user.id, T::resource_type())
|
||||
.await?
|
||||
.into_iter()
|
||||
.flat_map(|id| ObjectId::from_str(&id))
|
||||
.collect::<Vec<_>>();
|
||||
if let Some(ids) =
|
||||
get_resource_ids_for_user(user, T::resource_type()).await?
|
||||
{
|
||||
filters.insert("_id", doc! { "$in": ids });
|
||||
}
|
||||
find_collect(
|
||||
@@ -336,7 +332,7 @@ pub async fn create<T: MonitorResource>(
|
||||
|
||||
let resource_id = T::coll()
|
||||
.await
|
||||
.insert_one(&resource, None)
|
||||
.insert_one(&resource)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!("failed to add {} to db", T::resource_type())
|
||||
@@ -489,7 +485,6 @@ pub async fn update_description<T: MonitorResource>(
|
||||
.update_one(
|
||||
id_or_name_filter(id_or_name),
|
||||
doc! { "$set": { "description": description } },
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
@@ -524,7 +519,6 @@ pub async fn update_tags<T: MonitorResource>(
|
||||
.update_one(
|
||||
id_or_name_filter(id_or_name),
|
||||
doc! { "$set": { "tags": tags } },
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
@@ -535,7 +529,7 @@ pub async fn remove_tag_from_all<T: MonitorResource>(
|
||||
) -> anyhow::Result<()> {
|
||||
T::coll()
|
||||
.await
|
||||
.update_many(doc! {}, doc! { "$pull": { "tags": tag_id } }, None)
|
||||
.update_many(doc! {}, doc! { "$pull": { "tags": tag_id } })
|
||||
.await
|
||||
.context("failed to remove tag from resources")?;
|
||||
Ok(())
|
||||
@@ -614,13 +608,10 @@ where
|
||||
if let Err(e) = db_client()
|
||||
.await
|
||||
.permissions
|
||||
.delete_many(
|
||||
doc! {
|
||||
"resource_target.type": variant.as_ref(),
|
||||
"resource_target.id": &id
|
||||
},
|
||||
None,
|
||||
)
|
||||
.delete_many(doc! {
|
||||
"resource_target.type": variant.as_ref(),
|
||||
"resource_target.id": &id
|
||||
})
|
||||
.await
|
||||
{
|
||||
warn!("failed to delete_many permissions matching target {target:?} | {e:#}");
|
||||
@@ -652,7 +643,6 @@ where
|
||||
recent_field: id
|
||||
}
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to remove resource from users recently viewed")
|
||||
|
||||
@@ -337,12 +337,12 @@ async fn get_procedure_state_from_db(id: &str) -> ProcedureState {
|
||||
let state = db_client()
|
||||
.await
|
||||
.updates
|
||||
.find_one(
|
||||
doc! {
|
||||
"target.type": "Procedure",
|
||||
"target.id": id,
|
||||
"operation": "RunProcedure"
|
||||
},
|
||||
.find_one(doc! {
|
||||
"target.type": "Procedure",
|
||||
"target.id": id,
|
||||
"operation": "RunProcedure"
|
||||
})
|
||||
.with_options(
|
||||
FindOneOptions::builder()
|
||||
.sort(doc! { "start_ts": -1 })
|
||||
.build(),
|
||||
|
||||
@@ -244,15 +244,15 @@ async fn get_repo_state_from_db(id: &str) -> RepoState {
|
||||
let state = db_client()
|
||||
.await
|
||||
.updates
|
||||
.find_one(
|
||||
doc! {
|
||||
"target.type": "Repo",
|
||||
"target.id": id,
|
||||
"$or": [
|
||||
{ "operation": "CloneRepo" },
|
||||
{ "operation": "PullRepo" },
|
||||
],
|
||||
},
|
||||
.find_one(doc! {
|
||||
"target.type": "Repo",
|
||||
"target.id": id,
|
||||
"$or": [
|
||||
{ "operation": "CloneRepo" },
|
||||
{ "operation": "PullRepo" },
|
||||
],
|
||||
})
|
||||
.with_options(
|
||||
FindOneOptions::builder()
|
||||
.sort(doc! { "start_ts": -1 })
|
||||
.build(),
|
||||
|
||||
@@ -130,7 +130,6 @@ impl super::MonitorResource for Server {
|
||||
.update_many(
|
||||
doc! { "config.params.server_id": &id },
|
||||
doc! { "$set": { "config.params.server_id": "" } },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to detach server from builders")?;
|
||||
@@ -139,7 +138,6 @@ impl super::MonitorResource for Server {
|
||||
.update_many(
|
||||
doc! { "config.server_id": &id },
|
||||
doc! { "$set": { "config.server_id": "" } },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to detach server from deployments")?;
|
||||
@@ -148,7 +146,6 @@ impl super::MonitorResource for Server {
|
||||
.update_many(
|
||||
doc! { "config.server_id": &id },
|
||||
doc! { "$set": { "config.server_id": "" } },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to detach server from repos")?;
|
||||
@@ -160,7 +157,6 @@ impl super::MonitorResource for Server {
|
||||
"resolved": true,
|
||||
"resolved_ts": monitor_timestamp()
|
||||
} },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to detach server from repos")?;
|
||||
|
||||
@@ -213,12 +213,12 @@ async fn get_resource_sync_state_from_db(
|
||||
let state = db_client()
|
||||
.await
|
||||
.updates
|
||||
.find_one(
|
||||
doc! {
|
||||
"target.type": "ResourceSync",
|
||||
"target.id": id,
|
||||
"operation": "RunSync"
|
||||
},
|
||||
.find_one(doc! {
|
||||
"target.type": "ResourceSync",
|
||||
"target.id": id,
|
||||
"operation": "RunSync"
|
||||
})
|
||||
.with_options(
|
||||
FindOneOptions::builder()
|
||||
.sort(doc! { "start_ts": -1 })
|
||||
.build(),
|
||||
|
||||
+70
-3
@@ -1,10 +1,20 @@
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{Arc, OnceLock},
|
||||
};
|
||||
|
||||
use anyhow::{anyhow, Context};
|
||||
use monitor_client::entities::{
|
||||
build::BuildState, deployment::DeploymentState,
|
||||
procedure::ProcedureState, repo::RepoState,
|
||||
build::BuildState,
|
||||
config::core::{CoreConfig, GithubWebhookAppConfig},
|
||||
deployment::DeploymentState,
|
||||
procedure::ProcedureState,
|
||||
repo::RepoState,
|
||||
sync::ResourceSyncState,
|
||||
};
|
||||
use octorust::auth::{
|
||||
Credentials, InstallationTokenGenerator, JWTCredentials,
|
||||
};
|
||||
use tokio::sync::{Mutex, OnceCell};
|
||||
|
||||
use crate::{
|
||||
@@ -36,6 +46,63 @@ pub fn jwt_client() -> &'static JwtClient {
|
||||
JWT_CLIENT.get_or_init(|| JwtClient::new(core_config()))
|
||||
}
|
||||
|
||||
pub fn github_client(
|
||||
) -> Option<&'static HashMap<String, octorust::Client>> {
|
||||
static GITHUB_CLIENT: OnceLock<
|
||||
Option<HashMap<String, octorust::Client>>,
|
||||
> = OnceLock::new();
|
||||
GITHUB_CLIENT
|
||||
.get_or_init(|| {
|
||||
let CoreConfig {
|
||||
github_webhook_app:
|
||||
GithubWebhookAppConfig {
|
||||
app_id,
|
||||
installations,
|
||||
pk_path,
|
||||
..
|
||||
},
|
||||
..
|
||||
} = core_config();
|
||||
if *app_id == 0 || installations.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let private_key = std::fs::read(pk_path)
|
||||
.context("github webhook app | failed to load private key")
|
||||
.unwrap();
|
||||
|
||||
let private_key = nom_pem::decode_block(&private_key)
|
||||
.map_err(|e| anyhow!("{e:?}"))
|
||||
.context("github webhook app | failed to decode private key")
|
||||
.unwrap();
|
||||
|
||||
let jwt = JWTCredentials::new(*app_id, private_key.data)
|
||||
.context(
|
||||
"github webhook app | failed to make github JWTCredentials",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut clients =
|
||||
HashMap::with_capacity(installations.capacity());
|
||||
|
||||
for installation in installations {
|
||||
let token_generator = InstallationTokenGenerator::new(
|
||||
installation.id,
|
||||
jwt.clone(),
|
||||
);
|
||||
let client = octorust::Client::new(
|
||||
"github-app",
|
||||
Credentials::InstallationToken(token_generator),
|
||||
)
|
||||
.context("failed to initialize github client")
|
||||
.unwrap();
|
||||
clients.insert(installation.namespace.to_string(), client);
|
||||
}
|
||||
|
||||
Some(clients)
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
pub fn action_states() -> &'static ActionStates {
|
||||
static ACTION_STATES: OnceLock<ActionStates> = OnceLock::new();
|
||||
ACTION_STATES.get_or_init(ActionStates::default)
|
||||
|
||||
+1
-1
@@ -208,7 +208,7 @@ async fn user_can_see_update(
|
||||
}
|
||||
let (variant, id) = update_target.extract_variant_id();
|
||||
let permissions =
|
||||
get_user_permission_on_resource(&user.id, variant, id).await?;
|
||||
get_user_permission_on_resource(user, variant, id).await?;
|
||||
if permissions > PermissionLevel::None {
|
||||
Ok(())
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# Build Core
|
||||
FROM rust:1.79.0-bookworm as builder
|
||||
WORKDIR /builder
|
||||
COPY . .
|
||||
RUN cargo build -p migrator --release
|
||||
|
||||
# Final Image
|
||||
FROM gcr.io/distroless/cc-debian12
|
||||
|
||||
COPY --from=builder /builder/target/release/migrator /
|
||||
|
||||
CMD ["./migrator"]
|
||||
@@ -198,11 +198,6 @@ impl TryFrom<Build> for monitor_client::entities::build::Build {
|
||||
id: value.id,
|
||||
name: value.name,
|
||||
description: value.description,
|
||||
// permissions: value
|
||||
// .permissions
|
||||
// .into_iter()
|
||||
// .map(|(id, p)| (id, p.into()))
|
||||
// .collect(),
|
||||
updated_at: unix_from_monitor_ts(&value.updated_at)?,
|
||||
tags: Vec::new(),
|
||||
info: BuildInfo {
|
||||
@@ -233,6 +228,7 @@ impl TryFrom<Build> for monitor_client::entities::build::Build {
|
||||
build_path,
|
||||
dockerfile_path,
|
||||
build_args,
|
||||
secret_args: Default::default(),
|
||||
extra_args,
|
||||
use_buildx,
|
||||
labels: Default::default(),
|
||||
|
||||
@@ -106,11 +106,8 @@ impl TryFrom<User> for monitor_client::entities::user::User {
|
||||
create_server_permissions: value.create_server_permissions,
|
||||
create_build_permissions: value.create_build_permissions,
|
||||
last_update_view: Default::default(),
|
||||
recent_servers: Vec::new(),
|
||||
recent_deployments: Vec::new(),
|
||||
recent_builds: Vec::new(),
|
||||
recent_repos: Vec::new(),
|
||||
recent_procedures: Vec::new(),
|
||||
recents: Default::default(),
|
||||
all: Default::default(),
|
||||
updated_at: unix_from_monitor_ts(&value.updated_at)?,
|
||||
};
|
||||
Ok(user)
|
||||
|
||||
@@ -134,6 +134,7 @@ impl From<BuildConfig>
|
||||
.into_iter()
|
||||
.map(Into::into)
|
||||
.collect(),
|
||||
secret_args: Default::default(),
|
||||
labels: value.labels.into_iter().map(Into::into).collect(),
|
||||
extra_args: value.extra_args,
|
||||
use_buildx: value.use_buildx,
|
||||
|
||||
@@ -7,7 +7,9 @@ use monitor_client::entities::{
|
||||
update::{ResourceTarget, Update},
|
||||
user::User,
|
||||
};
|
||||
use mungos::find::find_collect;
|
||||
use mungos::{
|
||||
find::find_collect, mongodb::options::InsertManyOptions,
|
||||
};
|
||||
|
||||
use crate::legacy::v0;
|
||||
|
||||
@@ -28,13 +30,21 @@ pub async fn migrate_users(
|
||||
legacy_db: &v0::DbClient,
|
||||
target_db: &crate::DbClient,
|
||||
) -> anyhow::Result<()> {
|
||||
let existing = find_collect(&target_db.users, None, None)
|
||||
.await
|
||||
.context("failed to get existing target users")?;
|
||||
|
||||
let users = find_collect(&legacy_db.users, None, None)
|
||||
.await
|
||||
.context("failed to get legacy users")?
|
||||
.into_iter()
|
||||
.filter_map(|s| {
|
||||
let username = s.username.clone();
|
||||
s.try_into()
|
||||
.filter_map(|user| {
|
||||
if existing.iter().any(|u| u.username == user.username) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let username = user.username.clone();
|
||||
user.try_into()
|
||||
.inspect_err(|e| {
|
||||
warn!("failed to convert user {username} | {e:#}")
|
||||
})
|
||||
@@ -46,7 +56,7 @@ pub async fn migrate_users(
|
||||
|
||||
target_db
|
||||
.users
|
||||
.insert_many(users, None)
|
||||
.insert_many(users)
|
||||
.await
|
||||
.context("failed to insert users on target")?;
|
||||
|
||||
@@ -59,6 +69,10 @@ pub async fn migrate_servers(
|
||||
legacy_db: &v0::DbClient,
|
||||
target_db: &crate::DbClient,
|
||||
) -> anyhow::Result<()> {
|
||||
let existing = find_collect(&target_db.servers, None, None)
|
||||
.await
|
||||
.context("failed to get existing target servers")?;
|
||||
|
||||
let servers = find_collect(&legacy_db.servers, None, None)
|
||||
.await
|
||||
.context("failed to get legacy servers")?;
|
||||
@@ -67,6 +81,10 @@ pub async fn migrate_servers(
|
||||
let mut permissions = Vec::<Permission>::new();
|
||||
|
||||
for server in servers {
|
||||
if existing.iter().any(|s| s.name == server.name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (user_id, level) in &server.permissions {
|
||||
let permission = Permission {
|
||||
id: Default::default(),
|
||||
@@ -91,7 +109,10 @@ pub async fn migrate_servers(
|
||||
if !new_servers.is_empty() {
|
||||
target_db
|
||||
.servers
|
||||
.insert_many(new_servers, None)
|
||||
.insert_many(new_servers)
|
||||
.with_options(
|
||||
InsertManyOptions::builder().ordered(false).build(),
|
||||
)
|
||||
.await
|
||||
.context("failed to insert servers on target")?;
|
||||
}
|
||||
@@ -99,7 +120,10 @@ pub async fn migrate_servers(
|
||||
if !permissions.is_empty() {
|
||||
target_db
|
||||
.permissions
|
||||
.insert_many(permissions, None)
|
||||
.insert_many(permissions)
|
||||
.with_options(
|
||||
InsertManyOptions::builder().ordered(false).build(),
|
||||
)
|
||||
.await
|
||||
.context("failed to insert server permissions on target")?;
|
||||
}
|
||||
@@ -113,6 +137,10 @@ pub async fn migrate_deployments(
|
||||
legacy_db: &v0::DbClient,
|
||||
target_db: &crate::DbClient,
|
||||
) -> anyhow::Result<()> {
|
||||
let existing = find_collect(&target_db.deployments, None, None)
|
||||
.await
|
||||
.context("failed to get existing target deployments")?;
|
||||
|
||||
let deployments = find_collect(&legacy_db.deployments, None, None)
|
||||
.await
|
||||
.context("failed to get legacy deployments")?;
|
||||
@@ -121,6 +149,10 @@ pub async fn migrate_deployments(
|
||||
let mut permissions = Vec::<Permission>::new();
|
||||
|
||||
for deployment in deployments {
|
||||
if existing.iter().any(|d| d.name == deployment.name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (user_id, level) in &deployment.permissions {
|
||||
let permission = Permission {
|
||||
id: Default::default(),
|
||||
@@ -147,7 +179,10 @@ pub async fn migrate_deployments(
|
||||
if !new_deployments.is_empty() {
|
||||
target_db
|
||||
.deployments
|
||||
.insert_many(new_deployments, None)
|
||||
.insert_many(new_deployments)
|
||||
.with_options(
|
||||
InsertManyOptions::builder().ordered(false).build(),
|
||||
)
|
||||
.await
|
||||
.context("failed to insert deployments on target")?;
|
||||
}
|
||||
@@ -155,7 +190,10 @@ pub async fn migrate_deployments(
|
||||
if !permissions.is_empty() {
|
||||
target_db
|
||||
.permissions
|
||||
.insert_many(permissions, None)
|
||||
.insert_many(permissions)
|
||||
.with_options(
|
||||
InsertManyOptions::builder().ordered(false).build(),
|
||||
)
|
||||
.await
|
||||
.context("failed to insert deployment permissions on target")?;
|
||||
}
|
||||
@@ -169,6 +207,10 @@ pub async fn migrate_builds(
|
||||
legacy_db: &v0::DbClient,
|
||||
target_db: &crate::DbClient,
|
||||
) -> anyhow::Result<()> {
|
||||
let existing = find_collect(&target_db.builds, None, None)
|
||||
.await
|
||||
.context("failed to get existing target builds")?;
|
||||
|
||||
let builds = find_collect(&legacy_db.builds, None, None)
|
||||
.await
|
||||
.context("failed to get legacy builds")?;
|
||||
@@ -177,6 +219,10 @@ pub async fn migrate_builds(
|
||||
let mut permissions = Vec::<Permission>::new();
|
||||
|
||||
for build in builds {
|
||||
if existing.iter().any(|b| b.name == build.name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (user_id, level) in &build.permissions {
|
||||
let permission = Permission {
|
||||
id: Default::default(),
|
||||
@@ -201,17 +247,29 @@ pub async fn migrate_builds(
|
||||
if !new_builds.is_empty() {
|
||||
target_db
|
||||
.builds
|
||||
.insert_many(new_builds, None)
|
||||
.insert_many(new_builds)
|
||||
.with_options(
|
||||
InsertManyOptions::builder().ordered(false).build(),
|
||||
)
|
||||
.await
|
||||
.context("failed to insert builds on target")?;
|
||||
.inspect_err(|e| {
|
||||
warn!("failed to insert builds on target | {e}")
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
|
||||
if !permissions.is_empty() {
|
||||
target_db
|
||||
.permissions
|
||||
.insert_many(permissions, None)
|
||||
.insert_many(permissions)
|
||||
.with_options(
|
||||
InsertManyOptions::builder().ordered(false).build(),
|
||||
)
|
||||
.await
|
||||
.context("failed to insert build permissions on target")?;
|
||||
.inspect_err(|e| {
|
||||
warn!("failed to insert build permissions on target | {e}")
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
|
||||
info!("builds have been migrated\n");
|
||||
@@ -239,7 +297,8 @@ pub async fn migrate_updates(
|
||||
|
||||
target_db
|
||||
.updates
|
||||
.insert_many(updates, None)
|
||||
.insert_many(updates)
|
||||
.with_options(InsertManyOptions::builder().ordered(false).build())
|
||||
.await
|
||||
.context("failed to insert updates on target")?;
|
||||
|
||||
|
||||
@@ -34,7 +34,6 @@ pub async fn migrate_deployments_in_place(
|
||||
.update_one(
|
||||
doc! { "name": &deployment.name },
|
||||
doc! { "$set": to_document(&deployment)? },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to insert deployments on target")?;
|
||||
@@ -62,7 +61,6 @@ pub async fn migrate_builds_in_place(
|
||||
.update_one(
|
||||
doc! { "name": &build.name },
|
||||
doc! { "$set": to_document(&build)? },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.context("failed to insert builds on target")?;
|
||||
|
||||
+179
-19
@@ -1,41 +1,200 @@
|
||||
use anyhow::{anyhow, Context};
|
||||
use command::run_monitor_command;
|
||||
use formatting::format_serror;
|
||||
use monitor_client::entities::{
|
||||
server::docker_image::ImageSummary, update::Log,
|
||||
};
|
||||
use periphery_client::api::build::{
|
||||
Build, GetImageList, PruneImages,
|
||||
build::{Build, BuildConfig},
|
||||
get_image_name, optional_string,
|
||||
server::docker_image::ImageSummary,
|
||||
to_monitor_name,
|
||||
update::Log,
|
||||
EnvironmentVar, Version,
|
||||
};
|
||||
use periphery_client::api::build::{self, GetImageList, PruneImages};
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::{
|
||||
docker::{self, client::docker_client},
|
||||
config::periphery_config,
|
||||
docker::docker_client,
|
||||
helpers::{docker_login, parse_extra_args, parse_labels},
|
||||
State,
|
||||
};
|
||||
|
||||
impl Resolve<Build> for State {
|
||||
#[instrument(
|
||||
name = "Build",
|
||||
skip(self, registry_token, replacers, aws_ecr)
|
||||
)]
|
||||
impl Resolve<build::Build> for State {
|
||||
#[instrument(name = "Build", skip_all)]
|
||||
async fn resolve(
|
||||
&self,
|
||||
Build {
|
||||
build::Build {
|
||||
build,
|
||||
registry_token,
|
||||
replacers,
|
||||
aws_ecr,
|
||||
}: Build,
|
||||
registry_token,
|
||||
replacers: core_replacers,
|
||||
}: build::Build,
|
||||
_: (),
|
||||
) -> anyhow::Result<Vec<Log>> {
|
||||
docker::build::build(
|
||||
&build,
|
||||
registry_token,
|
||||
replacers,
|
||||
let Build {
|
||||
name,
|
||||
config:
|
||||
BuildConfig {
|
||||
version,
|
||||
skip_secret_interp,
|
||||
build_path,
|
||||
dockerfile_path,
|
||||
build_args,
|
||||
secret_args,
|
||||
labels,
|
||||
extra_args,
|
||||
use_buildx,
|
||||
image_registry,
|
||||
..
|
||||
},
|
||||
..
|
||||
} = &build;
|
||||
|
||||
let mut logs = Vec::new();
|
||||
|
||||
// Maybe docker login
|
||||
let should_push = match docker_login(
|
||||
image_registry,
|
||||
registry_token.as_deref(),
|
||||
aws_ecr.as_ref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(should_push) => should_push,
|
||||
Err(e) => {
|
||||
logs.push(Log::error(
|
||||
"docker login",
|
||||
format_serror(
|
||||
&e.context("failed to login to docker registry").into(),
|
||||
),
|
||||
));
|
||||
return Ok(logs);
|
||||
}
|
||||
};
|
||||
|
||||
let name = to_monitor_name(name);
|
||||
|
||||
// Get paths
|
||||
let build_dir =
|
||||
periphery_config().repo_dir.join(&name).join(build_path);
|
||||
let dockerfile_path = match optional_string(dockerfile_path) {
|
||||
Some(dockerfile_path) => dockerfile_path.to_owned(),
|
||||
None => "Dockerfile".to_owned(),
|
||||
};
|
||||
|
||||
// Get command parts
|
||||
let image_name = get_image_name(&build, |_| aws_ecr)
|
||||
.context("failed to make image name")?;
|
||||
let build_args = parse_build_args(build_args);
|
||||
let _secret_args =
|
||||
parse_secret_args(secret_args, *skip_secret_interp)?;
|
||||
let labels = parse_labels(labels);
|
||||
let extra_args = parse_extra_args(extra_args);
|
||||
let buildx = if *use_buildx { " buildx" } else { "" };
|
||||
let image_tags = image_tags(&image_name, version);
|
||||
let push_command = should_push
|
||||
.then(|| {
|
||||
format!(" && docker image push --all-tags {image_name}")
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
// Construct command
|
||||
let command = format!(
|
||||
"cd {} && docker{buildx} build{build_args}{_secret_args}{extra_args}{labels}{image_tags} -f {dockerfile_path} .{push_command}",
|
||||
build_dir.display()
|
||||
);
|
||||
|
||||
if *skip_secret_interp {
|
||||
let build_log =
|
||||
run_monitor_command("docker build", command).await;
|
||||
info!("finished building docker image");
|
||||
logs.push(build_log);
|
||||
} else {
|
||||
// Interpolate any missing secrets
|
||||
let (command, mut replacers) = svi::interpolate_variables(
|
||||
&command,
|
||||
&periphery_config().secrets,
|
||||
svi::Interpolator::DoubleBrackets,
|
||||
true,
|
||||
)
|
||||
.context(
|
||||
"failed to interpolate secrets into docker build command",
|
||||
)?;
|
||||
replacers.extend(core_replacers);
|
||||
|
||||
let mut build_log =
|
||||
run_monitor_command("docker build", command).await;
|
||||
build_log.command =
|
||||
svi::replace_in_string(&build_log.command, &replacers);
|
||||
build_log.stdout =
|
||||
svi::replace_in_string(&build_log.stdout, &replacers);
|
||||
build_log.stderr =
|
||||
svi::replace_in_string(&build_log.stderr, &replacers);
|
||||
logs.push(build_log);
|
||||
}
|
||||
|
||||
cleanup_secret_env_vars(secret_args);
|
||||
|
||||
Ok(logs)
|
||||
}
|
||||
}
|
||||
|
||||
fn image_tags(image_name: &str, version: &Version) -> String {
|
||||
let Version { major, minor, .. } = version;
|
||||
format!(
|
||||
" -t {image_name}:latest -t {image_name}:{version} -t {image_name}:{major}.{minor} -t {image_name}:{major}",
|
||||
)
|
||||
}
|
||||
|
||||
fn parse_build_args(build_args: &[EnvironmentVar]) -> String {
|
||||
build_args
|
||||
.iter()
|
||||
.map(|p| format!(" --build-arg {}=\"{}\"", p.variable, p.value))
|
||||
.collect::<Vec<_>>()
|
||||
.join("")
|
||||
}
|
||||
|
||||
fn parse_secret_args(
|
||||
secret_args: &[EnvironmentVar],
|
||||
skip_secret_interp: bool,
|
||||
) -> anyhow::Result<String> {
|
||||
let periphery_config = periphery_config();
|
||||
Ok(
|
||||
secret_args
|
||||
.iter()
|
||||
.map(|EnvironmentVar { variable, value }| {
|
||||
if variable.is_empty() {
|
||||
return Err(anyhow!("secret variable cannot be empty string"))
|
||||
} else if variable.contains('=') {
|
||||
return Err(anyhow!("invalid variable {variable}. variable cannot contain '='"))
|
||||
}
|
||||
let value = if skip_secret_interp {
|
||||
value.to_string()
|
||||
} else {
|
||||
svi::interpolate_variables(
|
||||
value,
|
||||
&periphery_config.secrets,
|
||||
svi::Interpolator::DoubleBrackets,
|
||||
true,
|
||||
)
|
||||
.context(
|
||||
"failed to interpolate periphery secrets into build secrets",
|
||||
)?.0
|
||||
};
|
||||
std::env::set_var(variable, value);
|
||||
anyhow::Ok(format!(" --secret id={variable}"))
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<_>>>()?
|
||||
.join(""),
|
||||
)
|
||||
}
|
||||
|
||||
fn cleanup_secret_env_vars(secret_args: &[EnvironmentVar]) {
|
||||
secret_args.iter().for_each(
|
||||
|EnvironmentVar { variable, .. }| std::env::remove_var(variable),
|
||||
)
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
impl Resolve<GetImageList> for State {
|
||||
@@ -58,6 +217,7 @@ impl Resolve<PruneImages> for State {
|
||||
_: PruneImages,
|
||||
_: (),
|
||||
) -> anyhow::Result<Log> {
|
||||
Ok(docker::build::prune_images().await)
|
||||
let command = String::from("docker image prune -a -f");
|
||||
Ok(run_monitor_command("prune images", command).await)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,24 @@
|
||||
use anyhow::anyhow;
|
||||
use anyhow::{anyhow, Context};
|
||||
use command::run_monitor_command;
|
||||
use formatting::format_serror;
|
||||
use monitor_client::entities::{
|
||||
deployment::{ContainerSummary, DockerContainerStats},
|
||||
deployment::{
|
||||
ContainerSummary, Conversion, Deployment, DeploymentConfig,
|
||||
DeploymentImage, DockerContainerStats, RestartMode,
|
||||
TerminationSignal,
|
||||
},
|
||||
to_monitor_name,
|
||||
update::Log,
|
||||
EnvironmentVar, SearchCombinator,
|
||||
};
|
||||
use periphery_client::api::container::*;
|
||||
use resolver_api::Resolve;
|
||||
use run_command::async_run_command;
|
||||
|
||||
use crate::{
|
||||
docker::{self, client::docker_client},
|
||||
config::periphery_config,
|
||||
docker::docker_client,
|
||||
helpers::{docker_login, parse_extra_args, parse_labels},
|
||||
State,
|
||||
};
|
||||
|
||||
@@ -34,10 +45,11 @@ impl Resolve<GetContainerLog> for State {
|
||||
#[instrument(name = "GetContainerLog", level = "debug", skip(self))]
|
||||
async fn resolve(
|
||||
&self,
|
||||
req: GetContainerLog,
|
||||
GetContainerLog { name, tail }: GetContainerLog,
|
||||
_: (),
|
||||
) -> anyhow::Result<Log> {
|
||||
Ok(docker::container::container_log(&req.name, req.tail).await)
|
||||
let command = format!("docker logs {name} --tail {tail}");
|
||||
Ok(run_monitor_command("get container log", command).await)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,12 +71,21 @@ impl Resolve<GetContainerLogSearch> for State {
|
||||
}: GetContainerLogSearch,
|
||||
_: (),
|
||||
) -> anyhow::Result<Log> {
|
||||
Ok(
|
||||
docker::container::container_log_search(
|
||||
&name, &terms, combinator, invert,
|
||||
)
|
||||
.await,
|
||||
)
|
||||
let maybe_invert = invert.then_some(" -v").unwrap_or_default();
|
||||
let grep = match combinator {
|
||||
SearchCombinator::Or => {
|
||||
format!("grep{maybe_invert} -E '{}'", terms.join("|"))
|
||||
}
|
||||
SearchCombinator::And => {
|
||||
format!(
|
||||
"grep{maybe_invert} -P '^(?=.*{})'",
|
||||
terms.join(")(?=.*")
|
||||
)
|
||||
}
|
||||
};
|
||||
let command =
|
||||
format!("docker logs {name} --tail 5000 2>&1 | {grep}");
|
||||
Ok(run_monitor_command("get container log grep", command).await)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,8 +103,7 @@ impl Resolve<GetContainerStats> for State {
|
||||
_: (),
|
||||
) -> anyhow::Result<DockerContainerStats> {
|
||||
let error = anyhow!("no stats matching {}", req.name);
|
||||
let mut stats =
|
||||
docker::container::container_stats(Some(req.name)).await?;
|
||||
let mut stats = container_stats(Some(req.name)).await?;
|
||||
let stats = stats.pop().ok_or(error)?;
|
||||
Ok(stats)
|
||||
}
|
||||
@@ -102,7 +122,7 @@ impl Resolve<GetContainerStatsList> for State {
|
||||
_: GetContainerStatsList,
|
||||
_: (),
|
||||
) -> anyhow::Result<Vec<DockerContainerStats>> {
|
||||
docker::container::container_stats(None).await
|
||||
container_stats(None).await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,10 +132,16 @@ impl Resolve<StartContainer> for State {
|
||||
#[instrument(name = "StartContainer", skip(self))]
|
||||
async fn resolve(
|
||||
&self,
|
||||
req: StartContainer,
|
||||
StartContainer { name }: StartContainer,
|
||||
_: (),
|
||||
) -> anyhow::Result<Log> {
|
||||
Ok(docker::container::start_container(&req.name).await)
|
||||
Ok(
|
||||
run_monitor_command(
|
||||
"docker start",
|
||||
format!("docker start {name}"),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,15 +151,26 @@ impl Resolve<StopContainer> for State {
|
||||
#[instrument(name = "StopContainer", skip(self))]
|
||||
async fn resolve(
|
||||
&self,
|
||||
req: StopContainer,
|
||||
StopContainer { name, signal, time }: StopContainer,
|
||||
_: (),
|
||||
) -> anyhow::Result<Log> {
|
||||
Ok(
|
||||
docker::container::stop_container(
|
||||
&req.name, req.signal, req.time,
|
||||
)
|
||||
.await,
|
||||
)
|
||||
let command = stop_container_command(&name, signal, time);
|
||||
let log = run_monitor_command("docker stop", command).await;
|
||||
if log.stderr.contains("unknown flag: --signal") {
|
||||
let command = stop_container_command(&name, None, time);
|
||||
let mut log = run_monitor_command("docker stop", command).await;
|
||||
log.stderr = format!(
|
||||
"old docker version: unable to use --signal flag{}",
|
||||
if !log.stderr.is_empty() {
|
||||
format!("\n\n{}", log.stderr)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
);
|
||||
Ok(log)
|
||||
} else {
|
||||
Ok(log)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,15 +180,31 @@ impl Resolve<RemoveContainer> for State {
|
||||
#[instrument(name = "RemoveContainer", skip(self))]
|
||||
async fn resolve(
|
||||
&self,
|
||||
req: RemoveContainer,
|
||||
RemoveContainer { name, signal, time }: RemoveContainer,
|
||||
_: (),
|
||||
) -> anyhow::Result<Log> {
|
||||
Ok(
|
||||
docker::container::stop_and_remove_container(
|
||||
&req.name, req.signal, req.time,
|
||||
)
|
||||
.await,
|
||||
)
|
||||
let stop_command = stop_container_command(&name, signal, time);
|
||||
let command =
|
||||
format!("{stop_command} && docker container rm {name}");
|
||||
let log =
|
||||
run_monitor_command("docker stop and remove", command).await;
|
||||
if log.stderr.contains("unknown flag: --signal") {
|
||||
let stop_command = stop_container_command(&name, None, time);
|
||||
let command =
|
||||
format!("{stop_command} && docker container rm {name}");
|
||||
let mut log = run_monitor_command("docker stop", command).await;
|
||||
log.stderr = format!(
|
||||
"old docker version: unable to use --signal flag{}",
|
||||
if !log.stderr.is_empty() {
|
||||
format!("\n\n{}", log.stderr)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
);
|
||||
Ok(log)
|
||||
} else {
|
||||
Ok(log)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,16 +214,15 @@ impl Resolve<RenameContainer> for State {
|
||||
#[instrument(name = "RenameContainer", skip(self))]
|
||||
async fn resolve(
|
||||
&self,
|
||||
req: RenameContainer,
|
||||
RenameContainer {
|
||||
curr_name,
|
||||
new_name,
|
||||
}: RenameContainer,
|
||||
_: (),
|
||||
) -> anyhow::Result<Log> {
|
||||
Ok(
|
||||
docker::container::rename_container(
|
||||
&req.curr_name,
|
||||
&req.new_name,
|
||||
)
|
||||
.await,
|
||||
)
|
||||
let new = to_monitor_name(&new_name);
|
||||
let command = format!("docker rename {curr_name} {new}");
|
||||
Ok(run_monitor_command("docker rename", command).await)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,14 +235,18 @@ impl Resolve<PruneContainers> for State {
|
||||
_: PruneContainers,
|
||||
_: (),
|
||||
) -> anyhow::Result<Log> {
|
||||
Ok(docker::container::prune_containers().await)
|
||||
let command = String::from("docker container prune -f");
|
||||
Ok(run_monitor_command("prune containers", command).await)
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
impl Resolve<Deploy> for State {
|
||||
#[instrument(name = "Deploy", skip(self, replacers))]
|
||||
#[instrument(
|
||||
name = "Deploy",
|
||||
skip(self, core_replacers, aws_ecr, registry_token)
|
||||
)]
|
||||
async fn resolve(
|
||||
&self,
|
||||
Deploy {
|
||||
@@ -198,24 +254,206 @@ impl Resolve<Deploy> for State {
|
||||
stop_signal,
|
||||
stop_time,
|
||||
registry_token,
|
||||
replacers,
|
||||
replacers: core_replacers,
|
||||
aws_ecr,
|
||||
}: Deploy,
|
||||
_: (),
|
||||
) -> anyhow::Result<Log> {
|
||||
let res = docker::container::deploy(
|
||||
&deployment,
|
||||
stop_signal
|
||||
.unwrap_or(deployment.config.termination_signal)
|
||||
.into(),
|
||||
stop_time
|
||||
.unwrap_or(deployment.config.termination_timeout)
|
||||
.into(),
|
||||
registry_token,
|
||||
replacers,
|
||||
if let Err(e) = docker_login(
|
||||
&deployment.config.image_registry,
|
||||
registry_token.as_deref(),
|
||||
aws_ecr.as_ref(),
|
||||
)
|
||||
.await;
|
||||
Ok(res)
|
||||
.await
|
||||
{
|
||||
return Ok(Log::error(
|
||||
"docker login",
|
||||
format_serror(
|
||||
&e.context("failed to login to docker registry").into(),
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let image = if let DeploymentImage::Image { image } =
|
||||
&deployment.config.image
|
||||
{
|
||||
if image.is_empty() {
|
||||
return Ok(Log::error(
|
||||
"get image",
|
||||
String::from("deployment does not have image attached"),
|
||||
));
|
||||
}
|
||||
image
|
||||
} else {
|
||||
return Ok(Log::error(
|
||||
"get image",
|
||||
String::from("deployment does not have image attached"),
|
||||
));
|
||||
};
|
||||
|
||||
let _ = pull_image(image).await;
|
||||
debug!("image pulled");
|
||||
let _ = State
|
||||
.resolve(
|
||||
RemoveContainer {
|
||||
name: deployment.name.clone(),
|
||||
signal: stop_signal,
|
||||
time: stop_time,
|
||||
},
|
||||
(),
|
||||
)
|
||||
.await;
|
||||
debug!("container stopped and removed");
|
||||
|
||||
let command = docker_run_command(&deployment, image);
|
||||
debug!("docker run command: {command}");
|
||||
|
||||
if deployment.config.skip_secret_interp {
|
||||
Ok(run_monitor_command("docker run", command).await)
|
||||
} else {
|
||||
let command = svi::interpolate_variables(
|
||||
&command,
|
||||
&periphery_config().secrets,
|
||||
svi::Interpolator::DoubleBrackets,
|
||||
true,
|
||||
)
|
||||
.context(
|
||||
"failed to interpolate secrets into docker run command",
|
||||
);
|
||||
if let Err(e) = command {
|
||||
return Ok(Log::error("docker run", format!("{e:?}")));
|
||||
}
|
||||
let (command, mut replacers) = command.unwrap();
|
||||
replacers.extend(core_replacers);
|
||||
let mut log = run_monitor_command("docker run", command).await;
|
||||
log.command = svi::replace_in_string(&log.command, &replacers);
|
||||
log.stdout = svi::replace_in_string(&log.stdout, &replacers);
|
||||
log.stderr = svi::replace_in_string(&log.stderr, &replacers);
|
||||
Ok(log)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
fn docker_run_command(
|
||||
Deployment {
|
||||
name,
|
||||
config:
|
||||
DeploymentConfig {
|
||||
volumes,
|
||||
ports,
|
||||
network,
|
||||
command,
|
||||
restart,
|
||||
environment,
|
||||
labels,
|
||||
extra_args,
|
||||
..
|
||||
},
|
||||
..
|
||||
}: &Deployment,
|
||||
image: &str,
|
||||
) -> String {
|
||||
let name = to_monitor_name(name);
|
||||
let ports = parse_conversions(ports, "-p");
|
||||
let volumes = volumes.to_owned();
|
||||
let volumes = parse_conversions(&volumes, "-v");
|
||||
let network = parse_network(network);
|
||||
let restart = parse_restart(restart);
|
||||
let environment = parse_environment(environment);
|
||||
let labels = parse_labels(labels);
|
||||
let command = parse_command(command);
|
||||
let extra_args = parse_extra_args(extra_args);
|
||||
format!("docker run -d --name {name}{ports}{volumes}{network}{restart}{environment}{labels}{extra_args} {image}{command}")
|
||||
}
|
||||
|
||||
fn parse_conversions(
|
||||
conversions: &[Conversion],
|
||||
flag: &str,
|
||||
) -> String {
|
||||
conversions
|
||||
.iter()
|
||||
.map(|p| format!(" {flag} {}:{}", p.local, p.container))
|
||||
.collect::<Vec<_>>()
|
||||
.join("")
|
||||
}
|
||||
|
||||
fn parse_environment(environment: &[EnvironmentVar]) -> String {
|
||||
environment
|
||||
.iter()
|
||||
.map(|p| format!(" --env {}=\"{}\"", p.variable, p.value))
|
||||
.collect::<Vec<_>>()
|
||||
.join("")
|
||||
}
|
||||
|
||||
fn parse_network(network: &str) -> String {
|
||||
format!(" --network {network}")
|
||||
}
|
||||
|
||||
fn parse_restart(restart: &RestartMode) -> String {
|
||||
let restart = match restart {
|
||||
RestartMode::OnFailure => "on-failure:10".to_string(),
|
||||
_ => restart.to_string(),
|
||||
};
|
||||
format!(" --restart {restart}")
|
||||
}
|
||||
|
||||
fn parse_command(command: &str) -> String {
|
||||
if command.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" {command}")
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
async fn container_stats(
|
||||
container_name: Option<String>,
|
||||
) -> anyhow::Result<Vec<DockerContainerStats>> {
|
||||
let format = "--format \"{{ json . }}\"";
|
||||
let container_name = match container_name {
|
||||
Some(name) => format!(" {name}"),
|
||||
None => "".to_string(),
|
||||
};
|
||||
let command =
|
||||
format!("docker stats{container_name} --no-stream {format}");
|
||||
let output = async_run_command(&command).await;
|
||||
if output.success() {
|
||||
let res = output
|
||||
.stdout
|
||||
.split('\n')
|
||||
.filter(|e| !e.is_empty())
|
||||
.map(|e| {
|
||||
let parsed = serde_json::from_str(e)
|
||||
.context(format!("failed at parsing entry {e}"))?;
|
||||
Ok(parsed)
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<DockerContainerStats>>>()?;
|
||||
Ok(res)
|
||||
} else {
|
||||
Err(anyhow!("{}", output.stderr.replace('\n', "")))
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
async fn pull_image(image: &str) -> Log {
|
||||
let command = format!("docker pull {image}");
|
||||
run_monitor_command("docker pull", command).await
|
||||
}
|
||||
|
||||
fn stop_container_command(
|
||||
container_name: &str,
|
||||
signal: Option<TerminationSignal>,
|
||||
time: Option<i32>,
|
||||
) -> String {
|
||||
let container_name = to_monitor_name(container_name);
|
||||
let signal = signal
|
||||
.map(|signal| format!(" --signal {signal}"))
|
||||
.unwrap_or_default();
|
||||
let time = time
|
||||
.map(|time| format!(" --time {time}"))
|
||||
.unwrap_or_default();
|
||||
format!("docker stop{signal}{time} {container_name}")
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
config::{accounts_response, secrets_response},
|
||||
docker, State,
|
||||
State,
|
||||
};
|
||||
|
||||
mod build;
|
||||
@@ -154,6 +154,7 @@ impl Resolve<PruneSystem> for State {
|
||||
PruneSystem {}: PruneSystem,
|
||||
_: (),
|
||||
) -> anyhow::Result<Log> {
|
||||
Ok(docker::prune_system().await)
|
||||
let command = String::from("docker system prune -a -f");
|
||||
Ok(run_monitor_command("prune system", command).await)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use command::run_monitor_command;
|
||||
use monitor_client::entities::{
|
||||
server::docker_network::DockerNetwork, update::Log,
|
||||
};
|
||||
@@ -6,10 +7,7 @@ use periphery_client::api::network::{
|
||||
};
|
||||
use resolver_api::Resolve;
|
||||
|
||||
use crate::{
|
||||
docker::{self, client::docker_client},
|
||||
State,
|
||||
};
|
||||
use crate::{docker::docker_client, State};
|
||||
|
||||
//
|
||||
|
||||
@@ -33,7 +31,12 @@ impl Resolve<CreateNetwork> for State {
|
||||
CreateNetwork { name, driver }: CreateNetwork,
|
||||
_: (),
|
||||
) -> anyhow::Result<Log> {
|
||||
Ok(docker::network::create_network(&name, driver).await)
|
||||
let driver = match driver {
|
||||
Some(driver) => format!(" -d {driver}"),
|
||||
None => String::new(),
|
||||
};
|
||||
let command = format!("docker network create{driver} {name}");
|
||||
Ok(run_monitor_command("create network", command).await)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +49,8 @@ impl Resolve<DeleteNetwork> for State {
|
||||
DeleteNetwork { name }: DeleteNetwork,
|
||||
_: (),
|
||||
) -> anyhow::Result<Log> {
|
||||
Ok(docker::network::delete_network(&name).await)
|
||||
let command = format!("docker network rm {name}");
|
||||
Ok(run_monitor_command("delete network", command).await)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +63,7 @@ impl Resolve<PruneNetworks> for State {
|
||||
_: PruneNetworks,
|
||||
_: (),
|
||||
) -> anyhow::Result<Log> {
|
||||
Ok(docker::network::prune_networks().await)
|
||||
let command = String::from("docker network prune -f");
|
||||
Ok(run_monitor_command("prune networks", command).await)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
use anyhow::Context;
|
||||
use command::run_monitor_command;
|
||||
use formatting::format_serror;
|
||||
use monitor_client::entities::{
|
||||
build::{Build, BuildConfig},
|
||||
config::core::AwsEcrConfig,
|
||||
get_image_name, optional_string, to_monitor_name,
|
||||
update::Log,
|
||||
EnvironmentVar, Version,
|
||||
};
|
||||
|
||||
use crate::config::periphery_config;
|
||||
|
||||
use super::{docker_login, parse_extra_args, parse_labels};
|
||||
|
||||
#[instrument]
|
||||
pub async fn prune_images() -> Log {
|
||||
let command = String::from("docker image prune -a -f");
|
||||
run_monitor_command("prune images", command).await
|
||||
}
|
||||
|
||||
#[instrument(skip(registry_token, core_replacers))]
|
||||
pub async fn build(
|
||||
build: &Build,
|
||||
registry_token: Option<String>,
|
||||
core_replacers: Vec<(String, String)>,
|
||||
aws_ecr: Option<&AwsEcrConfig>,
|
||||
) -> anyhow::Result<Vec<Log>> {
|
||||
let Build {
|
||||
name,
|
||||
config:
|
||||
BuildConfig {
|
||||
version,
|
||||
skip_secret_interp,
|
||||
build_path,
|
||||
dockerfile_path,
|
||||
build_args,
|
||||
labels,
|
||||
extra_args,
|
||||
use_buildx,
|
||||
image_registry,
|
||||
..
|
||||
},
|
||||
..
|
||||
} = build;
|
||||
|
||||
let mut logs = Vec::new();
|
||||
|
||||
// Maybe docker login
|
||||
let should_push = match docker_login(
|
||||
image_registry,
|
||||
registry_token.as_deref(),
|
||||
aws_ecr,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(should_push) => should_push,
|
||||
Err(e) => {
|
||||
logs.push(Log::error(
|
||||
"docker login",
|
||||
format_serror(
|
||||
&e.context("failed to login to docker registry").into(),
|
||||
),
|
||||
));
|
||||
return Ok(logs);
|
||||
}
|
||||
};
|
||||
|
||||
let name = to_monitor_name(name);
|
||||
|
||||
// Get paths
|
||||
let build_dir =
|
||||
periphery_config().repo_dir.join(&name).join(build_path);
|
||||
let dockerfile_path = match optional_string(dockerfile_path) {
|
||||
Some(dockerfile_path) => dockerfile_path.to_owned(),
|
||||
None => "Dockerfile".to_owned(),
|
||||
};
|
||||
|
||||
// Get command parts
|
||||
let image_name = get_image_name(build, |_| aws_ecr.cloned())
|
||||
.context("failed to make image name")?;
|
||||
let build_args = parse_build_args(build_args);
|
||||
let labels = parse_labels(labels);
|
||||
let extra_args = parse_extra_args(extra_args);
|
||||
let buildx = if *use_buildx { " buildx" } else { "" };
|
||||
let image_tags = image_tags(&image_name, version);
|
||||
let push_command = should_push
|
||||
.then(|| format!(" && docker image push --all-tags {image_name}"))
|
||||
.unwrap_or_default();
|
||||
|
||||
// Construct command
|
||||
let command = format!(
|
||||
"cd {} && docker{buildx} build{build_args}{extra_args}{labels}{image_tags} -f {dockerfile_path} .{push_command}",
|
||||
build_dir.display()
|
||||
);
|
||||
|
||||
if *skip_secret_interp {
|
||||
let build_log =
|
||||
run_monitor_command("docker build", command).await;
|
||||
info!("finished building docker image");
|
||||
logs.push(build_log);
|
||||
} else {
|
||||
// Interpolate any missing secrets
|
||||
let (command, mut replacers) = svi::interpolate_variables(
|
||||
&command,
|
||||
&periphery_config().secrets,
|
||||
svi::Interpolator::DoubleBrackets,
|
||||
true,
|
||||
)
|
||||
.context(
|
||||
"failed to interpolate secrets into docker build command",
|
||||
)?;
|
||||
replacers.extend(core_replacers);
|
||||
|
||||
let mut build_log =
|
||||
run_monitor_command("docker build", command).await;
|
||||
build_log.command =
|
||||
svi::replace_in_string(&build_log.command, &replacers);
|
||||
build_log.stdout =
|
||||
svi::replace_in_string(&build_log.stdout, &replacers);
|
||||
build_log.stderr =
|
||||
svi::replace_in_string(&build_log.stderr, &replacers);
|
||||
logs.push(build_log);
|
||||
}
|
||||
|
||||
Ok(logs)
|
||||
}
|
||||
|
||||
fn image_tags(image_name: &str, version: &Version) -> String {
|
||||
let Version { major, minor, .. } = version;
|
||||
format!(
|
||||
" -t {image_name}:latest -t {image_name}:{version} -t {image_name}:{major}.{minor} -t {image_name}:{major}",
|
||||
)
|
||||
}
|
||||
|
||||
fn parse_build_args(build_args: &[EnvironmentVar]) -> String {
|
||||
build_args
|
||||
.iter()
|
||||
.map(|p| format!(" --build-arg {}=\"{}\"", p.variable, p.value))
|
||||
.collect::<Vec<_>>()
|
||||
.join("")
|
||||
}
|
||||
@@ -1,328 +0,0 @@
|
||||
use anyhow::{anyhow, Context};
|
||||
use command::run_monitor_command;
|
||||
use formatting::format_serror;
|
||||
use monitor_client::entities::{
|
||||
config::core::AwsEcrConfig,
|
||||
deployment::{
|
||||
Conversion, Deployment, DeploymentConfig, DeploymentImage,
|
||||
DockerContainerStats, RestartMode, TerminationSignal,
|
||||
},
|
||||
to_monitor_name,
|
||||
update::Log,
|
||||
EnvironmentVar, SearchCombinator,
|
||||
};
|
||||
use run_command::async_run_command;
|
||||
|
||||
use crate::config::periphery_config;
|
||||
|
||||
use super::{docker_login, parse_extra_args, parse_labels};
|
||||
|
||||
#[instrument(level = "debug")]
|
||||
pub async fn container_log(container_name: &str, tail: u64) -> Log {
|
||||
let command = format!("docker logs {container_name} --tail {tail}");
|
||||
run_monitor_command("get container log", command).await
|
||||
}
|
||||
|
||||
#[instrument(level = "debug")]
|
||||
pub async fn container_log_search(
|
||||
container_name: &str,
|
||||
terms: &[String],
|
||||
combinator: SearchCombinator,
|
||||
invert: bool,
|
||||
) -> Log {
|
||||
let maybe_invert = invert.then_some(" -v").unwrap_or_default();
|
||||
let grep = match combinator {
|
||||
SearchCombinator::Or => {
|
||||
format!("grep{maybe_invert} -E '{}'", terms.join("|"))
|
||||
}
|
||||
SearchCombinator::And => {
|
||||
format!(
|
||||
"grep{maybe_invert} -P '^(?=.*{})'",
|
||||
terms.join(")(?=.*")
|
||||
)
|
||||
}
|
||||
};
|
||||
let command =
|
||||
format!("docker logs {container_name} --tail 5000 2>&1 | {grep}");
|
||||
run_monitor_command("get container log grep", command).await
|
||||
}
|
||||
|
||||
#[instrument(level = "debug")]
|
||||
pub async fn container_stats(
|
||||
container_name: Option<String>,
|
||||
) -> anyhow::Result<Vec<DockerContainerStats>> {
|
||||
let format = "--format \"{{ json . }}\"";
|
||||
let container_name = match container_name {
|
||||
Some(name) => format!(" {name}"),
|
||||
None => "".to_string(),
|
||||
};
|
||||
let command =
|
||||
format!("docker stats{container_name} --no-stream {format}");
|
||||
let output = async_run_command(&command).await;
|
||||
if output.success() {
|
||||
let res = output
|
||||
.stdout
|
||||
.split('\n')
|
||||
.filter(|e| !e.is_empty())
|
||||
.map(|e| {
|
||||
let parsed = serde_json::from_str(e)
|
||||
.context(format!("failed at parsing entry {e}"))?;
|
||||
Ok(parsed)
|
||||
})
|
||||
.collect::<anyhow::Result<Vec<DockerContainerStats>>>()?;
|
||||
Ok(res)
|
||||
} else {
|
||||
Err(anyhow!("{}", output.stderr.replace('\n', "")))
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
pub async fn prune_containers() -> Log {
|
||||
let command = String::from("docker container prune -f");
|
||||
run_monitor_command("prune containers", command).await
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
pub async fn start_container(container_name: &str) -> Log {
|
||||
let container_name = to_monitor_name(container_name);
|
||||
let command = format!("docker start {container_name}");
|
||||
run_monitor_command("docker start", command).await
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
pub async fn stop_container(
|
||||
container_name: &str,
|
||||
signal: Option<TerminationSignal>,
|
||||
time: Option<i32>,
|
||||
) -> Log {
|
||||
let command = stop_container_command(container_name, signal, time);
|
||||
let log = run_monitor_command("docker stop", command).await;
|
||||
if log.stderr.contains("unknown flag: --signal") {
|
||||
let command = stop_container_command(container_name, None, time);
|
||||
let mut log = run_monitor_command("docker stop", command).await;
|
||||
log.stderr = format!(
|
||||
"old docker version: unable to use --signal flag{}",
|
||||
if !log.stderr.is_empty() {
|
||||
format!("\n\n{}", log.stderr)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
);
|
||||
log
|
||||
} else {
|
||||
log
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
pub async fn stop_and_remove_container(
|
||||
container_name: &str,
|
||||
signal: Option<TerminationSignal>,
|
||||
time: Option<i32>,
|
||||
) -> Log {
|
||||
let stop_command =
|
||||
stop_container_command(container_name, signal, time);
|
||||
let command =
|
||||
format!("{stop_command} && docker container rm {container_name}");
|
||||
let log =
|
||||
run_monitor_command("docker stop and remove", command).await;
|
||||
if log.stderr.contains("unknown flag: --signal") {
|
||||
let stop_command =
|
||||
stop_container_command(container_name, None, time);
|
||||
let command = format!(
|
||||
"{stop_command} && docker container rm {container_name}"
|
||||
);
|
||||
let mut log = run_monitor_command("docker stop", command).await;
|
||||
log.stderr = format!(
|
||||
"old docker version: unable to use --signal flag{}",
|
||||
if !log.stderr.is_empty() {
|
||||
format!("\n\n{}", log.stderr)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
);
|
||||
log
|
||||
} else {
|
||||
log
|
||||
}
|
||||
}
|
||||
|
||||
fn stop_container_command(
|
||||
container_name: &str,
|
||||
signal: Option<TerminationSignal>,
|
||||
time: Option<i32>,
|
||||
) -> String {
|
||||
let container_name = to_monitor_name(container_name);
|
||||
let signal = signal
|
||||
.map(|signal| format!(" --signal {signal}"))
|
||||
.unwrap_or_default();
|
||||
let time = time
|
||||
.map(|time| format!(" --time {time}"))
|
||||
.unwrap_or_default();
|
||||
format!("docker stop{signal}{time} {container_name}")
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
pub async fn rename_container(
|
||||
curr_name: &str,
|
||||
new_name: &str,
|
||||
) -> Log {
|
||||
let curr = to_monitor_name(curr_name);
|
||||
let new = to_monitor_name(new_name);
|
||||
let command = format!("docker rename {curr} {new}");
|
||||
run_monitor_command("docker rename", command).await
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
async fn pull_image(image: &str) -> Log {
|
||||
let command = format!("docker pull {image}");
|
||||
run_monitor_command("docker pull", command).await
|
||||
}
|
||||
|
||||
#[instrument(skip(registry_token, core_replacers))]
|
||||
pub async fn deploy(
|
||||
deployment: &Deployment,
|
||||
stop_signal: Option<TerminationSignal>,
|
||||
stop_time: Option<i32>,
|
||||
registry_token: Option<String>,
|
||||
core_replacers: Vec<(String, String)>,
|
||||
aws_ecr: Option<&AwsEcrConfig>,
|
||||
) -> Log {
|
||||
if let Err(e) = docker_login(
|
||||
&deployment.config.image_registry,
|
||||
registry_token.as_deref(),
|
||||
aws_ecr,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Log::error(
|
||||
"docker login",
|
||||
format_serror(
|
||||
&e.context("failed to login to docker registry").into(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
let image = if let DeploymentImage::Image { image } =
|
||||
&deployment.config.image
|
||||
{
|
||||
if image.is_empty() {
|
||||
return Log::error(
|
||||
"get image",
|
||||
String::from("deployment does not have image attached"),
|
||||
);
|
||||
}
|
||||
image
|
||||
} else {
|
||||
return Log::error(
|
||||
"get image",
|
||||
String::from("deployment does not have image attached"),
|
||||
);
|
||||
};
|
||||
|
||||
let _ = pull_image(image).await;
|
||||
debug!("image pulled");
|
||||
let _ = stop_and_remove_container(
|
||||
&deployment.name,
|
||||
stop_signal,
|
||||
stop_time,
|
||||
)
|
||||
.await;
|
||||
debug!("container stopped and removed");
|
||||
|
||||
let command = docker_run_command(deployment, image);
|
||||
debug!("docker run command: {command}");
|
||||
|
||||
if deployment.config.skip_secret_interp {
|
||||
run_monitor_command("docker run", command).await
|
||||
} else {
|
||||
let command = svi::interpolate_variables(
|
||||
&command,
|
||||
&periphery_config().secrets,
|
||||
svi::Interpolator::DoubleBrackets,
|
||||
true,
|
||||
)
|
||||
.context("failed to interpolate secrets into docker run command");
|
||||
if let Err(e) = command {
|
||||
return Log::error("docker run", format!("{e:?}"));
|
||||
}
|
||||
let (command, mut replacers) = command.unwrap();
|
||||
replacers.extend(core_replacers);
|
||||
let mut log = run_monitor_command("docker run", command).await;
|
||||
log.command = svi::replace_in_string(&log.command, &replacers);
|
||||
log.stdout = svi::replace_in_string(&log.stdout, &replacers);
|
||||
log.stderr = svi::replace_in_string(&log.stderr, &replacers);
|
||||
log
|
||||
}
|
||||
}
|
||||
|
||||
pub fn docker_run_command(
|
||||
Deployment {
|
||||
name,
|
||||
config:
|
||||
DeploymentConfig {
|
||||
volumes,
|
||||
ports,
|
||||
network,
|
||||
command,
|
||||
restart,
|
||||
environment,
|
||||
labels,
|
||||
extra_args,
|
||||
..
|
||||
},
|
||||
..
|
||||
}: &Deployment,
|
||||
image: &str,
|
||||
) -> String {
|
||||
let name = to_monitor_name(name);
|
||||
let ports = parse_conversions(ports, "-p");
|
||||
let volumes = volumes.to_owned();
|
||||
let volumes = parse_conversions(&volumes, "-v");
|
||||
let network = parse_network(network);
|
||||
let restart = parse_restart(restart);
|
||||
let environment = parse_environment(environment);
|
||||
let labels = parse_labels(labels);
|
||||
let command = parse_command(command);
|
||||
let extra_args = parse_extra_args(extra_args);
|
||||
format!("docker run -d --name {name}{ports}{volumes}{network}{restart}{environment}{labels}{extra_args} {image}{command}")
|
||||
}
|
||||
|
||||
fn parse_conversions(
|
||||
conversions: &[Conversion],
|
||||
flag: &str,
|
||||
) -> String {
|
||||
conversions
|
||||
.iter()
|
||||
.map(|p| format!(" {flag} {}:{}", p.local, p.container))
|
||||
.collect::<Vec<_>>()
|
||||
.join("")
|
||||
}
|
||||
|
||||
fn parse_environment(environment: &[EnvironmentVar]) -> String {
|
||||
environment
|
||||
.iter()
|
||||
.map(|p| format!(" --env {}=\"{}\"", p.variable, p.value))
|
||||
.collect::<Vec<_>>()
|
||||
.join("")
|
||||
}
|
||||
|
||||
fn parse_network(network: &str) -> String {
|
||||
format!(" --network {network}")
|
||||
}
|
||||
|
||||
fn parse_restart(restart: &RestartMode) -> String {
|
||||
let restart = match restart {
|
||||
RestartMode::OnFailure => "on-failure:10".to_string(),
|
||||
_ => restart.to_string(),
|
||||
};
|
||||
format!(" --restart {restart}")
|
||||
}
|
||||
|
||||
fn parse_command(command: &str) -> String {
|
||||
if command.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" {command}")
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
use anyhow::{anyhow, Context};
|
||||
use command::run_monitor_command;
|
||||
use monitor_client::entities::{
|
||||
build::{CloudRegistryConfig, ImageRegistry},
|
||||
config::core::AwsEcrConfig,
|
||||
update::Log,
|
||||
EnvironmentVar,
|
||||
};
|
||||
use run_command::async_run_command;
|
||||
|
||||
use crate::helpers::{get_docker_token, get_github_token};
|
||||
|
||||
pub mod build;
|
||||
pub mod client;
|
||||
pub mod container;
|
||||
pub mod network;
|
||||
|
||||
/// Returns whether build result should be pushed after build
|
||||
pub async fn docker_login(
|
||||
registry: &ImageRegistry,
|
||||
// For local token override from core.
|
||||
registry_token: Option<&str>,
|
||||
// For local config override from core.
|
||||
aws_ecr: Option<&AwsEcrConfig>,
|
||||
) -> anyhow::Result<bool> {
|
||||
match registry {
|
||||
ImageRegistry::None(_) => Ok(false),
|
||||
ImageRegistry::DockerHub(CloudRegistryConfig {
|
||||
account, ..
|
||||
}) => {
|
||||
if account.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"Must configure account for DockerHub registry"
|
||||
));
|
||||
}
|
||||
let registry_token = match registry_token {
|
||||
Some(token) => token,
|
||||
None => get_docker_token(account)?,
|
||||
};
|
||||
let log = async_run_command(&format!(
|
||||
"docker login -u {account} -p {registry_token}",
|
||||
))
|
||||
.await;
|
||||
if log.success() {
|
||||
Ok(true)
|
||||
} else {
|
||||
Err(anyhow!(
|
||||
"dockerhub login error: stdout: {} | stderr: {}",
|
||||
log.stdout,
|
||||
log.stderr
|
||||
))
|
||||
}
|
||||
}
|
||||
ImageRegistry::Ghcr(CloudRegistryConfig { account, .. }) => {
|
||||
if account.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"Must configure account for GithubContainerRegistry"
|
||||
));
|
||||
}
|
||||
let registry_token = match registry_token {
|
||||
Some(token) => token,
|
||||
None => get_github_token(account)?,
|
||||
};
|
||||
let log = async_run_command(&format!(
|
||||
"docker login ghcr.io -u {account} -p {registry_token}",
|
||||
))
|
||||
.await;
|
||||
if log.success() {
|
||||
Ok(true)
|
||||
} else {
|
||||
Err(anyhow!(
|
||||
"ghcr login error: stdout: {} | stderr: {}",
|
||||
log.stdout,
|
||||
log.stderr
|
||||
))
|
||||
}
|
||||
}
|
||||
ImageRegistry::AwsEcr(label) => {
|
||||
let AwsEcrConfig { region, account_id } = aws_ecr
|
||||
.with_context(|| {
|
||||
format!("Could not find aws ecr config for label {label}")
|
||||
})?;
|
||||
let registry_token = registry_token
|
||||
.context("aws ecr build missing registry token from core")?;
|
||||
let log = async_run_command(&format!("docker login {account_id}.dkr.ecr.{region}.amazonaws.com -u AWS -p {registry_token}")).await;
|
||||
if log.success() {
|
||||
Ok(true)
|
||||
} else {
|
||||
Err(anyhow!(
|
||||
"aws ecr login error: stdout: {} | stderr: {}",
|
||||
log.stdout,
|
||||
log.stderr
|
||||
))
|
||||
}
|
||||
}
|
||||
ImageRegistry::Custom(_) => todo!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_extra_args(extra_args: &[String]) -> String {
|
||||
let args = extra_args.join(" ");
|
||||
if !args.is_empty() {
|
||||
format!(" {args}")
|
||||
} else {
|
||||
args
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_labels(labels: &[EnvironmentVar]) -> String {
|
||||
labels
|
||||
.iter()
|
||||
.map(|p| format!(" --label {}=\"{}\"", p.variable, p.value))
|
||||
.collect::<Vec<_>>()
|
||||
.join("")
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
pub async fn prune_system() -> Log {
|
||||
let command = String::from("docker system prune -a -f");
|
||||
run_monitor_command("prune system", command).await
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
use command::run_monitor_command;
|
||||
use monitor_client::entities::update::Log;
|
||||
|
||||
#[instrument]
|
||||
pub async fn create_network(
|
||||
name: &str,
|
||||
driver: Option<String>,
|
||||
) -> Log {
|
||||
let driver = match driver {
|
||||
Some(driver) => format!(" -d {driver}"),
|
||||
None => String::new(),
|
||||
};
|
||||
let command = format!("docker network create{driver} {name}");
|
||||
run_monitor_command("create network", command).await
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
pub async fn delete_network(name: &str) -> Log {
|
||||
let command = format!("docker network rm {name}");
|
||||
run_monitor_command("delete network", command).await
|
||||
}
|
||||
|
||||
#[instrument]
|
||||
pub async fn prune_networks() -> Log {
|
||||
let command = String::from("docker network prune -f");
|
||||
run_monitor_command("prune networks", command).await
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use anyhow::{anyhow, Context};
|
||||
use axum::{
|
||||
body::Body,
|
||||
extract::ConnectInfo,
|
||||
http::{Request, StatusCode},
|
||||
middleware::Next,
|
||||
response::Response,
|
||||
};
|
||||
use serror::{AddStatusCode, AddStatusCodeError};
|
||||
|
||||
use crate::config::periphery_config;
|
||||
|
||||
#[instrument(level = "debug")]
|
||||
pub async fn guard_request_by_passkey(
|
||||
req: Request<Body>,
|
||||
next: Next,
|
||||
) -> serror::Result<Response> {
|
||||
if periphery_config().passkeys.is_empty() {
|
||||
return Ok(next.run(req).await);
|
||||
}
|
||||
let Some(req_passkey) = req.headers().get("authorization") else {
|
||||
return Err(
|
||||
anyhow!("request was not sent with passkey")
|
||||
.status_code(StatusCode::UNAUTHORIZED),
|
||||
);
|
||||
};
|
||||
let req_passkey = req_passkey
|
||||
.to_str()
|
||||
.context("failed to convert passkey to str")
|
||||
.status_code(StatusCode::UNAUTHORIZED)?;
|
||||
if periphery_config()
|
||||
.passkeys
|
||||
.iter()
|
||||
.any(|passkey| passkey == req_passkey)
|
||||
{
|
||||
Ok(next.run(req).await)
|
||||
} else {
|
||||
Err(
|
||||
anyhow!("request passkey invalid")
|
||||
.status_code(StatusCode::UNAUTHORIZED),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(level = "debug")]
|
||||
pub async fn guard_request_by_ip(
|
||||
req: Request<Body>,
|
||||
next: Next,
|
||||
) -> serror::Result<Response> {
|
||||
if periphery_config().allowed_ips.is_empty() {
|
||||
return Ok(next.run(req).await);
|
||||
}
|
||||
let ConnectInfo(socket_addr) = req
|
||||
.extensions()
|
||||
.get::<ConnectInfo<SocketAddr>>()
|
||||
.context("could not get ConnectionInfo of request")
|
||||
.status_code(StatusCode::UNAUTHORIZED)?;
|
||||
let ip = socket_addr.ip();
|
||||
if periphery_config().allowed_ips.contains(&ip) {
|
||||
Ok(next.run(req).await)
|
||||
} else {
|
||||
Err(
|
||||
anyhow!("requesting ip {ip} not allowed")
|
||||
.status_code(StatusCode::UNAUTHORIZED),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::{anyhow, Context};
|
||||
use axum_extra::{headers::ContentType, TypedHeader};
|
||||
use resolver_api::Resolver;
|
||||
use serror::Json;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::State;
|
||||
|
||||
pub async fn handler(
|
||||
Json(request): Json<crate::api::PeripheryRequest>,
|
||||
) -> serror::Result<(TypedHeader<ContentType>, String)> {
|
||||
let req_id = Uuid::new_v4();
|
||||
|
||||
let res = tokio::spawn(task(req_id, request))
|
||||
.await
|
||||
.context("task handler spawn error");
|
||||
|
||||
if let Err(e) = &res {
|
||||
warn!("request {req_id} spawn error: {e:#}");
|
||||
}
|
||||
|
||||
Ok((TypedHeader(ContentType::json()), res??))
|
||||
}
|
||||
|
||||
#[instrument(name = "PeripheryHandler")]
|
||||
async fn task(
|
||||
req_id: Uuid,
|
||||
request: crate::api::PeripheryRequest,
|
||||
) -> anyhow::Result<String> {
|
||||
let timer = Instant::now();
|
||||
|
||||
let res =
|
||||
State
|
||||
.resolve_request(request, ())
|
||||
.await
|
||||
.map_err(|e| match e {
|
||||
resolver_api::Error::Serialization(e) => {
|
||||
anyhow!("{e:?}").context("response serialization error")
|
||||
}
|
||||
resolver_api::Error::Inner(e) => e,
|
||||
});
|
||||
|
||||
if let Err(e) = &res {
|
||||
warn!("request {req_id} error: {e:#}");
|
||||
}
|
||||
|
||||
let elapsed = timer.elapsed();
|
||||
debug!("request {req_id} | resolve time: {elapsed:?}");
|
||||
|
||||
res
|
||||
}
|
||||
@@ -1,4 +1,10 @@
|
||||
use anyhow::Context;
|
||||
use anyhow::{anyhow, Context};
|
||||
use monitor_client::entities::{
|
||||
build::{CloudRegistryConfig, ImageRegistry},
|
||||
config::core::AwsEcrConfig,
|
||||
EnvironmentVar,
|
||||
};
|
||||
use run_command::async_run_command;
|
||||
|
||||
use crate::config::periphery_config;
|
||||
|
||||
@@ -19,3 +25,103 @@ pub fn get_docker_token(
|
||||
.get(docker_account)
|
||||
.with_context(|| format!("did not find token in config for docker account {docker_account}"))
|
||||
}
|
||||
|
||||
pub fn parse_extra_args(extra_args: &[String]) -> String {
|
||||
let args = extra_args.join(" ");
|
||||
if !args.is_empty() {
|
||||
format!(" {args}")
|
||||
} else {
|
||||
args
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_labels(labels: &[EnvironmentVar]) -> String {
|
||||
labels
|
||||
.iter()
|
||||
.map(|p| format!(" --label {}=\"{}\"", p.variable, p.value))
|
||||
.collect::<Vec<_>>()
|
||||
.join("")
|
||||
}
|
||||
|
||||
/// Returns whether build result should be pushed after build
|
||||
#[instrument(skip(registry_token))]
|
||||
pub async fn docker_login(
|
||||
registry: &ImageRegistry,
|
||||
// For local token override from core.
|
||||
registry_token: Option<&str>,
|
||||
// For local config override from core.
|
||||
aws_ecr: Option<&AwsEcrConfig>,
|
||||
) -> anyhow::Result<bool> {
|
||||
match registry {
|
||||
ImageRegistry::None(_) => Ok(false),
|
||||
ImageRegistry::DockerHub(CloudRegistryConfig {
|
||||
account, ..
|
||||
}) => {
|
||||
if account.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"Must configure account for DockerHub registry"
|
||||
));
|
||||
}
|
||||
let registry_token = match registry_token {
|
||||
Some(token) => token,
|
||||
None => get_docker_token(account)?,
|
||||
};
|
||||
let log = async_run_command(&format!(
|
||||
"docker login -u {account} -p {registry_token}",
|
||||
))
|
||||
.await;
|
||||
if log.success() {
|
||||
Ok(true)
|
||||
} else {
|
||||
Err(anyhow!(
|
||||
"dockerhub login error: stdout: {} | stderr: {}",
|
||||
log.stdout,
|
||||
log.stderr
|
||||
))
|
||||
}
|
||||
}
|
||||
ImageRegistry::Ghcr(CloudRegistryConfig { account, .. }) => {
|
||||
if account.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"Must configure account for GithubContainerRegistry"
|
||||
));
|
||||
}
|
||||
let registry_token = match registry_token {
|
||||
Some(token) => token,
|
||||
None => get_github_token(account)?,
|
||||
};
|
||||
let log = async_run_command(&format!(
|
||||
"docker login ghcr.io -u {account} -p {registry_token}",
|
||||
))
|
||||
.await;
|
||||
if log.success() {
|
||||
Ok(true)
|
||||
} else {
|
||||
Err(anyhow!(
|
||||
"ghcr login error: stdout: {} | stderr: {}",
|
||||
log.stdout,
|
||||
log.stderr
|
||||
))
|
||||
}
|
||||
}
|
||||
ImageRegistry::AwsEcr(label) => {
|
||||
let AwsEcrConfig { region, account_id } = aws_ecr
|
||||
.with_context(|| {
|
||||
format!("Could not find aws ecr config for label {label}")
|
||||
})?;
|
||||
let registry_token = registry_token
|
||||
.context("aws ecr build missing registry token from core")?;
|
||||
let log = async_run_command(&format!("docker login {account_id}.dkr.ecr.{region}.amazonaws.com -u AWS -p {registry_token}")).await;
|
||||
if log.success() {
|
||||
Ok(true)
|
||||
} else {
|
||||
Err(anyhow!(
|
||||
"aws ecr login error: stdout: {} | stderr: {}",
|
||||
log.stdout,
|
||||
log.stderr
|
||||
))
|
||||
}
|
||||
}
|
||||
ImageRegistry::Custom(_) => todo!(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,14 +4,12 @@ extern crate tracing;
|
||||
use std::{net::SocketAddr, str::FromStr};
|
||||
|
||||
use anyhow::Context;
|
||||
use axum::{middleware, routing::post, Router};
|
||||
|
||||
mod api;
|
||||
mod config;
|
||||
mod docker;
|
||||
mod guard;
|
||||
mod handler;
|
||||
mod helpers;
|
||||
mod router;
|
||||
mod stats;
|
||||
|
||||
struct State;
|
||||
@@ -29,20 +27,16 @@ async fn app() -> anyhow::Result<()> {
|
||||
SocketAddr::from_str(&format!("0.0.0.0:{}", config.port))
|
||||
.context("failed to parse socket addr")?;
|
||||
|
||||
let app = Router::new()
|
||||
.route("/", post(handler::handler))
|
||||
.layer(middleware::from_fn(guard::guard_request_by_ip))
|
||||
.layer(middleware::from_fn(guard::guard_request_by_passkey));
|
||||
|
||||
info!("starting server on {}", socket_addr);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(&socket_addr)
|
||||
.await
|
||||
.context("failed to bind tcp listener")?;
|
||||
|
||||
info!("monitor core started on {}", socket_addr);
|
||||
|
||||
axum::serve(
|
||||
listener,
|
||||
app.into_make_service_with_connect_info::<SocketAddr>(),
|
||||
router::router()
|
||||
.into_make_service_with_connect_info::<SocketAddr>(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
use std::{net::SocketAddr, time::Instant};
|
||||
|
||||
use anyhow::{anyhow, Context};
|
||||
use axum::{
|
||||
body::Body,
|
||||
extract::ConnectInfo,
|
||||
http::{Request, StatusCode},
|
||||
middleware::{self, Next},
|
||||
response::Response,
|
||||
routing::post,
|
||||
Router,
|
||||
};
|
||||
use axum_extra::{headers::ContentType, TypedHeader};
|
||||
use resolver_api::Resolver;
|
||||
use serror::{AddStatusCode, AddStatusCodeError, Json};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{config::periphery_config, State};
|
||||
|
||||
pub fn router() -> Router {
|
||||
Router::new()
|
||||
.route("/", post(handler))
|
||||
.layer(middleware::from_fn(guard_request_by_ip))
|
||||
.layer(middleware::from_fn(guard_request_by_passkey))
|
||||
}
|
||||
|
||||
async fn handler(
|
||||
Json(request): Json<crate::api::PeripheryRequest>,
|
||||
) -> serror::Result<(TypedHeader<ContentType>, String)> {
|
||||
let req_id = Uuid::new_v4();
|
||||
|
||||
let res = tokio::spawn(task(req_id, request))
|
||||
.await
|
||||
.context("task handler spawn error");
|
||||
|
||||
if let Err(e) = &res {
|
||||
warn!("request {req_id} spawn error: {e:#}");
|
||||
}
|
||||
|
||||
Ok((TypedHeader(ContentType::json()), res??))
|
||||
}
|
||||
|
||||
#[instrument(name = "PeripheryHandler")]
|
||||
async fn task(
|
||||
req_id: Uuid,
|
||||
request: crate::api::PeripheryRequest,
|
||||
) -> anyhow::Result<String> {
|
||||
let timer = Instant::now();
|
||||
|
||||
let res =
|
||||
State
|
||||
.resolve_request(request, ())
|
||||
.await
|
||||
.map_err(|e| match e {
|
||||
resolver_api::Error::Serialization(e) => {
|
||||
anyhow!("{e:?}").context("response serialization error")
|
||||
}
|
||||
resolver_api::Error::Inner(e) => e,
|
||||
});
|
||||
|
||||
if let Err(e) = &res {
|
||||
warn!("request {req_id} error: {e:#}");
|
||||
}
|
||||
|
||||
let elapsed = timer.elapsed();
|
||||
debug!("request {req_id} | resolve time: {elapsed:?}");
|
||||
|
||||
res
|
||||
}
|
||||
|
||||
#[instrument(level = "debug")]
|
||||
async fn guard_request_by_passkey(
|
||||
req: Request<Body>,
|
||||
next: Next,
|
||||
) -> serror::Result<Response> {
|
||||
if periphery_config().passkeys.is_empty() {
|
||||
return Ok(next.run(req).await);
|
||||
}
|
||||
let Some(req_passkey) = req.headers().get("authorization") else {
|
||||
return Err(
|
||||
anyhow!("request was not sent with passkey")
|
||||
.status_code(StatusCode::UNAUTHORIZED),
|
||||
);
|
||||
};
|
||||
let req_passkey = req_passkey
|
||||
.to_str()
|
||||
.context("failed to convert passkey to str")
|
||||
.status_code(StatusCode::UNAUTHORIZED)?;
|
||||
if periphery_config()
|
||||
.passkeys
|
||||
.iter()
|
||||
.any(|passkey| passkey == req_passkey)
|
||||
{
|
||||
Ok(next.run(req).await)
|
||||
} else {
|
||||
Err(
|
||||
anyhow!("request passkey invalid")
|
||||
.status_code(StatusCode::UNAUTHORIZED),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(level = "debug")]
|
||||
async fn guard_request_by_ip(
|
||||
req: Request<Body>,
|
||||
next: Next,
|
||||
) -> serror::Result<Response> {
|
||||
if periphery_config().allowed_ips.is_empty() {
|
||||
return Ok(next.run(req).await);
|
||||
}
|
||||
let ConnectInfo(socket_addr) = req
|
||||
.extensions()
|
||||
.get::<ConnectInfo<SocketAddr>>()
|
||||
.context("could not get ConnectionInfo of request")
|
||||
.status_code(StatusCode::UNAUTHORIZED)?;
|
||||
let ip = socket_addr.ip();
|
||||
if periphery_config().allowed_ips.contains(&ip) {
|
||||
Ok(next.run(req).await)
|
||||
} else {
|
||||
Err(
|
||||
anyhow!("requesting ip {ip} not allowed")
|
||||
.status_code(StatusCode::UNAUTHORIZED),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -258,3 +258,29 @@ pub struct ListCommonBuildExtraArgs {
|
||||
|
||||
#[typeshare]
|
||||
pub type ListCommonBuildExtraArgsResponse = Vec<String>;
|
||||
|
||||
//
|
||||
|
||||
/// Get whether a Build's target repo has a webhook for the build configured. Response: [GetBuildWebhookEnabledResponse].
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
Serialize, Deserialize, Debug, Clone, Request, EmptyTraits,
|
||||
)]
|
||||
#[empty_traits(MonitorReadRequest)]
|
||||
#[response(GetBuildWebhookEnabledResponse)]
|
||||
pub struct GetBuildWebhookEnabled {
|
||||
/// Id or name
|
||||
#[serde(alias = "id", alias = "name")]
|
||||
pub build: String,
|
||||
}
|
||||
|
||||
/// Response for [GetBuildWebhookEnabled]
|
||||
#[typeshare]
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GetBuildWebhookEnabledResponse {
|
||||
/// Whether the repo webhooks can even be managed.
|
||||
/// The repo owner must be in `github_webhook_app.owners` list to be managed.
|
||||
pub managed: bool,
|
||||
/// Whether pushes to branch trigger build. Will always be false if managed is false.
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
@@ -91,6 +91,8 @@ pub struct GetCoreInfoResponse {
|
||||
pub transparent_mode: bool,
|
||||
/// Whether UI write access should be disabled
|
||||
pub ui_write_disabled: bool,
|
||||
/// The repo owners for which github webhook management api is available
|
||||
pub github_webhook_owners: Vec<String>,
|
||||
}
|
||||
|
||||
//
|
||||
@@ -106,4 +108,4 @@ pub struct GetCoreInfoResponse {
|
||||
pub struct GetAvailableAwsEcrLabels {}
|
||||
|
||||
#[typeshare]
|
||||
pub type GetAvailableAwsEcrLabelsResponse = Vec<String>;
|
||||
pub type GetAvailableAwsEcrLabelsResponse = Vec<String>;
|
||||
|
||||
@@ -108,5 +108,3 @@ pub struct GetProceduresSummaryResponse {
|
||||
/// The number of procedures with unknown state.
|
||||
pub unknown: u32,
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@@ -110,3 +110,31 @@ pub struct GetReposSummaryResponse {
|
||||
/// The number of repos with unknown state.
|
||||
pub unknown: u32,
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
/// Get a target Repo's configured webhooks. Response: [GetRepoWebhooksEnabledResponse].
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
Serialize, Deserialize, Debug, Clone, Request, EmptyTraits,
|
||||
)]
|
||||
#[empty_traits(MonitorReadRequest)]
|
||||
#[response(GetRepoWebhooksEnabledResponse)]
|
||||
pub struct GetRepoWebhooksEnabled {
|
||||
/// Id or name
|
||||
#[serde(alias = "id", alias = "name")]
|
||||
pub repo: String,
|
||||
}
|
||||
|
||||
/// Response for [GetRepoWebhooksEnabled]
|
||||
#[typeshare]
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GetRepoWebhooksEnabledResponse {
|
||||
/// Whether the repo webhooks can even be managed.
|
||||
/// The repo owner must be in `github_webhook_app.owners` list to be managed.
|
||||
pub managed: bool,
|
||||
/// Whether pushes to branch trigger clone. Will always be false if managed is false.
|
||||
pub clone_enabled: bool,
|
||||
/// Whether pushes to branch trigger pull. Will always be false if managed is false.
|
||||
pub pull_enabled: bool,
|
||||
}
|
||||
|
||||
@@ -111,3 +111,31 @@ pub struct GetResourceSyncsSummaryResponse {
|
||||
/// The number of syncs with unknown state.
|
||||
pub unknown: u32,
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
/// Get a target Sync's configured webhooks. Response: [GetSyncWebhooksEnabledResponse].
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
Serialize, Deserialize, Debug, Clone, Request, EmptyTraits,
|
||||
)]
|
||||
#[empty_traits(MonitorReadRequest)]
|
||||
#[response(GetSyncWebhooksEnabledResponse)]
|
||||
pub struct GetSyncWebhooksEnabled {
|
||||
/// Id or name
|
||||
#[serde(alias = "id", alias = "name")]
|
||||
pub sync: String,
|
||||
}
|
||||
|
||||
/// Response for [GetSyncWebhooksEnabled]
|
||||
#[typeshare]
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct GetSyncWebhooksEnabledResponse {
|
||||
/// Whether the repo webhooks can even be managed.
|
||||
/// The repo owner must be in `github_webhook_app.owners` list to be managed.
|
||||
pub managed: bool,
|
||||
/// Whether pushes to branch trigger refresh. Will always be false if managed is false.
|
||||
pub refresh_enabled: bool,
|
||||
/// Whether pushes to branch trigger sync execution. Will always be false if managed is false.
|
||||
pub sync_enabled: bool,
|
||||
}
|
||||
|
||||
@@ -22,8 +22,8 @@ pub type ListApiKeysResponse = Vec<ApiKey>;
|
||||
|
||||
//
|
||||
|
||||
/// Gets list of api keys for the user at ID.
|
||||
/// **Admin only.**
|
||||
/// Gets list of api keys for the user.
|
||||
/// Will still fail if you call for a user_id that isn't a service user.
|
||||
/// Response: [ListApiKeysForServiceUserResponse]
|
||||
#[typeshare]
|
||||
@@ -33,8 +33,9 @@ pub type ListApiKeysResponse = Vec<ApiKey>;
|
||||
#[empty_traits(MonitorReadRequest)]
|
||||
#[response(ListApiKeysForServiceUserResponse)]
|
||||
pub struct ListApiKeysForServiceUser {
|
||||
/// The id of the user.
|
||||
pub user_id: String,
|
||||
/// Id or username
|
||||
#[serde(alias = "id", alias = "username")]
|
||||
pub user: String,
|
||||
}
|
||||
|
||||
#[typeshare]
|
||||
@@ -42,8 +43,28 @@ pub type ListApiKeysForServiceUserResponse = Vec<ApiKey>;
|
||||
|
||||
//
|
||||
|
||||
/// Gets list of monitor users.
|
||||
/// **Admin only.**
|
||||
/// Find a user.
|
||||
/// Response: [FindUserResponse]
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
Serialize, Deserialize, Debug, Clone, Default, Request, EmptyTraits,
|
||||
)]
|
||||
#[empty_traits(MonitorReadRequest)]
|
||||
#[response(FindUserResponse)]
|
||||
pub struct FindUser {
|
||||
/// Id or username
|
||||
#[serde(alias = "id", alias = "username")]
|
||||
pub user: String,
|
||||
}
|
||||
|
||||
#[typeshare]
|
||||
pub type FindUserResponse = User;
|
||||
|
||||
//
|
||||
|
||||
/// **Admin only.**
|
||||
/// Gets list of monitor users.
|
||||
/// Response: [ListUsersResponse]
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
|
||||
@@ -59,7 +59,7 @@ pub struct DeleteAlerter {
|
||||
|
||||
/// Update the alerter at the given id, and return the updated alerter. Response: [Alerter].
|
||||
///
|
||||
/// Note. This method updates only the fields which are set in the [PartialAlerterConfig],
|
||||
/// Note. This method updates only the fields which are set in the [PartialAlerterConfig][crate::entities::alerter::PartialAlerterConfig],
|
||||
/// effectively merging diffs into the final document. This is helpful when multiple users are using
|
||||
/// the same resources concurrently by ensuring no unintentional
|
||||
/// field changes occur from out of date local state.
|
||||
|
||||
@@ -3,7 +3,10 @@ use resolver_api::derive::Request;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use typeshare::typeshare;
|
||||
|
||||
use crate::entities::build::{Build, _PartialBuildConfig};
|
||||
use crate::entities::{
|
||||
build::{Build, _PartialBuildConfig},
|
||||
NoData,
|
||||
};
|
||||
|
||||
use super::MonitorWriteRequest;
|
||||
|
||||
@@ -77,3 +80,41 @@ pub struct UpdateBuild {
|
||||
/// The partial config update to apply.
|
||||
pub config: _PartialBuildConfig,
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
/// Create a webhook on the github repo attached to the build
|
||||
/// passed in request. Response: [CreateBuildWebhookResponse]
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
Serialize, Deserialize, Debug, Clone, Request, EmptyTraits,
|
||||
)]
|
||||
#[empty_traits(MonitorWriteRequest)]
|
||||
#[response(CreateBuildWebhookResponse)]
|
||||
pub struct CreateBuildWebhook {
|
||||
/// Id or name
|
||||
#[serde(alias = "id", alias = "name")]
|
||||
pub build: String,
|
||||
}
|
||||
|
||||
#[typeshare]
|
||||
pub type CreateBuildWebhookResponse = NoData;
|
||||
|
||||
//
|
||||
|
||||
/// Delete a webhook on the github repo attached to the build
|
||||
/// passed in request. Response: [CreateBuildWebhookResponse]
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
Serialize, Deserialize, Debug, Clone, Request, EmptyTraits,
|
||||
)]
|
||||
#[empty_traits(MonitorWriteRequest)]
|
||||
#[response(DeleteBuildWebhookResponse)]
|
||||
pub struct DeleteBuildWebhook {
|
||||
/// Id or name
|
||||
#[serde(alias = "id", alias = "name")]
|
||||
pub build: String,
|
||||
}
|
||||
|
||||
#[typeshare]
|
||||
pub type DeleteBuildWebhookResponse = NoData;
|
||||
|
||||
@@ -5,13 +5,13 @@ use typeshare::typeshare;
|
||||
|
||||
use crate::entities::{
|
||||
permission::{PermissionLevel, UserTarget},
|
||||
update::ResourceTarget,
|
||||
update::{ResourceTarget, ResourceTargetVariant},
|
||||
NoData,
|
||||
};
|
||||
|
||||
use super::MonitorWriteRequest;
|
||||
|
||||
/// Update a user or user groups permission on a resource.
|
||||
/// **Admin only.** Update a user or user groups permission on a resource.
|
||||
/// Response: [NoData].
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
@@ -33,7 +33,29 @@ pub type UpdatePermissionOnTargetResponse = NoData;
|
||||
|
||||
//
|
||||
|
||||
/// Update a user's "base" permissions, eg. "enabled".
|
||||
/// **Admin only.** Update a user or user groups base permission level on a resource type.
|
||||
/// Response: [NoData].
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
Serialize, Deserialize, Debug, Clone, Request, EmptyTraits,
|
||||
)]
|
||||
#[empty_traits(MonitorWriteRequest)]
|
||||
#[response(UpdatePermissionOnResourceTypeResponse)]
|
||||
pub struct UpdatePermissionOnResourceType {
|
||||
/// Specify the user or user group.
|
||||
pub user_target: UserTarget,
|
||||
/// The resource type: eg. Server, Build, Deployment, etc.
|
||||
pub resource_type: ResourceTargetVariant,
|
||||
/// The base permission level.
|
||||
pub permission: PermissionLevel,
|
||||
}
|
||||
|
||||
#[typeshare]
|
||||
pub type UpdatePermissionOnResourceTypeResponse = NoData;
|
||||
|
||||
//
|
||||
|
||||
/// **Admin only.** Update a user's "base" permissions, eg. "enabled".
|
||||
/// Response: [NoData].
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
|
||||
@@ -3,7 +3,10 @@ use resolver_api::derive::Request;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use typeshare::typeshare;
|
||||
|
||||
use crate::entities::repo::{Repo, _PartialRepoConfig};
|
||||
use crate::entities::{
|
||||
repo::{Repo, _PartialRepoConfig},
|
||||
NoData,
|
||||
};
|
||||
|
||||
use super::MonitorWriteRequest;
|
||||
|
||||
@@ -80,3 +83,52 @@ pub struct UpdateRepo {
|
||||
/// The partial config update to apply.
|
||||
pub config: _PartialRepoConfig,
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
#[typeshare]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum RepoWebhookAction {
|
||||
Clone,
|
||||
Pull,
|
||||
}
|
||||
|
||||
/// Create a webhook on the github repo attached to the (monitor) repo
|
||||
/// passed in request. Response: [CreateRepoWebhookResponse]
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
Serialize, Deserialize, Debug, Clone, Request, EmptyTraits,
|
||||
)]
|
||||
#[empty_traits(MonitorWriteRequest)]
|
||||
#[response(CreateRepoWebhookResponse)]
|
||||
pub struct CreateRepoWebhook {
|
||||
/// Id or name
|
||||
#[serde(alias = "id", alias = "name")]
|
||||
pub repo: String,
|
||||
/// "Clone" or "Pull"
|
||||
pub action: RepoWebhookAction,
|
||||
}
|
||||
|
||||
#[typeshare]
|
||||
pub type CreateRepoWebhookResponse = NoData;
|
||||
|
||||
//
|
||||
|
||||
/// Delete the webhook on the github repo attached to the (monitor) repo
|
||||
/// passed in request. Response: [DeleteRepoWebhookResponse]
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
Serialize, Deserialize, Debug, Clone, Request, EmptyTraits,
|
||||
)]
|
||||
#[empty_traits(MonitorWriteRequest)]
|
||||
#[response(DeleteRepoWebhookResponse)]
|
||||
pub struct DeleteRepoWebhook {
|
||||
/// Id or name
|
||||
#[serde(alias = "id", alias = "name")]
|
||||
pub repo: String,
|
||||
/// "Clone" or "Pull"
|
||||
pub action: RepoWebhookAction,
|
||||
}
|
||||
|
||||
#[typeshare]
|
||||
pub type DeleteRepoWebhookResponse = NoData;
|
||||
|
||||
@@ -3,8 +3,9 @@ use resolver_api::derive::Request;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use typeshare::typeshare;
|
||||
|
||||
use crate::entities::sync::{
|
||||
ResourceSync, _PartialResourceSyncConfig,
|
||||
use crate::entities::{
|
||||
sync::{ResourceSync, _PartialResourceSyncConfig},
|
||||
NoData,
|
||||
};
|
||||
|
||||
use super::MonitorWriteRequest;
|
||||
@@ -96,3 +97,52 @@ pub struct RefreshResourceSyncPending {
|
||||
/// Id or name
|
||||
pub sync: String,
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
#[typeshare]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum SyncWebhookAction {
|
||||
Refresh,
|
||||
Sync,
|
||||
}
|
||||
|
||||
/// Create a webhook on the github repo attached to the sync
|
||||
/// passed in request. Response: [CreateSyncWebhookResponse]
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
Serialize, Deserialize, Debug, Clone, Request, EmptyTraits,
|
||||
)]
|
||||
#[empty_traits(MonitorWriteRequest)]
|
||||
#[response(CreateSyncWebhookResponse)]
|
||||
pub struct CreateSyncWebhook {
|
||||
/// Id or name
|
||||
#[serde(alias = "id", alias = "name")]
|
||||
pub sync: String,
|
||||
/// "Refresh" or "Sync"
|
||||
pub action: SyncWebhookAction,
|
||||
}
|
||||
|
||||
#[typeshare]
|
||||
pub type CreateSyncWebhookResponse = NoData;
|
||||
|
||||
//
|
||||
|
||||
/// Delete the webhook on the github repo attached to the sync
|
||||
/// passed in request. Response: [DeleteSyncWebhookResponse]
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
Serialize, Deserialize, Debug, Clone, Request, EmptyTraits,
|
||||
)]
|
||||
#[empty_traits(MonitorWriteRequest)]
|
||||
#[response(DeleteSyncWebhookResponse)]
|
||||
pub struct DeleteSyncWebhook {
|
||||
/// Id or name
|
||||
#[serde(alias = "id", alias = "name")]
|
||||
pub sync: String,
|
||||
/// "Refresh" or "Sync"
|
||||
pub action: SyncWebhookAction,
|
||||
}
|
||||
|
||||
#[typeshare]
|
||||
pub type DeleteSyncWebhookResponse = NoData;
|
||||
|
||||
@@ -7,11 +7,8 @@ use typeshare::typeshare;
|
||||
use crate::entities::{MongoId, I64};
|
||||
|
||||
use super::{
|
||||
_Serror,
|
||||
deployment::DeploymentState,
|
||||
server::stats::SeverityLevel,
|
||||
update::{Log, ResourceTarget},
|
||||
Version,
|
||||
_Serror, deployment::DeploymentState, server::stats::SeverityLevel,
|
||||
update::ResourceTarget, Version,
|
||||
};
|
||||
|
||||
/// Representation of an alert in the system.
|
||||
@@ -170,8 +167,6 @@ pub enum AlertData {
|
||||
name: String,
|
||||
/// The version that failed to build
|
||||
version: Version,
|
||||
/// The reason build failed
|
||||
err: Option<Log>,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -142,7 +142,9 @@ pub struct BuildConfig {
|
||||
#[builder(default)]
|
||||
pub extra_args: Vec<String>,
|
||||
|
||||
/// Docker build arguments
|
||||
/// Docker build arguments.
|
||||
///
|
||||
/// These values are visible in the final image by running `docker inspect`.
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "super::env_vars_deserializer"
|
||||
@@ -154,6 +156,27 @@ pub struct BuildConfig {
|
||||
#[builder(default)]
|
||||
pub build_args: Vec<EnvironmentVar>,
|
||||
|
||||
/// Secret arguments.
|
||||
///
|
||||
/// These values remain hidden in the final image by using
|
||||
/// docker secret mounts. See `<https://docs.docker.com/build/building/secrets>`.
|
||||
///
|
||||
/// The values can be used in RUN commands:
|
||||
/// ```
|
||||
/// RUN --mount=type=secret,id=SECRET_KEY \
|
||||
/// SECRET_KEY=$(cat /run/secrets/SECRET_KEY) ...
|
||||
/// ```
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "super::env_vars_deserializer"
|
||||
)]
|
||||
#[partial_attr(serde(
|
||||
default,
|
||||
deserialize_with = "super::option_env_vars_deserializer"
|
||||
))]
|
||||
#[builder(default)]
|
||||
pub secret_args: Vec<EnvironmentVar>,
|
||||
|
||||
/// Docker labels
|
||||
#[serde(
|
||||
default,
|
||||
@@ -203,6 +226,7 @@ impl Default for BuildConfig {
|
||||
build_path: default_build_path(),
|
||||
dockerfile_path: default_dockerfile_path(),
|
||||
build_args: Default::default(),
|
||||
secret_args: Default::default(),
|
||||
labels: Default::default(),
|
||||
extra_args: Default::default(),
|
||||
use_buildx: Default::default(),
|
||||
|
||||
@@ -79,6 +79,13 @@ pub struct Env {
|
||||
/// Override `local_auth`
|
||||
pub monitor_local_auth: Option<bool>,
|
||||
|
||||
/// Override `google_oauth.enabled`
|
||||
pub monitor_google_oauth_enabled: Option<bool>,
|
||||
/// Override `google_oauth.id`
|
||||
pub monitor_google_oauth_id: Option<String>,
|
||||
/// Override `google_oauth.secret`
|
||||
pub monitor_google_oauth_secret: Option<String>,
|
||||
|
||||
/// Override `github_oauth.enabled`
|
||||
pub monitor_github_oauth_enabled: Option<bool>,
|
||||
/// Override `github_oauth.id`
|
||||
@@ -86,12 +93,19 @@ pub struct Env {
|
||||
/// Override `github_oauth.secret`
|
||||
pub monitor_github_oauth_secret: Option<String>,
|
||||
|
||||
/// Override `google_oauth.enabled`
|
||||
pub monitor_google_oauth_enabled: Option<bool>,
|
||||
/// Override `google_oauth.id`
|
||||
pub monitor_google_oauth_id: Option<String>,
|
||||
/// Override `google_oauth.secret`
|
||||
pub monitor_google_oauth_secret: Option<String>,
|
||||
/// Override `github_webhook_app.app_id`
|
||||
pub monitor_github_webhook_app_app_id: Option<i64>,
|
||||
/// Override `github_webhook_app.installations[i].id`. Accepts comma seperated list.
|
||||
///
|
||||
/// Note. Paired by index with values in `monitor_github_webhook_app_installations_namespaces`
|
||||
pub monitor_github_webhook_app_installations_ids: Option<Vec<i64>>,
|
||||
/// Override `github_webhook_app.installations[i].namespace`. Accepts comma seperated list.
|
||||
///
|
||||
/// Note. Paired by index with values in `monitor_github_webhook_app_installations_ids`
|
||||
pub monitor_github_webhook_app_installations_namespaces:
|
||||
Option<Vec<String>>,
|
||||
/// Override `github_webhook_app.pk_path`
|
||||
pub monitor_github_webhook_app_pk_path: Option<String>,
|
||||
|
||||
/// Override `mongo.uri`
|
||||
pub monitor_mongo_uri: Option<String>,
|
||||
@@ -183,15 +197,6 @@ fn default_config_path() -> String {
|
||||
/// ## default: 0 (pruning disabled)
|
||||
/// keep_stats_for_days = 0
|
||||
///
|
||||
/// ## token that has to be given to github during repo webhook config as the secret
|
||||
/// ## default: empty (none)
|
||||
/// github_webhook_secret = "your_random_webhook_secret"
|
||||
///
|
||||
/// ## an alternate base url that is used to recieve github webhook requests
|
||||
/// ## if empty or not specified, will use 'host' address as base
|
||||
/// ## default: empty (none)
|
||||
/// # github_webhook_base_url = "https://github-webhook.monitor.dev"
|
||||
///
|
||||
/// ## these will be used by the GUI to attach to builds.
|
||||
/// ## when attached to build, image will be pushed to repo under the specified organization.
|
||||
/// ## if empty, the "docker organization" config option will not be shown.
|
||||
@@ -210,15 +215,36 @@ fn default_config_path() -> String {
|
||||
/// ## default: false
|
||||
/// # local_auth = true
|
||||
///
|
||||
/// ## Use to configure google oauth
|
||||
/// # google_oauth.enabled = true
|
||||
/// # google_oauth.id = "your_google_client_id"
|
||||
/// # google_oauth.secret = "your_google_client_secret"
|
||||
///
|
||||
/// ## Use to configure github oauth
|
||||
/// # github_oauth.enabled = true
|
||||
/// # github_oauth.id = "your_github_client_id"
|
||||
/// # github_oauth.secret = "your_github_client_secret"
|
||||
///
|
||||
/// ## Use to configure google oauth
|
||||
/// # google_oauth.enabled = true
|
||||
/// # google_oauth.id = "your_google_client_id"
|
||||
/// # google_oauth.secret = "your_google_client_secret"
|
||||
/// ## an alternate base url that is used to recieve github webhook requests
|
||||
/// ## if empty or not specified, will use 'host' address as base
|
||||
/// ## default: empty (none)
|
||||
/// # github_webhook_base_url = "https://github-webhook.monitor.dev"
|
||||
///
|
||||
/// ## token that has to be given to github during repo webhook config as the secret
|
||||
/// ## default: empty (none)
|
||||
/// github_webhook_secret = "your_random_webhook_secret"
|
||||
///
|
||||
/// ## Configure github webhook app. Enables webhook management apis.
|
||||
/// # github_webhook_app.app_id = 1234455 # Find on the app page.
|
||||
/// # github_webhook_app.installations = [
|
||||
/// # ## Find the id after installing the app to user / organization. "namespace" is the username / organization name.
|
||||
/// # { id = 1234, namespace = "mbecker20" }
|
||||
/// # ]
|
||||
///
|
||||
/// ## Path to github webhook app private key.
|
||||
/// ## This is defaulted to `/github/private-key.pem`, and doesn't need to be changed if running in Docker.
|
||||
/// ## Just mount the private key pem file on the host to `/github/private-key.pem` in the container.
|
||||
/// # github_webhook_app.pk_path = "/path/to/pk.pem"
|
||||
///
|
||||
/// ## MUST comment back in some way to configure mongo.
|
||||
/// # mongo.uri = "mongodb://username:password@localhost:27017"
|
||||
@@ -315,25 +341,6 @@ pub struct CoreConfig {
|
||||
#[serde(default)]
|
||||
pub keep_alerts_for_days: u64,
|
||||
|
||||
/// Used to verify validity from github webhooks.
|
||||
/// Should be some secure hash maybe 20-40 chars.
|
||||
/// It needs to be given to github when configuring the webhook.
|
||||
#[serde(default)]
|
||||
pub github_webhook_secret: String,
|
||||
|
||||
/// Used to form the frontend listener url, if None will use 'host'.
|
||||
///
|
||||
/// This can be used if core sits on an internal network which is
|
||||
/// unreachable directly from the open internet.
|
||||
/// A reverse proxy in a public network (with its own DNS)
|
||||
/// can forward webhooks to the internal monitor
|
||||
pub github_webhook_base_url: Option<String>,
|
||||
|
||||
/// Allowed github orgs used with monitor.
|
||||
/// Default: none.
|
||||
#[serde(default)]
|
||||
pub github_organizations: Vec<String>,
|
||||
|
||||
/// Allowed docker orgs used with monitor.
|
||||
/// Default: none.
|
||||
#[serde(default)]
|
||||
@@ -355,13 +362,37 @@ pub struct CoreConfig {
|
||||
#[serde(default)]
|
||||
pub local_auth: bool,
|
||||
|
||||
/// Configure google oauth
|
||||
#[serde(default)]
|
||||
pub google_oauth: OauthCredentials,
|
||||
|
||||
/// Configure github oauth
|
||||
#[serde(default)]
|
||||
pub github_oauth: OauthCredentials,
|
||||
|
||||
/// Configure google oauth
|
||||
/// Used to verify validity from github webhooks.
|
||||
/// Should be some secure hash maybe 20-40 chars.
|
||||
/// It needs to be given to github when configuring the webhook.
|
||||
#[serde(default)]
|
||||
pub google_oauth: OauthCredentials,
|
||||
pub github_webhook_secret: String,
|
||||
|
||||
/// Used to form the frontend listener url, if None will use 'host'.
|
||||
///
|
||||
/// This can be used if core sits on an internal network which is
|
||||
/// unreachable directly from the open internet.
|
||||
/// A reverse proxy in a public network (with its own DNS)
|
||||
/// can forward webhooks to the internal monitor
|
||||
pub github_webhook_base_url: Option<String>,
|
||||
|
||||
/// Configure a Github Webhook app.
|
||||
/// Allows users to manage repo webhooks from within the Monitor UI.
|
||||
#[serde(default)]
|
||||
pub github_webhook_app: GithubWebhookAppConfig,
|
||||
|
||||
/// Allowed github orgs used with monitor.
|
||||
/// Default: none.
|
||||
#[serde(default)]
|
||||
pub github_organizations: Vec<String>,
|
||||
|
||||
/// Configure core mongo connection.
|
||||
///
|
||||
@@ -397,7 +428,8 @@ pub struct CoreConfig {
|
||||
|
||||
/// Configure aws ecr registries.
|
||||
#[serde(default, alias = "aws_ecr_registry")]
|
||||
pub aws_ecr_registries: HashMap<String, AwsEcrConfigWithCredentials>,
|
||||
pub aws_ecr_registries:
|
||||
HashMap<String, AwsEcrConfigWithCredentials>,
|
||||
}
|
||||
|
||||
fn default_title() -> String {
|
||||
@@ -565,4 +597,39 @@ impl AwsEcrConfig {
|
||||
account_id: config.account_id.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Provide configuration for a Github Webhook app.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct GithubWebhookAppConfig {
|
||||
/// Github app id
|
||||
pub app_id: i64,
|
||||
/// Configure the app installations on multiple accounts / organizations.
|
||||
pub installations: Vec<GithubWebhookAppInstallationConfig>,
|
||||
/// Private key path. Default: /github-private-key.pem.
|
||||
#[serde(default = "default_private_key_path")]
|
||||
pub pk_path: String,
|
||||
}
|
||||
|
||||
fn default_private_key_path() -> String {
|
||||
String::from("/github/private-key.pem")
|
||||
}
|
||||
|
||||
impl Default for GithubWebhookAppConfig {
|
||||
fn default() -> Self {
|
||||
GithubWebhookAppConfig {
|
||||
app_id: 0,
|
||||
installations: Default::default(),
|
||||
pk_path: default_private_key_path(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Provide configuration for a Github Webhook app installation.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct GithubWebhookAppInstallationConfig {
|
||||
/// The installation ID
|
||||
pub id: i64,
|
||||
/// The user or organization name
|
||||
pub namespace: String,
|
||||
}
|
||||
|
||||
@@ -309,21 +309,13 @@ pub fn conversions_from_str(
|
||||
.enumerate()
|
||||
.filter(|(_, line)| !line.is_empty() && !line.starts_with('#'))
|
||||
.map(|(i, line)| {
|
||||
let mut split = line.split('=');
|
||||
let local = split
|
||||
.next()
|
||||
.with_context(|| {
|
||||
format!("line {i} does not have 'local' key")
|
||||
})?
|
||||
.trim()
|
||||
.to_string();
|
||||
let (local, container) =
|
||||
line.split_once('=').with_context(|| {
|
||||
format!("line {i} missing assignment (=)")
|
||||
})?;
|
||||
let local = local.trim().to_string();
|
||||
// remove trailing comments
|
||||
let mut container_split = split
|
||||
.next()
|
||||
.with_context(|| {
|
||||
format!("line {i} does not have 'container' key")
|
||||
})?
|
||||
.split('#');
|
||||
let mut container_split = container.split('#');
|
||||
let container = container_split
|
||||
.next()
|
||||
.with_context(|| {
|
||||
@@ -618,20 +610,16 @@ pub fn term_signal_labels_from_str(
|
||||
.enumerate()
|
||||
.filter(|(_, line)| !line.is_empty() && !line.starts_with('#'))
|
||||
.map(|(i, line)| {
|
||||
let mut split = line.split('=');
|
||||
let signal = split
|
||||
.next()
|
||||
.with_context(|| format!("line {i} does not have signal"))?
|
||||
.trim()
|
||||
.parse::<TerminationSignal>()
|
||||
.with_context(|| {
|
||||
format!("line {i} does not have valid signal")
|
||||
let (signal, label) =
|
||||
line.split_once('=').with_context(|| {
|
||||
format!("line {i} missing assignment (=)")
|
||||
})?;
|
||||
let signal =
|
||||
signal.trim().parse::<TerminationSignal>().with_context(
|
||||
|| format!("line {i} does not have valid signal"),
|
||||
)?;
|
||||
// remove trailing comments
|
||||
let mut label_split = split
|
||||
.next()
|
||||
.with_context(|| format!("line {i} does not have label"))?
|
||||
.split('#');
|
||||
let mut label_split = label.split('#');
|
||||
let label = label_split
|
||||
.next()
|
||||
.with_context(|| format!("line {i} does not have label"))?
|
||||
|
||||
@@ -368,17 +368,13 @@ pub fn environment_vars_from_str(
|
||||
.enumerate()
|
||||
.filter(|(_, line)| !line.is_empty() && !line.starts_with('#'))
|
||||
.map(|(i, line)| {
|
||||
let mut split = line.split('=');
|
||||
let variable = split
|
||||
.next()
|
||||
.with_context(|| format!("line {i} does not have variable"))?
|
||||
.trim()
|
||||
.to_string();
|
||||
let (variable, value) =
|
||||
line.split_once('=').with_context(|| {
|
||||
format!("line {i} missing assignment (=)")
|
||||
})?;
|
||||
let variable = variable.trim().to_string();
|
||||
// remove trailing comments
|
||||
let mut value_split = split
|
||||
.next()
|
||||
.with_context(|| format!("line {i} does not have value"))?
|
||||
.split('#');
|
||||
let mut value_split = value.split('#');
|
||||
let value = value_split
|
||||
.next()
|
||||
.with_context(|| format!("line {i} does not have value"))?
|
||||
|
||||
@@ -155,11 +155,12 @@ pub struct ServerHealth {
|
||||
Debug,
|
||||
Clone,
|
||||
Copy,
|
||||
PartialEq,
|
||||
Eq,
|
||||
PartialOrd,
|
||||
Default,
|
||||
Display,
|
||||
EnumString,
|
||||
PartialEq,
|
||||
Eq,
|
||||
)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
#[strum(serialize_all = "UPPERCASE")]
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{
|
||||
@@ -6,7 +8,7 @@ use super::{
|
||||
permission::PermissionLevel, procedure::PartialProcedureConfig,
|
||||
repo::PartialRepoConfig, server::PartialServerConfig,
|
||||
server_template::PartialServerTemplateConfig,
|
||||
sync::PartialResourceSyncConfig, update::ResourceTarget,
|
||||
sync::PartialResourceSyncConfig, update::{ResourceTarget, ResourceTargetVariant},
|
||||
variable::Variable,
|
||||
};
|
||||
|
||||
@@ -137,13 +139,26 @@ pub struct UserGroupToml {
|
||||
#[serde(default)]
|
||||
pub users: Vec<String>,
|
||||
|
||||
/// Give the user group elevated permissions on all resources of a certain type
|
||||
#[serde(default)]
|
||||
pub all: HashMap<ResourceTargetVariant, PermissionLevel>,
|
||||
|
||||
/// Permissions given to the group
|
||||
#[serde(default, rename = "permission")]
|
||||
#[serde(default, alias = "permission")]
|
||||
pub permissions: Vec<PermissionToml>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PermissionToml {
|
||||
/// Id can be:
|
||||
/// - resource name. `id = "abcd-build"`
|
||||
/// - regex matching resource names. `id = "\^(.+)-build-([0-9]+)$\"`
|
||||
pub target: ResourceTarget,
|
||||
|
||||
/// The permission level:
|
||||
/// - None
|
||||
/// - Read
|
||||
/// - Execute
|
||||
/// - Write
|
||||
pub level: PermissionLevel,
|
||||
}
|
||||
|
||||
@@ -11,7 +11,8 @@ use crate::entities::{
|
||||
use super::{
|
||||
alerter::Alerter, build::Build, builder::Builder,
|
||||
deployment::Deployment, procedure::Procedure, repo::Repo,
|
||||
server::Server, server_template::ServerTemplate, Version,
|
||||
server::Server, server_template::ServerTemplate,
|
||||
sync::ResourceSync, Version,
|
||||
};
|
||||
|
||||
/// Represents an action performed by Monitor.
|
||||
@@ -188,18 +189,16 @@ impl Log {
|
||||
/// Used to reference a specific resource across all resource types
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
Serialize,
|
||||
Deserialize,
|
||||
Debug,
|
||||
Clone,
|
||||
PartialEq,
|
||||
Eq,
|
||||
Hash,
|
||||
Serialize,
|
||||
Deserialize,
|
||||
EnumVariants,
|
||||
)]
|
||||
#[variant_derive(
|
||||
Serialize,
|
||||
Deserialize,
|
||||
Debug,
|
||||
Clone,
|
||||
Copy,
|
||||
@@ -207,6 +206,9 @@ impl Log {
|
||||
Eq,
|
||||
PartialOrd,
|
||||
Ord,
|
||||
Hash,
|
||||
Serialize,
|
||||
Deserialize,
|
||||
Display,
|
||||
EnumString,
|
||||
AsRefStr
|
||||
@@ -303,6 +305,12 @@ impl From<&ServerTemplate> for ResourceTarget {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&ResourceSync> for ResourceTarget {
|
||||
fn from(resource_sync: &ResourceSync) -> Self {
|
||||
Self::ResourceSync(resource_sync.id.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// An update's status
|
||||
#[typeshare]
|
||||
#[derive(
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
use std::sync::OnceLock;
|
||||
use std::{collections::HashMap, sync::OnceLock};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use typeshare::typeshare;
|
||||
|
||||
use crate::entities::{MongoId, I64};
|
||||
|
||||
use super::{
|
||||
permission::PermissionLevel, update::ResourceTargetVariant,
|
||||
};
|
||||
|
||||
#[typeshare]
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
|
||||
#[cfg_attr(
|
||||
@@ -54,25 +58,13 @@ pub struct User {
|
||||
#[serde(default)]
|
||||
pub last_update_view: I64,
|
||||
|
||||
/// Recently viewed server ids
|
||||
/// Recently viewed ids
|
||||
#[serde(default)]
|
||||
pub recent_servers: Vec<String>,
|
||||
pub recents: HashMap<ResourceTargetVariant, Vec<String>>,
|
||||
|
||||
/// Recently viewed deployment ids
|
||||
/// Give the user elevated permissions on all resources of a certain type
|
||||
#[serde(default)]
|
||||
pub recent_deployments: Vec<String>,
|
||||
|
||||
/// Recently viewed build ids
|
||||
#[serde(default)]
|
||||
pub recent_builds: Vec<String>,
|
||||
|
||||
/// Recently viewed repo ids
|
||||
#[serde(default)]
|
||||
pub recent_repos: Vec<String>,
|
||||
|
||||
/// Recently viewed procedure ids
|
||||
#[serde(default)]
|
||||
pub recent_procedures: Vec<String>,
|
||||
pub all: HashMap<ResourceTargetVariant, PermissionLevel>,
|
||||
|
||||
#[serde(default)]
|
||||
pub updated_at: I64,
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use typeshare::typeshare;
|
||||
|
||||
use super::{MongoId, I64};
|
||||
use super::{permission::PermissionLevel, update::ResourceTargetVariant, MongoId, I64};
|
||||
|
||||
/// Permission users at the group level.
|
||||
///
|
||||
/// All users that are part of a group inherit the group's permissions.
|
||||
/// A user can be a part of multiple groups. A user's permission on a particular resource
|
||||
/// will be resolved to be the maximum permission level between the user's own permissions and
|
||||
/// any groups they are a part of.
|
||||
#[typeshare]
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
|
||||
#[cfg_attr(
|
||||
@@ -21,13 +29,19 @@ pub struct UserGroup {
|
||||
)]
|
||||
pub id: MongoId,
|
||||
|
||||
/// A name for the user group
|
||||
#[cfg_attr(feature = "mongo", unique_index)]
|
||||
pub name: String,
|
||||
|
||||
/// User ids
|
||||
/// User ids of group members
|
||||
#[cfg_attr(feature = "mongo", index)]
|
||||
pub users: Vec<String>,
|
||||
|
||||
/// Give the user group elevated permissions on all resources of a certain type
|
||||
#[serde(default)]
|
||||
pub all: HashMap<ResourceTargetVariant, PermissionLevel>,
|
||||
|
||||
/// Unix time (ms) when user group last updated
|
||||
#[serde(default)]
|
||||
pub updated_at: I64,
|
||||
}
|
||||
|
||||
@@ -21,12 +21,13 @@ export type ReadResponses = {
|
||||
GetAvailableAwsEcrLabels: Types.GetAvailableAwsEcrLabelsResponse;
|
||||
|
||||
// ==== USER ====
|
||||
ListUsers: Types.ListUsersResponse;
|
||||
GetUsername: Types.GetUsernameResponse;
|
||||
GetPermissionLevel: Types.GetPermissionLevelResponse;
|
||||
FindUser: Types.FindUserResponse;
|
||||
ListUsers: Types.ListUsersResponse;
|
||||
ListApiKeys: Types.ListApiKeysResponse;
|
||||
ListApiKeysForServiceUser: Types.ListApiKeysForServiceUserResponse;
|
||||
ListPermissions: Types.ListPermissionsResponse;
|
||||
GetPermissionLevel: Types.GetPermissionLevelResponse;
|
||||
ListUserTargetPermissions: Types.ListUserTargetPermissionsResponse;
|
||||
|
||||
// ==== USER GROUP ====
|
||||
@@ -45,15 +46,13 @@ export type ReadResponses = {
|
||||
|
||||
// ==== SERVER TEMPLATE ====
|
||||
GetServerTemplate: Types.GetServerTemplateResponse;
|
||||
GetServerTemplatesSummary: Types.GetServerTemplatesSummaryResponse;
|
||||
ListServerTemplates: Types.ListServerTemplatesResponse;
|
||||
ListFullServerTemplates: Types.ListFullServerTemplatesResponse;
|
||||
GetServerTemplatesSummary: Types.GetServerTemplatesSummaryResponse;
|
||||
|
||||
// ==== SERVER ====
|
||||
GetServersSummary: Types.GetServersSummaryResponse;
|
||||
GetServer: Types.GetServerResponse;
|
||||
ListServers: Types.ListServersResponse;
|
||||
ListFullServers: Types.ListFullServersResponse;
|
||||
GetServerState: Types.GetServerStateResponse;
|
||||
GetPeripheryVersion: Types.GetPeripheryVersionResponse;
|
||||
GetSystemInformation: Types.GetSystemInformationResponse;
|
||||
@@ -64,27 +63,30 @@ export type ReadResponses = {
|
||||
GetHistoricalServerStats: Types.GetHistoricalServerStatsResponse;
|
||||
GetAvailableAccounts: Types.GetAvailableAccountsResponse;
|
||||
GetAvailableSecrets: Types.GetAvailableSecretsResponse;
|
||||
ListServers: Types.ListServersResponse;
|
||||
ListFullServers: Types.ListFullServersResponse;
|
||||
|
||||
// ==== DEPLOYMENT ====
|
||||
GetDeploymentsSummary: Types.GetDeploymentsSummaryResponse;
|
||||
GetDeployment: Types.GetDeploymentResponse;
|
||||
ListDeployments: Types.ListDeploymentsResponse;
|
||||
ListFullDeployments: Types.ListFullDeploymentsResponse;
|
||||
GetDeploymentContainer: Types.GetDeploymentContainerResponse;
|
||||
GetDeploymentActionState: Types.GetDeploymentActionStateResponse;
|
||||
GetDeploymentStats: Types.GetDeploymentStatsResponse;
|
||||
GetLog: Types.GetLogResponse;
|
||||
SearchLog: Types.SearchLogResponse;
|
||||
ListDeployments: Types.ListDeploymentsResponse;
|
||||
ListFullDeployments: Types.ListFullDeploymentsResponse;
|
||||
ListCommonDeploymentExtraArgs: Types.ListCommonDeploymentExtraArgsResponse;
|
||||
|
||||
// ==== BUILD ====
|
||||
GetBuildsSummary: Types.GetBuildsSummaryResponse;
|
||||
GetBuild: Types.GetBuildResponse;
|
||||
ListBuilds: Types.ListBuildsResponse;
|
||||
ListFullBuilds: Types.ListFullBuildsResponse;
|
||||
GetBuildActionState: Types.GetBuildActionStateResponse;
|
||||
GetBuildMonthlyStats: Types.GetBuildMonthlyStatsResponse;
|
||||
GetBuildVersions: Types.GetBuildVersionsResponse;
|
||||
GetBuildWebhookEnabled: Types.GetBuildWebhookEnabledResponse;
|
||||
ListBuilds: Types.ListBuildsResponse;
|
||||
ListFullBuilds: Types.ListFullBuildsResponse;
|
||||
ListCommonBuildExtraArgs: Types.ListCommonBuildExtraArgsResponse;
|
||||
ListGithubOrganizations: Types.ListGithubOrganizationsResponse;
|
||||
ListDockerOrganizations: Types.ListDockerOrganizationsResponse;
|
||||
@@ -92,16 +94,17 @@ export type ReadResponses = {
|
||||
// ==== REPO ====
|
||||
GetReposSummary: Types.GetReposSummaryResponse;
|
||||
GetRepo: Types.GetRepoResponse;
|
||||
GetRepoActionState: Types.GetRepoActionStateResponse;
|
||||
GetRepoWebhooksEnabled: Types.GetRepoWebhooksEnabledResponse;
|
||||
ListRepos: Types.ListReposResponse;
|
||||
ListFullRepos: Types.ListFullReposResponse;
|
||||
GetRepoActionState: Types.GetRepoActionStateResponse;
|
||||
|
||||
// ==== BUILDER ====
|
||||
GetBuildersSummary: Types.GetBuildersSummaryResponse;
|
||||
GetBuilder: Types.GetBuilderResponse;
|
||||
GetBuilderAvailableAccounts: Types.GetBuilderAvailableAccountsResponse;
|
||||
ListBuilders: Types.ListBuildersResponse;
|
||||
ListFullBuilders: Types.ListFullBuildersResponse;
|
||||
GetBuilderAvailableAccounts: Types.GetBuilderAvailableAccountsResponse;
|
||||
|
||||
// ==== ALERTER ====
|
||||
GetAlertersSummary: Types.GetAlertersSummaryResponse;
|
||||
@@ -112,9 +115,10 @@ export type ReadResponses = {
|
||||
// ==== SYNC ====
|
||||
GetResourceSyncsSummary: Types.GetResourceSyncsSummaryResponse;
|
||||
GetResourceSync: Types.GetResourceSyncResponse;
|
||||
GetResourceSyncActionState: Types.GetResourceSyncActionStateResponse;
|
||||
GetSyncWebhooksEnabled: Types.GetSyncWebhooksEnabledResponse;
|
||||
ListResourceSyncs: Types.ListResourceSyncsResponse;
|
||||
ListFullResourceSyncs: Types.ListFullResourceSyncsResponse;
|
||||
GetResourceSyncActionState: Types.GetResourceSyncActionStateResponse;
|
||||
|
||||
// ==== TOML ====
|
||||
ExportAllResourcesToToml: Types.ExportAllResourcesToTomlResponse;
|
||||
@@ -158,6 +162,7 @@ export type WriteResponses = {
|
||||
|
||||
// ==== PERMISSIONS ====
|
||||
UpdateUserBasePermissions: Types.UpdateUserBasePermissionsResponse;
|
||||
UpdatePermissionOnResourceType: Types.UpdatePermissionOnResourceTypeResponse;
|
||||
UpdatePermissionOnTarget: Types.UpdatePermissionOnTargetResponse;
|
||||
|
||||
// ==== DESCRIPTION ====
|
||||
@@ -184,6 +189,8 @@ export type WriteResponses = {
|
||||
CopyBuild: Types.Build;
|
||||
DeleteBuild: Types.Build;
|
||||
UpdateBuild: Types.Build;
|
||||
CreateBuildWebhook: Types.CreateBuildWebhookResponse;
|
||||
DeleteBuildWebhook: Types.DeleteBuildWebhookResponse;
|
||||
|
||||
// ==== BUILDER ====
|
||||
CreateBuilder: Types.Builder;
|
||||
@@ -202,6 +209,8 @@ export type WriteResponses = {
|
||||
CopyRepo: Types.Repo;
|
||||
DeleteRepo: Types.Repo;
|
||||
UpdateRepo: Types.Repo;
|
||||
CreateRepoWebhook: Types.CreateRepoWebhookResponse;
|
||||
DeleteRepoWebhook: Types.DeleteRepoWebhookResponse;
|
||||
|
||||
// ==== ALERTER ====
|
||||
CreateAlerter: Types.Alerter;
|
||||
@@ -221,6 +230,8 @@ export type WriteResponses = {
|
||||
DeleteResourceSync: Types.ResourceSync;
|
||||
UpdateResourceSync: Types.ResourceSync;
|
||||
RefreshResourceSyncPending: Types.ResourceSync;
|
||||
CreateSyncWebhook: Types.CreateSyncWebhookResponse;
|
||||
DeleteSyncWebhook: Types.DeleteSyncWebhookResponse;
|
||||
|
||||
// ==== TAG ====
|
||||
CreateTag: Types.Tag;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user