Authentication and permissions
This page describes how a request is tied to a person and how the system decides what that person may do. It is part of section 9 of the arc42 template. Tenant isolation covers the step that follows: confining the request to one company.
The problem
Section titled “The problem”Four kinds of people reach Ochema, and they must never be confused:
- staff of a carrier, who work in the office system and the driver app with an account;
- the platform team, who operate the product for every carrier;
- candidates, drivers and previous employers, who open a link and have no account;
- other systems, which send leads.
Inside a carrier, a recruiter, a compliance officer and an owner need different rights over the same records, and some records, such as drug and alcohol results, must stay hidden from almost everyone.
The rule
Section titled “The rule”- Signing in creates a session identified by a random token. The database stores only the hash of the token.
- A user acts in one company at a time, through a membership that has exactly one role.
- A role is a set of permissions taken from a fixed catalog. Every route declares what it needs, and the API decides. The screens only mirror the decision.
- Nobody grants a permission they do not hold.
- The platform team is a separate identity, with its own table, session and cookie.
- A person without an account is identified by a link token or an API key, which opens one record or one function and never a session.
How the code applies it
Section titled “How the code applies it”Accounts and sign-in
Section titled “Accounts and sign-in”An account is a row of users, one per email across the platform. What ties it to a company is a row of memberships, so one person can belong to several companies with one password. The tables are drawn in Domain model.
| Flow | How it works | Source |
|---|---|---|
| Sign-up | gate.register_tenant creates the company, the first user, the three system roles and the module switches in one call. |
packages/db/migrations/0003_gate_functions.sql |
| Sign-in | The API reads the account with gate.login_lookup and verifies the password, hashed with argon2id. An unknown email and a wrong password get the same answer. Attempts are limited per email and per IP address in Redis, and a slot is taken before the password is checked. A failed sign-in is written to the audit log, outside any company. |
apps/api/src/modules/platform/auth/auth.service.ts, passwords.ts |
| Invitation | Valid for 7 days. A new person sets a name and a password and gets a session in the company. A person who already has an account must sign in with their own password: accepting never changes an existing password. | apps/api/src/modules/platform/invitations/invitations.service.ts, gate.accept_invitation |
| Password reset | The answer is the same whether or not the email has an account. The link is valid for 1 hour, a user gets at most 3 per hour, and using it ends every session of the user. | gate.password_reset_request, gate.password_reset_consume |
Invitation and reset tokens travel in the body of a request, never in an API address, and only their hash is stored. See ADR-0018.
Sessions
Section titled “Sessions”SessionService and SessionGuard (apps/api/src/core/auth/) implement the session. The decision is in ADR-0024.
- The cookie carries a random token and is
HttpOnlyandSameSite=Lax. Over HTTPS its name has the__Host-prefix. The row ofsessionskeeps the SHA-256 of the token. - On every request,
gate.session_resolvelooks the hash up. A session lasts 30 days by default and ends after 7 days without use. A session that is expired, idle or of a disabled user is deleted and the request answers401. - Ending a session is deleting its row, and it takes effect on the next request.
CrossSiteRequestGuardrefuses a writing request that a browser reports as coming from another site, unless its origin is one of the configured front ends.- The active company is a column of the session.
POST /auth/switch-tenantchanges it, only to a company where the user has an active membership.
The driver app signs in with the same accounts and the same kind of session as the office system.
Roles and permissions
Section titled “Roles and permissions”The catalog has 97 permission keys (permissionKeys in apps/api/src/core/auth/permissions.ts). A key reads <module>.<entity>.<action>, for example recruit.candidates.manage; <module>.module.access opens a module in the menu. Keys are created only by migrations, and a test compares the list in the code with the table permissions.
Each company is born with three system roles, and can create custom roles from the same catalog.
| System role | Permissions |
|---|---|
| Owner | Every key. |
| Admin | Every key except platform.owners.manage, compliance.drug_alcohol.read, compliance.drug_alcohol.manage and compliance.sensitive_data.reveal. |
| Read only | The keys that end in .read or .access, except platform.audit.read and compliance.drug_alcohol.read. |
System roles cannot be renamed, edited or deleted: a trigger of the database refuses it for the application role. When a migration adds a permission, the same rule gives it to the system roles of the companies that already exist.
A route declares what it needs with decorators (apps/api/src/core/auth/decorators.ts): @ModuleRoutes('recruit') for the module, @RequirePermissions(...) when every key is needed and @RequireAnyPermission(...) when one is enough. A route that works without a session must be marked @Public(): nothing is public by omission. The guards run in a fixed order, shown in Building blocks. The diagram below shows what they decide for a route with a session, and the error each refusal answers with.
%%{init: {"flowchart": {"wrappingWidth": 220}}}%%
flowchart TB
s1["<b>1. Session</b><br/>The cookie token resolves"]
s2["<b>2. Company</b><br/>Active membership in<br/>an active company"]
s3["<b>3. Tab</b><br/>The tab shows the<br/>same company"]
s4["<b>4. Module</b><br/>Turned on for the company"]
s5["<b>5. Permission</b><br/>The role has module access<br/>and the permission"]
ok["The route runs in the<br/>transaction of the company"]
e1(["401 unauthenticated"])
e2(["403 no_active_tenant or<br/>tenant_access_denied"])
e3(["409 tenant_changed"])
e4(["403 module_disabled"])
e5(["403 forbidden"])
s1 --> s2
s2 --> s3
s3 --> s4
s4 --> s5
s5 --> ok
s1 -.->|"Fails"| e1
s2 -.->|"Fails"| e2
s3 -.->|"Fails"| e3
s4 -.->|"Fails"| e4
s5 -.->|"Fails"| e5
Legend. Box: a check, in the order the guards make it. Rounded box: the refusal, with the HTTP status and the error code of the API. Solid arrow: the check passed. Dotted arrow: it failed. The cross-site check runs before all of them. The third check applies when the request carries the header X-Ochema-Tenant, which the office system always sends.
How the decision is computed:
- Per request.
loadTenantAccess(session.service.ts) reads the membership, the role and its permissions inside the company context. A change of role, a disabled member or a suspended company takes effect on the next request. - Modules count. The effective permissions are the grants of the role minus those of modules turned off for the company in
tenant_modules. A module is switched withplatform.modules.manage; the Platform module cannot be turned off. - The screens mirror the API.
GET /auth/mereturns the effective permissions and the modules, and the apps hide what the user cannot do. Hiding is a convenience: the route refuses on its own. - Nobody grants what they do not hold.
RoleAccess(apps/api/src/modules/platform/roles/role-access.ts) applies one rule to inviting, changing a member and editing a role: the target role must grant nothing that the role of the caller lacks. The Owner role also needsplatform.owners.manage, nobody changes their own membership, and a company is never left without an active owner.
For the most restricted data, the permission is checked by the database itself. The policies of the drug and alcohol file call app.has_permission('compliance.drug_alcohol.read'), and revealing a sensitive value checks compliance.sensitive_data.reveal in the transaction that records the reveal. See Files and vaults and Sensitive data. In a new company only the Owner role has these permissions.
The platform team
Section titled “The platform team”Members of the platform team are rows of platform_staff, with no link to users. The decision and its alternatives are in ADR-0023.
- The panel has its own session table and its own cookie,
SameSite=Strict. A panel session lasts 12 hours and ends after 30 minutes without use. An invitation to the team is valid for 24 hours. - Routes of the panel are marked
@StaffRoutes()and live only inapps/api/src/modules/platform/admin.StaffSessionGuardreads only the panel cookie there, accepts only requests whose origin is the office system, and marks every answer as not cacheable.SessionGuardnever reads the company cookie on those routes. - A panel route has no company context. It reaches the database only through functions of the
staffschema, and each function checks the panel session again from the hash of its token. RouteBoundaryCheck(apps/api/src/core/auth/route-boundary.ts) stops the API at start when a route is marked on the wrong side, and a lint rule keeps the panel code from importing company tables.- What the team does is written to
platform_audit_log. An act that changes a company also appears in the audit log of that company, as “Ochema platform team”. See Audit log.
People and systems without an account
Section titled “People and systems without an account”| Who | What identifies them | What it opens |
|---|---|---|
| Candidate, driver, signer, previous employer | A random token inside a link. The database keeps its SHA-256, and the lookup is a gate function. |
One record: one application, one envelope, one request. Links expire or can be revoked, depending on the kind. |
| Another system sending leads | An API key in Authorization: Bearer, created in Platform > Integrations with platform.lead_api_keys.manage. The key is shown once and stored as a hash. |
POST /public/v1/leads of that company, until the key is revoked. |
| SMS and email providers | The signature of the webhook, verified before anything is read. | The webhook routes. |
A missing, unknown, malformed or revoked key gets the same 401, and the key is checked before the body. The table of link kinds is in Tenant isolation.
What guarantees it
Section titled “What guarantees it”| Test file | What it proves |
|---|---|
packages/db/test/gate.test.ts |
Session resolution deletes an expired session, an idle one and one of a disabled user. Invitations and reset tokens work once. A reset signs the user out everywhere. |
apps/api/test/auth.test.ts, login-limit.test.ts |
Cookie attributes, the same answer for a wrong password and an unknown email, the limits under parallel attempts, refusal of cross-site writes, switching only to a company of the user. |
apps/api/test/security.test.ts |
The __Host- cookie name over HTTPS and the security headers. |
apps/api/test/permissions.test.ts, role-access.test.ts |
A read only member cannot write; a custom role grants only what it lists; system roles cannot be changed; nobody raises a role above their own; a company always keeps an active owner; a disabled member is blocked on the next request. |
apps/api/test/modules.test.ts |
A module turned off answers 403 module_disabled on its routes and comes back when turned on. |
apps/api/test/openapi.test.ts, packages/db/test/privileges.test.ts |
The permission catalog of the code equals the one of the database; a new permission reaches the system roles of existing companies. |
apps/api/test/route-boundary.test.ts, lint-boundary.test.ts |
Every registered route is on one side: company routes refuse a panel session, panel routes refuse a company session, and a route marked the wrong way stops the start. |
apps/api/test/admin-auth.test.ts, admin-cookie.test.ts, admin-origin.test.ts, packages/db/test/staff-boundary.test.ts |
The panel session, its cookie, the origin check, and the refusal of every staff function without a valid panel session. |
apps/api/test/lead-api-auth.test.ts |
The same 401 for every invalid key, with no measurable difference in time, and no key in a log line, an audit row or a later answer. |
Known limits
Section titled “Known limits”- One role per member. A member has one role in each company. A person who needs the rights of two roles needs a custom role that combines them.
- Restricted permissions start with the owner. In a new company, only the Owner role can read the drug and alcohol file or reveal a full Social Security number. The owner grants these permissions through a custom role before a compliance officer can work on that file.
- Read and manage go together on the drug and alcohol file. A role with
compliance.drug_alcohol.manageand withoutcompliance.drug_alcohol.readcannot change existing records, because it cannot see them. - The platform team has a single role. Every member can do everything the panel offers.
- Lead intake is the only API for other systems. Sessions are meant for browsers. There is no general API token for integrations beyond the lead intake key.
Related
Section titled “Related”- ADR-0024: opaque cookie sessions. ADR-0023: the platform team as a separate identity. ADR-0018: public tokens stored as hashes. ADR-0016: the drug and alcohol vault.
- Tenant isolation, Sensitive data, Audit log.
- Domain model: users, memberships, roles and sessions.
- User guide: Users, roles and permissions, Invite your team, and the generated Roles and permissions matrix.