diff --git a/.sqlx/query-7d8344b73ec8569d3c683dc2b0db5c7f0b10c979eda6868a8a62c158bf34e21d.json b/.sqlx/query-7d8344b73ec8569d3c683dc2b0db5c7f0b10c979eda6868a8a62c158bf34e21d.json new file mode 100644 index 00000000..4b2683aa --- /dev/null +++ b/.sqlx/query-7d8344b73ec8569d3c683dc2b0db5c7f0b10c979eda6868a8a62c158bf34e21d.json @@ -0,0 +1,108 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT m.id, m.image, m.digest, m.created_at, m.untagged_since, m.last_pulled_at,\n m.subject_digest,\n ARRAY(SELECT r.digest FROM oci_manifest_ref r\n WHERE r.manifest_id = m.id AND r.kind = 'manifest'\n ORDER BY r.digest) AS \"children!\"\n FROM oci_manifest m\n WHERE m.repository_id = $1 AND m.image = $2\n ORDER BY m.id\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Int8", + "origin": { + "Table": { + "table": "oci_manifest", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "image", + "type_info": "Text", + "origin": { + "Table": { + "table": "oci_manifest", + "name": "image" + } + } + }, + { + "ordinal": 2, + "name": "digest", + "type_info": "Text", + "origin": { + "Table": { + "table": "oci_manifest", + "name": "digest" + } + } + }, + { + "ordinal": 3, + "name": "created_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "oci_manifest", + "name": "created_at" + } + } + }, + { + "ordinal": 4, + "name": "untagged_since", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "oci_manifest", + "name": "untagged_since" + } + } + }, + { + "ordinal": 5, + "name": "last_pulled_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "oci_manifest", + "name": "last_pulled_at" + } + } + }, + { + "ordinal": 6, + "name": "subject_digest", + "type_info": "Text", + "origin": { + "Table": { + "table": "oci_manifest", + "name": "subject_digest" + } + } + }, + { + "ordinal": 7, + "name": "children!", + "type_info": "TextArray", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Int8", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + true, + true, + true, + null + ] + }, + "hash": "7d8344b73ec8569d3c683dc2b0db5c7f0b10c979eda6868a8a62c158bf34e21d" +} diff --git a/.sqlx/query-b6324edfe7dd9b8783d9b54ccdcc75e1a400d8dc32d0c0aa0c9ced75fd2c03b5.json b/.sqlx/query-b6324edfe7dd9b8783d9b54ccdcc75e1a400d8dc32d0c0aa0c9ced75fd2c03b5.json new file mode 100644 index 00000000..02030a7c --- /dev/null +++ b/.sqlx/query-b6324edfe7dd9b8783d9b54ccdcc75e1a400d8dc32d0c0aa0c9ced75fd2c03b5.json @@ -0,0 +1,89 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT t.image, t.tag, t.manifest_id, m.digest, t.updated_at, m.last_pulled_at\n FROM oci_tag t\n JOIN oci_manifest m ON m.id = t.manifest_id\n WHERE t.repository_id = $1 AND t.image = $2\n ORDER BY t.tag\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "image", + "type_info": "Text", + "origin": { + "Table": { + "table": "oci_tag", + "name": "image" + } + } + }, + { + "ordinal": 1, + "name": "tag", + "type_info": "Text", + "origin": { + "Table": { + "table": "oci_tag", + "name": "tag" + } + } + }, + { + "ordinal": 2, + "name": "manifest_id", + "type_info": "Int8", + "origin": { + "Table": { + "table": "oci_tag", + "name": "manifest_id" + } + } + }, + { + "ordinal": 3, + "name": "digest", + "type_info": "Text", + "origin": { + "Table": { + "table": "oci_manifest", + "name": "digest" + } + } + }, + { + "ordinal": 4, + "name": "updated_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "oci_tag", + "name": "updated_at" + } + } + }, + { + "ordinal": 5, + "name": "last_pulled_at", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "oci_manifest", + "name": "last_pulled_at" + } + } + } + ], + "parameters": { + "Left": [ + "Int8", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + true + ] + }, + "hash": "b6324edfe7dd9b8783d9b54ccdcc75e1a400d8dc32d0c0aa0c9ced75fd2c03b5" +} diff --git a/crates/db/src/oci_dao.rs b/crates/db/src/oci_dao.rs index 809584eb..46eefd9c 100644 --- a/crates/db/src/oci_dao.rs +++ b/crates/db/src/oci_dao.rs @@ -1849,6 +1849,49 @@ pub async fn repository_size(pool: &PgPool, repository_id: i64) -> sqlx::Result< u64::try_from(bytes).map_err(|e| sqlx::Error::Protocol(e.to_string())) } +/// One image's manifests and tags as [`lock_image_for_retention`] loads +/// them, without locking them: for saying what a delete would take along +/// before an administrator confirms it. The answer is of the moment; the +/// delete decides again under the lock. +pub async fn image_for_delete_preview( + pool: &PgPool, + repository_id: i64, + image: &str, +) -> sqlx::Result<(Vec, Vec)> { + let manifests = sqlx::query_as!( + RetentionManifest, + r#" + SELECT m.id, m.image, m.digest, m.created_at, m.untagged_since, m.last_pulled_at, + m.subject_digest, + ARRAY(SELECT r.digest FROM oci_manifest_ref r + WHERE r.manifest_id = m.id AND r.kind = 'manifest' + ORDER BY r.digest) AS "children!" + FROM oci_manifest m + WHERE m.repository_id = $1 AND m.image = $2 + ORDER BY m.id + "#, + repository_id, + image, + ) + .fetch_all(pool) + .await?; + let tags = sqlx::query_as!( + RetentionTag, + r#" + SELECT t.image, t.tag, t.manifest_id, m.digest, t.updated_at, m.last_pulled_at + FROM oci_tag t + JOIN oci_manifest m ON m.id = t.manifest_id + WHERE t.repository_id = $1 AND t.image = $2 + ORDER BY t.tag + "#, + repository_id, + image, + ) + .fetch_all(pool) + .await?; + Ok((tags, manifests)) +} + /// Lock (`FOR UPDATE`) and load one image's manifests and tags, as /// [`retention_manifests`] and [`retention_tags`] load a repository's: for /// image retention to re-evaluate its decisions against the image's current diff --git a/crates/server/src/admin/images.rs b/crates/server/src/admin/images.rs index 4dc48299..b1b6358f 100644 --- a/crates/server/src/admin/images.rs +++ b/crates/server/src/admin/images.rs @@ -29,6 +29,12 @@ //! does not name. As after a registry delete, the manifests' configs and //! layers stay linked to the image until the registry sweeper finds them //! unreferenced, and the blob outbox deletes a blob no image links any more. +//! +//! `GET /admin/repositories/{name}/images/delete-preview?image=[&reference=]` +//! says what that delete would remove, and deletes nothing ([`preview`]): +//! the web UI's confirmation asks it, since the image page lists at most +//! 1,000 tags and 1,000 manifests and cannot tell (#546). It takes the same +//! query and refuses what the delete refuses. use std::collections::{HashMap, HashSet}; @@ -36,7 +42,7 @@ use axum::extract::{Extension, Path, Query, State}; use axum::http::StatusCode; use axum::response::{IntoResponse, Json, Response}; use forge_core::auth::principal::Principal; -use forge_db::model::RepoKind; +use forge_db::model::{RepoKind, Repository}; use forge_db::oci_dao::{self, RetentionManifest, RetentionTag}; use forge_db::repository_dao; use serde::{Deserialize, Serialize}; @@ -64,63 +70,70 @@ pub struct Deleted { pub tags: usize, } -/// `DELETE /admin/repositories/{name}/images?image=[&reference=]` -pub async fn delete( - State(state): State, - Extension(principal): Extension, - Path(name): Path, - Query(query): Query, -) -> Response { - let repo = match repository_dao::find_repository_by_name(&state.pool, &name).await { +/// What a [`DeleteQuery`] names. +enum Target<'a> { + Image, + Tag(&'a str), + Manifest(ContentDigest), +} + +/// The hosted images repository `name` and what `query` deletes of it, or +/// the refusal (**404** no such repository, **400** otherwise). +async fn target<'a>( + state: &AppState, + name: &str, + query: &'a DeleteQuery, +) -> Result<(Repository, Target<'a>), Response> { + let repo = match repository_dao::find_repository_by_name(&state.pool, name).await { Ok(Some(r)) => r, - Ok(None) => return (StatusCode::NOT_FOUND, "repository not found").into_response(), - Err(e) => return db_error(e), + Ok(None) => return Err((StatusCode::NOT_FOUND, "repository not found").into_response()), + Err(e) => return Err(db_error(e)), }; + let refused = |why: &'static str| Err((StatusCode::BAD_REQUEST, why).into_response()); if !state.formats.stores_images(&repo.format) { - return ( - StatusCode::BAD_REQUEST, - "images are deleted from repositories of images (docker)", - ) - .into_response(); + return refused("images are deleted from repositories of images (docker)"); } if repo.kind() != RepoKind::Hosted { - return ( - StatusCode::BAD_REQUEST, - "image delete is only supported for hosted repositories", - ) - .into_response(); + return refused("image delete is only supported for hosted repositories"); } if query.image.is_empty() { - return (StatusCode::BAD_REQUEST, "image is required").into_response(); + return refused("image is required"); } - if query.reference.as_deref() == Some("") { - return ( - StatusCode::BAD_REQUEST, - "reference is empty; leave it out to delete the whole image", - ) - .into_response(); - } - let grace = state.config.outbox.grace(); - let (result, what) = match query.reference.as_deref() { + let target = match query.reference.as_deref() { + Some("") => return refused("reference is empty; leave it out to delete the whole image"), // A tag never holds a `:`, a digest always does. - Some(reference) if reference.contains(':') => { - let Some(digest) = ContentDigest::parse(reference) else { - return ( - StatusCode::BAD_REQUEST, - "reference is neither a tag nor a digest", - ) - .into_response(); - }; - ( - delete_manifest(&state, repo.id, &query.image, digest.as_str(), grace).await, - "manifest not found", - ) - } - Some(tag) => ( + Some(reference) if reference.contains(':') => match ContentDigest::parse(reference) { + Some(digest) => Target::Manifest(digest), + None => return refused("reference is neither a tag nor a digest"), + }, + Some(tag) => Target::Tag(tag), + None => Target::Image, + }; + Ok((repo, target)) +} + +/// `DELETE /admin/repositories/{name}/images?image=[&reference=]` +pub async fn delete( + State(state): State, + Extension(principal): Extension, + Path(name): Path, + Query(query): Query, +) -> Response { + let (repo, target) = match target(&state, &name, &query).await { + Ok(found) => found, + Err(refusal) => return refusal, + }; + let grace = state.config.outbox.grace(); + let (result, what) = match &target { + Target::Manifest(digest) => ( + delete_manifest(&state, repo.id, &query.image, digest.as_str(), grace).await, + "manifest not found", + ), + Target::Tag(tag) => ( delete_tag(&state, repo.id, &query.image, tag).await, "tag not found", ), - None => ( + Target::Image => ( delete_image(&state, repo.id, &query.image, grace).await, "image not found", ), @@ -144,6 +157,144 @@ pub async fn delete( response } +/// The most tags and indexes a [`DeletePreview`] names; it counts them all. +const PREVIEW_NAMES: usize = 50; + +/// What a delete would remove, as of now: the delete itself decides again, +/// under the image's lock. +#[derive(Debug, Default, Serialize, PartialEq, Eq)] +pub struct DeletePreview { + /// The manifests it deletes, the one asked for included. + pub manifests: usize, + /// Of [`Self::manifests`], those that go along because an index that + /// goes lists them and nothing that stays needs them. + pub listed: usize, + /// Of [`Self::manifests`], the referrers (signatures, SBOMs, + /// attestations) of a manifest that goes. + pub referrers: usize, + /// The tags it deletes, by name: at most [`PREVIEW_NAMES`]. + pub tags: Vec, + /// How many tags it deletes. + pub tags_total: usize, + /// The digests of the indexes that list the manifest asked for and + /// stay, the newest first: at most [`PREVIEW_NAMES`]. Pulling the + /// manifest's platform through them fails once it is gone. + pub indexes: Vec, + /// How many indexes list it and stay. + pub indexes_total: usize, +} + +/// `GET /admin/repositories/{name}/images/delete-preview?image=[&reference=]` +/// +/// What the `DELETE` of the same query would remove, without removing it; +/// **404** when nothing matches, and the delete's refusals. +pub async fn preview( + State(state): State, + Path(name): Path, + Query(query): Query, +) -> Response { + let (repo, target) = match target(&state, &name, &query).await { + Ok(found) => found, + Err(refusal) => return refusal, + }; + let (tags, manifests) = + match oci_dao::image_for_delete_preview(&state.pool, repo.id, &query.image).await { + Ok(image) => image, + Err(e) => return db_error(e), + }; + let found = match &target { + Target::Image => (!manifests.is_empty()).then(|| DeletePreview { + manifests: manifests.len(), + tags_total: tags.len(), + tags: tags + .iter() + .take(PREVIEW_NAMES) + .map(|t| t.tag.clone()) + .collect(), + ..DeletePreview::default() + }), + Target::Tag(tag) => tags.iter().any(|t| t.tag == *tag).then(|| DeletePreview { + tags: vec![(*tag).to_string()], + tags_total: 1, + ..DeletePreview::default() + }), + Target::Manifest(digest) => manifests + .iter() + .find(|m| m.digest == digest.as_str()) + .map(|m| manifest_preview(&manifests, &tags, m.id)), + }; + match found { + Some(preview) => Json(preview).into_response(), + None => { + let what = match target { + Target::Image => "image not found", + Target::Tag(_) => "tag not found", + Target::Manifest(_) => "manifest not found", + }; + (StatusCode::NOT_FOUND, what).into_response() + } + } +} + +/// What deleting the manifest `target` of an image would remove +/// ([`taken_along`]), and the indexes it would leave listing it. +fn manifest_preview( + manifests: &[RetentionManifest], + tags: &[RetentionTag], + target: i64, +) -> DeletePreview { + let doomed: HashSet = taken_along(manifests, tags, target).into_iter().collect(); + let doomed_digests: HashSet<&str> = manifests + .iter() + .filter(|m| doomed.contains(&m.id)) + .map(|m| m.digest.as_str()) + .collect(); + // A manifest goes along as a referrer of one that goes, or else as one + // an index that goes lists. + let referrers = manifests + .iter() + .filter(|m| m.id != target && doomed.contains(&m.id)) + .filter(|m| { + m.subject_digest + .as_deref() + .is_some_and(|subject| doomed_digests.contains(subject)) + }) + .count(); + // Tags are in name order; what goes along has none. + let gone: Vec<&RetentionTag> = tags + .iter() + .filter(|t| doomed.contains(&t.manifest_id)) + .collect(); + let digest = manifests + .iter() + .find(|m| m.id == target) + .map(|m| m.digest.as_str()); + // Manifests are in id order: the newest index first. + let indexes: Vec<&RetentionManifest> = manifests + .iter() + .rev() + .filter(|m| !doomed.contains(&m.id)) + .filter(|m| m.children.iter().any(|c| Some(c.as_str()) == digest)) + .collect(); + DeletePreview { + manifests: doomed.len(), + listed: doomed.len() - 1 - referrers, + referrers, + tags: gone + .iter() + .take(PREVIEW_NAMES) + .map(|t| t.tag.clone()) + .collect(), + tags_total: gone.len(), + indexes: indexes + .iter() + .take(PREVIEW_NAMES) + .map(|m| m.digest.clone()) + .collect(), + indexes_total: indexes.len(), + } +} + async fn delete_tag( state: &AppState, repo_id: i64, @@ -371,6 +522,61 @@ mod tests { ); } + /// The confirmation's numbers (#546): what goes with an index, split + /// into the manifests it lists and the referrers, and every tag on it. + #[test] + fn a_preview_counts_what_goes_with_every_tag_on_the_manifest() { + // Index 1 lists 2 and 3 (3 is tagged); 4 signs the index, 5 is an + // SBOM of 2. + let manifests = [ + manifest(1, &[2, 3], None), + manifest(2, &[], None), + manifest(3, &[], None), + manifest(4, &[], Some(1)), + manifest(5, &[], Some(2)), + ]; + let tags = [tag("1.0", 1), tag("arm", 3), tag("stable", 1)]; + assert_eq!( + manifest_preview(&manifests, &tags, 1), + DeletePreview { + manifests: 4, + listed: 1, + referrers: 2, + tags: vec!["1.0".into(), "stable".into()], + tags_total: 2, + indexes: vec![], + indexes_total: 0, + } + ); + } + + /// The indexes that list the manifest and stay are named, the newest + /// first, whether tagged or not; the names are bounded, the counts not. + #[test] + fn a_preview_names_the_indexes_that_list_the_manifest() { + let manifests = [ + manifest(1, &[2], None), + manifest(2, &[], None), + manifest(3, &[2], None), + ]; + let preview = manifest_preview(&manifests, &[tag("v1-amd64", 2)], 2); + assert_eq!(preview.manifests, 1); + assert_eq!(preview.tags, vec!["v1-amd64".to_string()]); + assert_eq!(preview.indexes, vec!["sha256:3", "sha256:1"]); + assert_eq!(preview.indexes_total, 2); + + let mut many = vec![manifest(1, &[], None)]; + many.extend((2..200).map(|id| manifest(id, &[1], None))); + let tags: Vec = (0..120).map(|n| tag(&format!("t{n:03}"), 1)).collect(); + let preview = manifest_preview(&many, &tags, 1); + assert_eq!(preview.tags.len(), PREVIEW_NAMES); + assert_eq!(preview.tags[0], "t000"); + assert_eq!(preview.tags_total, 120); + assert_eq!(preview.indexes.len(), PREVIEW_NAMES); + assert_eq!(preview.indexes[0], "sha256:199"); + assert_eq!(preview.indexes_total, 198); + } + #[test] fn a_referrer_goes_without_its_subject() { let manifests = [manifest(1, &[], None), manifest(2, &[], Some(1))]; diff --git a/crates/server/src/admin/mod.rs b/crates/server/src/admin/mod.rs index ec23ced1..c3fd2d14 100644 --- a/crates/server/src/admin/mod.rs +++ b/crates/server/src/admin/mod.rs @@ -230,6 +230,10 @@ pub fn admin_router(state: AppState) -> Router { "/repositories/{name}/images", axum::routing::delete(images::delete), ) + .route( + "/repositories/{name}/images/delete-preview", + get(images::preview), + ) .route( "/repositories/{name}/proxy-cache/invalidate", axum::routing::post(proxy_cache::invalidate), diff --git a/crates/server/tests/registry.rs b/crates/server/tests/registry.rs index 831fd21d..54bec4ea 100644 --- a/crates/server/tests/registry.rs +++ b/crates/server/tests/registry.rs @@ -1261,6 +1261,74 @@ async fn admins_delete_tags_manifests_and_images() { 200 ); + // The preview (the web UI's confirmation, #546) says what a delete + // would remove, with the delete's refusals, and removes nothing: every + // tag on the manifest, what goes along, and the indexes that list it. + let preview = |query: Vec<(&'static str, String)>| { + let (srv, path) = (&srv, &path); + async move { + let (u, p) = srv.admin_basic(); + srv.client() + .get(format!("{}{path}/delete-preview", srv.base_url)) + .basic_auth(u, Some(p)) + .query(&query) + .send() + .await + .unwrap() + } + }; + assert_eq!(preview(vec![]).await.status(), 400); + assert_eq!( + preview(vec![image(), ("tag", "1.0".into())]).await.status(), + 400 + ); + for missing in ["2.0".to_string(), sha(b"none")] { + assert_eq!( + preview(vec![image(), ("reference", missing)]) + .await + .status(), + 404 + ); + } + let resp = preview(vec![image(), ("reference", index_digest.clone())]).await; + assert_eq!(resp.status(), 200); + assert_eq!( + resp.json::().await.unwrap(), + json!({ + "manifests": 3, "listed": 1, "referrers": 1, + "tags": ["1.0", "latest"], "tags_total": 2, + "indexes": [], "indexes_total": 0, + }) + ); + let resp = preview(vec![image(), ("reference", amd.clone())]).await; + assert_eq!( + resp.json::().await.unwrap(), + json!({ + "manifests": 1, "listed": 0, "referrers": 0, + "tags": ["amd64"], "tags_total": 1, + "indexes": [index_digest], "indexes_total": 1, + }) + ); + let resp = preview(vec![image(), ("reference", "latest".into())]).await; + assert_eq!( + resp.json::().await.unwrap(), + json!({ + "manifests": 0, "listed": 0, "referrers": 0, + "tags": ["latest"], "tags_total": 1, + "indexes": [], "indexes_total": 0, + }) + ); + let resp = preview(vec![image()]).await; + assert_eq!( + resp.json::().await.unwrap(), + json!({ + "manifests": 4, "listed": 0, "referrers": 0, + "tags": ["1.0", "amd64", "latest"], "tags_total": 3, + "indexes": [], "indexes_total": 0, + }) + ); + assert_eq!(oci.head(&name, "manifests/latest").await.status(), 200); + // The index goes with its tags, its signature and the platform manifest // only it listed; the one still tagged stays. let resp = delete(vec![image(), ("reference", index_digest.clone())]).await; diff --git a/docs/changes/2.2.0/546.fixed.md b/docs/changes/2.2.0/546.fixed.md new file mode 100644 index 00000000..f117b685 --- /dev/null +++ b/docs/changes/2.2.0/546.fixed.md @@ -0,0 +1,11 @@ +The web UI's confirmation of an image delete counted the rows the image page +lists, at most the newest 1,000 tags and 1,000 manifests: an image of 50,000 +tags was announced as "1,000 tags and 1,000 manifests", a manifest's delete +could leave out tags and referrers it takes and the warning that an index +lists the manifest, and deleting a chart version did not say that the other +tags of its manifest (`oras tag`, `crane tag`) go too. The whole image is now +counted by its totals, and a manifest's or chart version's confirmation shows +what the server would delete: every tag on the manifest, the manifests and +referrers that go along, and the indexes that list it. The admin API answers +that as `GET /admin/repositories//images/delete-preview`, with the +delete's `image` and `reference`. diff --git a/docs/docker.md b/docs/docker.md index 8f8c9e00..4b1b9961 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -346,6 +346,30 @@ pulling that platform through the index then fails. The answer counts the manifests and tags deleted (404 when nothing matched). A hosted repository is deleted only once it holds no image, so emptying one is deleting its images. +To see what a delete would remove before running it, ask +`GET /admin/repositories//images/delete-preview` with the same `image` +and `reference`; it deletes nothing and refuses what the delete refuses: + +```bash +curl -u admin@example.com: \ + 'https://forge.example.com/admin/repositories/docker-hosted/images/delete-preview?image=team/app&reference=sha256:' +# {"manifests": 3, "listed": 1, "referrers": 1, +# "tags": ["1.0", "latest"], "tags_total": 2, +# "indexes": [], "indexes_total": 0} +``` + +`manifests` counts the manifests that go, the one asked for included: of the +others, `listed` are manifests an index that goes lists and `referrers` are +signatures, SBOMs and attestations. `tags` names the tags that go (up to 50; +`tags_total` counts them all), and `indexes` the indexes that list the +manifest and stay (up to 50 digests, the newest first; `indexes_total`), +through which that platform no longer pulls. The answer is of the moment: the +delete decides again. The web UI's confirmation shows it, because the image +page lists at most 1,000 tags and 1,000 manifests of an image: a manifest's +delete names every tag on the manifest, also for a chart version whose +manifest has other tags (`oras tag`, `crane tag`), and the whole image's +delete counts all its tags and manifests. + The whole image goes 100 manifests at a time, the newest first, each batch in a transaction of its own: an image of tens of thousands of manifests never keeps them all locked, so pulls and pushes wait for one batch at most. diff --git a/web/src/api/images.ts b/web/src/api/images.ts index bc032845..c723c57e 100644 --- a/web/src/api/images.ts +++ b/web/src/api/images.ts @@ -195,6 +195,8 @@ export const imageKeys = { ['images', 'detail', repo, image] as const, chart: (repo: string, image: string, digest: string) => ['images', 'chart', repo, image, digest] as const, + deletePreview: (repo: string, image: string, reference: string) => + ['images', 'delete-preview', repo, image, reference] as const, } /** Fetch a page of one docker repository's images. */ @@ -271,3 +273,43 @@ export function deleteImage( { query: { image, reference } }, ) } + +/** + * What deleting a manifest would remove, as the server would decide it now + * (`admin::images::DeletePreview`). The image page cannot tell: it lists at + * most 1,000 tags and 1,000 manifests of an image. + */ +export interface ImageDeletePreview { + /** The manifests it deletes, the one asked for included. */ + manifests: number + /** Of those, the manifests an index that goes lists and nothing else needs. */ + listed: number + /** Of those, the referrers (signatures, SBOMs, attestations). */ + referrers: number + /** The tags it deletes, by name: at most 50 ({@link tags_total} counts all). */ + tags: string[] + tags_total: number + /** + * The indexes that list the manifest and stay (digests, the newest + * first): at most 50 ({@link indexes_total} counts all). + */ + indexes: string[] + indexes_total: number +} + +/** + * `GET /admin/repositories//images/delete-preview?image=&reference=<…>`: + * what {@link deleteImage} of the same reference would remove, without + * removing it. + */ +export function fetchImageDeletePreview( + repo: string, + image: string, + reference: string, + signal?: AbortSignal, +): Promise { + return httpClient.get( + `/admin/repositories/${encodeURIComponent(repo)}/images/delete-preview`, + { query: { image, reference }, signal }, + ) +} diff --git a/web/src/components/ImageDeleteDialog.tsx b/web/src/components/ImageDeleteDialog.tsx index cbcea1d1..d63d5e3e 100644 --- a/web/src/components/ImageDeleteDialog.tsx +++ b/web/src/components/ImageDeleteDialog.tsx @@ -1,9 +1,16 @@ import type { ReactNode } from 'react' import type { UseMutationResult } from '@tanstack/react-query' -import type { ImageDeleted, ImageDetail, ImageManifest, ImageTag } from '~/api/images' +import type { + ImageDeleted, + ImageDeletePreview, + ImageDetail, + ImageManifest, + ImageTag, +} from '~/api/images' import type { ApiError } from '~/lib/httpClient' import { chartVersion, isChartImage, shortDigest } from '~/lib/oci' +import { useImageDeletePreview } from '~/queries/useImageDetail' import { Code, Dialog, Notice } from '~/components/ui' /** What the image page asks an administrator to confirm the delete of. */ @@ -28,8 +35,37 @@ function referenceOf(target: ImageDeleteTarget): string | undefined { } } +/** The manifest a delete of `target` deletes, when it deletes one. */ +function manifestOf(target: ImageDeleteTarget | null): string | undefined { + return target?.kind === 'manifest' || target?.kind === 'version' + ? referenceOf(target) + : undefined +} + function count(n: number, one: string, many: string): string { - return `${n} ${n === 1 ? one : many}` + return `${n.toLocaleString()} ${n === 1 ? one : many}` +} + +/** `names` as code, and how many of `total` they leave out. */ +function Names({ names, total }: { names: string[]; total: number }) { + return ( + <> + {names.join(', ')} + {total > names.length && ` and ${(total - names.length).toLocaleString()} more`} + + ) +} + +/** What goes with a manifest, by the server's count: `''` when nothing does. */ +function takenAlong(preview: ImageDeletePreview): string { + const along = [ + preview.listed > 0 && `the ${count(preview.listed, 'manifest', 'manifests')} it lists`, + preview.referrers > 0 && + `${count(preview.referrers, 'referrer', 'referrers')} (signatures, SBOMs, attestations)`, + ].filter((part): part is string => !!part) + return along.length > 0 + ? `With it go ${along.join(' and ')}; what a tag or another manifest still needs stays. ` + : '' } /** @@ -37,6 +73,14 @@ function count(n: number, one: string, many: string): string { * repositories): the whole image, a tag, a manifest with what only it kept, * or a Helm chart's version. It says what goes along and runs the delete * through `del` ({@link useDeleteImage}); `onDeleted` closes it. + * + * The page lists at most 1,000 tags and 1,000 manifests of an image, so the + * wording never counts its rows (#546): the whole image is counted by the + * page's totals, and what a manifest's delete takes (every tag on it, the + * manifests it lists, its referrers) and which indexes list it is asked of + * the server ({@link useImageDeletePreview}). Until that answers, the delete + * cannot be confirmed; when it fails, the dialog says what the server does + * in general instead. */ export function ImageDeleteDialog({ detail, @@ -51,6 +95,12 @@ export function ImageDeleteDialog({ onClose: () => void onDeleted: (target: ImageDeleteTarget) => void }) { + const manifest = manifestOf(target) + const asked = useImageDeletePreview(detail.repo, detail.image, manifest) + // An answer still being asked again is not the server's current one. + const preview = manifest !== undefined && !asked.isFetching ? asked.data : undefined + const checking = manifest !== undefined && (asked.isFetching || (!preview && !asked.isError)) + let title = '' let description: ReactNode = null let warning: ReactNode = null @@ -59,17 +109,19 @@ export function ImageDeleteDialog({ if (target?.kind === 'image') { const chart = isChartImage(detail.manifests) + const tags = detail.tags_total ?? detail.tags.length + const manifests = detail.manifests_total ?? detail.manifests.length + const partial = tags > detail.tags.length || manifests > detail.manifests.length title = `Delete ${detail.image}?` confirm = chart ? 'Delete chart' : 'Delete image' description = ( <> Permanently delete {chart ? 'chart' : 'image'} {image} from repository{' '} {detail.repo}:{' '} - {chart - ? count(detail.tags.length, 'version', 'versions') - : count(detail.tags.length, 'tag', 'tags')}{' '} - and {count(detail.manifests.length, 'manifest', 'manifests')}. Clients that pull it start - failing; those that already pulled it keep their copy. This cannot be undone. + {chart ? count(tags, 'version', 'versions') : count(tags, 'tag', 'tags')} and{' '} + {count(manifests, 'manifest', 'manifests')} + {partial && ', not only the newest this page lists'}. Clients that pull it start failing; + those that already pulled it keep their copy. This cannot be undone. ) } else if (target?.kind === 'tag') { @@ -85,62 +137,79 @@ export function ImageDeleteDialog({ ) } else if (target?.kind === 'manifest') { const m = target.manifest - const referrers = detail.manifests.filter((r) => r.subject_digest === m.digest).length - const along = [ - m.children.length > 0 && - `the ${count(m.children.length, 'manifest', 'manifests')} it lists`, - referrers > 0 && - `the ${count(referrers, 'referrer', 'referrers')} (signatures, SBOMs, attestations) of it`, - ].filter((part): part is string => !!part) - const parents = detail.manifests.filter((p) => p.children.includes(m.digest)) title = `Delete manifest ${shortDigest(m.digest)}?` confirm = 'Delete manifest' description = ( <> Permanently delete the manifest {shortDigest(m.digest)} of {image} - {m.tags.length > 0 && ( + {preview && preview.tags_total > 0 && ( <> {' '} - with its {m.tags.length === 1 ? 'tag' : 'tags'} {m.tags.join(', ')} + with its {preview.tags_total === 1 ? 'tag' : 'tags'}{' '} + )} - .{' '} - {along.length > 0 && - `With it go ${along.join(' and ')}, unless a tag or another manifest still needs them. `} - This cannot be undone. + . {preview && takenAlong(preview)}This cannot be undone. ) - if (parents.length > 0) { - warning = ( - - {parents.length === 1 ? 'Index ' : 'Indexes '} - {parents.map((p, i) => ( - - {i > 0 && ', '} - {shortDigest(p.digest)} - - ))}{' '} - {parents.length === 1 ? 'lists' : 'list'} this manifest: pulling{' '} - {m.platforms.length > 0 ? m.platforms.join(', ') : 'its platform'} through{' '} - {parents.length === 1 ? 'it' : 'them'} fails once the manifest is gone. - - ) - } } else if (target?.kind === 'version') { const version = chartVersion(target.tag.tag) - const signed = detail.manifests.some((r) => r.subject_digest === target.tag.digest) + // The version's own tag is what is asked for; the others go unasked. + const others = preview?.tags.filter((tag) => tag !== target.tag.tag) ?? [] + // Its own tag is among the tags, named or (past the bound) only counted. + const own = + preview && (others.length < preview.tags.length || preview.tags_total > preview.tags.length) + const othersTotal = preview ? preview.tags_total - (own ? 1 : 0) : 0 title = `Delete ${detail.image} ${version}?` confirm = 'Delete version' description = ( <> Permanently delete version {version} of chart {image} from repository{' '} {detail.repo} - {signed && ', with its signatures and other referrers'}. Clients that already pulled it - keep their copy. This cannot be undone. + {othersTotal > 0 && ( + <> + , and with it the {othersTotal === 1 ? 'tag' : 'tags'}{' '} + of the same manifest + + )} + . {preview && takenAlong(preview)}Clients that already pulled it keep their copy. This + cannot be undone. ) } + if (manifest !== undefined && checking) { + warning = Checking what this delete takes along… + } else if (manifest !== undefined && !preview) { + warning = ( + + The manifest goes with every tag on it, also tags this page does not list, and with the + manifests it lists and its referrers (signatures, SBOMs, attestations) unless a tag or + another manifest still needs them. An index that lists it can no longer pull its + platform. ({asked.error?.body || asked.error?.message}) + + ) + } else if (preview && preview.indexes_total > 0) { + const one = preview.indexes_total === 1 + const platforms = target?.kind === 'manifest' ? target.manifest.platforms : [] + warning = ( + + {one ? 'Index ' : 'Indexes '} + {preview.indexes.map((digest, i) => ( + + {i > 0 && ', '} + {shortDigest(digest)} + + ))} + {preview.indexes_total > preview.indexes.length && + ` and ${(preview.indexes_total - preview.indexes.length).toLocaleString()} more`}{' '} + {one ? 'lists' : 'list'} this manifest: pulling{' '} + {platforms.length > 0 ? platforms.join(', ') : 'its platform'} through{' '} + {one ? 'it' : 'them'} fails once the manifest is gone. + + ) + } + return ( target && del.mutate(referenceOf(target), { diff --git a/web/src/queries/useImageDetail.ts b/web/src/queries/useImageDetail.ts index 811d239d..a17d7020 100644 --- a/web/src/queries/useImageDetail.ts +++ b/web/src/queries/useImageDetail.ts @@ -3,9 +3,11 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import type { ApiError } from '~/lib/httpClient' import { deleteImage, + fetchImageDeletePreview, fetchImageDetail, imageKeys, type ImageDeleted, + type ImageDeletePreview, type ImageDetail, } from '~/api/images' @@ -23,6 +25,22 @@ export function useImageDetail(repo: string, image: string) { }) } +/** + * What deleting the manifest `digest` would remove (the confirmation's + * wording): asked afresh each time a confirmation opens, never from a cache, + * and not at all without a digest. + */ +export function useImageDeletePreview(repo: string, image: string, digest: string | undefined) { + return useQuery({ + queryKey: imageKeys.deletePreview(repo, image, digest ?? ''), + queryFn: ({ signal }) => fetchImageDeletePreview(repo, image, digest ?? '', signal), + enabled: digest !== undefined, + staleTime: 0, + gcTime: 0, + retry: false, + }) +} + /** * Delete a tag or a manifest (the reference) of a hosted repository's image, * or (no reference) the whole image; refreshes every image query after. diff --git a/web/src/routes/ImageDetail.test.tsx b/web/src/routes/ImageDetail.test.tsx index 344acee6..00c8a9ec 100644 --- a/web/src/routes/ImageDetail.test.tsx +++ b/web/src/routes/ImageDetail.test.tsx @@ -10,7 +10,7 @@ import { import { clearSession } from '~/lib/auth' import type { Me } from '~/api/me' -import type { ChartDetail, ImageDetail } from '~/api/images' +import type { ChartDetail, ImageDeletePreview, ImageDetail } from '~/api/images' import type { BrowseRepo } from '~/api/packages' import { textContent } from '~/test/text' import { routeTree } from '~/routeTree.gen' @@ -124,18 +124,43 @@ const fetchMock = vi.fn() * Route the mock: `/admin/me` -> identity (`me`, a reader by default), * `/browse/repos` -> `repos`, * `/browse/images/{repo}/{image…}`, `/browse/chart` -> `chart` (404 without - * one), and a `DELETE /admin/repositories/{repo}/images` -> `deleteImage`. + * one), a `DELETE /admin/repositories/{repo}/images` -> `deleteImage`, and + * `GET …/images/delete-preview` -> `previews`, by digest (404 without one). */ + +/** A delete preview: of a manifest that goes alone, but for `fields`. */ +function previewOf(fields: Partial = {}): ImageDeletePreview { + return { + manifests: 1, + listed: 0, + referrers: 0, + tags: [], + tags_total: fields.tags?.length ?? 0, + indexes: [], + indexes_total: fields.indexes?.length ?? 0, + ...fields, + } +} + +/** The dialog's confirm button, once the preview has answered. */ +async function confirmButton(dialog: HTMLElement, name: string): Promise { + const button = within(dialog).getByRole('button', { name }) + await waitFor(() => expect(button).toBeEnabled()) + return button +} + function mockApi( detail: (repo: string, image: string) => Response, chart?: (query: URLSearchParams) => Response, { me = readerMe, deleteImage, + previews, repos, }: { me?: Me deleteImage?: (repo: string, query: URLSearchParams) => Response | Promise + previews?: Record> /** `/browse/repos` (404 without). */ repos?: BrowseRepo[] } = {}, @@ -150,6 +175,12 @@ function mockApi( if (del && init?.method === 'DELETE' && deleteImage) { return Promise.resolve(deleteImage(decodeURIComponent(del[1]), url.searchParams)) } + if (/^\/admin\/repositories\/[^/]+\/images\/delete-preview$/.test(url.pathname)) { + const preview = previews?.[url.searchParams.get('reference') ?? ''] + return Promise.resolve(preview).then((answer) => + answer ? jsonResponse(answer) : new Response('manifest not found', { status: 404 }), + ) + } if (url.pathname.endsWith('/browse/repos') && repos) { return Promise.resolve(jsonResponse(repos)) } @@ -764,6 +795,7 @@ describe('ImageDetail', () => { (q) => jsonResponse(stored(q.get('digest') ?? '')), { me: adminMe, + previews: { [CHART_OLD]: previewOf({ tags: ['1.9.0'] }) }, deleteImage: (repo, q) => { asked.push(`${repo}|${q.get('image')}|${q.get('reference')}`) current = { @@ -788,7 +820,11 @@ describe('ImageDetail', () => { const dialog = screen.getByRole('dialog') expect(dialog).toHaveTextContent('Delete stable/web 1.9.0?') expect(dialog).toHaveTextContent('This cannot be undone') - await user.click(within(dialog).getByRole('button', { name: 'Delete version' })) + await user.click(await confirmButton(dialog, 'Delete version')) + // Its own tag is the version: nothing else is said to go. + expect(dialog).toHaveTextContent( + 'Permanently delete version 1.9.0 of chart stable/web from repository charts. Clients that already pulled it keep their copy.', + ) await waitFor(() => expect(screen.queryByRole('button', { name: 'Delete version 1.9.0' })).toBeNull(), @@ -798,6 +834,60 @@ describe('ImageDetail', () => { expect(screen.getByRole('button', { name: 'Delete version 1.10.0' })).toBeInTheDocument() }) + it("says that a version's delete takes the manifest's other tags (#546)", async () => { + const asked: string[] = [] + let answer: (preview: ImageDeletePreview) => void = () => {} + mockApi( + () => jsonResponse(chartDetail), + (q) => jsonResponse(stored(q.get('digest') ?? '')), + { + me: adminMe, + previews: { + [CHART_OLD]: new Promise((resolve) => (answer = resolve)), + }, + deleteImage: (repo, q) => { + asked.push(`${repo}|${q.get('image')}|${q.get('reference')}`) + return jsonResponse({ manifests: 2, tags: 3 }) + }, + }, + ) + const user = userEvent.setup() + await renderDetail('/images/charts/stable/web') + + await user.click(await screen.findByRole('button', { name: 'Delete version 1.9.0' })) + const dialog = screen.getByRole('dialog') + // Not before the server has said what goes. + expect(within(dialog).getByRole('button', { name: 'Delete version' })).toBeDisabled() + expect(dialog).toHaveTextContent('Checking what this delete takes along…') + // `oras tag` put `stable` and `prod` on 1.9.0's manifest, and it is signed. + answer(previewOf({ manifests: 2, referrers: 1, tags: ['1.9.0', 'prod', 'stable'] })) + const confirm = await confirmButton(dialog, 'Delete version') + expect(dialog).toHaveTextContent( + 'Permanently delete version 1.9.0 of chart stable/web from repository charts, and with it the tags prod, stable of the same manifest. With it go 1 referrer (signatures, SBOMs, attestations); what a tag or another manifest still needs stays.', + ) + expect(dialog).not.toHaveTextContent('Checking') + await user.click(confirm) + await waitFor(() => expect(asked).toEqual([`charts|stable/web|${CHART_OLD}`])) + }) + + it("counts a version's other tags past the ones the server names", async () => { + const names = Array.from({ length: 50 }, (_, i) => `a${String(i).padStart(2, '0')}`) + mockApi( + () => jsonResponse(chartDetail), + (q) => jsonResponse(stored(q.get('digest') ?? '')), + // 61 tags on the manifest: 1.9.0 sorts after the 50 named ones. + { me: adminMe, previews: { [CHART_OLD]: previewOf({ tags: names, tags_total: 61 }) } }, + ) + const user = userEvent.setup() + await renderDetail('/images/charts/stable/web') + + await user.click(await screen.findByRole('button', { name: 'Delete version 1.9.0' })) + const dialog = screen.getByRole('dialog') + await confirmButton(dialog, 'Delete version') + expect(dialog).toHaveTextContent('and with it the tags a00, a01,') + expect(dialog).toHaveTextContent('a49 and 10 more of the same manifest.') + }) + it('renders an error state when the chart cannot be read', async () => { mockApi( () => jsonResponse(chartDetail), @@ -824,14 +914,20 @@ describe('ImageDetail', () => { } /** An admin's page whose deletes answer `answer` and leave `after`. */ - function mockDelete(after: ImageDetail | null, answer = jsonResponse({ manifests: 1, tags: 0 })) { + function mockDelete( + after: ImageDetail | null, + answer = jsonResponse({ manifests: 1, tags: 0 }), + previews: Record = {}, + before: ImageDetail = hostedDetail, + ) { const asked: { repo: string; image: string | null; reference: string | null }[] = [] - let current: ImageDetail | null = hostedDetail + let current: ImageDetail | null = before mockApi( () => (current ? jsonResponse(current) : new Response('image not found', { status: 404 })), undefined, { me: adminMe, + previews, deleteImage: (repo, q) => { asked.push({ repo, image: q.get('image'), reference: q.get('reference') }) if (answer.ok) current = after @@ -886,19 +982,23 @@ describe('ImageDetail', () => { }) it('deletes an index with what only it keeps, saying so first', async () => { - const asked = mockDelete(without([INDEX, ARM64, SIG]), jsonResponse({ manifests: 3, tags: 1 })) + const asked = mockDelete(without([INDEX, ARM64, SIG]), jsonResponse({ manifests: 3, tags: 1 }), { + // AMD64 is tagged `latest`, so it stays. + [INDEX]: previewOf({ manifests: 3, listed: 1, referrers: 1, tags: ['1.36'] }), + }) const user = userEvent.setup() await renderDetail('/images/docker-hosted/team/app') await user.click(await screen.findByRole('button', { name: 'Delete manifest 1111111111aa' })) const dialog = screen.getByRole('dialog') expect(dialog).toHaveTextContent('Delete manifest 1111111111aa?') + const confirm = await confirmButton(dialog, 'Delete manifest') expect(dialog).toHaveTextContent('with its tag 1.36') expect(dialog).toHaveTextContent( - 'With it go the 2 manifests it lists and the 1 referrer (signatures, SBOMs, attestations) of it, unless a tag or another manifest still needs them.', + 'With it go the 1 manifest it lists and 1 referrer (signatures, SBOMs, attestations); what a tag or another manifest still needs stays.', ) expect(within(dialog).queryByRole('alert')).toBeNull() - await user.click(within(dialog).getByRole('button', { name: 'Delete manifest' })) + await user.click(confirm) await waitFor(() => expect(screen.queryByRole('button', { name: 'Delete manifest 1111111111aa' })).toBeNull(), @@ -908,16 +1008,19 @@ describe('ImageDetail', () => { }) it('warns that an index lists the manifest, and shows a refusal', async () => { - const asked = mockDelete(null, new Response('internal error', { status: 500 })) + const asked = mockDelete(null, new Response('internal error', { status: 500 }), { + [ARM64]: previewOf({ indexes: [INDEX] }), + }) const user = userEvent.setup() await renderDetail('/images/docker-hosted/team/app') await user.click(await screen.findByRole('button', { name: 'Delete manifest 3333333333cc' })) const dialog = screen.getByRole('dialog') + const confirm = await confirmButton(dialog, 'Delete manifest') expect(within(dialog).getByRole('alert')).toHaveTextContent( 'Index 1111111111aa lists this manifest: pulling linux/arm64/v8 through it fails once the manifest is gone.', ) - await user.click(within(dialog).getByRole('button', { name: 'Delete manifest' })) + await user.click(confirm) expect(await within(dialog).findByText('Could not delete')).toBeInTheDocument() expect(dialog).toHaveTextContent('internal error') @@ -933,13 +1036,112 @@ describe('ImageDetail', () => { await user.click(await screen.findByRole('button', { name: 'Delete image…' })) const dialog = screen.getByRole('dialog') expect(dialog).toHaveTextContent('Delete team/app?') - expect(dialog).toHaveTextContent('2 tags and 4 manifests') + expect(dialog).toHaveTextContent('2 tags and 4 manifests. Clients') await user.click(within(dialog).getByRole('button', { name: 'Delete image' })) await waitFor(() => expect(router.state.location.pathname).toBe('/repos/docker-hosted')) expect(asked).toEqual([{ repo: 'docker-hosted', image: 'team/app', reference: null }]) }) + /** + * The page lists the newest 1,000 tags and manifests (here: 2 and 4 of + * 50,000 and 61,234); the confirmations count what the server deletes + * (#546). + */ + const partial: ImageDetail = { ...hostedDetail, tags_total: 50_000, manifests_total: 61_234 } + + it('counts every tag and manifest of an image the page lists in part', async () => { + mockDelete(null, undefined, {}, partial) + const user = userEvent.setup() + await renderDetail('/images/docker-hosted/team/app') + + await user.click(await screen.findByRole('button', { name: 'Delete image…' })) + expect(screen.getByRole('dialog')).toHaveTextContent( + 'Permanently delete image team/app from repository docker-hosted: 50,000 tags and 61,234 manifests, not only the newest this page lists. Clients', + ) + }) + + it('says what a manifest takes along that the page does not list', async () => { + // The page lists `latest` on AMD64, no referrer of it and no index but + // INDEX; the server knows two more tags, two SBOMs and an older index. + const OLD_INDEX = 'sha256:9999999999ab' + '0'.repeat(52) + const asked = mockDelete( + null, + jsonResponse({ manifests: 3, tags: 3 }), + { + [AMD64]: previewOf({ + manifests: 3, + referrers: 2, + tags: ['2019-01-01', 'latest', 'v1-amd64'], + indexes: [INDEX, OLD_INDEX], + }), + }, + partial, + ) + const user = userEvent.setup() + await renderDetail('/images/docker-hosted/team/app') + + await user.click(await screen.findByRole('button', { name: 'Delete manifest 2222222222bb' })) + const dialog = screen.getByRole('dialog') + const confirm = await confirmButton(dialog, 'Delete manifest') + expect(dialog).toHaveTextContent( + 'Permanently delete the manifest 2222222222bb of team/app with its tags 2019-01-01, latest, v1-amd64. With it go 2 referrers (signatures, SBOMs, attestations); what a tag or another manifest still needs stays. This cannot be undone.', + ) + expect(within(dialog).getByRole('alert')).toHaveTextContent( + 'Indexes 1111111111aa, 9999999999ab list this manifest: pulling linux/amd64 through them fails once the manifest is gone.', + ) + await user.click(confirm) + await waitFor(() => + expect(asked).toEqual([{ repo: 'docker-hosted', image: 'team/app', reference: AMD64 }]), + ) + }) + + it('counts the tags and indexes past the ones the server names', async () => { + mockDelete(null, undefined, { + [ARM64]: previewOf({ + tags: ['a', 'b'], + tags_total: 1_202, + indexes: [INDEX], + indexes_total: 3, + }), + }) + const user = userEvent.setup() + await renderDetail('/images/docker-hosted/team/app') + + await user.click(await screen.findByRole('button', { name: 'Delete manifest 3333333333cc' })) + const dialog = screen.getByRole('dialog') + await confirmButton(dialog, 'Delete manifest') + expect(dialog).toHaveTextContent('with its tags a, b and 1,200 more.') + expect(within(dialog).getByRole('alert')).toHaveTextContent( + 'Indexes 1111111111aa and 2 more list this manifest: pulling linux/arm64/v8 through them fails', + ) + }) + + it('says what the server does when it cannot be asked what goes along', async () => { + // No preview: the mock answers 404. + const asked = mockDelete(without([INDEX, ARM64, SIG]), jsonResponse({ manifests: 3, tags: 1 })) + const user = userEvent.setup() + await renderDetail('/images/docker-hosted/team/app') + + await user.click(await screen.findByRole('button', { name: 'Delete manifest 1111111111aa' })) + const dialog = screen.getByRole('dialog') + const confirm = await confirmButton(dialog, 'Delete manifest') + // Nothing is counted from the page's rows (a tag, two listed, a referrer). + expect(dialog).toHaveTextContent( + 'Permanently delete the manifest 1111111111aa of team/app. This cannot be undone.', + ) + const alert = within(dialog).getByRole('alert') + expect(alert).toHaveTextContent('Could not check what this delete takes along') + expect(alert).toHaveTextContent( + 'The manifest goes with every tag on it, also tags this page does not list, and with the manifests it lists and its referrers', + ) + expect(alert).toHaveTextContent('(manifest not found)') + await user.click(confirm) + await waitFor(() => + expect(asked).toEqual([{ repo: 'docker-hosted', image: 'team/app', reference: INDEX }]), + ) + }) + it('returns to the repository when the last manifest is gone', async () => { const only: ImageDetail = { ...hostedDetail, @@ -952,6 +1154,7 @@ describe('ImageDetail', () => { undefined, { me: adminMe, + previews: { [AMD64]: previewOf({ tags: ['latest'] }) }, deleteImage: () => { gone = true return jsonResponse({ manifests: 1, tags: 1 }) @@ -962,9 +1165,7 @@ describe('ImageDetail', () => { const router = await renderDetail('/images/docker-hosted/team/app') await user.click(await screen.findByRole('button', { name: 'Delete manifest 2222222222bb' })) - await user.click( - within(screen.getByRole('dialog')).getByRole('button', { name: 'Delete manifest' }), - ) + await user.click(await confirmButton(screen.getByRole('dialog'), 'Delete manifest')) await waitFor(() => expect(router.state.location.pathname).toBe('/repos/docker-hosted')) })