# 2026 Legal Review Workspace Security: Tenant Isolation Before Semantic Search

> Source: <https://dev.to/wilhelmknight8435/2026-legal-review-workspace-security-tenant-isolation-before-semantic-search-5bcd>
> Published: 2026-11-23 03:25:44+00:00

**Recommendation:** Pass tenant identity as a required typed input to every retrieval stage and reject candidates failing the tenant-and-revision intersection; prefix cache keys with tenant ID so identical boilerplate digests never cross workspaces.
More in the playbook "Retrieval and RAG": <https://wpnews.pro/playbooks/rag-retrieval>

Enforce tenant scope before retrieval, carry it through every intermediate object, and reject any result whose provenance cannot be reconciled with that scope. For a legal contract review workspace, the deciding constraint is not the embedding model; it is whether a request, chunk, candidate, citation, cache entry, and audit event all resolve to the same tenant without relying on a caller-supplied filter that can be forgotten.

Short answer: make tenant identity an authorization fact established at the request boundary, then require it as a typed input to chunk lookup, semantic retrieval, reranking, hydration, and citation assembly. Keep separate physical indexes only where regulation, contractual commitments, threat models, or deletion guarantees justify the operational cost.

This is an architecture decision record for semantic near-duplicate detection in contract review. A reviewer may need to find a clause that resembles language in another agreement, but similarity never grants visibility. Retrieval-augmented generation adds retrieved external context to generation; that context boundary is exactly where access control must remain explicit [1].

Treat authorization and relevance as two different predicates. Authorization decides which corpus may be searched. Relevance orders records inside that corpus. Reversing those operations creates a dangerous design: retrieve globally, rank globally, and remove unauthorized hits afterward. Even if the final response is filtered, an intermediate candidate can affect scores, logs, traces, cache keys, token budgets, or fallback behavior.

The governing invariant is concise: every artifact derived from a contract has one tenant owner, and every operation consuming that artifact proves equality with the authorized tenant. A document identifier is not enough. Neither is a workspace name supplied in JSON, because user-controlled labels are data, not authority. The trusted tenant must come from authenticated server-side context and be immutable for the lifetime of the request.

Fail closed.

For near-duplicate detection, chunking and freshness complicate the boundary. Each chunk needs a stable document lineage, tenant identity, source revision, chunking-policy version, and content digest. A newly signed amendment can supersede an older clause while both remain semantically close; without revision metadata, the system may return an authorized but stale passage. That is not a cross-tenant disclosure, yet it is still a correctness failure in a review workflow where citations and later reconciliation matter.

I would write the acceptance rule as an intersection, not a ranking preference:

```
allowed := candidate.TenantID == scope.TenantID
current := candidate.SourceRevision == activeRevision[candidate.DocumentID]
usable := allowed && current
```

Similarity is evaluated only after the authorized corpus has been selected, while freshness is checked again when source text is hydrated. The repeated check is deliberate: indexing and source storage do not update atomically unless the architecture supplies a transaction spanning both, and this design does not assume one.

The request boundary authenticates the principal, resolves memberships, selects one tenant, and emits an authorization scope. The retrieval layer accepts that scope as a required value rather than an optional map of filters. The storage layer enforces the same boundary independently. Defense in depth matters here because application review can verify a required function argument, while a storage policy can constrain the damage from a future call site that is implemented incorrectly.

Four invariants are enough to drive design reviews and tests:

The third invariant is easy to underestimate. Identical boilerplate can produce identical digests and embeddings in separate workspaces. A global cache keyed only by digest may therefore join two otherwise isolated data paths. Tenant-prefixed keys preserve ownership even when content is byte-for-byte equal, and they make deletion and reconciliation bounded operations rather than corpus-wide investigations.

The audit trail should describe decisions, not become a shadow contract repository. Record identifiers and digests that let an operator reconstruct which authorized inputs produced a citation; restrict the log itself; define retention deliberately. I am not sure one retention period can satisfy every jurisdiction or client engagement. The workspace needs a policy input, legal review, and evidence that expiry actually runs. NIST describes zero trust as removing implicit trust based on network location, which supports authenticating and authorizing access to resources rather than treating an internal retrieval service as trusted by placement alone [2].

Freshness has two clocks: source acceptance and index visibility. Store both. If revision 42 is accepted at 14:03 but becomes searchable at 14:05, the review UI can distinguish an indexing lag from an absence. Do not silently query revision 41 and present it as current. Depending on the product contract, the safer response may be to mark semantic search as catching up while exact source access remains available.

There are three credible patterns. None wins on every axis, and the choice must be recorded per data classification rather than inherited from whichever prototype was easiest.

| Pattern | Authorization mechanism | Main benefit | Main limitation | Suitable use | 
|---|---|---|---|---|
| Shared index with mandatory tenant predicate | Trusted scope is bound to every search and enforced again during hydration | Lower operational duplication; uniform migrations | A missed or weakened predicate has a large blast radius; proving deletion requires careful evidence | Many similarly governed tenants when the engine can enforce scoped queries | 
| Tenant-specific namespace or collection | Scope resolves to a bounded logical corpus before query execution | Clearer quotas, deletion, and per-tenant rebuilds | More lifecycle automation and uneven-resource management | Workspaces needing independent rebuild or retention schedules | 
| Dedicated deployment or account | Physical and administrative boundary per tenant | Strongest separation of data plane, keys, and operations | Highest deployment, patching, observability, and capacity overhead | Contractual or regulatory isolation that requires dedicated control planes | 

A shared index is not automatically unsafe, and a dedicated deployment is not automatically sufficient. Shared storage can be correct when the predicate is unskippable and tested at the storage boundary. Dedicated infrastructure can still leak through a shared cache, telemetry pipeline, export bucket, or operator tool. Architecture diagrams should follow the data into those less glamorous systems.

The catch is operational proof. A namespace-per-tenant design is not suitable when the search engine imposes lifecycle or scale characteristics the team cannot operate reliably across the expected tenant count. Stick with a shared index when mandatory scoping is enforceable, tenant data has comparable policy, and automated tests can demonstrate isolation for every query path. Choose dedicated infrastructure when an agreement requires separate keys, administrative access, backups, or deletion evidence; accepting the extra operational burden is then part of the control, not accidental complexity.

Chunking also belongs in this table's decision process. Chunk identifiers should be namespaced, but boundaries should follow legal structure where possible: clause, schedule item, definition, and amendment linkage are more auditable than arbitrary windows alone. Very small chunks improve localization but can detach an obligation from its qualifier. Very large chunks preserve context but make near-duplicate scores less diagnostic and citations less precise. There is no universal token count in the available evidence, so calibrate against an annotated contract set and retain the policy version beside each chunk.

The following Go sketch makes the boundary visible. The interfaces are generic on purpose. `TenantScope` can be constructed only by the authorization layer; retrieval cannot accept a raw tenant string, and hydration rechecks ownership and revision before any text reaches a reranker or generator.

