감사와 증거

읽는 데 약 65분분 걸린다, 9절에 9개 예제이(가) 있음.

2026.11.31판 예제 통과 2026년 11월 19 108개 예제 중 108개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.31판을 번역한 것이다. 원문 읽기

이 장을 마치면 모든 접근 결정과 쿼리에 대한 감사 로그를 남길 수 있다. 로그에는 값이 들어가지 않으며, 로그를 연쇄로 묶어 수정이 드러나게 한다. 로그는 결정이 내려지는 곳에서 기록한다. 로그의 헤드, 곧 마지막 레코드의 번호와 해시는 로그를 쓰는 주체가 바꿀 수 없는 곳에 따로 적어 둔다. 그러면 그 헤드까지의 어떤 레코드든 수정하거나 삭제했을 때 이를 알아볼 수 있다. 또한 정책이 바뀐 뒤에도 과거의 결정을 설명하고, 쿼리 엔진이 실행한 내용을 직접 기록한 것과 로그를 교차 검증하며, 로그와 정책으로부터 접근 검토와 증거 보고서를 누구나 다시 실행할 수 있는 코드로 생성한다.

이 책이 다루는 온라인 학습 플랫폼에서 지원 책임자가 지난주에 분석가가 리뷰 텍스트를 읽을 수 있었던 이유를 묻거나, 감사인이 접근 규칙이 작동함을 보이라고 요구해도, 기록만으로 답할 수 있는 사람은 없다. 5장에서는 플랫폼의 접근 정책을 Rego로 작성했고, 6장의 집행 계층인 lib.enforce.Enforcer는 쿼리가 읽는 모든 테이블에 대해 정책에 결정을 요청하고, DuckDB가 결정이 허용하는 것만 반환하도록 쿼리를 재작성한다. 이 계층은 결정을 적용하고 나면 곧바로 잊는다. 모든 쿼리의 텍스트를 로그로 남기는 것이 가장 먼저 떠오르는 해결책이지만, 그렇게 하면 정책이 보호하는 대상의 사본이 하나 더 생긴다. 지원 담당자의 쿼리는 WHERE 절에 학습자의 이메일을 담을 수 있고, 7장에서 다루듯 학습자의 데이터가 간 모든 곳에서 그 학습자를 지워야 하기 때문이다.

이 장의 용어는 책에서 쓰는 뜻 그대로 정의한다. 감사 로그(audit log)는 누가 언제 무엇을 했고 결과가 어땠는지를 나중에 누군가 확인할 수 있도록 남긴 기록이다. 플랫폼의 감사 로그에는 쿼리마다 결정 레코드 하나가 들어 있다. 정책 리비전(policy revision)은 요청 외에 결정이 의존한 모든 것의 지문이다. 로그를 변경했을 때 이를 탐지할 수 있으면, 변경을 막지는 못하더라도 그 로그는 변조 탐지 가능(tamper-evident)하다고 한다. 접근 검토(access review)는 각 사람이 읽을 수 있는 것과 실제로 사용하는 것을 비교한다. 증거(evidence)는 통제가 작동함을 보이는 보고서로, 화면을 캡처한 것이 아니라 기록으로부터 생성한 것이다.

코드는 이 책의 공유 모듈 lib.audit이다. 이 모듈의 Audited 클래스는 6장의 Enforcer를 수정하지 않고 감싼다. 쿼리마다 레코드를 쓴 다음 집행 계층이 쿼리를 실행하게 한다. 대부분의 예제는 플랫폼의 하루치 쿼리인 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

마지막으로 변경된 판: 2026.11.31판

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:

decision-record.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 course assistant's two queries, sent as instructor-17: one allowed, one denied, each recorded with both identities.The point rests on the `user` and `via` lines of both records and on the denial in record 2."""from lib import auditfrom lib.catalog import open_catalogfrom lib.enforce import Deniedfrom lib.platform import scratch# Chapter 6's enforcement layer, wrapped so that every query it's given is recorded before DuckDB runs anything.log = audit.Log(scratch() / "audit.jsonl")platform = audit.Audited(open_catalog(["crm.learners", "learning.reviews"]), log)# instructor-17 asks the course assistant how their reviews look. The assistant writes the SQL; the query runs as the# instructor, with the assistant recorded as the one that sent it.question = "select course_id, count(*) as reviews, round(avg(rating), 2) as rating from learning.reviews group by all"platform.sql(question, user="instructor-17", via="assistant-1").fetchall()# Then the assistant tries to put names to the ratings, which the instructor may not see. The denial is recorded before# it's raised, so the script only needs to go on.try:    platform.sql("select l.full_name, r.rating from learning.reviews as r join crm.learners as l using (learner_id)",                 user="instructor-17", via="assistant-1").fetchall()except Denied:    passfor record in log.records():    print(f"record {record['seq']}:")    print(audit.show(record))
출력python decision-record.py
record 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).

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Keep values out of the record

마지막으로 변경된 판: 2026.11.31판

The decision record holds IDs, names of tables and columns, decisions and digests, and no value from the data its query read, because everything an audit log holds becomes data to protect. NIST's discussion of AU-3 warns that the audit trail can reveal personally identifiable information, especially when it records inputs, and its enhancement AU-3(3) asks systems to limit that information in audit records to the elements the privacy risk assessment names (NIST SP 800-53 Rev. 5). Limit, not remove: AU-3's item f asks for the principal, so every record names one, such as instructor-17, one instructor's account. The GDPR defines personal data as "any information relating to an identified or identifiable natural person" (GDPR, Article 4(1)), and a person is identifiable directly or indirectly, in particular through an identifier such as a name or an online identifier. An account ID like this one can be such an identifier. The platform has a sharper reason to keep learners out: chapter 7 erases a learner from every table their data reached, and erasing one record from the chain this chapter adds can't be told from tampering.

