Access policies as code

阅读约需 84分钟 分钟,11节中含13个示例。

版次 2026.11.31 示例于 2026年11月19日 通过 108个示例中有108个通过 变化内容

AI 翻译。由人工以英文核验。 我们如何制作图书

译自英文版图书,版次 2026.11.31。 阅读原文

这部分尚未翻译,因此以英文显示。

By the end of this chapter you can write a data platform's access rules as one policy that denies by default and returns row filters and column masks as data. The policy allows by role and narrows by attribute, and an engine can apply its whole decision. You'll write it in Rego, the policy language of Open Policy Agent (OPA), test it the way opa test, OPA's test runner, does, check it against a who-sees-what table that the data's owners can read, know where the in-process engine this book uses differs from OPA, and see the same rules in Cedar, a narrower policy language.

Each group that reads the platform's warehouse, from support agents to its course assistant, needs something different. Support agents each serve one region, americas, emea or apac, and need learners' contact details to answer tickets. Instructors see the learners and reviews of their own courses, without contact details. Marketing may reach only learners who agreed to marketing email. Finance reconciles payments, and the legacy card_number column of billing.payments must never show more than its last four digits. Data scientists see learner_id as stored, to join tables on it, with personal columns pseudonymized and free text redacted. The course assistant reads only the reviews whose authors agreed to AI training. Chapter 1 showed one rule, support agents see only their own region, and enforced it on one query. Rules for every group need to live in one place, stated exactly, and tested before anyone relies on them.

This chapter's terms are the ones the rest of the book uses. A policy is code that answers whether a request may go ahead. A decision is a policy's answer. The principal is who asks, a role is a group of principals with the same job, and an attribute is any other fact a rule reads, about the principal, the data or the request. A row filter limits which rows a query returns, and a column mask changes how a column's values are shown, such as pseudonymization, which replaces an identifier with a consistent stand-in.

The platform's policy is governance/policies/access.rego, and its tests are in governance/policies/access_test.rego. The book's shared module lib.policy loads both into regopy 1.5.2, the Python binding of rego-cpp, Microsoft's C++ implementation of Rego, which evaluates policies inside the Python process with no server to run.

让请求的形状与 Trino 一致

最近一次修改见于版次 2026.11.27

策略引擎回答的是关于请求的问题,因此请求的形状决定了哪些系统可以向它发问。OPA 的前提是把策略从执行策略的服务中分离出来:OPA“让你把策略与该软件服务解耦”,这样策略就可以独立地阅读、版本管理和测试(OPA 理念)。服务发送一份描述请求的 JSON 文档,策略则以 input 的形式读取它。开源 SQL 引擎 Trino 正是这样做的:查询所需的每一次访问检查,其 OPA 插件都会发送一份文档,其中 context.identity 给出用户及其所属的组,action 给出操作和资源,资源细化到目录、模式、表和列(Trino 484,OPA 访问控制)。

平台的策略读取相同的字段,因此能够按 Trino 发送的原样,对 Trino 读取列的请求 SelectFromColumns 作出决定。但 Trino 需要的不止这一项决定。它还要求把每个行过滤器和列掩码以 SQL 的形式给出,其中行过滤器的形式为 {"expression": "clause"},由策略返回一个列和一个值(Trino 484,OPA 访问控制)。它还会询问其他检查,例如 ExecuteQuery 和 AccessCatalog,而这份策略的 allow 会拒绝这些检查(Trino 484 中的 OpaAccessControl.java)。第 6 章说明了与策略并列的模块必须为这些检查返回什么。lib.policy.request 按 Trino 的形状构建平台的请求,下面的示例用它为一个 emea 的支持代理 agent-a05 构建请求,该代理读取 support.tickets 的三个列:

trino-shaped-request.py Python 3.12.15 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 通过
"""The request a support agent's read sends the policy, shaped as Trino's OPA plugin sends it. The point rests on the printed `action`: the operation SelectFromColumns, and the table with the columns the query reads."""import jsonfrom lib import policy# A support agent's query reads three columns of the tickets table: the request Trino's OPA plugin would send for it.# no groups here, because the policy reads them from users.toml; no purpose either, since request adds one only when givenrequest = policy.request("agent-a05", "support.tickets", ["ticket_id", "opened_at", "body"])print(json.dumps(request, indent=2))
输出python trino-shaped-request.py
{
  "context": {
    "identity": {
      "user": "agent-a05"
    }
  },
  "action": {
    "operation": "SelectFromColumns",
    "resource": {
      "table": {
        "catalogName": "platform",
        "schemaName": "support",
        "tableName": "tickets",
        "columns": [
          "ticket_id",
          "opened_at",
          "body"
        ]
      }
    }
  }
}

操作是 SelectFromColumns,即 Trino 对读取操作的称呼,表位于 action.resource.table 之下,带有其目录、模式、名称以及查询涉及的列。平台的请求与 Trino 的请求有两处重要差异。第一,它省略了 context.identity.groups,因为策略会在存放用户属性的同一个文件 governance/users.toml 中查找用户所属的组,这样测试和策略读取的是同一个事实来源。第二,它可以带有一个顶层的 purpose(例如 ai-training),而 Trino 不会发送这个字段。在 Trino 背后使用时,我们建议从身份推导出用途,例如为训练流水线单独设置一个服务用户,而不是信任客户端设置的值。

工作准则: 让策略的输入与将要执行它的引擎的请求保持一致,逐字段对应,并且只添加该引擎无法发送的内容,把它放在顶层,以便审阅者能看到。如果你的引擎不是 Trino,就从该引擎的请求格式出发,并像 lib.policy.request 那样把这种形状集中在一个函数里,使测试和调用方不会各行其是。

生成策略所读取的数据

最近一次修改见于版次 2026.11.31

请求说明了谁在请求什么。除请求之外,规则所需的其他一切,例如每个用户所属的组和每一列的分类,都来自第二份文档,OPA 称之为 data。该文档中的一条事实,其时效性只取决于它的来源,而平台策略所读取的每一条事实本来就有其所有者。用户及其属性保存在 governance/users.toml 中。每一列的分类保存在 governance/metadata.toml 中,这是经过评审的元数据文件,第 2 章按 Iceberg 字段 ID 为其建立键。至于哪位讲师教授哪门课程,则记录在 learning.courses 表本身之中。把其中任何一项直接写进策略,或复制到第二个文件里,都会产生一份副本,而总得有人记得去更新它。

lib.policy.data_document 在每次加载策略时,从这三个来源构建该文档,绝不依赖任何手工键入的内容:

