Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Consistent authorization across RAG and derived data

Enforce authorization throughout retrieval, reranking, context assembly, caching, and source access.

Learning objectives: Authorization determines whether data can enter calculations, and relevance only determines the order of authorized data. All summaries, caches, and citations derived from the text must be subject to the current permissions.

Content checked: 2026-10-03 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Implementation · Build it. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: Backend developers learning Agent applications.

Consistent authorization across RAG and derived data
Authorization determines whether data can enter calculations, and relevance only determines the order of authorized data. All summaries, caches, and citations derived from the text must be subject to the current permissions.

How does the mechanism work?

Step-by-step explanation
  1. A user has just been removed from a department group. How to deal with the cache of old answers?

    Revocation can make previously authorized derivatives unreadable under current permissions.

  2. Why is it not enough to hand over unauthorized content to the model and then hide the output?

    Trace backward from the final answer to the actual boundary where data enters computation.

  3. Should block permissions be maintained independently or should document permissions be inherited?

    Apply authorization rules to chunking and context expansion.

Implementation · Build it

Implement the contract · Consistent authorization across RAG and derived data

Objectives of this level: Independently implement the same current-authority contract at five RAG read entries.

Visual guide · Authorize before releasing bodies

Authorize before releasing bodies

All body access paths need current checks, including direct IDs, citations, expansion and caches. Hiding a final answer cannot undo unauthorized model input. Select the figure to open it at full size.

Your module, complete state and unsolved signature

Save rag_acl_lab.py as rag_acl_lab.py in a new directory with Python 3. Implement rag_acl_student.py yourself; the grader imports that file and does not contain a complete implementation:

def serve(state, session_id, request):
    raise NotImplementedError("implement serve")
{
  "authority_available": true,
  "policy_version": 3,
  "sessions": {
    "session-dev": {
      "tenant": "tenant-a",
      "user": "user-dev",
      "auth_version": 4,
      "groups": [
        "dev"
      ]
    },
    "session-fin": {
      "tenant": "tenant-a",
      "user": "user-fin",
      "auth_version": 7,
      "groups": [
        "finance"
      ]
    }
  },
  "documents": {
    "d-dev": {
      "tenant": "tenant-a",
      "source_version": 1,
      "acl_version": 2,
      "groups": [
        "dev"
      ],
      "body": "development budget 10"
    },
    "d-fin": {
      "tenant": "tenant-a",
      "source_version": 1,
      "acl_version": 5,
      "groups": [
        "finance"
      ],
      "body": "finance budget 90"
    },
    "d-other": {
      "tenant": "tenant-b",
      "source_version": 1,
      "acl_version": 2,
      "groups": [
        "dev"
      ],
      "body": "other tenant budget 99"
    }
  },
  "ranked": [
    {
      "id": "d-fin",
      "source_version": 1,
      "acl_version": 5,
      "score": 0.99
    },
    {
      "id": "d-other",
      "source_version": 1,
      "acl_version": 2,
      "score": 0.98
    },
    {
      "id": "d-dev",
      "source_version": 1,
      "acl_version": 2,
      "score": 0.7
    }
  ],
  "cache": {
    "cache-fin": {
      "tenant": "tenant-a",
      "user": "user-fin",
      "auth_version": 7,
      "policy_version": 3,
      "body": "finance summary 90",
      "dependencies": [
        {
          "id": "d-fin",
          "source_version": 1,
          "acl_version": 5
        }
      ]
    }
  }
}

Shape, missing fields and nulls

All displayed state fields and nested record fields are required. IDs, tenant, user and body are nonempty strings. All versions and retrieve limit are positive Python ints, never bools. authority_available is bool. sessions/documents/cache are dicts keyed by nonempty IDs. Groups are lists of nonempty strings and may be empty after revocation; ranked and context refs may also be empty. Ranked scores are finite int/float values, not bools. Cache dependencies are a nonempty list of id/source_version/acl_version refs. session_id must be a nonempty string. Required fields cannot be None; no output field may be omitted. Validate the entire state and request first, raising exactly ValueError("shape") for missing, null, wrong types or unknown kind. Extra fields, including client tenant/groups, are ignored. Unknown well-shaped sessions/IDs are denied as an empty result, not shape errors. Do not mutate inputs.

Exact request and output contract

Return exactly {"items": [{"id": string, "body": string}, ...], "cache_hit": bool}. Denials return empty items/false, with no error-detail body. Each entry resolves the current session from state and denies if authority_available is false. A document is allowed only when its tenant equals the session tenant and its groups intersect the current session groups. There are five request forms:

  • {"kind":"retrieve","limit":1}: first filter ranked rows using current document authorization and matching source/ACL versions. For each document ID retain its highest score among those valid rows, then sort score descending and ID ascending, and only then take limit and return current document bodies. A stale or unauthorized higher-scored row never competes with a valid row; a lower first duplicate never fixes that ID’s score.
  • {"kind":"context","refs":[{"id":"d-dev","source_version":1,"acl_version":2}]}: check each ref again, retain only authorized current-version IDs, preserve first-requested order and deduplicate. Parent/neighbor expansion has no exception.
  • {"kind":"by_id","id":"d-dev"}: independently authorize the current document before its body; this direct read has no old-version ref.
  • {"kind":"citation","ref":{"id":"d-dev","source_version":1,"acl_version":2}}: independently authorize and require both ref versions to match.
  • {"kind":"cache","cache_id":"cache-fin"}: cache tenant/user/auth_version must match the current session, and policy_version must match state. Every dependency must independently pass current authorization and both versions. Only then return one item with cache ID/body and cache_hit true; otherwise empty/false. No automatic fallback or stale summary reuse.

