DEV Community

Cover image for How We Rethought RBAC for a Multi-Instance B2B Platform
Raviraj Jariwala
Raviraj Jariwala

Posted on

How We Rethought RBAC for a Multi-Instance B2B Platform

TL;DR: A multi-instance B2B platform had 700 lines of hardcoded navigation with inline permission checks, no route-level security, and Cognito group changes requiring code deploys. We separated instance config, group-based RBAC, and per-user overrides into three distinct layers: moved navigation to the database, built a flat group-to-policy mapping, and added a two-gate route enforcement system. Access changes went from "deploy a PR" to "update a DB row."

Nobody designs a broken permission system on purpose. Ours wasn't a mistake. It was the right call, made correctly, several times in a row.

With one client and a dozen users, hiding a sidebar item behind a flag isn't a shortcut. It's the correct amount of engineering. Building a permissions layer at that scale would have been solving a problem we didn't have yet.

A few clients later, another feature ships with its own access rule. Another flag goes in next to the last one. Still the right call. A real RBAC system still costs more than the problem it would solve.

Then a client asks for a custom navigation just for their instance. There's no layer for "per-client" anywhere in the system, so it goes in the same place everything else did. That's not laziness. It's consistency with how the codebase already works.

Fast forward to a dozen clients and a hundred menu items, and the same decision, repeated at ten times the scale, isn't cheap anymore. It's a 700-line file where every item carries its own inline permission check, and shipping one more feature means finding the right spot in it, wiring up another hasAccess() call, and testing everything around it before you deploy.

Nothing here was ever broken by a bad decision. The system just outgrew the scale it was built for.

That was us.


What We Were Building

We were building a multi-instance B2B SaaS platform. Each client gets their own isolated instance. Their employees use it daily: Sales, Marketing, Content teams, Executives. Same app, completely different access needs.

The product had grown to multiple modules. Each module had sub-features. Each sub-feature had its own access requirements. And underneath all of that, each client had a different subscription: some had all modules, some had three, some had two.

On paper, not a complicated problem. In practice, we had made it one.


The Real Problem

When a client asked us to restrict the Reports section for a specific employee, the answer was: "We'll need to create a new user group in Cognito, redeploy, and it'll be live in a few hours."

That's not a permission system. That's a deployment pipeline masquerading as one.

The navigation file looked like this:

const menuItems = [
  {
    label: 'Customers',
    link: '/app/customers',
    icon: <CustomersIcon />,
    hidden: !hasCustomerAccess(),
  },
  {
    label: 'Reports',
    link: '/app/reports',
    icon: <ReportingIcon />,
    hidden: !hasReportingAccess(),
  },
  {
    label: 'Budget',
    link: '/app/budget',
    icon: <CoinsIcon />,
    hidden:
      !hasAccess(budgetRoles.BUDGET_FULL_ACCESS) &&
      !hasAccess(fullAdminRoles.FULL_ADMIN),
  },
  // ... 60 more items like this
]
Enter fullscreen mode Exit fullscreen mode

Every item. Inline. In code. Adding a new feature meant opening this file, finding the right place, wiring up a new hasAccess() call, and shipping a deploy.

There were three things happening that shouldn't have been:

Access changes required code deploys. Every time a group needed different access, a developer had to touch the navigation file and ship it. For a platform serving multiple clients simultaneously, this was a constant low-grade tax on engineering time.

Route protection stopped at the group level. Routes did call hasAccess(), the same Cognito group check the sidebar used, before rendering a component for a given path. But that was the only gate. There was no way to block one specific person without pulling their entire group's access, so a one-off restriction only ever lived in the sidebar. If someone hid from the menu still knew the URL, the route let them straight in.

One-off exceptions were impossible. If a client wanted their Sales Manager to see everything except the Budget module, there was no clean way to do it. Every exception became a new Cognito group, which accumulated over time into a list nobody fully understood.


Separating Three Things We Had Mixed Together

The first useful thing I did was stop thinking of this as one problem.

What looked like a permission problem was actually three separate concerns we had conflated into one system:

Three separated concerns: instance config, group-based RBAC, per-user overrides

Once I separated these three, each one had an obvious solution. The mess came from trying to solve all three in the same place.


What Changed

1. The Navigation Moved to the Database

Before: navigation hardcoded in JS

src/
  components/
    Sidebar/
      helpers.js       ← 700+ lines, every menu item hardcoded
      permissions.js   ← hasCustomerAccess, hasCorporateAccess...
      Icons/           ← 30+ icon files
Enter fullscreen mode Exit fullscreen mode

After: navigation lives in the DB, code just renders it

src/
  core/
    ui/
      Sidebar/
        SideNav.jsx        ← fetches menu, builds tree, renders
        helpers.js         ← menuArrayToTreeWithFilter()
        components/
          StaticNav.js     ← product icons strip
          NavDrawer.jsx    ← feature list flyout
Enter fullscreen mode Exit fullscreen mode

Every menu item is now a database row:

ui_config_menu
┌─────────────────┬──────────────┬─────────────────────────────────┬─────────────────┐
│ menu_identifier │ url          │ access_policies                 │ product_id      │
├─────────────────┼──────────────┼─────────────────────────────────┼─────────────────┤
│ customers_list  │ /app/cust... │ ["customer_full_access",        │ 2               │
│                 │              │  "customer_restricted_view"]    │                 │
├─────────────────┼──────────────┼─────────────────────────────────┼─────────────────┤
│ reports_main    │ /app/repo... │ ["report_full_access",          │ 1               │
│                 │              │  "reports_advance_flow_full"]   │                 │
├─────────────────┼──────────────┼─────────────────────────────────┼─────────────────┤
│ budget_overview │ /app/budg... │ ["budget_full_access",          │ 1               │
│                 │              │  "full_admin"]                  │                 │
└─────────────────┴──────────────┴─────────────────────────────────┴─────────────────┘
Enter fullscreen mode Exit fullscreen mode

