クエリへのポリシーの強制

読了まで約74 分分、13 節 節の 16 例 例。

第2026.11.31版 2026年11月19日時点で例が通過 108 例中 108 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.31)から翻訳した。 原文を読む

この章を終えると、プラットフォームが実行するすべてのクエリに対してアクセス判定を強制できるようになる。各クエリを書き換えて、読み取るすべてのテーブルを、ユーザーが閲覧してよい行だけを残し、閲覧できない列をマスクするサブクエリに置き換える。それ以外を読み取るクエリはすべて拒否する。実際のクエリを実行して、誰が何を得るかをテストする。そして、DuckDB の前段に置いた書き換えが何も保護しなくなる境界を説明する。

ポリシーがオンライン学習プラットフォームのウェアハウスを保護できるのは、そこに到達するすべてのクエリに対して有効である場合に限られる。このウェアハウスには、学習者の連絡先、支払い、学習者が書いたテキストが保管されている。第5章では、プラットフォームのアクセスポリシーを Rego で記述した。ユーザー、テーブル、ユーザーが求める列、そして必要に応じてその理由を与えると、ポリシーは判定を返す。判定は、読み取りを allow するかどうか、ユーザーが閲覧してよい行を残す行フィルタ、列の見せ方を変える列マスク(redact、last4、pseudonymize、redact_contacts)、そして reasons から成る。判定はそれだけでは何も行わない。サポート担当者の SQL はテキストとして DuckDB に届くため、両者の間にある何かが、クエリの書き方にかかわらず、そのテキストが読み取るすべてのテーブルに判定を適用しなければならない。

この本の共有モジュール lib.enforce が判定を強制する。これを強制レイヤーと呼ぶ。その Enforcer は、カタログの各テーブルに対するビュー(lib.warehouse.connect)を持つ DuckDB 接続、テーブルのスキーマ、ポリシー、そして仮名用の鍵を保持する。ユーザーが接続を手にすることはない。Enforcer.sql(query, user) はユーザーのクエリを書き換え、書き換えたクエリを実行する。サービスが公開するのは lib.enforce.answer だけであり、これが書き換えを呼び出して行を返す。リレーション、接続へのハンドル、そして鍵を付けたまま強制レイヤーが書いた SQL を実行する Enforcer.run は、決して公開しない。コードは sqlglot 30.33.0 と DuckDB 2.0.0 で動作する。

クエリが読むすべてのテーブルと列を見つける

最終変更:版2026.11.27

ポリシーは問われたことについてしか判断できない。そのため、このレイヤーは、クエリが読むすべてのテーブルと、各テーブルから読む列を把握していなければならない。SQL の文字列からこれを読み取る作業は、落とし穴のある構文解析の問題である。落とし穴には、*、エイリアス、USING を伴う結合、共通テーブル式(CTE)、大文字小文字が混在する識別子がある。sqlglot はクエリを木構造に解析する。その qualify の段階では、すべての列をスキーマに照らして解決し、列にテーブルの修飾を付ける。展開先のスキーマがある場合は、* を、それが表す列に展開する(v30.24.0 の qualify)。レイヤーは起動時にこのスキーマを構築する。カタログのテーブルを列挙し、lib.warehouse.connect が各テーブルのために作成したビューから、各テーブルの列と型を読み取る。そのため、DuckDB が他の用途で保持しているビューがスキーマに入ることはない。

それぞれに落とし穴のある 4 つのクエリで、Enforcer.reads が何を返すかを示す。返されるのは、ポリシーに問い合わせる列であり、これは各クエリが名指しする列と一致していなければならない。

tables-a-query-reads.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""The columns four queries read from each table, and how each dialect normalizes the quoted name "LEARNERS". Theprose's point rests on the query with a CTE and on the normalization lines at the end."""import sqlglotfrom sqlglot import expfrom sqlglot.optimizer.normalize_identifiers import normalize_identifiersfrom lib.catalog import open_catalogfrom lib.enforce import Enforcer# only these two tables are loaded, so the layer's schema holds nothing elseplatform = Enforcer(open_catalog(["crm.learners", "support.tickets"]))# What each query reads, found by sqlglot's qualify against the catalog's schema, with `*` expanded.queries = {    "every column": "select * from crm.learners",    "a join": """select l.country, count(*) as tickets                 from crm.learners as l join support.tickets as t using (learner_id) group by all""",    # exclude drops notes from the CTE, so the reads name every other column of crm.learners    "a CTE": """with emea as (select * exclude (notes) from crm.learners where support_region = 'emea')                select email from emea""",    "names in capitals": 'select EMAIL from "CRM"."LEARNERS"',}for name, sql in queries.items():    for table, columns in platform.reads(sql).items():        print(f"{name}, {table}: {', '.join(columns)}")# DuckDB resolves quoted capitals to the lowercase table. Whether sqlglot lowercases them depends on the dialect.capitals = 'select count(*) from "CRM"."LEARNERS"'print('DuckDB, "CRM"."LEARNERS":', f"{platform.connection.sql(capitals).fetchall()[0][0]:,} rows")for dialect in ["duckdb", "trino", "postgres"]:    # the name the dialect's parser resolves the quoted identifier to    table = normalize_identifiers(sqlglot.parse_one('select * from "LEARNERS"', read=dialect), dialect=dialect).find(exp.Table)    print(f'{dialect} normalizes "LEARNERS" to:', table.name)
出力python tables-a-query-reads.py
every column, crm.learners: ai_training_consent, city, closed_at, country, date_of_birth, email, full_name, learner_id, marketing_consent, notes, phone, signup_at, status, street_address, support_region
a join, crm.learners: country, learner_id
a join, support.tickets: learner_id
a CTE, crm.learners: ai_training_consent, city, closed_at, country, date_of_birth, email, full_name, learner_id, marketing_consent, phone, signup_at, status, street_address, support_region
names in capitals, crm.learners: email
DuckDB, "CRM"."LEARNERS": 5,000 rows
duckdb normalizes "LEARNERS" to: learners
trino normalizes "LEARNERS" to: learners
postgres normalizes "LEARNERS" to: LEARNERS

読み取りは、クエリが返すものではなく、クエリが名指しするものに従う。SELECT * は crm.learners のすべての列を読む。結合は両方のテーブルから learner_id を読む。USING がそれらを比較するためであり、どちらも出力には現れない。CTE が返すのは email だけだが、crm.learners の notes を除くすべての列を名指ししている。そのため、レイヤーはそれらすべてについて問い合わせる。クエリの読み取りは、クエリの返す内容より多いことはあっても、少ないことはない。"CRM"."LEARNERS" も crm.learners に解決される。レイヤーが識別子を DuckDB の解決方法に合わせて正規化するからである。この名前に対して DuckDB は crm.learners の 5,000 rows を返す。ダイアレクトは重要である。sqlglot は "LEARNERS" を、DuckDB と Trino 向けには小文字にし、PostgreSQL 向けには LEARNERS のまま保持する。そのため、レイヤーはクエリを実行するエンジンのダイアレクトで正規化する。

qualify には、レイヤーの設計を決める抜け穴が 1 つある。既知のテーブルに存在しない列があると失敗するが、スキーマにまったく存在しないテーブルは素通りし、そのテーブルの * は展開されないままになる。スキーマの読み取り後にパイプラインが書き込んだテーブルを表す marketing.audience との結合でこれを実行する。次に、そのクエリと他の 5 つの読み取りをレイヤーに通す。

unknown-tables-denied.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""Runs sqlglot's qualify on a join with a table the schema lacks, then sends that join and five other reads throughthe enforcement layer. The prose's point rests on the qualify line, where the star stays, and on the denial lines."""import sqlglotfrom sqlglot.optimizer.qualify import qualifyfrom lib.catalog import open_catalogfrom lib.enforce import Denied, Enforcerplatform = Enforcer(open_catalog(["crm.learners"]))# marketing.audience stands for a table a pipeline wrote after the schema was read. qualify alone lets it through.query = "select * from crm.learners as l join marketing.audience as a on a.learner_id = l.learner_id"print("qualify on its own:", qualify(sqlglot.parse_one(query, read="duckdb"), schema=platform.schema, dialect="duckdb").sql("duckdb"))# The enforcement layer denies anything that isn't a catalog table, before it asks the policy.attempts = {    "a table missing from the catalog": query,    "a column the table doesn't have": "select shoe_size from crm.learners",    # scan_crm_learners is the scan lib.warehouse registers for crm.learners, and DuckDB resolves it like a table    "the scan behind a view": "select count(*) from scan_crm_learners",    "a Parquet file": "select count(*) from read_parquet('data/platform/learners.parquet')",    "a table function": "select count(*) from query_table('crm.learners')",    "a statement that isn't a query": "summarize crm.learners",}for name, sql in attempts.items():    try:        platform.rewrite(sql, "analyst-1")        print(f"{name}: allowed")    except Denied as reason:        print(f"{name}: denied, {reason}")# What those reads would do on the layer's own connection, without the rewrite in front of it.rows = lambda sql: f"{platform.connection.sql(sql).fetchall()[0][0]:,} rows"print("the scan, run directly:", rows("select count(*) from scan_crm_learners"))print("the table function, run directly:", rows("select count(*) from query_table('crm.learners')"))try:    rows("select count(*) from read_parquet('data/platform/learners.parquet')")except Exception as error:    print("the file, run directly:", str(error).split(":")[0])# the layer turned external access off, and DuckDB refuses to turn it back on while the database runstry:    platform.connection.execute("set enable_external_access = true")except Exception as error:    print("turning external access back on:", str(error).split(": ", 1)[1])
出力python unknown-tables-denied.py
qualify on its own: SELECT * FROM "crm"."learners" AS "l" JOIN "marketing"."audience" AS "a" ON "a"."learner_id" = "l"."learner_id"
a table missing from the catalog: denied, not a table in the catalog: marketing.audience AS a
a column the table doesn't have: denied, Column 'shoe_size' could not be resolved. Line: 1, Col: 16
the scan behind a view: denied, not a table in the catalog: scan_crm_learners
a Parquet file: denied, not a table in the catalog: READ_PARQUET('data/platform/learners.parquet')
a table function: denied, not a table in the catalog: QUERY_TABLE('crm.learners')
a statement that isn't a query: denied, only a single query is allowed
the scan, run directly: 5,000 rows
the table function, run directly: 5,000 rows
the file, run directly: Permission Error
turning external access back on: Cannot enable external access while database is running

qualify だけでは、SELECT * がそのまま残ったクエリがエラーなしで返る。これを信頼するレイヤーは、crm.learners についてポリシーに問い合わせ、marketing.audience を検査せずに通してしまう。このレイヤーは、ポリシーに何かを問い合わせる前に、カタログ外のテーブルをすべて拒否する。テーブルに存在しない列は qualify 自体が拒否する。残りの 4 つの読み取りは、この規則が広い理由を示している。lib.warehouse は、各テーブルのスキャンを独自の名前で登録する。たとえば scan_crm_learners である。レイヤーの接続でこれを直接実行すると、そのスキャンは生の学習者データを 5,000 rows 返す。query_table は、文字列が指すテーブルを何でも読み、直接実行すると 5,000 rows を返す。read_parquet はファイルを読み、SUMMARIZE は書き換えが解析できるクエリではない。最初の 3 つはカタログのテーブルではなく、最後の 1 つはクエリではないので、4 つとも拒否される。また、レイヤーの接続では DuckDB の enable_external_access が無効になっている。そのため、書き換えをすり抜けたファイル読み取りがあっても、Permission Error で失敗する(DuckDB のセキュリティ保護)。

実践ルール: クエリが名指しするすべてのテーブルと列についてポリシーに問い合わせる。その際、* はカタログのスキーマに照らして展開する。スキーマに存在しないものは、未知のテーブル、ファイル、テーブル関数、単一のクエリ以外の文を含め、すべて拒否する。拒否のコストは、プラットフォームチームへの 1 回の問い合わせで済む。素通りのコストは、そのテーブルが保持するものすべてである。

この部分はまだ翻訳されていないため、英語で表示している。

Allow only catalog tables, CTEs and subqueries

最終変更:版2026.11.31

Denying names the catalog doesn't hold isn't enough on its own, because a query can read data through sources that aren't table names. A table function can sit under LATERAL, or in a subquery in the select list. Outside a CTE's scope, or before the CTE is defined, DuckDB resolves its name to whatever else the connection holds under that name. A check that inspects only table names, and accepts any name a CTE uses, passes both.

So the layer checks sources against an allowlist. Enforcer.check_sources walks the whole query and requires every FROM and JOIN source, at every level, to be a catalog table, a CTE in scope or a subquery, and a LATERAL to be over a subquery. Everything else is denied, including table functions wherever they appear, VALUES, UNNEST and joins in parentheses. A CTE is in scope in its own query, below it and in later CTEs, and a recursive one also in its UNION's recursive branch. An allowlist fails closed on a kind of source nobody thought of.

A query through the layer must change nothing. DuckDB's scalar write_log writes into the engine's query log. duckdb_functions() marks such functions: has_side_effects is "true if this function changes the database state" (DuckDB, duckdb_functions). At 2.0.0 it also marks functions that only vary, such as random and uuid. The layer denies every flagged function, and every macro that calls one, such as pg_sleep, reading the list from duckdb_functions() when it starts. A list sorted by hand into harmful and harmless can go stale on an upgrade without anyone noticing, and a governed read seldom needs a random number.

lib.enforce keeps the cases as a regression test, source_cases, which chapter 10's CI runs along with the order test below. Running them shows each denial and whether anything was logged:

catalog-sources-only.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""Runs the allowlist's regression cases through the layer and prints each denial with its reason; a case passes when it'sdenied exactly when it must be and its parse logs nothing. The prose's points rest on the count of cases that pass, the functions-denied line and the allowed-query line at the end."""from lib.catalog import open_catalogfrom lib.enforce import MUST_ALLOW, MUST_DENY, Enforcer, source_casesplatform = Enforcer(open_catalog(["crm.learners", "support.tickets"]))# The allowlist's regression test, lib.enforce.source_cases, which chapter 10's CI runs too: queries that read data# other than through a catalog table, a call to each function DuckDB marks as having side effects, and a query the# layer must still allow. A case passes when the layer denies it exactly when it must, and its parse logs nothing.cases = source_cases(platform)for case in cases:    if case["case"] in MUST_DENY:        print(f"{case['case']}:", f"denied, {case['reason']}" if case["denied"] else "ALLOWED")functions = [case for case in cases if case["must"] == "deny" and case["case"] not in MUST_DENY]print("functions with side effects:", ", ".join(case["case"].removeprefix("the function ") for case in functions))print("functions with side effects, denied:", f"{sum(case['denied'] for case in functions)} of {len(functions)}")print("cases whose parse sqlglot logged, quoting the query:", f"{sum(case['logged'] for case in cases)} of {len(cases)}")passing = [case for case in cases if case["denied"] == (case["must"] == "deny") and not case["logged"]]print("cases that pass:", f"{len(passing)} of {len(cases)}")# What two of the cases do on the layer's own connection, without the layer in front of it.# the name is used before its CTE is defined, so DuckDB resolves it to the scan of the same namebefore_the_cte = platform.connection.sql(MUST_DENY["a CTE's name before the CTE"]).fetchall()[0][0]print("a CTE's name before the CTE, run directly:", f"{before_the_cte:,} rows")# turns on DuckDB's query log, the one write_log writes into, so the entries below are what the call leftplatform.connection.execute("CALL enable_logging('QueryLog')")platform.connection.sql(MUST_DENY["a function that writes DuckDB's log"]).fetchall()logged = [message for (message,) in platform.connection.sql("select message from duckdb_logs where type = 'QueryLog'").fetchall()]print("the log function, run directly, query-log entries it leaves:", logged)# the query the allowlist must admit: a CTE, a join and a scalar subquery over catalog tablesfor name, query in MUST_ALLOW.items():    print(f"{name}, allowed:", f"{platform.sql(query, 'agent-a05').fetchall()[0][0]:,} rows")
出力python catalog-sources-only.py
a table function in FROM: denied, not a table in the catalog: QUERY_TABLE('crm.learners')
a table function in a scalar subquery: denied, not a table in the catalog: QUERY_TABLE('crm.learners')
a table function under LATERAL: denied, a LATERAL that isn't a subquery: LATERAL QUERY_TABLE('crm.learners')
a catalog-qualified name: denied, not a table in the catalog: memory.crm.learners
an information_schema view: denied, not a table in the catalog: information_schema.tables
a CTE's name outside its scope: denied, not a table in the catalog: other
a CTE's name before the CTE: denied, not a table in the catalog: scan_crm_learners
a function that writes DuckDB's log: denied, a function DuckDB marks as having side effects: write_log
a statement sqlglot keeps as text: denied, only a single query is allowed
functions with side effects: current_connection_id, current_query, current_query_id, current_transaction_id, currval, error, gen_random_uuid, nextval, pg_sleep, random, setseed, setval, sleep_ms, stats, uuid, uuidv4, uuidv7, vector_type, write_log
functions with side effects, denied: 19 of 19
cases whose parse sqlglot logged, quoting the query: 0 of 29
cases that pass: 29 of 29
a CTE's name before the CTE, run directly: 5,000 rows
the log function, run directly, query-log entries it leaves: ["select write_log('an entry', log_type := 'QueryLog')", 'an entry']
a CTE, a join and a scalar subquery, allowed: 61 rows

Each case the layer must deny is refused before any policy is asked, with a reason that names the source. The parse has to leave no trace of its own. sqlglot logs any statement it keeps as text, such as a CALL, values included (sqlglot source, v30.24.0), so the layer silences the parser's warnings, and every case checks that nothing was logged. 29 of 29 cases pass.

On the layer's own connection, two cases show what their denials prevent. The name used before its CTE reads the scan of the same name, 5,000 rows of raw learners, and write_log leaves ["select write_log('an entry', log_type := 'QueryLog')", 'an entry'] in the query log: its own statement, and an entry no query made. Every function with side effects is denied, 19 of 19.

The allowlist also has to let ordinary queries through. Run as agent-a05, the EMEA support agent, a CTE, a join and a scalar subquery over catalog tables return 61 rows.

Working rule: Check every source against an allowlist of catalog tables, CTEs in scope and subqueries, deny the rest, and deny every function the engine marks as having side effects, read from its own list. Keep the cases as a regression test for every layer change and engine upgrade, and add one for each new kind of source or function.

この部分はまだ翻訳されていないため、英語で表示している。

Masking column references leaks

最終変更:版2026.11.27

With the columns known, the obvious enforcement rewrites them: wherever the query selects email and the decision masks it, select the mask instead. It needs only the column list from the first section, and it looks right on the queries people test with. It fails because a query can read a column without selecting it, and DuckDB can return a column without naming it.

Enforcer.mask_select_list does the column rewrite, kept only to show its failure. We test it with five reads aimed at learner 2's email, run as analyst-1, a data scientist who may read crm.learners with email and the other personal columns pseudonymized and free text such as notes redacted. The first print is the rewrite of a plain read, with any stored email replaced by a placeholder, since the examples never print one. Predict how many of the five the rewrite stops:

select-list-masks-leak.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""Masks the email in the select list only, then runs five reads aimed at one learner's email through that rewrite andprints what each returns. The prose's point rests on the five attack lines, each of which returns learner 2's ID, thestored email, or an error that holds it."""import reimport duckdbfrom lib.catalog import open_catalogfrom lib.enforce import EMAIL, Enforcerplatform = Enforcer(open_catalog(["crm.learners"]))# analyst-1, a data scientist, may read crm.learners with `email` pseudonymized. The attacks aim at learner 2.email = platform.connection.sql("select email from crm.learners where learner_id = 2").fetchall()[0][0]print("the column rewrite:", platform.mask_select_list("select learner_id, email from crm.learners", "analyst-1"))attacks = {    "a WHERE on the raw column": f"select learner_id from crm.learners where email = '{email}'",    "the whole row as a struct": "select struct_extract(l, 'email') from crm.learners as l where learner_id = 2",    "COLUMNS(...)": "select columns('^email$') from crm.learners where learner_id = 2",    "to_json": "select to_json(l) ->> 'email' from crm.learners as l where learner_id = 2",    "a cast error": "select learner_id from crm.learners where cast(email as integer) = 0",}for name, sql in attacks.items():    try:        # the column rewrite changes only the select list, so every other clause reads the stored email        answer = str(platform.run(platform.mask_select_list(sql, "analyst-1")).fetchall())    except duckdb.Error as error:        answer = str(error).splitlines()[0]    print(f"{name}:", re.sub(EMAIL, "<a stored email>", answer))      # the book never prints a stored email
出力python select-list-masks-leak.py
the column rewrite: SELECT "learners"."learner_id" AS "learner_id", SHA256($pseudonym_key || CAST("learners"."email" AS TEXT)) AS "email" FROM "crm"."learners" AS "learners"
a WHERE on the raw column: [(2,)]
the whole row as a struct: [('<a stored email>',)]
COLUMNS(...): [('<a stored email>',)]
to_json: [('<a stored email>',)]
a cast error: Conversion Error: Could not convert string '<a stored email>' to INT32 when casting from source column email

The column rewrite stops none of the five. Its rewrite of the plain read is correct: email comes back as a hash. The five reads get past it in three ways:

  • A WHERE on the raw column never passes through the select list, so it compares the stored email. The analyst guesses an email and gets back learner 2's ID, [(2,)], which links that person to every row they can join on learner_id.
  • The whole row as a struct, COLUMNS(...) and to_json return the stored email, [('<a stored email>',)], without any column reference named email for the rewrite to find: DuckDB expands the row, or matches column names against a pattern, itself.
  • A cast error prints a stored email in its message. DuckDB's cast errors include the value, and PostgreSQL's documentation warns that "most casting functions include their input values in the error messages they produce" (PostgreSQL 18, Rules and Privileges).

Masking the column wherever the query names it, in the WHERE clause too, would stop the first and the last read. It can't stop the middle three, because they never name the column.

Working rule: Don't enforce masks by rewriting column references. However many reference shapes you cover, the engine has more ways to read a column than the rewrite can recognize. Mask where the data comes from instead, so every read sees the masked value, as the next section does.

各テーブルをフィルタ済みでマスク済みのサブクエリに置き換える

最終変更:版2026.11.27

列参照の書き換えが漏えいを起こすのは、生のテーブルがクエリに残るからである。対策はテーブルそのものを置き換えることである。Enforcer.rewriteは、クエリ内の各カタログテーブルを、そのクエリが付けた別名のまま、ユーザーに対する判定から作ったサブクエリに置き換える。サブクエリは次のように構成される。

  • テーブルのすべての列を、テーブルでの並び順のまま含める。これにより、*、構造体、COLUMNS(...)は想定どおりの形を受け取る。
  • クエリが読む各列は、判定の指示に従って、保存された値のまま、またはマスクした値として返す。これは、後の節で説明する行フィルタを条件とするCASEの内側に置く。
  • クエリが読まない各列は、型付きのNULLとする。ポリシーにはその列について問い合わせていないためである。
  • 判定に含まれるすべての行フィルタを入れたWHERE句を付ける。

ユーザーのクエリが行うすべての処理は、そのWHEREから構造体の読み取りに至るまで、このサブクエリの上で行われる。これはTrinoのOPAプラグインが採るモデルであり、エンジンの節が示すとおり、行フィルタは本質的に追加のWHERE句として働く。

instructor-17を例に取る。この講師は、自分の講座のレビューのうち低い評価のものを読む。ポリシーは、自分の講座のレビューだけを残し、bodyから連絡先を取り除く。出力された書き換え結果は次のとおりである。

table-rewrite.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""Rewrites instructor-17's query over the reviews, prints the rewrite and runs it. The prose's point rests on the tworesult lines: how many reviews come back, and how many of them still hold an email."""import sqlglotfrom lib.catalog import open_catalogfrom lib.enforce import Enforcerplatform = Enforcer(open_catalog(["learning.reviews"]))# instructor-17 reads the low ratings of their courses' reviews. The policy filters reviews to their six courses and# shows `body` with contact details removed.query = "select course_id, rating, body from learning.reviews where rating <= 2"# the query as text, with the reviews table replaced by a subquery built from the decisionrewritten = platform.rewrite(query, "instructor-17")print(sqlglot.transpile(rewritten, read="duckdb", write="duckdb", pretty=True)[0])print("reviews returned:", len(platform.run(rewritten).fetchall()))print("of them holding an email:", platform.run(f"select count(*) from ({rewritten}) where body like '%@%'").fetchall()[0][0])
出力python table-rewrite.py
SELECT
  "reviews"."course_id" AS "course_id",
  "reviews"."rating" AS "rating",
  "reviews"."body" AS "body"
FROM (
  SELECT
    CAST(NULL AS BIGINT) AS review_id,
    CAST(NULL AS BIGINT) AS learner_id,
    CASE WHEN source.course_id IN (2, 75, 80, 87, 103, 134) THEN source.course_id END AS course_id,
    CASE WHEN source.course_id IN (2, 75, 80, 87, 103, 134) THEN source.rating END AS rating,
    CASE
      WHEN source.course_id IN (2, 75, 80, 87, 103, 134)
      THEN REGEXP_REPLACE(
        REGEXP_REPLACE(source.body, '[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+', '[email]', 'g'),
        '\+?\(?[0-9][0-9 ().-]{6,}[0-9]',
        '[phone]',
        'g'
      )
    END AS body,
    CAST(NULL AS TIMESTAMPTZ) AS posted_at
  FROM learning.reviews AS source
  WHERE
    source.course_id IN (2, 75, 80, 87, 103, 134)
) AS "reviews"
WHERE
  "reviews"."rating" <= 2
reviews returned: 9
of them holding an email: 0

クエリは9件のレビューを返し、そのうち0件にメールアドレスが含まれる。講師のクエリは外側に残り、修飾されるだけで、ほかは変わらない。内側では、course_idとratingは保存された値のまま通り、bodyはredact_contactsマスクを通る。それぞれは行フィルタ、つまり講師の講座の列挙リストを条件とするCASEの中にある。クエリが読まない列は、型付きのNULLとして通る。

列の書き換えを破った五つの読み取りを、analyst-1としてテーブルの書き換えに通して実行する。あわせて、サービスが境界で呼び出す関数であるlib.enforce.answerを通しても実行する。

table-rewrite-holds.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""Sends the five reads from the column rewrite through the table rewrite, and through `answer`, the service's boundary.It then shows what the analyst receives and what the platform team's log holds. The prose's point rests on the five attacklines, the operator's log line and the relation line."""import loggingimport refrom lib.catalog import open_catalogfrom lib.enforce import EMAIL, Enforcer, QueryFailed, answerplatform = Enforcer(open_catalog(["crm.learners"]))operator_log = []                     # the platform team's log, kept in a list here so the example can print itlogging.getLogger("lib.enforce").addHandler(handler := logging.Handler())handler.emit = lambda record: operator_log.append(record.getMessage().splitlines()[0])# The five attacks on the column rewrite, run by analyst-1 again: through the table rewrite this time, and through# `answer`, the function a service calls at its boundary.email = platform.connection.sql("select email from crm.learners where learner_id = 2").fetchall()[0][0]attacks = {    "a WHERE on the raw column": f"select learner_id from crm.learners where email = '{email}'",    "the whole row as a struct": "select struct_extract(l, 'email') from crm.learners as l where learner_id = 2",    "COLUMNS(...)": "select columns('^email$') from crm.learners where learner_id = 2",    "to_json": "select to_json(l) ->> 'email' from crm.learners as l where learner_id = 2",    "a cast error": "select learner_id from crm.learners where cast(email as integer) = 0",}# a pseudonym is 64 hex digits, shortened here; the example never prints a stored emailshorten = lambda text: re.sub(r"\b([0-9a-f]{8})[0-9a-f]{56}\b", r"\1…", re.sub(EMAIL, "<a stored email>", text))for name, sql in attacks.items():    try:        # answer returns the rows, or raises QueryFailed with a generic message, as a service sees it        got = str(answer(platform, sql, "analyst-1"))    except QueryFailed as error:        got = f"{type(error).__name__}, {error}"    print(f"{name}:", shorten(got))for line in operator_log:    print("in the operator's log:", shorten(line))      # a pseudonym, 64 hex digits, shortened# Why `answer` returns rows: the relation Enforcer.sql returns is a handle on the layer's connection, and runs any SQL.# the relation is a handle on the layer's connection, so its .query runs SQL of its own thererelation = platform.sql("select learner_id from crm.learners", "analyst-1")print("the relation, running SQL of its own:", shorten(str(relation.query("r", "select email from crm.learners where learner_id = 2").fetchall())))print("what answer returns:", type(answer(platform, "select learner_id from crm.learners", "analyst-1")).__name__)
出力python table-rewrite-holds.py
a WHERE on the raw column: []
the whole row as a struct: [(None,)]
COLUMNS(...): [(None,)]
to_json: [(None,)]
a cast error: QueryFailed, the query failed: the platform team can see why
in the operator's log: a query by analyst-1 failed in the engine: Conversion Error: Could not convert string 'e4f62f1a…' to INT32 when casting from source column email
the relation, running SQL of its own: [('<a stored email>',)]
what answer returns: list

書き換えは五つすべてを止める。WHEREは[]を返す。サブクエリの内側ではemailがすでに仮名になっているからである。構造体、COLUMNS(...)、to_jsonによる読み取りは、仮名ではなくNULLを返す。これらのクエリはlearner_id以外の列を名指ししていないからである。ポリシーはほかの列について問い合わせを受けておらず、型付きのNULLは残りの列に値を与えない。書き換えが見通せない読み取りは、安全側に倒れて失敗する。キャストエラーには、メールアドレスではなく仮名が含まれるようになる。さらにanswerはそれすら隠す。tryの内側で行を取得し、エンジンのエラーをすべてQueryFailedに変え、DuckDBのメッセージをプラットフォームチームのログに書く。このログは、例の五つの読み取りのあとに出力される。アナリストが受け取るのはQueryFailed, the query failed: the platform team can see whyである。

answerはリレーションではなく行を返す。DuckDBのリレーションは、その接続上で任意のSQLを実行できるからである。アナリストのリレーションは、メールアドレスを要求すると[('<a stored email>',)]を返す。

クエリごとにサブクエリを生成し、ロールごとにビューを書かないことが、サブクエリをポリシーと歩調の合った状態に保つ。プラットフォームの判定は地域、講座、同意、目的に依存する。あらゆる組み合わせに手作りのビューを用意すると、NISTが述べる「ロールの爆発」になる。そこでは条件が「その場しのぎで、所属が限られた多数のロール」になる(NIST SP 800-162)。そのようなビューは、誰かが片方だけを編集した時点でポリシーからずれていく。

実践ルール: 保護対象のテーブルはすべて、クエリ自身の別名のまま、判定から生成したサブクエリに置き換え、ユーザーのクエリにはそれ以外手を加えない。読まれない列には型付きのNULLを与える。ユーザーが値を表示するために行全体の読み取りを必要とする場合は、代わりに各テーブルのすべての列についてポリシーに問い合わせ、マスクがそのすべてを覆うようにする。その代償として、クエリが使わない列を名指しする要求と監査記録が生じる。

この部分はまだ翻訳されていないため、英語で表示している。

Write each mask as SQL in one place

最終変更:版2026.11.31

The policy names a mask; the layer decides what SQL it becomes. Keeping that mapping in one place, the MASKS table in lib.enforce and the typed NULL beside it, means a fix to a mask reaches every table that uses it, and the policy never carries SQL, which would be code arriving as data. The table rewrite calls lib.enforce.masked for every masked column, and prints the SQL for the four masks the policy names:

masks-as-sql.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""Prints the SQL the enforcement layer writes for each of the four masks the policy names, and counts DuckDB's functionsnamed like HMAC. The prose's points rest on the pseudonymize line and on the HMAC count."""import duckdbfrom sqlglot import expfrom lib.enforce import masked# The four masks the policy names, as the SQL the enforcement layer writes for them.# the column's type, which the redact mask casts its NULL tofor kind, column, type_ in [("redact", "date_of_birth", "DATE"), ("last4", "card_number", "VARCHAR"),                            ("pseudonymize", "email", "VARCHAR"), ("redact_contacts", "body", "VARCHAR")]:    # redact is a typed NULL; the other masks' SQL comes from lib.enforce's MASKS table    print(f"{kind}:", masked(kind, exp.column(column), type_).sql("duckdb"))# The pseudonymize mask hashes the key followed by the value, because DuckDB has no HMAC function to call.# DuckDB's function catalog, searched for any name containing hmac, whatever its casehmac = duckdb.sql("select count(*) from duckdb_functions() where function_name ilike '%hmac%'").fetchall()[0][0]print("DuckDB functions named like HMAC:", hmac)
出力python masks-as-sql.py
redact: CAST(NULL AS DATE)
last4: RIGHT(REGEXP_REPLACE(card_number, '[^0-9]', '', 'g'), 4)
pseudonymize: SHA256($pseudonym_key || CAST(email AS TEXT))
redact_contacts: REGEXP_REPLACE(REGEXP_REPLACE(body, '[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+', '[email]', 'g'), '\+?\(?[0-9][0-9 ().-]{6,}[0-9]', '[phone]', 'g')
DuckDB functions named like HMAC: 0

Each mask does one job:

  • redact is a NULL cast to the column's type, so the column keeps its type for anything the query does with it, such as a union or a date function.
  • last4 keeps the last four digits of a card number, after removing anything that isn't a digit.
  • pseudonymize is a keyed hash, SHA-256 over the key followed by the value, because DuckDB 2.0.0 has no HMAC function: duckdb_functions() lists 0 named like it. Where your engine has one, prefer HMAC (RFC 2104).
  • redact_contacts replaces emails and phone numbers in free text with [email] and [phone].

Picture someone holding a list of the platform's emails, who hashes each one and looks for it among the pseudonyms analyst-1 sees in crm.learners:

pseudonym-key.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""Hashes a list of emails the way the layer hashes pseudonyms, with and without its key, then rotates the key and countsthe pseudonyms that change. The prose's points rest on the three count lines: the matches without the key and with it, andthe pseudonyms that change on rotation."""from lib.catalog import open_catalogfrom lib.enforce import Enforcer# The pseudonyms analyst-1, the platform's data scientist, sees in crm.learners. Someone holding a list of the# platform's emails hashes each one and looks for it among them, first without the key and then with it.# an example key, not a secret: production keeps the real one where only the layer can read itplatform = Enforcer(open_catalog(["crm.learners"]), key="example-key-not-a-secret")seen = platform.sql("select learner_id, email from crm.learners", "analyst-1").to_arrow_table()platform.connection.register("seen", seen)# a guess is an email's hash; the second also puts the key first, as the layer hashes a pseudonymfor name, guess in [("without the key", "sha256(email)"), ("with the key", "sha256($pseudonym_key || email)")]:    matched = platform.run(f"select count(*) from crm.learners where {guess} in (select email from seen)").fetchall()[0][0]    print(f"pseudonyms matched from a list of emails, {name}: {matched:,} of {seen.num_rows:,}")# A new key gives every learner a new pseudonym, so data pseudonymized under the old key no longer joins.platform.key = "example-key-rotated"rotated = platform.sql("select learner_id, email from crm.learners", "analyst-1").to_arrow_table()# pairs each learner's old and new pseudonym, row by rowchanged = sum(a != b for a, b in zip(seen["email"].to_pylist(), rotated["email"].to_pylist()))print("pseudonyms that change when the key is rotated:", f"{changed:,} of {seen.num_rows:,}")
出力python pseudonym-key.py
pseudonyms matched from a list of emails, without the key: 0 of 5,000
pseudonyms matched from a list of emails, with the key: 5,000 of 5,000
pseudonyms that change when the key is rotated: 5,000 of 5,000

The key is what makes a pseudonym a pseudonym. Without it, the hashes match 0 of 5,000 pseudonyms; with it, they match 5,000 of 5,000, so whoever holds the key and a list of emails can name every pseudonym on it. The key belongs to the layer alone. It stays out of the policy, which is code read in pull requests, and out of the query, where a user who chose the key could compute pseudonyms of guessed emails. The layer passes the key to DuckDB as a query parameter, so it stays out of the query text that DuckDB's log records, as chapter 8 shows, and the layer denies any user query that carries a parameter, since one named $pseudonym_key would receive the key. In production, keep the key in a secret manager that only the layer can read. Rotate it when it may have leaked, and plan for what rotation does: 5,000 of 5,000 pseudonyms change, so data pseudonymized under the old key no longer joins with data under the new one.

redact_contacts is two regular expressions, and it's worth measuring what they remove. The platform's tickets and reviews come with every piece of personal data the generator placed in them, labelled by construction, which chapter 3 calls the truth. Each text goes through the mask here, and the labels count what survives:

redact-contacts-recall.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""Applies the redact_contacts mask to every ticket and review, then counts the labelled personal data still left in themasked text, and the phone replacements made in the tickets. The prose's points rest on the 'left in the text' lines, thereplacement count, and the assert on the tickets' card, IBAN and date lines."""import duckdbfrom sqlglot import expfrom lib.enforce import maskedfrom lib.platform import load# The redact_contacts mask, run over every ticket and review, against the personal data the generator placed in them# (pii_spans, labelled by construction).con = duckdb.connect()# each table registers under its short name, which the queries below usefor name in ["support.tickets", "learning.reviews", "pii_spans"]:    con.register(name.split(".")[-1], load(name))mask = masked("redact_contacts", exp.column("body"), "VARCHAR").sql("duckdb")# a span counts as left when its exact text is still in the masked body, which the row_id join findscounts = con.sql(f"""    with masked as (select 'tickets' as source, ticket_id as row_id, {mask} as body from tickets                    union all select 'reviews', review_id, {mask} from reviews)    select source, entity, count(*), count(*) filter (where contains(masked.body, pii_spans.text))    from pii_spans join masked using (source, row_id) group by all order by all""").fetchall()# the phone pattern takes every card number, IBAN and date in the tickets, so none is left in the masked textleft_in_tickets = {entity: left for source, entity, _, left in counts if source == "tickets"}assert all(left_in_tickets[entity] == 0 for entity in ("CREDIT_CARD", "IBAN_CODE", "DATE_TIME"))for source, entity, placed, left in counts:    print(f"{source}, {entity}, left in the text: {left:,} of {placed:,}")# The phone pattern also takes card numbers, IBANs and dates, which are digits too.replaced = con.sql(f"select sum(len(regexp_extract_all({mask}, '\\[phone\\]'))) from tickets").fetchall()[0][0]print("[phone] replacements in tickets:", f"{replaced:,}")
出力python redact-contacts-recall.py
reviews, EMAIL_ADDRESS, left in the text: 0 of 120
reviews, PERSON, left in the text: 798 of 798
tickets, CREDIT_CARD, left in the text: 0 of 213
tickets, DATE_TIME, left in the text: 0 of 196
tickets, EMAIL_ADDRESS, left in the text: 0 of 423
tickets, IBAN_CODE, left in the text: 0 of 236
tickets, LOCATION, left in the text: 210 of 210
tickets, PERSON, left in the text: 1,657 of 1,657
tickets, PHONE_NUMBER, left in the text: 0 of 439
[phone] replacements in tickets: 1,520

The mask removes contact details and leaves names alone. In the reviews, which instructors and the assistant read through this mask, 0 of 120 emails are left, and 798 of 798 names are.

In the tickets, 0 of 439 phone numbers are left, but the phone pattern makes 1,520 replacements. Card numbers, IBANs and dates are digits too, so the pattern takes them as well, and none of them is left. Names and street addresses stay, so the mask doesn't make text anonymous.

Working rule: Keep every mask's SQL in one table in the enforcement layer, and let the policy name masks, never write them. Key every pseudonym with a secret only the layer holds, passed as a parameter. Measure each text mask against labelled data before a policy relies on it, and name masks for what they remove, so nobody reads redact_contacts as "anonymized".

判断のデータから行フィルタを構築する

最終変更:版2026.11.27

マスクは値の見せ方を変えるが、行フィルタはユーザーがどの行を得るかを決める。行フィルタは、判断の中にデータとして届く。その形は三つあり、列が値に等しいもの、列が値のリストに含まれるもの、行が属する学習者に対する同意の確認である。lib.enforce.row_filterは、それぞれを SQL の条件に変換する。このとき値は sqlglot によって SQL リテラルとして書かれ、SQL 文に貼り付けられることはない。知らない形のフィルタや、テーブルに存在しない列が指定されたフィルタについては、クエリを拒否する。同意フィルタの場合は、レイヤーが検査を組み立てる前に、その列をcrm.learnersと照合する。第5章では、まさにこの理由から、ポリシーがフィルタをデータとして返すようにした。リクエストが運ぶものは、何であってもコードとしてクエリに到達できない。

注意が必要なのは同意の形である。コースアシスタントのassistant-1が読んでよいのは、自分のレビュー文をプラットフォームの AI の学習に使うことに同意した学習者のレビューだけである。その同意はcrm.learnersにあり、アシスタントはこのテーブルを読めない。レイヤーはこれをセミジョインに変換する。セミジョインとは、レビューのlearner_idが同意した学習者の中にあるかを調べるテストであり、レイヤー自身のcrm.learnersへのアクセス権で実行する。

row-filters-from-data.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""Prints the condition the layer writes for each row filter in three decisions, then the reviews the assistant readsthrough its consent filter, and the denial of its read of the learners table. The prose's points rest on the read countsand the consent counts, and on the denied read at the end."""from lib.catalog import open_catalogfrom lib.enforce import Enforcer, row_filterplatform = Enforcer(open_catalog(["crm.learners", "learning.reviews", "support.tickets"]))# Each row filter in a decision, as the condition the enforcement layer writes for it.for user, table in [("agent-a05", "support.tickets"), ("instructor-17", "learning.reviews"), ("assistant-1", "learning.reviews")]:    # the decision for this read; its row filters are data, written as SQL in the loop below    decision = platform.decide(user, {table: set()})[table]    for rule in decision["row_filters"]:        print(f"{user}, {table}: {row_filter(rule, platform.columns(table)).sql('duckdb')}")# A filter's values come from data, so a value that looks like SQL stays a value.odd = {"column": "support_region", "equals": "emea' or '1' = '1"}print("a region that looks like SQL:", row_filter(odd, platform.columns("support.tickets")).sql("duckdb"))# The assistant's consent filter reads crm.learners, which the assistant itself may not read.total = platform.connection.sql("select count(*) from learning.reviews").fetchall()[0][0]read = platform.sql("select count(*) from learning.reviews", "assistant-1").fetchall()[0][0]print("reviews the assistant reads:", f"{read:,} of {total:,}")# a null consent means no answer was recorded, so the label reads 'never asked'by_consent = platform.connection.sql("""select coalesce(l.ai_training_consent::varchar, 'never asked'), count(*)    from learning.reviews r join crm.learners l using (learner_id) group by all order by all""").fetchall()for consent, reviews in by_consent:    print(f"reviews whose author's AI-training consent is {consent}: {reviews:,}")try:    platform.sql("select count(*) from crm.learners", "assistant-1")except Exception as reason:    print("the assistant reading crm.learners:", reason)
出力python row-filters-from-data.py
agent-a05, support.tickets: source.support_region = 'emea'
instructor-17, learning.reviews: source.course_id IN (2, 75, 80, 87, 103, 134)
assistant-1, learning.reviews: source.learner_id IN (SELECT consent.learner_id FROM crm.learners AS consent WHERE consent.ai_training_consent IS TRUE)
a region that looks like SQL: source.support_region = 'emea'' or ''1'' = ''1'
reviews the assistant reads: 436 of 3,000
reviews whose author's AI-training consent is false: 955
reviews whose author's AI-training consent is never asked: 1,609
reviews whose author's AI-training consent is true: 436
the assistant reading crm.learners: assistant-1 may not read crm.learners: no group of this user may read this table