generated-policy-data.py Python 3.12.15 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 通过
"""The data the policy reads besides the request, built from the files that own each fact. The point rests on the last two lines: instructor 17's courses come from learning.courses, not from anything typed."""from lib import policy# What the policy reads besides the request, built from the files that own each fact.# the document's one top-level key, which the policy reads as data.platformdata = policy.data_document()["platform"]print("users, from governance/users.toml:", len(data["users"]))print("agent-a05:", data["users"]["agent-a05"])print("instructor-17:", data["users"]["instructor-17"])classifications = data["classifications"]print("tables, from governance/metadata.toml:", len(classifications))print("columns classified:", sum(len(columns) for columns in classifications.values()))print("crm.learners.email:", classifications["crm.learners"]["email"])print("billing.payments.card_number:", classifications["billing.payments"]["card_number"])courses = data["instructor_courses"]print("instructors with courses, from learning.courses:", len(courses))# instructor IDs are string keys in the document, so the lookup is "17"print("instructor 17's courses:", courses["17"])
输出python generated-policy-data.py
users, from governance/users.toml: 8
agent-a05: {'groups': ['support'], 'region': 'emea'}
instructor-17: {'groups': ['instructor'], 'instructor_id': 17}
tables, from governance/metadata.toml: 10
columns classified: 77
crm.learners.email: personal
billing.payments.card_number: sensitive
instructors with courses, from learning.courses: 48
instructor 17's courses: [2, 75, 80, 87, 103, 134]

文档中的每一条事实都来自拥有它的文件或表,输出还会标明每项计数的来源:governance/users.toml 中的用户、governance/metadata.toml 中各表里已分类的列,以及 learning.courses 中的讲师。agent-a05 有一个组和一个区域,instructor-17 有一个组和一个讲师 ID,但 users.toml 中没有任何内容说明 17 号讲师教授哪些课程。该文档从 learning.courses 中找到了 [2, 75, 80, 87, 103, 134]。当平台发布这位讲师的另一门课程时,下一次生成策略数据后,讲师的行过滤器就会包含它,无需在任何地方做任何编辑。分类的情形与此相同:要把 card_number 从 sensitive 改掉,只需对 metadata.toml 提交一次经过评审的变更,策略便会随之更新。

**工作准则:**每次加载策略时,都从拥有每条事实的文件或表中生成策略的数据,绝不把事实复制进策略或第二个文件。当某条事实尚无所有者时,例如支持坐席所在的区域,就为它指定一个文件,像评审代码那样评审它,正如平台对 users.toml 所做的那样。

默认拒绝,再按角色允许

最近一次修改见于版次 2026.11.31

有了请求及其数据,策略首先要确定的是:对于没有任何规则预见到的请求,该如何处理。Saltzer 和 Schroeder 提出的故障安全默认值原则是:“访问决策应基于许可,而不是基于排除”(Saltzer and Schroeder, 1975)。在 Rego 中,这体现为一个默认值。规则体从未求值为真的规则没有值,Rego 称之为未定义(undefined);当同名的所有规则都未定义时,OPA 使用默认值(OPA policy language)。有了 default allow := false,凡是没有任何 allow 规则匹配的请求都会被拒绝,无论发送者是谁,也无论请求的内容是什么。

基于角色的访问控制最早由 Ferraiolo 和 Kuhn 于 1992 年形式化,它依据主体所担任的职务而不是主体是谁来授予访问权限。在该平台上,角色是 users.toml 中的一个组,策略中的 readable 对象把每个组映射到它可以读取的表。当请求是读取,用户所属的某个组可以读取该表,并且该组的行过滤器所依赖的内容都没有缺失时,请求才被允许:

default allow := false

allow if {
	input.action.operation == "SelectFromColumns"
	readable_by_a_group
	not missing_attribute
}

最后一行用来防范一种故障,关于生产环境的一节通过删除这一行展示了该故障。打印出映射,并对四个请求作出决策,即可看到默认值如何起作用:

allow-by-role.py Python 3.12.15 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 通过
"""Which groups may read which tables, then four requests decided by the default-deny policy. The points rest on the four decisions and their reasons, printed last."""from lib import policyrego = policy.interpreter()# The groups the policy knows, and the tables each may read: the role part of the policy.readable = policy.evaluate(rego, "data.platform.access.readable", {})for group, tables in readable.items():    print(f"{group} may read:", ", ".join(tables))# Who may read what. Anything no rule allows is denied, including a user or an operation the policy has never seen.requests = [    policy.request("finance-1", "billing.payments", ["amount"]),    policy.request("marketing-1", "billing.payments", ["amount"]),    policy.request("someone-else", "crm.learners", ["learner_id"]),]delete = policy.request("finance-1", "billing.payments", ["amount"])# the same request as finance's read, asking to delete insteaddelete["action"]["operation"] = "DeleteFromTable"for request in requests + [delete]:    decision = policy.decide(request, rego)    who, table = request["context"]["identity"]["user"], request["action"]["resource"]["table"]    print(f"{who}, {request['action']['operation']} on {table['schemaName']}.{table['tableName']}:",          "allowed" if decision["allow"] else "denied", "|", "; ".join(decision["reasons"]))
输出python allow-by-role.py
ai may read: learning.courses, learning.reviews
data-science may read: analytics.course_performance, analytics.learner_activity, billing.payments, crm.learners, learning.courses, learning.enrollments, learning.events, learning.reviews
finance may read: billing.payments, learning.courses, learning.enrollments
instructor may read: learning.courses, learning.enrollments, learning.reviews
marketing may read: crm.learners, learning.courses, marketing.audience
support may read: crm.learners, support.tickets
finance-1, SelectFromColumns on billing.payments: allowed | finance may read billing.payments
marketing-1, SelectFromColumns on billing.payments: denied | no group of this user may read this table
someone-else, SelectFromColumns on crm.learners: denied | no group of this user may read this table
finance-1, DeleteFromTable on billing.payments: denied | DeleteFromTable is not an operation this policy allows

只有规则授予的内容才被允许。财务组可以读取 billing.payments,原因中会指明允许该请求的组。市场组不可以,someone-else 也不可以,后者是策略从未听说过的用户,因为没有任何规则授予它们任何权限。第四个请求仍来自财务组,但请求的是删除而不是读取。没有任何规则提到 DeleteFromTable,因此它同样被拒绝,原因中会说明拒绝的理由。若策略试图列出被禁止的内容,就需要为该操作写一条规则;而这里不需要。每个决策都附带其原因,因此拒绝可以向被拒绝的人解释,也可以记入日志。

工作准则: 每个策略都以 default allow := false 开头,并且只通过指明角色和资源的规则来允许请求。把角色到表的映射集中放在一处,让审阅者可以一次读完全部内容,并为每个决策给出原因。当本应被允许的请求被拒绝时,添加一条允许它的规则;切勿削弱默认值。

这部分尚未翻译,因此以英文显示。

Narrow by attribute: region, consent and purpose

最近一次修改见于版次 2026.11.31

Roles say which tables a group may read; they can't say which rows. NIST's guide to attribute-based access control defines the general approach, in which access is decided by attributes of the subject, the object, the requested operations and, sometimes, the environment. It treats a role as one such attribute (NIST SP 800-162). The alternative, a role for every combination, is what NIST's guide calls "role explosion".