The risk is the query text. A support agent who looks a learner up by the email in a ticket writes that email into the query. lib.audit.normalized keeps the query's shape and drops its values: sqlglot parses the query, and every literal, in any of DuckDB's syntaxes, becomes ?. So does every name the catalog doesn't hold, such as a value typed in double quotes, except that an alias or a CTE's name the query defines becomes alias_1, alias_2 and so on. Comments, which can hold anything, are left out, and a denial's reason is recorded with the same values taken out. The SQL the layer hands DuckDB is kept only as rewritten_digest, an HMAC-SHA256 under a key only the layer holds, which the cross-check matches against DuckDB's own log. OPA starts from the whole input instead, and can be told to drop what a policy names: "queries the data.system.log.mask path prior to encoding and uploading decision logs" (OPA, decision logs). The platform's layer never writes the values at all.

Here agent-a05 looks up an EMEA learner by email, then by ID, while analyst-1 reads learners' emails, which the policy pseudonymizes. Neither value is printed; the lines below say where each is kept:

query-without-literals.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 통과
"""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.The printed lines the prose rests on are the asserts about the email and the four count lines at the end."""from lib import auditfrom lib.catalog import open_catalogfrom lib.platform import load, scratchlog = audit.Log(scratch() / "audit.jsonl")platform = audit.Audited(open_catalog(["crm.learners"]), log)# agent-a05 looks up an EMEA learner by the email in a ticket, then by their ID. Neither value is ever printed.learners = load("crm.learners").to_pylist()learner = next(row for row in learners if row["support_region"] == "emea")      # any EMEA learner will do, since the example needs only oneemail, learner_id = learner["email"], learner["learner_id"]platform.sql(f"select learner_id, full_name from crm.learners where email = '{email}'", "agent-a05").fetchall()platform.sql(f"select email, phone from crm.learners where learner_id = {learner_id}", "agent-a05").fetchall()platform.sql("select learner_id, email from crm.learners", "analyst-1").fetchall()      # pseudonymized with the keyfor record in log.records():    print("query in the record:", record["query"])engine = audit.engine_queries(platform.enforcer.connection)      # DuckDB's own query log, literals and allprint("the email, in the audit log:", email in log.path.read_text())assert email not in log.path.read_text()        # the record keeps `?` where the email was, so nothing matchesprint("the email, in DuckDB's query log:", any(email in query for query in engine))assert any(email in query for query in engine)  # DuckDB logs the SQL text it runs, literals includedprint("the pseudonymization key, in DuckDB's query log:", any(platform.enforcer.key in query for query in engine))assert not any(platform.enforcer.key in query for query in engine)print("its placeholder, in DuckDB's query log:", any("$pseudonym_key" in query for query in engine))assert any("$pseudonym_key" in query for query in engine)# Guessing which learner the agent looked up, from a list of the platform's emails: rebuild the text DuckDB ran with# each email, digest it, and compare. First with a plain SHA-256 of the query, as a log might keep, then with the# record's keyed digest, by someone without the layer's key and by someone who holds it.ran = next(query for query in engine if email in query)guesses = [ran.replace(email, row["email"]) for row in learners]    # the same text, with each learner's email in its placelogged = log.records()[0]["rewritten_digest"]                    # record 1 is the agent's lookup by emailprint("emails tried:", f"{len(guesses):,}")print("emails a plain SHA-256 of the query confirms:", sum(audit.sha256(g) == audit.sha256(ran) for g in guesses))print("emails the keyed digest confirms, without the layer's key:",      sum(audit.digest(g, "a-guessed-key") == logged for g in guesses))     # a wrong key, the only kind a guesser hasprint("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.py
query 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

The records keep WHERE email = ? and WHERE learner_id = ?, and a search of the log for the email finds nothing. DuckDB's query log does hold the email, because it records the SQL text DuckDB runs, literals included. The pseudonymization key isn't there: chapter 6 passes the key as a parameter, so DuckDB's log shows the placeholder $pseudonym_key where the key would be.

A keyed digest of a query that held an email is a pseudonym of that email, and the key is what keeps it one, as chapter 6 showed for the platform's pseudonyms. The rewrite is code in the repository, so anyone with a list of emails, from an old export or a breach, can rebuild the text DuckDB ran for each and test it. Of 5,000 emails tried, a plain SHA-256 of that text confirms 1: the learner the agent looked up. The record's keyed digest confirms 0 without the layer's key, and 1 with it. The key stays with the layer, away from anyone who reads the log, and so does the cross-check, which needs it.

DuckDB takes a value in more ways than a quoted string, and a name can hold one too. A regression test for normalized types the same learner's email, name and ID into agent-a05's queries in each of those ways. Those requests leave these traces, one record each:

query-shape-hard-cases.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 통과
"""Eleven places to type a learner's values into a query, and what each record keeps of it: the query's shape, with a`?` for each value and each name the catalog doesn't hold, and a numbered alias for each alias or CTE the query defines.The printed count of records that hold the email, the name or the IDis the line the prose rests on."""import jsonimport refrom lib import auditfrom lib.catalog import open_catalogfrom lib.enforce import Deniedfrom lib.platform import load, scratchlog = audit.Log(scratch() / "audit.jsonl")platform = audit.Audited(open_catalog(["crm.learners"]), log)# An EMEA learner's email, name and ID, typed into agent-a05's queries as values and as names. None is ever printed.learner = next(row for row in load("crm.learners").to_pylist() if row["support_region"] == "emea")email, name, learner_id = learner["email"], learner["full_name"], learner["learner_id"]cases = {                                                 # each query puts the same values in one more way    "a string": f"select learner_id from crm.learners where email = '{email}'",    "a dollar-quoted string": f"select learner_id from crm.learners where email = $${email}$$",    "an escape string": f"select learner_id from crm.learners where email = e'{email}'",    "a list": f"select learner_id from crm.learners where email in ['{email}']",    "a number": f"select email from crm.learners where learner_id = {learner_id}",    "a comment": f"select email from crm.learners where learner_id = {learner_id} -- {name}",    "a name in double quotes": f'select learner_id from crm.learners where full_name = "{name}"',    # a column, to DuckDB    "a column alias": f'select learner_id as "{email}" from crm.learners',    "a table alias": f'select "{name}".email from crm.learners as "{name}"',    "a CTE's name": f'with "{email}" as (select learner_id from crm.learners) select learner_id from "{email}"',    "a table the catalog doesn't hold": f'select learner_id from "{email}"',}for query in cases.values():    try:        platform.sql(query, "agent-a05").fetchall()      # a denial is recorded, then raised: the script carries on    except Denied:        pass# What each record keeps of its query. The email or the name anywhere in its line, or the ID in what it keeps, is a# value that got through, and is never printed.held = []for case, line in zip(cases, log.lines()):               # one record per query, in the order they ran    record = json.loads(line)    kept = record["query"] + (f" (denied: {record['denial']})" if record["denial"] else "")    held.append(email in line or name in line or bool(re.search(rf"\b{learner_id}\b", kept)))     # the ID as a whole word    print(f"{case}:", "(holds a value)" if held[-1] else kept)print("records holding the email, the name or the ID:", sum(held), "of", len(cases))
출력python query-shape-hard-cases.py
a 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