各フィルタの値は SQL リテラルになるので、値は値のままであり、未回答の同意は「同意なし」として扱われる。エージェントの地域と講師のコースは、等価条件とINリストになる。SQL のように見せかけて書かれた地域は、引用符が二重化された一つの文字列のままである。同意フィルタはIS TRUEを検査する。そのため、1,609件のレビューの著者は、プラットフォームがこの質問をする前に登録して回答が記録されていないので、同意しないと答えた人とともに、同意していない者として扱われる。

アシスタントが読むのは436 of 3,000件のレビューであり、これらは著者が同意したレビューである。アシスタント自身によるcrm.learnersへのリクエストは、ポリシーの理由を付けて拒否される。セミジョインによるそのテーブルの読み取りはレイヤーに属するものであり、ユーザーに属するものではないからである。

実践ルール: すべての行フィルタは、SQL ビルダーを使って判断の値から構築し、レイヤーが認識しないフィルタの形や列はすべて拒否する。不明な同意は同意なしとして扱う。フィルタがユーザーの読めないテーブルを必要とする場合は、ユーザーのアクセス権を広げるのではなく、サブクエリの中でレイヤー自身のアクセス権を使って読む。

すべての列を行フィルタで保護する

最終変更:版2026.11.27

行フィルタはサブクエリのWHEREに置かれ、ユーザーのクエリがそのサブクエリを包む。そのため、DuckDBはまずフィルタを適用すると考えたくなる。しかしSQLは評価順序を保証せず、オプティマイザは条件をもっとも安価になる位置へ移す。キャストのように失敗しうるユーザーの条件が、フィルタで除外される行に対して実行されることがある。しかも汎用的なエラーであっても安全ではない。クエリが失敗したという事実が、ユーザーに見せてはならない行について何かを伝えてしまうからである。

PostgreSQLのドキュメントはこの漏えいを明示している。引数次第で失敗しうる関数は、ビューの行フィルタより先に実行されると、見えない行についての重要な情報を明らかにしうる。PostgreSQLでは、security_barrierを指定したビューは「悪意をもって選ばれた関数や演算子に、ビューの処理が終わるまで行の値が渡されること」を防ぎ、先に実行できるのはLEAKPROOFを指定した関数だけである(PostgreSQL 18, Rules and Privileges)。DuckDBにはどちらもない。

そこで本層は、順序が結果に影響しないようにする。クエリが読む列はすべて、CASE WHEN <row filters> THEN <value> ENDの形でサブクエリから出力される。これは講師の書き換えと同じである。こうすると、ユーザーの条件はフィルタの結果に依存する。DuckDBがどれを先に評価しても、フィルタで除外される行では、すべての列がNULLに見える。

lib.enforce.order_casesは、本層が書き出すフィルタの形を一つずつ検査する。対象は、サポート担当者の等価条件、講師のINリスト、コースアシスタントの同意セミ結合である。各ケースでは、フィルタ対象のテーブルをコピーする。このときbodyには、フィルタが残す行に数字を、除外する行にテキストを入れる。続いてbodyを数値にキャストするクエリを実行する。このキャストが失敗するのは、除外された行の値が見えた場合だけである。

row-filter-order.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""Runs the evaluation-order test for each filter shape the layer writes, with the filter in a WHERE alone and as the layerwrites it. The prose's point rests on the consent semi-join's two lines, and on the count at the end."""from lib.enforce import order_cases# The evaluation-order regression test, lib.enforce.order_cases, which chapter 10's CI runs on every DuckDB upgrade.# For each shape of row filter the layer writes, it takes a real user's filter and a copy of the filtered table whose# `body` holds digits in the rows the filter keeps and text in the rows it drops. A query that casts `body` to a number# fails only if the cast sees a dropped row's value. It runs over the filter in a WHERE alone, and over the layer's# subquery.cases = order_cases()for case in cases:    for form, safe in [("with the filter in WHERE only", case["safe_with_where_only"]),                       ("as the layer writes it", case["safe_as_written"])]:        print(f"{case['shape']}, {form}: the cast {'never saw' if safe else 'saw'} a dropped row's value")print("filter shapes the layer's subquery keeps safe:", f"{sum(case['safe_as_written'] for case in cases)} of {len(cases)}")
出力python row-filter-order.py
equality, with the filter in WHERE only: the cast never saw a dropped row's value
equality, as the layer writes it: the cast never saw a dropped row's value
IN list, with the filter in WHERE only: the cast never saw a dropped row's value
IN list, as the layer writes it: the cast never saw a dropped row's value
consent semi-join, with the filter in WHERE only: the cast saw a dropped row's value
consent semi-join, as the layer writes it: the cast never saw a dropped row's value
filter shapes the layer's subquery keeps safe: 3 of 3

各列を保護することが、同意セミ結合を安全に保つ。フィルタをWHEREだけに置いた場合、等価条件とINリストは安全だったが、同意セミ結合は安全ではなかった。DuckDBは、著者が同意していないレビューに対してもキャストを実行したのである。本層の書き方では、3 of 3のフィルタの形がいずれも、除外された行からキャストを遠ざける。最初の二つは、2.0.0ではオプティマイザの選択によって安全だったにすぎず、何らかの保証があったわけではない。したがって、このテストはアップグレードのたびに実行する。この保護の代償は、クエリが読む列ごとにフィルタを再び評価することである。

実践ルール: フィルタが除外する行にユーザーの条件を触れさせないために、エンジンの評価順序に頼ってはならない。ユーザーのクエリが読めるすべての値を行フィルタに依存させ、エンジンをアップグレードするたびに各フィルタの形をテストする。PostgreSQLのsecurity_barrierビューのように、エンジンに固有のバリアがある場合は、それも併用する。

クエリを実行して誰に何が見えるかをテストする

最終変更:版2026.11.27

第5章では、誰に何が見えるかを表す lib.policy.WHO_SEES_WHAT を使ってポリシーを検査する。これは requests のリストであり、各 requests には、レビュー担当者が期待する決定が付いている。この検査で確かめられるのは決定であり、ユーザーが実際に受け取るものではない。受け取るものは、書き換え、マスクの SQL、データにも左右される。lib.enforce.observe は、各ケースをそのケースのユーザーとして層に通し、返ってきたものを保存されているものと比較する。比較するのは、行数と、どの列が異なるかである。ケースが決定と一致するのは、次の三つの条件がすべて満たされる場合である。ユーザーが拒否されるのは、ケースがそう示している場合に限る。保存されている行数より少ない行を受け取るのは、ケースが行フィルタを期待している場合に限る。値が変更された列があるのは、ケースがマスクを期待している列に限る。

who-sees-what-in-queries.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""Runs chapter 5's who-sees-what cases as queries and compares what each user gets with what is stored, then readsmarketing.audience, which has no metadata. The prose's points rest on the agreement count and on the two marketing lines."""from lib import pipelines, policyfrom lib.catalog import open_catalogfrom lib.enforce import Enforcer, agrees, observecatalog = open_catalog(["crm.learners", "learning.reviews", "billing.payments", "learning.enrollments", "learning.courses"])pipelines.run(catalog, "marketing_audience")          # a copy of learners' names and emails, with no metadata yetplatform = Enforcer(catalog)# Chapter 5's who-sees-what table, run as queries: what each user gets, against what's stored. A column is "changed"# when at least one value the user gets differs from the stored one.agreeing = 0for case in policy.WHO_SEES_WHAT:    got = observe(platform, case.user, case.table, case.columns, case.purpose)    who = case.user + (f" for {case.purpose}" if case.purpose else "")    if got is None:        print(f"{who}, {case.table}: denied")    else:        print(f"{who}, {case.table}: {got['rows']:,} of {got['stored']:,} rows, changed: {', '.join(got['changed']) or 'none'}")    agreeing += agrees(case, got)print("cases where what the user gets agrees with the decision:", f"{agreeing} of {len(policy.WHO_SEES_WHAT)}")# marketing.audience is a table marketing may read, but nobody has classified its columns, so the policy treats each# one as sensitive: marketing gets every row, and no value in any column.rows = platform.sql("select * from marketing.audience", "marketing-1").fetchall()# a column counts as shown when one of its values isn't None, which is what a redact mask returnsshown = sum(any(value is not None for value in column) for column in zip(*rows))print("marketing-1, marketing.audience, which has no metadata, rows:", f"{len(rows):,}")print("marketing-1, marketing.audience, which has no metadata, columns with a value:", f"{shown} of {len(rows[0])}")
出力python who-sees-what-in-queries.py
agent-a05, crm.learners: 1,581 of 5,000 rows, changed: none
agent-a05, billing.payments: denied
instructor-17, learning.reviews: 69 of 3,000 rows, changed: body
instructor-17, crm.learners: denied
marketing-1, crm.learners: 1,861 of 5,000 rows, changed: phone
finance-1, billing.payments: 17,562 of 17,562 rows, changed: card_number
analyst-1, billing.payments: 17,562 of 17,562 rows, changed: card_number
analyst-1, crm.learners: 5,000 of 5,000 rows, changed: email, notes
analyst-1, learning.reviews: 3,000 of 3,000 rows, changed: body
analyst-1 for ai-training, learning.reviews: 436 of 3,000 rows, changed: body
assistant-1, learning.reviews: 436 of 3,000 rows, changed: body
someone-else, crm.learners: denied
cases where what the user gets agrees with the decision: 12 of 12
marketing-1, marketing.audience, which has no metadata, rows: 1,829
marketing-1, marketing.audience, which has no metadata, columns with a value: 0 of 5

ユーザーが受け取るものが決定と一致するケースは 12 of 12 である。EMEA のサポート担当者は、自分の地域の学習者を保存されたとおりに受け取る。マーケティングは、同意済みで有効な学習者を、phone を変更した状態で受け取る。アナリストはすべての学習者を、email と notes を変更した状態で受け取る。最後の二行は marketing.audience を扱う。これはパイプラインが書き込むもので、まだ誰も分類していない。マーケティングはこれを読むことができ、1,829 行を受け取る。そのうち値を持つ列は 0 of 5 である。ポリシーが、未分類の列を機微なものとして扱うためである。

このテストが価値を発揮するのは、変更があったときである。たとえば、サポートがチケットに対応できるように、プルリクエストが analyst-1 を EMEA のサポートグループに追加するとする。これは governance/users.toml への 2 行の変更であり、サポートの行フィルタが必要とするグループと地域である。次のコードはこの変更をメモリ上で行い、同じケースをそれに対して実行する。

group-change-caught.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""Makes one change to the users file in memory, runs the who-sees-what cases again, and runs chapter 5's decision checkon the same change. The prose's points rest on the lines that say which cases fail, and on the decision count."""from lib import policyfrom lib.catalog import open_catalogfrom lib.enforce import Enforcer, agrees, observe# A pull request changes one user in governance/users.toml, in two lines: analyst-1 joins support, with the region# support's row filter needs, EMEA, to help with tickets.# the users file as a document, changed here in memory and not on diskdata = policy.data_document()data["platform"]["users"]["analyst-1"] = {"groups": ["data-science", "support"], "region": "emea"}platform = Enforcer(open_catalog(["crm.learners", "learning.reviews", "billing.payments"]),                    rego=policy.interpreter(data=data))# The who-sees-what cases, run as queries with the change in place. The cases are unchanged: they say what each# user should get, and the change was meant to touch support tickets only.failing = 0for case in policy.WHO_SEES_WHAT:    got = observe(platform, case.user, case.table, case.columns, case.purpose)    # got is None when the user is denied, which agrees only with a case that expects a denial    if not agrees(case, got):        failing += 1        who = case.user + (f" for {case.purpose}" if case.purpose else "")        print(f"fails, {who}, {case.table}, rows: {got['rows']:,} of {got['stored']:,}")        print(f"fails, {who}, {case.table}, columns changed: {', '.join(got['changed']) or 'none'}, "              f"expected: {', '.join(case.masked)}")print("cases that fail:", f"{failing} of {len(policy.WHO_SEES_WHAT)}")# Chapter 5's table, which checks the decisions themselves, on the same change.decisions = [policy.decide(policy.request(c.user, c.table, c.columns, c.purpose), platform.rego) for c in policy.WHO_SEES_WHAT]print("cases that fail as decisions:", f"{sum(not policy.matches(c, d) for c, d in zip(policy.WHO_SEES_WHAT, decisions))} of {len(decisions)}")
出力python group-change-caught.py
fails, analyst-1, crm.learners, rows: 1,581 of 5,000
fails, analyst-1, crm.learners, columns changed: none, expected: email, notes
fails, analyst-1, learning.reviews, rows: 3,000 of 3,000
fails, analyst-1, learning.reviews, columns changed: none, expected: body
fails, analyst-1 for ai-training, learning.reviews, rows: 436 of 3,000
fails, analyst-1 for ai-training, learning.reviews, columns changed: none, expected: body
cases that fail: 3 of 12
cases that fail as decisions: 3 of 12

この変更では 3 of 12 件のケースが失敗するが、チケットに関するものは一つもない。失敗する 3 件はすべて、アナリストによる学習者とレビューの読み取りである。crm.learners では、アナリストは列が一つも変更されていない 1,581 of 5,000 行を受け取る。サポートの地域フィルタがアナリストに適用される一方で、ポリシーの個人情報列のマスクはサポート以外のユーザーにしか適用されないため、すべてのメールアドレスとメモが保存されたまま渡される。レビューのテキストは、データサイエンティストには本来まったく読めないか、AI の学習用に連絡先を除去した状態でしか読めないが、そのまま渡される。第5章の決定レベルの表も同じケースで失敗し、その結果は 3 of 12 である。この章のテストは、アナリストが何を受け取るかを示す。

実践ルール: ポリシー、ユーザーファイル、メタデータ、層のいずれかを変更するたびに、誰に何が見えるかのケースを層に通すクエリとして実行し、一つでも一致しないケースがあればビルドを失敗させる。失敗したケースは、ポリシーまたはユーザーファイルを変更して直す。ケースを変更するのは、ユーザーが受け取るべきものが変わったことにデータの所有者が同意した場合に限る。

レポートで小さなグループを非表示にする

最終変更:版2026.11.31

行フィルタとマスクは、ユーザーがどの行と値を見られるかを決める。集計はもう一つの経路である。少数の人々についての件数や平均は、その人々を描写してしまう。通常の防御策は最小グループサイズであり、これを下回る報告グループは非表示にする。この数値は測定値ではなく経験則である。米国のメディケア・メディケイドサービスセンター(Centers for Medicare & Medicaid Services)の公開データ利用契約の一つは11を定めており、さらに「11未満のセルが表示される結果になるのであれば、パーセンテージやその他の数式を用いてはならない」と付け加えている(CMS-R-0235L)。このプラットフォームも同じ最小値 11 を用い、それを governance/enforcement.toml に保持する。そこでは変更がポリシー変更と同様にレビューされ、lib.enforce.minimum_group_size がそれを読み込む。

講師には、コースと学習者の国ごとに学習者数と平均進捗を示す日次のコースレポートが提供される。このレポートは、講師が読むことを許されていない国の情報を読むジョブによって作成される。講師は、自分のコースの受講登録を、それぞれの進捗とともに読むことができる。この二つを組み合わせると、instructor-17 のレポートは次のようになる。

small-groups-difference.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""Builds instructor-17's daily course report, counts its cells under the minimum and its cells of one learner, and matcheseach cell of one against the enrollments the instructor may read. The prose's points rest on the cell and lookup counts, andon the last line, which shows the differencing."""from lib.catalog import open_catalogfrom lib.enforce import Enforcer, minimum_group_sizeplatform = Enforcer(open_catalog(["crm.learners", "learning.courses", "learning.enrollments"]))minimum = minimum_group_size()print("minimum group size:", minimum)count = lambda sql: platform.connection.sql(f"select count(*) from ({sql})").fetchall()[0][0]# The platform's daily course report for instructor-17: learners and average progress, per course and learner country.# The report job reads learners' countries, which instructors may not read.platform.connection.execute("""create view mine as    select e.course_id, e.progress_pct, e.enrolled_at::date as day, l.country    from learning.enrollments e join crm.learners l using (learner_id)    where e.course_id in (select course_id from learning.courses where instructor_id = 17)""")platform.connection.execute("""create view report as    select course_id, country, count(*) as learners, avg(progress_pct) as progress from mine group by all""")print("cells in the report:", count("from report"))# the minimum is the threshold: a cell with fewer learners than it is held backprint("cells under the minimum:", count(f"from report where learners < {minimum}"))# instructor-17 may read their courses' enrollments, with each one's progress. A cell of one learner, matched on its# progress, names that learner's country.# what instructor-17 may read: enrollments with each one's progress, and no countryseen = platform.sql("select course_id, progress_pct from learning.enrollments", "instructor-17").to_arrow_table()platform.connection.register("seen", seen)print("cells of one learner:", count("from report where learners = 1"))print("learners a cell of one names:", count("""from report as cell where learners = 1 and (select count(*) from seen    where seen.course_id = cell.course_id and seen.progress_pct = cell.progress) = 1"""))print("cells shown with the minimum:", count(f"from report where learners >= {minimum}"))# The minimum doesn't stop differencing. An enrollment that arrives alone in its course on its day, in a cell already# shown, raises that cell by one in the next day's report, and the instructor sees which enrollment arrived.# an enrollment alone in its course that day, whose country already has the minimum on earlier daysrevealed = count(f"""from mine as m    where (select count(*) from mine as o where o.course_id = m.course_id and o.day = m.day) = 1      and (select count(*) from mine as o where o.course_id = m.course_id and o.country = m.country and o.day < m.day) >= {minimum}""")print("learners whose country the daily report reveals anyway:", f"{revealed} of {count('from mine')}")
出力python small-groups-difference.py
minimum group size: 11
cells in the report: 63
cells under the minimum: 51
cells of one learner: 6
learners a cell of one names: 3
cells shown with the minimum: 12
learners whose country the daily report reveals anyway: 92 of 482

1人だけのセルは、その学習者を見つけ出せる人に対して、その学習者の国を明かしてしまう。講師にはそれができる。セルの平均進捗を自分の受講登録と照合すれば、3 人の学習者が正確に特定される。このレポートには 63 個のセルがあり、そのうち 51 個が最小値を下回り、6 個がそれぞれ学習者1人を含んでいる。