The platform shows why. Support by region would need three support roles, and adding marketing's consent and a purpose for AI training would multiply the roles again. Instead, the policy keeps one role per job and reads three attributes. The region is an attribute of the principal, from users.toml. Consent is an attribute of the data: the learner's marketing_consent and ai_training_consent columns in crm.learners. The purpose is an attribute of the request. Each one becomes a row filter, a structured condition on a column that the engine adds to the query. The support agent's filter reads the agent's region:

row_filters contains {"column": "support_region", "equals": user.region} if {
	"support" in groups
	table in {"crm.learners", "support.tickets"}
}

Reads by support agents, an instructor, marketing and a data scientist show what each attribute does, with the data scientist reading reviews twice, once with no purpose and once for ai-training:

attributes-as-row-filters.py Python 3.12.15 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 通过
"""Row filters the policy builds for seven reads, from three attributes: the agent's region, the learner's consent and the request's purpose. The points rest on the analyst's two review reads, with and without a purpose."""import jsonfrom lib import policyrego = policy.interpreter()# Region is the agent's attribute, consent the learner's, and purpose the request's. Each becomes a row filter.reads = [    ("agent-a01", "support.tickets", ["ticket_id"], None),    ("agent-a05", "support.tickets", ["ticket_id"], None),    ("agent-a09", "support.tickets", ["ticket_id"], None),    ("instructor-17", "learning.reviews", ["rating"], None),    ("marketing-1", "crm.learners", ["email"], None),    ("analyst-1", "learning.reviews", ["rating", "body"], None),    # the same read with a purpose, the one attribute the requester supplies    ("analyst-1", "learning.reviews", ["rating", "body"], "ai-training"),]for user, table, columns, purpose in reads:    decision = policy.decide(policy.request(user, table, columns, purpose), rego)    who = user + (f" for {purpose}" if purpose else "")    # json shows the consent filter with its learner_consented key, not a column    print(f"{who} reads {table}, row filters:", json.dumps(decision["row_filters"]))    if "body" in columns:        print(f"{who} reads {table}, body shown as:", decision["column_masks"]["body"])
输出python attributes-as-row-filters.py
agent-a01 reads support.tickets, row filters: [{"column": "support_region", "equals": "americas"}]
agent-a05 reads support.tickets, row filters: [{"column": "support_region", "equals": "emea"}]
agent-a09 reads support.tickets, row filters: [{"column": "support_region", "equals": "apac"}]
instructor-17 reads learning.reviews, row filters: [{"column": "course_id", "in": [2, 75, 80, 87, 103, 134]}]
marketing-1 reads crm.learners, row filters: [{"column": "marketing_consent", "equals": true}, {"column": "status", "equals": "active"}]
analyst-1 reads learning.reviews, row filters: []
analyst-1 reads learning.reviews, body shown as: redact
analyst-1 for ai-training reads learning.reviews, row filters: [{"learner_consented": "ai_training_consent"}]
analyst-1 for ai-training reads learning.reviews, body shown as: redact_contacts

The purpose is what changes a data scientist's view of review text. Without one, every review is visible, but the text, body, is shown as redact. For ai-training, only the reviews of learners who agreed to AI training remain, and the text comes back as redact_contacts, with contact details taken out. The three agents get the same rule with one value per region, from one role, and instructor 17's filter lists their courses, generated from learning.courses. Marketing gets two filters, consent given and account active, and an engine applies both. The AI-training filter, learner_consented, tests the review's author, not the review, so enforcing it takes a join to crm.learners. A learner who signed up before the platform asked about AI training has no answer in ai_training_consent, according to the platform's data card, so enforcing the filter has to count an unknown answer as a no.

The purpose is the one attribute the requester supplies, so it reveals more only under a narrower condition: stating ai-training shows review text, but only for consenting learners and without contact details. Leaving it out, or giving any other purpose, gets what the role allows anyway, with the text hidden.

Working rule: Model each condition as an attribute of the principal, the data or the request, read by one rule per role, rather than as another role. When an attribute comes from the requester, as a purpose does, let it unlock access only under a narrower condition, so that leaving it out, or getting it wrong, falls back to what the role allows anyway.

将决策作为一份文档返回

最近一次修改见于版次 2026.11.31

一个是或否无法承载由属性产生的行过滤器。Rego 的决策不必是是或否,因为 OPA 策略可以用结构化数据表示决策,从布尔值到由列表和映射嵌套而成的映射均可(OPA 的设计理念)。平台的策略借助结构化数据,把完整的答复作为一份文档 data.platform.access.decision 返回,其中有四个键:allow、row_filters、column_masks 和 reasons。lib.policy.decide 通过一次查询取得这份文档,并将其作为 Python 字典返回。

过滤器和掩码都是数据,而不是 SQL。过滤器给出一个列名,以及一个值或一组值;对于同意(consent)类过滤器,则给出学员的同意列。掩码是一个名称,取值为 redact、last4、pseudonymize 和 redact_contacts 之一。负责执行决策的组件用自己的代码把每一项转换为 SQL,因此请求或用户记录中的任何内容,例如写入 users.toml 的某个区域,都不可能以 SQL 文本的形式进入查询。掩码依据每一列的分类确定。敏感列对所有人隐藏,唯一的例外是银行卡号的最后四位,财务人员可以看到。个人信息列对需要联系方式的客服人员显示,对其他人则一律掩码,这符合其工作需要。而元数据中没有分类的列,一律视为敏感列:

classification(column) := level if {
	level := data.platform.classifications[table][column]
} else := "sensitive"

设想市场部读取 crm.learners 的四个列,其中三个在元数据中已有分类。第四个列 linkedin_url 代表某条流水线新增、尚无人分类的列:

one-decision-document.py Python 3.12.15 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 通过
"""The whole decision for one read: marketing's four columns of crm.learners, one of them unclassified. The point rests on the masks and the reasons, which give one line per mask and per group that allowed the read."""import jsonfrom lib import policy# Marketing reads four columns of crm.learners. `linkedin_url` stands for a column added to the table and not yet# classified in governance/metadata.toml.request = policy.request("marketing-1", "crm.learners", ["full_name", "email", "phone", "linkedin_url"])# with no interpreter given, decide loads the platform's policy itselfdecision = policy.decide(request)print(json.dumps(decision, indent=2))print("keys:", ", ".join(sorted(decision)))
输出python one-decision-document.py
{
  "allow": true,
  "column_masks": {
    "linkedin_url": "redact",
    "phone": "redact"
  },
  "reasons": [
    "linkedin_url is sensitive, shown as redact",
    "marketing may read crm.learners",
    "phone is personal, shown as redact"
  ],
  "row_filters": [
    {
      "column": "marketing_consent",
      "equals": true
    },
    {
      "column": "status",
      "equals": "active"
    }
  ]
}
keys: allow, column_masks, reasons, row_filters

市场部获得读取权限,附带两条行过滤器,四个列中有两个被掩码。phone 属于个人信息列,而市场部发送电子邮件并不需要它。linkedin_url 未经分类,因此在有人审核之前按敏感列处理。full_name 和 email 没有掩码,没有掩码的列按存储原样显示,这正是市场部发送电子邮件所需要的。reasons 为每个允许读取的组给出一行,并为每个掩码给出一行,因此这份文档能够自行说明理由。拒绝决策携带空的过滤器和掩码,因为策略用两条各自独立的规则构造这两种结果,下游组件便不会把拒绝误认为是部分列被掩码的读取。

