From c6dd52c700ed7a9e714d296d45c084c450f7643c Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Sun, 15 Nov 2026 14:57:46 +0700 Subject: [PATCH] feat: rename restore targets and show the application next to them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - PUT /api/v1/restore-targets/:id changes only the display name (admin, validated, audited); ids, identity, relations and jobs are untouched - Relations console: Application column, inline rename, application in the target pickers - Refresh screen: the application on each card - registering a target suggests ' · ' Co-Authored-By: Claude Sonnet 5.5 --- crates/tessera-hub/src/api/access_tests.rs | 3 +- crates/tessera-hub/src/api/refresh_tests.rs | 107 ++++++++++++++++++ crates/tessera-hub/src/api/restore.rs | 38 +++++++ crates/tessera-hub/src/db/restore.rs | 11 ++ docs/DATABASE-CAPTURE.md | 4 +- docs/auth-endpoint-contract.md | 1 + web/src/api.ts | 1 + .../reconstitute/DatabaseRestore.tsx | 6 +- .../reconstitute/ReconstituteWizard.tsx | 2 +- .../reconstitute/RestoreTargetForm.tsx | 17 ++- web/src/components/refresh/RefreshView.tsx | 1 + .../components/relations/RelationsView.tsx | 52 +++++++-- 12 files changed, 225 insertions(+), 18 deletions(-) diff --git a/crates/tessera-hub/src/api/access_tests.rs b/crates/tessera-hub/src/api/access_tests.rs index 5b9efbf..9c9fda6 100644 --- a/crates/tessera-hub/src/api/access_tests.rs +++ b/crates/tessera-hub/src/api/access_tests.rs @@ -349,7 +349,7 @@ fn recipe(w: &World, row: &Row) -> (String, Option) { } "/api/v1/refresh-runs/:id" => Uuid::parse_str(&w.run).unwrap(), "/api/v1/orbits/:id/environment" => a.orbit, - "/api/v1/restore-targets/:id/environment" => a.target, + "/api/v1/restore-targets/:id" | "/api/v1/restore-targets/:id/environment" => a.target, "/api/v1/relations/:id" | "/api/v1/relations/:id/access" | "/api/v1/relations/:id/access/:grant" => a.relation, @@ -374,6 +374,7 @@ fn recipe(w: &World, row: &Row) -> (String, Option) { ("POST", "/api/v1/orbits") => Some( json!({"name": "created", "provider": "filesystem", "source": "filesystem", "provider_config": {"path": "/nonexistent"}}), ), + ("PUT", "/api/v1/restore-targets/:id") => Some(json!({"name": "renamed"})), ("PUT", "/api/v1/orbits/:id/retention") => Some(json!({"decay_preset": "week-of-dailies"})), ("PUT", "/api/v1/orbits/:id/outpost") => Some(json!({"outpost_id": a.outpost})), ("POST", "/api/v1/reconstitute") => { diff --git a/crates/tessera-hub/src/api/refresh_tests.rs b/crates/tessera-hub/src/api/refresh_tests.rs index 87bdecc..3eb8a37 100644 --- a/crates/tessera-hub/src/api/refresh_tests.rs +++ b/crates/tessera-hub/src/api/refresh_tests.rs @@ -1739,3 +1739,110 @@ async fn reconciling_a_job_that_needs_no_recovery_says_so() { .await; assert_eq!(status, StatusCode::BAD_REQUEST); } + +// ---- naming restore targets ---- + +#[tokio::test] +async fn an_administrator_can_rename_a_target_and_everything_that_points_at_it_keeps_working() { + let lab = fresh().await; + let admin = lab.admin(); + let (qa, _) = lab.refresher("qa"); + let uri = format!("/api/v1/restore-targets/{}", lab.target); + let (status, _) = lab + .send( + &admin, + "PUT", + &uri, + Some(json!({"name": "presensi · dev · app_dev"})), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + + let (_, overview) = lab.send(&admin, "GET", "/api/v1/relations", None).await; + let target = &overview["targets"][0]; + assert_eq!(target["name"], "presensi · dev · app_dev"); + assert_eq!(target["id"], lab.target.to_string()); + assert_eq!( + target["identity"]["database"], "staging_app", + "identity is untouched" + ); + let relation = &overview["relations"][0]; + assert_eq!(relation["target_name"], "presensi · dev · app_dev"); + assert_eq!( + relation["id"], lab.relation, + "the relation is the same relation" + ); + assert!(relation["usable"].as_bool().unwrap()); + // the person who refreshes through it sees the new name, and a run through it still starts + let (_, mine) = lab + .send(&qa, "GET", "/api/v1/refresh-relations", None) + .await; + assert_eq!(mine[0]["target_name"], "presensi · dev · app_dev"); + let confirmation = format!( + "REFRESH prod-db TO presensi · dev · app_dev v{}", + lab.relation_version + ); + let (status, body) = lab + .send(&qa, "POST", "/api/v1/refresh-runs", Some(json!({"relation_id": lab.relation, "confirmation": confirmation, "idempotency_key": "after-rename"}))) + .await; + assert_eq!(status, StatusCode::ACCEPTED, "{body}"); + assert!(lab + .audit_log() + .iter() + .any(|(event, detail)| event == "restore_target.renamed" + && detail.contains(&lab.target.to_string()))); +} + +#[tokio::test] +async fn a_target_name_is_validated_like_a_registration_and_only_administrators_set_it() { + let lab = fresh().await; + let admin = lab.admin(); + let uri = format!("/api/v1/restore-targets/{}", lab.target); + for name in ["", " ", &"x".repeat(129), "bad\nname", "tab\tname"] { + let (status, _) = lab + .send(&admin, "PUT", &uri, Some(json!({"name": name}))) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{name:?}"); + } + let (status, _) = lab + .send( + &admin, + "PUT", + &uri, + Some(json!({"name": "ok", "identity": {}})), + ) + .await; + assert_eq!( + status, + StatusCode::UNPROCESSABLE_ENTITY, + "only the name is editable" + ); + let unknown = format!("/api/v1/restore-targets/{}", Uuid::new_v4()); + assert_eq!( + lab.send(&admin, "PUT", &unknown, Some(json!({"name": "ok"}))) + .await + .0, + StatusCode::NOT_FOUND + ); + let (qa, _) = lab.refresher("qa"); + let status = lab + .send(&qa, "PUT", &uri, Some(json!({"name": "mine"}))) + .await + .0; + assert!( + status == StatusCode::FORBIDDEN || status == StatusCode::NOT_FOUND, + "{status}" + ); + let (_, overview) = lab.send(&admin, "GET", "/api/v1/relations", None).await; + assert_eq!( + overview["targets"][0]["name"], "staging-db", + "nothing above changed it" + ); + // the longest allowed name is fine + assert_eq!( + lab.send(&admin, "PUT", &uri, Some(json!({"name": "y".repeat(128)}))) + .await + .0, + StatusCode::NO_CONTENT + ); +} diff --git a/crates/tessera-hub/src/api/restore.rs b/crates/tessera-hub/src/api/restore.rs index 038aa0a..e8d24e0 100644 --- a/crates/tessera-hub/src/api/restore.rs +++ b/crates/tessera-hub/src/api/restore.rs @@ -27,6 +27,7 @@ use uuid::Uuid; pub(super) fn routes() -> Router { Router::new() .route("/api/v1/restore-targets", post(register)) + .route("/api/v1/restore-targets/:id", axum::routing::put(rename)) .route("/api/v1/capture-profiles/:id/restore-targets", get(targets)) .route( "/api/v1/snapshots/:id/restore-targets", @@ -82,6 +83,43 @@ async fn register( Ok((StatusCode::CREATED, Json(target))) } +#[derive(serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct Rename { + name: String, +} + +/// Same rules as at registration: not blank, at most 128 characters, no control characters. +fn valid_target_name(name: &str) -> bool { + !name.trim().is_empty() && name.len() <= 128 && !name.chars().any(char::is_control) +} + +async fn rename( + ConnectInfo(peer): ConnectInfo, + State(state): State, + headers: HeaderMap, + Path(id): Path, + Json(body): Json, +) -> Result { + let actor = admin_write(&state, peer, &headers)?; + let name = body.name.trim(); + if !valid_target_name(name) { + return Err(StatusCode::BAD_REQUEST); + } + if !state.db.rename_restore_target(id, name).map_err(internal)? { + return Err(StatusCode::NOT_FOUND); + } + state + .db + .audit( + "restore_target.renamed", + &format!("actor={actor} target={id}"), + ) + .await + .map_err(internal)?; + Ok(StatusCode::NO_CONTENT) +} + async fn targets( ConnectInfo(peer): ConnectInfo, State(state): State, diff --git a/crates/tessera-hub/src/db/restore.rs b/crates/tessera-hub/src/db/restore.rs index 0656853..7af7a3b 100644 --- a/crates/tessera-hub/src/db/restore.rs +++ b/crates/tessera-hub/src/db/restore.rs @@ -104,6 +104,17 @@ impl Db { Ok(changed == 1) } + /// Change the display name of a restore target. Its id, identity and Outpost are not touched, so + /// relations and jobs that refer to it stay valid. Returns false for an unknown target. + pub fn rename_restore_target(&self, id: Uuid, name: &str) -> Result { + let conn = self.conn.lock().unwrap(); + let changed = conn.execute( + "UPDATE restore_targets SET profile = json_set(profile, '$.name', ?2) WHERE id = ?1", + params![id.to_string(), name], + )?; + Ok(changed == 1) + } + pub fn restore_targets(&self, application: Uuid) -> Result> { Ok(self .restore_targets_with_activity(application)? diff --git a/docs/DATABASE-CAPTURE.md b/docs/DATABASE-CAPTURE.md index ff815c3..a9ca486 100644 --- a/docs/DATABASE-CAPTURE.md +++ b/docs/DATABASE-CAPTURE.md @@ -164,7 +164,9 @@ On the target agent, add a `targets` map under the application UUID, keyed by th } ``` -Use `{"reset":"recreate_database"}` to recreate the registered PostgreSQL database. It requires access to the `postgres` maintenance database and permission to drop and create the target database. Schema mode resets the named schema and applies the dump in a transaction. Use `{"reset":"user_schemas"}` for a database whose tables live in several schemas: it drops every non-system schema (everything except `pg_*` and `information_schema`) and recreates `public`, in the same transaction as the restore, so a dump's `CREATE SCHEMA` for a schema that already exists on the target cannot collide. Schema mode only drops the one named schema, so a dump that also creates another schema that the target already has fails and rolls back; the target is left unchanged. Objects that live outside schemas (roles, publications, subscriptions) are not touched, and the connected role must own, or be allowed to drop, every schema it empties. Supply a local `post_restore_sql` file for target-specific SQL. PostgreSQL can read custom archives and plain or gzip-compressed SQL. The agent requires a psql client with restricted mode for restore. `omit_transaction_timeout` and `omit_pg_stat_statements` enable specific compatibility rules. +Use `{"reset":"recreate_database"}` to recreate the registered PostgreSQL database. It requires access to the `postgres` maintenance database and permission to drop and create the target database. Schema mode resets the named schema and applies the dump in a transaction. A restore target can be renamed later with `PUT /api/v1/restore-targets/{id}` and `{"name": "..."}` (administrators only, 1 to 128 characters, no control characters, audited as `restore_target.renamed`). Only the display name changes: the id, the identity, the Outpost, relations and earlier jobs stay as they are. Since several applications can each have a target called `dev`, the Relations console shows the application next to every target and in its pickers, and the Refresh screen shows the application on each card. Registering a target suggests ` · ` until a name is typed. + +Use `{"reset":"user_schemas"}` for a database whose tables live in several schemas: it drops every non-system schema (everything except `pg_*` and `information_schema`) and recreates `public`, in the same transaction as the restore, so a dump's `CREATE SCHEMA` for a schema that already exists on the target cannot collide. Schema mode only drops the one named schema, so a dump that also creates another schema that the target already has fails and rolls back; the target is left unchanged. Objects that live outside schemas (roles, publications, subscriptions) are not touched, and the connected role must own, or be allowed to drop, every schema it empties. Supply a local `post_restore_sql` file for target-specific SQL. PostgreSQL can read custom archives and plain or gzip-compressed SQL. The agent requires a psql client with restricted mode for restore. `omit_transaction_timeout` and `omit_pg_stat_statements` enable specific compatibility rules. A custom-format archive must be readable by the `pg_restore` on the restore host. pg_restore refuses archives made by a newer pg_dump, so install a client at least as new as the one that captured. The check happens while the archive is being prepared, before the safety backup and before anything is touched, and the failure names both versions, for example `pg_restore 16.15 cannot read this archive (made by pg_dump 17.2, archive format 1.16): install a PostgreSQL client >= 17 on the restore host`. With `omit_pg_stat_statements`, the dump's own `pg_stat_statements` statements are skipped, but an extension the target already had is recreated in the schema it lived in (a target without it does not get it). diff --git a/docs/auth-endpoint-contract.md b/docs/auth-endpoint-contract.md index 7813c74..a15422c 100644 --- a/docs/auth-endpoint-contract.md +++ b/docs/auth-endpoint-contract.md @@ -30,6 +30,7 @@ admin/browser. Semua status/data job hanya di scope owner/admin yang berizin. | /api/v1/access/users/:id/revoke-sessions | POST | human | access.manage | admin | tidak ada; semua sesi user berakhir | | /api/v1/me/preferences | GET,PUT | human | session.self | current account | pilihan tampilan sendiri (look: window atau radar); no-store; CSRF pada PUT; token/dev tanpa akun: GET kosong, PUT 404 | | /api/v1/orbits/:id/environment | PUT | human | orbit.manage | admin | tidak ada; menandai sumber (production/staging/development); diaudit | +| /api/v1/restore-targets/:id | PUT | human | relation.manage | admin | hanya name (1-128, tanpa karakter kontrol); id, identity, outpost, relasi, dan job lama tidak berubah; diaudit `restore_target.renamed` | | /api/v1/restore-targets/:id/environment | PUT | human | relation.manage | admin | relasi aktif ke target yang diberi label production berakhir seketika; diaudit | | /api/v1/relations | GET,POST | human | relation.manage | admin | daftar relasi, orbit dan target untuk wizard (dengan identity); POST membuat relasi atau menyebut aturan yang menolak | | /api/v1/relations/:id | PUT,DELETE | human | relation.manage | admin | PUT = versi baru (id baru, grant tidak ikut); DELETE menonaktifkan; diaudit | diff --git a/web/src/api.ts b/web/src/api.ts index 6756886..d76cd20 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -119,6 +119,7 @@ export const fetchRelations = () => api("/api/v1/relations"); export const setOrbitEnvironment = (id: string, environment: Environment) => api(`/api/v1/orbits/${id}/environment`, json("PUT", { environment })); export const setTargetEnvironment = (id: string, environment: Environment) => api<{ ended_relations: string[] }>(`/api/v1/restore-targets/${id}/environment`, json("PUT", { environment })); +export const renameTarget = (id: string, name: string) => api(`/api/v1/restore-targets/${id}`, json("PUT", { name })); export const createRelation = (source_orbit_id: string, target_id: string) => api("/api/v1/relations", json("POST", { source_orbit_id, target_id })); export const retargetRelation = (id: string, target_id: string) => api(`/api/v1/relations/${id}`, json("PUT", { target_id })); export const endRelation = (id: string) => api(`/api/v1/relations/${id}`, { method: "DELETE" }); diff --git a/web/src/components/reconstitute/DatabaseRestore.tsx b/web/src/components/reconstitute/DatabaseRestore.tsx index 4a19c15..a433425 100644 --- a/web/src/components/reconstitute/DatabaseRestore.tsx +++ b/web/src/components/reconstitute/DatabaseRestore.tsx @@ -22,8 +22,8 @@ const phases: Record = { cancelled: "Cancelled", }; -export function DatabaseRestore({ snapshot, application, engine }: { - snapshot: string; application: string; engine: RestoreTarget["engine"]; +export function DatabaseRestore({ snapshot, application, applicationName, engine }: { + snapshot: string; application: string; applicationName?: string; engine: RestoreTarget["engine"]; }) { const fieldId = useId(); const query = useQueryClient(); @@ -112,7 +112,7 @@ export function DatabaseRestore({ snapshot, application, engine }: { )} {registering - ? setRegistering(false)} /> + ? setRegistering(false)} /> : !targets.data?.length && } diff --git a/web/src/components/reconstitute/ReconstituteWizard.tsx b/web/src/components/reconstitute/ReconstituteWizard.tsx index a46f62b..1629c44 100644 --- a/web/src/components/reconstitute/ReconstituteWizard.tsx +++ b/web/src/components/reconstitute/ReconstituteWizard.tsx @@ -117,7 +117,7 @@ export function ReconstituteWizard({ {managed && databaseMode ? ( - + ) : <>