Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cyclops): explain billing policy denials (#6842)

r33drichards5f403c9f1405
diff --git a/libs/fleet/backend/auth/policy_ast.go b/libs/fleet/backend/auth/policy_ast.go
index 6e5cce84f7..827348d3c0 100644
--- a/libs/fleet/backend/auth/policy_ast.go
+++ b/libs/fleet/backend/auth/policy_ast.go
@@ -35,6 +35,14 @@ type AnyNode struct{ Children []Node }
func (AnyNode) node() {}
+// BecauseNode associates one public denial reason with a policy subtree.
+type BecauseNode struct {
+ Child Node
+ Reason string
+}
+
+func (BecauseNode) node() {}
+
func All(children ...Node) Node {
if len(children) == 0 {
panic("OPA All requires at least one policy")
@@ -49,6 +57,16 @@ func Any(children ...Node) Node {
return AnyNode{Children: children}
}
+func Because(child Node, reason string) Node {
+ if child == nil {
+ panic("OPA Because requires a policy")
+ }
+ if reason == "" {
+ panic("OPA Because requires a denial reason")
+ }
+ return BecauseNode{Child: child, Reason: reason}
+}
+
// Policy builds a leaf. It performs no I/O and no compilation; both happen in
// Compile. It still panics on a missing query because that is a pure-data
// programming error detectable without touching the filesystem.
@@ -142,6 +160,9 @@ func explainInto(builder *strings.Builder, n Node, depth int) {
for _, child := range node.Children {
explainInto(builder, child, depth+1)
}
+ case BecauseNode:
+ fmt.Fprintf(builder, "%sBecause reason=%q\n", indent, node.Reason)
+ explainInto(builder, node.Child, depth+1)
default:
fmt.Fprintf(builder, "%s<unknown %T>\n", indent, n)
}
diff --git a/libs/fleet/backend/auth/policy_ast_test.go b/libs/fleet/backend/auth/policy_ast_test.go
index bec4283f24..58ec1720b5 100644
--- a/libs/fleet/backend/auth/policy_ast_test.go
+++ b/libs/fleet/backend/auth/policy_ast_test.go
@@ -258,3 +258,54 @@ func TestMultiSourceKeyIsInjective(t *testing.T) {
t.Fatalf("multi keys collide across different groupings: %q", left)
}
}
+
+func TestBecauseRejectsInvalidAnnotations(t *testing.T) {
+ deny := Policy(Inline("deny.rego", `package deny
+default allow = false
+`), Query("data.deny.allow"))
+
+ for _, testCase := range []struct {
+ name string
+ child Node
+ reason string
+ }{
+ {name: "nil child", reason: "denied"},
+ {name: "empty reason", child: deny},
+ } {
+ t.Run(testCase.name, func(t *testing.T) {
+ defer func() {
+ if recover() == nil {
+ t.Fatal("Because did not panic")
+ }
+ }()
+ Because(testCase.child, testCase.reason)
+ })
+ }
+}
+
+func TestCompileRejectsMalformedBecauseNode(t *testing.T) {
+ deny := Policy(Inline("deny.rego", `package deny
+default allow = false
+`), Query("data.deny.allow"))
+
+ for _, node := range []Node{
+ BecauseNode{Reason: "denied"},
+ BecauseNode{Child: deny},
+ } {
+ if _, err := Compile(node); err == nil {
+ t.Fatalf("Compile(%#v) succeeded", node)
+ }
+ }
+}
+
+func TestExplainRendersBecauseNode(t *testing.T) {
+ node := Because(
+ Policy(Registered("policy"), Query("data.policy.allow")),
+ "payment method required",
+ )
+ want := "Because reason=\"payment method required\"\n" +
+ " Leaf query=data.policy.allow source=registered:policy\n"
+ if got := Explain(node); got != want {
+ t.Fatalf("Explain output:\n%s\nwant:\n%s", got, want)
+ }
+}
diff --git a/libs/fleet/backend/auth/policy_card_admission_test.go b/libs/fleet/backend/auth/policy_card_admission_test.go
index 3876062661..b4a1acae44 100644
--- a/libs/fleet/backend/auth/policy_card_admission_test.go
+++ b/libs/fleet/backend/auth/policy_card_admission_test.go
@@ -83,6 +83,83 @@ func runK8sPolicy(t *testing.T, request *http.Request) (int, bool) {
return response.Code, reached
}
+func runK8sPolicyResponse(t *testing.T, request *http.Request) (*httptest.ResponseRecorder, bool) {
+ t.Helper()
+ surface, ok := surfacePolicies["k8s"]
+ if !ok {
+ t.Fatal("K8s surface is not configured")
+ }
+ options := append([]MiddlewareOption{}, surface.options...)
+ options = append(options, WithPipeline())
+
+ reached := false
+ handler := PolicyMiddleware(surface.tree(), options...)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ reached = true
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ response := httptest.NewRecorder()
+ handler.ServeHTTP(response, request)
+ return response, reached
+}
+
+func TestK8sCopyTestsUseProductionSurfaceDeniedMessage(t *testing.T) {
+ const want = "configured K8s denial"
+ previous := surfacePolicies["k8s"]
+ surface := previous
+ surface.options = []MiddlewareOption{WithDeniedMessage(want)}
+ surfacePolicies["k8s"] = surface
+ t.Cleanup(func() {
+ surfacePolicies["k8s"] = previous
+ })
+
+ setCardAdmissionFlags(t, false)
+ response, reached := runK8sPolicyResponse(t, cardAdmissionRequest(http.MethodGet, "api/v1/nodes", "user-1"))
+ if response.Code != http.StatusForbidden || reached {
+ t.Fatalf("status, reached = %d, %v; want %d, false", response.Code, reached, http.StatusForbidden)
+ }
+ if got := policyErrorMessage(t, response); got != want {
+ t.Fatalf("error = %q, want %q", got, want)
+ }
+}
+
+func TestK8sCardAdmissionReturnsBillingMessage(t *testing.T) {
+ setCardAdmissionFlags(t, true)
+ installAdmissionFacts(t, StripeCardsFactProvider, &countingAdmissionFacts{
+ cacheKey: StripeCardsFactProvider,
+ facts: FactSet{"cards": []map[string]any{}},
+ })
+ installAdmissionFacts(t, CurrentYearFactProvider, &countingAdmissionFacts{
+ cacheKey: CurrentYearFactProvider,
+ facts: FactSet{"current_year": 2026},
+ })
+ installAdmissionFacts(t, CurrentMonthFactProvider, &countingAdmissionFacts{
+ cacheKey: CurrentMonthFactProvider,
+ facts: FactSet{"current_month": 8},
+ })
+
+ const path = "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims"
+ response, reached := runK8sPolicyResponse(t, cardAdmissionRequest(http.MethodPost, path, "user-1"))
+ if response.Code != http.StatusForbidden || reached {
+ t.Fatalf("status, reached = %d, %v; want %d, false", response.Code, reached, http.StatusForbidden)
+ }
+ const want = "A payment method is required to create this resource. Add one in Billing and try again."
+ if got := policyErrorMessage(t, response); got != want {
+ t.Fatalf("error = %q, want %q", got, want)
+ }
+}
+
+func TestK8sUnrelatedDenialKeepsSurfaceMessage(t *testing.T) {
+ setCardAdmissionFlags(t, false)
+ const path = "api/v1/nodes"
+ response, reached := runK8sPolicyResponse(t, cardAdmissionRequest(http.MethodGet, path, "user-1"))
+ if response.Code != http.StatusForbidden || reached {
+ t.Fatalf("status, reached = %d, %v; want %d, false", response.Code, reached, http.StatusForbidden)
+ }
+ if got := policyErrorMessage(t, response); got != "k8s request is not allowed" {
+ t.Fatalf("error = %q, want %q", got, "k8s request is not allowed")
+ }
+}
+
func TestK8sCardAdmissionLazyTruthTable(t *testing.T) {
const createPath = "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims"
const readPath = "apis/osgym.cua.ai/v1alpha1/namespaces/ns-a/osgymsandboxclaims/claim-a"
diff --git a/libs/fleet/backend/auth/policy_cost.go b/libs/fleet/backend/auth/policy_cost.go
index f89dffcdd6..40f808b6d4 100644
--- a/libs/fleet/backend/auth/policy_cost.go
+++ b/libs/fleet/backend/auth/policy_cost.go
@@ -215,6 +215,9 @@ func sinkNode(n Node, model costModel) (Node, cost) {
case AnyNode:
children, lowest := sinkChildren(node.Children, model)
return AnyNode{Children: children}, lowest
+ case BecauseNode:
+ child, childCost := sinkNode(node.Child, model)
+ return BecauseNode{Child: child, Reason: node.Reason}, childCost
}
// An unknown node kind is not something to guess a cost for. cost{} is the
// cheapest value, so it sorts first and is evaluated first — and Compile
diff --git a/libs/fleet/backend/auth/policy_fuzz_test.go b/libs/fleet/backend/auth/policy_fuzz_test.go
index d3d3baef63..0117def9be 100644
--- a/libs/fleet/backend/auth/policy_fuzz_test.go
+++ b/libs/fleet/backend/auth/policy_fuzz_test.go
@@ -215,6 +215,8 @@ func siblingLeafPairs(n Node) [][2]Leaf {
children = node.Children
case AnyNode:
children = node.Children
+ case BecauseNode:
+ return siblingLeafPairs(node.Child)
default:
return nil
}
diff --git a/libs/fleet/backend/auth/policy_middleware.go b/libs/fleet/backend/auth/policy_middleware.go
index 80e6b2713a..f53be72faa 100644
--- a/libs/fleet/backend/auth/policy_middleware.go
+++ b/libs/fleet/backend/auth/policy_middleware.go
@@ -439,7 +439,11 @@ func PolicyMiddleware(expression Node, options ...MiddlewareOption) Middleware {
case truthTrue:
next.ServeHTTP(w, request)
case truthFalse:
- writeJSONErr(w, http.StatusForbidden, config.deniedMessage)
+ message := verdict.reason
+ if message == "" {
+ message = config.deniedMessage
+ }
+ writeJSONErr(w, http.StatusForbidden, message)
default:
// truthError, and deliberately also any truth value a future
// change adds: an undecidable policy must fail closed rather
diff --git a/libs/fleet/backend/auth/policy_middleware_test.go b/libs/fleet/backend/auth/policy_middleware_test.go
index a6b6cbad21..e696d2627e 100644
--- a/libs/fleet/backend/auth/policy_middleware_test.go
+++ b/libs/fleet/backend/auth/policy_middleware_test.go
@@ -3,6 +3,7 @@ package auth
import (
"bytes"
"context"
+ "encoding/json"
"errors"
"fmt"
"io"
@@ -830,3 +831,116 @@ allow {
t.Fatalf("provider loads = year:%d month:%d, want 1 each", year.loads, month.loads)
}
}
+
+func policyErrorMessage(t *testing.T, response *httptest.ResponseRecorder) string {
+ t.Helper()
+ var body struct {
+ Error string `json:"error"`
+ }
+ if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
+ t.Fatalf("decode response: %v; body = %q", err, response.Body.String())
+ }
+ return body.Error
+}
+
+func TestPolicyMiddlewareUsesAnnotatedDenialReason(t *testing.T) {
+ deny := Policy(Inline("deny-reason.rego", `package deny_reason
+default allow = false
+`), Query("data.deny_reason.allow"))
+ handler := PolicyMiddleware(
+ Because(deny, "specific denial"),
+ WithDeniedMessage("fallback denial"),
+ )(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ t.Fatal("denied request reached downstream handler")
+ }))
+ response := httptest.NewRecorder()
+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))
+
+ if response.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want %d", response.Code, http.StatusForbidden)
+ }
+ if got := policyErrorMessage(t, response); got != "specific denial" {
+ t.Fatalf("error = %q, want %q", got, "specific denial")
+ }
+}
+
+func TestAllStopsAfterAnnotatedDenial(t *testing.T) {
+ deny := Policy(Inline("deny-short-circuit.rego", `package deny_short_circuit
+default allow = false
+`), Query("data.deny_short_circuit.allow"))
+ provider := &testFactProvider{cacheKey: "reason-must-not-load", facts: FactSet{"allowed": true}}
+ expensive := Policy(Inline("reason-must-not-load.rego", `package reason_must_not_load
+allow { input.facts.user.allowed }
+`), Query("data.reason_must_not_load.allow"), WithFacts("user", provider))
+ handler := PolicyMiddleware(All(Because(deny, "stop here"), expensive), WithPipeline())(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ t.Fatal("denied request reached downstream handler")
+ }))
+ response := httptest.NewRecorder()
+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))
+
+ if got := policyErrorMessage(t, response); got != "stop here" {
+ t.Fatalf("error = %q, want %q", got, "stop here")
+ }
+ if provider.loads != 0 {
+ t.Fatalf("later fact provider loaded %d times, want 0", provider.loads)
+ }
+}
+
+func TestPolicyMiddlewareFallsBackForUnannotatedDenial(t *testing.T) {
+ deny := Policy(Inline("deny-fallback.rego", `package deny_fallback
+default allow = false
+`), Query("data.deny_fallback.allow"))
+ handler := PolicyMiddleware(deny, WithDeniedMessage("fallback denial"))(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ t.Fatal("denied request reached downstream handler")
+ }))
+ response := httptest.NewRecorder()
+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))
+
+ if got := policyErrorMessage(t, response); got != "fallback denial" {
+ t.Fatalf("error = %q, want %q", got, "fallback denial")
+ }
+}
+
+func TestBecauseReasonComposition(t *testing.T) {
+ allow := Policy(Inline("reason-allow.rego", `package reason_allow
+allow { true }
+`), Query("data.reason_allow.allow"))
+ deny := Policy(Inline("reason-deny.rego", `package reason_deny
+default allow = false
+`), Query("data.reason_deny.allow"))
+ brokenProvider := &testFactProvider{cacheKey: "reason-error", err: errors.New("dependency unavailable")}
+ broken := Policy(Inline("reason-error.rego", `package reason_error
+allow { input.facts.user.allowed }
+`), Query("data.reason_error.allow"), WithFacts("user", brokenProvider))
+
+ cases := []struct {
+ name string
+ expression Node
+ wantStatus int
+ wantError string
+ }{
+ {name: "all propagates denying child", expression: All(allow, Because(deny, "all denial")), wantStatus: http.StatusForbidden, wantError: "all denial"},
+ {name: "any remembers first reason when all deny", expression: Any(Because(deny, "first denial"), Because(deny, "second denial")), wantStatus: http.StatusForbidden, wantError: "first denial"},
+ {name: "outer annotation replaces inner reason", expression: Because(Because(deny, "inner denial"), "outer denial"), wantStatus: http.StatusForbidden, wantError: "outer denial"},
+ {name: "allow discards remembered reason", expression: Any(Because(deny, "must disappear"), allow), wantStatus: http.StatusNoContent},
+ {name: "error discards remembered reason", expression: Any(Because(deny, "must disappear"), broken), wantStatus: http.StatusInternalServerError, wantError: "policy evaluation failed"},
+ }
+
+ for _, testCase := range cases {
+ t.Run(testCase.name, func(t *testing.T) {
+ handler := PolicyMiddleware(testCase.expression, WithPipeline(), WithDeniedMessage("fallback denial"))(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ response := httptest.NewRecorder()
+ handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))
+ if response.Code != testCase.wantStatus {
+ t.Fatalf("status = %d, want %d; body = %s", response.Code, testCase.wantStatus, response.Body.String())
+ }
+ if testCase.wantError != "" {
+ if got := policyErrorMessage(t, response); got != testCase.wantError {
+ t.Fatalf("error = %q, want %q", got, testCase.wantError)
+ }
+ }
+ })
+ }
+}
diff --git a/libs/fleet/backend/auth/policy_optimize.go b/libs/fleet/backend/auth/policy_optimize.go
index 65aa5c6b2c..2addccfe8d 100644
--- a/libs/fleet/backend/auth/policy_optimize.go
+++ b/libs/fleet/backend/auth/policy_optimize.go
@@ -123,6 +123,8 @@ func mapChildren(n Node, rewrite func(Node) Node) Node {
return AllNode{Children: rewriteChildren(node.Children, rewrite)}
case AnyNode:
return AnyNode{Children: rewriteChildren(node.Children, rewrite)}
+ case BecauseNode:
+ return BecauseNode{Child: rewrite(node.Child), Reason: node.Reason}
}
return n
}
diff --git a/libs/fleet/backend/auth/policy_optimize_test.go b/libs/fleet/backend/auth/policy_optimize_test.go
index 888d1d5af1..16b3492373 100644
--- a/libs/fleet/backend/auth/policy_optimize_test.go
+++ b/libs/fleet/backend/auth/policy_optimize_test.go
@@ -133,6 +133,8 @@ func emptyCompositeIn(n Node) Node {
children = node.Children
case AnyNode:
children = node.Children
+ case BecauseNode:
+ return emptyCompositeIn(node.Child)
default:
return nil
}
@@ -147,6 +149,14 @@ func emptyCompositeIn(n Node) Node {
return nil
}
+func TestEmptyCompositeInFindsAnnotatedChild(t *testing.T) {
+ got := emptyCompositeIn(Because(AllNode{}, "payment method required"))
+ empty, ok := got.(AllNode)
+ if !ok || len(empty.Children) != 0 {
+ t.Fatalf("emptyCompositeIn = %#v, want empty AllNode", got)
+ }
+}
+
func childrenOf(t *testing.T, n Node) []Node {
t.Helper()
switch node := n.(type) {
@@ -164,6 +174,87 @@ func childrenOf(t *testing.T, n Node) []Node {
// Flatten
// ---------------------------------------------------------------------------
+func TestOptimizersPreserveBecauseAnnotations(t *testing.T) {
+ t.Run("flatten rewrites the annotated child", func(t *testing.T) {
+ got := Optimize(Because(All(allowLeaf("a"), All(allowLeaf("b"), allowLeaf("c"))), "payment method required"), []string{"flatten"})
+
+ because, ok := got.(BecauseNode)
+ if !ok || because.Reason != "payment method required" {
+ t.Fatalf("flatten = %#v, want payment-method annotation", got)
+ }
+ if want := Explain(All(allowLeaf("a"), allowLeaf("b"), allowLeaf("c"))); Explain(because.Child) != want {
+ t.Fatalf("flattened child:\n%s\nwant:\n%s", Explain(because.Child), want)
+ }
+ })
+
+ t.Run("collapse keeps annotations with different reasons nested", func(t *testing.T) {
+ got := Optimize(Because(Because(All(allowLeaf("a")), "account inactive"), "payment method required"), []string{"collapse"})
+
+ outer, ok := got.(BecauseNode)
+ if !ok || outer.Reason != "payment method required" {
+ t.Fatalf("collapse outer = %#v, want payment-method annotation", got)
+ }
+ inner, ok := outer.Child.(BecauseNode)
+ if !ok || inner.Reason != "account inactive" {
+ t.Fatalf("collapse child = %#v, want nested account annotation", outer.Child)
+ }
+ if want := Explain(allowLeaf("a")); Explain(inner.Child) != want {
+ t.Fatalf("collapsed child:\n%s\nwant:\n%s", Explain(inner.Child), want)
+ }
+ })
+
+ t.Run("dedupe keeps annotated siblings with different reasons", func(t *testing.T) {
+ got := Optimize(All(Because(allowLeaf("a"), "account inactive"), Because(allowLeaf("a"), "payment method required")), []string{"dedupe"})
+
+ children := childrenOf(t, got)
+ if len(children) != 2 {
+ t.Fatalf("dedupe children = %d, want 2\n%s", len(children), Explain(got))
+ }
+ for index, wantReason := range []string{"account inactive", "payment method required"} {
+ because, ok := children[index].(BecauseNode)
+ if !ok || because.Reason != wantReason {
+ t.Fatalf("dedupe child %d = %#v, want annotation %q", index, children[index], wantReason)
+ }
+ if want := Explain(allowLeaf("a")); Explain(because.Child) != want {
+ t.Fatalf("dedupe child %d policy:\n%s\nwant:\n%s", index, Explain(because.Child), want)
+ }
+ }
+ })
+}
+
+func TestSinkFactsPricesBecauseByItsChild(t *testing.T) {
+ annotatedFacts := Because(
+ All(
+ factLeaf("annotated-facts", &testFactProvider{cacheKey: "annotated-facts"}),
+ allowLeaf("annotated-pure"),
+ ),
+ "fact denial",
+ )
+ got := Optimize(All(factLeaf("sibling-facts", &testFactProvider{cacheKey: "sibling-facts"}), annotatedFacts), []string{"sink-facts"})
+
+ all := got.(AllNode)
+ because, ok := all.Children[0].(BecauseNode)
+ if !ok {
+ t.Fatalf("first child = %T, want BecauseNode\n%s", all.Children[0], Explain(got))
+ }
+ if because.Reason != "fact denial" {
+ t.Fatalf("reason = %q, want fact denial", because.Reason)
+ }
+ annotatedChild, ok := because.Child.(AllNode)
+ if !ok {
+ t.Fatalf("annotated child = %T, want AllNode\n%s", because.Child, Explain(got))
+ }
+ if query := annotatedChild.Children[0].(Leaf).Query; query != "data.annotated-pure.allow" {
+ t.Fatalf("first annotated query = %q, want data.annotated-pure.allow\n%s", query, Explain(got))
+ }
+ if query := annotatedChild.Children[1].(Leaf).Query; query != "data.annotated-facts.allow" {
+ t.Fatalf("second annotated query = %q, want data.annotated-facts.allow\n%s", query, Explain(got))
+ }
+ if query := all.Children[1].(Leaf).Query; query != "data.sibling-facts.allow" {
+ t.Fatalf("second parent query = %q, want data.sibling-facts.allow\n%s", query, Explain(got))
+ }
+}
+
func TestFlattenCollapsesNestedSameKindNodes(t *testing.T) {
node := All(allowLeaf("a"), All(allowLeaf("b"), allowLeaf("c")))
got := Optimize(node, []string{"flatten"})
diff --git a/libs/fleet/backend/auth/policy_ownership_test.go b/libs/fleet/backend/auth/policy_ownership_test.go
index 7da145c963..cfd44308b3 100644
--- a/libs/fleet/backend/auth/policy_ownership_test.go
+++ b/libs/fleet/backend/auth/policy_ownership_test.go
@@ -297,6 +297,8 @@ func reverseChildren(n Node) Node {
return AllNode{Children: reverse(node.Children)}
case AnyNode:
return AnyNode{Children: reverse(node.Children)}
+ case BecauseNode:
+ return BecauseNode{Child: reverseChildren(node.Child), Reason: node.Reason}
default:
return n
}
@@ -470,6 +472,8 @@ func allLeaves(n Node) []Leaf {
leaves = append(leaves, allLeaves(child)...)
}
return leaves
+ case BecauseNode:
+ return allLeaves(node.Child)
}
return nil
}
diff --git a/libs/fleet/backend/auth/policy_plan.go b/libs/fleet/backend/auth/policy_plan.go
index dab6053e5c..4187b77ee9 100644
--- a/libs/fleet/backend/auth/policy_plan.go
+++ b/libs/fleet/backend/auth/policy_plan.go
@@ -46,8 +46,9 @@ const (
// verdict is the result of evaluating a policy against one request.
type verdict struct {
- truth truth
- err error // non-nil if and only if truth == truthError
+ truth truth
+ err error // non-nil if and only if truth == truthError
+ reason string // non-empty only when truth == truthFalse
}
// A combinator is a fold over truth: All is min, Any is max. annihilator must
@@ -121,6 +122,18 @@ func compileNode(n Node) (compiledNode, error) {
return nil, err
}
return &compiledAny{children: children}, nil
+ case BecauseNode:
+ if node.Child == nil {
+ return nil, fmt.Errorf("policy reason %q has no child", node.Reason)
+ }
+ if node.Reason == "" {
+ return nil, fmt.Errorf("policy reason is empty")
+ }
+ child, err := compileNode(node.Child)
+ if err != nil {
+ return nil, err
+ }
+ return &compiledBecause{child: child, reason: node.Reason}, nil
default:
return nil, fmt.Errorf("cannot compile unknown policy node %T", n)
}
@@ -197,6 +210,23 @@ func (leaf *compiledLeaf) eval(ctx context.Context, input *requestPolicyInput) v
func (leaf *compiledLeaf) bodyBudget() int64 { return leaf.config.maxBodyBytes }
+type compiledBecause struct {
+ child compiledNode
+ reason string
+}
+
+func (node *compiledBecause) eval(ctx context.Context, input *requestPolicyInput) verdict {
+ result := node.child.eval(ctx, input)
+ if result.truth == truthFalse {
+ result.reason = node.reason
+ return result
+ }
+ result.reason = ""
+ return result
+}
+
+func (node *compiledBecause) bodyBudget() int64 { return node.child.bodyBudget() }
+
type compiledAll struct{ children []compiledNode }
func (node *compiledAll) eval(ctx context.Context, input *requestPolicyInput) verdict {
@@ -218,6 +248,7 @@ func (node *compiledAny) bodyBudget() int64 { return maxChildBudget(node.childre
// annihilator can still win — that is what makes the fold order-independent.
func fold(ctx context.Context, input *requestPolicyInput, children []compiledNode, over combinator) verdict {
var errs []error
+ var reason string
for _, child := range children {
result := child.eval(ctx, input)
switch result.truth {
@@ -230,13 +261,17 @@ func fold(ctx context.Context, input *requestPolicyInput, children []compiledNod
slog.Warn("opa: policy error discarded; a sibling decided the verdict",
"allowed", over.annihilator == truthTrue, "err", errors.Join(errs...))
}
- return verdict{truth: over.annihilator}
+ return verdict{truth: over.annihilator, reason: result.reason}
case truthError:
errs = append(errs, result.err)
+ case truthFalse:
+ if reason == "" {
+ reason = result.reason
+ }
}
}
if len(errs) > 0 {
return verdict{truth: truthError, err: errors.Join(errs...)}
}
- return verdict{truth: over.identity}
+ return verdict{truth: over.identity, reason: reason}
}
diff --git a/libs/fleet/backend/auth/policy_routes.go b/libs/fleet/backend/auth/policy_routes.go
index 877fa32bc8..3155042c1a 100644
--- a/libs/fleet/backend/auth/policy_routes.go
+++ b/libs/fleet/backend/auth/policy_routes.go
@@ -173,6 +173,8 @@ func StateQueryRoutePolicy() Node {
return All(BasePolicy(), surfaceLeaf("authz-state-query", "data.authz_state_query.allow"))
}
+const billingSetupRequiredMessage = "A payment method is required to create this resource. Add one in Billing and try again."
+
// K8sRoutePolicy guards /api/k8s/{path...}. It is the same base + surface shape
// as every other route, with two admission conjuncts: card-or-admin admission
// for custom-resource creation, and pool admission over the request body.
@@ -209,7 +211,7 @@ func K8sRoutePolicy() Node {
return All(
BasePolicy(),
surfaceLeaf("authz-k8s", "data.authz_k8s.allow"),
- CustomResourceCreationAdmissionPolicy(),
+ Because(CustomResourceCreationAdmissionPolicy(), billingSetupRequiredMessage),
Policy(
Modules(
Registered("authz"),
diff --git a/libs/fleet/backend/auth/policy_test.go b/libs/fleet/backend/auth/policy_test.go
index e141aeb997..4e467422d2 100644
--- a/libs/fleet/backend/auth/policy_test.go
+++ b/libs/fleet/backend/auth/policy_test.go
@@ -125,6 +125,8 @@ func evalPolicyNode(t *testing.T, node Node, input map[string]any) bool {
}
}
return true
+ case BecauseNode:
+ return evalPolicyNode(t, policy.Child, input)
case AnyNode:
for _, child := range policy.Children {
if evalPolicyNode(t, child, input) {
diff --git a/libs/fleet/backend/auth/testdata/k8s-route-plan.txt b/libs/fleet/backend/auth/testdata/k8s-route-plan.txt
index eff10236e9..939bb73851 100644
--- a/libs/fleet/backend/auth/testdata/k8s-route-plan.txt
+++ b/libs/fleet/backend/auth/testdata/k8s-route-plan.txt
@@ -1,7 +1,8 @@
All
Leaf query=data.authz_base.allow source=registered:authz-base
Leaf query=data.authz_k8s.allow source=multi["registered:authz","registered:authz-k8s"]
- Any
- Leaf query=data.custom_resource_creation_admission.exempt source=multi["registered:authz","registered:custom-resource-creation-admission"]
- Leaf query=data.custom_resource_creation_admission.billing_eligible source=multi["registered:authz","registered:custom-resource-creation-admission"] facts=stripe_cards@registered-facts:stripe-cards facts=time@registered-facts:current-year facts=time@registered-facts:current-month
+ Because reason="A payment method is required to create this resource. Add one in Billing and try again."
+ Any
+ Leaf query=data.custom_resource_creation_admission.exempt source=multi["registered:authz","registered:custom-resource-creation-admission"]
+ Leaf query=data.custom_resource_creation_admission.billing_eligible source=multi["registered:authz","registered:custom-resource-creation-admission"] facts=stripe_cards@registered-facts:stripe-cards facts=time@registered-facts:current-year facts=time@registered-facts:current-month
Leaf query=data.pool_admission.allow source=multi["registered:authz","registered:pool-admission"] body=1048576