crates/server: enhance auth middleware and error responses
Signed-off-by: NotAShelf <raf@notashelf.dev> Change-Id: I48a780779d884c4a7730347f920b91216a6a6964
This commit is contained in:
parent
000fb8994f
commit
92153bf9aa
8 changed files with 272 additions and 99 deletions
|
|
@ -6,9 +6,7 @@ use axum::{
|
|||
response::{IntoResponse, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
use fc_common::{
|
||||
Build, BuildProduct, BuildStatus, BuildStep, CreateBuild, PaginatedResponse, PaginationParams,
|
||||
};
|
||||
use fc_common::{Build, BuildProduct, BuildStep, PaginatedResponse, PaginationParams};
|
||||
use serde::Deserialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
|
|
@ -155,44 +153,17 @@ async fn restart_build(
|
|||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<Build>, ApiError> {
|
||||
check_role(&extensions, &["restart-jobs"])?;
|
||||
let original = fc_common::repo::builds::get(&state.pool, id)
|
||||
let build = fc_common::repo::builds::restart(&state.pool, id)
|
||||
.await
|
||||
.map_err(ApiError)?;
|
||||
|
||||
// Can only restart completed or failed builds
|
||||
if original.status != BuildStatus::Failed
|
||||
&& original.status != BuildStatus::Completed
|
||||
&& original.status != BuildStatus::Cancelled
|
||||
{
|
||||
return Err(ApiError(fc_common::CiError::Validation(
|
||||
"Can only restart failed, completed, or cancelled builds".to_string(),
|
||||
)));
|
||||
}
|
||||
|
||||
// Create a new build with the same parameters
|
||||
let new_build = fc_common::repo::builds::create(
|
||||
&state.pool,
|
||||
CreateBuild {
|
||||
evaluation_id: original.evaluation_id,
|
||||
job_name: original.job_name.clone(),
|
||||
drv_path: original.drv_path.clone(),
|
||||
system: original.system.clone(),
|
||||
outputs: original.outputs.clone(),
|
||||
is_aggregate: Some(original.is_aggregate),
|
||||
constituents: original.constituents.clone(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(ApiError)?;
|
||||
|
||||
tracing::info!(
|
||||
original_id = %id,
|
||||
new_id = %new_build.id,
|
||||
job = %original.job_name,
|
||||
build_id = %id,
|
||||
job = %build.job_name,
|
||||
"Build restarted"
|
||||
);
|
||||
|
||||
Ok(Json(new_build))
|
||||
Ok(Json(build))
|
||||
}
|
||||
|
||||
async fn bump_build(
|
||||
|
|
|
|||
|
|
@ -170,9 +170,9 @@ async fn sign_narinfo(narinfo: &str, key_file: &std::path::Path) -> String {
|
|||
.output()
|
||||
.await;
|
||||
|
||||
if let Ok(o) = re_output {
|
||||
if let Ok(parsed) = serde_json::from_slice::<serde_json::Value>(&o.stdout) {
|
||||
if let Some(sigs) = parsed
|
||||
if let Ok(o) = re_output
|
||||
&& let Ok(parsed) = serde_json::from_slice::<serde_json::Value>(&o.stdout)
|
||||
&& let Some(sigs) = parsed
|
||||
.as_array()
|
||||
.and_then(|a| a.first())
|
||||
.and_then(|e| e.get("signatures"))
|
||||
|
|
@ -187,8 +187,6 @@ async fn sign_narinfo(narinfo: &str, key_file: &std::path::Path) -> String {
|
|||
return format!("{narinfo}{}\n", sig_lines.join("\n"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
narinfo.to_string()
|
||||
}
|
||||
_ => narinfo.to_string(),
|
||||
|
|
|
|||
|
|
@ -316,6 +316,14 @@ struct AdminTemplate {
|
|||
auth_name: String,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "project_setup.html")]
|
||||
#[allow(dead_code)]
|
||||
struct ProjectSetupTemplate {
|
||||
is_admin: bool,
|
||||
auth_name: String,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "login.html")]
|
||||
struct LoginTemplate {
|
||||
|
|
@ -353,14 +361,13 @@ async fn home(State(state): State<AppState>, extensions: Extensions) -> Html<Str
|
|||
fc_common::repo::evaluations::list_filtered(&state.pool, Some(js.id), None, 1, 0)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
if let Some(e) = js_evals.into_iter().next() {
|
||||
if last_eval
|
||||
if let Some(e) = js_evals.into_iter().next()
|
||||
&& last_eval
|
||||
.as_ref()
|
||||
.map_or(true, |le| e.evaluation_time > le.evaluation_time)
|
||||
.is_none_or(|le| e.evaluation_time > le.evaluation_time)
|
||||
{
|
||||
last_eval = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
let (status, class, time) = match &last_eval {
|
||||
Some(e) => {
|
||||
|
|
@ -884,6 +891,19 @@ async fn admin_page(State(state): State<AppState>, extensions: Extensions) -> Ht
|
|||
)
|
||||
}
|
||||
|
||||
// --- Setup Wizard ---
|
||||
|
||||
async fn project_setup_page(extensions: Extensions) -> Html<String> {
|
||||
let tmpl = ProjectSetupTemplate {
|
||||
is_admin: is_admin(&extensions),
|
||||
auth_name: auth_name(&extensions),
|
||||
};
|
||||
Html(
|
||||
tmpl.render()
|
||||
.unwrap_or_else(|e| format!("Template error: {e}")),
|
||||
)
|
||||
}
|
||||
|
||||
// --- Login / Logout ---
|
||||
|
||||
async fn login_page() -> Html<String> {
|
||||
|
|
@ -950,7 +970,28 @@ async fn login_action(State(state): State<AppState>, Form(form): Form<LoginForm>
|
|||
}
|
||||
}
|
||||
|
||||
async fn logout_action() -> Response {
|
||||
async fn logout_action(State(state): State<AppState>, request: axum::extract::Request) -> Response {
|
||||
// Remove server-side session
|
||||
if let Some(cookie_header) = request
|
||||
.headers()
|
||||
.get("cookie")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
&& let Some(session_id) = cookie_header
|
||||
.split(';')
|
||||
.filter_map(|pair| {
|
||||
let pair = pair.trim();
|
||||
let (k, v) = pair.split_once('=')?;
|
||||
if k.trim() == "fc_session" {
|
||||
Some(v.trim().to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.next()
|
||||
{
|
||||
state.sessions.remove(&session_id);
|
||||
}
|
||||
|
||||
let cookie = "fc_session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0";
|
||||
(
|
||||
[(axum::http::header::SET_COOKIE, cookie.to_string())],
|
||||
|
|
@ -966,6 +1007,7 @@ pub fn router(state: AppState) -> Router<AppState> {
|
|||
.route("/logout", axum::routing::post(logout_action))
|
||||
.route("/", get(home))
|
||||
.route("/projects", get(projects_page))
|
||||
.route("/projects/new", get(project_setup_page))
|
||||
.route("/project/{id}", get(project_page))
|
||||
.route("/jobset/{id}", get(jobset_page))
|
||||
.route("/evaluations", get(evaluations_page))
|
||||
|
|
|
|||
|
|
@ -5,7 +5,8 @@ use axum::{
|
|||
routing::{get, post},
|
||||
};
|
||||
use fc_common::{CreateEvaluation, Evaluation, PaginatedResponse, PaginationParams, Validate};
|
||||
use serde::Deserialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::auth_middleware::RequireRoles;
|
||||
|
|
@ -85,9 +86,127 @@ async fn trigger_evaluation(
|
|||
Ok(Json(evaluation))
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct CompareParams {
|
||||
to: Uuid,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct EvalComparison {
|
||||
from_id: Uuid,
|
||||
to_id: Uuid,
|
||||
new_jobs: Vec<JobDiff>,
|
||||
removed_jobs: Vec<JobDiff>,
|
||||
changed_jobs: Vec<JobChange>,
|
||||
unchanged_count: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct JobDiff {
|
||||
job_name: String,
|
||||
system: Option<String>,
|
||||
drv_path: String,
|
||||
status: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct JobChange {
|
||||
job_name: String,
|
||||
system: Option<String>,
|
||||
old_drv: String,
|
||||
new_drv: String,
|
||||
old_status: String,
|
||||
new_status: String,
|
||||
}
|
||||
|
||||
async fn compare_evaluations(
|
||||
State(state): State<AppState>,
|
||||
Path(id): Path<Uuid>,
|
||||
Query(params): Query<CompareParams>,
|
||||
) -> Result<Json<EvalComparison>, ApiError> {
|
||||
// Verify both evaluations exist
|
||||
let _from_eval = fc_common::repo::evaluations::get(&state.pool, id)
|
||||
.await
|
||||
.map_err(ApiError)?;
|
||||
let _to_eval = fc_common::repo::evaluations::get(&state.pool, params.to)
|
||||
.await
|
||||
.map_err(ApiError)?;
|
||||
|
||||
let from_builds = fc_common::repo::builds::list_for_evaluation(&state.pool, id)
|
||||
.await
|
||||
.map_err(ApiError)?;
|
||||
let to_builds = fc_common::repo::builds::list_for_evaluation(&state.pool, params.to)
|
||||
.await
|
||||
.map_err(ApiError)?;
|
||||
|
||||
let from_map: HashMap<&str, &fc_common::Build> = from_builds
|
||||
.iter()
|
||||
.map(|b| (b.job_name.as_str(), b))
|
||||
.collect();
|
||||
let to_map: HashMap<&str, &fc_common::Build> =
|
||||
to_builds.iter().map(|b| (b.job_name.as_str(), b)).collect();
|
||||
|
||||
let mut new_jobs = Vec::new();
|
||||
let mut removed_jobs = Vec::new();
|
||||
let mut changed_jobs = Vec::new();
|
||||
let mut unchanged_count = 0;
|
||||
|
||||
// Jobs in `to` but not in `from` are new
|
||||
for (name, build) in &to_map {
|
||||
if !from_map.contains_key(name) {
|
||||
new_jobs.push(JobDiff {
|
||||
job_name: name.to_string(),
|
||||
system: build.system.clone(),
|
||||
drv_path: build.drv_path.clone(),
|
||||
status: format!("{:?}", build.status),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Jobs in `from` but not in `to` are removed
|
||||
for (name, build) in &from_map {
|
||||
if !to_map.contains_key(name) {
|
||||
removed_jobs.push(JobDiff {
|
||||
job_name: name.to_string(),
|
||||
system: build.system.clone(),
|
||||
drv_path: build.drv_path.clone(),
|
||||
status: format!("{:?}", build.status),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Jobs in both: compare derivation paths
|
||||
for (name, from_build) in &from_map {
|
||||
if let Some(to_build) = to_map.get(name) {
|
||||
if from_build.drv_path != to_build.drv_path {
|
||||
changed_jobs.push(JobChange {
|
||||
job_name: name.to_string(),
|
||||
system: to_build.system.clone(),
|
||||
old_drv: from_build.drv_path.clone(),
|
||||
new_drv: to_build.drv_path.clone(),
|
||||
old_status: format!("{:?}", from_build.status),
|
||||
new_status: format!("{:?}", to_build.status),
|
||||
});
|
||||
} else {
|
||||
unchanged_count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Json(EvalComparison {
|
||||
from_id: id,
|
||||
to_id: params.to,
|
||||
new_jobs,
|
||||
removed_jobs,
|
||||
changed_jobs,
|
||||
unchanged_count,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn router() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/evaluations", get(list_evaluations))
|
||||
.route("/evaluations/{id}", get(get_evaluation))
|
||||
.route("/evaluations/{id}/compare", get(compare_evaluations))
|
||||
.route("/evaluations/trigger", post(trigger_evaluation))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -96,13 +96,12 @@ async fn stream_build_log(
|
|||
consecutive_empty += 1;
|
||||
if consecutive_empty > 5 {
|
||||
// Check build status
|
||||
if let Ok(b) = fc_common::repo::builds::get(&pool, build_id).await {
|
||||
if b.status != fc_common::models::BuildStatus::Running
|
||||
if let Ok(b) = fc_common::repo::builds::get(&pool, build_id).await
|
||||
&& b.status != fc_common::models::BuildStatus::Running
|
||||
&& b.status != fc_common::models::BuildStatus::Pending {
|
||||
yield Ok(Event::default().event("done").data("Build completed"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
consecutive_empty = 0;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue