diff --git a/AGENTS.md b/AGENTS.md index 2fbd99fc..07501533 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -677,11 +677,19 @@ neither one's. behind a bool. πŸ”΄ Doing that leaks a full-scope personal API key. `isTrustedDownloadHost` attaches the bearer token to `civitai.com` and to **any** `*.civitai.com` subdomain β€” correct for the model-download route it - was written for β€” and orchestrator output blobs are served from - `orchestration.civitai.com`, which **matches**. So `DownloadFile` would send - a 25-scope key (including `ModelsDelete` and `VaultWrite`) to the - orchestrator, on a request that is already authorized by its own signature - and needs no token whatsoever. + was written for β€” and orchestrator output blobs are served from a + `*.civitai.com` host (observed: `orchestration-new.civitai.com`), which + **matches**. So `DownloadFile` would send a 25-scope key (including + `ModelsDelete` and `VaultWrite`) to the orchestrator, on a request that is + already authorized by its own signature and needs no token whatsoever. + πŸ”΄ **The specific subdomain is incidental to the argument, and must not be + written as if it were the load-bearing fact.** An earlier revision of this + item named `orchestration.civitai.com`; the host actually observed in a real + upload reply is `orchestration-new.civitai.com`. BOTH match the `*.civitai.com` + wildcard, so the credential-free seam is required either way β€” which is + exactly why the reasoning is stated over the wildcard rather than over a + hostname a server-side rename can invalidate. Do not "fix" this seam because + the subdomain you see does not match the one written here. Weakening `isTrustedDownloadHost` is not the alternative: `civitai download` depends on it attaching the token. The fix is a **seam that never has a credential to attach** β€” `DownloadPresigned` passes `""` to `doDownload`, @@ -901,9 +909,12 @@ neither one's. item 17's download does not.** `UploadPresigned` (`pkg/civitai/upload.go`) is a near-duplicate of `DownloadPresigned` and will attract the same "fold it back in behind a bool". The upload URL is **server-supplied** and lives on a - `*.civitai.com` host, which `isTrustedDownloadHost` **matches**, so a - token-carrying path would hand a 25-scope personal API key to a request its - own signature already authorizes. The interface has no token parameter and + `*.civitai.com` host (observed: `orchestration-new.civitai.com`), which + `isTrustedDownloadHost` **matches**, so a token-carrying path would hand a + 25-scope personal API key to a request its own signature already authorizes. + As in item 17, the WILDCARD is the load-bearing fact and the subdomain is + incidental β€” the seam is required for any `*.civitai.com` host, so a rename + server-side changes nothing here. The interface has no token parameter and consults no `TokenSource`, so the safety is structural rather than conditional. `genapi.UploadImageBlob`'s two hops differ on purpose β€” hop 1 (presign) is authed, hop 2 (upload) is not β€” and the test asserts BOTH, since diff --git a/README.md b/README.md index 36989a72..0c7e8a3d 100644 --- a/README.md +++ b/README.md @@ -217,7 +217,7 @@ README. For the end-to-end walkthrough, see | `civitai generate "" [--negative-prompt

] [--quantity ] [--aspect-ratio ] [--checkpoint ] [--lora [:strength]] [--image ] [--ecosystem ] [--input ] [--print-input] [--dry-run] [--json] [--max-cost ] [--yes] [--no-wait] [--timeout ] [--out-dir

] [--no-download] [--force] [--external-id ]` | **Generate images from a text prompt β€” this SPENDS REAL BUZZ.** Prices the job with the server's estimator, shows the cost + your balance, asks before spending, submits, then **waits and downloads** the results into `--out-dir` as `-.`. `--no-wait` prints the workflow id and exits; `--timeout` bounds the **wait** (never the job and never the charge); `--no-download` waits but prints URLs instead of writing files. `--dry-run` estimates and exits without submitting (`--dry-run --json` emits the raw estimate). `--print-input` prints the assembled graph and exits **without reaching any money seam** (no submit, no estimate, no balance read) β€” note that with `--image` it still **uploads** local files first, because the printed graph has to reference real blob URLs for `--input` to be able to submit it; uploading spends nothing; `--input ` (or `-` for stdin) sends a raw graph as-is β€” txt2img only, and mutually exclusive with the content flags. `--image ` (repeatable) attaches a reference image for **image-to-image** β€” a local png/jpeg is uploaded, an https URL is passed through β€” and **requires `--ecosystem`**, because without one the server ignores the images, generates from the prompt alone and charges anyway. Needs a **personal API key** with the AI Services scopes; an OAuth login is refused. `--max-cost` is an **estimate check, not a spending cap**. See [Generate](#generate). | | `civitai workflows list [--limit ] [--cursor ] [--tag ] [--json]` | **List the generation workflows you have submitted**, newest first β€” status, when, cost, and `deliverable/total` outputs. Cursor-paged: the next cursor is printed on stdout when more results exist. Reading spends nothing. See [Generate](#listing-and-cancelling-workflows). | | `civitai workflows get [--json]` | **Look up one generation workflow** β€” status, steps and outputs. This is how you re-attach after `--no-wait`, a `--timeout` expiry or a Ctrl-C. Outputs that are blocked, unavailable or hidden are listed **with the reason** rather than omitted. Output URLs are presigned and expire; re-run for fresh links. Reading spends nothing. See [Generate](#waiting-downloading-and-re-attaching). | -| `civitai workflows cancel [--json]` | **Stop a running generation.** πŸ”΄ **This does not refund anything** β€” a mid-run cancel bills the accrued cost, non-refundably. Cancel because you no longer want the output, never to save money. See [Generate](#listing-and-cancelling-workflows). | +| `civitai workflows cancel [--yes] [--json]` | **Stop a running generation.** πŸ”΄ **This does not refund anything** β€” a mid-run cancel bills the accrued cost, non-refundably. Cancel because you no longer want the output, never to save money. Asks for confirmation (default **no**); `--yes` skips the prompt and a non-TTY without it refuses. See [Generate](#listing-and-cancelling-workflows). | | `civitai version` | Print version / commit / build date. | | `civitai completion [shell]` | Generate a shell-completion script. | @@ -1213,7 +1213,8 @@ civitai workflows list # newest first civitai workflows list --limit 5 civitai workflows list --limit 50 --cursor civitai workflows list --json # raw server payload, incl. nextCursor -civitai workflows cancel +civitai workflows cancel # asks for confirmation +civitai workflows cancel -y # skip the prompt (scripts/CI) ``` `list` is **cursor-paged**, not page-numbered: when more results exist it prints @@ -1234,6 +1235,20 @@ the per-output reason. > do **not** cancel: stopping the wait costs nothing, while stopping the job > would cost the same as letting it finish and throw the result away.) +`cancel` **asks for confirmation**, matching `civitai generate` and +`civitai app submit`. It is the one irreversible action here, and it destroys a +job you have already paid for, so it is gated the same way every other +destructive path in this feature is: + +- `--yes` / `-y` proceeds without prompting; +- an interactive terminal prints what is lost and prompts β€” the default is + **no**, so a bare Enter aborts; +- a **non-interactive** shell without `--yes` **refuses** rather than cancelling + silently. Scripts must pass `--yes` explicitly. + +Nothing is cancelled when the confirmation is refused β€” the gate runs before the +request goes out. + ### Exit codes specific to `generate` `generate` follows the [global exit-code table](#exit-codes), with one diff --git a/internal/cmd/generate.go b/internal/cmd/generate.go index 48bc33de..e3e99089 100644 --- a/internal/cmd/generate.go +++ b/internal/cmd/generate.go @@ -689,9 +689,10 @@ func buildGenerateGraph(ctx context.Context, deps generateDeps, o generateOpts) } out.graph.Images = imgs // Label each image with the SOURCE the user typed, not just the blob URL it - // became: after upload every entry is an opaque orchestration.civitai.com - // blob, so a confirmation listing only those cannot be matched back to the - // files on disk β€” which is the whole point of showing them before a spend. + // became: after upload every entry is an opaque blob URL on a *.civitai.com + // host (observed: orchestration-new.civitai.com), so a confirmation listing + // only those cannot be matched back to the files on disk β€” which is the whole + // point of showing them before a spend. // resolveImages preserves order, so imgs[i] is o.images[i]. for i, img := range imgs { src := "" diff --git a/internal/cmd/generate_confirm_test.go b/internal/cmd/generate_confirm_test.go new file mode 100644 index 00000000..8b10b20c --- /dev/null +++ b/internal/cmd/generate_confirm_test.go @@ -0,0 +1,217 @@ +package cmd + +import ( + "context" + "errors" + "strings" + "testing" +) + +// πŸ”΄ Nothing in this file may reach a real server: every case drives the stubbed +// genSeams submit counter, which is what makes "0 submits" a MEASURED zero. + +// --- the prompt defaults to NO ------------------------------------------------ + +// πŸ”΄ THE default-deny guard for the spend prompt. +// +// The existing tests feed only "y" and "n", and that pair CANNOT see the +// mutation this test exists to kill β€” rewriting confirmGenerate's +// +// case "y", "yes": proceed; default: cancel +// +// as +// +// case "n", "no": cancel; default: proceed +// +// keeps both of those cases green while silently turning `[y/N]` into `[Y/n]`. +// The difference is only observable on an answer that is NEITHER accepting NOR +// explicitly refusing: a bare Enter, a typo, a stray "1". Under the mutation +// every one of those SPENDS REAL BUZZ. +// +// "n" and "no" are deliberately absent from the deny table below: they abort +// under the mutation too, so they discriminate nothing. +func TestGenerate_PromptDefaultsToNoAndNeverSubmits(t *testing.T) { + withStdinTTY(t, true) + + deny := []struct { + name string + stdin string + }{ + {"bare Enter", "\n"}, + {"empty stdin (EOF)", ""}, + {"whitespace only", " \n"}, + {"maybe", "maybe\n"}, + {"yy", "yy\n"}, + {"Ye (prefix of yes, not yes)", "Ye\n"}, + {"1", "1\n"}, + {"ok", "ok\n"}, + {"sure", "sure\n"}, + {"yeah", "yeah\n"}, + {"y-with-trailing-junk", "y!\n"}, + } + for _, tc := range deny { + t.Run("deny/"+tc.name, func(t *testing.T) { + var s genSeams + c, out, errb := genCmd(tc.stdin) + err := runGenerate(c, s.deps(t), baseOpts()) + if err == nil { + t.Fatalf("answer %q: want a cancellation, got nil", tc.stdin) + } + // πŸ”΄ The load-bearing assertion: no money moved. Under the inverted + // switch this is 1. + if s.submitCalls != 0 { + t.Errorf("πŸ”΄ answer %q SPENT BUZZ: submit called %d time(s), want 0", tc.stdin, s.submitCalls) + } + // The case must actually have reached the switch. Without this, a + // refusal from some earlier guard would look like a default-deny. + if !strings.Contains(errb.String(), "[y/N]") { + t.Errorf("answer %q: no prompt printed, so this case never reached the switch:\n%s", tc.stdin, errb.String()) + } + if strings.Contains(out.String(), "wf_123") { + t.Errorf("answer %q: a workflow id was printed for a cancelled run: %q", tc.stdin, out.String()) + } + }) + } + + // πŸ”΄ POSITIVE CONTROLS, in the same test. Every zero above is only meaningful + // because these drive the SAME counter, through the SAME deps constructor, to + // 1 β€” a submit seam wired to nothing would report 0 for the whole table. + for _, tc := range []struct { + name string + stdin string + }{ + {"y", "y\n"}, + {"yes", "yes\n"}, + {"Y uppercase", "Y\n"}, + {"YES uppercase", "YES\n"}, + {"y with surrounding spaces", " y \n"}, + } { + t.Run("accept/"+tc.name, func(t *testing.T) { + var s genSeams + c, out, _ := genCmd(tc.stdin) + if err := runGenerate(c, s.deps(t), baseOpts()); err != nil { + t.Fatalf("answer %q: want the generation to proceed, got %v", tc.stdin, err) + } + if s.submitCalls != 1 { + t.Fatalf("POSITIVE CONTROL FAILED: answer %q submitted %d times, want 1 β€” the zeros in the deny table prove nothing", + tc.stdin, s.submitCalls) + } + if !strings.Contains(out.String(), "wf_123") { + t.Errorf("answer %q: accepted run printed no workflow id: %q", tc.stdin, out.String()) + } + }) + } +} + +// πŸ”΄ The non-TTY refusal must hold REGARDLESS of what is on stdin. +// +// TestGenerate_NonTTYWithoutYesRefusesAndNeverSubmits pipes EMPTY stdin, so if +// the `!stdinIsTTY()` refusal were removed the run would fall through to the +// prompt, read EOF, and cancel anyway β€” the submit counter stays at 0 and only +// the message assertions notice. The counter never discriminates, so the guard +// is pinned by its wording rather than by its behaviour. +// +// Piping "y" is the real shape of the hazard: a CI job that answers the prompt +// on stdin instead of passing --yes. With the non-TTY branch gone, that SPENDS +// REAL BUZZ with no --yes anywhere in the command line. The claim is "a terminal +// is attached", not "somebody typed something". +func TestGenerate_NonTTYIgnoresPipedYes(t *testing.T) { + withStdinTTY(t, false) + + for _, piped := range []string{"y\n", "yes\n", "Y\n", "YES\n"} { + var s genSeams + c, _, errb := genCmd(piped) + err := runGenerate(c, s.deps(t), baseOpts()) + if err == nil { + t.Errorf("non-TTY with %q piped to stdin: want a refusal, got nil", piped) + } + if s.submitCalls != 0 { + t.Errorf("πŸ”΄ non-TTY with %q piped to stdin SPENT BUZZ (%d submit(s)) β€” piped input is not a confirmation", + piped, s.submitCalls) + } + if strings.Contains(errb.String(), "[y/N]") { + t.Errorf("non-TTY with %q piped: a prompt was printed to a shell that cannot answer it", piped) + } + } + + // POSITIVE CONTROL: the same seam, same non-TTY, with --yes β€” submits. + var ok genSeams + o := baseOpts() + o.assumeYes = true + c, _, _ := genCmd("") + if err := runGenerate(c, ok.deps(t), o); err != nil { + t.Fatalf("positive control (--yes on a non-TTY): %v", err) + } + if ok.submitCalls != 1 { + t.Fatalf("POSITIVE CONTROL FAILED: submit called %d times, want 1", ok.submitCalls) + } +} + +// --- the cost-vs-balance boundary -------------------------------------------- + +// πŸ”΄ The `cost > balance` comparison at its BOUNDARY. +// +// Surviving mutation: `>` β†’ `>=`. Every existing case sits far from the edge +// (balance 3 vs cost 12, or balance 1,000,000), so none of them can tell the two +// operators apart. Spending your last Buzz on a job you can exactly afford is a +// legitimate, and not especially rare, thing to do β€” under `>=` it is refused +// with "exceeds your balance of 12", which is simply false. +// +// The three points are measured together so the claim carries its own scope: +// just below the balance, exactly at it, and just above it. +func TestGenerate_CostEqualToBalanceIsAffordable(t *testing.T) { + withStdinTTY(t, false) + + const cost = 12 // genSeams' default quote (okQuote(12)) + + cases := []struct { + name string + balance int64 + wantSubmits int + wantErr bool + }{ + // Below the cost: refused. This is the POSITIVE CONTROL for the guard β€” + // it proves the balance check is wired up and CAN fire, so the zeros in + // the "want a refusal" direction are real. + {"balance one below the cost", cost - 1, 0, true}, + // πŸ”΄ AT the boundary: affordable. This is the case `>=` gets wrong. + {"balance exactly equal to the cost", cost, 1, false}, + // Above: affordable (guards against `<` style inversions too). + {"balance one above the cost", cost + 1, 1, false}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var s genSeams + bal := tc.balance + s.balance = func(context.Context) (int64, error) { return bal, nil } + o := baseOpts() + o.assumeYes = true + c, _, _ := genCmd("") + err := runGenerate(c, s.deps(t), o) + + if tc.wantErr { + if err == nil { + t.Fatalf("balance %d vs cost %d: want a refusal, got nil", tc.balance, cost) + } + // Pinned by errors.Is, never by message text. + if !errors.Is(err, ErrInsufficientBuzz) { + t.Errorf("balance %d: want ErrInsufficientBuzz, got %v", tc.balance, err) + } + } else if err != nil { + t.Fatalf("balance %d vs cost %d: this job IS affordable and must not be refused: %v", + tc.balance, cost, err) + } + + if s.submitCalls != tc.wantSubmits { + t.Errorf("balance %d vs cost %d: submit called %d time(s), want %d", + tc.balance, cost, s.submitCalls, tc.wantSubmits) + } + // The balance seam must have been consulted, or the comparison under + // test never ran and the whole case is vacuous. + if s.balanceCalls != 1 { + t.Errorf("balance seam called %d time(s), want 1 β€” the comparison under test did not run", s.balanceCalls) + } + }) + } +} diff --git a/internal/cmd/generate_image.go b/internal/cmd/generate_image.go index 554cb460..880b0462 100644 --- a/internal/cmd/generate_image.go +++ b/internal/cmd/generate_image.go @@ -165,6 +165,22 @@ func decodeImageHeader(r io.Reader, what string) (int, int, string, error) { "%s could not be read as an image (%w) β€” the file may be truncated or corrupt; supported formats: %s", what, err, supportedImageFormatList()) } + // πŸ”΄ DEFENSIVE ONLY β€” this branch is UNREACHABLE as the package is currently + // built, and no test can kill a mutation inside it. image.DecodeConfig can + // only name a format whose decoder is registered, this file registers exactly + // png and jpeg (the blank imports above), and both are keys of + // supportedImageFormats β€” so every input either yields one of those two names + // or fails earlier with image.ErrFormat. Neutering this `if` therefore leaves + // the whole suite green, and that is a fact about reachability, not a missing + // test: forcing it reachable would mean registering a third decoder, which is + // exactly what gifBytes() in generate_image_test.go documents as the thing + // that would silently destroy the real unsupported-format test. + // + // It is kept because the invariant it depends on is one line away from being + // broken: adding a blank import WITHOUT adding the map entry makes this the + // live guard that stops an unlabelled format reaching the upload. That + // lockstep is what TestSupportedImageFormats_DecoderRegistrationIsInLockstep + // pins β€” the reachable half of this rule. if _, ok := supportedImageFormats[format]; !ok { return 0, 0, "", fmt.Errorf( "%s is a %s image, which this CLI cannot attach β€” supported formats: %s", diff --git a/internal/cmd/generate_image_guards_test.go b/internal/cmd/generate_image_guards_test.go new file mode 100644 index 00000000..09021c1b --- /dev/null +++ b/internal/cmd/generate_image_guards_test.go @@ -0,0 +1,324 @@ +package cmd + +import ( + "bytes" + "context" + "errors" + "fmt" + "image" + "io" + "net/http" + "strings" + "sync" + "testing" +) + +// --- degenerate dimensions ---------------------------------------------------- + +// πŸ”΄ The `cfg.Width <= 0 || cfg.Height <= 0` guard, at its BOUNDARY. +// +// Surviving mutation: `<= 0` β†’ `< 0`. No fixture in the suite decoded to a zero +// dimension, so nothing could tell the two apart β€” and `< 0` is unreachable in +// practice, which makes the mutated guard permanently inert. +// +// A zero-dimension image is not hypothetical and is not malformed enough to be +// caught upstream. MEASURED with the Go 1.25 stdlib: +// +// jpeg.Encode of a 16x0 image -> 591 bytes, DecodeConfig returns +// format="jpeg", w=16, h=0, err=nil +// png.Encode of a 16x0 image -> the ENCODER refuses ("invalid image size") +// +// so JPEG is the format that can express it and PNG is not β€” which is why every +// fixture here is a JPEG. `image.DecodeConfig` hands those dimensions back +// cleanly, so without this guard a `width: 0` reaches genapi.GraphImage and then +// the server, where item 19(d) records that the images node validates the +// transformed array and a bad entry is a hard 400 AFTER the graph is priced. +func TestDecodeImageHeader_RefusesDegenerateDimensions(t *testing.T) { + degenerate := []struct { + name string + w, h int + }{ + {"zero width", 0, 16}, + {"zero height", 16, 0}, + {"both zero", 0, 0}, + } + for _, tc := range degenerate { + t.Run(tc.name, func(t *testing.T) { + data := jpegBytes(t, tc.w, tc.h) + + // Precondition, stated as an assertion rather than assumed: the + // decoder really does accept this fixture and report the zero. If a + // future stdlib starts rejecting it, this test must fail LOUDLY here + // rather than pass for the wrong reason. + cfg, format, derr := image.DecodeConfig(bytes.NewReader(data)) + if derr != nil { + t.Fatalf("fixture precondition broken: DecodeConfig refused the %dx%d jpeg itself (%v) β€” this case no longer reaches the dimension guard", + tc.w, tc.h, derr) + } + if format != "jpeg" { + t.Fatalf("fixture precondition broken: format = %q, want jpeg", format) + } + if cfg.Width != tc.w || cfg.Height != tc.h { + t.Fatalf("fixture precondition broken: decoded %dx%d, want %dx%d", cfg.Width, cfg.Height, tc.w, tc.h) + } + + // πŸ”΄ The guard itself. + w, h, _, err := decodeImageHeader(bytes.NewReader(data), "--image x") + if err == nil { + t.Fatalf("πŸ”΄ a %dx%d image was ACCEPTED (returned %dx%d) β€” the server requires positive width and height", + tc.w, tc.h, w, h) + } + // This must be the DIMENSION refusal, not the unknown-format or + // corrupt-file arm. A test that is green because a *different* guard + // fired is green for the wrong reason. + if !strings.Contains(err.Error(), "degenerate size") { + t.Errorf("wrong guard fired for %dx%d: %v", tc.w, tc.h, err) + } + }) + } + + // POSITIVE CONTROL: the same helper, the same format, positive dimensions β€” + // accepted. Without it, the refusals above could equally come from a + // decodeImageHeader that rejects every JPEG. + t.Run("positive control: a positive-dimension jpeg is accepted", func(t *testing.T) { + w, h, format, err := decodeImageHeader(bytes.NewReader(jpegBytes(t, 24, 40)), "--image x") + if err != nil { + t.Fatalf("POSITIVE CONTROL FAILED: a valid 24x40 jpeg was refused: %v", err) + } + if w != 24 || h != 40 || format != "jpeg" { + t.Fatalf("POSITIVE CONTROL FAILED: got %dx%d %q, want 24x40 jpeg", w, h, format) + } + }) +} + +// The same boundary through the REAL --image path, so the guard is pinned where +// a user meets it and not only at the helper. A degenerate file must be refused +// as a usage error and must never be uploaded. +func TestResolveLocalImage_DegenerateDimensionsAreRefusedBeforeUpload(t *testing.T) { + dir := t.TempDir() + bad := writeFixture(t, dir, "flat.jpg", jpegBytes(t, 16, 0)) + + s := &genSeams{} + _, err := resolveImages(context.Background(), s.deps(t), []string{bad}) + if err == nil { + t.Fatal("πŸ”΄ a 16x0 image was accepted by --image") + } + if !errors.Is(err, ErrUsage) { + t.Errorf("want ErrUsage (exit 2), got %v", err) + } + // πŸ”΄ Nothing was uploaded: the refusal happens before the network write. + if s.uploadCalls != 0 { + t.Errorf("a degenerate image was uploaded anyway (%d upload(s))", s.uploadCalls) + } + + // POSITIVE CONTROL for that zero: the SAME seam, driven by a valid file. + good := writeFixture(t, dir, "ok.jpg", jpegBytes(t, 24, 40)) + ok := &genSeams{} + imgs, err := resolveImages(context.Background(), ok.deps(t), []string{good}) + if err != nil { + t.Fatalf("POSITIVE CONTROL FAILED: a valid image was refused: %v", err) + } + if ok.uploadCalls != 1 { + t.Fatalf("POSITIVE CONTROL FAILED: upload seam called %d times, want 1 β€” the 0 above proves nothing", ok.uploadCalls) + } + if imgs[0].Width != 24 || imgs[0].Height != 40 { + t.Errorf("dimensions = %dx%d, want 24x40", imgs[0].Width, imgs[0].Height) + } +} + +// --- the supported-format allowlist ------------------------------------------- + +// The REACHABLE half of the unsupported-format rule. +// +// The `if _, ok := supportedImageFormats[format]; !ok` branch in +// decodeImageHeader is UNREACHABLE as the package is built (see the comment at +// that branch): only png and jpeg have registered decoders, both are keys of the +// map, and everything else fails earlier with image.ErrFormat. Neutering it +// therefore survives, and no test can change that without registering a third +// decoder β€” which gifBytes() documents as the thing that would silently destroy +// the real unsupported-format test. +// +// So instead of pretending to cover the branch, this pins the INVARIANT that +// makes it unreachable, which is the thing that can actually regress: the map +// and the blank imports must stay in lockstep. Add a decoder without a map +// entry and the "unsupported format" arm goes live for a format users can +// legitimately hand us; add a map entry without a decoder and the CLI advertises +// a format it cannot read. +func TestSupportedImageFormats_DecoderRegistrationIsInLockstep(t *testing.T) { + // Every advertised format must actually DECODE, and must decode under the + // name the map is keyed by (the Content-Type is looked up with that key). + fixtures := map[string]func(t *testing.T, w, h int) []byte{ + "png": pngBytes, + "jpeg": jpegBytes, + } + for format := range supportedImageFormats { + fixture, ok := fixtures[format] + if !ok { + t.Fatalf("supportedImageFormats advertises %q but this test has no fixture for it β€” "+ + "a format was added to the map without proving a decoder is registered for it", format) + } + _, _, got, err := decodeImageHeader(bytes.NewReader(fixture(t, 12, 20)), "--image x") + if err != nil { + t.Errorf("advertised format %q does not decode: %v β€” the map and the blank imports have drifted", format, err) + } + if got != format { + t.Errorf("fixture for %q decoded as %q β€” the map key must be the name image.DecodeConfig reports", format, got) + } + } + + // The content types are what the upload POST is labelled with; assert the + // VALUES, not just that the keys exist. + want := map[string]string{"png": "image/png", "jpeg": "image/jpeg"} + if len(supportedImageFormats) != len(want) { + t.Errorf("supportedImageFormats has %d entries (%v), want %d β€” "+ + "if a format was added on purpose, add it to this test AND check the unreachability comment in decodeImageHeader is still true", + len(supportedImageFormats), supportedImageFormats, len(want)) + } + for k, v := range want { + if supportedImageFormats[k] != v { + t.Errorf("supportedImageFormats[%q] = %q, want %q", k, supportedImageFormats[k], v) + } + } + + // The user-facing list must name exactly the advertised formats. It is a + // hand-written string (a map range would reorder between runs), so it is the + // half most likely to go stale. + list := supportedImageFormatList() + for format := range supportedImageFormats { + if !strings.Contains(list, format) { + t.Errorf("supportedImageFormatList() = %q does not mention the advertised format %q", list, format) + } + } + + // NEGATIVE CONTROL: an unregistered format fails EARLY, with ErrFormat β€” + // which is exactly why the allowlist branch cannot be reached. If this ever + // stops being ErrFormat, the unreachability comment in decodeImageHeader is + // wrong and must be revisited. + _, _, gifFormat, err := decodeImageHeader(bytes.NewReader(gifBytes()), "--image x") + if err == nil { + t.Fatal("gif was accepted β€” a decoder for it has been registered somewhere in this test binary") + } + if gifFormat != "" { + t.Errorf("gif decoded as %q; the allowlist branch may now be reachable", gifFormat) + } + if !strings.Contains(err.Error(), "not an image this CLI recognises") { + t.Errorf("gif failed via the wrong arm (%v) β€” the unreachability argument for the allowlist branch depends on this being the ErrFormat arm", err) + } +} + +// --- response-body handle leaks ----------------------------------------------- + +// closeRecorder is a response body that records whether it was closed. The +// recording happens on the side THIS TEST owns β€” not on the server β€” so the +// observation is synchronous with the call under test and cannot race. +type closeRecorder struct { + mu sync.Mutex + reader io.Reader + closed int +} + +func newCloseRecorder(data []byte) *closeRecorder { + return &closeRecorder{reader: bytes.NewReader(data)} +} + +func (c *closeRecorder) Read(p []byte) (int, error) { return c.reader.Read(p) } + +func (c *closeRecorder) Close() error { + c.mu.Lock() + defer c.mu.Unlock() + c.closed++ + return nil +} + +func (c *closeRecorder) closeCount() int { + c.mu.Lock() + defer c.mu.Unlock() + return c.closed +} + +// πŸ”΄ resolveRemoteImage must close the response body on EVERY path. +// +// Surviving mutation: delete `defer resp.Body.Close()`. A leaked body holds the +// connection out of the pool; with `--image` passed several times that is one +// leak per reference image, and the fetch happens before a spend the user is +// still deciding on. +// +// The fetcher seam returns a response this test constructed, so "was it closed?" +// is answered by a counter in this process at the moment resolveRemoteImage +// returns. There is no server, no goroutine and no timing dependency, which is +// what keeps it deterministic. +func TestResolveRemoteImage_ClosesTheResponseBody(t *testing.T) { + cases := []struct { + name string + status int + body []byte + wantOK bool + }{ + {"success", http.StatusOK, pngBytes(t, 64, 48), true}, + {"non-2xx", http.StatusForbidden, []byte("nope"), false}, + {"2xx but undecodable", http.StatusOK, []byte("not an image at all"), false}, + {"2xx but degenerate dimensions", http.StatusOK, jpegBytes(t, 16, 0), false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := newCloseRecorder(tc.body) + s := &genSeams{downloadBlob: func(context.Context, string) (*http.Response, error) { + return &http.Response{StatusCode: tc.status, Body: rec, Header: make(http.Header)}, nil + }} + + _, err := resolveImages(context.Background(), s.deps(t), []string{"https://example.com/pic.png"}) + if tc.wantOK && err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !tc.wantOK && err == nil { + t.Fatal("want an error for this case") + } + + // πŸ”΄ THE assertion, on every path. + if got := rec.closeCount(); got != 1 { + t.Errorf("πŸ”΄ HANDLE LEAK: the response body was closed %d time(s), want exactly 1", got) + } + }) + } + + // POSITIVE CONTROL for the recorder: it reports 0 when nothing closes it, so + // a "1" above is a real observation and not a counter stuck at one. + t.Run("control: the recorder can report zero", func(t *testing.T) { + rec := newCloseRecorder([]byte("x")) + if got := rec.closeCount(); got != 0 { + t.Fatalf("CONTROL FAILED: a never-closed recorder reports %d, want 0", got) + } + _ = rec.Close() + if got := rec.closeCount(); got != 1 { + t.Fatalf("CONTROL FAILED: recorder counted %d closes after one Close(), want 1", got) + } + }) +} + +// Every reference image gets its body closed, not just the first β€” the leak this +// guards against is per-image, so a loop is where it bites. +func TestResolveRemoteImage_ClosesEveryBodyAcrossMultipleImages(t *testing.T) { + const n = 4 + var recs []*closeRecorder + s := &genSeams{downloadBlob: func(context.Context, string) (*http.Response, error) { + rec := newCloseRecorder(pngBytes(t, 64, 48)) + recs = append(recs, rec) + return &http.Response{StatusCode: http.StatusOK, Body: rec, Header: make(http.Header)}, nil + }} + + urls := make([]string, 0, n) + for i := 0; i < n; i++ { + urls = append(urls, fmt.Sprintf("https://example.com/pic%d.png", i)) + } + if _, err := resolveImages(context.Background(), s.deps(t), urls); err != nil { + t.Fatalf("resolveImages: %v", err) + } + if len(recs) != n { + t.Fatalf("the fetch seam was reached %d time(s), want %d", len(recs), n) + } + for i, rec := range recs { + if got := rec.closeCount(); got != 1 { + t.Errorf("πŸ”΄ HANDLE LEAK: image %d's body was closed %d time(s), want 1", i, got) + } + } +} diff --git a/internal/cmd/generate_state.go b/internal/cmd/generate_state.go index 9109d15c..4b9ca69c 100644 --- a/internal/cmd/generate_state.go +++ b/internal/cmd/generate_state.go @@ -32,11 +32,21 @@ type pendingGeneration struct { ExternalID string `json:"externalId"` // SubmittedAt is when the CLI was about to POST, in RFC3339. SubmittedAt string `json:"submittedAt"` - // PayloadHash is the SHA-256 of the marshalled GRAPH. It exists so a - // re-attach can tell "the same job" from "a different job that reused the - // key" β€” the orchestrator would silently return the FIRST workflow either - // way, so a mismatch here is the only local signal that the key no longer - // describes what the user is asking for. + // PayloadHash is the SHA-256 of the marshalled GRAPH. + // + // πŸ”΄ It is RECORDED ONLY β€” nothing reads it back and compares it. The single + // reader of a written record is recordPendingWorkflowID, which loads the file + // solely to add the workflow id and rewrites this field unchanged. So the CLI + // does NOT today detect "a different job that reused the key", and this + // comment must not claim it does: the comparison needs a recover/re-attach + // flow that does not exist yet. + // + // It is written now because the value is only obtainable at submit time β€” + // once the process is gone the graph is gone with it β€” so recording it is + // what keeps that future comparison POSSIBLE. If you add the recover flow, + // the comparison is the point: the orchestrator silently returns the FIRST + // workflow for a reused key, so a hash mismatch would be the only local + // signal that the key no longer describes what the user is asking for. PayloadHash string `json:"payloadHash"` // BaseURL records which server was charged. BaseURL string `json:"baseUrl,omitempty"` diff --git a/internal/cmd/generate_state_test.go b/internal/cmd/generate_state_test.go new file mode 100644 index 00000000..f6688bfb --- /dev/null +++ b/internal/cmd/generate_state_test.go @@ -0,0 +1,171 @@ +package cmd + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// πŸ”΄ pendingPath's containment guard. +// +// The externalId is normally a CLI-minted UUID, but --external-id lets a user +// supply it verbatim, and the record is written with os.WriteFile + os.Rename. +// So the value steers a WRITE PATH, and filepath.Base is the only thing standing +// between "--external-id ../../config.yaml" and clobbering the user's config. +// +// Surviving mutation: delete the filepath.Base call. The reject list below it +// ("", ".", "..", "/") does NOT catch a traversal β€” "../../evil" is none of +// those β€” so without Base, filepath.Join cleans the "../.." and the write lands +// outside the pending dir. Nothing in the suite noticed. +// +// Every case uses t.TempDir(): a unit test must never write into the developer's +// real ~/.config/civitai. + +// TestPendingPath_CannotEscapeThePendingDir pins containment STRUCTURALLY β€” on +// the resolved parent directory of the returned path, not on the spelling of the +// input. A guard that rejected the literal string "../../evil" would pass a +// spelling test and still let "..%2F", "a/../../b" or a nested path through. +func TestPendingPath_CannotEscapeThePendingDir(t *testing.T) { + parent := t.TempDir() + dir := filepath.Join(parent, "pending") + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatalf("mkdir: %v", err) + } + + hostile := []struct { + name string + externalID string + }{ + {"parent traversal", "../../evil"}, + {"single parent", "../evil"}, + {"deep traversal", "../../../../../../etc/passwd"}, + {"absolute path", "/etc/passwd"}, + {"absolute into config", "/home/someone/.config/civitai/config.yaml"}, + {"nested relative", "a/../../b"}, + {"subdirectory", "sub/dir/evil"}, + {"trailing slash", "evil/"}, + {"traversal with surrounding space", " ../../evil "}, + {"windows-ish separators", `..\..\evil`}, + } + + for _, tc := range hostile { + t.Run(tc.name, func(t *testing.T) { + got, err := pendingPath(dir, tc.externalID) + if err != nil { + // Refusing outright is an acceptable answer for a hostile value; + // what is NOT acceptable is returning a path outside dir. + return + } + // πŸ”΄ THE assertion: whatever name survived, it lives directly in dir. + if parentOf := filepath.Dir(got); parentOf != filepath.Clean(dir) { + t.Fatalf("πŸ”΄ TRAVERSAL: --external-id %q produced %q, whose directory is %q, not the pending dir %q", + tc.externalID, got, parentOf, dir) + } + // Belt and braces: the cleaned path must still be under dir. + rel, rerr := filepath.Rel(dir, filepath.Clean(got)) + if rerr != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + t.Fatalf("πŸ”΄ TRAVERSAL: %q escapes %q (rel=%q, err=%v)", got, dir, rel, rerr) + } + }) + } +} + +// The values pendingPath refuses outright. Each of these reduces to a basename +// that names no file, so there is nothing safe to write. +func TestPendingPath_RejectsUnusableIDs(t *testing.T) { + dir := t.TempDir() + for _, id := range []string{"", ".", "..", string(filepath.Separator), " ", "\t\n"} { + got, err := pendingPath(dir, id) + if err == nil { + t.Errorf("external id %q was accepted and produced %q, want a refusal", id, got) + } + } + + // POSITIVE CONTROL: an ordinary id IS accepted by the same function, so the + // refusals above are a property of these values and not of a function that + // rejects everything. + ok, err := pendingPath(dir, "3f2504e0-4f89-41d3-9a0c-0305e82c3301") + if err != nil { + t.Fatalf("POSITIVE CONTROL FAILED: a normal external id was refused: %v", err) + } + if filepath.Dir(ok) != filepath.Clean(dir) { + t.Errorf("a normal id landed outside the pending dir: %q", ok) + } + if !strings.HasSuffix(ok, ".json") { + t.Errorf("record path %q does not end in .json", ok) + } +} + +// The containment property, asserted on the FILESYSTEM rather than on a string. +// A path assertion can be defeated by a symlink or by a later change to how the +// record is written; this walks the tree afterwards and checks where bytes +// actually landed. +func TestWritePendingGeneration_HostileExternalIDWritesOnlyInsideThePendingDir(t *testing.T) { + parent := t.TempDir() + dir := filepath.Join(parent, "pending") + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatalf("mkdir: %v", err) + } + // A file the traversal would clobber if the guard were removed. Its contents + // are the canary. + victim := filepath.Join(parent, "evil.json") + const canary = "ORIGINAL CONTENTS β€” MUST NOT BE OVERWRITTEN" + if err := os.WriteFile(victim, []byte(canary), 0o600); err != nil { + t.Fatalf("write victim: %v", err) + } + + rec := pendingGeneration{ + ExternalID: "../evil", + SubmittedAt: "2026-08-05T00:00:00Z", + PayloadHash: "deadbeef", + } + path, err := writePendingGeneration(dir, rec) + if err != nil { + // A refusal is fine; nothing was written, so the canary is safe. + t.Logf("hostile id refused outright: %v", err) + } else if filepath.Dir(path) != filepath.Clean(dir) { + t.Fatalf("πŸ”΄ record was written to %q, outside the pending dir %q", path, dir) + } + + // πŸ”΄ The canary must be untouched. + got, rerr := os.ReadFile(victim) //nolint:gosec // test-controlled path + if rerr != nil { + t.Fatalf("the victim file disappeared: %v", rerr) + } + if string(got) != canary { + t.Fatalf("πŸ”΄ TRAVERSAL: --external-id %q overwrote %q outside the pending dir.\n got: %q\nwant: %q", + rec.ExternalID, victim, got, canary) + } + + // POSITIVE CONTROL: the writer DOES create files, and it creates them in dir. + // Without this, an untouched canary could simply mean nothing was ever + // written by anything. + okPath, err := writePendingGeneration(dir, pendingGeneration{ + ExternalID: "3f2504e0-4f89-41d3-9a0c-0305e82c3301", + SubmittedAt: "2026-08-05T00:00:00Z", + }) + if err != nil { + t.Fatalf("POSITIVE CONTROL FAILED: a normal record could not be written: %v", err) + } + if _, serr := os.Stat(okPath); serr != nil { + t.Fatalf("POSITIVE CONTROL FAILED: no file at %q: %v", okPath, serr) + } + if filepath.Dir(okPath) != filepath.Clean(dir) { + t.Fatalf("POSITIVE CONTROL FAILED: normal record landed at %q, outside %q", okPath, dir) + } + + // And nothing new appeared beside the pending dir: the only entries in the + // parent are the victim file and the pending dir itself. + entries, err := os.ReadDir(parent) + if err != nil { + t.Fatalf("readdir: %v", err) + } + var names []string + for _, e := range entries { + names = append(names, e.Name()) + } + if len(names) != 2 { + t.Errorf("the parent dir gained entries: %v β€” a write escaped the pending dir", names) + } +} diff --git a/internal/cmd/workflows_cancel.go b/internal/cmd/workflows_cancel.go index 2482c2cc..ef053489 100644 --- a/internal/cmd/workflows_cancel.go +++ b/internal/cmd/workflows_cancel.go @@ -1,8 +1,10 @@ package cmd import ( + "bufio" "context" "encoding/json" + "errors" "fmt" "strings" @@ -18,6 +20,8 @@ import ( type workflowsCancelOpts struct { jsonOut bool baseURL string + // assumeYes is --yes/-y: skip the confirmation prompt (for scripts/CI). + assumeYes bool } // workflowsCancelDeps is the single network seam. @@ -49,9 +53,15 @@ Cancelling an already-finished workflow is harmless β€” the outputs of a succeed workflow are not deleted by it (use the website to delete results). This needs the same personal API key with the AI Services scopes that -` + "`civitai generate`" + ` needs.`, +` + "`civitai generate`" + ` needs. + +CONFIRMATION: cancelling is IRREVERSIBLE and destroys a job you have already paid +for, so an interactive run asks first. Pass ` + "`--yes`" + ` to skip the prompt in a +script; a non-interactive shell without ` + "`--yes`" + ` REFUSES rather than cancelling +silently.`, Example: ` civitai workflows cancel 01JABCXYZ - civitai workflows cancel 01JABCXYZ --json`, + civitai workflows cancel 01JABCXYZ --yes + civitai workflows cancel 01JABCXYZ --json --yes`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { cfg, err := config.Load() @@ -68,15 +78,68 @@ This needs the same personal API key with the AI Services scopes that }, } cmd.Flags().BoolVar(&o.jsonOut, "json", false, "emit the raw server reply on stdout (scriptable)") + cmd.Flags().BoolVarP(&o.assumeYes, "yes", "y", false, "skip the confirmation prompt and cancel (for scripts/CI)") return cmd } +// confirmCancel gates the cancel mutation, mirroring confirmSubmit and +// confirmGenerate. +// +// Every other destructive path in this feature gates, and this one has the +// strongest case of the three: `app submit` gates a REVERSIBLE action, and +// `generate` gates a spend the user has not made yet, whereas a cancel is +// irreversible AND throws away a job that has ALREADY been paid for. A bare +// `civitai workflows cancel ` on the wrong id used to destroy that job with +// no prompt at all. +// +// - --yes/-y β†’ proceed without prompting. +// - non-TTY without --yes β†’ REFUSE (never hang, never destroy silently). +// - interactive TTY β†’ say what is lost, prompt, proceed only on "y". +// +// Everything it prints goes to STDERR so a `--json` stdout stays machine-clean. +// +// πŸ”΄ The prompt DEFAULTS TO NO: the switch enumerates the accepting answers and +// everything else β€” including a bare Enter β€” cancels. Rewriting it to enumerate +// the refusing answers instead would turn `[y/N]` into `[Y/n]` and destroy a +// paid-for job on a stray keystroke. +func confirmCancel(cmd *cobra.Command, workflowID string, assumeYes bool) error { + if assumeYes { + return nil + } + if !stdinIsTTY() { + return fmt.Errorf("refusing to cancel without --yes in a non-interactive shell β€” cancelling %s is irreversible and does NOT refund the Buzz already spent on it. "+ + "Pass --yes to confirm, or `civitai workflows get %s` to see what it has produced first", + safeTerm(workflowID), safeTerm(workflowID)) + } + + errw := cmd.ErrOrStderr() + st := ui.For(errw) + fmt.Fprintf(errw, "About to cancel workflow %s.\n", safeTerm(workflowID)) + fmt.Fprintln(errw, st.Warn("This does NOT refund anything β€” a mid-run cancel bills the accrued cost, non-refundably.")) + fmt.Fprintln(errw, st.Dim("You are throwing away a job you have already paid for. It cannot be un-cancelled.")) + fmt.Fprint(errw, "Cancel it? [y/N]: ") + + r := bufio.NewReader(cmd.InOrStdin()) + line, _ := r.ReadString('\n') + switch strings.ToLower(strings.TrimSpace(line)) { + case "y", "yes": + return nil + default: + return errors.New("cancel aborted") + } +} + // runWorkflowsCancel is the testable core. func runWorkflowsCancel(cmd *cobra.Command, deps workflowsCancelDeps, o workflowsCancelOpts, workflowID string) error { id := strings.TrimSpace(workflowID) if id == "" { return asUsageError(fmt.Errorf("a workflow id is required: civitai workflows cancel ")) } + // πŸ”΄ The gate runs BEFORE the mutation seam is touched, so a refusal cannot + // have cancelled anything. + if err := confirmCancel(cmd, id, o.assumeYes); err != nil { + return err + } ctx := cmd.Context() if ctx == nil { ctx = context.Background() diff --git a/internal/cmd/workflows_cancel_confirm_test.go b/internal/cmd/workflows_cancel_confirm_test.go new file mode 100644 index 00000000..a184e515 --- /dev/null +++ b/internal/cmd/workflows_cancel_confirm_test.go @@ -0,0 +1,262 @@ +package cmd + +import ( + "strings" + "testing" +) + +// πŸ”΄ cancelWorkflow is a MUTATION and it is IRREVERSIBLE β€” it destroys a job the +// user has already paid for. Every case in this file drives a stubbed seam and +// counts what reached it; nothing here may touch a real server. +// +// The claim under test is the confirmation gate added for `workflows cancel`, +// mirroring confirmSubmit (app_submit.go) and confirmGenerate (generate.go): +// +// --yes/-y β†’ proceed +// non-TTY without --yes β†’ REFUSE +// interactive TTY β†’ prompt, and DEFAULT TO NO +// +// Every "0 cancels" assertion below is paired with a case in the SAME test +// driving the SAME counter to 1. A counter wired to nothing reads zero too. + +// TestWorkflowsCancel_NonTTYWithoutYesRefusesAndNeverCancels is the headline +// property, with its positive control. +func TestWorkflowsCancel_NonTTYWithoutYesRefusesAndNeverCancels(t *testing.T) { + withStdinTTY(t, false) + + // (A) negative: no --yes on a non-TTY. + refuseCalls := 0 + c, out, errb := genCmd("") + err := runWorkflowsCancel(c, wfCancelDeps(`{}`, nil, nil, &refuseCalls), workflowsCancelOpts{}, "wf_1") + if err == nil { + t.Fatal("non-TTY without --yes: want a refusal, got nil") + } + if refuseCalls != 0 { + t.Errorf("non-TTY without --yes: the cancel seam was reached %d time(s), want 0", refuseCalls) + } + // The refusal must be actionable: it names the flag that proceeds and the + // read-only command that shows what would be thrown away. + for _, want := range []string{"--yes", "workflows get"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("refusal does not mention %q: %v", want, err) + } + } + if strings.Contains(errb.String(), "[y/N]") { + t.Error("a non-TTY must not print a prompt (nobody can answer it)") + } + if out.Len() != 0 { + t.Errorf("a refused cancel printed to stdout: %q", out.String()) + } + + // πŸ”΄ (A2) The case that makes the COUNTER the discriminator. + // + // Case (A) pipes empty stdin, so if the non-TTY refusal were removed the run + // would fall through to the prompt, read EOF and abort anyway β€” the seam + // stays at 0 and only the message assertions above notice. That is a guard + // killed by a DIFFERENT guard's error. + // + // A CI script that pipes "y" is the real shape of the hazard: with the + // non-TTY branch gone, that answer satisfies the prompt and the job is + // destroyed with no --yes anywhere. A non-TTY must refuse REGARDLESS of what + // is on stdin, because "a terminal is attached" is the thing being asserted, + // not "somebody typed something". + for _, piped := range []string{"y\n", "yes\n", "Y\n"} { + pipedCalls := 0 + c3, _, errb3 := genCmd(piped) + err := runWorkflowsCancel(c3, wfCancelDeps(`{}`, nil, nil, &pipedCalls), workflowsCancelOpts{}, "wf_1") + if err == nil { + t.Errorf("non-TTY with %q piped to stdin: want a refusal, got nil", piped) + } + if pipedCalls != 0 { + t.Errorf("πŸ”΄ non-TTY with %q piped to stdin CANCELLED the workflow (%d seam call(s)) β€” piped input is not a confirmation", + piped, pipedCalls) + } + if strings.Contains(errb3.String(), "[y/N]") { + t.Errorf("non-TTY with %q piped: a prompt was printed", piped) + } + } + + // (B) POSITIVE CONTROL: identical wiring, --yes set. Without this, the zero + // in (A) is indistinguishable from a seam that is never called at all. + proceedCalls := 0 + c2, _, _ := genCmd("") + if err := runWorkflowsCancel(c2, wfCancelDeps(`{}`, nil, nil, &proceedCalls), workflowsCancelOpts{assumeYes: true}, "wf_1"); err != nil { + t.Fatalf("positive control (--yes): %v", err) + } + if proceedCalls != 1 { + t.Fatalf("POSITIVE CONTROL FAILED: cancel seam called %d times, want 1 β€” the 0 in case (A) proves nothing", proceedCalls) + } +} + +// πŸ”΄ THE default-deny guard for the cancel prompt. +// +// The mutation this exists to kill is the switch inversion β€” rewriting +// +// case "y", "yes": proceed; default: abort +// +// as +// +// case "n", "no": abort; default: proceed +// +// which silently turns `[y/N]` into `[Y/n]`. It type-checks, it keeps the "n" +// and "y" tests green, and it destroys a paid-for job on a bare Enter or a +// typo. Only inputs that are NEITHER "y"/"yes" NOR "n"/"no" can see it. +func TestWorkflowsCancel_PromptDefaultsToNo(t *testing.T) { + withStdinTTY(t, true) + + // Every one of these must ABORT. "n"/"no" are deliberately NOT in this list: + // they abort under the mutation too, so they cannot discriminate. + deny := []struct { + name string + stdin string + }{ + {"bare Enter", "\n"}, + {"empty stdin (EOF)", ""}, + {"whitespace only", " \n"}, + {"maybe", "maybe\n"}, + {"yy", "yy\n"}, + {"Ye (prefix of yes, not yes)", "Ye\n"}, + {"1", "1\n"}, + {"ok", "ok\n"}, + {"sure", "sure\n"}, + {"yeah", "yeah\n"}, + } + for _, tc := range deny { + t.Run("deny/"+tc.name, func(t *testing.T) { + calls := 0 + c, out, errb := genCmd(tc.stdin) + err := runWorkflowsCancel(c, wfCancelDeps(`{}`, nil, nil, &calls), workflowsCancelOpts{}, "wf_1") + if err == nil { + t.Fatalf("answer %q: want an abort, got nil", tc.stdin) + } + // πŸ”΄ The load-bearing assertion: the irreversible seam was NOT reached. + if calls != 0 { + t.Errorf("answer %q: the cancel seam was reached %d time(s) β€” this answer must NOT cancel", tc.stdin, calls) + } + if out.Len() != 0 { + t.Errorf("answer %q: an aborted cancel printed to stdout: %q", tc.stdin, out.String()) + } + // The prompt must have actually been shown, or the case above proves + // nothing about the switch (it could have refused earlier). + if !strings.Contains(errb.String(), "[y/N]") { + t.Errorf("answer %q: no prompt was printed, so this case never reached the switch:\n%s", tc.stdin, errb.String()) + } + }) + } + + // POSITIVE CONTROLS in the same test: the accepting answers DO proceed, so + // the zeros above cannot come from a gate that refuses everything. + for _, tc := range []struct { + name string + stdin string + }{ + {"y", "y\n"}, + {"yes", "yes\n"}, + {"Y uppercase", "Y\n"}, + {"YES uppercase", "YES\n"}, + {"y with surrounding spaces", " y \n"}, + } { + t.Run("accept/"+tc.name, func(t *testing.T) { + calls := 0 + c, _, _ := genCmd(tc.stdin) + if err := runWorkflowsCancel(c, wfCancelDeps(`{}`, nil, nil, &calls), workflowsCancelOpts{}, "wf_1"); err != nil { + t.Fatalf("answer %q: want the cancel to proceed, got %v", tc.stdin, err) + } + if calls != 1 { + t.Fatalf("POSITIVE CONTROL FAILED: answer %q reached the cancel seam %d times, want 1", tc.stdin, calls) + } + }) + } +} + +// An interactive decline is the ordinary case, kept separate so a failure names +// it directly. The prompt goes to STDERR so a --json stdout stays machine-clean. +func TestWorkflowsCancel_TTYDeclineDoesNotCancel(t *testing.T) { + withStdinTTY(t, true) + calls := 0 + c, out, errb := genCmd("n\n") + err := runWorkflowsCancel(c, wfCancelDeps(`{}`, nil, nil, &calls), workflowsCancelOpts{}, "wf_1") + if err == nil { + t.Fatal("declined prompt: want an abort, got nil") + } + if calls != 0 { + t.Errorf("declined prompt: the cancel seam was reached %d time(s), want 0", calls) + } + if !strings.Contains(errb.String(), "[y/N]") { + t.Errorf("confirmation prompt missing from stderr: %q", errb.String()) + } + if strings.Contains(out.String(), "[y/N]") { + t.Errorf("confirmation leaked to stdout: %q", out.String()) + } + // The prompt must state what is lost β€” it is the last point at which the + // user can find out that cancelling does not get the money back. + if !strings.Contains(errb.String(), "does NOT refund") { + t.Errorf("the prompt does not say cancelling is not refunded:\n%s", errb.String()) + } +} + +// The gate runs BEFORE the mutation even with --json, so a scripted `--json` +// cancel without --yes cannot destroy a job and then fail to print. +func TestWorkflowsCancel_JSONStillGated(t *testing.T) { + withStdinTTY(t, false) + calls := 0 + c, out, _ := genCmd("") + if err := runWorkflowsCancel(c, wfCancelDeps(`{}`, nil, nil, &calls), workflowsCancelOpts{jsonOut: true}, "wf_1"); err == nil { + t.Fatal("--json without --yes on a non-TTY: want a refusal, got nil") + } + if calls != 0 { + t.Errorf("--json without --yes: the cancel seam was reached %d time(s), want 0", calls) + } + if out.Len() != 0 { + t.Errorf("a refused --json cancel wrote to stdout: %q", out.String()) + } + + // POSITIVE CONTROL: with --yes the same wiring both cancels and prints JSON. + okCalls := 0 + c2, out2, _ := genCmd("") + if err := runWorkflowsCancel(c2, wfCancelDeps(`{}`, nil, nil, &okCalls), workflowsCancelOpts{jsonOut: true, assumeYes: true}, "wf_1"); err != nil { + t.Fatalf("positive control (--json --yes): %v", err) + } + if okCalls != 1 || out2.Len() == 0 { + t.Fatalf("POSITIVE CONTROL FAILED: calls=%d, stdout=%q", okCalls, out2.String()) + } +} + +// The flag must exist with its short form, and it must be a real bool the +// command wires to the gate. Asserted on the flag's VALUE after parsing, not on +// its name: a flag that is registered but never read looks identical to one that +// works if you only check that the name is present. +func TestWorkflowsCancel_YesFlagIsRegisteredAndWired(t *testing.T) { + cmd := newWorkflowsCancelCmd() + f := cmd.Flags().Lookup("yes") + if f == nil { + t.Fatal("`workflows cancel` has no --yes flag") + } + if f.Shorthand != "y" { + t.Errorf("--yes shorthand = %q, want \"y\" (matches `app submit`)", f.Shorthand) + } + if f.Value.Type() != "bool" { + t.Errorf("--yes type = %q, want bool", f.Value.Type()) + } + if got := f.Value.String(); got != "false" { + t.Errorf("--yes default = %q, want false β€” the gate must be ON by default", got) + } + // Parsing -y must actually flip the value the RunE closure reads. + if err := cmd.Flags().Parse([]string{"-y"}); err != nil { + t.Fatalf("parse -y: %v", err) + } + if got := f.Value.String(); got != "true" { + t.Fatalf("after -y the flag value is %q, want true", got) + } +} + +// The help text must tell a scripter how to get past the gate, or the refusal is +// a dead end. Normalised so a re-wrap does not break it. +func TestWorkflowsCancel_HelpDocumentsTheConfirmation(t *testing.T) { + long := strings.ToLower(strings.Join(strings.Fields(newWorkflowsCancelCmd().Long), " ")) + for _, want := range []string{"--yes", "non-interactive", "refuses"} { + if !strings.Contains(long, want) { + t.Errorf("`workflows cancel --help` does not document the confirmation (%q missing):\n%s", want, long) + } + } +} diff --git a/internal/cmd/workflows_cancel_test.go b/internal/cmd/workflows_cancel_test.go index d7aae7c0..f388a36d 100644 --- a/internal/cmd/workflows_cancel_test.go +++ b/internal/cmd/workflows_cancel_test.go @@ -36,7 +36,7 @@ func wfCancelDeps(reply string, err error, seenID *string, calls *int) workflows func TestWorkflowsCancel_Success(t *testing.T) { var seen string c, out, errb := genCmd("") - if err := runWorkflowsCancel(c, wfCancelDeps(`{"result":{"data":{}}}`, nil, &seen, nil), workflowsCancelOpts{}, " wf_1 "); err != nil { + if err := runWorkflowsCancel(c, wfCancelDeps(`{"result":{"data":{}}}`, nil, &seen, nil), workflowsCancelOpts{assumeYes: true}, " wf_1 "); err != nil { t.Fatalf("workflows cancel: %v", err) } if seen != "wf_1" { @@ -80,7 +80,7 @@ func TestWorkflowsCancel_HelpStatesTheBillingTruth(t *testing.T) { func TestWorkflowsCancel_NotFound(t *testing.T) { apiErr := apiErrorWithStatus(t, http.StatusNotFound) c, out, _ := genCmd("") - err := runWorkflowsCancel(c, wfCancelDeps("", apiErr, nil, nil), workflowsCancelOpts{}, "wf_gone") + err := runWorkflowsCancel(c, wfCancelDeps("", apiErr, nil, nil), workflowsCancelOpts{assumeYes: true}, "wf_gone") if err == nil { t.Fatal("a 404 must return an error") } @@ -95,7 +95,7 @@ func TestWorkflowsCancel_NotFound(t *testing.T) { func TestWorkflowsCancel_EmptyIDIsAUsageError(t *testing.T) { calls := 0 c, _, _ := genCmd("") - err := runWorkflowsCancel(c, wfCancelDeps("", nil, nil, &calls), workflowsCancelOpts{}, " ") + err := runWorkflowsCancel(c, wfCancelDeps("", nil, nil, &calls), workflowsCancelOpts{assumeYes: true}, " ") if !errors.Is(err, ErrUsage) { t.Fatalf("want ErrUsage (exit 2), got %v", err) } @@ -103,7 +103,7 @@ func TestWorkflowsCancel_EmptyIDIsAUsageError(t *testing.T) { t.Errorf("a mutation was issued for an empty id (%d calls)", calls) } // Positive control: the same seam IS reached for a real id. - if err := runWorkflowsCancel(c, wfCancelDeps(`{}`, nil, nil, &calls), workflowsCancelOpts{}, "wf_1"); err != nil { + if err := runWorkflowsCancel(c, wfCancelDeps(`{}`, nil, nil, &calls), workflowsCancelOpts{assumeYes: true}, "wf_1"); err != nil { t.Fatalf("control cancel: %v", err) } if calls != 1 { @@ -115,7 +115,7 @@ func TestWorkflowsCancel_EmptyIDIsAUsageError(t *testing.T) { // on success β€” an empty stdout is a hard error for `jq`. func TestWorkflowsCancel_JSONEmitsAParseableDocument(t *testing.T) { c, out, _ := genCmd("") - if err := runWorkflowsCancel(c, wfCancelDeps("", nil, nil, nil), workflowsCancelOpts{jsonOut: true}, "wf_1"); err != nil { + if err := runWorkflowsCancel(c, wfCancelDeps("", nil, nil, nil), workflowsCancelOpts{jsonOut: true, assumeYes: true}, "wf_1"); err != nil { t.Fatalf("--json: %v", err) } var decoded map[string]any @@ -136,7 +136,7 @@ func TestWorkflowsCancel_AgainstHTTPTest(t *testing.T) { gen := genapi.New(srv.URL, "test-key") c, out, _ := genCmd("") - if err := runWorkflowsCancel(c, workflowsCancelDeps{cancelWorkflow: gen.CancelWorkflow}, workflowsCancelOpts{}, "wf_1"); err != nil { + if err := runWorkflowsCancel(c, workflowsCancelDeps{cancelWorkflow: gen.CancelWorkflow}, workflowsCancelOpts{assumeYes: true}, "wf_1"); err != nil { t.Fatalf("cancel: %v", err) } if method != http.MethodPost || path != genapi.CancelWorkflowPath { diff --git a/internal/genapi/blobs_close_test.go b/internal/genapi/blobs_close_test.go new file mode 100644 index 00000000..803e9cc6 --- /dev/null +++ b/internal/genapi/blobs_close_test.go @@ -0,0 +1,134 @@ +package genapi + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "sync" + "testing" + + "github.com/civitai/cli/pkg/civitai" +) + +// πŸ”΄ UploadImageBlob must close the upload response body on EVERY path. +// +// Surviving mutation: delete `defer func() { _ = resp.Body.Close() }()` in +// UploadImageBlob. Deleting it leaves the whole suite green β€” every existing +// test reads the returned URL or the returned error and never asks what happened +// to the handle. A leaked body keeps the connection out of the pool, and this is +// the one hop in the feature that runs once PER REFERENCE IMAGE. +// +// The uploader seam here is a fake that returns a response THIS TEST built, so +// the close is observed by a counter in this process at the moment +// UploadImageBlob returns: no server, no goroutine, no timing dependency. +// Deliberately not measured on the server side β€” a count of what a handler +// observes is a race, not an assertion. + +// closingBody is a response body that counts its own Close calls. +type closingBody struct { + mu sync.Mutex + reader io.Reader + closed int +} + +func newClosingBody(s string) *closingBody { + return &closingBody{reader: bytes.NewReader([]byte(s))} +} + +func (b *closingBody) Read(p []byte) (int, error) { return b.reader.Read(p) } + +func (b *closingBody) Close() error { + b.mu.Lock() + defer b.mu.Unlock() + b.closed++ + return nil +} + +func (b *closingBody) closeCount() int { + b.mu.Lock() + defer b.mu.Unlock() + return b.closed +} + +// fakeUploader is a civitai.PresignedUploader returning a scripted response. +// +// It takes no token parameter β€” that is the interface's whole point (AGENTS.md +// item 19(e)) β€” so this fake cannot accidentally weaken the credential-free +// contract the sibling tests assert. +type fakeUploader struct { + status int + body *closingBody + calls int +} + +func (f *fakeUploader) UploadPresigned(_ context.Context, _, _ string, _ []byte) (*http.Response, error) { + f.calls++ + return &http.Response{StatusCode: f.status, Body: f.body, Header: make(http.Header)}, nil +} + +func TestUploadImageBlob_ClosesTheUploadResponseBody(t *testing.T) { + // The presign hop is a real httptest server; only the upload hop is faked, + // so the two-hop shape under test is the real one. + presign := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"uploadUrl":"https://storage.example/v2/consumer/blobs","expiresAt":"2030-01-01T00:00:00Z"}`) + })) + defer presign.Close() + + cases := []struct { + name string + status int + reply string + wantErr bool + }{ + {"success", http.StatusOK, `{"id":"B1","available":true,"url":"https://storage.example/blobs/B1.png"}`, false}, + {"rejected (413)", http.StatusRequestEntityTooLarge, `too big`, true}, + {"expired signature (403)", http.StatusForbidden, `denied`, true}, + {"2xx with unparseable body", http.StatusOK, `not json`, true}, + {"2xx with a null url", http.StatusOK, `{"id":"B1","available":false,"url":null}`, true}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + body := newClosingBody(tc.reply) + up := &fakeUploader{status: tc.status, body: body} + c := New(presign.URL, "test-key") + + _, err := c.UploadImageBlob(context.Background(), up, "image/png", []byte("PNGBYTES")) + if tc.wantErr && err == nil { + t.Fatal("want an error for this case") + } + if !tc.wantErr && err != nil { + t.Fatalf("unexpected error: %v", err) + } + if up.calls != 1 { + t.Fatalf("the upload seam was reached %d time(s), want 1 β€” the close assertion below would be vacuous", up.calls) + } + + // πŸ”΄ THE assertion, on every path. + if got := body.closeCount(); got != 1 { + t.Errorf("πŸ”΄ HANDLE LEAK: the upload response body was closed %d time(s), want exactly 1", got) + } + }) + } + + // POSITIVE/NEGATIVE CONTROL for the counter itself: it reads 0 until + // something closes it and 1 afterwards, so the 1s above are observations + // rather than a constant. + t.Run("control: the counter moves", func(t *testing.T) { + b := newClosingBody("x") + if got := b.closeCount(); got != 0 { + t.Fatalf("CONTROL FAILED: an untouched body reports %d closes, want 0", got) + } + _ = b.Close() + if got := b.closeCount(); got != 1 { + t.Fatalf("CONTROL FAILED: after one Close() the counter reads %d, want 1", got) + } + }) +} + +// The fake must satisfy the real interface, or this file is testing a shape the +// production code does not use. +var _ civitai.PresignedUploader = (*fakeUploader)(nil) diff --git a/internal/genapi/client_replay_test.go b/internal/genapi/client_replay_test.go new file mode 100644 index 00000000..1625ee45 --- /dev/null +++ b/internal/genapi/client_replay_test.go @@ -0,0 +1,136 @@ +package genapi + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "testing" +) + +// πŸ”΄ The transparent-refresh replay is 401-ONLY, and that narrowness is the +// safety property β€” not an implementation detail. +// +// Surviving mutation: `status == http.StatusUnauthorized` β†’ `status != 200`. +// TestAuthedDo_RefreshesOn401 stays green under it (a 401 still replays), so +// nothing in the suite could see the change. What it does is turn EVERY +// non-200 into a second request β€” including a 500, which is precisely the +// status the platform's own submit wrapper already retries 3Γ— server-side. The +// idempotency key makes a replayed submit safe rather than a double charge +// (AGENTS.md item 16), but "safe" is not "free": it doubles the load a +// struggling orchestrator sees, and it burns a refresh on an error that has +// nothing to do with the credential. +// +// A 401 is the only status that a NEW TOKEN can plausibly fix. Everything else +// must be handed to the caller on the first response. +// +// Nothing here spends anything: WhatIfFromGraph is the read-only cost estimate, +// and it runs against httptest. + +// replayProbe counts requests a server actually received and answers each with a +// scripted status. +type replayProbe struct { + requests int + statuses []int // one per request; the last is reused once exhausted +} + +func (p *replayProbe) handler() http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + i := p.requests + p.requests++ + st := p.statuses[len(p.statuses)-1] + if i < len(p.statuses) { + st = p.statuses[i] + } + if st == http.StatusOK { + writeTRPC(w, map[string]any{"ready": true, "cost": map[string]any{"total": 60}}) + return + } + w.WriteHeader(st) + _, _ = io.WriteString(w, `{"error":{"json":{"message":"scripted"}}}`) + } +} + +// TestAuthedDo_ReplaysOnlyOn401 measures the request count for a range of +// non-401 failures, and pairs every "1 request" with a 401 case in the SAME test +// that produces 2. A counter that never moved would report 1 everywhere. +func TestAuthedDo_ReplaysOnlyOn401(t *testing.T) { + noReplay := []struct { + name string + status int + }{ + {"500 internal server error", http.StatusInternalServerError}, + {"502 bad gateway", http.StatusBadGateway}, + {"503 service unavailable", http.StatusServiceUnavailable}, + // 403 is the interesting one: it is auth-ADJACENT, so a "looks like an + // auth problem" rewrite would sweep it in. A refresh cannot fix a token + // that is valid but lacks the scope. + {"403 forbidden", http.StatusForbidden}, + {"404 not found", http.StatusNotFound}, + {"400 bad request", http.StatusBadRequest}, + {"429 too many requests", http.StatusTooManyRequests}, + } + + for _, tc := range noReplay { + t.Run(tc.name, func(t *testing.T) { + probe := &replayProbe{statuses: []int{tc.status}} + srv := httptest.NewServer(probe.handler()) + defer srv.Close() + + src := &refreshOnceSource{} + c := NewWithSource(srv.URL, src) + // The call fails; the failure is not what is under test. + _, _, _ = c.WhatIfFromGraph(context.Background(), Graph{Workflow: "txt2img"}) + + if probe.requests != 1 { + t.Errorf("πŸ”΄ a %d was REPLAYED: the server saw %d requests, want exactly 1 β€” only a 401 may be retried", + tc.status, probe.requests) + } + // The second, independent discriminator: a non-401 must not even ask + // the token source to refresh. + if src.calls != 0 { + t.Errorf("πŸ”΄ a %d triggered %d token refresh(es), want 0", tc.status, src.calls) + } + }) + } + + // πŸ”΄ POSITIVE CONTROL, same harness, same client, same call: a 401 DOES + // replay. Without this, every "1 request" above is indistinguishable from a + // probe that cannot count, a server never reached, or a client that never + // retries anything at all. + t.Run("positive control: 401 does replay", func(t *testing.T) { + probe := &replayProbe{statuses: []int{http.StatusUnauthorized, http.StatusOK}} + srv := httptest.NewServer(probe.handler()) + defer srv.Close() + + src := &refreshOnceSource{} + c := NewWithSource(srv.URL, src) + if _, _, err := c.WhatIfFromGraph(context.Background(), Graph{Workflow: "txt2img"}); err != nil { + t.Fatalf("POSITIVE CONTROL FAILED: the 401β†’refreshβ†’200 path errored: %v", err) + } + if probe.requests != 2 { + t.Fatalf("POSITIVE CONTROL FAILED: a 401 produced %d requests, want 2 β€” the counts above prove nothing", probe.requests) + } + if src.calls != 1 { + t.Fatalf("POSITIVE CONTROL FAILED: a 401 produced %d refreshes, want 1", src.calls) + } + }) + + // A 401 that is STILL 401 after the refresh must stop at two requests, not + // loop. Pins the "refresh once" half of the contract. + t.Run("a persistent 401 replays exactly once", func(t *testing.T) { + probe := &replayProbe{statuses: []int{http.StatusUnauthorized}} + srv := httptest.NewServer(probe.handler()) + defer srv.Close() + + src := &refreshOnceSource{} + c := NewWithSource(srv.URL, src) + _, _, _ = c.WhatIfFromGraph(context.Background(), Graph{Workflow: "txt2img"}) + if probe.requests != 2 { + t.Errorf("a persistent 401 produced %d requests, want exactly 2 (one replay, then give up)", probe.requests) + } + if src.calls != 1 { + t.Errorf("a persistent 401 produced %d refreshes, want exactly 1", src.calls) + } + }) +} diff --git a/pkg/civitai/upload.go b/pkg/civitai/upload.go index 8ba038da..b32f2488 100644 --- a/pkg/civitai/upload.go +++ b/pkg/civitai/upload.go @@ -62,6 +62,15 @@ func (c *Client) UploadPresigned(ctx context.Context, uploadURL, contentType str return nil, fmt.Errorf("refusing to upload without a Content-Type β€” the orchestrator rejects an unlabelled blob") } req.Header.Set("Content-Type", contentType) + // BELT-AND-BRACES, not load-bearing today: http.NewRequestWithContext ALREADY + // sets ContentLength (and GetBody, which is what makes the body replayable) + // when handed a *bytes.Reader, so deleting this line changes nothing about + // the request currently sent β€” measured. It is kept because the requirement + // is the ENDPOINT's, not the reader type's: the orchestrator's signed URL + // rejects a chunked body, and the day someone swaps bytes.NewReader for a + // wrapper the stdlib cannot size, that guarantee would vanish silently with + // no test able to see it. One line to keep the length pinned to the bytes we + // were handed rather than to an implementation detail of net/http. req.ContentLength = int64(len(body)) return c.downloadHTTPClient().Do(req) } diff --git a/pkg/civitai/upload_test.go b/pkg/civitai/upload_test.go index a37c6a9f..ba2fc66f 100644 --- a/pkg/civitai/upload_test.go +++ b/pkg/civitai/upload_test.go @@ -74,6 +74,12 @@ func TestUploadPresigned_SendsNoCredential(t *testing.T) { if rec.ctype != "image/png" { t.Errorf("Content-Type = %q, want image/png", rec.ctype) } + // This pins the OUTCOME the signed endpoint requires (a real Content-Length, + // never a chunked body), NOT the `req.ContentLength = …` line in upload.go. + // Measured: deleting that line leaves this assertion green, because + // http.NewRequestWithContext already sizes a *bytes.Reader body. Read it as + // "the request went out sized", not as coverage of our own assignment β€” see + // the belt-and-braces comment at that line. if rec.clen != int64(len("PNGBYTES")) { t.Errorf("Content-Length = %d, want %d β€” the signed endpoint rejects a chunked body", rec.clen, len("PNGBYTES")) }