Each record keeps the query's shape and none of its values, allowed or denied alike. The last line counts the records that hold the email, the name or the ID: 0 of 11.

Two things are lost. The normalized text drops harmless values and names too: in the first record, ROUND(AVG(rating), 2) became ROUND(AVG(rating), ?), and in the second, the aliases r and l became alias_2 and alias_1. And the log can't answer "who looked up this learner?". When the platform needs that answer, for a learner who asks who has read their data, keep it in a separate access log, with learner IDs, a retention period and no chain, which chapter 7's erasure reaches like any other table.

Working rule: Record a query's shape, never its values: replace every literal, in every syntax the engine accepts, and every name the catalog doesn't hold, drop comments, take the same values out of denial reasons, and keep the executed SQL only as a keyed digest whose key the log's readers never get. Never use a plain hash of text that may hold personal data. When you need to know who read one person's data, keep that in a separate log that retention and erasure reach, not in the tamper-evident one.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Replay an old decision under its own policy

마지막으로 변경된 판: 2026.11.31판

A decision record holds the request, but a decision depends on three things: the request, the policy's rules, and the data the policy reads. The last two change all the time. The platform's policy reads governance/users.toml, governance/metadata.toml and learning.courses, as chapter 5 set up, so a support agent moved to another region, or a course added to learning.courses, changes decisions without anyone touching Rego. If a record says nothing about what the policy was, its decision can't be explained once either changes: replayed later, it gives a different answer, and the log looks wrong. OPA records the policy's version as bundles[_].revision. For policies that call non-deterministic built-ins, such as the time or an HTTP request, OPA can also log their results in nd_builtin_cache, which exists for debugging and decision replay (OPA, decision logs). The platform's policy calls none.

lib.audit.bundle puts together the policy's modules and its data document, the facts the policy reads, generated from those three sources, as OPA ships them in a bundle. lib.audit.revision is the SHA-256 of that bundle: a fingerprint that changes when any rule changes, or any fact the policy reads. Every record carries the revision that decided it. lib.audit.Archive keeps every bundle the layer has used, under its revision, so a decision can be made again under the policy that made it. A bundle holds rules and the attributes of the platform's users, not data about learners, so the archive can be kept as long as the log.

On the platform, analyst-1 reads learners' emails and gets pseudonyms. Suppose a later pull request adds it to support for EMEA, the change chapter 6 caught with its who-sees-what test. The old record is replayed under each revision:

explain-old-decision.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 통과
"""Replays a logged decision under the revision it was made with and under the current one, after a change to the usersfile alone. The printed email and match lines are the point: only the archived revision explains the record."""from lib import audit, policyfrom lib.catalog import open_catalogfrom lib.platform import scratchfolder = scratch()archive = audit.Archive(folder / "bundles")         # every policy revision that has decided anything, by revisionlog = audit.Log(folder / "audit.jsonl")# analyst-1 reads learners' emails, which the policy pseudonymizes.platform = audit.Audited(open_catalog(["crm.learners"]), log, archive=archive)platform.sql("select learner_id, email from crm.learners", "analyst-1").fetchall()record = log.records()[0]# Later, a pull request adds analyst-1 to support for EMEA, as in chapter 6. Only users.toml changes, which reaches# the policy through its data document, and no Rego.data = policy.data_document()data["platform"]["users"]["analyst-1"] = {"groups": ["data-science", "support"], "region": "emea"}current, logged = audit.bundle(data=data), archive.get(record["policy_revision"])     # the bundle the record was decided underprint("logged under revision:", record["policy_revision"][:12])print("current revision:", audit.revision(current)[:12])modules_changed = current["modules"] != logged["modules"]assert not modules_changed                      # no Rego changed, so the policy modules are the sameprint("policy modules changed:", modules_changed)data_changed = current["data"] != logged["data"]assert data_changed                             # the data document is the only part that changedprint("data document changed:", data_changed)# Explain the logged decision by making it again, from the request the record holds, under each revision.print("email, as logged:", record["decisions"][0]["column_masks"].get("email", "shown as stored"))for name, revision in [("the current revision", current), ("the logged revision", logged)]:    again = audit.replay(record, revision)    matches = again == record["decisions"]    assert matches == (revision is logged)      # only the revision the record was decided under explains it    print(f"under {name}, email:", again[0]["column_masks"].get("email", "shown as stored"))    print(f"under {name}, the decision matches the log:", matches)
출력python explain-old-decision.py
logged 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

The revision changed, from f761e4ad08d4 to 0350e789b34d, though no Rego did. The policy modules are the same, and the data document, which now lists the new membership, is not. A fingerprint of the policy files alone would have missed the change. Replayed under the current revision, the decision doesn't match the log: email is shown as stored, because support sees contact details. An investigator holding only the current policy would conclude the log, or the layer, was wrong. Replayed under the logged revision from the archive, email is pseudonymize again, and the decision matches the log.

Replay explains the decision, not the rows. A row filter is replayed as a rule, such as support's region or the consent filter learner_consented, and which rows passed it depended on that day's data, which may have changed since, or been erased. That split is by design: the log says what the rule was, and the tables, with their own snapshots and retention, say what it matched.

