# The filter you can see is not the one that matters

> Embedding a BI tool in a multi-tenant product gives you two tenancy mechanisms that look identical in a demo: a URL parameter, and a SQL wildcard on a user attribute, which is the only one holding.

- Author: Deyan Peev (https://deyanpeev.com)
- Published: 2024-08-17
- Tags: Analytics, Looker, Multi-Tenancy, NestJS, TypeScript, Redis, Security
- URL: https://deyanpeev.com/posts/the-filter-you-can-see-is-not-the-one-that-matters

The requirement is ordinary. One set of dashboards, built once, shown inside a
multi-tenant product, and each customer sees their own numbers. Every embedded
BI tool sells this and every one of them can demonstrate it in five minutes.

But the five-minute demo and the thing that holds in production use different
mechanisms, and the tenancy bugs are in the gap between them.

# Two filters

**The one you can see.** The dashboard has an `Organization` filter, and the
embedding application sets it in the iframe URL and then hides the control:

```ts
export const setDefaultSearchParams = (
  searchParams: URLSearchParams,
  theme: string,
  accountSlug?: string,
) => {
  searchParams.set('allow_login_screen', 'false')
  searchParams.set('theme', theme)

  if (accountSlug && !searchParams.has('Organization')) {
    searchParams.set('Organization', accountSlug)
  }

  if (!searchParams.has('hide_filter')) {
    searchParams.set('hide_filter', 'Organization')
  }
}
```

That's presentation. It puts the dashboard in the right state and it stops a
confusing empty filter chip appearing above every tile. As a boundary it's
worth nothing. It is a query-string parameter in a URL, in a browser, belonging
to the person we are trying to constrain.

**The one that matters.** The embed user carries a user attribute holding the
organisation identifiers it may see, and the model's access filter applies it
server-side while the SQL is being built. The browser never takes part. There's
no request the user can craft that removes it, because it isn't in a request.

Both exist, but only the second is the control. In any demo (and in most
incident post-mortems) people point at the first one.

# The embed user is not a user

Embed users aren't provisioned in advance. They are created on demand from the
product's own identifier:

```ts
public async createEmbedUser(externUserId: string): Promise<IUser> {
    return this.adminSDK.ok(this.adminSDK.create_embed_user({ external_user_id: externUserId }))
}
```

Their groups and attributes are then *recomputed*, not assigned, every time a
session is acquired:

```ts
const actualUserGroups = await this.getUserGroupsForUser(user)

const missingUserGroups = filter(actualUserGroups, (ag) => !includes(lookerUser.group_ids, ag))
const groupsToRemove = filter(
    lookerUser.group_ids,
    (groupId) => !includes([LOOKER_DEFAULT_USER_GROUP, ...actualUserGroups], groupId),
)
```

Adding the missing groups is the obvious half. Removing the extra ones is the
half that gets skipped, and then a user demoted from editor to viewer keeps the
editor group forever, because nothing ever went back and took it away.
Permission code that only ever adds is a ratchet. The default group has to be
excluded by name, because the tool puts everyone in it and you aren't allowed
to remove people from it.

# Your tenancy boundary is a LIKE pattern

Two attributes carry the scope. One is a comma-joined list of organisation
identifiers. The other is finer-grained (organisation and location together),
and with that one you can see what the mechanism really is:

```ts
forEach(accounts, (a) => {
    if (some(a.locations)) {
        forEach(a.locations, (l) => orgLocationPairs.push(`${a.id}_${l}`))
    } else {
        orgLocationPairs.push(`${a.id}^_%`)
    }
})
```

The `^_%` is there for a reason. The pair is matched with `LIKE`, `_` matches any
single character, and the separator between the two halves *is* an underscore.
So a user scoped to a whole organisation with no location restriction needs
"this organisation, then a literal underscore, then anything". That's an
escaped `_` followed by `%`, with `^` as the escape character.

Get that wrong by one character and `123_%` matches organisation `1234` as well
as `123`. So the escaping is the boundary. I'd guess any tenancy scheme built on
string patterns has a version of this line in it somewhere, and it deserves a
test with two organisations whose identifiers share a prefix. Ours has one now.

The blunter instrument is next to it. An internal user, represented by an empty
accounts array, is mapped to `%`, which matches everything:

```ts
const accounts = some(user.accounts) ? map(user.accounts, 'id') : ['%']
```

The requirement is legitimate, support staff need to see a customer's
dashboard to answer a question about it. What I don't like is that the
privilege is expressed as *an array being empty*. An empty collection is what
a mapping bug produces, and here it grants access to every tenant in the
instance. It should have been an explicit role, checked explicitly. That it
works is not an argument.

# Cache the result, key it by the input

Reconciling groups and attributes on every session acquire is several API calls
against the BI instance, on a path a user is waiting on. The cache avoids them,
and I would copy the way it is keyed:

```ts
private async getActualCachedLookerUser(userData: User): Promise<IUser | undefined> {
    const userHash = objectHash(userData)
    const lookerUser = await this.cacheManager.get(this.getUserCacheKey(userData))

    if (lookerUser && lookerUser.hash === userHash) {
        return lookerUser
    }
}
```

The cached record carries a hash of the input that produced it, and a hit is only
honoured if the hash still matches. Change a permission anywhere and the hash
changes, the entry is ignored, and the reconciliation runs. There's no
invalidation call to forget and no TTL to tune, and no window in which a revoked
permission is still being served from cache.

The alternative, and it's what was there first, is a short TTL and a window in
which a revoked permission is still served from cache.

There was a related bug in the same area. The attributes are stored as
comma-joined strings, and the check for "has this changed" compared the strings.
The same set in a different order is a different string, so the service rewrote
both attributes on a large share of requests. Nothing behaved incorrectly, it
was just a steady stream of writes to the BI instance's API for no reason.
Sorting both sides before comparing fixed it:

```ts
if (!isEqual(sortBy(lookerOrgIds), sortBy(accounts))) {
    await this.lookerClient.setUserAttribute(lookerUser, ORG_ATTR_ID, accounts.join(','))
}
```

# Cookieless, and why it is not about Chrome

The embed session is cookieless. It's tempting to file that under third-party
cookie deprecation, and after Google's announcement last month that Chrome will
keep them and offer a choice instead, that filing would age badly. The reason
is older and simpler. Safari and Firefox have blocked or partitioned
third-party cookies for years, so an iframe served from another origin hasn't
been able to rely on a cookie for a long time, whatever Chrome decides next.

So the session is four tokens with four separate lifetimes, and where each one
lives is the design:

```ts
const {
  authenticationToken, // used once, to enter
  navigationToken,     // in the iframe URL
  apiToken,            // posted into the iframe
  sessionReferenceToken, // never leaves the server
} = await acquire()
```

The authentication token is spent immediately on the login URL. The navigation
token rides in the iframe address. The API token is handed to the iframe over
`postMessage`. The session reference token, the one that can mint new tokens,
is stored server-side against the user and never reaches the browser at all.

Refresh is a message, not a reload:

```ts
postMessageToIframe({
  type: 'session:tokens',
  navigation_token: navigationToken,
  navigation_token_ttl: navigationTokenTtl,
  api_token: apiToken,
  api_token_ttl: apiTokenTtl,
  session_reference_token_ttl: sessionReferenceTokenTtl,
})
```

A user reading a dashboard for an hour never sees anything happen. The tokens
turn over underneath them and the server re-checks who they are on each acquire.
And the one credential capable of extending the session was never in reach of
the page. I think that last property is what makes the arrangement worth the
extra moving parts. A token that can renew itself is a session, and I want
sessions on the server.

# Seats leak, so something has to sweep

Create an embed user per product user and the count only ever goes up. People
leave, trials end, test accounts pile up, and the instance keeps every one of
them. A job walks the non-disabled embed users and turns off the ones that
aren't being used:

```ts
const inActiveUsers = users.filter((user) => isEmpty(user.sessions))

for (const user of inActiveUsersInCurrentEnv) {
    const plans = await this.lookerClient.getAllScheduledPlans({ user_id: user.id })

    if (isEmpty(plans)) {
        await this.disableUser(user)
    }
}
```

The scheduled-plan check is easy to leave out, and leaving it out is expensive.
A user with no sessions looks abandoned, but if they own a scheduled
delivery they're still doing work every week that somebody downstream depends
on. Disable them and the report stops, and nothing raises a hand. The first
signal is a customer asking where their Monday email went.

The sweep itself isn't correct in one pass. It pages with limit and offset over
a filtered list (users that are not disabled) while disabling users, so rows
disappear from under the cursor and the next page skips records. It converges
across repeated runs, it is not right on any single one. That's acceptable for
a housekeeping job and not for anything that matters.

# The server-side attribute is the boundary

So there are two mechanisms that look near-identical on screen. One is a
parameter the browser sets, the other an attribute the server attaches to a
user before it writes any SQL. The escaping, the reconciliation, the hash-keyed
cache and the token that stays behind are all there to keep the second one true
on every request, including the ones that were never demoed.

The visible filter is for the person reading the dashboard, and it should stay.
But when somebody asks "how do we know they cannot see another customer's
revenue", the answer is the user attribute and the `LIKE` pattern with its
escaped underscore.
