Repository navigation
✨ feat(ownership): libpod ownership + visibility wiring (#148) - #193
Conversation
…ownership+visibility wiring
Pods have no Docker-compat equivalent, and libpod network inspect
uses lowercase "labels" (plus an occasional single-element array
wrap) unlike every other Docker-compat-shaped inspect body — both
need their own Kind so ownership/visibility dispatch can route on
Kind alone without threading libpod-ness through every call site.
- LibpodInspectPath: dedicated /libpod/{kind}/{id}/json builder for
the two new kinds, wired into InspectPath's existing switch
- DecodeLibpodLabels/decodeLibpodNetworkLabels: lowercase-keyed pod
labels, plus array-unwrap-then-decode for network inspect
…on libpod endpoints Extends mutateOwnershipRequest with libpod cases so POST /libpod/containers/create, /pods/create, /volumes/create, /networks/create, and /secrets/create get the owner label injected when ownership.owner is configured — matching each endpoint's actual wire shape rather than assuming a single convention: - container/pod/network create: lowercase top-level "labels" - volume create: capitalized "Labels" (VolumeCreateOptions has no json tag on that field, so it falls back to the Go field name) - secret create: no JSON body at all — driver/labels are query params, reuses the existing addOwnerLabelToBuildQuery helper Read-side owner filtering (list injection + per-resource inspect/ action dispatch) is extended to every /libpod/ list and inspect path for containers, pods, networks, volumes, and secrets — not just pods — so switching a client from Docker-compat to libpod-native paths can't bypass ownership isolation for reads on existing resources. Closes the cross-owner pod-membership deferral called out in #190: POST /libpod/pods/create requests joining another owner's namespaces are denied, and POST /libpod/containers/create requests targeting another owner's pod (SpecGenerator "pod" field) are denied, reusing the existing container:<ref> namespace-sharing and embedded-resource reference checks against libpod's uniform {"nsmode":"container","value":"<ref>"} namespace shape. Deny reasons for libpod-family requests get the "libpod " prefix, matching the convention libpod's body inspectors already use.
…l, and read dispatch Table-driven tests mirroring the existing ownership test patterns: label stamping on every libpod create endpoint (including the capitalized-Labels volume-create deviation and the secret-create query-param path), cross-owner pod-membership denial in both directions (pod-create namespace joins, container-create pod targeting) plus the same-owner allow counterparts, libpod read-path owner-filter dispatch across container/pod/network/volume/secret, exec-identifier resolution, and a negative test proving libpod predicates never fire on Docker-compat paths.
…and network array-unwrap Wires every /libpod/ list endpoint into the existing visibility label-filter injection (needsVisibilityLabelFilter), and every inspect/action path (containers, pods, networks, volumes, secrets) into resourceVisible dispatch — pods route through the new KindLibpodPod since they have no Docker-compat equivalent, the rest reuse the existing Docker-compat Kind constants since ownership labels live in the same shape once decoded. Every libpod inspect endpoint is uniformly suffixed "/json" (unlike Docker-compat's mixed bare-path/json-suffixed convention), so the new identifier helpers use suffixedIdentifier rather than singleSegmentIdentifier. Network inspect responses are unwrapped from Podman's occasional single-element-array envelope before label extraction (upstream Inspector round-trip, dockerresource.DecodeLibpodLabels). Hidden-resource deny reasons get the "libpod " prefix for requests under /libpod/, matching the body-inspector convention.
…ty, and network array-unwrap Table-driven tests: visibility label-filter injection on every libpod list endpoint, KindLibpodPod list/inspect visibility (hidden-pod 404, visible-pod forward, rollout-mode would-deny), the "libpod " deny-reason prefix across libpod pod/container and Docker-compat paths, an end-to-end upstreamInspector round-trip for both bare-object and array-wrapped network inspect responses, and a negative test proving libpod predicates never fire on Docker-compat paths.
…d checks CHANGELOG: new Unreleased/Added entry after the existing #148 entries, and updates the pod-create entry's "deferred to a later PR" note now that cross-owner pod-membership checks have landed. configuration.mdx: new paragraph under Owner Label Isolation covering the libpod-specific label casing/query-param deviations, KindLibpodPod, and the two-directional cross-owner pod check.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Review limit reached
Next review available in: 15 minutes You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughThe pull request adds Podman/libpod pod and network resource kinds, inspect paths, and label decoding. Ownership middleware now stamps labels, extracts namespace and resource references, filters list routes, and checks ownership for libpod resources and actions. Visibility middleware now classifies libpod paths, applies label filters, inspects resources, and prefixes denial reasons. Tests cover request mutation, cross-owner checks, response formats, path isolation, and visibility behavior. Documentation describes the new enforcement coverage. Possibly related PRs
🚥 Pre-merge checks | ✅ 2✅ Passed checks (2 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (6)
app/internal/ownership/libpod_test.go (4)
157-158: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDerive the field list from
libpodNamespaceSharingFields.Line 157 hardcodes the five namespace fields. The test and the production set at
libpod.goLine 36 can now drift. If a field is added tolibpodNamespaceSharingFields, this test keeps passing without covering it.The test is in package
ownership, so it can read the variable directly.♻️ Proposed change
- fields := []string{"netns", "pidns", "ipcns", "userns", "utsns"} - for _, field := range fields { + for _, field := range libpodNamespaceSharingFields {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/internal/ownership/libpod_test.go` around lines 157 - 158, Update the test’s field iteration in `libpod_test.go` to derive directly from the package-level `libpodNamespaceSharingFields` variable instead of maintaining a hardcoded namespace list. Preserve the existing test behavior while ensuring newly added production fields are automatically covered.
387-411: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd the exec
!foundfail-through case.This test covers the resolved-exec denial. It does not cover
middleware.goLines 338-340, where an unresolvable exec ID returnsverdictPassThroughand the request reaches the socket. That branch is the fail-open edge of the libpod exec path. Pin it with a subtest that supplies an emptyexecsmap and asserts the request is forwarded.Convert this test into a table with
resolvedandunresolvedrows to keep the file's table-driven style.As per coding guidelines: "Prefer table-driven tests with
testing.Tandhttptest."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/internal/ownership/libpod_test.go` around lines 387 - 411, Convert TestMiddlewareLibpodExecDispatchResolvesContainerOwner into a table-driven test with resolved and unresolved cases. Keep the resolved case asserting a forbidden response and handler denial; add an unresolved case with an empty execs map, asserting verdictPassThrough behavior by confirming the downstream handler is invoked and the request succeeds.Source: Coding guidelines
19-24: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueStale table contract on
wantLabels.The comment says
nilmeans "checkr.URL.RawQuery's labels param instead". No case setsnil, and the subtest body has no branch for it. Anilvalue would make the assertion loop run zero times and pass silently.
TestMiddlewareStampsOwnerLabelOnLibpodSecretCreateQueryParamalready covers the query-param case. Drop the comment.♻️ Proposed change
tests := []struct { name string path string body string - wantLabels map[string]any // nil means "check r.URL.RawQuery's labels param instead" + wantLabels map[string]any }{🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/internal/ownership/libpod_test.go` around lines 19 - 24, Remove the stale inline comment on the wantLabels field in the test table used by TestMiddlewareStampsOwnerLabelOnLibpodSecretCreateQueryParam; leave the field and assertion behavior unchanged.
142-148: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAssert the forwarded request's query, not the original request's.
Line 143 reads
req.URL.Query()afterServeHTTPreturns. That passes only because the middleware mutates the request URL in place. If the middleware later switches tor.Clone(), this assertion fails even though the injected label is correct.
TestMiddlewareLibpodListInjectsOwnerFiltercapturesr.URL.Query()inside the downstream handler at Line 430. Use the same approach here.♻️ Proposed change
forwardedBody := "" + forwardedLabels := "" handler := middlewareWithDeps(testLogger(), opts, fakeInspector{}.inspectResource, fakeInspector{}.inspectExec)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { raw, err := io.ReadAll(r.Body) if err != nil { t.Fatalf("read body: %v", err) } forwardedBody = string(raw) + forwardedLabels = r.URL.Query().Get("labels") w.WriteHeader(http.StatusAccepted) }))var labels map[string]string - if err := json.NewDecoder(strings.NewReader(req.URL.Query().Get("labels"))).Decode(&labels); err != nil { + if err := json.Unmarshal([]byte(forwardedLabels), &labels); err != nil { t.Fatalf("decode labels query param: %v", err) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/internal/ownership/libpod_test.go` around lines 142 - 148, Update TestMiddlewareLibpodListInjectsOwnerFilter to assert the query captured inside the downstream handler, rather than reading req.URL.Query() after ServeHTTP returns. Reuse the handler-captured query value, decode its labels parameter, and keep the existing owner-label assertion unchanged.app/internal/ownership/libpod_paths.go (2)
105-144: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCollapse the five matchers into one helper.
libpodContainerIdentifier,libpodExecIdentifier,libpodPodIdentifier,libpodNetworkIdentifier,libpodVolumeIdentifier, andlibpodSecretIdentifiershare one body. They differ only in the path segment and the reserved-word set. A single helper puts the reserved sets next to each other, which is where the container matcher's missingstatsentry is easy to miss.♻️ Proposed helper
func libpodResourceIdentifier(normPath, segment string, reserved ...string) (string, bool) { prefix := libpodPrefix + segment + "/" if !strings.HasPrefix(normPath, prefix) { return "", false } identifier, _, _ := strings.Cut(strings.TrimPrefix(normPath, prefix), "/") if identifier == "" || slices.Contains(reserved, identifier) { return "", false } return identifier, true }Call sites keep the documented reserved sets:
func libpodNetworkIdentifier(normPath string) (string, bool) { return libpodResourceIdentifier(normPath, "networks", "create", "json", "prune") } func libpodVolumeIdentifier(normPath string) (string, bool) { return libpodResourceIdentifier(normPath, "volumes", "create", "json", "prune") } func libpodSecretIdentifier(normPath string) (string, bool) { return libpodResourceIdentifier(normPath, "secrets", "create", "json") }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/internal/ownership/libpod_paths.go` around lines 105 - 144, Collapse the duplicated logic in libpodContainerIdentifier, libpodExecIdentifier, libpodPodIdentifier, libpodNetworkIdentifier, libpodVolumeIdentifier, and libpodSecretIdentifier into a shared libpodResourceIdentifier helper accepting the path segment and reserved identifiers. Update each matcher to delegate to it while preserving its existing reserved-word set, including the container matcher’s stats entry.
53-64: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winReserve the libpod container collection-level segments.
libpodContainerIdentifiercurrently matchesGET /libpod/containers/statsandGET /libpod/containers/showmountedas container IDs. Those collection endpoints should pass through unless a container is namedstatsorshowmounted, where the ownership check would consult the wrong container. MatchlibpodPodIdentifierand reserve the collection segments.♻️ Proposed reservation
switch identifier { - case "", "create", "json", "prune": + case "", "create", "json", "prune", "stats", "showmounted": return "", false default: return identifier, true }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/internal/ownership/libpod_paths.go` around lines 53 - 64, Update libpodContainerIdentifier to reserve the collection-level path segments used by libpod container endpoints, matching the same pattern already used by libpodPodIdentifier. Extend the existing switch on the parsed identifier so paths like stats and showmounted are treated as non-container collection routes and return false. Keep the current prefix parsing in libpodContainerIdentifier unchanged and only adjust the reserved segment handling.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@app/internal/visibility/libpod_test.go`:
- Around line 23-55: Add fuzz coverage for the libpod identifier helper
functions near TestMiddlewareLibpodListInjectsVisibilityLabelFilter. Ensure the
fuzz test rejects every input that does not use the /libpod/ prefix and rejects
collection routes as resource identifiers, while accepting only valid
resource-specific paths; seed it with representative valid, collection, and
non-libpod inputs.
- Around line 59-153: The tests in app/internal/visibility/libpod_test.go:59-153
should be consolidated into a table-driven
TestMiddlewareLibpodPodListAndInspectVisibility covering hidden, visible, and
rollout cases, with expected forwarding, status, decision, reason code, and
reason-prefix fields asserted per case. Also convert the negative
Docker-compatible path test in app/internal/visibility/libpod_test.go:248-272
into a table-driven test; update both sites without changing the behaviors being
validated.
In `@docs/content/docs/configuration.mdx`:
- Line 699: Update the libpod_pod_create entry in the configuration
documentation matrix to remove the obsolete statement that cross-owner pod
membership checks are deferred. Mark or describe the check as implemented,
consistent with the paragraph documenting enforcement for libpod pod and
container creation.
---
Nitpick comments:
In `@app/internal/ownership/libpod_paths.go`:
- Around line 105-144: Collapse the duplicated logic in
libpodContainerIdentifier, libpodExecIdentifier, libpodPodIdentifier,
libpodNetworkIdentifier, libpodVolumeIdentifier, and libpodSecretIdentifier into
a shared libpodResourceIdentifier helper accepting the path segment and reserved
identifiers. Update each matcher to delegate to it while preserving its existing
reserved-word set, including the container matcher’s stats entry.
- Around line 53-64: Update libpodContainerIdentifier to reserve the
collection-level path segments used by libpod container endpoints, matching the
same pattern already used by libpodPodIdentifier. Extend the existing switch on
the parsed identifier so paths like stats and showmounted are treated as
non-container collection routes and return false. Keep the current prefix
parsing in libpodContainerIdentifier unchanged and only adjust the reserved
segment handling.
In `@app/internal/ownership/libpod_test.go`:
- Around line 157-158: Update the test’s field iteration in `libpod_test.go` to
derive directly from the package-level `libpodNamespaceSharingFields` variable
instead of maintaining a hardcoded namespace list. Preserve the existing test
behavior while ensuring newly added production fields are automatically covered.
- Around line 387-411: Convert
TestMiddlewareLibpodExecDispatchResolvesContainerOwner into a table-driven test
with resolved and unresolved cases. Keep the resolved case asserting a forbidden
response and handler denial; add an unresolved case with an empty execs map,
asserting verdictPassThrough behavior by confirming the downstream handler is
invoked and the request succeeds.
- Around line 19-24: Remove the stale inline comment on the wantLabels field in
the test table used by
TestMiddlewareStampsOwnerLabelOnLibpodSecretCreateQueryParam; leave the field
and assertion behavior unchanged.
- Around line 142-148: Update TestMiddlewareLibpodListInjectsOwnerFilter to
assert the query captured inside the downstream handler, rather than reading
req.URL.Query() after ServeHTTP returns. Reuse the handler-captured query value,
decode its labels parameter, and keep the existing owner-label assertion
unchanged.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: b993561c-a117-42bf-a76a-ca75c6843a67
⛔ Files ignored due to path filters (1)
CHANGELOG.mdis excluded by!CHANGELOG.md
📒 Files selected for processing (13)
app/internal/dockerresource/kind.goapp/internal/dockerresource/kind_test.goapp/internal/dockerresource/labels.goapp/internal/dockerresource/labels_test.goapp/internal/filter/libpod_pod_create.goapp/internal/ownership/libpod.goapp/internal/ownership/libpod_paths.goapp/internal/ownership/libpod_test.goapp/internal/ownership/middleware.goapp/internal/visibility/libpod_paths.goapp/internal/visibility/libpod_test.goapp/internal/visibility/middleware.godocs/content/docs/configuration.mdx
…ibility tests - Add FuzzLibpodPathIdentifiers covering libpod_paths.go's identifier helpers: no match outside /libpod/, collection routes never classify as a single-resource identifier, matched identifiers are non-empty and (bar the readSubresourceIdentifier-based container helper) never contain '/'. Wired into the CI fuzz matrix. - Convert TestMiddlewareLibpodPodListAndInspectVisibility and TestMiddlewareLibpodDoesNotAffectDockerCompatVisibilityPaths to table-driven form per repo convention; assertions unchanged. Addresses CodeRabbit comments 3722497023 and 3722497031 on PR #193.
…al note The libpod_pod_create prose bullet and reference table row still said cross-owner pod-membership checks were deferred to a later release. This PR implements them (see the Owner Label Isolation section) — update both to describe the now-enforced behavior instead. Addresses CodeRabbit comment 3722497036 on PR #193.
Summary
PR5 of the #148 Podman/libpod train: wires owner-label stamping and read-side visibility filtering into the libpod-native (
/libpod/) surface, and closes the cross-owner pod-membership deferral called out in #190.POST /libpod/containers/create,/pods/create,/networks/create,/volumes/create, and/secrets/createwhenownership.owneris configured — each matched to its actual wire shape (lowercaselabelsfor container/pod/network create, capitalizedLabelsfor volume create sinceVolumeCreateOptionshas no JSON tag on that field, and a query parameter for secret create since it has no JSON body).dockerresource.KindLibpodPodresource kind (pods have no Docker-compat equivalent) with its own list/inspect owner-filtering and visibility coverage./libpod/list and inspect/action path — containers, pods, networks, volumes, secrets — not just pods, so switching from Docker-compat to libpod-native paths can't bypass ownership isolation or visibility policy.dockerresource.DecodeLibpodLabelsunwraps Podman's occasional single-element-array envelope before decoding lowercaselabels.POST /libpod/pods/createrequests joining another owner's host namespaces are denied, andPOST /libpod/containers/createrequests targeting another owner's pod (SpecGenerator.pod) are denied — reusing the existingcontainer:<ref>namespace-sharing and embedded-resource-reference machinery against libpod's uniform{"nsmode":"container","value":"<ref>"}namespace shape.libpoddeny-reason prefix applied to both ownership and visibility denials on/libpod/paths, matching the convention the libpod body inspectors already use.Design decisions applied (per
#148design doc, decision C6)dockerresource.Kinditself (only 2 new kinds:KindLibpodPod,KindLibpodNetwork) rather than threading a libpod flag through ~80 existing call sites./containers/json//images/jsononly, per the design doc's explicit scope.Deviations / scope notes (from initial task framing, not from the design doc)
Labels, not lowercase — verified against real Podman v5.8.1VolumeCreateOptionssource (no JSON tag on the field, falls back to the Go field name), contradicting a naive "libpod is always lowercase" assumption.Test / coverage results
go build ./...,go vet ./...: clean.go test ./...: all packages pass.golangci-lint run: 0 issues.go test -race -coverprofile=... -covermode=atomic, differential/testcert/testhelp filtered per CI's gate): 96.1%, above the 96% gate.KindLibpodPodlist/inspect visibility (including rollout-mode would-deny), cross-owner pod denial in both directions plus same-owner allow counterparts, and negative tests proving Docker-compat behavior is unchanged.Test plan
go build ./...go vet ./...go test ./...golangci-lint runChangelog
✨ Added
KindLibpodPodandKindLibpodNetworkwith libpod-specific inspect paths and label decoding.✨ Added owner-label stamping for libpod container, pod, network, volume, and secret creation.
✨ Added ownership and visibility filtering for libpod list, inspect, exec, and action endpoints.
🔒 Added cross-owner denial for pod namespace sharing, pod targets, infra images, and container images.
🔧 Added libpod path classification and
libpoddenial-reason prefixes.🐛 Added network inspect array-envelope unwrapping.
✨ Added table-driven ownership and visibility tests.
✨ Documented libpod ownership isolation and pod-membership checks.
🔧 Validation passes for build, vet, tests, lint, race checks, and 96.1% coverage.
Confirm that every
/libpod/route requiring protection is covered by the path matchers.Confirm that libpod label casing and array/object response handling match all supported Podman API versions.