Working rule: Fingerprint every decision with a hash of everything it depended on besides the request: the policy's modules and its data document, together. Archive each revision for as long as you keep the log, and explain an old decision by replaying it under its own revision, never under the current one. If a policy reads the clock or calls another service, log those results too, as OPA's nd_builtin_cache does.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Chain the records so an edit shows

마지막으로 변경된 판: 2026.11.31판

The platform's decision records are evidence only if a change to them can be detected. SP 800-53 asks systems to "Protect audit information and audit logging tools from unauthorized access, modification, and deletion" (AU-9), and, in AU-9(3), to "Implement cryptographic mechanisms to protect the integrity of audit information and audit tools". Its AU-9(3) discussion offers, as an example, "signed hash functions using asymmetric cryptography" (NIST SP 800-53 Rev. 5), which only the holder of a private key can make. The platform's chain, below, is not that, and protects nothing on its own. NIST's guide to log management, SP 800-92, describes the plainest mechanism: a message digest for each log file, stored securely, so that a change to an archived log is detected (NIST SP 800-92). The guide dates from 2006. It names MD5 and SHA-1 as the common digests of its day, and its own footnote 25 advises SHA-256, which the platform uses.

A digest per file detects a change to a closed file. A hash chain detects a change to a log that's still growing: every record carries a sequence number, seq, and the SHA-256 of the line before it, prev_hash, so changing a record breaks the link to the next one, and removing one leaves a gap. lib.audit.check walks the chain and reports each break. A chain is tamper-evident, not tamper-proof. Schneier and Kelsey designed a log in which an attacker who takes over the logging machine can neither read nor falsify the entries written before. Even there, the attacker "can delete a block of entries (or the entire log file)", and the trusted party the log reports to notices only the next time the machine contacts it (Schneier and Kelsey, 1999). A plain chain like the platform's is weaker: anyone who can write the file can rebuild it, renumbering as they go. So what it proves depends on a chain's head, the number of records and the hash of the last one, written down where the log's writer can't change it. An edit to, or a removal of, any record up to that head shows, however it's hidden. After the head, a chain rebuilt or cut passes every check, and without a head, so does a chain rebuilt from the start. check takes the head as an anchor.

To test the chain, the example replays lib.audit.DAY, the 13 queries the platform received on Oct 1, and writes the head down at noon, at record 9. Then it tampers with copies of the log in five ways. Before noon, record 3, agent-a05's lookup of a learner's contact details, is handed to another agent, once as a plain edit and once with the chain rebuilt. After noon, record 12, the denied read by someone-else, the user the platform doesn't know, is removed, once plainly and once with the chain rebuilt; and the day's last two records are cut off. Before you run it, predict which of the five the chain finds on its own, and which against the noon head.

chain-catches-edit.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 통과
"""Replays the day's queries into a chained log, writes the head down at noon, then tampers with copies of the log fiveways and checks each against the chain alone and against the noon head. The point rests on the two checks of eachchange: the chain finds the plain edit and the plain removal on its own, and only the head finds the rebuilt chain."""import jsonfrom lib import auditfrom lib.catalog import open_catalogfrom lib.platform import scratchlog = audit.Log(scratch() / "audit.jsonl")platform = audit.Audited(open_catalog(["crm.learners", "learning.reviews", "billing.payments", "support.tickets"]), log)audit.run_day(platform, [query for query in audit.DAY if query[0] < "12:00"])     # the morning; times compare as stringsanchor = log.head()                               # the head, written down at noon somewhere the log's writer can't reachaudit.run_day(platform, [query for query in audit.DAY if query[0] >= "12:00"])    # the afternoonlines = log.lines()print("records:", len(lines))print("head written down at noon, at record:", anchor["records"])print("record 3:", json.loads(lines[2])["user"], "reads", json.loads(lines[2])["query"])     # record 3 is index 2def rechained(lines: list[str]) -> list[str]:    """The chain built again, every record renumbered and every prev_hash recomputed: what anyone who can rewrite the    log's file can do."""    rebuilt, previous = [], audit.GENESIS          # the first record points at 64 zeros, not at a record    for seq, line in enumerate(lines, start=1):        rebuilt.append(audit.canonical(json.loads(line) | {"seq": seq, "prev_hash": previous}))        previous = audit.sha256(rebuilt[-1])    return rebuilt# Before noon, record 3 handed to another agent. After noon, record 12 (someone-else's denied read) removed, and the# day's last two records cut off.edited = lines[:2] + [audit.canonical(json.loads(lines[2]) | {"user": "agent-a01"})] + lines[3:]     # index 2 is record 3removed = lines[:11] + lines[12:]                                                                    # index 11 is record 12for name, version in [("untouched", lines), ("record 3 edited", edited), ("record 3 edited, chain rebuilt", rechained(edited)),                      ("record 12 removed", removed), ("record 12 removed, chain rebuilt", rechained(removed)),                      ("last 2 records removed", lines[:-2])]:    print(f"{name}, checked alone:", "; ".join(audit.check(version)) or "no problem found")    print(f"{name}, checked against the noon head:", "; ".join(audit.check(version, anchor)) or "no problem found")
출력python chain-catches-edit.py
records: 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

On its own, the chain catches the plain edit, record 3 was changed: record 4 doesn't follow it, and the plain removal, record 12 is missing: record 13 follows record 11, and nothing else. It misses both rebuilt chains, which are consistent from start to end, and the cut, since no record follows the last one to notice.

A head protects only the records written before it. Against the noon head, the edit made before noon still shows with the chain rebuilt, the chain no longer passes through the head written down at record 9. Everything hidden after noon passes: the removal with the chain rebuilt gives no problem found, and the cut gives no problem found.

This is why the rule about values isn't optional. Erasing a learner from a chained log means changing or removing a record, and wherever a check can see that, it can't tell it from tampering. A log that holds no data about learners never meets chapter 7's erasure. The IDs of the people who query are another matter: give the log a retention period, and start a new chain each period, with its last head written down, so a whole period can be deleted when it expires.

