Spaces:
Running

File size: 9,877 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
"""The rule AST, its deterministic Cedar and plain-language renderings, and rule tests.



The planner model never writes Cedar. It fills ``RuleAST`` (a closed vocabulary: three

effects, six comparison operators, known tools and known arguments only), the AST is

validated against the live tool catalog, and Cedar is *rendered* from it by code.



Effects and how the gateway's policy engine treats them:



* ``require_approval`` -> ``forbid`` annotated ``@id("review.…")``: a matching call is not

  denied but held for a human (``core.gateway.policy``: review-only forbids -> REVIEW);

* ``forbid`` -> plain ``forbid``: a matching call is denied, even with approval;

* ``permit`` -> ``permit``: a matching call to a tool of tier T2 or lower runs without

  approval. Only by explicit owner choice, and never for T3 (the engine keeps T3 in review).



``require_approval`` and ``forbid`` can only tighten (Cedar: forbid always wins).

"""

from __future__ import annotations

import itertools
import re
from dataclasses import dataclass, field
from typing import Any, Literal

import cedarpy
from pydantic import BaseModel, Field

from core.gateway.policy import REVIEW_PREFIX

Op = Literal["gt", "ge", "lt", "le", "eq", "ne"]
OPS = {"gt": ">", "ge": ">=", "lt": "<", "le": "<=", "eq": "==", "ne": "!="}
WORDS = {
    "gt": "is more than",
    "ge": "is at least",
    "lt": "is less than",
    "le": "is at most",
    "eq": "is",
    "ne": "is not",
}
NUMERIC = ("integer", "number")
_STR_VALUE = re.compile(r"^[\w .@:/+#,-]{0,100}$", re.UNICODE)
_ARG = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
_TOOL = re.compile(r"^[A-Za-z0-9_.:-]{1,200}$")


class Condition(BaseModel):
    arg: str = Field(description="argument name of the tool, exactly as listed")
    op: Op
    value: bool | int | str = Field(description="whole numbers for amounts (10k = 10000)")


class RuleAST(BaseModel):
    effect: Literal["require_approval", "forbid", "permit"]
    tools: list[str] = Field(min_length=1, max_length=10, description="tool names, as listed")
    conditions: list[Condition] = Field(default_factory=list, max_length=5)
    principal: Literal["any", "agent", "user"] = Field(
        default="any", description="agent = the AI agent, user = a human operator"
    )


class RuleDraft(BaseModel):
    """What the planner model returns."""

    understood: bool
    rule: RuleAST | None = None
    question: str | None = Field(default=None, description="clarifying question if not")


@dataclass(frozen=True)
class ToolInfo:
    name: str
    description: str
    tier: int
    args: dict[str, str] = field(default_factory=dict)  # field name -> json type


Catalog = dict[str, ToolInfo]


def validate_rule(rule: RuleAST, catalog: Catalog) -> list[str]:
    errors: list[str] = []
    for t in rule.tools:
        if t not in catalog or not _TOOL.match(t):
            errors.append(f"unknown tool {t!r}")
    if len(set(rule.tools)) != len(rule.tools):
        errors.append("a tool is listed twice")
    for c in rule.conditions:
        if not _ARG.match(c.arg):
            errors.append(f"invalid argument name {c.arg!r}")
            continue
        for t in rule.tools:
            info = catalog.get(t)
            if info is None:
                continue
            kind = info.args.get(c.arg)
            if kind is None:
                errors.append(f"tool {t} has no argument {c.arg!r}")
            elif c.op in ("gt", "ge", "lt", "le"):
                if kind not in NUMERIC or isinstance(c.value, bool) or not isinstance(c.value, int):
                    errors.append(f"{c.arg} on {t}: '{c.op}' needs a numeric argument and value")
            elif kind == "boolean" and not isinstance(c.value, bool):
                errors.append(f"{c.arg} on {t} is yes/no; the value must be true or false")
            elif kind == "string" and not isinstance(c.value, str):
                errors.append(f"{c.arg} on {t} is text; the value must be text")
            elif kind in NUMERIC and (isinstance(c.value, bool) or not isinstance(c.value, int)):
                errors.append(f"{c.arg} on {t} is a number; the value must be a whole number")
        if isinstance(c.value, str) and not _STR_VALUE.match(c.value):
            errors.append(f"value for {c.arg} has unsupported characters")
    if rule.effect == "permit":
        for t in rule.tools:
            info = catalog.get(t)
            if info is not None and info.tier >= 3:
                errors.append(f"{t} is tier T3: it always needs a human and cannot be permitted")
    return errors


def _literal(value: bool | int | str) -> str:
    if isinstance(value, bool):
        return "true" if value else "false"
    if isinstance(value, int):
        return str(value)
    return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'


def policy_id(rule: RuleAST, rule_id: str) -> str:
    kind = {
        "require_approval": f"{REVIEW_PREFIX}rule",
        "forbid": "forbid.rule",
        "permit": "permit.rule",
    }
    return f"{kind[rule.effect]}.{rule_id}"


def render_cedar(rule: RuleAST, rule_id: str) -> str:
    actions = ", ".join(f'Action::"{t}"' for t in rule.tools)
    conds = [
        f"(context.args has {c.arg} && context.args.{c.arg} {OPS[c.op]} {_literal(c.value)})"
        for c in rule.conditions
    ]
    if rule.principal != "any":
        conds.insert(0, f'principal.kind == "{rule.principal}"')
    effect = "permit" if rule.effect == "permit" else "forbid"
    when = f"\nwhen {{ {' && '.join(conds)} }}" if conds else ""
    return (
        f'@id("{policy_id(rule, rule_id)}")\n'
        f"{effect} (principal, action in [{actions}], resource){when};"
    )


def _value_text(v: bool | int | str) -> str:
    if isinstance(v, bool):
        return "yes" if v else "no"
    if isinstance(v, int):
        return f"{v:,}"
    return f'"{v}"'


def render_plain(rule: RuleAST) -> str:
    who = {"any": "", "agent": " made by the AI agent", "user": " made by a team member"}
    tools = ", ".join(rule.tools)
    where = " and ".join(f"{c.arg} {WORDS[c.op]} {_value_text(c.value)}" for c in rule.conditions)
    scope = f"Calls to {tools}{who[rule.principal]}" + (f" where {where}" if where else "")
    then = {
        "require_approval": "need your approval before they run.",
        "forbid": "are blocked, even with approval.",
        "permit": "may run automatically without approval (unless another rule blocks them).",
    }
    return f"{scope} {then[rule.effect]}"


def check_syntax(cedar: str) -> None:
    """Raises ``ValueError`` if Cedar cannot parse the text."""
    cedarpy.policies_to_json_str(cedar)


# -------------------------------------------------------------------------- tests


def _just(c: Condition, satisfy: bool) -> bool | int | str:
    v = c.value
    if isinstance(v, bool):
        return v if (c.op == "eq") == satisfy else (not v)
    if isinstance(v, int):
        inside = {"gt": v + 1, "ge": v, "lt": v - 1, "le": v, "eq": v, "ne": v + 1}
        outside = {"gt": v, "ge": v - 1, "lt": v, "le": v + 1, "eq": v + 1, "ne": v}
        return inside[c.op] if satisfy else outside[c.op]
    other = f"{v}_other" if v else "other"
    if c.op == "eq":
        return v if satisfy else other
    return other if satisfy else v


def sample_calls(rule: RuleAST) -> list[dict[str, Any]]:
    """Boundary samples: one that matches every condition, one per condition that misses it,

    for the first tool; both principals when the rule names one."""
    tool = rule.tools[0]
    actors = ["agent", "user"] if rule.principal != "any" else ["agent"]
    out: list[dict[str, Any]] = []
    for actor, miss in itertools.product(actors, [None, *range(len(rule.conditions))]):
        if actor != actors[0] and miss is not None:
            continue
        args = {c.arg: _just(c, i != miss) for i, c in enumerate(rule.conditions)}
        out.append({"tool": tool, "args": args, "actor": actor})
    return out


def evaluate_samples(

    rule: RuleAST, cedar: str, samples: list[dict[str, Any]]

) -> list[dict[str, Any]]:
    """Evaluate the rule *alone* against sample calls: does it match, and what happens then."""
    base = "" if rule.effect == "permit" else "\npermit (principal, action, resource);"
    effect = {
        "require_approval": "needs approval",
        "forbid": "blocked",
        "permit": "runs automatically",
    }[rule.effect]
    results = []
    for sample in samples:
        actor = str(sample.get("actor") or "agent")
        kind = "user" if actor == "user" else "agent"
        ptype = "User" if kind == "user" else "Agent"
        args = {k: v for k, v in (sample.get("args") or {}).items() if v is not None}
        request = {
            "principal": f'{ptype}::"sample"',
            "action": f'Action::"{sample["tool"]}"',
            "resource": 'Tenant::"sample"',
            "context": {"args": args},
        }
        entities = [
            {"uid": {"type": ptype, "id": "sample"}, "attrs": {"kind": kind}, "parents": []}
        ]
        r = cedarpy.is_authorized(request, cedar + base, entities)
        errors = [str(e) for e in r.diagnostics.errors]
        allowed = r.decision == cedarpy.Decision.Allow
        matched = allowed if rule.effect == "permit" else not allowed
        results.append(
            {
                "tool": sample["tool"],
                "args": args,
                "actor": kind,
                "matched": matched and not errors,
                "outcome": effect if matched and not errors else "not affected by this rule",
                "errors": errors,
            }
        )
    return results