工作准则: 每个请求返回一份决策文档,其中包含允许与否、行过滤器、列掩码和理由,并把它作为整体来读取。过滤器和掩码以名称和值的形式保存,由你的执行代码负责转换,绝不由策略写出 SQL。如果某个引擎需要从策略获得 SQL,如 Trino 对其行过滤器和列掩码的做法(Trino 484,OPA 访问控制),就在两者之间用一个经过测试的函数来生成。

这部分尚未翻译,因此以英文显示。

Unit-test the policy in Rego

最近一次修改见于版次 2026.11.27

The decision document is what a test can compare, which matters because a policy decides who sees personal data, and a change to it can widen access without anyone seeing it in a diff. OPA's answer is tests written in Rego: a test is a rule whose name is prefixed with test_, and "If the test rule is undefined or generates a non-true value the test result is reported as FAIL" (OPA policy testing). A test sets up its request with with, which replaces part of input or data for one expression.

The book's engine, regopy, has no opa test, so lib.policy.run_tests plays its part. It finds every test_ rule in the folder's _test.rego files, evaluates each one, and reports PASS when the rule is true, FAIL when it's false or undefined, and ERROR when evaluation fails. Each of the platform's tests sets the user and the action as two separate paths, each to a literal value, for reasons the section on regopy shows:

test_finance_sees_only_the_last_four_digits if {
	decision := access.decision with input.context.identity.user as "finance-1"
		with input.action as {"operation": "SelectFromColumns", "resource": {"table": {"schemaName": "billing", "tableName": "payments", "columns": ["amount", "card_number"]}}}
	decision.allow
	decision.row_filters == []
	decision.column_masks == {"card_number": "last4"}
}

The tests cover each group's allow, its filters and its masks, and the ways a request is denied: a table the group isn't given, an operation other than a read, a user the policy doesn't know, and a support agent with no region.

policy-unit-tests.py Python 3.12.15 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 通过
"""Runs every test in the platform's Rego test file and counts the passes. The point rests on the last line, the tests passed out of all of them."""from collections import Counterfrom lib import policy# Every `test_` rule in governance/policies/access_test.rego, run by name: PASS, FAIL or ERROR, as `opa test` reports.results = policy.run_tests()for test, result in results.items():    print(f"{result}: {test}")# len(results) counts every test, so one that fails or errors still shows in the totalprint("tests passed:", f"{Counter(results.values())['PASS']} of {len(results)}")
输出python policy-unit-tests.py
PASS: test_support_reads_only_its_own_region
PASS: test_support_without_a_region_is_denied
PASS: test_marketing_sees_only_consenting_active_learners
PASS: test_a_group_only_reads_its_own_tables
PASS: test_finance_sees_only_the_last_four_digits
PASS: test_data_science_never_sees_card_numbers
PASS: test_data_science_sees_pseudonyms_not_people
PASS: test_an_unclassified_column_is_hidden
PASS: test_an_unknown_user_is_denied
PASS: test_an_instructor_sees_only_their_courses
PASS: test_the_assistant_reads_only_consented_reviews
PASS: test_training_reads_only_consented_reviews_without_contacts
tests passed: 12 of 12

A test that checks only decision.allow would miss most mistakes, so every test of an allowed read compares the row filters and the column masks whole. In finance's test, decision.row_filters == [] fails if the policy adds any filter to finance's reads, and decision.column_masks == {"card_number": "last4"} fails if it masks one column more or one fewer, or shows the card number another way. The run passes 12 of 12 tests.

Working rule: Write a test for every rule that grants or narrows access, and one for every way a request can be denied, and compare whole filters and masks, not single keys. Run the tests on every change to the policy and to the data the policy reads.

从决策表检查谁能看到什么

最近一次修改见于版次 2026.11.31

单元测试由编写策略的人用 Rego 编写。掌握数据的人,例如支持主管或财务团队,也应当能够检查策略,而不必阅读 Rego。决策表每个请求占一行,说明谁读取哪张表,以及他们必须得到什么结果,用他们工作中的语言来表述。

平台的决策表是 lib.policy.WHO_SEES_WHAT,它是 Python 中的一组行。每一行给出用户、表、读取的列和可选的用途,随后给出该读取是否被允许、行过滤条件检验哪些列、哪些列被脱敏以及如何脱敏。每一行都要经过 lib.policy.decide,它返回决策文档,示例为每一行打印一行结果,采用便于展示给数据所有者的形式:

who-sees-what.py Python 3.12.15 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 通过
"""Each row of the who-sees-what table run through the policy and printed as one line, with the count of rows the policy matches. The point rests on the last line, the count of rows whose decision matches the outcome its row expects."""from lib import policyrego = policy.interpreter()# Each row of lib.policy.WHO_SEES_WHAT is a request and the decision a reviewer expects for it.matching = 0for case in policy.WHO_SEES_WHAT:    decision = policy.decide(policy.request(case.user, case.table, case.columns, case.purpose), rego)    # matches returns True or False, which add as 1 or 0    matching += policy.matches(case, decision)    who = case.user + (f" ({case.purpose})" if case.purpose else "")    shown = "allowed" if decision["allow"] else "denied"    # a consent filter has no column key, so filtered_on reads its learner_consented key    filters = ", ".join(policy.filtered_on(decision)) or "-"    masks = ", ".join(f"{column}: {mask}" for column, mask in decision["column_masks"].items()) or "-"    print(f"{who:26} {case.table:17} {shown:8} rows: {filters:29} masks: {masks}")print("rows of the table the policy matches:", f"{matching} of {len(policy.WHO_SEES_WHAT)}")
输出python who-sees-what.py
agent-a05                  crm.learners      allowed  rows: support_region                masks: -
agent-a05                  billing.payments  denied   rows: -                             masks: -
instructor-17              learning.reviews  allowed  rows: course_id                     masks: body: redact_contacts
instructor-17              crm.learners      denied   rows: -                             masks: -
marketing-1                crm.learners      allowed  rows: marketing_consent, status     masks: phone: redact
finance-1                  billing.payments  allowed  rows: -                             masks: card_number: last4
analyst-1                  billing.payments  allowed  rows: -                             masks: card_number: redact
analyst-1                  crm.learners      allowed  rows: -                             masks: email: pseudonymize, notes: redact
analyst-1                  learning.reviews  allowed  rows: -                             masks: body: redact
analyst-1 (ai-training)    learning.reviews  allowed  rows: ai_training_consent           masks: body: redact_contacts
assistant-1                learning.reviews  allowed  rows: ai_training_consent           masks: body: redact_contacts
someone-else               crm.learners      denied   rows: -                             masks: -
rows of the table the policy matches: 12 of 12

