feat: rename orbits; snapshots and downloads show the orbit's current name

PUT /api/v1/orbits/:id changes only the name (admin, validated, case-insensitively unique, audited).
Snapshot metadata is immutable, so the list and the download file name look the orbit up by id and
fall back to the written name only when the orbit is gone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 15:01:49 +07:00
parent c6dd52c700
commit f52fc1930f
7 changed files with 240 additions and 4 deletions

View File

@@ -337,7 +337,8 @@ fn recipe(w: &World, row: &Row) -> (String, Option<Value>) {
| "/api/v1/snapshots/:id/download"
| "/api/v1/snapshots/:id/restore-targets"
| "/api/v1/snapshots/:id/restore-jobs" => a.snapshot,
"/api/v1/orbits/:id/retention"
"/api/v1/orbits/:id"
| "/api/v1/orbits/:id/retention"
| "/api/v1/orbits/:id/run"
| "/api/v1/orbits/:id/outpost" => a.orbit,
"/api/v1/capture-profiles/:id"
@@ -374,6 +375,7 @@ fn recipe(w: &World, row: &Row) -> (String, Option<Value>) {
("POST", "/api/v1/orbits") => Some(
json!({"name": "created", "provider": "filesystem", "source": "filesystem", "provider_config": {"path": "/nonexistent"}}),
),
("PUT", "/api/v1/orbits/:id") => Some(json!({"name": "renamed-orbit"})),
("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})),

View File

@@ -116,8 +116,14 @@ async fn download(
.schedule
.map(|s| s.timezone)
});
let orbit_name = state
.db
.orbit_names()
.ok()
.and_then(|names| names.get(&snapshot.manifest.orbit_id).cloned())
.unwrap_or_else(|| snapshot.manifest.orbit_name.clone());
let file_name = exports::download_name(
&snapshot.manifest.orbit_name,
&orbit_name,
snapshot.taken_at,
zone.as_deref(),
snapshot

View File

@@ -1846,3 +1846,144 @@ async fn a_target_name_is_validated_like_a_registration_and_only_administrators_
StatusCode::NO_CONTENT
);
}
// ---- renaming orbits ----
impl Lab {
async fn download_disposition(&self, snapshot: Uuid) -> String {
let request = Request::builder()
.method("GET")
.uri(format!("/api/v1/snapshots/{snapshot}/download"))
.header("x-tessera-admin-token", ADMIN)
.extension(ConnectInfo("127.0.0.1:4000".parse::<SocketAddr>().unwrap()))
.body(Body::empty())
.unwrap();
let response = self.app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
response.headers()[header::CONTENT_DISPOSITION]
.to_str()
.unwrap()
.to_string()
}
}
#[tokio::test]
async fn renaming_an_orbit_renames_its_old_snapshots_everywhere_they_are_shown() {
let lab = fresh().await;
let admin = lab.admin();
let (qa, _) = lab.refresher("qa");
lab.start(&admin, "orbit-rename").await;
let snapshot = lab
.capture(&Lab::production_identity(), false)
.await
.unwrap();
assert!(lab
.download_disposition(snapshot)
.await
.contains("filename=\"prod-db_"));
let uri = format!("/api/v1/orbits/{}", lab.orbit);
assert_eq!(
lab.send(&admin, "PUT", &uri, Some(json!({"name": " broiler "})))
.await
.0,
StatusCode::NO_CONTENT
);
// the snapshot was written under the old name; it is shown under the current one
let (_, listed) = lab.send(&admin, "GET", "/api/v1/snapshots", None).await;
assert_eq!(listed[0]["orbit_name"], "broiler", "{listed}");
assert!(lab
.download_disposition(snapshot)
.await
.contains("filename=\"broiler_"));
let (_, overview) = lab.send(&admin, "GET", "/api/v1/relations", None).await;
assert!(overview["orbits"]
.as_array()
.unwrap()
.iter()
.any(|o| o["name"] == "broiler"));
let (_, mine) = lab
.send(&qa, "GET", "/api/v1/refresh-relations", None)
.await;
assert_eq!(mine[0]["source_name"], "broiler");
// nothing but the name moved: the relation, its confirmation text and the id are the same relation
assert_eq!(overview["relations"][0]["id"], lab.relation);
assert!(
lab.audit_log()
.iter()
.any(|(event, detail)| event == "orbit.renamed"
&& detail.contains(&lab.orbit.to_string()))
);
}
#[tokio::test]
async fn an_orbit_name_is_validated_unique_and_only_administrators_change_it() {
let lab = fresh().await;
let admin = lab.admin();
let uri = format!("/api/v1/orbits/{}", lab.orbit);
for name in ["", " ", &"x".repeat(129), "bad\nname"] {
assert_eq!(
lab.send(&admin, "PUT", &uri, Some(json!({"name": name})))
.await
.0,
StatusCode::BAD_REQUEST,
"{name:?}"
);
}
assert_eq!(
lab.send(
&admin,
"PUT",
&uri,
Some(json!({"name": "ok", "provider": "x"}))
)
.await
.0,
StatusCode::UNPROCESSABLE_ENTITY
);
let unknown = format!("/api/v1/orbits/{}", Uuid::new_v4());
assert_eq!(
lab.send(&admin, "PUT", &unknown, Some(json!({"name": "ok"})))
.await
.0,
StatusCode::NOT_FOUND
);
// another orbit already has that name (compared without regard to case); keeping your own name is fine
lab.state
.db
.upsert_orbit(&crate::db::OrbitRow {
id: Uuid::new_v4(),
name: "Other".into(),
provider: "wormhole".into(),
provider_config: "{}".into(),
schedule: None,
decay_preset: "week-of-dailies".into(),
retention: None,
dry_run: false,
last_status: "idle".into(),
})
.await
.unwrap();
assert_eq!(
lab.send(&admin, "PUT", &uri, Some(json!({"name": "other"})))
.await
.0,
StatusCode::CONFLICT
);
assert_eq!(
lab.send(&admin, "PUT", &uri, Some(json!({"name": "prod-db"})))
.await
.0,
StatusCode::NO_CONTENT
);
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}"
);
}

