Back to Engineering Journal
Infrastructure7 min read

Practical Security for B2B Platforms: The Role-Based Access Control (RBAC) & Audit Log Blueprint

Most B2B data leaks do not come from movie-style hackers—they come from missing tenant checks when a user edits an invoice ID in a URL. Here is how deterministic RBAC, tenant-scoped queries, and immutable audit logs protect B2B platforms cleanly.

#Infrastructure #Security #RBAC #Data Protection #Architecture
WRITTEN BYFebin & Dale Engineering
Practical Security for B2B Platforms: The Role-Based Access Control (RBAC) & Audit Log Blueprint

Why Most B2B Data Leaks Happen Without Any "Hacking"

When founders picture software security failures, they imagine sophisticated attackers cracking encryption keys. In real B2B SaaS and client portals, the vast majority of damaging data exposures are far simpler: a logged-in user from Company A notices a URL like /api/invoices/4082, changes the final digit to 4083, and immediately downloads Company B's confidential PDF.

That failure class—Broken Object-Level Authorization (IDOR)—happens when teams verify authentication ("is this person logged in?") while forgetting authorization ("does this person belong to the specific company that owns record 4083, and does their role allow viewing billing?").

Even worse, many fast-moving products try to fix permissions on the frontend by hiding buttons with UI conditionals like if (user.role === 'admin'). Hiding a menu item in the browser only stops casual clicks; anyone opening browser developer tools can still fire the underlying API request directly.

UI Permission Hiding vs. Deterministic Backend Enforcement

Security cannot live inside UI templates. Every authenticated API endpoint and database query in a multi-tenant B2B platform must enforce two deterministic guarantees before returning or mutating a single row:

  1. Tenant Boundary Scoping: The active tenant_id comes exclusively from the cryptographically verified server session—never from a client-supplied query parameter or hidden form field. Every query filters explicitly by both record ID and session tenant_id.
  2. Capability-Based RBAC Matrix: Rather than scattering raw role-name string checks across 50 endpoints, map roles (org_owner, finance_admin, operator, client_viewer) to explicit action permissions (invoices:read, invoices:approve, members:invite) evaluated in one central middleware guard.
┌──────────────────────┐     ┌───────────────────────────────────────────┐
│ Authenticated Client │ ──▶ │ Session Middleware (Extracts Verified     │
│ GET /invoices/4083   │     │ user_id + tenant_id + role from Token)    │
└──────────────────────┘     └─────────────────────┬─────────────────────┘
                                                   ▼
                             ┌───────────────────────────────────────────┐
                             │ Central RBAC Policy Check                 │
                             │ Does role have 'invoices:read'?           │
                             └──────────┬─────────────────────┬──────────┘
                                   Deny │                     │ Allow
                                        ▼                     ▼
                             ┌──────────────────┐  ┌─────────────────────┐
                             │ 403 Forbidden    │  │ Tenant-Scoped Query │
                             │ + Audit Attempt  │  │ WHERE id = 4083     │
                             └──────────────────┘  │ AND tenant_id = T1  │
                                                   └──────────┬──────────┘
                                                              ▼
                                                   ┌─────────────────────┐
                                                   │ Append Immutable    │
                                                   │ Audit Log Record    │
                                                   └─────────────────────┘

The Multi-Tenant RBAC & Audit Log Schema Blueprint

When mid-market or enterprise buyers evaluate your platform during procurement, their security questionnaire almost always converges on two non-negotiable questions: "How do you guarantee another customer can never read our data?" and "Can we prove who exported or modified sensitive records and when?"

You can satisfy both requirements cleanly in PostgreSQL without complex infrastructure overhead—using composite tenant foreign keys and an append-only audit_logs table:

-- Tenant-scoped membership and deterministic RBAC role binding
CREATE TABLE tenant_memberships (
  tenant_id   UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  user_id     UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  role        TEXT NOT NULL CHECK (role IN ('org_owner', 'finance_admin', 'operator', 'viewer')),
  created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  PRIMARY KEY (tenant_id, user_id)
);

-- Composite foreign key guarantees invoices can never cross tenant boundaries
CREATE TABLE invoices (
  id          UUID NOT NULL,
  tenant_id   UUID NOT NULL REFERENCES tenants(id),
  amount_inr  BIGINT NOT NULL,
  status      TEXT NOT NULL,
  PRIMARY KEY (tenant_id, id)
);

-- Append-only audit log for sensitive reads, exports, and permission changes
CREATE TABLE audit_logs (
  id           BIGSERIAL PRIMARY KEY,
  tenant_id    UUID NOT NULL,
  actor_id     UUID NOT NULL,
  action       TEXT NOT NULL,         -- e.g. 'invoice.exported', 'member.role_updated'
  target_type  TEXT NOT NULL,
  target_id    TEXT NOT NULL,
  metadata     JSONB NOT NULL DEFAULT '{}'::jsonb,
  occurred_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_audit_logs_tenant_time ON audit_logs (tenant_id, occurred_at DESC);

Ad-Hoc UI Checks vs. Deterministic RBAC Architecture

Security Dimension Ad-Hoc UI Role Checks Tenant-Scoped RBAC + Audit Logs
URL ID Tampering (IDOR) Vulnerable if API forgets manual ownership check Blocked structurally via session-derived tenant_id
Adding a New User Role Requires hunting through dozens of frontend files Add one capability row in the central RBAC policy map
Enterprise Procurement Stalls on basic data isolation & logging questions Passes security review with documented schema & logs
Query Performance Uneven; unindexed cross-tenant scans slow down Fast composite indexes keyed on (tenant_id, ...)
Incident Forensics Guesswork; no record of who viewed or exported files Exact actor, action, target ID, and timestamp trail

A Pragmatic 5-Point Security Checklist for Growing B2B Teams

  1. Never Trust Client-Sent Tenant IDs: Derive tenant_id solely from the server-verified authentication session on every request.
  2. Centralize Permission Maps: Keep one typed RBAC policy file mapping roles to explicit capabilities, shared cleanly between API guards and UI hint rendering.
  3. Write Negative Authorization Tests: Every critical endpoint should have an automated test proving that User A in Tenant 1 receives HTTP 403/404 when requesting Tenant 2's record ID.
  4. Log Sensitive Exports & Role Changes: Record every role escalation, API key creation, and bulk CSV/PDF export inside an append-only audit_logs table.
  5. Enforce Short-Lived Sessions & Least Privilege: Expire unused invite tokens automatically and give external contractors or client viewers scoped read-only roles by default.
Operational Axiom

Enterprise security does not require bloated compliance middleware. Enforce tenant boundaries at the database query layer, map roles to explicit server-side capabilities, and record sensitive mutations in an immutable audit log—and you eliminate 90% of real-world B2B breach vectors.

NEXT STEP

Audit Your Platform Security

Continue