監査と証跡
読了まで約67 分分、9 節 節の 9 例 例。
本章を終えると、すべてのアクセス判定とクエリについて、値を含まず、改変があれば分かるように連鎖させた監査ログを保持できるようになる。ログは判定が行われる場所で書く。さらに、ログの先頭(head)、すなわち最後のレコードの番号とハッシュを、ログの書き込み側が変更できない場所に書き留める。これにより、その head までのどのレコードに対する編集や削除も検出できる。また、ポリシーが変更された後に過去の判定を説明する方法、ログをクエリエンジン自身が記録した実行内容と突き合わせる方法、ログとポリシーからアクセスレビューと証跡レポートを、誰でも再実行できるコードとして生成する方法も扱う。
本書が統制の対象とするオンライン学習プラットフォームで、サポート責任者が先週なぜアナリストがレビュー文を読めたのかを尋ねたとき、あるいは監査人がアクセス規則が機能していることの提示を求めたとき、記録に基づいて答えられる者はいない。第5章ではプラットフォームのアクセスポリシーを Rego で書いた。第6章の強制レイヤである lib.enforce.Enforcer は、クエリが読むすべてのテーブルについてポリシーに判定を求め、判定が許可する内容だけを DuckDB が返すようにクエリを書き換える。このレイヤは、判定を適用した後にそれを忘れてしまう。明白な対策は、すべてのクエリの文面をログに残すことである。しかしそれでは、ポリシーが守っているものの複製をもう一つ作ってしまう。サポート担当者のクエリは WHERE 句に学習者のメールアドレスを含むことがあり、第7章では学習者のデータが渡ったすべての場所からその学習者を消去しなければならない。
本章の用語を、本書での用法に従って示す。監査ログとは、誰が、いつ、何を行い、結果がどうだったかの記録であり、後から誰かが確認できるように保持される。このプラットフォームの監査ログは、クエリごとに一つの判定レコードを持つ。ポリシーリビジョンとは、リクエスト以外に判定が依存したすべてのものを表すフィンガープリントである。ログが改ざん検知可能であるとは、ログへの変更を防ぐことはできないが、検出できることをいう。アクセスレビューは、各人が読めるものと実際に使っているものを比較する。証跡とは、統制が機能していることを示すレポートであり、画面から取得するのではなく、記録から生成される。
コードは、本書の共有モジュール lib.audit である。その Audited クラスは、第6章の Enforcer を変更せずにラップする。すべてのクエリについてレコードを書き、その後でレイヤにクエリを実行させる。ほとんどの例では、プラットフォームの1日分のクエリ lib.audit.DAY を再生する。これは 2026年10月1日の 13 件のクエリであり、サポート担当者、財務部門、コースアシスタント経由の講師、マーケティング部門、データサイエンティスト、アシスタント自身のアカウント、そしてプラットフォームが知らない一人のユーザーによるものである。例は DuckDB 2.0.0、sqlglot 30.33.0、regopy 1.5.2 で実行する。
この部分はまだ翻訳されていないため、英語で表示している。
Record every decision where it's made
An audit record is only as complete as what its writer knows. The query engine knows the SQL it ran, but not who asked or why. The policy knows its decision, but not the query. Only the enforcement layer holds all of it at once: the principal, meaning the user or program that asks, the tables and columns the query reads, each table's decision, and the SQL it hands the engine. That is where Open Policy Agent (OPA) writes its own record. OPA's decision logs hold events that describe policy queries, with the policy queried, its input, the bundle metadata, and other information that makes auditing and offline debugging possible (OPA, decision logs). Each event carries a decision_id, the path of the rule queried, the input, the result, a timestamp, and bundles[_].revision, the bundle's revision at evaluation. regopy, which runs the policy inside Python, returns the value of the query and nothing more, so the layer has to build every other field itself.
NIST's catalog of security controls gives a checklist for those fields. Control AU-3 asks that audit records establish six things: (a) what type of event occurred, (b) when it occurred, (c) where, (d) its source, (e) its outcome, and (f) the identity of the individuals, subjects or objects associated with it (NIST SP 800-53 Rev. 5).
lib.audit.Audited takes a catalog and a Log, the audit log's file. Its sql method takes the same arguments as Enforcer.sql, plus via, the assistant that sent it, when one did. It plans the query, asks the policy about every table the query reads, writes one record, and only then hands the rewritten query to DuckDB. So no query reaches DuckDB through the layer without a record, and when the record can't be written, the query doesn't run. Chapter 6 left this chapter one case: when the course assistant answers instructor-17, the query runs as the instructor, and both identities belong in the log. The assistant's query for instructor-17, and its attempt to put names to the ratings, each leave a record, showing what a record holds when two identities are involved:
1"""The course assistant's two queries, sent as instructor-17: one allowed, one denied, each recorded with both identities.2The point rests on the `user` and `via` lines of both records and on the denial in record 2."""3from lib import audit4from lib.catalog import open_catalog5from lib.enforce import Denied6from lib.platform import scratch78# Chapter 6's enforcement layer, wrapped so that every query it's given is recorded before DuckDB runs anything.9log = audit.Log(scratch() / "audit.jsonl")10platform = audit.Audited(open_catalog(["crm.learners", "learning.reviews"]), log)1112# instructor-17 asks the course assistant how their reviews look. The assistant writes the SQL; the query runs as the13# instructor, with the assistant recorded as the one that sent it.14question = "select course_id, count(*) as reviews, round(avg(rating), 2) as rating from learning.reviews group by all"15platform.sql(question, user="instructor-17", via="assistant-1").fetchall()1617# Then the assistant tries to put names to the ratings, which the instructor may not see. The denial is recorded before18# it's raised, so the script only needs to go on.19try:20 platform.sql("select l.full_name, r.rating from learning.reviews as r join crm.learners as l using (learner_id)",21 user="instructor-17", via="assistant-1").fetchall()22except Denied:23 pass2425for record in log.records():26 print(f"record {record['seq']}:")27 print(audit.show(record))
python decision-record.pyrecord 1:
seq: 1
event: query
time: 2026-10-01T09:00:00Z
catalog: platform
user: instructor-17
via: assistant-1
purpose: null
query: SELECT course_id, COUNT(*) AS reviews, ROUND(AVG(rating), ?) AS rating FROM learning.reviews GROUP BY ALL
outcome: allowed
denial: null
decision: {"table": "learning.reviews", "columns": ["course_id", "rating"], "allow": true, "row_filters": [{"column": "course_id", "in": [2, 75, 80, 87, 103, 134]}], "column_masks": {}, "reasons": ["instructor may read learning.reviews"]}
policy_revision: f761e4ad08d4...
rewritten_digest: 385c5cdabeae...
prev_hash: 000000000000...
record 2:
seq: 2
event: query
time: 2026-10-01T09:01:00Z
catalog: platform
user: instructor-17
via: assistant-1
purpose: null
query: SELECT alias_1.full_name, alias_2.rating FROM learning.reviews AS alias_2 JOIN crm.learners AS alias_1 USING (learner_id)
outcome: denied
denial: instructor-17 may not read crm.learners: no group of this user may read this table
decision: {"table": "crm.learners", "columns": ["full_name", "learner_id"], "allow": false, "row_filters": [], "column_masks": {}, "reasons": ["no group of this user may read this table"]}
decision: {"table": "learning.reviews", "columns": ["learner_id", "rating"], "allow": true, "row_filters": [{"column": "course_id", "in": [2, 75, 80, 87, 103, 134]}], "column_masks": {}, "reasons": ["instructor may read learning.reviews"]}
policy_revision: f761e4ad08d4...
rewritten_digest: null
prev_hash: 0d3e61eaadeb...
Record 1 covers AU-3's six items. event is the type, and time says when, in UTC with a Z, since control AU-8 asks for time stamps that "use Coordinated Universal Time" or state their offset; the examples take it from a fixed clock. catalog says where. user and via are the source: the query ran as instructor-17, and assistant-1 sent it. With the decision's table, they are the identities AU-3's item f asks for. query and the decision's columns say what was read, and outcome and the decision's allow, row_filters, column_masks and reasons say how it ended, down to the course IDs the row filter kept. The next sections explain policy_revision, rewritten_digest and prev_hash.
Record 2 is a denial, and it holds both tables' decisions: the join may read learning.reviews but not crm.learners, and one denied table denies the query. Without via, the log would say that the instructor tried to read learners' names. With it, a reviewer knows the assistant wrote that query, and looks at the assistant's behaviour as well as the instructor's.
Working rule: Write the audit record in the enforcement layer, where the principal, the query and the decision meet, and write it before the query runs, so that a failed write stops the query. Record every identity involved, the person and any assistant acting for them, and every table's decision with its filters, masks and reasons. When an engine enforces the policy itself, as the SQL engine Trino does through OPA, turn on OPA's decision log instead, and make sure its input names every identity involved: Trino's opa.identity.extra-credentials-keys, for example, forwards the credentials it lists "to OPA as extraCredentials in the identity context" (Trino 484, OPA access control).
値を記録に残さない
判断記録が保持するのは、ID、テーブル名と列名、判断、ダイジェストであり、そのクエリが読んだデータの値は一つも含まない。監査ログに入るものはすべて、保護すべきデータになるためである。NIST の AU-3 の解説は、監査証跡が個人を特定できる情報を明らかにしうること、とりわけ入力を記録する場合にそうなることを警告している。その拡張 AU-3(3) は、監査記録に含まれるその種の情報を、プライバシーリスク評価が挙げる要素に限定するようシステムに求めている(NIST SP 800-53 Rev. 5)。求められているのは除去ではなく限定である。AU-3 の項目 f は主体の記録を求めるので、どの記録にも主体が一つ記される。たとえば instructor-17 は、ある講師のアカウントである。GDPR は個人データを「識別された、または識別可能な自然人に関するあらゆる情報」と定義しており(GDPR, Article 4(1))、人は直接または間接に識別可能であり、特に氏名やオンライン識別子といった識別子を通じて識別される。この種のアカウント ID は、そうした識別子になりうる。プラットフォームには、学習者をログから遠ざけるもっと切実な理由がある。第7章は、学習者のデータが届いたすべてのテーブルからその学習者を消去する。ところが、本章が追加するチェーンから1件の記録を消すと、それは改ざんと区別できない。
危険はクエリ文にある。チケットに書かれたメールアドレスで学習者を検索するサポート担当者は、そのメールアドレスをクエリに書き込む。lib.audit.normalized はクエリの形を残して値を捨てる。sqlglot がクエリを構文解析し、DuckDB のどの構文で書かれたリテラルも ? に置き換える。カタログに存在しない名前も同様で、たとえば二重引用符で書かれた値がそうである。ただし、クエリが定義するエイリアスや CTE の名前は、alias_1、alias_2 のように置き換わる。何でも書き込めるコメントは除外され、拒否の理由も同じように値を取り除いて記録される。層が DuckDB に渡す SQL は、rewritten_digest としてのみ保持される。これは層だけが持つ鍵による HMAC-SHA256 であり、突き合わせで DuckDB 自身のログと照合される。OPA は逆に入力全体から出発し、ポリシーが指定するものを捨てるよう設定できる。「決定ログをエンコードしてアップロードする前に、data.system.log.mask パスを問い合わせる」(OPA, decision logs)。このプラットフォームの層は、値をそもそも書き込まない。
次の例では、agent-a05 が EMEA の学習者をメールアドレスで、続いて ID で検索し、analyst-1 は学習者のメールアドレスを読む。ポリシーはこれを仮名化する。どちらの値も出力しない。以下の行は、それぞれの値がどこに保持されるかを示す。
1"""A record keeps a query's shape and none of its values, while DuckDB's own query log keeps the email as it was typed.2The printed lines the prose rests on are the asserts about the email and the four count lines at the end."""3from lib import audit4from lib.catalog import open_catalog5from lib.platform import load, scratch67log = audit.Log(scratch() / "audit.jsonl")8platform = audit.Audited(open_catalog(["crm.learners"]), log)910# agent-a05 looks up an EMEA learner by the email in a ticket, then by their ID. Neither value is ever printed.11learners = load("crm.learners").to_pylist()12learner = next(row for row in learners if row["support_region"] == "emea") # any EMEA learner will do, since the example needs only one13email, learner_id = learner["email"], learner["learner_id"]14platform.sql(f"select learner_id, full_name from crm.learners where email = '{email}'", "agent-a05").fetchall()15platform.sql(f"select email, phone from crm.learners where learner_id = {learner_id}", "agent-a05").fetchall()16platform.sql("select learner_id, email from crm.learners", "analyst-1").fetchall() # pseudonymized with the key1718for record in log.records():19 print("query in the record:", record["query"])20engine = audit.engine_queries(platform.enforcer.connection) # DuckDB's own query log, literals and all21print("the email, in the audit log:", email in log.path.read_text())22assert email not in log.path.read_text() # the record keeps `?` where the email was, so nothing matches23print("the email, in DuckDB's query log:", any(email in query for query in engine))24assert any(email in query for query in engine) # DuckDB logs the SQL text it runs, literals included25print("the pseudonymization key, in DuckDB's query log:", any(platform.enforcer.key in query for query in engine))26assert not any(platform.enforcer.key in query for query in engine)27print("its placeholder, in DuckDB's query log:", any("$pseudonym_key" in query for query in engine))28assert any("$pseudonym_key" in query for query in engine)2930# Guessing which learner the agent looked up, from a list of the platform's emails: rebuild the text DuckDB ran with31# each email, digest it, and compare. First with a plain SHA-256 of the query, as a log might keep, then with the32# record's keyed digest, by someone without the layer's key and by someone who holds it.33ran = next(query for query in engine if email in query)34guesses = [ran.replace(email, row["email"]) for row in learners] # the same text, with each learner's email in its place35logged = log.records()[0]["rewritten_digest"] # record 1 is the agent's lookup by email36print("emails tried:", f"{len(guesses):,}")37print("emails a plain SHA-256 of the query confirms:", sum(audit.sha256(g) == audit.sha256(ran) for g in guesses))38print("emails the keyed digest confirms, without the layer's key:",39 sum(audit.digest(g, "a-guessed-key") == logged for g in guesses)) # a wrong key, the only kind a guesser has40print("emails the keyed digest confirms, with the layer's key:", sum(audit.digest(g, platform.key) == logged for g in guesses))
python query-without-literals.pyquery in the record: SELECT learner_id, full_name FROM crm.learners WHERE email = ?
query in the record: SELECT email, phone FROM crm.learners WHERE learner_id = ?
query in the record: SELECT learner_id, email FROM crm.learners
the email, in the audit log: False
the email, in DuckDB's query log: True
the pseudonymization key, in DuckDB's query log: False
its placeholder, in DuckDB's query log: True
emails tried: 5,000
emails a plain SHA-256 of the query confirms: 1
emails the keyed digest confirms, without the layer's key: 0
emails the keyed digest confirms, with the layer's key: 1
記録に残るのは WHERE email = ? と WHERE learner_id = ? であり、ログをメールアドレスで検索しても何も見つからない。DuckDB のクエリログにはメールアドレスが残る。DuckDB が実行する SQL 文をリテラルも含めて記録するためである。仮名化の鍵はそこにない。第6章は鍵をパラメータとして渡すので、DuckDB のログでは鍵のあるべき位置にプレースホルダ $pseudonym_key が表示される。
メールアドレスを含んでいたクエリの鍵付きダイジェストは、そのメールアドレスの仮名であり、それを仮名にとどめているのは鍵である。これは第6章がプラットフォームの仮名について示したとおりである。書き換えはリポジトリ内のコードなので、古いエクスポートや漏洩で入手したメールアドレスの一覧を持つ者は、それぞれについて DuckDB が実行したテキストを再構築し、照合できる。試した 5,000 件のメールアドレスのうち、そのテキストの単純な SHA-256 が確認できるのは 1 件である。これはエージェントが検索した学習者にあたる。記録の鍵付きダイジェストは、層の鍵がなければ 0 件、鍵があれば 1 件を確認する。鍵は層の手元にとどまり、ログを読む者には渡らない。鍵を必要とする突き合わせも同様である。
DuckDB は値を引用符付き文字列以外の方法でも受け取り、名前が値を含むこともある。normalized の回帰テストは、同じ学習者のメールアドレス、氏名、ID を、それらの方法のそれぞれで agent-a05 のクエリに入力する。これらのリクエストは、1件につき1記録の次の痕跡を残す。
1"""Eleven places to type a learner's values into a query, and what each record keeps of it: the query's shape, with a2`?` for each value and each name the catalog doesn't hold, and a numbered alias for each alias or CTE the query defines.3The printed count of records that hold the email, the name or the ID4is the line the prose rests on."""5import json6import re78from lib import audit9from lib.catalog import open_catalog10from lib.enforce import Denied11from lib.platform import load, scratch1213log = audit.Log(scratch() / "audit.jsonl")14platform = audit.Audited(open_catalog(["crm.learners"]), log)1516# An EMEA learner's email, name and ID, typed into agent-a05's queries as values and as names. None is ever printed.17learner = next(row for row in load("crm.learners").to_pylist() if row["support_region"] == "emea")18email, name, learner_id = learner["email"], learner["full_name"], learner["learner_id"]19cases = { # each query puts the same values in one more way20 "a string": f"select learner_id from crm.learners where email = '{email}'",21 "a dollar-quoted string": f"select learner_id from crm.learners where email = $${email}$$",22 "an escape string": f"select learner_id from crm.learners where email = e'{email}'",23 "a list": f"select learner_id from crm.learners where email in ['{email}']",24 "a number": f"select email from crm.learners where learner_id = {learner_id}",25 "a comment": f"select email from crm.learners where learner_id = {learner_id} -- {name}",26 "a name in double quotes": f'select learner_id from crm.learners where full_name = "{name}"', # a column, to DuckDB27 "a column alias": f'select learner_id as "{email}" from crm.learners',28 "a table alias": f'select "{name}".email from crm.learners as "{name}"',29 "a CTE's name": f'with "{email}" as (select learner_id from crm.learners) select learner_id from "{email}"',30 "a table the catalog doesn't hold": f'select learner_id from "{email}"',31}3233for query in cases.values():34 try:35 platform.sql(query, "agent-a05").fetchall() # a denial is recorded, then raised: the script carries on36 except Denied:37 pass3839# What each record keeps of its query. The email or the name anywhere in its line, or the ID in what it keeps, is a40# value that got through, and is never printed.41held = []42for case, line in zip(cases, log.lines()): # one record per query, in the order they ran43 record = json.loads(line)44 kept = record["query"] + (f" (denied: {record['denial']})" if record["denial"] else "")45 held.append(email in line or name in line or bool(re.search(rf"\b{learner_id}\b", kept))) # the ID as a whole word46 print(f"{case}:", "(holds a value)" if held[-1] else kept)47print("records holding the email, the name or the ID:", sum(held), "of", len(cases))
python query-shape-hard-cases.pya string: SELECT learner_id FROM crm.learners WHERE email = ?
a dollar-quoted string: SELECT learner_id FROM crm.learners WHERE email = ?
an escape string: SELECT learner_id FROM crm.learners WHERE email = ?
a list: SELECT learner_id FROM crm.learners WHERE email IN (?)
a number: SELECT email FROM crm.learners WHERE learner_id = ?
a comment: SELECT email FROM crm.learners WHERE learner_id = ?
a name in double quotes: SELECT learner_id FROM crm.learners WHERE full_name = ? (denied: Column '?' could not be resolved)
a column alias: SELECT learner_id AS alias_1 FROM crm.learners
a table alias: SELECT alias_1.email FROM crm.learners AS alias_1
a CTE's name: WITH alias_1 AS (SELECT learner_id FROM crm.learners) SELECT learner_id FROM alias_1
a table the catalog doesn't hold: SELECT learner_id FROM ? (denied: not a table in the catalog: "?")
records holding the email, the name or the ID: 0 of 11
どの記録も、許可されたものも拒否されたものも、クエリの形を保持し、値は一つも保持していない。最後の行は、メールアドレス、氏名、ID を含む記録を数えたものである。0 of 11。
失われるものが二つある。一つは、正規化されたテキストが無害な値や名前まで落とすことである。最初の記録では ROUND(AVG(rating), 2) が ROUND(AVG(rating), ?) になり、2番目の記録ではエイリアス r と l が alias_2 と alias_1 になった。もう一つは、ログが「誰がこの学習者を検索したか」に答えられないことである。自分のデータを誰が読んだかを尋ねる学習者がいるなど、その答えが必要になった場合は、別のアクセスログに保持する。そのログは学習者 ID を持ち、保持期間を定め、チェーンを持たない。第7章の消去は、他のテーブルと同様にそのログにも及ぶ。
実践ルール: クエリは形だけを記録し、値は決して記録しない。エンジンが受け付けるあらゆる構文のリテラルと、カタログに存在しない名前をすべて置き換え、コメントを除外し、拒否理由からも同じ値を取り除く。実行された SQL は鍵付きダイジェストとしてのみ保持し、その鍵をログの読者には決して渡さない。個人データを含みうるテキストの単純なハッシュは決して使わない。特定の人物のデータを誰が読んだかを知る必要がある場合は、改ざん検知ログではなく、保持期間と消去が及ぶ別のログに記録する。
過去の決定をそのポリシーのもとで再現する
決定レコードにはリクエストが記録されているが、決定は三つのものに依存する。リクエスト、ポリシーのルール、そしてポリシーが読み取るデータである。後の二つは絶えず変化する。第5章で構成したとおり、このプラットフォームのポリシーは governance/users.toml、governance/metadata.toml、learning.courses を読み取るので、サポート担当者が別のリージョンに異動したり、learning.courses にコースが追加されたりすれば、Rego に誰も手を加えていなくても決定は変わる。ポリシーがどうであったかをレコードが何も伝えていなければ、どちらかが変わった時点でその決定を説明できなくなる。後から再現すると異なる答えが返り、ログのほうが誤っているように見える。OPA はポリシーのバージョンを bundles[_].revision として記録する。時刻や HTTP リクエストのように非決定的な組み込み関数を呼び出すポリシーについては、OPA はその結果を nd_builtin_cache にログとして残すこともできる。これはデバッグと決定の再現のために用意されたものである(OPA, decision logs)。このプラットフォームのポリシーは、そうした関数を一つも呼び出さない。
lib.audit.bundle は、ポリシーのモジュールとデータドキュメント(ポリシーが読み取る事実の集合で、先の三つのソースから生成される)をまとめ、OPA がバンドルとして配布する形にする。lib.audit.revision はそのバンドルの SHA-256 であり、ルールのいずれか、あるいはポリシーが読み取る事実のいずれかが変われば値が変わるフィンガープリントである。すべてのレコードは、その決定を下したリビジョンを保持する。lib.audit.Archive は、この層がこれまでに使用したすべてのバンドルをリビジョンごとに保管するので、ある決定を、それを下したポリシーのもとでもう一度行うことができる。バンドルが保持するのはルールとプラットフォームのユーザーの属性であり、学習者に関するデータではない。したがって、アーカイブはログと同じ期間だけ保管できる。
このプラットフォームでは、analyst-1 は学習者のメールアドレスを読み取り、仮名を受け取る。その後のプルリクエストで、このユーザーが EMEA のサポートに追加されたとする。これは第6章で、誰に何が見えるかを調べるテストによって検出した変更である。古いレコードを、それぞれのリビジョンのもとで再現する。
1"""Replays a logged decision under the revision it was made with and under the current one, after a change to the users2file alone. The printed email and match lines are the point: only the archived revision explains the record."""3from lib import audit, policy4from lib.catalog import open_catalog5from lib.platform import scratch67folder = scratch()8archive = audit.Archive(folder / "bundles") # every policy revision that has decided anything, by revision9log = audit.Log(folder / "audit.jsonl")1011# analyst-1 reads learners' emails, which the policy pseudonymizes.12platform = audit.Audited(open_catalog(["crm.learners"]), log, archive=archive)13platform.sql("select learner_id, email from crm.learners", "analyst-1").fetchall()14record = log.records()[0]1516# Later, a pull request adds analyst-1 to support for EMEA, as in chapter 6. Only users.toml changes, which reaches17# the policy through its data document, and no Rego.18data = policy.data_document()19data["platform"]["users"]["analyst-1"] = {"groups": ["data-science", "support"], "region": "emea"}20current, logged = audit.bundle(data=data), archive.get(record["policy_revision"]) # the bundle the record was decided under21print("logged under revision:", record["policy_revision"][:12])22print("current revision:", audit.revision(current)[:12])23modules_changed = current["modules"] != logged["modules"]24assert not modules_changed # no Rego changed, so the policy modules are the same25print("policy modules changed:", modules_changed)26data_changed = current["data"] != logged["data"]27assert data_changed # the data document is the only part that changed28print("data document changed:", data_changed)2930# Explain the logged decision by making it again, from the request the record holds, under each revision.31print("email, as logged:", record["decisions"][0]["column_masks"].get("email", "shown as stored"))32for name, revision in [("the current revision", current), ("the logged revision", logged)]:33 again = audit.replay(record, revision)34 matches = again == record["decisions"]35 assert matches == (revision is logged) # only the revision the record was decided under explains it36 print(f"under {name}, email:", again[0]["column_masks"].get("email", "shown as stored"))37 print(f"under {name}, the decision matches the log:", matches)
python explain-old-decision.pylogged under revision: f761e4ad08d4
current revision: 0350e789b34d
policy modules changed: False
data document changed: True
email, as logged: pseudonymize
under the current revision, email: shown as stored
under the current revision, the decision matches the log: False
under the logged revision, email: pseudonymize
under the logged revision, the decision matches the log: True
リビジョンは f761e4ad08d4 から 0350e789b34d へ変わったが、Rego は変わっていない。ポリシーのモジュールは同じであり、新しいメンバー構成を列挙するようになったデータドキュメントは同じではない。ポリシーファイルだけのフィンガープリントでは、この変更を見逃していたはずである。現在のリビジョンのもとで再現すると、決定はログと一致しない。サポートには連絡先情報が見えるため、email は shown as stored になる。現在のポリシーしか手元にない調査者は、ログか、この層のどちらかが誤っていると結論づけるだろう。アーカイブからログに記録されたリビジョンを取り出して再現すれば、email は再び pseudonymize となり、決定はログと一致する。
再現が説明するのは決定であって、行ではない。行フィルタはルールとして再現される。サポートのリージョンや、同意フィルタ learner_consented がその例である。そして、どの行がそれを通過したかはその日のデータに依存しており、そのデータはその後に変更されたか、消去されている可能性がある。この分離は設計によるものである。ログはルールが何であったかを伝え、テーブルは、それぞれのスナップショットと保持期間のもとで、そのルールが何に該当したかを伝える。
実践ルール: すべての決定に、リクエスト以外にその決定が依存したすべてのもの、すなわちポリシーのモジュールとそのデータドキュメントをあわせたハッシュでフィンガープリントを付ける。各リビジョンは、ログを保持する期間と同じだけアーカイブし、過去の決定は現在のリビジョンではなく、その決定自身のリビジョンのもとで再現して説明する。ポリシーが時計を読み取ったり他のサービスを呼び出したりする場合は、OPA の nd_builtin_cache のように、その結果もログに残す。
レコードを連鎖させ、編集を検出可能にする
プラットフォームの判断記録が証拠として成り立つのは、その変更を検出できる場合に限られる。SP 800-53 は、システムに対して「監査情報および監査ログツールを、不正なアクセス、改変、削除から保護すること」(AU-9)を求め、AU-9(3) ではさらに「監査情報および監査ツールの完全性を保護するために暗号的メカニズムを実装すること」を求めている。AU-9(3) の解説は例として「非対称暗号を用いた署名付きハッシュ関数」を挙げており(NIST SP 800-53 Rev. 5)、これは秘密鍵の保持者だけが作成できる。以下で扱うプラットフォームの連鎖はそれに当たらず、単独では何も保護しない。NIST のログ管理ガイドである SP 800-92 は、最も単純な仕組みを述べている。ログファイルごとにメッセージダイジェストを作成して安全に保管し、保管済みログへの変更を検出するというものである(NIST SP 800-92)。このガイドは 2006 年のもので、当時一般的だったダイジェストとして MD5 と SHA-1 を挙げているが、脚注 25 自体は SHA-256 を勧めており、プラットフォームが用いているのもこれである。
ファイルごとのダイジェストは、閉じられたファイルへの変更を検出する。ハッシュチェーンは、まだ書き込みが続いているログへの変更を検出する。すべてのレコードが連番 seq と、直前の行の SHA-256 である prev_hash を持つので、あるレコードを変更すると次のレコードへのリンクが切れ、レコードを削除すると欠番が生じる。lib.audit.check はチェーンをたどり、切れ目をすべて報告する。チェーンが示すのは改ざんの痕跡であり、改ざんそのものを防ぐわけではない。Schneier と Kelsey は、ログを記録するマシンを乗っ取った攻撃者が、それ以前に書かれたエントリを読むことも偽造することもできないログを設計した。そこでも攻撃者は「エントリのブロック(あるいはログファイル全体)を削除できる」のであり、ログの報告先である信頼できる当事者がそれに気づくのは、そのマシンが次に接触してきたときだけである(Schneier and Kelsey, 1999)。プラットフォームのような単純なチェーンはそれより弱い。ファイルに書き込める者なら誰でも、番号を振り直しながらチェーンを再構築できる。したがって、チェーンが何を証明するかは、チェーンのヘッド、すなわちレコード数と最後のレコードのハッシュを、ログの書き手が変更できない場所に書き留めてあるかどうかで決まる。そのヘッドまでのどのレコードに対する編集も削除も、どのように隠されていても検出される。ヘッドより後では、再構築されたチェーンや切り詰められたチェーンはあらゆる検査を通過する。ヘッドがなければ、最初から再構築されたチェーンも同様に通過する。check はヘッドをアンカーとして受け取る。
チェーンを試すために、この例では、10 月 1 日にプラットフォームが受け取った 13 件のクエリである lib.audit.DAY を再生し、正午の時点、すなわちレコード 9 でヘッドを書き留める。そのうえで、ログのコピーに 5 通りの改ざんを加える。正午より前では、レコード 3、すなわち agent-a05 による学習者の連絡先の参照を別のエージェントのものにすり替える。これを単純な編集として一度、チェーンを再構築して一度行う。正午より後では、レコード 12、すなわちプラットフォームが把握していないユーザー someone-else による拒否された読み取りを削除する。これも単純な削除として一度、チェーンを再構築して一度行い、さらに、その日の最後の 2 件のレコードを切り落とす。実行する前に、5 通りのうちチェーン単独で見つかるものはどれか、正午のヘッドと照合して初めて見つかるものはどれかを予想してほしい。
1"""Replays the day's queries into a chained log, writes the head down at noon, then tampers with copies of the log five2ways and checks each against the chain alone and against the noon head. The point rests on the two checks of each3change: the chain finds the plain edit and the plain removal on its own, and only the head finds the rebuilt chain."""4import json56from lib import audit7from lib.catalog import open_catalog8from lib.platform import scratch910log = audit.Log(scratch() / "audit.jsonl")11platform = audit.Audited(open_catalog(["crm.learners", "learning.reviews", "billing.payments", "support.tickets"]), log)12audit.run_day(platform, [query for query in audit.DAY if query[0] < "12:00"]) # the morning; times compare as strings13anchor = log.head() # the head, written down at noon somewhere the log's writer can't reach14audit.run_day(platform, [query for query in audit.DAY if query[0] >= "12:00"]) # the afternoon15lines = log.lines()16print("records:", len(lines))17print("head written down at noon, at record:", anchor["records"])18print("record 3:", json.loads(lines[2])["user"], "reads", json.loads(lines[2])["query"]) # record 3 is index 2192021def rechained(lines: list[str]) -> list[str]:22 """The chain built again, every record renumbered and every prev_hash recomputed: what anyone who can rewrite the23 log's file can do."""24 rebuilt, previous = [], audit.GENESIS # the first record points at 64 zeros, not at a record25 for seq, line in enumerate(lines, start=1):26 rebuilt.append(audit.canonical(json.loads(line) | {"seq": seq, "prev_hash": previous}))27 previous = audit.sha256(rebuilt[-1])28 return rebuilt293031# Before noon, record 3 handed to another agent. After noon, record 12 (someone-else's denied read) removed, and the32# day's last two records cut off.33edited = lines[:2] + [audit.canonical(json.loads(lines[2]) | {"user": "agent-a01"})] + lines[3:] # index 2 is record 334removed = lines[:11] + lines[12:] # index 11 is record 1235for name, version in [("untouched", lines), ("record 3 edited", edited), ("record 3 edited, chain rebuilt", rechained(edited)),36 ("record 12 removed", removed), ("record 12 removed, chain rebuilt", rechained(removed)),37 ("last 2 records removed", lines[:-2])]:38 print(f"{name}, checked alone:", "; ".join(audit.check(version)) or "no problem found")39 print(f"{name}, checked against the noon head:", "; ".join(audit.check(version, anchor)) or "no problem found")
python chain-catches-edit.pyrecords: 13
head written down at noon, at record: 9
record 3: agent-a05 reads SELECT full_name, email, phone FROM crm.learners WHERE learner_id = ?
untouched, checked alone: no problem found
untouched, checked against the noon head: no problem found
record 3 edited, checked alone: record 3 was changed: record 4 doesn't follow it
record 3 edited, checked against the noon head: record 3 was changed: record 4 doesn't follow it
record 3 edited, chain rebuilt, checked alone: no problem found
record 3 edited, chain rebuilt, checked against the noon head: the chain no longer passes through the head written down at record 9
record 12 removed, checked alone: record 12 is missing: record 13 follows record 11
record 12 removed, checked against the noon head: record 12 is missing: record 13 follows record 11
record 12 removed, chain rebuilt, checked alone: no problem found
record 12 removed, chain rebuilt, checked against the noon head: no problem found
last 2 records removed, checked alone: no problem found
last 2 records removed, checked against the noon head: no problem found
チェーン単独で見つかるのは、単純な編集 record 3 was changed: record 4 doesn't follow it と単純な削除 record 12 is missing: record 13 follows record 11 だけで、ほかは見つからない。再構築された 2 つのチェーンは始めから終わりまで整合しているので見逃され、切り落としも、最後のレコードの後に続くレコードがなく、欠落に気づけないため見逃される。
ヘッドが保護するのは、それより前に書かれたレコードだけである。正午のヘッドと照合すると、正午前の編集は、チェーンが再構築されていても the chain no longer passes through the head written down at record 9 のように検出される。正午より後に隠されたものはすべて通過する。チェーンを再構築した削除は no problem found となり、切り落としは no problem found となる。
これが、値に関する規則が任意ではない理由である。チェーン化されたログから学習者を消去するには、レコードを変更するか削除するしかなく、それを検査が検出できる場面では、改ざんとの区別がつかない。学習者に関するデータを含まないログは、第 7 章の消去には関わらない。クエリを発行する人々の ID は別の問題である。ログに保持期間を設け、期間ごとに新しいチェーンを始めて、その最後のヘッドを書き留めておけば、期限が来たときに期間全体を削除できる。
チェーンの検査は、すべてのレコードを読み直すことを意味する。Crosby と Wallach は、木構造のログについて述べている。このログは「個々の記録されたイベントが今も存在すること、そして現在見えているログが過去に見えていたものと整合していること」を、対数サイズの証明で示すことができ、従来の線形の構成を改善している(Crosby and Wallach, 2009)。1 つのプラットフォーム自身のログには、毎日検査するチェーンを推奨する。外部の当事者が、読み直すには大きすぎるログを監査する場合には、木を推奨する。
実践ルール: すべてのレコードを、SHA-256 と連番によって直前のレコードに連鎖させる。ただし、チェーンが保護するのは、この層の制御の外に最後に書き留めたヘッドまでのレコードだけだと見なす。ヘッドは頻繁に、追記専用のストアか、別の認証情報で動く別のシステムに書き留める。頻度は、許容できる未保護レコードの数で決める。その数がゼロなら、各レコードを書き込むと同時にマシンの外へ送り出す。チェーンは、最後のヘッドと照合して定期的に検査する。AU-9(3) が述べる水準が必要なら、この層が鍵を一切持たないシステムに各ヘッドへ署名させる。いつか特定の個人のために消去しなければならなくなるかもしれないレコードは、決してチェーンに入れない。代わりに、期間ごと丸ごと失効させる。
ログを DuckDB のクエリログと突き合わせる
プラットフォームの監査ログは、強制レイヤを通過したすべてのクエリを記録するが、記録するのはそれだけである。ノートブックのヘルパーや、接続を渡されたテストが、レイヤの DuckDB 接続で直接実行したクエリには、判定も記録も残らない。これに気づくには、エンジンが保持する第 2 の記録が必要になる。DuckDB 2.0.0 にはその記録があるが、既定では無効である。DuckDB のロギング機構には QueryLog 型があり、DuckDB が実行したクエリを記録する。有効にするには CALL enable_logging('QueryLog') を実行し、記録は duckdb_logs ビューから読む(DuckDB, logging)。これとは別に、クエリを記録するファイルを指定する設定 log_query_path がある(DuckDB, configuration)。ただしレイヤの接続はこの設定を拒否する。これは本番環境の節で示したとおりである。
DuckDB のログは監査ログではない。各エントリが保持するのは SQL テキストであり、これに接続 ID、トランザクション ID、クエリ ID とタイムスタンプが付く。ユーザーも判定も含まれない。見えるのは書き換え後のクエリだけであり、ログは記録対象のプロセスに属する。このログにできるのは監査ログの検査である。DuckDB が実行したクエリはすべて、何らかの判定記録が DuckDB に渡した SQL であるはずだ。Audited は、起動時に DuckDB のログを有効にし、接続の設定をロックする。Audited.check_engine_log は、DuckDB のログにある各クエリを、前回の検査以降に書かれた記録の rewritten_digest と、鍵付きダイジェストによって照合する。その後、クエリの値を含む DuckDB のログを空にする。リレーションのクエリは「Output 節のメソッドがリレーションを読むときに実行され、読むたびに再び実行される」(DuckDB, relational API)。また、絞り込んだリレーションは独自の SQL を実行するが、その SQL はどの記録も DuckDB に渡していない。そこで Audited.sql は、各結果を自らちょうど 1 回取得し、その行を独自の接続上のリレーションとして返す。呼び出し側がそれをどう扱っても、DuckDB のログには許可された各クエリが 1 回だけ残る。
最初の検査では、その日の 13 件のクエリを再実行して照合する。次に、さらに 2 つのクエリをレイヤ経由で実行する。1 つは呼び出し側が結果を取得しないクエリ、もう 1 つは 5 行に絞り込むクエリである。さらに、ノートブックのヘルパーがレイヤを迂回し、レイヤの接続で学習者のメールアドレスを読む。続いて 2 回目の検査を行う。
1"""DuckDB's query log checked against the audit log: first on the day's queries, then after two more queries through the2layer and a read around it. The point rests on the last check's unrecorded query, the one read that bypassed the layer."""3from lib import audit4from lib.catalog import open_catalog5from lib.platform import scratch67log = audit.Log(scratch() / "audit.jsonl")8platform = audit.Audited(open_catalog(["crm.learners", "learning.reviews", "billing.payments", "support.tickets"]), log)9day = audit.run_day(platform)10print("queries allowed:", day["allowed"])11print("queries denied:", day["denied"])1213# DuckDB's own query log, kept on the layer's connection, against the records written since the last check. The check14# then empties DuckDB's log, which holds the queries' values.15found = platform.check_engine_log()16print("queries DuckDB ran:", found["engine queries"])17print("queries DuckDB ran with no decision record:", len(found["unrecorded"]))1819# Two more queries through the layer: one whose caller never fetches it, and one the caller narrows to five rows.20platform.sql("select learner_id, country from crm.learners", "analyst-1") # the layer fetches it, so DuckDB logs it once21platform.sql("select learner_id, country from crm.learners", "analyst-1").limit(5).fetchall() # narrowed after the layer's fetch22# Then a notebook helper that was handed the layer's connection reads a learner's email with it, around the layer.23platform.enforcer.connection.sql("select email from crm.learners where learner_id = 541").fetchall() # no record for this one24found = platform.check_engine_log()25print("next check, records checked:", " to ".join(map(str, found["records checked"])))26print("next check, queries with no decision record:", len(found["unrecorded"]))27for query in found["unrecorded"]:28 print("unrecorded:", query)29print("next check, decision records DuckDB has no query for:", len(found["not in the engine log"]))
python query-log-cross-check.pyqueries allowed: 9
queries denied: 4
queries DuckDB ran: 9
queries DuckDB ran with no decision record: 0
next check, records checked: 14 to 15
next check, queries with no decision record: 1
unrecorded: SELECT email FROM crm.learners WHERE learner_id = ?
next check, decision records DuckDB has no query for: 0
この突き合わせは、その日のクエリを記録と対応づける。9 件が許可され、4 件が拒否された。DuckDB が実行したのは 9 件であり、許可された各クエリに 1 件ずつで、拒否されたクエリは 0 件である。記録のないクエリは 0 件である。
次の検査で見つかるのは、レイヤを迂回した読み取りだけである。この検査は記録 14 to 15 件、すなわちレイヤ経由の 2 つのクエリを対象とし、警告は出さない。レイヤを迂回した読み取りは、判定記録のないクエリ 1 件として現れ、値は出力されない。最後の行は逆方向の検査で、DuckDB に痕跡のないクエリの記録を調べる。ここでは 0 件である。
検査で何を捕捉できるかは、接続を誰が持っているかで決まる。捕捉できるのは、DuckDB のログに手を触れないコードによる迂回読み取りである。たとえばこのノートブックのヘルパー、テスト、誤って接続を渡されたジョブがこれに当たる。接続を持ち、隠す意図のあるコードは捕捉できない。検査の後に読み取りを行い、レイヤの次のクエリの前に DuckDB のログを再び空にすれば、どちらの方向の検査も何も見つけられない。さらに、DuckDB の write_log 関数はログ型を引数に取るため、QueryLog エントリを書き込める(DuckDB source, v2.0.0)。設定のロックは関数を止めない。このようなコードに対する保証には、接続を持つプロセスの外部に書き込まれたエンジンのログが必要である。
この検査は、レイヤ自身の近道も見つける。たとえば第 6 章の observe は、ユーザーを介さずにレイヤの接続で保存済みテーブルを読む。このようなクエリには、検査の例外とするのではなく、レイヤ自身をユーザーとする独自の記録を与える。
実践ルール: ポリシーを強制する場所ではどこでも、エンジン自身のクエリログを有効にし、すべての結果をレイヤ内で取得する。そして、前回の検査以降に書かれた記録と、ログを定期的に双方向で照合する。エンジンが実行したすべてのクエリが記録に対応し、許可されたすべての記録がクエリに対応しなければならない。その後、ログを空にする。ログはクエリの値を保持するためである。不一致は、ノイズとして除外せず、説明すべきインシデントとして扱う。この検査に期待できるのはミスの捕捉であり、接続を持って隠す意図のあるコードの捕捉ではない。後者にはプロセスの外部に書かれたログだけが有効である。エンジンのログを監査ログとして使ってはならない。ログにはユーザーも判定もないからである。
ログからアクセスレビューを生成する
プラットフォームの監査ログは各人が何を読んだかを示し、ポリシーは各人が何を読めるかを定める。アクセスレビューは、この二つを並べて照合するものである。SP 800-53 は、組織に対して、アカウント管理要件への準拠についてアカウントをレビューすること(AC-2 j)、およびロールとクラスに割り当てられた権限を定められた頻度でレビューし、その必要性を検証したうえで、必要に応じて再割り当てまたは削除することを求めている(AC-6(7))(NIST SP 800-53 Rev. 5)。誰がどのロールを持つかという一覧は、このどちらにも答えない。必要性について何も語らないからである。レビューに必要な事実は、コードで計算できる。ポリシーが各人に許可していること、ログが示す各人の利用実績、拒否されたこと、そして何も指していない所属である。アクセスを削除するかどうかは、データの所有者が決めることとして残る。
lib.audit.review は、users.toml にいるすべてのユーザーについて、プラットフォームのポリシーをすべてのテーブルに対して評価し、ログを読み、ユーザーごとに次の項目を一覧にする。読めるテーブル、実際に読んだテーブル、使われなかった権限、拒否されたクエリとそれを送ったアシスタント、そして誰かが確認すべき事項である。古くなったものを見つけさせるために、この例ではユーザーに analyst-2 を加える。このユーザーは、ポリシーにはもう存在しないグループ bi にまだ所属として載っている。グループを廃止しても、ユーザーファイルを誰も編集しなかった場合に起こる状況である。
1"""An access review of every user in the users file, and every user the log names, against the policy and the day's log,2with a stale group membership added to find. The printed `look at` lines and the grants-not-used count are what the prose3rests on."""4from lib import audit, policy5from lib.catalog import open_catalog6from lib.platform import TABLES, scratch78log = audit.Log(scratch() / "audit.jsonl")9platform = audit.Audited(open_catalog(["crm.learners", "learning.reviews", "billing.payments", "support.tickets"]), log)10audit.run_day(platform) # the day's queries, so that the review has a log to read1112# users.toml as the review finds it: analyst-2 is still listed in bi, a group the policy no longer has.13data = policy.data_document()14data["platform"]["users"]["analyst-2"] = {"groups": ["bi"]}15rows = audit.review(audit.bundle(data=data), log.records(), TABLES) # all eight of the platform's tables1617for row in rows:18 print(f"{row['user']}: may read {len(row['may read'])}, read {len(row['read'])}, denied {row['denied']}"19 + (f" (sent by {', '.join(row['denied via'])})" if row["denied via"] else ""))20 if row["unused"]: # a grant unused: a table the policy lets the user read, and the log never shows them reading21 print(" not used:", ", ".join(row["unused"]))22 for finding in row["findings"]:23 print(" look at:", finding)24print("users reviewed:", len(rows))25print("grants not used:", sum(len(row["unused"]) for row in rows))26print("users to look at:", sum(bool(row["findings"]) for row in rows)) # any finding at all needs a person27print("denied queries flagged at:", audit.settings()["review"]["denied_queries_flagged"]) # from governance/audit.toml
python access-review.pyagent-a01: may read 2, read 0, denied 0
not used: crm.learners, support.tickets
agent-a05: may read 2, read 2, denied 0
agent-a09: may read 2, read 0, denied 0
not used: crm.learners, support.tickets
analyst-1: may read 6, read 2, denied 0
not used: billing.payments, learning.courses, learning.enrollments, learning.events
analyst-2: may read 0, read 0, denied 0
look at: in group bi, which the policy doesn't know
assistant-1: may read 2, read 1, denied 0
not used: learning.courses
finance-1: may read 3, read 1, denied 0
not used: learning.courses, learning.enrollments
instructor-17: may read 3, read 1, denied 3 (sent by assistant-1)
not used: learning.courses, learning.enrollments
look at: 3 denied queries
marketing-1: may read 2, read 1, denied 0
not used: learning.courses
someone-else: may read 0, read 0, denied 1
look at: not in users.toml
users reviewed: 10
grants not used: 14
users to look at: 3
denied queries flagged at: 3
lib.audit.DAY が再生する 10月1日の1日間では、14 件の権限が使われず、agent-a01 と agent-a09 はまったく何も読まなかった。1日では、誰かのアクセスを削除するには短すぎる。サポートは交代制で働き、経理は月次の締めのときにしか読まないテーブルがあるからである。したがって、これらの件数は判断ではなく手がかりである。テーブルの所有者に持ち込むべきなのは、四半期などレビュー期間全体を通して使われなかった権限である。3 人のユーザーは、人による確認が必要である。
analyst-2は、どのルールも知らないグループに属している。この所属は現在は何も許可しないが、将来bi向けのルールが追加されれば、そのルールが許可するものをそのまま許可してしまう。したがって削除する。someone-elseはusers.tomlにいない。つまり、プラットフォームが知らないプリンシパルが、学習者のメールアドレスを読もうとしたことになる。instructor-17の行はmay read 3, read 1, denied 3 (sent by assistant-1)となっている。アシスタントは、講師の最初の質問に答えた後の2分間に、learners、次に reviews と結合した learners、そして tickets を順に試した。これはアシスタントがテーブルを一つずつ試している状態であり、viaがなければ、レビューは講師を責めていただろう。
フラグを立てるしきい値である、3 件の拒否されたクエリは経験則であり、その根拠とともに governance/audit.toml に保管する。こうしておけば、しきい値の変更はポリシーの変更と同様に、レビューを経る変更になる。
実践ルール: アクセスレビューは、ロール所属の一覧からではなく、ポリシーと監査ログから生成する。各人が読めるものと読んだもの、拒否された件、ポリシーがもう把握していない所属を照らし合わせる。レビューは、すべての業務のリズムをカバーできる長さの期間、たとえば四半期にわたって実行し、各所見は、それが関わるテーブルまたはグループの所有者に送る。期間中に誰も使わなかった権限は、所有者がその必要性を説明しない限り削除する。
証拠をデータとして生成する
チェーン検査、突き合わせ、アクセスレビューは、チームの外部の者が検証できるときに最も価値を持つ。EU の一般データ保護規則(GDPR)は、この責務を説明責任の原則として組織に課している。「管理者は、第1項の遵守に責任を負い、かつ、その遵守を実証できなければならない(「説明責任」)」(GDPR, Article 5(2))。何をもって実証とみなすかは法律家が判断する問題であり、この節ではコードが何を生成できるかを示す。アカウント管理に関する NIST の評価手順は、評価者が調べる記録を挙げており、そこにはアクセス認可の記録、アカウント管理の遵守状況のレビュー、システム監査記録が含まれる(NIST SP 800-53A Rev. 5, in NIST's OSCAL catalog)。コンソールのスクリーンショットは、そのどれにも当たらない。再実行することも、前四半期のものと比較することも、どのポリシーを表示していたかを知ることもできないからである。
lib.audit.evidence は、記録とコードからプラットフォームのレポートを組み立てる。レポートの節は次のとおりである。
- ポリシー。各モジュールとデータ文書のダイジェストを含む
- 第5章のポリシーの単体テスト
- ポリシーと照合した、誰が何を見られるかの表
- 第2章のメタデータ検査による分類のカバレッジ
- 監査ログのチェーン検査
- DuckDB のログとの突き合わせ
- ログに記録された消去
- アクセスレビュー
各節には、計算に用いたポリシーのリビジョン、入力のダイジェスト、そして再計算に必要なものを明記する。必要なものとは、アーカイブしたバンドル、テストファイル、metadata.toml とテーブルのスキーマ、監査ログである。エンジンとの突き合わせは、一部しか再計算できず、レポートはその旨を述べる。レイヤーは DuckDB が実行した全クエリの鍵付きダイジェストを保持しているので、ログを持つ者なら誰でも2つの件数を再計算できる。しかし DuckDB のログを読めたのはレイヤーだけであり、それも空にする前の一度きりであった。10月1日分のレポートを、カタログ内のすべてのテーブルとパイプラインの出力、07:00 に記録された第7章の学習者の消去、およびその日のクエリを対象に生成する。
1"""The platform on Oct 1, after an erasure and the day's queries: the first evidence report, written to a file as data, with2each section's result printed. The printed checks, the erasure's lines and the head are what the prose rests on."""3import json4from datetime import timedelta56from lib import audit, retention7from lib.platform import scratch89# The platform on Oct 1: every table and pipeline output, chapter 7's erasure of learner 3590 at 07:00, then the day's10# queries through the audited layer.11catalog, graph = retention.open_platform(statistics_off=True) # statistics off for personal columns: each table rewritten under them, old files swept12log = audit.Log(scratch() / "audit.jsonl")13_, found, done = retention.erase_everywhere(catalog, graph, 3590, "erasure-0001", min_age=timedelta(0)) # zero: no file age guard14audit.record_erasure(log, "erasure-0001", done, retention.scan(catalog, found), at=audit.MIDNIGHT.replace(hour=7))15platform = audit.Audited(catalog, log)16audit.run_day(platform)1718# The first report, so there's no head from an earlier one to check the chain against.19report = audit.evidence(platform, catalog, anchor=None)20reports = scratch() # in production, another system, which the log's writer can't change21(reports / "evidence-2026-10-01.json").write_text(json.dumps(report, indent=2, sort_keys=True), encoding="utf-8")22result = {name: section["result"] for name, section in report.items()}23print("sections:", ", ".join(report))24print("policy tests passed:", f"{result['policy tests']['passed']} of {result['policy tests']['of']}")25print("who-sees-what cases the policy agrees with:", f"{result['who sees what']['agree']} of {result['who sees what']['of']}")26for problem in result["classification coverage"]["problems"]:27 print("classification problem:", problem)28print("audit log records:", result["audit log"]["records"])29print("chain problems, checked alone:", len(result["audit log"]["chain problems"]))30print("queries DuckDB ran with no decision record:", len(result["engine cross-check"]["unrecorded"]))31print("decision records DuckDB has no query for:", len(result["engine cross-check"]["not in the engine log"]))32for erasure in result["erasures"]:33 print(f"erasure {erasure['request']}: {erasure['rows_deleted']} rows deleted, "34 f"{erasure['files_holding_the_person']} of {erasure['files_read']} files hold the person")35 for kept in erasure["kept"]:36 print(f"erasure {erasure['request']}, kept under an exception: {kept['table']}, decided by {kept['decided_by']},",37 f"{', '.join(kept['columns_erased'])} erased")38print("chain head written down, at record:", report["audit log"]["inputs"]["head"]["records"]) # the next report's anchor39print("engine cross-check, computed again from:", "; ".join(report["engine cross-check"]["computed again from"]))40print("engine cross-check, not computed again:", report["engine cross-check"]["not computed again"])
python evidence-report.pysections: policy, policy tests, who sees what, classification coverage, audit log, engine cross-check, erasures, access review
policy tests passed: 12 of 12
who-sees-what cases the policy agrees with: 12 of 12
classification problem: ai.review_corpus: no metadata
classification problem: marketing.audience: no metadata
audit log records: 14
chain problems, checked alone: 0
queries DuckDB ran with no decision record: 0
decision records DuckDB has no query for: 0
erasure erasure-0001: 25 rows deleted, 0 of 115 files hold the person
erasure erasure-0001, kept under an exception: billing.payments, decided by legal team, card_number erased
chain head written down, at record: 14
engine cross-check, computed again from: the audit log; the engine digests, for the two counts
engine cross-check, not computed again: the reading of DuckDB's log, and the unrecorded queries' shapes: the layer read that log once, then emptied it
レポートは合格した項目だけでなく、失敗した項目も示す。合格した検査しか示せないレポートは、何の証拠にもならないからである。ポリシーは 12 of 12 件の単体テストに合格し、誰が何を見られるかの 12 of 12 件のケースとポリシーが一致している。分類のカバレッジは完全ではない。ai.review_corpus と marketing.audience にはメタデータがない。これらは第2章と第4章で見つかった欠落であり、その間ポリシーはこれらを機微なものとして扱っている。
ログ自身の検査は問題なしと返るが、その証明力は見かけより小さい。チェーンの問題は、単独で検査した場合に 0 件である。これは、先行するレポートがヘッドを書き留めていないためである。突き合わせが捕捉するのは誤りであり、隠すつもりで書かれたコードではない(前述)。DuckDB は判定記録のないクエリを 0 件実行しており、クエリのない記録は 0 件である。
消去の行である 25 rows deleted, 0 of 115 files hold the person と billing.payments, decided by legal team, card_number erased は、ログに記録された第7章の消去から得られる。行には、リクエストの ID、テーブル、件数、例外として残した各テーブルについて governance/retention.toml が示す理由、およびスキャンの結果が含まれ、学習者の ID や値は含まれない。したがって、この記録はチェーンに加えても安全である。欧州データ保護会議は、管理者が「消去が実施されたことを検証し、その消去を実証できるようにする」ことを勧告している(EDPB, 2026)。この行が記録するのは、プラットフォーム自身のスキャンが見つけた内容である。レポートはまた、レコード 14 におけるチェーンのヘッドも書き留める。ヘッドを別のシステムに保管しておけば、それが次のレポートがチェーンを照合するための基準点になる。そこまでの任意の記録に対する編集や削除は、そのときに検出される。それより後の記録は、後のヘッドがそれを覆うようになって初めて保護される。
レポートは、いかなる法律や枠組みについても何も主張しない。何を、どのポリシーのもとで、どの入力から検査し、その結果がどうであったかを述べるだけである。
実践ルール: 証拠は記録からコードで生成し、スケジュールに従って、またポリシーを変更するたびに実行する。各節に、ポリシーのリビジョン、入力のダイジェスト、再計算に必要なものをスタンプし、誰にも再計算できない部分はその旨を述べる。レポートはログの書き込み側が変更できない場所に保管し、失敗した所見はフィルタで除かず含め、各レポートに、前回のレポートが書き留めたヘッドに対してチェーンを検査させる。レポートを生成できる場面でスクリーンショットを送ってはならない。第10章では、これらに類する検査をすべてのプルリクエストで実行する。
本番環境で何が問題になるか
監査証跡が完全でなくなっても、真実でなくなっても、読まれなくなっても、何かが壊れるわけではない。最も重大な失敗は、監査対象のコードが停止できるロギングである。DuckDB のクエリログはこの種類に当たる。クエリログは、記録対象のプロセスに属しているからである。二つの実施層が同じ攻撃に直面する。一つ目の層は、lib.audit を使わずに構築した層と同様に、設定をロックしない。この層の接続を握るコードは、ファイルへのログ出力を試み、ログを停止し、その後で層を迂回して学習者のメールアドレスを読み取る。二つ目は lib.audit の層であり、ロックされている。この層では、同様のコードがログの停止を試み、層を迂回して読み取り、その後でログを空にする。
1"""Code holding a layer's connection tries to switch DuckDB's query log off, first on a layer that doesn't lock its2configuration and then on one that does. The printed lines show the switch working on the first, failing on the second,3and the gap that emptying the log leaves in the second layer's check."""4import duckdb56from lib import audit7from lib.catalog import open_catalog8from lib.platform import scratch910AROUND = "select email from crm.learners where learner_id = 541" # a read around the enforcement layer11folder = scratch()1213# A layer that doesn't lock its configuration: code holding its connection tries a file log, then switches logging off.14unlocked = audit.Audited(open_catalog(["crm.learners"]), audit.Log(folder / "unlocked.jsonl"), lock=False)15connection = unlocked.enforcer.connection16try:17 connection.execute("set log_query_path = 'queries.log'") # the layer's connection refuses to write a file18except duckdb.Error as error:19 print("a query log in a file, on the layer's connection:", type(error).__name__)20connection.execute("CALL disable_logging()") # nothing stops the switch here21connection.sql(AROUND).fetchall() # so this read leaves nothing in DuckDB's log22for query in unlocked.check_engine_log()["unrecorded"]: # only the statements made before the switch remain23 print("unlocked, unrecorded:", query)2425# lib.audit's layer locks its configuration: switching the log off is refused, but emptying it isn't.26log = audit.Log(folder / "locked.jsonl")27locked = audit.Audited(open_catalog(["crm.learners"]), log)28locked.sql("select learner_id, email from crm.learners", "analyst-1").fetchall() # its entry in DuckDB's log is emptied below29connection = locked.enforcer.connection30try:31 connection.execute("CALL disable_logging()")32except duckdb.Error as error:33 print("locked, disable_logging():", type(error).__name__)34connection.sql(AROUND).fetchall()35connection.execute("CALL truncate_duckdb_logs()") # emptying isn't locked, so the log loses its entries36found = locked.check_engine_log()37print("locked, after truncate_duckdb_logs(), queries with no decision record:", len(found["unrecorded"]))38print("locked, decision records DuckDB has no query for:", len(found["not in the engine log"]))
python query-log-switched-off.pya query log in a file, on the layer's connection: PermissionException
unlocked, unrecorded: CALL disable_logging()
unlocked, unrecorded: SET log_query_path = ?
locked, disable_logging(): InvalidInputException
locked, after truncate_duckdb_logs(), queries with no decision record: 0
locked, decision records DuckDB has no query for: 1
ロックされていない層では、disable_logging() が成功し、その後の読み取りは何の痕跡も残さない。クロスチェックが見つけられるのは、沈黙より前の文だけである。すなわち、拒否された SET log_query_path と、CALL disable_logging() 自体である。この拒否は PermissionException である。第6章が、層の接続によるファイルへのアクセスを禁じているためである。
ロックされた層では、停止は失敗するが、ログを空にすることは失敗しない。停止は InvalidInputException で失敗するが、truncate_duckdb_logs() は成功し、その後のチェックでは記録のないクエリが 0 件見つかる。逆方向のチェックもこの欠落に気づく。決定記録のうち 1 件に対応するクエリが DuckDB のログにないため、何者かがログを空にしたと分かる。ただし、気づくのは、空にされた区間に記録が含まれていた場合に限られる。write_log でエントリを書き戻すコードは、ログを欠けのない状態に見せかけることができる。
以上のいずれも、接続を握るコードを止めることはできない。本番環境では、Trino と OPA の組み合わせのように、独立したサービスとして動作するエンジンで実施する。そうすれば、クエリを発行する者のプロセスの外でログが書かれる。統制 AU-9(2) が求めるとおり、監査記録は別のシステムに保管する。「Store audit records [Assignment: frequency] in a repository that is part of a physically different system or system component than the system or component being audited」(NIST SP 800-53 Rev. 5)。各記録は書き込まれるたびに送信し、チェーンの先頭は、さらに別の場所に保持することを推奨する。
監査証跡が損なわれる経路は、ほかにもある。
- 誰も読まないログ。 NIST のログ管理ガイドは、ログを読むべき理由を述べている。定期的なレビューは、セキュリティインシデント、ポリシー違反、不正行為、運用上の問題を、発生の直後に特定する助けになるという(§2.2、NIST SP 800-92)。書かれるだけのログは、ストレージを消費するだけで、何も守らない。アクセスレビューと証跡レポートを定期的に実施し、すべての指摘事項に担当者を置き、四半期を待てない事象については警告を出す。たとえば、クエリを拒否されたユーザーにフラグが立った場合である。
- ポリシー変更後に説明できなくなる決定。 ポリシーのリビジョンがない記録や、アーカイブされたバンドルがないリビジョンは、現行のポリシーで再生すると、自己矛盾を起こす。データドキュメントもルールと一緒にフィンガープリントを取る。データドキュメントの変更は、ルールの変更と同様に、確実に決定を変えるからである。
- 個人データを含むログ。 個人データは、さまざまな経路でログに入り込む。クエリのリテラル、エンジン自身のクエリログ、値を表示するエラーメッセージ、そして層のデバッグ出力である。エラーメッセージについては、第6章が DuckDB のキャストエラーで示したとおりである。パーサーの警告も経路の一つである。sqlglot は、文をテキストとして保持するときに警告を出し、その警告には文が引用される(sqlglot source, v30.24.0)。そのため、
lib.auditは、ユーザーのクエリを解析する間、sqlglot の警告を抑止する。監査ログには ID とダイジェストだけを残し、それ以外のログには、消去が及ぶ保存期間を設定する。 - 完全ではない決定ログ。 OPA は、
system.log.dropを通じて、ルールに従い決定イベントを破棄できる。また、「OPA will drop events if the rate limit is exceeded」とされている(OPA, decision logs)。すべての決定がログに残ったと仮定せず、クロスチェックのように、エンジンのクエリ数を決定記録と突き合わせて数える。 - ログのそばに置かれた先頭。 ログの書き手が変更できる場所に保存されたアンカーは、チェーン自体が検出できるもの以上のことを検出しない。別のシステムに、別の認証情報で保管する。
この章で決めたこと
- クエリごとに1件の記録を、クエリの実行前に実施層が書き込む。
lib.audit.Auditedは、第6章のEnforcerを変更せずにラップし、各結果を自ら取得する。記録は AU-3 の6項目を網羅しており、その中にはクエリを送信したプリンシパルとアシスタントも含まれる。 - 記録に保持するのは ID だけであり、値は保持しない。 DuckDB のどの構文で書かれたリテラルも、カタログに存在しない名前もすべて、クエリ内でも拒否理由内でも置き換えられ、コメントは除去される。DuckDB が実行した SQL は、実施層だけが持つ鍵による HMAC-SHA256 ダイジェストとして保存する。鍵があればダイジェストによって推測の正否を確認できるためである。消去は要求 ID によって記録する。
- すべての記録にポリシーのリビジョンを記す。 リビジョンとは、ポリシーのモジュールとデータドキュメントの SHA-256 であり、すべてのリビジョンは再現のためにアーカイブされる。
- 記録は SHA-256 で連鎖させ、番号を付ける。 連鎖が保護するのは、実施層の管理外に最後に書き留められた先頭までの記録だけである。各証跡レポートは先頭を書き留める。この頻度をさらに上げることを推奨する。
- DuckDB のクエリログは誤りを検出するための相互チェックであり、監査ログではない。 実施層はこのログを有効にし、その設定をロックし、前回のチェック以降の記録と双方向に照合した上で、ログを空にする。接続を保持するコードは、この仕組みを無効にできる。
- アクセスレビューと証跡レポートは、ポリシー、ログ、カタログから生成する。 各節には、ポリシーのリビジョンと入力が記される。拒否されたクエリにフラグを立てるしきい値 3 は、
governance/audit.tomlに置いた経験則である。監査証跡の信頼性は、監査対象のコードが変更できないものによって決まる。本章のチェックは、システムのどの部分をコードが変更できるかを示す。重要なのは、監査対象のコードが無効にする手段を持たない記録である。
この版における本章
第2026.11.31版2026年11月19日時点で例が通過この章の9 例件のうち9件が合格
英語版の書籍(版2026.11.31)から翻訳した。