{"slug": "2026-legal-review-workspace-security-tenant-isolation-before-semantic-search", "title": "2026 Legal Review Workspace Security: Tenant Isolation Before Semantic Search", "summary": "An engineer published an architecture decision record for securing a legal contract review workspace, arguing that tenant isolation must be enforced before semantic search rather than filtered afterward. The design makes tenant identity an authorization fact established at the request boundary and requires it as a typed input to chunk lookup, retrieval, reranking, hydration, and citation assembly, with a fail-closed acceptance rule that intersects tenant match with source-revision freshness. The author also warns that global caches keyed only by content digest can silently join otherwise isolated workspaces, so cache keys must be tenant-prefixed.", "body_md": "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.\n\nShort 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.\n\nThis 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].\n\nTreat 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.\n\nThe 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.\n\nFail closed.\n\nFor 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.\n\nI would write the acceptance rule as an intersection, not a ranking preference:\n\n```\nallowed := candidate.TenantID == scope.TenantID\ncurrent := candidate.SourceRevision == activeRevision[candidate.DocumentID]\nusable := allowed && current\n```\n\nSimilarity 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.\n\nThe 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.\n\nFour invariants are enough to drive design reviews and tests:\n\nThe 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.\n\nThe 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].\n\nFreshness 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.\n\nThere 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.\n\n| Pattern | Authorization mechanism | Main benefit | Main limitation | Suitable use | \n|---|---|---|---|---|\n| 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 | \n| 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 | \n| 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 | \n\nA 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.\n\nThe 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.\n\nChunking 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.\n\nThe 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.\n\n```\npackage retrieval\n\nimport (\n    \"context\"\n    \"errors\"\n    \"fmt\"\n)\n\ntype TenantScope struct {\n    id string\n}\n\nfunc NewTenantScope(authorizedTenantID string) (TenantScope, error) {\n    if authorizedTenantID == \"\" {\n        return TenantScope{}, errors.New(\"missing authorized tenant\")\n    }\n    return TenantScope{id: authorizedTenantID}, nil\n}\n\ntype Candidate struct {\n    TenantID        string\n    DocumentID      string\n    ChunkID         string\n    SourceRevision  uint64\n    ChunkPolicy     uint32\n    ContentDigest   string\n    SimilarityScore float64\n}\n\ntype SourceChunk struct {\n    TenantID       string\n    DocumentID     string\n    ChunkID        string\n    SourceRevision uint64\n    Text           string\n}\n\ntype Index interface {\n    SearchTenant(ctx context.Context, tenantID, query string, limit int) ([]Candidate, error)\n}\n\ntype SourceStore interface {\n    ActiveRevision(ctx context.Context, tenantID, documentID string) (uint64, error)\n    GetChunk(ctx context.Context, tenantID, chunkID string) (SourceChunk, error)\n}\n\ntype AuditSink interface {\n    RecordDecision(ctx context.Context, event DecisionEvent) error\n}\n\ntype DecisionEvent struct {\n    TenantID      string\n    QueryDigest   string\n    DocumentID    string\n    ChunkID       string\n    Revision      uint64\n    Outcome       string\n}\n\ntype Service struct {\n    index Index\n    source SourceStore\n    audit AuditSink\n}\n\nfunc (s Service) Retrieve(\n    ctx context.Context,\n    scope TenantScope,\n    query string,\n    queryDigest string,\n    limit int,\n) ([]SourceChunk, error) {\n    candidates, err := s.index.SearchTenant(ctx, scope.id, query, limit)\n    if err != nil {\n        return nil, fmt.Errorf(\"scoped search: %w\", err)\n    }\n\n    results := make([]SourceChunk, 0, len(candidates))\n    for _, candidate := range candidates {\n        if candidate.TenantID != scope.id {\n            return nil, errors.New(\"candidate violates tenant scope\")\n        }\n\n        active, err := s.source.ActiveRevision(\n            ctx, scope.id, candidate.DocumentID,\n        )\n        if err != nil {\n            return nil, fmt.Errorf(\"resolve active revision: %w\", err)\n        }\n        if candidate.SourceRevision != active {\n            continue\n        }\n\n        chunk, err := s.source.GetChunk(ctx, scope.id, candidate.ChunkID)\n        if err != nil {\n            return nil, fmt.Errorf(\"hydrate scoped chunk: %w\", err)\n        }\n        if chunk.TenantID != scope.id || chunk.SourceRevision != active {\n            return nil, errors.New(\"hydrated chunk violates scope or freshness\")\n        }\n\n        event := DecisionEvent{\n            TenantID: scope.id, QueryDigest: queryDigest,\n            DocumentID: chunk.DocumentID, ChunkID: chunk.ChunkID,\n            Revision: chunk.SourceRevision, Outcome: \"returned\",\n        }\n        if err := s.audit.RecordDecision(ctx, event); err != nil {\n            return nil, fmt.Errorf(\"record retrieval decision: %w\", err)\n        }\n        results = append(results, chunk)\n    }\n    return results, nil\n}\n```\n\nThis 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.\n\nThe 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.\n\nTests 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.\n\nThis 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.\n\nThere 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.\n\nThis 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.\n\nThe 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.", "url": "https://wpnews.pro/news/2026-legal-review-workspace-security-tenant-isolation-before-semantic-search", "canonical_source": "https://dev.to/wilhelmknight8435/2026-legal-review-workspace-security-tenant-isolation-before-semantic-search-5bcd", "published_at": "2026-11-23 03:25:44+00:00", "updated_at": "2026-11-23 03:42:01.308816+00:00", "lang": "en", "topics": ["ai-safety", "large-language-models", "ai-agents"], "entities": [], "also_reported_by": [], "takeaway": "Enforce tenant scope as a required typed argument through chunk lookup, retrieval, reranking, hydration and citation assembly, and accept a candidate only when tenant match and source-revision freshness both hold, since global caches keyed by content digest alone can merge isolated workspaces.", "recommendation": {"advice": "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.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/2026-legal-review-workspace-security-tenant-isolation-before-semantic-search", "markdown": "https://wpnews.pro/news/2026-legal-review-workspace-security-tenant-isolation-before-semantic-search.md", "text": "https://wpnews.pro/news/2026-legal-review-workspace-security-tenant-isolation-before-semantic-search.txt", "jsonld": "https://wpnews.pro/news/2026-legal-review-workspace-security-tenant-isolation-before-semantic-search.jsonld"}}