Checking a chain means re-reading every record. Crosby and Wallach describe tree-shaped logs that can prove "that individual logged events are still present, and that the log, as seen now, is consistent with how it was seen in the past", with proofs of logarithmic size, an improvement on earlier linear constructions (Crosby and Wallach, 2009). For one platform's own log we recommend a chain checked daily, and a tree when outside parties audit a log too large to re-read.

Working rule: Chain every record to the one before with SHA-256 and a sequence number, and count on the chain to protect only the records up to the last head written down outside the layer's control. Write the head down often, to an append-only store or to another system under other credentials, as often as the number of unprotected records you can accept; if that number is zero, send each record off the machine as it's written. Check the chain against the last head on a schedule. If you need what AU-9(3) describes, have each head signed by a system whose key the layer never holds. Never chain a record that might one day have to be erased for one person; let whole periods expire instead.

로그를 DuckDB의 쿼리 로그와 대조하기

마지막으로 변경된 판: 2026.11.27판

플랫폼의 감사 로그는 집행 계층을 거치는 모든 쿼리를 기록하며, 기록하는 것은 그 쿼리뿐이다. 노트북 도우미나 연결을 넘겨받은 테스트가 계층의 DuckDB 연결에서 직접 실행한 쿼리에는 결정도 기록도 남지 않는다. 이를 알아채려면 엔진이 보관하는 두 번째 기록이 필요하다. DuckDB 2.0.0에는 그런 기록이 있으며 기본값은 꺼짐이다. DuckDB의 로깅 프레임워크에는 DuckDB가 실행하는 쿼리를 기록하는 QueryLog 유형이 있다. 이 유형은 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의 로그를 비운다. 관계(relation)의 쿼리는 "Output 절의 메서드가 그 관계를 읽을 때 실행되며, 읽을 때마다 다시 실행된다"(DuckDB, relational API). 또 좁혀진 관계는 어떤 기록도 DuckDB에 넘기지 않은 자체 SQL을 실행한다. 그래서 Audited.sql는 각 결과를 직접 한 번 가져온 뒤 그 행들을 자체 연결의 관계로 돌려준다. 호출자가 그것으로 무엇을 하든 DuckDB의 로그에는 허용된 쿼리가 한 번씩만 남는다.

첫 번째 검사는 그날의 13개 쿼리를 재실행하여 검사한다. 이어서 계층을 통해 쿼리 두 개가 더 실행된다. 하나는 호출자가 결과를 가져가지 않는 쿼리이고, 다른 하나는 다섯 행으로 좁히는 쿼리이다. 또 노트북 도우미가 계층을 우회하여 계층의 연결로 학습자의 이메일을 읽는다. 그다음 두 번째 검사가 이어진다.

query-log-cross-check.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 통과
"""DuckDB's query log checked against the audit log: first on the day's queries, then after two more queries through thelayer and a read around it. The point rests on the last check's unrecorded query, the one read that bypassed the layer."""from lib import auditfrom lib.catalog import open_catalogfrom lib.platform import scratchlog = audit.Log(scratch() / "audit.jsonl")platform = audit.Audited(open_catalog(["crm.learners", "learning.reviews", "billing.payments", "support.tickets"]), log)day = audit.run_day(platform)print("queries allowed:", day["allowed"])print("queries denied:", day["denied"])# DuckDB's own query log, kept on the layer's connection, against the records written since the last check. The check# then empties DuckDB's log, which holds the queries' values.found = platform.check_engine_log()print("queries DuckDB ran:", found["engine queries"])print("queries DuckDB ran with no decision record:", len(found["unrecorded"]))# Two more queries through the layer: one whose caller never fetches it, and one the caller narrows to five rows.platform.sql("select learner_id, country from crm.learners", "analyst-1")        # the layer fetches it, so DuckDB logs it onceplatform.sql("select learner_id, country from crm.learners", "analyst-1").limit(5).fetchall()    # narrowed after the layer's fetch# Then a notebook helper that was handed the layer's connection reads a learner's email with it, around the layer.platform.enforcer.connection.sql("select email from crm.learners where learner_id = 541").fetchall()    # no record for this onefound = platform.check_engine_log()print("next check, records checked:", " to ".join(map(str, found["records checked"])))print("next check, queries with no decision record:", len(found["unrecorded"]))for query in found["unrecorded"]:    print("unrecorded:", query)print("next check, decision records DuckDB has no query for:", len(found["not in the engine log"]))
출력python query-log-cross-check.py
queries 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개를 실행했다. 허용된 쿼리마다 하나씩이고 거부된 쿼리에는 없으며, 기록이 없는 쿼리는 0개이다.

다음 검사는 계층을 우회한 읽기만 찾아내고 다른 것은 찾지 않는다. 이 검사는 14 to 15개의 기록과 계층을 통과한 두 쿼리를 대상으로 하며 경보를 울리지 않는다. 계층을 우회한 읽기는 결정 기록이 없는 쿼리 1개로 나타나고, 값은 출력되지 않는다. 마지막 줄은 반대 방향을 검사하여, DuckDB에 쿼리의 흔적이 없는 기록을 찾는다. 여기서는 0개이다.

이 검사가 무엇을 잡아내는지는 연결을 누가 쥐고 있는지에 달려 있다. DuckDB의 로그를 건드리지 않는 코드가 계층을 우회해 읽은 경우는 잡아낸다. 이 노트북 도우미, 테스트, 실수로 연결을 넘겨받은 작업이 그런 예이다. 그러나 연결을 쥐고 숨기려는 코드는 잡아내지 못한다. 검사 직후에 읽고 계층의 다음 쿼리 전에 DuckDB의 로그를 다시 비우면, 어느 방향으로도 찾아낼 것이 남지 않는다. 또 DuckDB의 write_log 함수는 로그 유형을 인자로 받으므로 QueryLog 항목을 쓸 수 있다(DuckDB source, v2.0.0). 설정 잠금은 함수를 막지 못한다. 이런 코드에 대한 보증에는 연결을 쥔 프로세스 바깥에 기록되는 엔진 로그가 필요하다.

이 검사는 계층 자신의 지름길도 찾아낸다. 6장의 observe가 그 예로, 사용자 없이 계층의 연결로 저장된 테이블을 읽는다. 이런 쿼리는 검사에서 예외로 두지 말고 계층을 사용자로 하는 자체 기록을 만들어 주어라.