最小値を適用すると、12 個のセルが表示され、これらの照合はいずれも成立しなくなる。ただし、最小値は差分攻撃を防げない。ある日、あるコースにただ1件の受講登録が届き、それがすでに表示されているセルに加わると、翌日のレポートではそのセルの値が1増える。講師はどの受講登録が届いたかを知る。これにより 92 of 482 人の学習者の国が明らかになる。

差分攻撃、すなわち連続するレポートの比較は、Denning、Denning、Schwartzがトラッカー(tracker)と呼んだ攻撃である。彼らは「小さなクエリ集合の侵害は、実際にはほとんど常に、トラッカーと呼ばれる特徴的な式の助けを借りて達成できる」ことを示した(Denning et al., 1979)。

Snowflakeはエンジン内で最小グループサイズを強制しているが、そのポリシーは「悪意ある者が意図的なクエリによって機微なデータを得る可能性がないことを保証するものではない」と述べている(Snowflake aggregation policies)。差分攻撃に対しては、しきい値を引き上げるのではなく、差分プライバシー(differential privacy)のようにノイズを加えることを推奨する(Dwork and Roth, 2014)。これについては Privacy Engineering for Data Teams で扱っている。

実践ルール: governance/enforcement.toml に定めた最小値を下回る報告グループはすべて非表示にし、最小値は1人の個人を特定する検索に対する保護であって、差分攻撃に対する保護ではないと位置づける。読み手が読むことを許されていない属性でレポートを内訳に分け、背後の行を見られる読み手に送ってはならない。講師向けの国別レポートは、国を引き当てるための対応表になってしまう。内訳を取り除くか、ノイズを加えた後にのみ報告する。

同じポリシーを、それを強制するエンジンに渡す

最終変更:版2026.11.27

本番環境では、強制はすべてのツールがクエリを発行するエンジンで行うべきである。Saltzer と Schroeder の完全媒介(complete mediation)の原則は「あらゆるオブジェクトへのあらゆるアクセスは、権限を確認されなければならない」と述べており(Saltzer and Schroeder, 1975)、あるツールで強制し別のツールで強制しないポリシーはこの原則を満たさないからである。オープンソースの分散 SQL エンジンである Trino は、プラグインを通じて Open Policy Agent(OPA)からアクセス制御を受け取ることができる。5 章では、同じポリシーで両方をまかなえるように、プラットフォームのリクエストをこのプラグインのリクエストと同じ形に作った。Trino 484 が提供するアクセス制御はファイルベース、OPA、Ranger であり、Cedar 向けのものはない(Trino 484, Security)。

このプラグインは、OPA に対して別々の URI で別々の問いを送る(Trino 484, OPA access control)。

  • 操作を許可するかどうか。たとえば SelectFromColumns であり、答えは真偽値 allow で返る。
  • テーブルに対する行フィルタ、すなわち GetRowFilters。OPA は {"expression": ...} のリストで答え、各式は「本質的に追加の WHERE 句として振る舞う」。この URI は省略可能であり、設定されていなければ Trino は行フィルタを適用しない。
  • 1 つの列に対する列マスク、すなわち GetColumnMask。複数の列をまとめて扱う場合は opa.policy.batch-column-masking-uri を使う。「1 つの列に対して返せる列マスクは 1 つだけである」。

操作名と、各リクエストがテーブルや列をどこに置くかは、タグ 484 のプラグインのソースにある(OpaAccessControl.java、OpaHighLevelClient.java)。ドキュメントのバッチマスク用ポリシーは filterResources[i].catalogName を読むが、同じドキュメントのリクエスト例ではこれらのフィールドが .column の下に入れ子になっており、掲載されたままでは一致しない。これらの形で組み立てたリクエストを、そのポリシーに渡す。

