Skip to content

fix(rbac): scope combo predicates to their correct api_groups (#125) - #131

Merged
rrskris merged 2 commits into
kaaval:mainfrom
shariqueahmad108-ship-it:fix/combo-predicates-api-groups
Aug 5, 2026
Merged

rrskris merged 2 commits into
kaaval:mainfrom
shariqueahmad108-ship-it:fix/combo-predicates-api-groups

Conversation

@shariqueahmad108-ship-it

Copy link
Copy Markdown
Contributor

What this changes

_has_resource() in effective_access.py matched on resource name alone, ignoring api_groups. So a rule granting impersonate on a CRD-defined users resource in an unrelated API group fired impersonation_grant, even though that escalation path only exists for users in the core group (""). Same issue for roles/clusterroles/rolebindings/clusterrolebindings, which only matter in rbac.authorization.k8s.io.

Added an api-group dimension to _has_resource() and pass the correct group per predicate (per the table in the issue). Missing/empty api_groups is treated as the core group, not "matches nothing" — existing fixtures needed no changes. "*" in api_groups still matches, same as resources/verbs.

Closes #125

Type

  • Bug fix

Checklist

  • Tests pass (see below)
  • Added/updated tests for the behavior change
  • N/A — not a new rule, no remediation/citation change
  • N/A — not a new rule, no fixture needed
  • N/A — not a new rule, no doc change needed
  • Conventional commit messages

How you verified it

KAAVAL_ADMIN_PASSWORD=test-admin-password python -m pytest tests/test_effective_access.py -v — 24/24 pass, including two new regression tests pinning the non-core-group negative case (for combo_role_escalation and impersonation_grant) and one for the missing-api_groups-key case.

Ran the full suite too: 117 passed. The 2 failures need a live Postgres instance I didn't have running locally (test_smoke.py, test_error_surfacing.py) — unrelated to this change, and CI's Postgres service container should cover them.

…#125)

_has_resource() matched on resource name alone, so a rule granting
e.g. impersonate on a CRD-defined 'users' resource in an unrelated
API group fired impersonation_grant, even though that escalation path
only exists for 'users' in the core group. Same issue for
roles/clusterroles/rolebindings/clusterrolebindings, which only matter
in rbac.authorization.k8s.io.

Added an api-group dimension to _has_resource() and pass the correct
group per predicate. Missing/empty api_groups is treated as the core
group (not 'matches nothing'), so existing fixtures needed no changes.
Wildcard ('*') in api_groups still matches, same as resources/verbs.

Added regression tests for combo_role_escalation and
impersonation_grant pinning the non-core-group negative case, plus one
for the missing-api_groups-key case.

Fixes kaaval#125

Signed-off-by: shariqueahmad108-ship-it <[email protected]>

@rrskris rrskris left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Welcome, and thank you — you turned #125 around in about two hours and the shape of this is right. I've approved the workflow runs (first-time contributor gate, nothing you did), and CI is fully green.

I'm still asking for one change, because I found a false-negative regression that your tests don't cover and CI can't see. On a security scanner a missed CRITICAL finding is the worst failure mode we have, so it needs fixing before this lands.

The core of the fix is correct

_has_resource(rule, groups, *resources) with per-predicate group sets is exactly right, and the table from the issue is implemented faithfully. "*" in api_groups still wildcards. Both non-core negative tests are good, and the CRD-reuse scenario they pin is the real thing #125 was about.

Required: the missing-api_groups default silently disables two CRITICAL rules

# Missing/empty api_groups means the core group (""), not "matches nothing".
rule_groups = set(rule.get("api_groups") or [""])

Defaulting to core is right for impersonate and pods. It is wrong for the two RBAC-group predicates, because {""} ∩ {"rbac.authorization.k8s.io"} is empty — so a rule granting create on roles with no api_groups key now fails the check that used to pass.

Ran against your branch:

B. roles+escalate, no api_groups key         -> []      (was: combo_role_escalation)
C. rolebindings+bind, no api_groups key      -> []      (was: combo_bind_escalation)
H. cluster-admin: verbs ['*'], resources ['*'], no api_groups key
                                             -> ['impersonation_grant', 'privileged_pod_creation']
                                                (was: all four)

Case H is the one that decided it for me: a wildcard-everything grant — the most dangerous rule Kubernetes can express — silently stops reporting both escalation findings.

Your test suite passes because the only missing-api_groups test you added, test_combo_fires_on_impersonate_users_with_missing_api_groups_key, covers impersonate — a core-group predicate, the one case where the core default happens to be correct. The RBAC-group predicates have no equivalent test, so the regression is invisible. That's an easy blind spot to hit; it's not carelessness.

Worth saying why this input actually occurs: real Kubernetes rejects a PolicyRule without api_groups, so a live cluster scan is safe. But POST /rbac/combo-scan (shipped in #105) takes hand-written graphs, --manifests mode parses YAML that can be an unrendered template, and the fixtures in this repo omit the field in places. Those are precisely the paths where someone writes resources: ["roles"] and nothing else.

Suggested fix

Treat absent/empty api_groups as unspecified — don't exclude on it, rather than as core:

    rule_groups = rule.get("api_groups")
    if not rule_groups:          # absent/empty -> unspecified, don't narrow
        return True
    rule_groups = set(rule_groups)
    return bool(rule_groups & groups) or "*" in rule_groups

The principle: api_groups should only ever be used to rule out a rule that explicitly declares a different group. An absent field is missing information, and a scanner should resolve missing information toward reporting, not toward silence.

I ran this against your branch — all 24 of your tests still pass, including all three new ones, and B/C/H all detect again. Your two non-core negative tests still pass because those rules set api_groups explicitly, which is the case the check is genuinely for.

Please also add the mirror of your existing test for an RBAC-group predicate — "create roles with no api_groups key, paired with escalate, still fires combo_role_escalation" — so this can't come back.

Non-blocking

_role_is_privileged() has the same class of issue and this PR doesn't touch it. It inlines its own resource checks rather than going through _has_resource, so secrets and pods/exec still match on name alone regardless of group. It feeds privileged_pod_creation, so it's the same detection path. Out of scope for #125 as written — don't expand this PR. If you want it, say so and I'll file it; otherwise I will.

One housekeeping note

Your PR description reports "117 passed, 2 failures needing a live Postgres." I get 128 passed, 0 failures, no Postgres on your branch (main is 125, so your 3 new tests are the delta). The suite uses SQLite and shouldn't need a database — so your local env is likely on a stale base or a partial install. Nothing to fix in this PR, but worth sorting out so your local runs mean something. CI agrees with me here.

Fix the default and add the RBAC-group test, and I'll merge this. Genuinely good first contribution — the diagnosis was right, the structure was right, and the gap is one that a careful reviewer catches, not one that says anything bad about the work.

Good catch in review - defaulting a missing/empty api_groups to "" was
right for impersonate/pods but wrong for the roles/clusterroles and
rolebindings/clusterrolebindings checks, since "" isn't in
rbac.authorization.k8s.io. A rule with no api_groups key was silently
failing to trip combo_role_escalation / combo_bind_escalation.

Now a missing/empty api_groups is treated as unspecified rather than
core-only, so it just doesn't narrow the match. That's broader than
before, so it can't bring back the miss on the core-group predicates
while fixing the RBAC-group ones.

Added the roles/clusterroles + missing-api_groups test that was asked
for.

Signed-off-by: shariqueahmad108-ship-it <[email protected]>
@shariqueahmad108-ship-it
shariqueahmad108-ship-it force-pushed the fix/combo-predicates-api-groups branch from bae1954 to 2cd093f Compare August 1, 2026 08:17
@shariqueahmad108-ship-it

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review — good catch, that was a real miss. Fixed: _has_resource now treats a missing/empty api_groups as unspecified instead of defaulting it to core, so it just doesn't narrow the match when the field's absent. Added the roles/clusterroles + missing-api_groups test you asked for.

On the Postgres/SQLite thing — I didn't have Docker running locally so I couldn't spin up real Postgres. Just tried overriding DATABASE_URL to SQLite and got 128 passed / 1 failed. The one failure is test_smoke.py::test_login_and_self_scan, which hits a genuinely Postgres-only SQL path (near "SET": syntax error under SQLite) — unrelated to this PR, and probably the same test that passes for you against real Postgres. Not sure where I got "SQLite" from originally, sorry for the noise there.

Should be good to go now.

@rrskris rrskris left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is exactly right. Approving.

I re-ran the four cases from my review across three commits to confirm the fix does what it claims and doesn't trade one bug for another:

Case (no api_groups key) main your first commit this branch
B. roles+escalate fires [] fires ✅
C. rolebindings+bind fires [] fires ✅
H. wildcard */* all 4 2 of 4 all 4 ✅
N. explicit unrelated group fires (the #125 bug) [] [] ✅

Row N is the one that matters for scope: the #125 false positive stays fixed. Rows B/C/H are back to parity with main. The middle column reproduces what I reported in the review, so we agree on what was broken and on what fixed it.

tests/test_effective_access.py: 25 passed. Full suite: 128 passed, 0 failures.

The new test is well-chosen — it pins the RBAC-group half of the default, which is the specific thing that was invisible before. The if not rule_groups: return True comment explaining why (resolve missing information toward reporting) is the part I'd have written myself; it's the reasoning that keeps someone from "tidying" this back into a core-group default in six months.

On the local test env — you don't need to override DATABASE_URL at all. The suite runs on the default config with no Postgres and no Docker; test_smoke.py::test_login_and_self_scan passes for me that way. The SQLite override is what's causing your one failure (near "SET": syntax error), not revealing it. Drop the override and you should get a clean 128.

Merging this. Thanks for the quick, precise turnaround on the follow-up — you diagnosed #125 correctly, took the regression report without getting defensive about it, and fixed it at the right level rather than patching the symptom. That's a good first contribution by any measure.

I'm filing the _role_is_privileged() follow-up I mentioned, as promised — you were right to leave it out of this PR.

If you want more

That follow-up issue is yours if you want it — it's the direct continuation of this work, same file, same reasoning, and you already have the whole context loaded. Comment on it and I'll assign it to you.

If you'd rather do something different from the same area, #120 (namespaced Role granting cluster-scoped resources — a grant that silently does nothing, which users read as "it's fine") is a self-contained new rule and a good match for how you work: read the predicate, find the edge case, pin it with a test.

Your #143 is in my queue too — I'll get to it this week. Three PRs in, you've got a real feel for this codebase, so pick whatever looks interesting and just say so on the issue; I'll assign it so nobody doubles up on you.

@rrskris

rrskris commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

Follow-up filed as #144 (_role_is_privileged(), same class of bug, same file) — tagged good first issue, unassigned. It's yours if you want it, just say so there.

@rrskris
rrskris merged commit 866c29f into kaaval:main Aug 5, 2026
7 checks passed
rrskris pushed a commit that referenced this pull request Aug 5, 2026
) (#145)

_role_is_privileged() inlined its own resource checks and matched
`secrets` and the `pods/*` exec subresources by name alone, ignoring
api_groups. A CRD reusing one of those names in an unrelated group could
make a role look privileged, feeding a false-positive HIGH
privileged_pod_creation finding — the same class of bug #131 fixed for the
combo predicates.

Route those checks through _has_resource() with _CORE_API_GROUP, exactly as
_can_create_pods() and _can_impersonate() do after #131. The wildcard and
escalation-verb checks are group-independent and left unchanged. Missing or
empty api_groups stays unspecified and still matches, so hand-built graphs
from POST /rbac/combo-scan and unrendered --manifests templates are not
silently dropped.

Tests: add a privileged-SA fixture whose `secrets` grant sits in an
unrelated API group (must not fire) and the same fixture with api_groups
absent (must still fire — the regression guard).

Closes #144.

Signed-off-by: shariqueahmad108-ship-it <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
@rrskris

rrskris commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

Following up on the test_smoke.py::test_login_and_self_scan failure you hit, and the local-Postgres requirement you mentioned.

You were right, and our documentation was wrong. I owe you a correction.

CONTRIBUTING.md claimed the test suite needs "neither a cluster nor a database". That is true for the RBAC, scoring and remediation tests, but not for test_smoke.py — it drives the real FastAPI startup path (create_all plus tenant/admin seeding) through TestClient, so it opens a genuine database connection. Its own docstring said "Requires a reachable Postgres instance" the whole time. The two documents contradicted each other and you followed the wrong one.

This got written off earlier on the grounds that it "passes locally with no Postgres". That was my mistake: this machine runs a Postgres on 127.0.0.1:5432, which happens to be the exact application default in app/database.py. CI passes for the same reason — it runs a postgres:16-alpine service container on 5432. Point DATABASE_URL at a closed port and your failure reproduces immediately:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError)
connection to server at "127.0.0.1", port 55432 failed: Connection refused

There was a second trap underneath it: make db publishes Postgres on 55432, while the application default is 5432. make test sets DATABASE_URL for you, but the command printed in test_smoke.py's docstring did not — so following that docstring after make db failed against the wrong port, with a working database sitting right there.

Fixed in #149: CONTRIBUTING.md now names the one test that needs a database, shows the exact error so it reads as expected rather than as a broken checkout, documents the port mismatch, and gives a --ignore one-liner for running the other 130 tests with no database at all.

Thank you for reporting it, and sorry it took two of you saying the same thing before it was taken at face value.

rrskris added a commit that referenced this pull request Aug 13, 2026
…output (#157)

The fixture YAML is right, but three of its explanatory comments describe
behaviour the scanner does not produce, which would send the next person
working on #84 chasing a phantom:

- combo-role-writer was documented as producing NO per-role finding; its
  ClusterRoleBinding raises segmentation_violation like every other
  ClusterRoleBinding over a namespaced ServiceAccount.
- combo-escalate-gate was documented as privilege_escalation_verbs MEDIUM;
  the rule scores HIGH whenever the role is cluster-scoped, and MEDIUM only
  for a namespaced Role.
- The verify block said combo_role_escalation arrives once #84 lands.
  evaluate_combo_findings() already reports it today (#105/#131/#145) —
  what #84 adds is surfacing it through the per-role scan path.

Verified by running the scan and evaluate_combo_findings() against the
fixture. Follow-up to #152 (@Maqbool61).

Signed-off-by: Vamshi Krishna Santhapuri <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Combo predicates ignore api_groups (resource-name-only matching)

2 participants