작업 규칙: 정책을 집행하는 모든 곳에서 엔진 자체의 쿼리 로그를 켜고, 모든 결과를 계층 안에서 가져오며, 마지막 검사 이후 기록된 레코드와 대조해 정해진 주기로 로그를 검사하라. 검사는 양방향으로 한다. 엔진이 실행한 모든 쿼리는 기록과 맞아야 하고, 허용된 모든 기록은 쿼리와 맞아야 한다. 검사 후에는 쿼리의 값을 보관하므로 로그를 비운다. 불일치는 걸러낼 잡음이 아니라 원인을 밝혀야 할 사고로 다룬다. 이 검사는 실수를 잡아내리라고 기대해야 하며, 연결을 쥐고 숨기려는 코드를 잡아내리라고 기대해서는 안 된다. 그런 코드에는 프로세스 바깥에 기록되는 로그만 도움이 된다. 엔진의 로그를 감사 로그로 쓰지 마라. 그 로그에는 사용자도 결정도 없다.

로그로 접근 검토 생성하기

마지막으로 변경된 판: 2026.11.27판

플랫폼의 감사 로그는 각 사람이 무엇을 읽었는지 알려 주고, 정책은 각 사람이 무엇을 읽을 수 있는지 알려 준다. 접근 검토는 이 둘을 나란히 놓는 일이다. SP 800-53은 조직이 계정 관리 요구 사항을 준수하는지 계정을 검토하라고 요구하고(AC-2 j), 역할과 분류에 할당된 권한을 정해진 주기로 검토하여 그 필요성을 확인하고 필요하면 권한을 재할당하거나 제거하라고 요구한다(AC-6(7)) (NIST SP 800-53 Rev. 5). 누가 어떤 역할을 가졌는지의 목록은 필요성에 대해 아무것도 말해 주지 않으므로 이 두 요구에 모두 답하지 못한다. 검토에 필요한 사실은 코드로 계산할 수 있다. 정책이 각 사람에게 허용하는 것, 로그에 나타난 사용 내역, 거부된 내역, 아무것도 가리키지 않는 멤버 지정이 그 사실이다. 접근을 제거할지는 여전히 데이터 소유자가 결정할 일이다.

lib.audit.review는 users.toml에 있는 모든 사용자에 대해 모든 테이블을 상대로 플랫폼의 정책을 평가하고 로그를 읽은 다음, 사용자마다 읽을 수 있는 테이블, 읽은 테이블, 사용하지 않은 권한, 거부된 쿼리와 그 쿼리를 보낸 어시스턴트, 그리고 누군가 살펴봐야 할 항목을 나열한다. 찾아낼 오래된 항목을 마련하기 위해, 예제는 사용자에 analyst-2를 추가한다. 이 사용자는 여전히 bi에 속해 있지만, 정책에는 더 이상 그 그룹이 없다. 그룹을 폐기하고 아무도 사용자 파일을 고치지 않으면 이런 일이 생긴다.

access-review.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 통과
"""An access review of every user in the users file, and every user the log names, against the policy and the day's log,with a stale group membership added to find. The printed `look at` lines and the grants-not-used count are what the proserests on."""from lib import audit, policyfrom lib.catalog import open_catalogfrom lib.platform import TABLES, scratchlog = audit.Log(scratch() / "audit.jsonl")platform = audit.Audited(open_catalog(["crm.learners", "learning.reviews", "billing.payments", "support.tickets"]), log)audit.run_day(platform)      # the day's queries, so that the review has a log to read# users.toml as the review finds it: analyst-2 is still listed in bi, a group the policy no longer has.data = policy.data_document()data["platform"]["users"]["analyst-2"] = {"groups": ["bi"]}rows = audit.review(audit.bundle(data=data), log.records(), TABLES)      # all eight of the platform's tablesfor row in rows:    print(f"{row['user']}: may read {len(row['may read'])}, read {len(row['read'])}, denied {row['denied']}"          + (f" (sent by {', '.join(row['denied via'])})" if row["denied via"] else ""))    if row["unused"]:            # a grant unused: a table the policy lets the user read, and the log never shows them reading        print("  not used:", ", ".join(row["unused"]))    for finding in row["findings"]:        print("  look at:", finding)print("users reviewed:", len(rows))print("grants not used:", sum(len(row["unused"]) for row in rows))print("users to look at:", sum(bool(row["findings"]) for row in rows))     # any finding at all needs a personprint("denied queries flagged at:", audit.settings()["review"]["denied_queries_flagged"])     # from governance/audit.toml
출력python access-review.py
agent-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일 동안 14개의 권한이 사용되지 않았고, agent-a01와 agent-a09은 아무것도 읽지 않았다. 지원 부서는 교대로 일하고 재무 부서는 월 마감 때에만 일부 테이블을 읽으므로, 하루는 누군가의 접근을 제거하기에 너무 짧다. 따라서 이 수치는 결정이 아니라 단서이다. 분기처럼 검토 기간 전체 동안 사용되지 않은 권한을 테이블 소유자에게 가져가야 한다. 3명의 사용자는 사람이 살펴봐야 한다.

  • analyst-2는 어떤 규칙도 모르는 그룹에 속해 있다. 이 멤버 지정은 현재 아무것도 허용하지 않지만, 앞으로 bi에 대한 규칙이 생기면 그 규칙이 허용하는 것을 모두 허용하게 되므로 제거해야 한다.
  • someone-else는 users.toml에 없으므로, 플랫폼이 모르는 주체가 학습자의 이메일을 읽으려 한 것이다.
  • instructor-17의 줄은 may read 3, read 1, denied 3 (sent by assistant-1)로 표시된다. 어시스턴트가 강사의 첫 질문에 답한 뒤 2분 동안 학습자 테이블, 리뷰와 조인한 학습자 테이블, 티켓 테이블을 차례로 시도했다. 이것은 어시스턴트가 테이블을 하나씩 시도하는 것이며, via가 없었다면 검토는 강사를 탓했을 것이다.