```
package retrieval

import (
    "context"
    "errors"
    "fmt"
)

type TenantScope struct {
    id string
}

func NewTenantScope(authorizedTenantID string) (TenantScope, error) {
    if authorizedTenantID == "" {
        return TenantScope{}, errors.New("missing authorized tenant")
    }
    return TenantScope{id: authorizedTenantID}, nil
}

type Candidate struct {
    TenantID        string
    DocumentID      string
    ChunkID         string
    SourceRevision  uint64
    ChunkPolicy     uint32
    ContentDigest   string
    SimilarityScore float64
}

type SourceChunk struct {
    TenantID       string
    DocumentID     string
    ChunkID        string
    SourceRevision uint64
    Text           string
}

type Index interface {
    SearchTenant(ctx context.Context, tenantID, query string, limit int) ([]Candidate, error)
}

type SourceStore interface {
    ActiveRevision(ctx context.Context, tenantID, documentID string) (uint64, error)
    GetChunk(ctx context.Context, tenantID, chunkID string) (SourceChunk, error)
}

type AuditSink interface {
    RecordDecision(ctx context.Context, event DecisionEvent) error
}

type DecisionEvent struct {
    TenantID      string
    QueryDigest   string
    DocumentID    string
    ChunkID       string
    Revision      uint64
    Outcome       string
}

type Service struct {
    index Index
    source SourceStore
    audit AuditSink
}

func (s Service) Retrieve(
    ctx context.Context,
    scope TenantScope,
    query string,
    queryDigest string,
    limit int,
) ([]SourceChunk, error) {
    candidates, err := s.index.SearchTenant(ctx, scope.id, query, limit)
    if err != nil {
        return nil, fmt.Errorf("scoped search: %w", err)
    }

    results := make([]SourceChunk, 0, len(candidates))
    for _, candidate := range candidates {
        if candidate.TenantID != scope.id {
            return nil, errors.New("candidate violates tenant scope")
        }

        active, err := s.source.ActiveRevision(
            ctx, scope.id, candidate.DocumentID,
        )
        if err != nil {
            return nil, fmt.Errorf("resolve active revision: %w", err)
        }
        if candidate.SourceRevision != active {
            continue
        }

        chunk, err := s.source.GetChunk(ctx, scope.id, candidate.ChunkID)
        if err != nil {
            return nil, fmt.Errorf("hydrate scoped chunk: %w", err)
        }
        if chunk.TenantID != scope.id || chunk.SourceRevision != active {
            return nil, errors.New("hydrated chunk violates scope or freshness")
        }

        event := DecisionEvent{
            TenantID: scope.id, QueryDigest: queryDigest,
            DocumentID: chunk.DocumentID, ChunkID: chunk.ChunkID,
            Revision: chunk.SourceRevision, Outcome: "returned",
        }
        if err := s.audit.RecordDecision(ctx, event); err != nil {
            return nil, fmt.Errorf("record retrieval decision: %w", err)
        }
        results = append(results, chunk)
    }
    return results, nil
}
```

This code chooses correctness over partial success: an ownership mismatch stops the request, and an audit-write failure prevents an unaudited result. That exactly-once mindset does not claim distributed exactly-once delivery; retries still happen. The practical requirement is an idempotency key for each retrieval decision and a uniqueness constraint at the audit sink, so a retried request records one logical decision rather than two indistinguishable events.

The sample skips embedding generation and reranking because they do not own authorization. They receive only already-scoped candidates. In production, cap `limit`, hash or otherwise minimize query material in telemetry, apply deadlines, and expose counters for stale candidates, scope violations, index lag, and audit failures. A scope-violation counter should remain zero and page an operator; stale-candidate counts are expected during controlled reindexing but should be bounded by a declared freshness objective.

Tests need adversarial fixtures, not only happy-path relevance judgments. Create two tenants with identical clauses, identical digests, colliding human-readable document names, and different active revisions. Assert that queries, caches, exports, traces, and audit searches cannot cross the boundary. Then rotate a revision during retrieval and verify that hydration either returns the active source or no result. Re-run the suite for every chunk-policy migration because dual-read periods create two representations of the same contract.

This record rejects global retrieval followed by application-side tenant filtering. It is attractive for offline corpus analysis because one query can discover near-duplicates across all documents, but it violates the online workspace invariant: unauthorized candidates exist in memory and may influence ranking before the filter executes. Post-filtering also makes an empty authorized result depend on how many unauthorized candidates occupied the initial top set.

There is a valid use case: a separately authorized, offline compliance or template-analysis job may compare contracts across participating tenants when its legal basis, input manifest, output destination, retention, and operator access are explicit. That job should use a distinct identity and data path. It must not be activated by a request flag in the normal reviewer API.

This decision also rejects a universal demand for dedicated infrastructure. Physical separation is appropriate when policy calls for it, but applying it to every tenant can multiply patching and recovery work without fixing shared telemetry or operator access. The control objective is end-to-end tenant ownership, with deployment topology selected as one component of that proof.

The final review criterion is therefore auditable and pleasantly strict: if the team cannot reconstruct why a particular revision of a particular clause was eligible for a particular tenant-scoped request, the retrieval result is not ready for a legal workspace. Relevance can be tuned later. Isolation cannot.
