Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
232 changes: 232 additions & 0 deletions pkg/rest/vd_put_size_bounds_round4_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
// SPDX-License-Identifier: Apache-2.0

/*
Copyright 2026 Cozystack contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package rest

import (
"encoding/json"
"io"
"net/http"
"strings"
"testing"

apiv1 "github.com/cozystack/blockstor/pkg/api/v1"
"github.com/cozystack/blockstor/pkg/store"
)

// VD-resize size-bounds gap (adversarial round 4, 2026-07-03): the VD
// CREATE path gates size_kib into [4 MiB, 16 TiB] via validateVDSize
// (Bug 155), so the satellite never hot-loops on `drbdadm create-md`
// for an unmaterializable size. The RESIZE path
// (`PUT /v1/resource-definitions/{rd}/volume-definitions/{vn}`, i.e.
// `linstor vd set-size`) enforced only the Bug 383 non-positive floor
// and the scenario 4.W13 shrink-vs-force gate — it never called
// validateVDSize. So a `vd set-size` below the 4 MiB metadata floor
// (with force to clear the shrink gate) or above the 16 TiB ceiling
// was accepted (200) and stored verbatim, reproducing the exact Bug
// 155 satellite hot-loop through the resize verb instead of create.
//
// The fix mirrors the create gate on the PUT branch (rejectVDPatch
// OutOfBounds), evaluated — like the Bug 383 non-positive floor — BEFORE
// the shrink-vs-force check: `force` waives the shrink-direction opt-in,
// never the physical floor/ceiling, and running the bounds check first
// hands the operator the accurate "invalid size" envelope instead of an
// "add --force" hint on a size that would be rejected even with force.
//
// These are the L1 fail-on-bug regressions: each FAILS on the pre-fix
// tree (PUT 200s and mutates the stored row) and PASSES with the gate.

// TestVDPutBelowFloorWithForceRejected: a force-shrink to a positive
// size below the 4 MiB DRBD metadata floor must be refused with the
// same 400 + FAIL_INVLD_VLM_SIZE envelope the create path returns, and
// must NOT mutate the stored size.
func TestVDPutBelowFloorWithForceRejected(t *testing.T) {
st := store.NewInMemory()
const origSize = int64(1024 * 1024) // 1 GiB, comfortably in-bounds
seedRDWithVD(t, st, "r4-floor-rd", origSize)

base, stop := startServerWithStore(t, st)
defer stop()

belowFloor := minVolumeDefinitionSizeKib - 1024 // 1 MiB below the 4 MiB floor, still > 0
body, err := json.Marshal(volumeDefinitionModifyBody{
SizeKib: &belowFloor,
Force: true, // clears the shrink-without-force gate
})
if err != nil {
t.Fatalf("marshal: %v", err)
}

resp := httpPut(t, base+"/v1/resource-definitions/r4-floor-rd/volume-definitions/0", body)
defer func() { _ = resp.Body.Close() }()

respBody, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}

if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status: got %d, want 400 (sub-floor size must be refused like create); body=%s",
resp.StatusCode, respBody)
}

assertVDSizeRejectionEnvelope(t, respBody, "below minimum")

// The stored row must stay at the pre-PUT size — a rejected resize
// leaves the spec untouched.
assertVDSize(t, st, "r4-floor-rd", origSize)
}

// TestVDPutAboveMaxRejected: a grow above the 16 TiB DRBD per-device
// ceiling (a pure grow, so only a max-bound gate can stop it) must be
// refused and must not mutate the stored size.
func TestVDPutAboveMaxRejected(t *testing.T) {
st := store.NewInMemory()
const origSize = int64(8192)
seedRDWithVD(t, st, "r4-max-rd", origSize)

base, stop := startServerWithStore(t, st)
defer stop()

aboveMax := maxVolumeDefinitionSizeKib + (1024 * 1024) // 1 GiB past the ceiling
body, err := json.Marshal(volumeDefinitionModifyBody{
SizeKib: &aboveMax,
})
if err != nil {
t.Fatalf("marshal: %v", err)
}

resp := httpPut(t, base+"/v1/resource-definitions/r4-max-rd/volume-definitions/0", body)
defer func() { _ = resp.Body.Close() }()

respBody, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}

if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status: got %d, want 400 (over-ceiling size must be refused like create); body=%s",
resp.StatusCode, respBody)
}

assertVDSizeRejectionEnvelope(t, respBody, "above maximum")

assertVDSize(t, st, "r4-max-rd", origSize)
}

// TestVDPutAtBoundsAccepted: the boundary is inclusive on both ends
// (validateVDSize rejects `< min` and `> max`), so a resize to exactly
// the floor (force-shrink) and exactly the ceiling (grow) must still
// land. Guards the new gate against being one-off over-broad.
func TestVDPutAtBoundsAccepted(t *testing.T) {
t.Run("exact-floor-force-shrink", func(t *testing.T) {
st := store.NewInMemory()
seedRDWithVD(t, st, "r4-atfloor-rd", 1024*1024)

base, stop := startServerWithStore(t, st)
defer stop()

atFloor := minVolumeDefinitionSizeKib
body, _ := json.Marshal(volumeDefinitionModifyBody{SizeKib: &atFloor, Force: true})

resp := httpPut(t, base+"/v1/resource-definitions/r4-atfloor-rd/volume-definitions/0", body)
defer func() { _ = resp.Body.Close() }()

if resp.StatusCode != http.StatusOK {
rb, _ := io.ReadAll(resp.Body)
t.Fatalf("status: got %d, want 200 (exact floor is in-bounds); body=%s", resp.StatusCode, rb)
}

assertVDSize(t, st, "r4-atfloor-rd", atFloor)
})

t.Run("exact-ceiling-grow", func(t *testing.T) {
st := store.NewInMemory()
seedRDWithVD(t, st, "r4-atmax-rd", 8192)

base, stop := startServerWithStore(t, st)
defer stop()

atMax := maxVolumeDefinitionSizeKib
body, _ := json.Marshal(volumeDefinitionModifyBody{SizeKib: &atMax})

resp := httpPut(t, base+"/v1/resource-definitions/r4-atmax-rd/volume-definitions/0", body)
defer func() { _ = resp.Body.Close() }()

if resp.StatusCode != http.StatusOK {
rb, _ := io.ReadAll(resp.Body)
t.Fatalf("status: got %d, want 200 (exact ceiling is in-bounds); body=%s", resp.StatusCode, rb)
}

assertVDSize(t, st, "r4-atmax-rd", atMax)
})
}

// TestVDPutInBoundsForceShrinkStillWorks: a legitimate in-bounds
// force-shrink (1 GiB → 8 MiB, well above the 4 MiB floor) must still
// land 200 and persist. The bounds gate must not regress the
// scenario-4.W13 force-shrink path linstor-csi drives after a
// `resize2fs -s` on the consumer — `force` still clears the shrink-
// direction gate, and the in-bounds size passes the new floor/ceiling.
func TestVDPutInBoundsForceShrinkStillWorks(t *testing.T) {
st := store.NewInMemory()
seedRDWithVD(t, st, "r4-inbounds-shrink-rd", 1024*1024) // 1 GiB

base, stop := startServerWithStore(t, st)
defer stop()

newSize := int64(8 * 1024) // 8 MiB, comfortably in-bounds
body, err := json.Marshal(volumeDefinitionModifyBody{SizeKib: &newSize, Force: true})
if err != nil {
t.Fatalf("marshal: %v", err)
}

resp := httpPut(t, base+"/v1/resource-definitions/r4-inbounds-shrink-rd/volume-definitions/0", body)
defer func() { _ = resp.Body.Close() }()

if resp.StatusCode != http.StatusOK {
rb, _ := io.ReadAll(resp.Body)
t.Fatalf("status: got %d, want 200 (in-bounds force-shrink must still land); body=%s", resp.StatusCode, rb)
}

assertVDSize(t, st, "r4-inbounds-shrink-rd", newSize)
}

// assertVDSizeRejectionEnvelope pins that a rejected resize returns the
// single-entry LINSTOR envelope with the FAIL_INVLD_VLM_SIZE sub-code
// (create-path parity) and a message naming the specific bound.
func assertVDSizeRejectionEnvelope(t *testing.T, respBody []byte, wantBound string) {
t.Helper()

var rcs []apiv1.APICallRc
if err := json.Unmarshal(respBody, &rcs); err != nil {
t.Fatalf("unmarshal envelope: %v; body=%s", err, respBody)
}

if len(rcs) != 1 {
t.Fatalf("envelope length: got %d, want 1; body=%s", len(rcs), respBody)
}

if rcs[0].RetCode&apiCallRcFailInvldVlmSize == 0 {
t.Errorf("ret_code missing FAIL_INVLD_VLM_SIZE sub-code (create-path parity); got %d", rcs[0].RetCode)
}

if !strings.Contains(rcs[0].Message, wantBound) {
t.Errorf("message must name the %q bound; got %q", wantBound, rcs[0].Message)
}
}
39 changes: 39 additions & 0 deletions pkg/rest/volume_definitions.go
Original file line number Diff line number Diff line change
Expand Up @@ -819,6 +819,21 @@ func rejectVDPatchSize(
return true
}

// Adversarial round 4 (2026-07-03): mirror the CREATE path's Bug 155
// bounds gate on the RESIZE path. The create path refuses size_kib
// outside [4 MiB, 16 TiB] via validateVDSize so the satellite never
// hot-loops on `drbdadm create-md`; `linstor vd set-size` previously
// skipped that check, so a below-floor force-shrink or an over-ceiling
// grow was stored verbatim and reproduced the Bug 155 hot-loop through
// the resize verb. Runs — like the Bug 383 non-positive floor above —
// BEFORE the shrink-vs-force gate: `force` waives the shrink-direction
// opt-in, never the physical floor/ceiling, and checking bounds first
// gives the operator the accurate "invalid size" envelope instead of an
// "add --force" hint on a size that would be refused even with force.
if rejectVDPatchOutOfBounds(w, patch, rd, vn) {
return true
}

// Scenario 4.W13: reject any shrink (`new < previous`) unless the
// operator opted in via `force=true`. Runs BEFORE the merge + store
// write so a rejected shrink leaves the stored spec untouched — a
Expand All @@ -827,6 +842,30 @@ func rejectVDPatchSize(
return rejectShrinkWithoutForce(w, r, patch, rd, vn, previousSizeKib)
}

// rejectVDPatchOutOfBounds writes a 400 + FAIL_INVLD_VLM_SIZE envelope
// when the patch carries a `size_kib` outside the accepted
// [minVolumeDefinitionSizeKib, maxVolumeDefinitionSizeKib] range and
// returns true to signal the caller to short-circuit. Reuses the create
// path's validateVDSize + writeVDSizeRejection so the wire shape is
// byte-identical across the create and resize verbs (Bug 155 parity).
// A patch that does not touch size (`SizeKib == nil`) is left alone.
func rejectVDPatchOutOfBounds(
w http.ResponseWriter, patch *volumeDefinitionModifyBody, rd string, vn int32,
) bool {
if patch.SizeKib == nil {
return false
}

sizeErr := validateVDSize(*patch.SizeKib)
if sizeErr == nil {
return false
}

writeVDSizeRejection(w, rd, vn, *patch.SizeKib, sizeErr)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The writeVDSizeRejection helper has a hardcoded correction message (Correc) that instructs the operator to re-issue linstor vd c (the create command). Since this helper is now reused in the resize/PUT path (rejectVDPatchOutOfBounds), this correction message will be misleading to operators attempting a resize. Consider refactoring writeVDSizeRejection to accept the action/verb or make the correction message more generic (e.g., "retry the operation with a valid size").


return true
}

// rejectVDNonPositiveSize writes a 400 + FAIL_INVLD_VLM_SIZE envelope
// when the patch carries a non-positive `size_kib` and returns true
// to signal the caller to short-circuit.
Expand Down
26 changes: 16 additions & 10 deletions pkg/rest/volume_definitions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -810,12 +810,18 @@ func TestVolumeDefinitionsUpdateShrinkWithForceQueryAccepted(t *testing.T) {
}
}

// TestVolumeDefinitionsUpdateLargeSizeKibRoundTrip pins that
// petabyte-scale `size_kib` values survive the JSON round-trip
// without truncation. The wire field is int64 on our side and uint64
// in golinstor; a regression that decoded into int32 would clamp
// anything above ~2 TiB. 2^40 KiB = 1 PiB — covers the largest
// volumes any sane cluster would carve.
// TestVolumeDefinitionsUpdateLargeSizeKibRoundTrip pins that a large
// (multi-TiB) `size_kib` survives the JSON round-trip without
// truncation. The wire field is int64 on our side and uint64 in
// golinstor; a regression that decoded into int32 would clamp anything
// above ~2 TiB. The guard uses DRBD's 16 TiB per-device ceiling
// (maxVolumeDefinitionSizeKib, Bug 155) — the largest accepted size and
// still 8× above the int32 clamp point, so it exercises the >int32 wire
// path while remaining a size the resize bounds gate accepts. Petabyte-
// scale sizes are refused on BOTH create and resize (see
// TestBug155VDCreateRefusesAbsurdSize and the round-4 resize-bounds
// regressions); this test previously used 1 PiB, which pinned the exact
// create/resize bounds asymmetry the round-4 gate closed.
func TestVolumeDefinitionsUpdateLargeSizeKibRoundTrip(t *testing.T) {
st := store.NewInMemory()
ctx := t.Context()
Expand All @@ -832,9 +838,9 @@ func TestVolumeDefinitionsUpdateLargeSizeKibRoundTrip(t *testing.T) {
base, stop := startServerWithStore(t, st)
defer stop()

const oneEiB = int64(1) << 40 // 1 PiB in KiB
const largeInBoundsKib = maxVolumeDefinitionSizeKib // 16 TiB, the largest accepted size (~8× int32 max)

body, _ := json.Marshal(apiv1.VolumeDefinition{SizeKib: oneEiB})
body, _ := json.Marshal(apiv1.VolumeDefinition{SizeKib: largeInBoundsKib})

resp := httpPut(t, base+"/v1/resource-definitions/pvc-pib/volume-definitions/0", body)
_ = resp.Body.Close()
Expand All @@ -848,8 +854,8 @@ func TestVolumeDefinitionsUpdateLargeSizeKibRoundTrip(t *testing.T) {
t.Fatalf("Get: %v", err)
}

if got.SizeKib != oneEiB {
t.Errorf("SizeKib after large PUT: got %d, want %d (truncation?)", got.SizeKib, oneEiB)
if got.SizeKib != largeInBoundsKib {
t.Errorf("SizeKib after large PUT: got %d, want %d (truncation?)", got.SizeKib, largeInBoundsKib)
}
}

Expand Down
Loading