표시 기준인 거부된 쿼리 3건은 경험칙이며, 그 근거와 함께 governance/audit.toml에 보관한다. 그래야 기준을 바꾸는 일이 정책 변경처럼 검토를 거치는 변경이 된다.

작업 규칙: 접근 검토는 역할 멤버 목록이 아니라 정책과 감사 로그로 생성한다. 각 사람이 읽을 수 있는 것과 읽은 것, 거부 내역, 정책이 더 이상 알지 못하는 멤버 지정을 대조한다. 분기처럼 모든 업무의 주기를 포괄할 만큼 긴 기간에 걸쳐 실행하고, 각 발견 사항은 해당 테이블이나 그룹의 소유자에게 보낸다. 기간 동안 아무도 사용하지 않은 권한은, 소유자가 필요한 이유를 밝히지 않는 한 제거한다.

증거를 데이터로 생성하기

마지막으로 변경된 판: 2026.11.27판

체인 검사, 교차 검증, 접근 검토는 팀 바깥의 누군가가 확인할 수 있을 때 가치가 가장 크다. EU의 일반 데이터 보호 규정(GDPR)은 책임성 원칙으로 이 의무를 조직에 부과한다. "컨트롤러는 제1항을 준수할 책임을 지며, 그 준수를 입증할 수 있어야 한다('책임성')"(GDPR, Article 5(2)). 무엇이 입증에 해당하는지는 법률가가 판단할 문제이며, 이 절은 코드가 무엇을 생성할 수 있는지를 보인다. 계정 관리에 대한 NIST의 평가 절차는 평가자가 검토하는 기록을 명시하는데, 접근 승인 기록, 계정 관리 준수 검토, 시스템 감사 기록이 여기에 속한다(NIST SP 800-53A Rev. 5, NIST의 OSCAL 카탈로그). 콘솔 화면 캡처는 이 가운데 어느 것도 아니다. 누구도 그것을 다시 실행할 수 없고, 지난 분기의 것과 비교할 수 없으며, 어떤 정책을 보여 준 것인지 알 수도 없다.

lib.audit.evidence은 기록과 코드로 플랫폼의 보고서를 만들며, 보고서는 다음 절들로 구성된다.

  • 정책, 그리고 각 모듈과 데이터 문서의 다이제스트
  • 5장의 정책 단위 테스트
  • 정책과 대조하여 검사한 누가 무엇을 보는지 표
  • 2장의 메타데이터 검사에서 나온 분류 적용 범위
  • 감사 로그의 체인 검사
  • DuckDB 로그와의 교차 검증
  • 로그에 기록된 삭제
  • 접근 검토

모든 절에는 계산에 사용한 정책 리비전, 입력의 다이제스트, 그리고 다른 사람이 같은 결과를 다시 계산하는 데 필요한 것이 명시된다. 필요한 것은 보관된 번들, 테스트 파일, metadata.toml와 테이블의 스키마, 감사 로그이다. 엔진 교차 검증은 일부만 다시 계산할 수 있으며, 보고서는 이를 밝힌다. 보고서는 DuckDB가 실행한 모든 쿼리의 키 기반 다이제스트를 보관하므로 로그를 가진 사람은 누구나 두 가지 집계를 다시 구할 수 있다. 그러나 DuckDB의 로그를 읽을 수 있었던 것은 로그를 비우기 전 한 번뿐이었던 계층뿐이다. 10월 1일의 보고서를 생성한다. 카탈로그의 모든 테이블과 파이프라인 출력, 07:00에 기록된 7장의 학습자 삭제, 그리고 그날의 쿼리를 대상으로 한다.

evidence-report.py Python 3.12.15 · duckdb 2.0.0 · openlineage-python 1.55.0 · pyarrow 26.0.1 · pyiceberg 0.12.0 · pyyaml 6.0.3 · regopy 1.5.2 · sqlglot 30.33.0 통과
"""The platform on Oct 1, after an erasure and the day's queries: the first evidence report, written to a file as data, witheach section's result printed. The printed checks, the erasure's lines and the head are what the prose rests on."""import jsonfrom datetime import timedeltafrom lib import audit, retentionfrom lib.platform import scratch# The platform on Oct 1: every table and pipeline output, chapter 7's erasure of learner 3590 at 07:00, then the day's# queries through the audited layer.catalog, graph = retention.open_platform(statistics_off=True)      # statistics off for personal columns: each table rewritten under them, old files sweptlog = audit.Log(scratch() / "audit.jsonl")_, found, done = retention.erase_everywhere(catalog, graph, 3590, "erasure-0001", min_age=timedelta(0))    # zero: no file age guardaudit.record_erasure(log, "erasure-0001", done, retention.scan(catalog, found), at=audit.MIDNIGHT.replace(hour=7))platform = audit.Audited(catalog, log)audit.run_day(platform)# The first report, so there's no head from an earlier one to check the chain against.report = audit.evidence(platform, catalog, anchor=None)reports = scratch()          # in production, another system, which the log's writer can't change(reports / "evidence-2026-10-01.json").write_text(json.dumps(report, indent=2, sort_keys=True), encoding="utf-8")result = {name: section["result"] for name, section in report.items()}print("sections:", ", ".join(report))print("policy tests passed:", f"{result['policy tests']['passed']} of {result['policy tests']['of']}")print("who-sees-what cases the policy agrees with:", f"{result['who sees what']['agree']} of {result['who sees what']['of']}")for problem in result["classification coverage"]["problems"]:    print("classification problem:", problem)print("audit log records:", result["audit log"]["records"])print("chain problems, checked alone:", len(result["audit log"]["chain problems"]))print("queries DuckDB ran with no decision record:", len(result["engine cross-check"]["unrecorded"]))print("decision records DuckDB has no query for:", len(result["engine cross-check"]["not in the engine log"]))for erasure in result["erasures"]:    print(f"erasure {erasure['request']}: {erasure['rows_deleted']} rows deleted, "          f"{erasure['files_holding_the_person']} of {erasure['files_read']} files hold the person")    for kept in erasure["kept"]:        print(f"erasure {erasure['request']}, kept under an exception: {kept['table']}, decided by {kept['decided_by']},",              f"{', '.join(kept['columns_erased'])} erased")print("chain head written down, at record:", report["audit log"]["inputs"]["head"]["records"])     # the next report's anchorprint("engine cross-check, computed again from:", "; ".join(report["engine cross-check"]["computed again from"]))print("engine cross-check, not computed again:", report["engine cross-check"]["not computed again"])
출력python evidence-report.py
sections: 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장은 이와 같은 검사를 모든 풀 리퀘스트에서 실행한다.