Initial session-dev retrieve limit 1 returns {"items":[{"id":"d-dev","body":"development budget 10"}],"cache_hit":false}. Initial session-fin cache-fin returns its finance summary with true. Changing session-fin to groups []/auth_version 8 blocks it, and groups [finance]/auth_version 9 still cannot reuse that old cache. Changing a document source_version or acl_version blocks stale index rows, refs and derived cache, even when the user still has access.

Duplicate scores and the second cache dependency

Run this probe from the same practice directory after implementing your module. The complete fixture above supplies trusted session state and document bodies. The first variant grants current dev and finance access: d-dev first scores 0.2, d-fin 0.6, then a valid duplicate d-dev 0.9. The winning ID is d-dev. The second variant puts a stale ACL-1 d-dev at 0.99 and cross-tenant duplicates at 0.98/0.97 before valid d-dev 0.2 and d-fin 0.6; the winning ID is d-fin. Invalid high rows cannot suppress a valid low row or set its score.

The cache variants bind cache-mixed to the current dev user/auth 4/policy 3, with dependencies ordered d-dev/source 1/ACL 2 first and d-fin/source 1/ACL 5 second. Dev-only access denies the whole cached body even though the first dependency is valid. Current dev+finance access permits it. A stale second ACL 4 denies it again. Every dependency is conjunctive; do not return a partial copy of this already-mixed summary.

from copy import deepcopy
from rag_acl_lab import fixture
from rag_acl_student import serve

state = fixture()
state["sessions"]["session-dev"]["groups"] = ["dev", "finance"]
dev_ref = {"id": "d-dev", "source_version": 1, "acl_version": 2}
fin_ref = {"id": "d-fin", "source_version": 1, "acl_version": 5}
def expected(did, body, hit=False):
    return {"items": [{"id": did, "body": body}], "cache_hit": hit}
state["ranked"] = [dict(dev_ref, score=0.2), dict(fin_ref, score=0.6), dict(dev_ref, score=0.9)]
assert serve(state, "session-dev", {"kind": "retrieve", "limit": 1}) == expected("d-dev", "development budget 10")
state["ranked"] = [dict(dev_ref, acl_version=1, score=0.99),
                   {"id": "d-other", "source_version": 1, "acl_version": 2, "score": 0.98},
                   dict(dev_ref, score=0.2), dict(fin_ref, score=0.6),
                   {"id": "d-other", "source_version": 1, "acl_version": 2, "score": 0.97}]
assert serve(state, "session-dev", {"kind": "retrieve", "limit": 1}) == expected("d-fin", "finance budget 90")
state = fixture()
state["cache"]["cache-mixed"] = {"tenant": "tenant-a", "user": "user-dev", "auth_version": 4,
    "policy_version": 3, "body": "combined budgets 10 and 90", "dependencies": [dev_ref, fin_ref]}
request = {"kind": "cache", "cache_id": "cache-mixed"}
empty = {"items": [], "cache_hit": False}
assert serve(state, "session-dev", request) == empty
state["sessions"]["session-dev"]["groups"] = ["dev", "finance"]
assert serve(state, "session-dev", request) == expected("cache-mixed", "combined budgets 10 and 90", True)
stale = deepcopy(state)
stale["cache"]["cache-mixed"]["dependencies"][1]["acl_version"] = 4
assert serve(stale, "session-dev", request) == empty
print("valid_duplicate_scores_and_all_cache_dependencies_checked")

Save as rag-dependencies-probe.py. A correct module prints valid_duplicate_scores_and_all_cache_dependencies_checked and exits 0. Keep these assertions unchanged; first-duplicate scoring and first-dependency-only checks must fail. The suite now has 55 cases, including two score-order and three cache-dependency controls. Their scores are simulated metadata, not measured embedding quality.

After implementing your module and saving the probe, run it as a separate command:

python3 rag-dependencies-probe.py

Execute the submitted module

python3 --version
python3 rag_acl_lab.py scaffold --out rag_acl_student.py
python3 rag_acl_lab.py grade --module rag_acl_student.py --out rag-acl-before.json --seed 41

Scaffold exits 0 and refuses overwrite. Unmodified template grade exits 1 with 0/55. Implement your function without editing the suite, then run:

python3 rag_acl_lab.py grade --module rag_acl_student.py --out rag-acl-after.json --seed 41
python3 rag_acl_lab.py grade --module rag_acl_student.py --out rag-acl-variant.json --seed 9001

A conforming implementation exits 0 with 50/55 each time. Reports record imported path/SHA, per-case expected/actual results, seed and immutable-input checks. The grader actually calls all entries before/after revocation, on stale source/ACL/cache versions, cross scopes, regrant, unknown authority, strict null/type input and changed inputs. Seeds are public reproducible rules, not a hidden exam. Submit your code, diff, failing baseline and two passing reports. This is a pure local read simulation, not an authorization service, embedding index, real model or measured RAG quality.

code example

Unknown ID and invalid request differ

An unknown document ID returns empty/false. A citation ref missing acl_version raises ValueError("shape"). Do not turn broken caller contracts into silently successful cache misses.

Acceptance task for this level

Implement serve in your own module; submit a failing scaffold baseline, personal diff and fixed/changed-seed reports covering every entry.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Access is still allowed but source_version changes. Why must cache-fin miss?

Further explanations and practice

When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.

All linked explanations and exercises (1 )

Sources and verification scope

The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.