沿着表向下阅读,各角色的规则就以结果的形式显现出来。策略匹配了 12 of 12 行:支持坐席按地区过滤并被拒绝访问支付表;讲师按课程过滤并被拒绝访问学员表;财务人员看到的 card_number 是 last4,而数据科学家看到的是 redact;以及数据科学家对评论表的两次读取,一次带用途,一次不带用途。审阅者若认为某一行有误,可以在拉取请求中直接指出,而无须知道是哪条规则产生了该行。

**工作准则:**在仓库中与策略放在一起维护一张谁能看到什么的表,与单元测试一同运行,并把它的打印形式以数据所有者能够核对的方式展示给他们。当所有者不同意某一行时,先修改这一行,再由失败的行推动对策略的修改。

这部分尚未翻译,因此以英文显示。

Know where regopy differs from OPA

最近一次修改见于版次 2026.11.27

The platform's tests run in regopy because the book's examples must run offline, in seconds, inside Python, and OPA is a separate program. regopy 1.5.2 is close to OPA. Its engine states that it supports Rego v1.18.1 as OPA defines it, and that it passes all the non-built-in test suites OPA publishes. Its README lists the built-ins it doesn't support, such as net.* and http.send (rego-cpp README at v1.5.2), but regopy also differs from OPA in ways that README doesn't list. The platform's policy and tests avoid each of the cases that follow, and OPA itself is the reference for anything in production.

The first group runs without any error:

regopy-silent-differences.py Python 3.12.15 · regopy 1.5.2 通过
"""Small policies that regopy answers differently from OPA, each printed with the answer regopy gives. The prose's points rest on the printed values, and the bound and literal-mock lines are the controls where regopy agrees with OPA."""import jsonfrom regopy import Input, Interpreterdef ask(rules: str, query: str, request: dict) -> str:    """One query's answer from regopy: the value bound to x, or "undefined"."""    rego = Interpreter()    rego.add_module("example", "package example\n" + rules)    rego.set_input(Input(request))    output = str(rego.query(query))    # regopy writes undefined as a bare word; otherwise the binding for x is the answer    return output if output == "undefined" else json.dumps(json.loads(output)["bindings"]["x"])admins_only = 'default allow := false\nallow if input.user == "admin"\n'# no variable in the queryprint("a false decision, queried on its own:", ask(admins_only, "data.example.allow", {"user": "guest"}))# bound to x, the same false decision comes back as a valueprint("the same decision, bound to a variable:", ask(admins_only, "x := data.example.allow", {"user": "guest"}))pre_1_0 = 'allow { input.user == "admin" }\n'                      # no `if`: OPA 1.x refuses to load thisprint("a rule in pre-1.0 syntax:", ask(pre_1_0, "x := data.example.allow", {"user": "admin"}))# regoin is never defined, so deny is undefined and not deny is true for any requesttypo = 'region := "emea"\ndefault allow := false\nallow if not deny\ndeny if input.region != regoin\n'print("a deny with a misspelt, unbound variable, for apac:", ask(typo, "x := data.example.allow", {"region": "apac"}))mocks = """region := input.user.regionemea := {"region": "emea"}with_a_literal := seen if { seen := region with input.user as {"region": "emea"} }with_a_reference := seen if { seen := region with input.user as emea }"""print("region under a mock written as a literal:", ask(mocks, "x := data.example.with_a_literal", {"user": {"region": "apac"}}))# the mock refers to the rule emea, which regopy ignores, so the real input's region comes backprint("region under a mock that refers to a rule:", ask(mocks, "x := data.example.with_a_reference", {"user": {"region": "apac"}}))
输出python regopy-silent-differences.py
a false decision, queried on its own: undefined
the same decision, bound to a variable: false
a rule in pre-1.0 syntax: true
a deny with a misspelt, unbound variable, for apac: true
region under a mock written as a literal: "emea"
region under a mock that refers to a rule: "apac"
  • A false decision comes back undefined. Asked for data.example.allow on its own, regopy answers undefined where the value is false, so "denied" can't be told from "no decision". Bound to a variable, the same query gives false. lib.policy binds every decision it reads.
  • Pre-1.0 syntax runs. Since OPA 1.0, if is required for every rule and contains for multi-value rules (OPA v1.0.0 release notes), and rego-cpp's changelog records that it has dropped support for v0 Rego (rego-cpp changelog). Yet regopy evaluates allow { ... } and answers true, so a policy can pass here and fail to load in OPA, and behind Trino as well.
  • An unbound variable switches a rule off. OPA requires a variable in a comparison to be bound by another expression in the same rule, and rejects the policy otherwise (OPA policy language). regopy runs it anyway. A deny with regoin misspelt for region is silently undefined, so allow if not deny allows an apac request, as true shows.
  • A mock that refers to another rule is ignored. In a policy whose region rule reads input.user.region, a mock written as a literal, with input.user as {"region": "emea"}, gives "emea". Written as a reference to a rule holding the same object, it gives the real input's "apac".

The second group fails, and one failure takes Python down with it. One case adds a test to a copy of the platform's tests; the other formats the same string from nine sources:

regopy-failed-outputs.py Python 3.12.15 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 通过
"""One test that replaces the whole input, and what that does to the interpreter: every query fails, and printing a failed output ends Python. The points rest on the printed error count, the assert that true does not succeed, and the signal the crash ends with."""import signalimport subprocessimport sysimport tempfilefrom collections import Counterfrom pathlib import Pathfrom lib import policy# The platform's tests, plus one that replaces the whole input at once rather than one path at a time.whole_input = """test_finance_reads_payments if {	access.decision.allow with input as {"context": {"identity": {"user": "finance-1"}}, "action": {"operation": "SelectFromColumns", "resource": {"table": {"schemaName": "billing", "tableName": "payments", "columns": ["amount"]}}}}}"""with tempfile.TemporaryDirectory() as name:    folder = Path(name)    for path in policy.POLICIES.glob("*.rego"):        (folder / path.name).write_text(path.read_text(encoding="utf-8"), encoding="utf-8")    with open(folder / "access_test.rego", "a", encoding="utf-8") as tests:        tests.write(whole_input)    results = policy.run_tests(folder)    print("tests that end in ERROR:", f"{Counter(results.values())['ERROR']} of {len(results)}")    rego = policy.interpreter(folder, tests=True)    succeeded = rego.query("true").ok()    # no query succeeds here, not even true: the interpreter loads the file with the broken test    assert not succeeded    print("the query true succeeds:", succeeded)    # lib.policy checks each output before reading it, so a decision asked of this interpreter raises an error.    try:        policy.decide(policy.request("finance-1", "billing.payments", ["amount"]), rego)    except RuntimeError as error:        print("lib.policy.decide raises:", error)    # Printing one of those failed outputs, in a separate Python process.    crash = "import sys; from pathlib import Path; from lib import policy; print(policy.interpreter(Path(sys.argv[1]), tests=True).query('true'))"    ended = subprocess.run([sys.executable, "-c", crash, str(folder)], capture_output=True)    # a negative return code names the signal that ended the process    print("printing the failed output ends Python with:", signal.Signals(-ended.returncode).name)
输出python regopy-failed-outputs.py
tests that end in ERROR: 13 of 13
the query true succeeds: False
lib.policy.decide raises: regopy couldn't evaluate data.platform.access.decision, so there is no decision to read
printing the failed output ends Python with: SIGSEGV
regopy-sprintf-quotes.py Python 3.12.15 · regopy 1.5.2 通过
"""One label formatted from nine sources, the schema taken from each in turn. The point rests on the printed lines where regopy's JSON is invalid: a source that keeps its quotes breaks the output."""import jsonfrom regopy import Input, Interpreter# The same label, sprintf("%s.%s", [schema, input.table]), with the schema "crm" taken from nine places.# crm is a rule and schema_of a function, two of the nine sourceshelpers = 'crm := "crm"\nschema_of(x) := "crm" if x == 1\n'cases = [    ("from input.schema", "input.schema", "true"),    ("from a rule", "crm", "true"),    ("from a function", "schema_of(1)", "true"),    ("from iterating over a set", "s", 'some s in {"crm"}'),    ("from object.get, the key found", 'object.get(input, "schema", "public")', "true"),    # namespace is not in the input, so object.get returns its default, crm    ("from object.get, its default", 'object.get(input, "namespace", "crm")', "true"),    ("from lower(input.schema)", "lower(input.schema)", "true"),    ("from concat", 'concat("", ["c", "rm"])', "true"),    ("from a local variable set to a literal", "v", 'v := "crm"'),]for name, schema, body in cases:    rego = Interpreter()    rego.add_module("example", f'package example\n{helpers}label := sprintf("%s.%s", [{schema}, input.table]) if {{ {body} }}\n')    rego.set_input(Input({"schema": "crm", "table": "learners"}))    try:        print(f"{name}:", json.loads(str(rego.query("x := data.example.label")))["bindings"]["x"])    except json.JSONDecodeError as error:        print(f"{name}, regopy's invalid JSON:", error.doc)
输出python regopy-sprintf-quotes.py
from input.schema: crm.learners
from a rule: crm.learners
from a function: crm.learners
from iterating over a set: crm.learners
from object.get, the key found: crm.learners
from object.get, its default, regopy's invalid JSON: {"expressions":[true], "bindings":{"x":""crm".learners"}}
from lower(input.schema), regopy's invalid JSON: {"expressions":[true], "bindings":{"x":""crm".learners"}}
from concat, regopy's invalid JSON: {"expressions":[true], "bindings":{"x":""crm".learners"}}
from a local variable set to a literal, regopy's invalid JSON: {"expressions":[true], "bindings":{"x":""crm".learners"}}
  • Replacing the whole input breaks every query. One extra test that writes its request as with input as {...}, and evaluates rules that call built-ins such as sprintf, makes every query in that interpreter fail. Every test then ends in ERROR, 13 of 13, and so does the first query asked of a fresh interpreter loaded with the same files, before any test runs: even the query true fails. Replacing one path at a time, as the platform's tests do, works.
  • Printing a failed output crashes Python. Converting one of those failed outputs to a string ends the process with SIGSEGV. So lib.policy checks output.ok() before it reads anything, and a decision asked of that interpreter raises an error instead: regopy couldn't evaluate data.platform.access.decision, so there is no decision to read.
  • sprintf keeps stray quotes. Formatting a string returned by some built-ins, such as object.get's default, lower or concat, or a local variable set to a literal, keeps its quotes. regopy's own output is then invalid JSON, which its Python wrapper fails to parse, as {"expressions":[true], "bindings":{"x":""crm".learners"}} shows. Strings from input, a rule, a function, iteration and object.get's found value format cleanly, and the platform's policy formats only strings like those.

Working rule: Treat regopy as a fast local evaluator and OPA as the reference. Write Rego v1 only, bind every decision to a variable, mock input one path at a time with literal values, and check that an output succeeded before reading it. Before a policy guards production data, check and test it with OPA itself, with opa check --strict and opa test.

用 Cedar 编写同样的规则

最近一次修改见于版次 2026.11.31

Rego 并不是编写此类策略(如本平台的策略)的唯一语言。Cedar 的设计者将其定位为一种表达力强、速度快、安全且可分析的授权语言(Cutler et al., 2024),它对决策的看法更为收敛。一个 Cedar 请求指明主体、动作和资源,答案遵循三条规则:默认拒绝,forbid 优先于 permit,出错即跳过。文档对最后一条的定义是“如果某条策略的求值返回错误,该策略不计入授权响应;它被跳过”(Cedar, authorization)。模式(schema)声明每一种实体类型,即请求可以指明的主体和资源的种类及其属性,除非模式将属性标为可选,否则属性都是必需的(Cedar, schema)。验证会在任何请求到来之前,依据模式检查策略;对于与模式相符的请求,通过验证的策略集可以避免求值时可能出现的大部分错误(Cedar, validation)。本书的示例使用 cedarpy 4.12.2 运行 Cedar,它为 Python 封装了 Rust 编写的 Cedar Policy 库(cedarpy)。

本平台的规则以 Cedar 写成,位于 governance/policies/access.cedar,模式位于 access.cedarschema。每个组一条 permit,重复了 Rego 策略中的 readable 映射。一条 forbid 将客服人员限定在其所在区域的学员范围内,另一条则对所有人隐藏敏感列,财务视图中的卡号除外。lib.policy.cedar_entities 根据 Rego 策略所读取的同一份数据文档生成用户、组、表和列,代码还会为每个区域添加 crm.learners 的第一位学员:

cedar-same-rules.py Python 3.12.15 · cedarpy 4.12.2 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 通过
"""The platform's Cedar policies checked against their schema, then asked the questions the Rego policy answers, over entities generated from its data. The points rest on the printed decisions, and on the misspelt-region error the schema gives before any request."""import cedarpyfrom lib import policyfrom lib.platform import loadpolicies = policy.CEDAR_POLICIES.read_text(encoding="utf-8")schema = policy.CEDAR_SCHEMA.read_text(encoding="utf-8")print("policies valid against the schema:", cedarpy.validate_policies(policies, schema).validation_passed)# misspells region in the policy's text, so the schema reports the attribute that User lackstypo = cedarpy.validate_policies(policies.replace("principal.region", "principal.regoin"), schema)# the validator's first errorprint("with region misspelt:", typo.errors[0].error)# Entities generated from the files the Rego policy reads, plus the first learner of crm.learners in each region.first = {}for learner in load("crm.learners").select(["learner_id", "support_region"]).to_pylist():    # setdefault keeps the first learner seen in each region    first.setdefault(learner["support_region"], learner)entities = policy.cedar_entities(learners=first.values())def ask(user: str, resource: str) -> cedarpy.AuthzResult:    request = {"principal": f'User::"{user}"', "action": 'Action::"read"', "resource": resource, "context": {}}    return cedarpy.is_authorized(request, policies, entities, schema)for user, kind, name in [("finance-1", "Column", "billing.payments.card_number"),                         ("analyst-1", "Column", "billing.payments.card_number"),                         ("analyst-1", "Column", "billing.payments.amount"),                         ("marketing-1", "Table", "billing.payments")]:    print(f"{user} reads {name}:", ask(user, f'{kind}::"{name}"').decision.value)for region, learner in sorted(first.items()):    print(f"agent-a05 (emea) reads a learner in {region}:", ask("agent-a05", f'Learner::"{learner["learner_id"]}"').decision.value)answer = ask("finance-1", 'Column::"billing.payments.card_number"')# the policies that decided the answer, and those skipped on an error, come from its diagnosticsprint("everything Cedar returns for finance-1's card numbers:", answer.decision.value, list(answer.diagnostics.reasons), list(answer.diagnostics.errors))
输出python cedar-same-rules.py
policies valid against the schema: True
with region misspelt: for policy `policy6`, attribute `regoin` on entity type `User` not found
finance-1 reads billing.payments.card_number: Allow
analyst-1 reads billing.payments.card_number: Deny
analyst-1 reads billing.payments.amount: Allow
marketing-1 reads billing.payments: Deny
agent-a05 (emea) reads a learner in americas: Deny
agent-a05 (emea) reads a learner in apac: Deny
agent-a05 (emea) reads a learner in emea: Allow
everything Cedar returns for finance-1's card numbers: Allow ['policy3'] []