View File

@@ -373,6 +373,7 @@ pub fn router(state: HubState) -> Router {
.route("/health", get(health))
.route("/api/v1/snapshots", get(list_snapshots))
.route("/api/v1/orbits", get(list_orbits).post(create_orbit))
.route("/api/v1/orbits/:id", put(rename_orbit))
.route("/api/v1/orbits/:id/retention", put(update_orbit_retention))
.route("/api/v1/orbits/:id/run", post(trigger_orbit))
.route("/api/v1/orbits/:id/outpost", put(bind_outpost))
@@ -430,6 +431,10 @@ async fn list_snapshots(
let snaps = vault
.list_snapshots()
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let names = state
.db
.orbit_names()
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let out = snaps
.into_iter()
.filter(|s| s.manifest.provider != "legacy-history")
@@ -439,7 +444,11 @@ async fn list_snapshots(
orbit_id: s.manifest.orbit_id,
taken_at: s.taken_at,
capture: CaptureSnapshotSummary::from_manifest(&s.manifest),
orbit_name: s.manifest.orbit_name,
// the orbit's current name; the manifest keeps the one it was written under
orbit_name: names
.get(&s.manifest.orbit_id)
.cloned()
.unwrap_or(s.manifest.orbit_name),
size_bytes: s.size_bytes,
stored_bytes: s.stored_bytes,
new_data_chunks: s.new_data_chunks,
@@ -609,6 +618,42 @@ fn retention_settings(
))
}
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct OrbitRename {
name: String,
}
/// Change an orbit's name and nothing else. Its snapshots are shown under the new name from now on.
async fn rename_orbit(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(req): Json<OrbitRename>,
) -> Result<StatusCode, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let name = req.name.trim();
if name.is_empty() || name.len() > 128 || name.chars().any(char::is_control) {
return Err(StatusCode::BAD_REQUEST);
}
match state
.db
.rename_orbit(id, name)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
{
None => return Err(StatusCode::NOT_FOUND),
Some(false) => return Err(StatusCode::CONFLICT),
Some(true) => {}
}
state
.db
.audit("orbit.renamed", &format!("actor={actor} orbit={id}"))
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(StatusCode::NO_CONTENT)
}
#[utoipa::path(put, path = "/api/v1/orbits/{id}/retention", params(("id" = Uuid, Path, description = "orbit id")), request_body = RetentionUpdate, responses((status = 204), (status = 400), (status = 404)))]
async fn update_orbit_retention(
ConnectInfo(peer): ConnectInfo<SocketAddr>,

View File

@@ -147,6 +147,45 @@ impl Db {
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}
/// Current names of all orbits, by id. Snapshots keep the name they were written under; what people see
/// is the name the orbit has now.
pub fn orbit_names(&self) -> Result<std::collections::HashMap<Uuid, String>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT id, name FROM orbits")?;
let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
Ok(rows
.filter_map(Result::ok)
.filter_map(|(id, name)| Some((Uuid::parse_str(&id).ok()?, name)))
.collect())
}
/// Change an orbit's name. `None` for an unknown orbit, `Some(false)` when another orbit has the name
/// (compared without regard to case), `Some(true)` when renamed.
pub fn rename_orbit(&self, id: Uuid, name: &str) -> Result<Option<bool>> {
let conn = self.conn.lock().unwrap();
let exists: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM orbits WHERE id = ?1)",
params![id.to_string()],
|r| r.get(0),
)?;
if !exists {
return Ok(None);
}
let taken: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM orbits WHERE lower(name) = lower(?2) AND id <> ?1)",
params![id.to_string(), name],
|r| r.get(0),
)?;
if taken {
return Ok(Some(false));
}
conn.execute(
"UPDATE orbits SET name = ?2 WHERE id = ?1",
params![id.to_string(), name],
)?;
Ok(Some(true))
}
pub async fn upsert_orbit(&self, row: &OrbitRow) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(