phase41: add lifecycle owner api boundary gate

This commit is contained in:
pingqiu committed 2026-06-14 09:44:38 -07:00
1 parent cd552ac3b6
commit 63d9d64749
5 files changed
+256 -7

No files matched your search

@@ -226,6 +226,82 @@ func TestPhase40D1StatusConformanceRejectsSchemaAndRBACDrift(t *testing.T) {
}
}
func TestPhase41D2LifecycleOwnerFinalizerBoundary(t *testing.T) {
api := newStatusConformanceAPIServer(t)
defer api.Close()
finalizerPatch := map[string]any{"metadata": map[string]any{
"finalizers": []any{"block.seaweedfs.com/swblockvolume-protection"},
}}
cases := []struct {
name string
token string
path string
body map[string]any
want int
}{
{
name: "operator-status cannot patch finalizers through main object",
token: "operator-status-token",
path: "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/pvc-a",
body: finalizerPatch,
want: http.StatusForbidden,
},
{
name: "lifecycle-owner can patch only finalizers through main object",
token: "lifecycle-owner-token",
path: "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/pvc-a",
body: finalizerPatch,
want: http.StatusOK,
},
{
name: "lifecycle-owner still cannot use non-existent finalizers endpoint",
token: "lifecycle-owner-token",
path: "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/pvc-a/finalizers",
body: finalizerPatch,
want: http.StatusForbidden,
},
{
name: "lifecycle-owner cannot patch spec",
token: "lifecycle-owner-token",
path: "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/pvc-a",
body: map[string]any{"spec": map[string]any{"volumeID": "pvc-a"}},
want: http.StatusForbidden,
},
{
name: "lifecycle-owner cannot patch unrelated metadata",
token: "lifecycle-owner-token",
path: "/apis/block.seaweedfs.com/v1alpha1/namespaces/kube-system/swblockvolumes/pvc-a",
body: map[string]any{"metadata": map[string]any{"labels": map[string]any{"changed": "true"}}},
want: http.StatusForbidden,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
raw, err := json.Marshal(tc.body)
if err != nil {
t.Fatalf("marshal body: %v", err)
}
req, err := http.NewRequest(http.MethodPatch, api.URL+tc.path, bytes.NewReader(raw))
if err != nil {
t.Fatalf("new request: %v", err)
}
req.Header.Set("Content-Type", "application/merge-patch+json")
if tc.token != "" {
req.Header.Set("Authorization", "Bearer "+tc.token)
}
resp, err := api.Client().Do(req)
if err != nil {
t.Fatalf("do request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != tc.want {
t.Fatalf("status=%d want %d", resp.StatusCode, tc.want)
}
})
}
}
type statusConformanceAPIServer struct {
*httptest.Server
clusterStatusSchema map[string]any
@@ -249,6 +325,8 @@ func (api *statusConformanceAPIServer) handle(w http.ResponseWriter, r *http.Req
switch {
case r.Method == http.MethodPatch && strings.HasSuffix(r.URL.Path, "/status"):
api.handleStatusPatch(w, r)
case r.Method == http.MethodPatch && strings.Contains(r.URL.Path, "/swblockvolumes/") && !strings.HasSuffix(r.URL.Path, "/finalizers"):
api.handleLifecycleOwnerPatch(w, r)
case r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/api/v1/namespaces/") && strings.HasSuffix(r.URL.Path, "/events"):
api.handleEventCreate(w, r)
default:
@@ -256,6 +334,48 @@ func (api *statusConformanceAPIServer) handle(w http.ResponseWriter, r *http.Req
}
}
func (api *statusConformanceAPIServer) handleLifecycleOwnerPatch(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer lifecycle-owner-token" {
http.Error(w, "main resource patch forbidden for observer", http.StatusForbidden)
return
}
if got := r.Header.Get("Content-Type"); got != "application/merge-patch+json" {
http.Error(w, "resource patches must use merge-patch", http.StatusUnsupportedMediaType)
return
}
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if !isFinalizerOnlyPatch(body) {
http.Error(w, "lifecycle-owner may patch only metadata.finalizers", http.StatusForbidden)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"kind":"SwBlockVolume","metadata":{"name":"pvc-a"}}`))
}
func isFinalizerOnlyPatch(body map[string]any) bool {
if len(body) != 1 {
return false
}
metadata, ok := body["metadata"].(map[string]any)
if !ok || len(metadata) != 1 {
return false
}
finalizers, ok := metadata["finalizers"].([]any)
if !ok {
return false
}
for _, item := range finalizers {
if _, ok := item.(string); !ok {
return false
}
}
return true
}
func (api *statusConformanceAPIServer) handleStatusPatch(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("Content-Type"); got != "application/merge-patch+json" {
http.Error(w, "status patches must use merge-patch", http.StatusUnsupportedMediaType)
+23 -7
View File
@@ -90,22 +90,31 @@ no code changes that broaden RBAC before this contract is accepted
Goal: stop live-only schema/RBAC bugs before QA.
Status: in progress. The schema-aware boundary gate is dev-complete; a real
live-apiserver/envtest path remains open.
Acceptance:
```text
[ ] harness installs real SwBlockCluster/SwBlockVolume CRDs
[ ] harness uses real or equivalent ServiceAccounts and ClusterRoles
[ ] status-only observer can patch status and create Events only
[ ] lifecycle owner can perform only the explicitly approved lifecycle mutation
[ ] wrong status casing, enum drift, endpoint drift, and RBAC broadening fail
[ ] finalizer/main-object patch behavior is tested against the real API
[x] harness loads real SwBlockCluster/SwBlockVolume CRD status schemas
[x] harness uses equivalent ServiceAccount/RBAC tokens for observer and
lifecycle owner
[x] status-only observer can patch status and create Events only
[x] lifecycle owner can perform only the explicitly approved finalizer-shaped
main-object patch
[x] wrong status casing, enum drift, endpoint drift, RBAC broadening, spec
patch, unrelated metadata patch, and fake `/finalizers` endpoint fail
[ ] run the same boundary against a real Kubernetes API or envtest apiserver
```
Verification:
```text
go test ./core/ops ./cmd/sw-block
new envtest/live-apiserver target with real CRD schemas and RBAC
scripts/run-phase41-lifecycle-owner-api-boundary.ps1
scripts/run-phase41-lifecycle-owner-api-boundary.sh
testops/scenarios/lifecycle-owner-api-boundary-chain.yaml
future envtest/live-apiserver target with real CRD schemas and RBAC
negative tests for forbidden spec/storage/workload mutation
```
@@ -243,6 +252,13 @@ git diff --check
released operator-status status/events-only boundary; and making finalizer
mutation an explicit lifecycle-owner strategy decision rather than an RBAC
patch to the observer.
- 24%: D2 schema-aware boundary gate dev-complete. Added
`TestPhase41D2LifecycleOwnerFinalizerBoundary`, Phase 41 D2 wrapper scripts,
and a TestOps scenario. The gate proves the observer cannot patch the main
`SwBlockVolume`, the future lifecycle-owner identity can only make a
finalizer-shaped main-object patch, and spec/unrelated metadata/fake
`/finalizers` endpoint mutation is rejected. A true live-apiserver/envtest
execution path remains open before D2 can be called fully closed.
## Prerequisites / Risks
@@ -0,0 +1,37 @@
param(
[string]$ProductRoot = (Get-Location).Path,
[string]$ArtifactDir = ""
)
$ErrorActionPreference = "Stop"
if ([string]::IsNullOrWhiteSpace($ArtifactDir)) {
$stamp = Get-Date -Format "yyyyMMdd-HHmmss"
$ArtifactDir = Join-Path $ProductRoot "results\phase41-lifecycle-owner-api-boundary-$stamp"
}
New-Item -ItemType Directory -Force -Path $ArtifactDir | Out-Null
$summary = Join-Path $ArtifactDir "phase41-lifecycle-owner-api-boundary-summary.txt"
Set-Content -Path $summary -Value "phase41_lifecycle_owner_api_boundary_status=running"
Push-Location $ProductRoot
try {
$testPattern = "TestPhase40D1KubernetesStatusClientConformsToCRDSchemaAndRBAC|TestPhase40D1StatusConformanceRejectsSchemaAndRBACDrift|TestPhase41D2LifecycleOwnerFinalizerBoundary"
$log = Join-Path $ArtifactDir "go-test-core-ops.log"
& go test ./core/ops -count=1 -run $testPattern *>&1 | Tee-Object -FilePath $log
if ($LASTEXITCODE -ne 0) {
Add-Content -Path $summary -Value "go_test_core_ops=failed"
Add-Content -Path $summary -Value "phase41_lifecycle_owner_api_boundary_status=failed"
exit $LASTEXITCODE
}
Add-Content -Path $summary -Value "go_test_core_ops=ok"
Add-Content -Path $summary -Value "operator_status_main_patch_allowed=false"
Add-Content -Path $summary -Value "lifecycle_owner_finalizer_patch_allowed=true"
Add-Content -Path $summary -Value "lifecycle_owner_spec_patch_allowed=false"
Add-Content -Path $summary -Value "lifecycle_owner_unrelated_metadata_patch_allowed=false"
Add-Content -Path $summary -Value "finalizers_endpoint_allowed=false"
Add-Content -Path $summary -Value "phase41_lifecycle_owner_api_boundary_status=ok"
} finally {
Pop-Location
}
@@ -0,0 +1,32 @@
#!/usr/bin/env bash
set -euo pipefail
PRODUCT_ROOT="${1:-$(pwd)}"
ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-"$PRODUCT_ROOT/results/phase41-lifecycle-owner-api-boundary-$(date -u +%Y%m%dT%H%M%SZ)"}"
mkdir -p "$ARTIFACT_DIR"
SUMMARY="$ARTIFACT_DIR/phase41-lifecycle-owner-api-boundary-summary.txt"
echo "phase41_lifecycle_owner_api_boundary_status=running" > "$SUMMARY"
cd "$PRODUCT_ROOT"
TEST_PATTERN='TestPhase40D1KubernetesStatusClientConformsToCRDSchemaAndRBAC|TestPhase40D1StatusConformanceRejectsSchemaAndRBACDrift|TestPhase41D2LifecycleOwnerFinalizerBoundary'
GO_BIN="${GO_BIN:-go}"
if "$GO_BIN" test ./core/ops -count=1 -run "$TEST_PATTERN" > "$ARTIFACT_DIR/go-test-core-ops.log" 2>&1; then
{
echo "go_test_core_ops=ok"
echo "operator_status_main_patch_allowed=false"
echo "lifecycle_owner_finalizer_patch_allowed=true"
echo "lifecycle_owner_spec_patch_allowed=false"
echo "lifecycle_owner_unrelated_metadata_patch_allowed=false"
echo "finalizers_endpoint_allowed=false"
echo "phase41_lifecycle_owner_api_boundary_status=ok"
} >> "$SUMMARY"
else
cat "$ARTIFACT_DIR/go-test-core-ops.log"
{
echo "go_test_core_ops=failed"
echo "phase41_lifecycle_owner_api_boundary_status=failed"
} >> "$SUMMARY"
exit 1
fi
@@ -0,0 +1,44 @@
# Runner-native Phase 41 D2 gate: lifecycle-owner API/RBAC boundary.
name: lifecycle-owner-api-boundary-chain
description: >
Proves that the released operator-status boundary remains status/events-only
while the future lifecycle-owner boundary permits only finalizer-shaped main
SwBlockVolume patches and rejects spec/unrelated metadata mutation.
vars:
product_root: "{{ env.PRODUCT_ROOT | default('/mnt/c/work/seaweed_block') }}"
phases:
- name: api_boundary
actions:
- type: exec
name: run_phase41_api_boundary
cmd: "rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary && cd {{ product_root }} && SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary bash scripts/run-phase41-lifecycle-owner-api-boundary.sh {{ product_root }}"
- name: asserts
actions:
- type: grep_log
name: api_boundary_ok
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary/phase41-lifecycle-owner-api-boundary-summary.txt"
pattern: "^phase41_lifecycle_owner_api_boundary_status=ok$"
- type: grep_log
name: operator_status_no_main_patch
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary/phase41-lifecycle-owner-api-boundary-summary.txt"
pattern: "^operator_status_main_patch_allowed=false$"
- type: grep_log
name: lifecycle_owner_finalizer_only_allowed
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary/phase41-lifecycle-owner-api-boundary-summary.txt"
pattern: "^lifecycle_owner_finalizer_patch_allowed=true$"
- type: grep_log
name: lifecycle_owner_spec_forbidden
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary/phase41-lifecycle-owner-api-boundary-summary.txt"
pattern: "^lifecycle_owner_spec_patch_allowed=false$"
- type: grep_log
name: lifecycle_owner_unrelated_metadata_forbidden
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary/phase41-lifecycle-owner-api-boundary-summary.txt"
pattern: "^lifecycle_owner_unrelated_metadata_patch_allowed=false$"
- type: grep_log
name: finalizers_endpoint_forbidden
path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-phase41-lifecycle-owner-api-boundary/phase41-lifecycle-owner-api-boundary-summary.txt"
pattern: "^finalizers_endpoint_allowed=false$"