trino-requests.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""Builds requests in the shape Trino 484's OPA plugin sends, and runs them through the platform's policy. The prose'spoints rest on the allow lines, which the example asserts are False, and on the GetRowFilters and GetColumnMask lines."""import jsonfrom lib import metadata, policyfrom lib.enforce import row_filter# The platform's policy, with a support agent added before anyone set their region (chapter 5's missing-region case).data = policy.data_document()data["platform"]["users"]["agent-new"] = {"groups": ["support"]}rego = policy.interpreter(data=data)described = metadata.load()def trino_request(user: str, operation: str, resource: dict | None = None) -> dict:    """A request in the shape Trino 484's OPA plugin sends (OpaAccessControl, OpaHighLevelClient)."""    action = {"operation": operation} | ({"resource": resource} if resource else {})    return {"context": {"identity": {"user": user, "groups": []}, "softwareStack": {"trinoVersion": "484"}}, "action": action}# Trino asks `allow` about every operation: ExecuteQuery before any query runs, AccessCatalog for each catalog it names.for operation, resource in [("ExecuteQuery", None), ("AccessCatalog", {"catalog": {"name": "platform"}})]:    allowed = policy.decide(trino_request("agent-a05", operation, resource), rego)["allow"]    # allow admits only SelectFromColumns, so Trino's checks before any query are denied    assert allowed is False    print(f"allow, {operation}, agent-a05:", allowed)# GetRowFilters names a table. The policy's row_filters rule on its own skips `allow` and its missing-attribute guard,# so for agent-new it returns no filter, which Trino reads as no filtering. The answer comes from the decision instead,# for the same read asked as SelectFromColumns: its filters in Trino's SQL, or a filter that keeps no rows.for user, schema, table in [("agent-a05", "support", "tickets"), ("instructor-17", "learning", "reviews"),                            ("agent-new", "support", "tickets")]:    request = trino_request(user, "GetRowFilters", {"table": {"catalogName": "platform", "schemaName": schema, "tableName": table}})    print(f"GetRowFilters, {user}, {schema}.{table}, the rule alone:",          json.dumps(policy.evaluate(rego, "data.platform.access.row_filters", request)))    decision = policy.decide(policy.request(user, f"{schema}.{table}", []), rego)    columns = {c.name: "" for c in described[f"{schema}.{table}"].columns.values()}    # no table alias: Trino applies the filter to the table itself, as a WHERE clause on it    filters = [{"expression": row_filter(rule, columns, table=None).sql("trino")} for rule in decision["row_filters"]]    # a denied read gets a filter that keeps no rows    print(f"GetRowFilters, {user}, {schema}.{table}, answered:", json.dumps(filters if decision["allow"] else [{"expression": "false"}]))# GetColumnMask names one column, under action.resource.column. The policy reads the columns of a SelectFromColumns# request instead, so it masks nothing here until the request is translated.column = {"catalogName": "platform", "schemaName": "crm", "tableName": "learners", "columnName": "email", "columnType": "varchar"}decision = policy.decide(trino_request("analyst-1", "GetColumnMask", {"column": column}), rego)print("GetColumnMask as sent, analyst-1, crm.learners.email:", json.dumps(decision["column_masks"]), decision["reasons"][0])translated = policy.request("analyst-1", "crm.learners", [column["columnName"]])print("GetColumnMask translated, analyst-1, crm.learners.email:", json.dumps(policy.decide(translated, rego)["column_masks"]))
出力python trino-requests.py
allow, ExecuteQuery, agent-a05: False
allow, AccessCatalog, agent-a05: False
GetRowFilters, agent-a05, support.tickets, the rule alone: [{"column": "support_region", "equals": "emea"}]
GetRowFilters, agent-a05, support.tickets, answered: [{"expression": "support_region = 'emea'"}]
GetRowFilters, instructor-17, learning.reviews, the rule alone: [{"column": "course_id", "in": [2, 75, 80, 87, 103, 134]}]
GetRowFilters, instructor-17, learning.reviews, answered: [{"expression": "course_id IN (2, 75, 80, 87, 103, 134)"}]
GetRowFilters, agent-new, support.tickets, the rule alone: []
GetRowFilters, agent-new, support.tickets, answered: [{"expression": "false"}]
GetColumnMask as sent, analyst-1, crm.learners.email: {} GetColumnMask is not an operation this policy allows
GetColumnMask translated, analyst-1, crm.learners.email: {"email": "pseudonymize"}

このポリシーをそのまま Trino に向けると、Trino が最初に行うチェックが拒否される。allow が許可するのは SelectFromColumns だけだからである。allow は、クエリの実行前に Trino が問い合わせる ExecuteQuery に対して、また AccessCatalog に対して false になる。

row_filters ルールは操作を検査しないので GetRowFilters に答えられるが、単独では allow と 5 章の属性欠落ガードを飛ばしてしまう。まだ地域を持たないサポート担当者 agent-new に対しては [] を返し、Trino はこれをフィルタなしと解釈する。したがって答えは、同じ読み取りに対する決定、つまり SelectFromColumns として問い合わせた決定から得なければならない。その決定が許可する場合は、書き換えが使うのと同じ row_filter が Trino の SQL で書いたフィルタを返す。読み取りを拒否する場合は [{"expression": "false"}] を返し、これは行を 1 つも残さない。

GetColumnMask は列を action.resource.column の下に指定するが、ポリシーは SelectFromColumns リクエストの列を読む。そのため、送ったままでは何もマスクされず、ポリシーが操作を拒否する。変換すると pseudonymize が適用される。本番では、これらの変換、allow のチェック、Trino の SQL は、ポリシーと並べて Rego モジュールに置き、OPA が Trino に直接答えられるようにする。ここでは OPA サーバーは動かないため、コードはそのモジュールが返すべきものだけを示す。もう 1 つ、Trino に直接対応づく要素がある。同意フィルタは crm.learners を読むが、アシスタントはこれを読めない。Trino ではフィルタに実行ユーザーとして identity を持たせることができ、「リクエストしたユーザーが見えない列を、フィルタが対象にできる」。

OPA の Compile API は 1.9.0 以降、部分評価によってポリシーから SQL の WHERE 句を書き出すこともできる(OPA v1.9.0、Data filtering with OPA)。ただし OPA サーバーが必要であり、例では動かしていない。

実践ルール: 強制は、すべてのツールがクエリを発行するエンジンに置き、そのエンジンと、この章のような書き換えの両方に同じ 1 つのポリシーを適用する。Trino では、プラグインが問い合わせるすべての操作に答え、行フィルタと列マスクの両方の URI を設定し(設定しなければフィルタもマスクも適用されない)、行フィルタは読み取りを許可する決定からのみ返す。テストは、ドキュメントのポリシー例ではなく、プラグインのソースにあるリクエストの形から作る。

利用者に代わって問い合わせる

最終変更:版2026.11.31

ウェアハウスから質問に答えるアシスタントは、このレイヤの利用者がもう一つ増えたものにすぎないが、選択すべき点がある。そのクエリはだれのIDを持つのか、という点である。講座アシスタントのassistant-1は、同意した受講者のレビューに対する独自のアクセス権を持っている。人に答えるときは、その人としてクエリを実行しなければならない。そうすれば、答えにはその人自身が読めるものだけが含まれる。言語モデルを使うアプリケーションに関するOWASPのガイダンスも同じことを述べている。「ある操作が許可されるかどうかをLLMに判断させるのではなく、下流のシステムで認可を実装せよ」(OWASP LLM06:2025)。アシスタント自体はData Assistants in Practiceで扱う。この節の対象は、そのクエリである。

instructor-17がアシスタントに自分の講座のレビューの状況を尋ねると、アシスタントはクエリを書く。ツールは、サインイン済みのセッションからユーザーを取得する。モデルや会話から取得することはないため、どのようなプロンプトでも、クエリがだれとして実行されるかを変えることはできない。

assistant-on-behalf.py Python 3.12.15 · duckdb 2.0.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · regopy 1.5.2 · sqlglot 30.33.0 合格
"""Runs the course assistant's review query as instructor-17 and as assistant-1, through a tool that takes the user fromthe signed-in session. The prose's point rests on the reviews-behind-it lines for each user."""from lib import policyfrom lib.catalog import open_catalogfrom lib.enforce import Enforcerplatform = Enforcer(open_catalog(["crm.learners", "learning.reviews"]))courses = set(policy.data_document()["platform"]["instructor_courses"]["17"])     # instructor-17's own coursesdef query_tool(session_user: str):    """The tool the course assistant calls to query the warehouse. The model writes the SQL; the user it runs as comes    from the signed-in session, never from the model or the conversation."""    # the user is the session's; the SQL is all the model contributes    return lambda sql: platform.sql(sql, user=session_user).fetchall()# instructor-17 asks the assistant how their courses' reviews look. The assistant writes this query.question = "select course_id, count(*) as reviews, round(avg(rating), 2) as rating from learning.reviews group by all"for runs_as in ["instructor-17", "assistant-1"]:    answer = query_tool(runs_as)(question)    print(f"run as {runs_as}, courses in the answer:", len(answer))    print(f"run as {runs_as}, reviews behind it:", sum(reviews for _, reviews, _ in answer))    # each answer row is (course, reviews, rating), so row[0] is the course    mine = [row for row in answer if row[0] in courses]    print(f"run as {runs_as}, instructor-17's reviews behind it:", sum(reviews for _, reviews, _ in mine))
出力python assistant-on-behalf.py
run as instructor-17, courses in the answer: 6
run as instructor-17, reviews behind it: 69
run as instructor-17, instructor-17's reviews behind it: 69
run as assistant-1, courses in the answer: 130
run as assistant-1, reviews behind it: 436
run as assistant-1, instructor-17's reviews behind it: 7

クエリがだれのIDを持つかによって、答えの範囲が決まる。アシスタント自身のIDを使うのは、どちらの向きにも誤りである。講師に見る権限のないものを見せる一方で、見る権限のあるものを隠してしまう。instructor-17として実行すると、答えは6件の講座と69件のレビューを対象とする。アシスタントとして実行すると、対象は130件の講座となり、その大半は他の講師の講座である。その講師自身のレビューは、AI学習に同意した著者のものに限られ、7件しか含まれない。検索でも同様である。管理対象のテキストに基づいて回答するアシスタントには、「権限を考慮したベクトルストアおよび埋め込みストア」が必要になる(OWASP LLM08:2025)。

実践ルール: アシスタントのクエリは、それが答える相手として実行し、そのIDは相手の認証済みセッションから取得して、その人に対するレイヤの判定を適用させる。アシスタント自身のIDは、特定の誰のためでもない作業にだけ使う。たとえば、講座ページ向けに同意済みレビューを毎晩要約する作業である。そのときは、両方のIDを監査ログに記録する。アシスタントの学習セットを作成する者は、第9章のとおり、自分自身として、目的をai-trainingとしてクエリを実行する。

本番環境で何がうまくいかなくなるか

最終変更:版2026.11.27

強制層が失敗するのは、誰もテストしていない読み取りを通してしまうときであり、こうした失敗の多くは正しい答えのように見える。

  • スキーマにないテーブルでは SELECT * がすり抜ける。 qualify は星印を展開しないまま残し、何のエラーも出さない。カタログにないテーブルはすべて拒否し、カタログが変わるたびにスキーマを再構築する。
  • 集計が小さなグループを漏らす。 1 件だけのセルはその構成員を特定する。また、レポートの例で示したように、レポート間の差分は、どの最小値を満たすセルであってもその構成員を特定してしまう。最小値を設定し、読み手が読めない属性による内訳は取り除く。
  • 結合とコピーがマスクした列を元に戻す。 marketing.audience を書き出すパイプラインのように、完全なアクセス権を持つパイプラインは、email を、そのテーブル自身の分類だけで保護されたテーブルへコピーする。分類されていなければ、誰に何が見えるかのテストで示したように、そのコピーは全員から隠される。誤って internal に分類されると、そのテーブルを読める誰にでも見える。第 4 章では、これを捕捉するために分類を系統に沿って伝播させる。マスクされていない列は、結合によっても個人を再識別する。Sweeney は、1990 年の国勢調査データで、米国人口の 87% が郵便番号、性別、生年月日によって一意になりうると見いだした(Sweeney, 2002)。Golle は数え直し、同じ 1990 年のデータで 61%、2000 年のデータで 63% を見いだした(Golle, 2006)。Rocher らは、国勢調査データに当てはめたモデルから、15 個の人口統計属性があればマサチューセッツ州の人の 99.98% が一意になると推定している(Rocher et al., 2019)。
  • ファイルの直接読み取りは書き換えを迂回する。 read_parquet、FROM 内のパス、テーブル関数は、テーブル名を指定せずにデータを読む。書き換えの中でこれらを拒否し、enable_external_access を無効にする。無効にすると、DuckDB はそれを再び有効にできない。「Cannot enable external access while database is running」。lock_configuration は、ほかのすべての設定を層が残したままの状態に固定する。これは接続を作成するときではなく、層の接続の設定が完全に終わってから設定する(Securing DuckDB)。第 8 章が、その後で DuckDB のクエリログを開始するためである。ストレージ上のウェアハウスのファイルを読める者は SQL を必要としないので、ストレージの権限も強制の一部である。
  • 識別子の大文字小文字が、名前の一致を決める。 名前を正規化せずに照合する層では、"LEARNERS" が生のテーブルに到達してしまう。DuckDB はこれを learners に解決する。これは最初の節で示したとおりである。名前を照合する前に、クエリを実行するエンジンの方言で正規化する。
  • エラーメッセージが値を出力する。 DuckDB のキャストエラーには値が含まれる。テーブルの書き換えによってそれはマスクされた値になり、各列のゲートによって破棄された行は手の届かないままになるが、何かが止めない限り、メッセージは利用者に届く。サービスの境界では lib.enforce.answer のように汎用的なエラーを返し、エンジンのメッセージは、プラットフォームチームだけが読める場所に記録する。この場所は、第 8 章が値を含めないようにしている監査ログとは別である。PostgreSQL は、セキュリティバリアの内側でも、実行計画と所要時間は隠れた通信路のままであると警告している(PostgreSQL 18, Rules and Privileges)。
  • DuckDB はセキュリティ境界ではない。 「DuckDB は、シェルやスクリプトインタプリタとほぼ同じように、実行するユーザーの完全な権限で SQL を実行する」(Securing DuckDB)。同じプロセス内での書き換えがデータを守るのは、利用者がほかの経路で DuckDB に到達できない間だけである。この章の層は、Trino などのエンジンが強制する内容をテストしたモデルとして扱い、本番ではそちらで強制する。

この章で決めたこと

最終変更:版2026.11.27
  • 適用の対象は列ではなくテーブルである。 カタログの各テーブルは、決定から生成されたサブクエリに置き換えられる。列参照の書き換えは、それが情報を漏らすことを示すためにだけ残してある。
  • このレイヤーは安全側に倒れる(フェイルクローズド)。 ソースとして許可されるのは、カタログテーブルの許可リスト、スコープ内の CTE、およびサブクエリである。副作用のある関数、パラメータ、単一のクエリ以外のものは拒否する。クエリが読まない列は NULL 型になり、読む列は行フィルタによって制御される。
  • ユーザーが受け取るエラーは answer が返す汎用的なもの1種類だけであり、DuckDB のメッセージはプラットフォームチームに送られる。
  • マスクの SQL は1か所にまとめる。 ポリシーはマスクの名前を指定し、lib.enforce がその SQL を書く。仮名は、このレイヤーだけが持つ秘密鍵をパラメータとして渡して生成する。
  • 行フィルタはデータから組み立てる。 値はリテラルとして埋め込む。同意の確認は、このレイヤーが自身のアクセス権で実行するセミジョインであり、同意が不明な場合は不同意として扱う。
  • 誰に何が見えるかはクエリとしてテストする。 第5章のケースは、変更のたびにこのレイヤーを通して実行される。
  • レポートでは、最小グループサイズ未満のグループを伏せる。 最小グループサイズは governance/enforcement.toml で 11 と定められている。また、読み手が読めない属性による内訳は出さない。
  • アシスタントは、回答する相手の本人として問い合わせる。 その本人の ID はセッションから取得する。
  • 本番ではエンジンが適用を担う。 同じポリシーから生成した Trino と OPA を使う。両方の URI を設定し、行フィルタは許可された決定からのみ返す。レイヤーの安全性は、そのテストの質を超えることはない。

この版における本章

第2026.11.31版2026年11月19日時点で例が通過この章の16 例件のうち16件が合格

英語版の書籍(版2026.11.31)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全10章中の第6章: クエリへのポリシーの強制

  1. クエリが読むすべてのテーブルと列を見つける
  2. Allow only catalog tables, CTEs and subqueries
  3. Masking column references leaks
  4. 各テーブルをフィルタ済みでマスク済みのサブクエリに置き換える
  5. Write each mask as SQL in one place
  6. 判断のデータから行フィルタを構築する
  7. すべての列を行フィルタで保護する
  8. クエリを実行して誰に何が見えるかをテストする
  9. レポートで小さなグループを非表示にする
  10. 同じポリシーを、それを強制するエンジンに渡す
  11. 利用者に代わって問い合わせる
  12. 本番環境で何がうまくいかなくなるか
  13. この章で決めたこと

ページの先頭に戻るすべての章