凡是 Cedar 能够表达的地方,其决策都与 Rego 策略一致。财务可以读取 card_number 列,数据科学家则不能;在 Rego 中,读取被允许,但该列会被脱敏。数据科学家可以读取 amount,市场部则不能读取支付数据。emea 的客服人员可以读取 emea 的学员,而不能读取其他两位。这些策略同样通过了模式验证,而将 region 拼错时,会在任何东西运行之前给出精确的错误:for policy policy6, attribute regoin on entity type User not found。

Rego 默认没有这样的检查。属性上的同样拼写错误,即客服人员行过滤器中的 user.regoin,在 OPA 和 regopy 中都是未定义的,而 opa check --strict 会放过它,因为只有在你提供模式时,OPA 才会依据模式检查引用(OPA policy language, schemas),而本平台并未提供。客服人员的行过滤器就此消失,只有对过滤器做比较的测试,例如 test_support_reads_only_its_own_region,才能发现这一问题。

Cedar 只返回一个决策,几乎别无其他。输出的最后一行就是它为财务的卡号所返回的全部内容:决策,以及做出该决策的策略的 ID。cedarpy 按位置为策略命名,第四条是 policy3,而不是按 @id 注解(例如 finance-tables)命名。Cedar 的文档指出,@id 对语言本身没有任何意义:它的命令行工具用它来设置策略 ID,其他接口则以别的方式设置(Cedar, syntax)。答案中没有任何内容给出 last4,即 Rego 策略为财务的卡号返回的掩码,因为 Cedar 可以允许访问某一列,却无法说明如何展示它。这条规则只能移入执行代码,置于策略及其测试之外。行的情形与此相同。Cedar 一次只对一位学员做出决策,因此要过滤本平台的学员,就需要对每位学员各发一次请求,或者使用 Cedar 实验性的部分求值,它会为尚无法决定的部分返回残余策略,其结果并不是最终的授权决策(cedarpy)。Cedar 的论文从另一面权衡了这一取舍:“Rego 额外的表达力是福也是祸”。论文接着指出,Rego 没有提供内置的授权概念,例如 allow 或 deny。同一篇论文报告称,在三种带有传递关系的工作负载上,以 Cedar 3.0.1 对比 OPA 的 Rego 0.61.0,Cedar 的中位数速度是 Rego 的 42.8 至 80.8 倍。这些是其设计者的测量结果,并非本书所测,而且与 regopy 无关。

工作准则: 当每个问题都是“该主体可否对该资源执行此操作?”时,例如应用程序的权限检查,并且你希望由模式在每条策略运行之前对其进行检查,就选择 Cedar。当答案必须携带数据时,例如数据仓库的行过滤器和列掩码,或者引擎本来就向 OPA 发出查询时(如 Trino),就选择 Rego。对于本平台的数据仓库,我们推荐 Rego。

这部分尚未翻译,因此以英文显示。

What goes wrong in production

最近一次修改见于版次 2026.11.27

We consider the most damaging failure a rule that silently doesn't apply because an attribute is missing, and it happens in both languages. In Rego, "Expressions that refer to undefined values are also undefined" (OPA policy language). The support agent's row filter takes its value from user.region, so for a user without a region the filter doesn't exist at all. A rule that allows by group still allows, and no filter means every row.

Take a copy of the platform's policy and tests, in a temporary folder, and remove the one line, not missing_attribute, from allow. Then add a support agent with their group and no region, as happens when someone is given a role before anyone sets their region, and ask both policies for the agent's tickets:

missing-region-guard.py Python 3.12.15 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 通过
"""The support policy with and without its guard, asked for a support agent's tickets. The prose's points rest on the printed reasons, row filters and regions seen with each version, and on the test the copy without the guard fails."""import tempfilefrom pathlib import Pathfrom lib import policyfrom lib.platform import load# A support agent added to users.toml with their group, before anyone has set their region.data = policy.data_document()data["platform"]["users"]["agent-new"] = {"groups": ["support"]}request = policy.request("agent-new", "support.tickets", ["ticket_id", "body"])# every region with a ticket, the candidates for what the agent may seeregions = sorted(set(load("support.tickets").column("support_region").to_pylist()))# A copy of the platform's policy and tests, with one line taken out of `allow`: the missing-attribute guard.with tempfile.TemporaryDirectory() as name:    folder = Path(name)    for path in policy.POLICIES.glob("*.rego"):        # the guard's line in allow is indented with a tab, and this removes it        (folder / path.name).write_text(path.read_text(encoding="utf-8").replace("\tnot missing_attribute\n", ""), encoding="utf-8")    for label, policies in [("with the guard", policy.POLICIES), ("without the guard", folder)]:        decision = policy.decide(request, policy.interpreter(policies, data=data))        # a region counts when the decision allows the read and every row filter names it, so no filters means every region        seen = [r for r in regions if decision["allow"] and all(f["equals"] == r for f in decision["row_filters"])]        print(f"{label}, allowed:", decision["allow"])        print(f"{label}, reasons:", "; ".join(decision["reasons"]))        print(f"{label}, row filters:", decision["row_filters"])        print(f"{label}, regions whose tickets the agent sees:", ", ".join(seen) or "none")    failing = [test for test, result in policy.run_tests(folder).items() if result != "PASS"]print("tests that fail without the guard:", ", ".join(failing))
输出python missing-region-guard.py
with the guard, allowed: False
with the guard, reasons: support's row filter needs the user's region, and there is none
with the guard, row filters: []
with the guard, regions whose tickets the agent sees: none
without the guard, allowed: True
without the guard, reasons: support may read support.tickets; support's row filter needs the user's region, and there is none
without the guard, row filters: []
without the guard, regions whose tickets the agent sees: americas, apac, emea
tests that fail without the guard: test_support_without_a_region_is_denied

Without the guard, the agent is allowed, with row filters [], and sees the tickets of americas, apac, emea, including every learner's message and contact details. The reasons already say the region is missing; nothing in allow asked. With the guard, the agent is denied, and the reason names what is missing: support's row filter needs the user's region, and there is none. default allow := false didn't help either, because a rule did allow. One test catches it, test_support_without_a_region_is_denied, which is why the policy's tests include the case of the missing attribute.

Cedar fails the same way, through skip on error. Strip the has region check from the support agents' forbid in the platform's Cedar policies, and it reads principal.region on an agent who has none:

cedar-missing-region.py Python 3.12.15 · cedarpy 4.12.2 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 通过
"""Cedar's support forbid with and without its `has region` check, asked about a support agent with no region. The points rest on the printed decisions with each version, and on the validation error the unguarded policy gets."""import cedarpyfrom lib import policyfrom lib.platform import loadguarded = policy.CEDAR_POLICIES.read_text(encoding="utf-8")unguarded = guarded.replace("principal has region && ", "")            # the same forbid, without its `has` checkschema = policy.CEDAR_SCHEMA.read_text(encoding="utf-8")# A support agent with no region yet, as when a role is given before anyone sets one, and the first learner of crm.learners in each region.data = policy.data_document()data["platform"]["users"]["agent-new"] = {"groups": ["support"]}first = {}for learner in load("crm.learners").select(["learner_id", "support_region"]).to_pylist():    first.setdefault(learner["support_region"], learner)entities = policy.cedar_entities(learners=first.values(), data=data)for name, policies in [("with `has region`", guarded), ("without it", unguarded)]:    for region, learner in sorted(first.items()):        request = {"principal": 'User::"agent-new"', "action": 'Action::"read"',                   "resource": f'Learner::"{learner["learner_id"]}"', "context": {}}        answer = cedarpy.is_authorized(request, policies, entities, schema)        print(f"{name}, a learner in {region}:", answer.decision.value)    # answer is the last learner's request, in emea, the last region in sorted order    print(f"{name}, policies skipped on an error:", list(answer.diagnostics.errors))# the first error the validator returns for the unguarded policiesprint("validation without it:", cedarpy.validate_policies(unguarded, schema).errors[0].error)
输出python cedar-missing-region.py
with `has region`, a learner in americas: Deny
with `has region`, a learner in apac: Deny
with `has region`, a learner in emea: Deny
with `has region`, policies skipped on an error: []
without it, a learner in americas: Allow
without it, a learner in apac: Allow
without it, a learner in emea: Allow
without it, policies skipped on an error: ['error while evaluating policy `policy6`: `User::"agent-new"` does not have the attribute `region`']
validation without it: for policy `policy6`, unable to guarantee safety of access to optional attribute `region` on entity type `User`

Without the check, Cedar lets a support agent with no region read the learners of all three regions. Evaluating the forbid raises an error, Cedar skips that policy, and the support permit still applies. With the check, the same agent is denied every learner. Passing the schema to is_authorized didn't stop it, because the schema declares region optional, since users outside support have none. Validation did, before any request: for policy policy6, unable to guarantee safety of access to optional attribute region on entity type User.

Other failures to watch for:

  • A misspelt attribute is undefined, not an error. user.regoin for user.region passes opa check --strict, and the support filter disappears as it does for a missing region. Compare whole filters in the tests, and give OPA a schema if you want the check before any test runs.
  • A deny rule that reads a missing attribute fails open. The guard fixes allow; a deny or forbid needs the same care. Deny explicitly when a required attribute is absent, and write the test for it before the rule.
  • Policies nobody can test. Rules kept in an engine's settings or in hand-made views per role can't be unit-tested or diffed, so they drift. Keep the policy, its tests and its decision table in the repository, and run all three on every change.
  • regopy passes and OPA refuses. Pre-1.0 syntax and unbound variables run in regopy. Check every policy with opa check --strict before deploying it to OPA.
  • Data that changed under the policy. A support agent moved to another region is one edit to users.toml, and the decision follows only when the data document is rebuilt. Rebuild it whenever its sources change, and deploy it with the policy.

本章的决定

最近一次修改见于版次 2026.11.27
  • **一份策略,用 Rego 编写,**位于 governance/policies/access.rego,默认拒绝,按组放行,并通过三个属性收窄范围:代理所在的地区、学习者的同意情况和请求的用途。
  • **请求的形状与 Trino 的 OPA 请求一致,**由 lib.policy.request 构建,外加一个可选的顶层 purpose;组来自 users.toml,而不是来自请求。
  • **策略所用的数据是生成的,**由 lib.policy.data_document 根据 users.toml、metadata.toml 和 learning.courses 生成,从不手工输入。
  • **每次决策是一份文档,**包含 allow、row_filters、column_masks 和 reasons。过滤器和掩码是数据,而不是 SQL,掩码有 redact、last4、pseudonymize 和 redact_contacts。拒绝决策不带任何过滤器或掩码。
  • **缺失的事实一律按拒绝处理:**元数据未分类的列被视为敏感列,行过滤器所需属性缺失的用户会被拒绝。
  • **策略认识的唯一用途是 ai-training,**它把评论限定在同意参与 AI 训练的学习者范围内,并在展示其文本时去除联系方式。没有用途的读取只获得角色所允许的内容,评论文本被隐藏。
  • **每次变更都运行两类测试:**通过 lib.policy.run_tests 运行的 Rego 单元测试,以及谁能看到什么的对照表 lib.policy.WHO_SEES_WHAT。
  • **示例使用 regopy,以 OPA 为参照:**只用 Rego v1,每个决策都绑定到变量,输入用字面量逐个路径地模拟,每个输出在读取前都要检查。
  • Cedar 用于对比(governance/policies/access.cedar)。它适合对单个资源做允许或拒绝的检查;平台的数据仓库需要把过滤器和掩码作为数据,因此使用 Rego。访问策略是否清晰,取决于测试是否周全。把规则写成代码,意味着谁能看到什么的变更就是评审者可以阅读的差异,而且测试可以在任何人依赖它之前运行。

本章,在本版次中

版次 2026.11.31示例于 2026年11月19日 通过本章 13个示例 个示例中有 13 个通过

译自英文版图书,版次 2026.11.31。

引用本节

格式

每种格式均引用英文原书,本译本以其为准。

每种格式都会注明该版次。其链接会打开当前版次,节标题处会说明该节文本最后一次修改的时间。访问日期和检索日期即为您打开此页的当天。

本页内容

第 5 章,共 10 章: Access policies as code

  1. 让请求的形状与 Trino 一致
  2. 生成策略所读取的数据
  3. 默认拒绝,再按角色允许
  4. Narrow by attribute: region, consent and purpose
  5. 将决策作为一份文档返回
  6. Unit-test the policy in Rego
  7. 从决策表检查谁能看到什么
  8. Know where regopy differs from OPA
  9. 用 Cedar 编写同样的规则
  10. What goes wrong in production
  11. 本章的决定

返回顶部全部章节