Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
Sichere ProgrammierungI wanted the diff, not a screenshot: a small URL-change API(24.09.2026 um 06:05 Uhr)
Sichere ProgrammierungFreeze Object Identity Before One Mutator Extract(24.09.2026 um 06:06 Uhr)
Sichere ProgrammierungRun an n8n workflow when a page's text changes(24.09.2026 um 06:12 Uhr)
Sichere ProgrammierungThe Spreadsheet That Runs Your Company (And Why That Should Worry You)(24.09.2026 um 06:12 Uhr)
Sichere ProgrammierungArchitecting an Enterprise Network on AWS Cloud WAN(24.09.2026 um 06:31 Uhr)
Sichere ProgrammierungI wanted the diff, not a screenshot: a small URL-change API(24.09.2026 um 06:05 Uhr)
Sichere ProgrammierungFreeze Object Identity Before One Mutator Extract(24.09.2026 um 06:06 Uhr)
Sichere ProgrammierungRun an n8n workflow when a page's text changes(24.09.2026 um 06:12 Uhr)
Sichere ProgrammierungThe Spreadsheet That Runs Your Company (And Why That Should Worry You)(24.09.2026 um 06:12 Uhr)
Sichere ProgrammierungArchitecting an Enterprise Network on AWS Cloud WAN(24.09.2026 um 06:31 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

How to Build True Multi-Tenant Database Isolation (Stop using if-statements)

If you are building a B2B SaaS, your biggest nightmare isn't downtime—it's a cross-tenant data leak. Most tutorials teach you to handle multi-tenancy like this: // ❌ The Junior Developer Approach const data = await db.…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

If you are building a B2B SaaS, your biggest nightmare isn't downtime—it's a cross-tenant data leak.



Most tutorials teach you to handle multi-tenancy like this:




// ❌ The Junior Developer Approach
const data = await db.query.invoices.findMany({
where: eq(invoices.orgId, req.body.orgId)
});






This is a ticking time bomb. It relies on the developer remembering to append the orgId check on every single database query. If a developer forgets it on one endpoint, Tenant A just saw Tenant B's invoices.



Here is how you build true multi-tenant isolation that senior engineers actually trust.






1. The Principle of Zero Trust in the Application Layer



Your application logic should not be responsible for tenant isolation. The isolation must happen at the middleware or database level.



When a request comes in, the context of who is asking and which organization they belong to must be established before the route handler is even executed.






2. The Implementation: Hono + Drizzle + Better Auth



In modern architectures, we can leverage middleware to inject the tenant context into the request lifecycle. Here is how we handle it in our stack.



Step 1: Validate and Extract the Tenant

Every request passes through an authentication middleware. If the token is valid, we extract the activeOrganizationId.




// ✅ The Architect Approach (Hono Middleware)
import { createMiddleware } from 'hono/factory';

export const tenantAuthMiddleware = createMiddleware(async (c, next) => {
// Extract session securely from cookies/headers
const session = await betterAuth.getSession(c.req);

if (!session || !session.activeOrganizationId) {
// Failure Handling: Explicitly reject missing tenant contexts
return c.json({ error: "Unauthorized: Missing organization context." }, 401);
}

// Inject the trusted org ID into the request context
c.set("orgId", session.activeOrganizationId);
await next();
});






Step 2: Enforced Database Context

Now, inside your route, you don't rely on the client payload. You rely on the strictly validated context.




app.get("/api/protected/invoices", tenantAuthMiddleware, async (c) => {
const orgId = c.get("orgId"); // Guaranteed to be valid and authorized

// The DB query relies on the trusted middleware context, not req.body
const tenantInvoices = await db
.select()
.from(invoices)
.where(eq(invoices.orgId, orgId));

return c.json(tenantInvoices);
});









3. Handling Failure States



What happens if the service-to-service call fails, or the JWT expires mid-flight?




  • Token Expired: The middleware catches the expired session and returns a 401 Unauthorized before hitting the database. The frontend is forced to refresh the session.

  • Tenant Mismatch: If a user tries to access a resource belonging to Org B but their token resolves to Org A, the middleware (or a subsequent RBAC middleware) throws a 403 Forbidden. The database is never touched.






4. Going Further: Row-Level Security (RLS)



For absolute paranoia, you push this logic down into PostgreSQL itself using Row-Level Security (RLS). You set the Postgres session variable app.current_tenant to the orgId upon connection, and Postgres physically blocks any query trying to read rows outside that ID, even if the application developer writes select * from invoices.






The Takeaway



Stop building SaaS templates that rely on application-level if statements for security.



I got tired of auditing codebases with these vulnerabilities, so I built an open-source monorepo that enforces these boundaries by default. It separates the Vite frontend from the Hono API, uses Drizzle ORM, and strictly isolates tenant data at the middleware level using Better Auth.



If you want to see the full production implementation of this architecture, check out the organization-v2 branch of FlowStack on my GitHub.



Don't let framework magic make you lazy about security boundaries.

SOC Incident Playbook: Remote Code Execution (RCE) Defense
title: Detect Exploitation - How to Build True Multi-Tenant Database Isolation (Stop using if-statements)
id: 9adcc63c-ad39-42ac-970b-f49036d4edf9
status: experimental
description: Automatisch generierte SIEM-Erkennungsregel basierend auf CTI Intelligence
references:
  - https://tsecurity.de/
author: iShareStuff CTI Automated Detection Engine
date: 2026-09-24
logsource:
  category: network_connection
  product: any
detection:
  selection:
      CommandLine|contains:
        - 'exploit'
  condition: selection
falsepositives:
  - Legitime administrative Zugriffe oder Penetrationstests
level: high
tags:
  - attack.initial_access
rule CTI_Threat_Indicator {
    meta:
        author = "iShareStuff CTI Automated Detection Engine"
        date = "2026-09-24"
        description = "YARA Signature for "
    strings:
        $str = "How to Build True Multi-Tenant" ascii wide
    condition:
        any of them
}
tsecurity.de Cognitive Threat RAG
Fokus-Vektor:

Kognitive Analyse für identifizierte Bedrohung: Erhöhte Bedrohungslage im Bereich How to Build True Multi-Tenant Database .... Basierend auf 368k Vektor-Korrelationen werden sofortige Isolationsmaßnahmen für betroffene Endpunkte empfohlen.

🛡️ Angriffsfläche & Exposure

Netzwerk/Remote-Zugriff ohne Vorauthentifizierung möglich.

Empfohlene Sofortmaßnahmen
  • 1. Perimeter-Inspektion: Relevante Portfreigaben und exponierte Endpunkte unverzüglich scannen.
  • 2. Patch-Applikation: Hersteller-Hotfix einspielen oder betroffene Daemons in isolierte DMZ-Segmente überführen.
  • 3. Telemetrie & EDR-Alerts: Prozessaufrufe und Child-Processes auf anomale Shell-Spawns überwachen.
🔗 Semantisch verwandte Zero-Days MariaDB 11.7 VEC
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten How to Build True Multi-Tenant Database Isolation (Stop using if-statements)

Thematisch verwandte Begriffe: Build, True, MultiTenant, Database · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-96676 | A vulnerability was identified in Fast FAC1900R 20190827_2.0.2. The impa…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel TTP ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick