Access policies as code

閱讀約需 93 分鐘 分鐘,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 philosophy)。服務會送出一份描述請求的 JSON 文件,政策則以 input 讀取它。開放原始碼的 SQL 引擎 Trino 正是這樣做的:查詢所需的每一次存取檢查,其 OPA 外掛程式都會送出一份文件,其中包含 context.identity(使用者及其所屬群組)與 action(操作與資源,細分到目錄、結構描述、資料表與欄位)(Trino 484, OPA access control)。

平台的政策讀取相同的欄位,因此能按照 Trino 送出的原樣,判定 Trino 讀取欄位的請求 SelectFromColumns。Trino 需要的不只這一項判定。它還要求每個列篩選條件與欄位遮罩都以 SQL 形式提供,列篩選條件的形式為 {"expression": "clause"},由政策回傳欄位與值(Trino 484, OPA access control)。它也會詢問其他檢查,例如 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 的失效安全預設(fail-safe defaults)原則是「以許可而非排除作為存取決策的依據」(Saltzer and Schroeder, 1975)。在 Rego 中,這就是一個預設值。本體(body)永遠不會評估為真的規則沒有值,Rego 稱之為未定義(undefined),而當所有同名規則都未定義時,OPA 會採用預設值(OPA policy language)。有了 default allow := false,沒有任何 allow 規則符合的請求就會被拒絕,無論由誰發出、要求什麼。

角色型存取控制(role-based access control)由 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 philosophy)。平台的政策利用結構化資料,把完整的答覆以單一文件 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 沒有遮罩,沒有遮罩的欄位依儲存內容顯示,這正是行銷部門寄送電子郵件所需。理由欄位為每個允許該次讀取的群組各列一行,並為每項遮罩各列一行,因此這份文件本身即可說明決策緣由。拒絕的決策帶有空的篩選條件與遮罩,因為政策以兩條各自獨立的規則建構這兩種結果,所以下游不會把拒絕誤認為帶有部分欄位遮罩的讀取。

實用原則: 每個請求回傳一份決策文件,內含允許與否、列篩選條件、欄位遮罩與理由,並將其視為一個整體來讀取。篩選條件與遮罩應以名稱與值的形式保存,交由執行端的程式碼轉譯,切勿由政策撰寫成 SQL。若引擎需要政策提供 SQL,例如 Trino 對其列篩選條件與欄位遮罩的做法(Trino 484, OPA access control),則應在兩者之間以一個經過測試的函式來產生。

此部分尚未翻譯,因此以英文呈現。

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;以及資料科學家對評論資料表的兩次讀取,一次附用途,一次不附用途。審閱者若認為某一列有誤,可以直接在 pull request 中提出,而不必知道是哪一條規則產生了該結果。

**實用原則:**將「誰能看到什麼」的決策表與政策一同放在儲存庫中,與單元測試一起執行,並以資料擁有者能夠檢查的用語,將其印出的形式展示給他們。當擁有者不同意某一列時,先修改該列,再讓失敗的那一列帶動政策的修改。

此部分尚未翻譯,因此以英文呈現。

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.

此部分尚未翻譯,因此以英文呈現。

Write the same rules in Cedar

最近一次變動於第 2026.11.31 版

Rego isn't the only language for policies like the platform's. Cedar's designers present it as a language for expressive, fast, safe and analyzable authorization (Cutler et al., 2024), and it takes a narrower view of a decision. A Cedar request names a principal, an action and a resource, and the answer follows three rules: default deny, forbid overrides permit, and skip on error, which the documentation defines as "if a policy's evaluation returns error, the policy does not factor into the authorization response; it is skipped" (Cedar, authorization). A schema declares every type of entity, the kinds of principal and resource a request can name, with its attributes, and attributes are required unless the schema marks them optional (Cedar, schema). Validation checks policies against a schema before any request, and a set that validates avoids most of the errors that evaluation could raise, for requests that match the schema (Cedar, validation). The book's examples run Cedar with cedarpy 4.12.2, which wraps the Rust Cedar Policy library for Python (cedarpy).

The platform's rules in Cedar are in governance/policies/access.cedar, with the schema in access.cedarschema. A permit per group repeats the Rego policy's readable map. A forbid keeps support agents to learners in their own region, and another hides sensitive columns from everyone except finance's view of card numbers. lib.policy.cedar_entities generates the users, groups, tables and columns from the same data document the Rego policy reads, and the code adds the first learner of crm.learners in each region:

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'] []

The decisions agree with the Rego policy wherever Cedar can express them. Finance may read the card_number column, and the data scientist may not, where Rego allows the read and redacts the column. The data scientist may read amount, and marketing may not read payments. The emea agent may read the emea learner and neither of the others. The policies validate against the schema too, and misspelling region gives a precise error before anything runs: for policy policy6, attribute regoin on entity type User not found.

Rego has no such check by default. The same typo in an attribute, user.regoin in the support agent's row filter, is undefined in OPA and regopy alike, and opa check --strict passes it, because OPA checks references against a schema only when you give it one (OPA policy language, schemas), and the platform gives none. The agent's row filter disappears, and only a test that compares the filters, such as test_support_reads_only_its_own_region, catches it.

Cedar returns a decision and little else. The last line of the output is everything it gives back for finance's card numbers: the decision, and the ID of the policy that made it. cedarpy names policies by position, policy3 for the fourth, not by their @id annotations such as finance-tables. Cedar's documentation says @id means nothing to the language itself: its CLI uses it to set policy IDs, and other interfaces set them another way (Cedar, syntax). Nothing in the answer says last4, the mask the Rego policy returns for finance's card numbers, because Cedar can permit a column but can't say how to show it. That rule would move into the enforcement code, outside the policy and its tests. Rows are the same. Cedar decides one learner at a time, so filtering the platform's learners means one request per learner, or Cedar's experimental partial evaluation, which returns residual policies for the parts it can't yet decide, and whose result is not a final authorization decision (cedarpy). Cedar's paper makes the trade-off from the other side: "Rego's added expressiveness is a blessing but also a curse". It adds that Rego provides no built-in authorization concepts such as allow or deny. The same paper reports Cedar 42.8 to 80.8 times faster than Rego at the median, on three workloads with transitive relations, with Cedar 3.0.1 against OPA's Rego 0.61.0. Those are its designers' measurements, not this book's, and they say nothing about regopy.

Working rule: Choose Cedar when every question is "may this principal do this to this resource?", as in an application's permission checks, and you want a schema to check every policy before it runs. Choose Rego when the answer has to carry data, as a warehouse's row filters and column masks do, or when the engine already asks OPA, as Trino does. For the platform's warehouse, we recommend 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. Write the same rules in Cedar
  10. What goes wrong in production
  11. 本章的決定

返回頂端所有章節