A retrieval adapter receives the tenant ID team_a from trusted application context. It binds that value to a SQL parameter. The query returns documents belonging to teamXa as well.

The developer did not interpolate SQL or append a wildcard. The underscore was already in the tenant name, and LIKE interpreted it as a pattern character.

I would keep pattern matching out of tenant identity checks. Parameter binding protects the structure of a SQL statement; the chosen operator still determines what the supplied value means. A RAG system can use a correctly bound parameter and select the wrong tenant before it ever calls a model.

The fixture below demonstrates that boundary in an in-memory SQLite database with invented tenants and titles. It is not an incident report or a finding against a named RAG product. It tests a query contract, not an authenticated service.

A tenant name becomes a pattern

Consider a document lookup with this predicate:

rows = db.execute(
    "SELECT tenant, title FROM docs WHERE tenant LIKE ?",
    (tenant_id,),
).fetchall()

Python’s sqlite3 documentation recommends placeholders rather than string formatting to bind values. Keep that practice. Replacing this code with SQL string interpolation would introduce a different defect.

The mistake is the operator. SQLite’s expression documentation defines _ as matching any single character and % as matching any sequence of zero or more characters. A value bound to the right-hand side of LIKE is still a pattern.

Thus team_a matches both team_a and teamXa. A bound value of % matches every non-null text tenant in this fixture. The SQL statement has not changed shape; its pattern has selected a wider set of rows.

SQLite’s default LIKE also folds ASCII case. The same team_a pattern matches TEAM_A. This can matter even after someone fixes the underscore by escaping it. If your identity provider treats differently cased identifiers as distinct, case-insensitive matching is another source of cross-tenant selection.

Do not assume the same behaviour for every Unicode character. SQLite documents that its default folding is limited to ASCII, while extensions can change it. A lookup whose identity rules depend on the installed search extension is a poor place to enforce tenant separation.

Run the counterexample

Download and inspect the Python fixture, then run the saved file:

python3 rag-tenant-like.py
python3 -O rag-tenant-like.py

It uses the standard library, creates its database in memory and makes no network requests. On SQLite 3.51.0, its demonstration printed:

{
  "sqlite": "3.51.0",
  "weak_tenants": ["TEAM_A", "teamXa", "team_a"],
  "exact_tenants": ["team_a"],
  "literal_search": ["Budget 100% approved"]
}

The fixture has twelve test methods. They passed in both normal and optimised Python mode. The weak-path tests deliberately require the broad match to occur, so their success records a reproduced defect rather than an accepted security policy.

The other tests check exact identity, case separation, quoted SQL text remaining data, literal percent and underscore searches, the escape character itself, invalid inputs and a search term that must not reach another tenant. These are deterministic database checks. They do not establish that a production service derives its tenant from the right principal or applies document-level access rules.

Use equality with an explicit identity contract

For this example, tenant IDs are nonempty strings, at most 128 characters, without a NUL character. They are case sensitive. The application does not trim, lowercase or otherwise rewrite them.

The repaired tenant predicate is:

WHERE tenant COLLATE BINARY = ?

SQLite’s collation rules give an explicit COLLATE operator precedence over a column’s declared collation. COLLATE BINARY therefore makes this comparison rule explicit rather than inheriting a case-insensitive column collation. It belongs on an equality comparison here. Adding COLLATE BINARY to a LIKE expression does not turn that expression into exact matching; the fixture includes a test for that tempting but ineffective repair.

The accepted grammar is an application choice. If your identity provider defines a different canonical representation, implement that documented representation at the identity boundary and store it consistently. Avoid copying the fixture’s length limit as though SQLite or a particular identity platform required it.

A safer comparison still needs trusted inputs. The fixture takes tenant as an ordinary Python argument so the tests can exercise it. In a service, obtain the authorised tenant from authenticated context and verify the caller’s membership or delegated scope. Do not let a model argument or a client-editable filter choose that value. Equality would faithfully select an attacker’s requested tenant if the application handed it one.

For a tenant-scoped document lookup, retain the tenant predicate even when the document ID appears globally unique. That also makes the scope visible in the query and its tests. Add document permissions where your policy requires them; belonging to the same tenant does not give every user access to every document.

Keep title search separate

There is a legitimate role for LIKE: a user may want documents whose titles contain some text. That is a search feature inside an already authorised scope.

Suppose a user searches for the literal text 100%. The fixture contains both Budget 100% approved and Budget 1000 approved. Wrapping the unescaped term in % would also match the second title. To offer a literal contains search, escape the pattern characters and declare the escape character in SQL:

def literal_contains(term):
    if type(term) is not str or not term.strip() or len(term) > 256 or '\x00' in term:
        raise ValueError('invalid search term')
    return '%' + term.replace('!', '!!').replace('%', '!%').replace('_', '!_') + '%'

The escape character must be escaped first. Otherwise a later replacement could alter the escape sequences introduced for % or _. SQLite documents the ESCAPE clause and its treatment of an escaped percent, underscore or escape character.

The complete query uses separate parameters for identity and search:

SELECT title
FROM docs
WHERE tenant COLLATE BINARY = ?
  AND title LIKE ? ESCAPE '!'
ORDER BY title

The application binds the checked tenant to the first placeholder and the escaped contains pattern to the second. Title matching retains SQLite’s default ASCII case behaviour; the escaping function does not promise case-sensitive or Unicode-normalised search. If users need those semantics, specify and test them separately.

The fixture rejects blank search terms rather than translating them into an all-title match. Its 256-character cap is a teaching policy, not a demonstrated query-cost bound. A leading-wildcard search on a large collection needs its own query-plan and latency checks. This example does not benchmark indexes, pagination or production load.

The earlier FTS query-boundary article covers a related but different contract: full-text query syntax inside a bound MATCH value. Here the dangerous operator sits in the tenant predicate itself. Escaping a title query cannot repair that predicate.

Test the selected identities before answer quality

An answer-quality evaluation can miss this bug if all its documents belong to one tenant or its tenant names contain only letters. Add conflicting names deliberately. For the contract in this article, team_a, teamXa and TEAM_A are distinct identities, so a request for the first must return no rows from the others.

Run those cases through the actual retrieval adapter, including any ORM or filter builder. Inspect the generated SQL and compare the selected document IDs before passing their text to a model. If a framework rewrites equality into a pattern search, the in-memory fixture will still pass while the service remains wrong. The adapter-level check is follow-up work, not something this fixture has executed.

Keep the scope check through later retrieval stages too. A correct initial query does not authorise neighbouring chunks, cached answers or citation expansion. The neighbour-expansion example shows why the final evidence loader needs its own permission checks.

For the broader agent operating and review workflow, see my Claude Code book, available as a Kindle edition on Amazon UK.

Start with one tenant-scoped query in your service. Add the conflicting-name fixture, assert the exact returned identity set and run the same check through the deployed adapter in a disposable test environment.