운영 환경에서 잘못되는 것

마지막으로 변경된 판: 2026.11.27판

감사 추적이 완전하지 않거나, 사실이 아니거나, 아무도 읽지 않게 되어도 눈에 띄게 깨지는 것은 없다. 가장 중요한 실패는 감사 대상 코드가 끌 수 있는 로깅이며, DuckDB의 쿼리 로그가 바로 그런 종류다. 쿼리 로그는 그것이 기록하는 프로세스에 속해 있기 때문이다. 두 개의 시행 계층이 같은 공격을 받는다. 첫 번째 계층은 lib.audit 없이 만든 계층이 모두 그렇듯 설정을 잠그지 않는다. 이 계층의 연결을 쥔 코드는 로그를 파일에 쓰려 하고, 로그를 끈 다음, 계층을 우회하여 학습자의 이메일을 읽는다. 두 번째 계층은 lib.audit의 계층으로 잠겨 있다. 이 계층에서 그런 코드는 로그를 끄려 하고, 계층을 우회하여 읽은 다음, 로그를 비운다.

query-log-switched-off.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 통과
"""Code holding a layer's connection tries to switch DuckDB's query log off, first on a layer that doesn't lock itsconfiguration and then on one that does. The printed lines show the switch working on the first, failing on the second,and the gap that emptying the log leaves in the second layer's check."""import duckdbfrom lib import auditfrom lib.catalog import open_catalogfrom lib.platform import scratchAROUND = "select email from crm.learners where learner_id = 541"       # a read around the enforcement layerfolder = scratch()# A layer that doesn't lock its configuration: code holding its connection tries a file log, then switches logging off.unlocked = audit.Audited(open_catalog(["crm.learners"]), audit.Log(folder / "unlocked.jsonl"), lock=False)connection = unlocked.enforcer.connectiontry:    connection.execute("set log_query_path = 'queries.log'")       # the layer's connection refuses to write a fileexcept duckdb.Error as error:    print("a query log in a file, on the layer's connection:", type(error).__name__)connection.execute("CALL disable_logging()")                       # nothing stops the switch hereconnection.sql(AROUND).fetchall()                                  # so this read leaves nothing in DuckDB's logfor query in unlocked.check_engine_log()["unrecorded"]:            # only the statements made before the switch remain    print("unlocked, unrecorded:", query)# lib.audit's layer locks its configuration: switching the log off is refused, but emptying it isn't.log = audit.Log(folder / "locked.jsonl")locked = audit.Audited(open_catalog(["crm.learners"]), log)locked.sql("select learner_id, email from crm.learners", "analyst-1").fetchall()     # its entry in DuckDB's log is emptied belowconnection = locked.enforcer.connectiontry:    connection.execute("CALL disable_logging()")except duckdb.Error as error:    print("locked, disable_logging():", type(error).__name__)connection.sql(AROUND).fetchall()connection.execute("CALL truncate_duckdb_logs()")                  # emptying isn't locked, so the log loses its entriesfound = locked.check_engine_log()print("locked, after truncate_duckdb_logs(), queries with no decision record:", len(found["unrecorded"]))print("locked, decision records DuckDB has no query for:", len(found["not in the engine log"]))
출력python query-log-switched-off.py
a 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로 항목을 다시 써넣는 코드라면 로그는 온전해 보일 것이다.

이 중 어느 것도 연결을 쥔 코드를 막지 못한다. 운영 환경에서는 OPA를 붙인 Trino처럼 독립된 서비스로 실행되는 엔진에서 시행하여, 쿼리하는 사람의 프로세스 바깥에서 로그가 기록되게 한다. 통제 항목 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 소스, v30.24.0), lib.audit는 사용자의 쿼리를 파싱하는 동안 sqlglot의 경고를 억제한다. 감사 로그에는 ID와 다이제스트만 남기고, 다른 모든 로그에는 삭제 요청이 미치는 보존 기간을 둔다.
  • 완전하지 않은 결정 로그. OPA는 system.log.drop를 통해 규칙에 따라 결정 이벤트를 버릴 수 있으며, "OPA will drop events if the rate limit is exceeded"(OPA, decision logs)라고 한다. 모든 결정이 기록되었다고 가정하지 말고, 교차 검증처럼 엔진의 쿼리 수를 결정 기록과 대조하여 센다.
  • 로그 옆에 보관된 헤드. 로그의 기록자가 바꿀 수 있는 곳에 저장된 앵커는 체인이 이미 탐지하는 것 이상은 탐지하지 못한다. 다른 시스템에 다른 자격 증명으로 보관한다.

이 장에서 결정한 것

마지막으로 변경된 판: 2026.11.27판
  • 질의마다 기록을 하나씩 남기며, 기록은 질의가 실행되기 전에 집행 계층이 쓴다. lib.audit.Audited는 6장의 Enforcer를 수정하지 않고 감싸며, 각 결과도 직접 가져온다. 기록에는 AU-3의 여섯 항목이 들어 있고, 질의를 보낸 주체와 어시스턴트도 그 안에 포함된다.
  • 기록에는 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판을 번역한 것이다.

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

10장 중 8장: 감사와 증거

  1. Record every decision where it's made
  2. Keep values out of the record
  3. Replay an old decision under its own policy
  4. Chain the records so an edit shows
  5. 로그를 DuckDB의 쿼리 로그와 대조하기
  6. 로그로 접근 검토 생성하기
  7. 증거를 데이터로 생성하기
  8. 운영 환경에서 잘못되는 것
  9. 이 장에서 결정한 것

맨 위로 돌아가기전체 장