The frontend fetches this at runtime and builds the tree dynamically:

export const menuArrayToTreeWithFilter = (items, userGroupsAndPolicies, userCognitoData) => {
  items.forEach((item) => {
    const isRestricted = restrictedMenuIdentifiers.has(item.menu_identifier)
    if (isRestricted) return                                    // per-user block

    if (!hasProductAccess(item.product_id, userCognitoData)) return  // subscription check

    const hasAccess = item.access_policies?.some(              // RBAC check
      (policy) => userGroupsAndPolicies?.includes(policy)
    )
    if (hasAccess) parent.children.push(item)
  })
}
Enter fullscreen mode Exit fullscreen mode

Adding a new feature to the nav is now a database row. No PR. No deploy. No risk.


2. A Flat Group Model, Not a Hierarchy

I considered building a role hierarchy, where admin inherits from manager which inherits from user. I dropped the idea quickly.

For this kind of business platform, access is naturally group-shaped, not hierarchical. Sales gets sales access. Marketing gets marketing access. CEO gets everything. No inheritance chain to reason about.

Instead, there's a mapping table between Cognito groups and access policies:

user_group_access_list

Cognito Group         →    Access Policy
─────────────────────────────────────────────
sales_team            →    customer_full_access
sales_team            →    product_restricted_view
sales_team            →    dashboard_season_view

marketing_team        →    customer_non_restricted_view
marketing_team        →    social_full_access
marketing_team        →    dashboard_full_access

exec_team             →    full_admin
Enter fullscreen mode Exit fullscreen mode

At login, Cognito groups get expanded into a flat list of all access policies the user holds:

export const setUserGroups = async (userGroupAccessList = [], callback) => {
  const cognitoGroups = getCurrentUser()?.userGroups || []

  // expand each group into its access policies
  let accessPolicies = []
  Object.keys(groupAccessByUserGroup).forEach((group) => {
    if (cognitoGroups.includes(group)) {
      accessPolicies.push(...groupAccessByUserGroup[group].map((i) => i.access_policy))
    }
  })

  // store the full expanded list in session
  user.userGroups = [...new Set([...cognitoGroups, ...accessPolicies])]
  setUser(user)
}
Enter fullscreen mode Exit fullscreen mode

Every access check from that point uses this expanded list. The indirection matters: if we want to change what the sales team can access, we update the mapping table. No Cognito change. No code change.


3. Two Gates on Every Route

Before: routes only had one gate, the group check

Before: routes only had one gate, the group check

After: routes have two gates, group check and per-user deny-list

After: routes have two gates, group check and per-user deny-list

In code:

const RestrictedRoute = ({ Component, accessList, ...props }) => {
  const path = props.location.pathname
  const { gatsbyUserData, user } = useAuthContext()
  const { urlPathMap } = useSidebarContext()

  // Gate 1: group access
  const hasAccess = hasValidAccess({
    accessList: gatsbyUserData?.userGroups || [],
    namesOfAccessList: accessList || [],
  })

  // Gate 2: admin deny-list
  const isRestricted = user?.restricted_menu_identifiers?.includes(
    urlPathMap[path]?.menuIdentifier
  )

  if (!hasAccess || isRestricted) return <AccessDenied />

  return <Component {...props} />
}
Enter fullscreen mode Exit fullscreen mode

Both gates have to pass. The first checks group membership. The second checks whether an admin has explicitly blocked this specific item for this specific user.


4. Per-User Exceptions Without Engineering

For the edge cases, where one specific person needs a different scope than their group, we built an admin UI. It shows the user's accessible menu as a tree. An admin checks or unchecks items. Changes save immediately.

Manage User Access: John Smith (Sales Team)
─────────────────────────────────────────────
☑ Customers
  ☑ Customer List
  ☑ Customer Details
  ☑ Import
☑ Products
  ☑ Tickets
  ☐ Hospitality        ← unchecked by admin
  ☑ Merchandise
☑ Dashboard
  ☐ Revenue Flow       ← unchecked by admin
  ☑ Season View
Enter fullscreen mode Exit fullscreen mode

This is purely a deny-list. It can only restrict, never grant beyond what the group allows. That constraint is intentional: if it could grant extra access, you'd have two systems to keep in sync instead of one.

What used to be a Cognito console operation involving an engineer is now a ten-second admin action.


Before vs After

Before vs after summary: access change, new feature nav, route protection, per-user scope, audit access


Decisions I'd Make the Same Way Again

Keeping subscription separate from RBAC. Product availability is instance configuration, answered at provisioning and doesn't change. Mixing it into the permission system would have coupled two concerns with completely different owners and change frequencies.

Deny-list over per-user allow-list. An allow-list creates a maintenance problem: you'd need to keep it in sync with group access as groups evolve. A deny-list composes cleanly on top. Edge cases are almost always about restricting, not granting.

Client-side menu filtering. The menu builds and filters in the browser. The real security boundary is the API layer. For an internal platform with controlled users this is the right call. The sidebar is a UX concern, not a security perimeter.


What I'd Tell Someone Starting This

The hardest part wasn't the implementation. It was resisting the urge to solve all three concerns (subscription, group access, individual exceptions) in one system.

When access control feels messy, it's usually because these three things have been layered on top of each other in the same place over time. Nobody designed it that way. It accumulated.

Separating them, even if the resulting code feels like more pieces, makes every individual decision obvious. You always know which layer you're working in and why.

The complexity doesn't disappear. It just gets organized.

Top comments (0)