@smplcty/auth 5.0.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -46,7 +46,7 @@ const widgets = await withSession(pool, { token, roleName: 'user' }, async (clie
46
46
  });
47
47
  ```
48
48
 
49
- Active-role selection happens in TypeScript: the requested `roleName` if given (must be one the user holds), else the user's **default** role, else none — a privilege-only request is not an error. If the session doesn't exist, is expired/revoked, or the requested role isn't held, `withSession` throws **before** your callback runs.
49
+ Active-role selection happens in TypeScript: the requested `roleName` if given (must be one the user holds), else the user's **sole** role if they hold exactly one (so an admin who only holds `security` never needs the default `user` role), else their **default** role, else none — a privilege-only request is not an error. If the session doesn't exist, is expired/revoked, or the requested role isn't held, `withSession` throws **before** your callback runs.
50
50
 
51
51
  ### Errors thrown by `withSession`
52
52
 
@@ -95,6 +95,32 @@ await withSession(pool, { token, roleName: 'user' }, fn, { scope });
95
95
 
96
96
  Apps with a richer model (producer/region/plant, rep hierarchy) ship their own hook, or enforce scope "function-carried" (RLS policies call functions that read `current_user_id()`).
97
97
 
98
+ ### The RLS toolkit
99
+
100
+ The library ships role-aware, tenant-scoped RLS on its own tables (`users`, `tenants`, `user_roles`, `user_communication_methods`, `auth_domains`) — a `security` admin manages users and their roles within tenants they administer, a `settings` admin maintains `auth_domains` and (globally) creates tenants, and a plain user sees only itself. `roles` and `communication_channels` are public; `sessions` and `dev_otp_enrollments` are reached only through the bypass pool.
101
+
102
+ Those policies are built from a few `SECURITY DEFINER` functions in `public` that **your app's policies can call too** — they read `user_roles` without the policies on it recursing, and `EXECUTE` is public:
103
+
104
+ | Function | Use in a policy |
105
+ | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
106
+ | `current_user_id()` | The request actor (`app.actor_id`) — the join key every policy keys on; `NULL` when unauthenticated. |
107
+ | `auth_in_tenant(tenant_id)` | The actor holds **any** role reaching that tenant. |
108
+ | `auth_has_role(role_name, tenant_id)` | The actor holds `role_name` over that tenant. A wildcard assignment (`user_roles.tenant_id IS NULL`) reaches every tenant; passing `NULL` for `tenant_id` means "global authority" — only a wildcard assignment qualifies. |
109
+
110
+ Treat these three names as a **stable contract**: policies may depend on them. So any business table that carries a `tenant_id` gets isolation directly, and the checks compose with your own predicates:
111
+
112
+ ```yaml
113
+ policies:
114
+ - { name: read, for: SELECT, to: app_rls, using: 'auth_in_tenant(widgets.tenant_id)' }
115
+ - name: manage
116
+ for: ALL
117
+ to: app_rls
118
+ using: "auth_has_role('settings', widgets.tenant_id)"
119
+ check: "auth_has_role('settings', widgets.tenant_id)"
120
+ ```
121
+
122
+ **The `user_roles` contract.** Membership is `user_roles(user_id, role_id, tenant_id)`, where `tenant_id IS NULL` means _all tenants_ (a wildcard/global assignment). To model a finer hierarchy, `extend` `user_roles` with your own scope columns (`producer_id`, `region_id`, … — each `NULL` = wildcard at that level) and write a `SECURITY DEFINER` view or function that expands a user's assignments down your hierarchy tables. That expansion is app-owned because only your app has those tables; auth gives you the identity key and the tenant/role checks to build it on. The same wildcard rule applies at every level: `scope_col IS NULL OR scope_col = row.scope_col`.
123
+
98
124
  ## Background work — `withServiceContext`
99
125
 
100
126
  Background writers (ingestion, workers, app-init) have no human session, but audit attribution is NOT NULL. Run them as a named **service principal** (a `users` row of `kind='service'`) so `app.actor_id` is set and writes are attributed:
@@ -9,8 +9,9 @@ import type { SessionAuth, SessionContext, WithSessionOptions } from './types.js
9
9
  *
10
10
  * Active-role selection (in TS, not the resolver):
11
11
  * 1. `roleName` if given — must be one the user holds, else {@link RoleNotHeldError}.
12
- * 2. otherwise the user's default role, if any.
13
- * 3. otherwise none — a privilege-only request, which is **not** an error.
12
+ * 2. otherwise the user's sole role, if they hold exactly one.
13
+ * 3. otherwise the user's default role, if any.
14
+ * 4. otherwise none — a privilege-only request, which is **not** an error.
14
15
  *
15
16
  * Identity GUCs are transaction-local, so they vanish on COMMIT/ROLLBACK —
16
17
  * no cross-request leakage. Scope GUCs are not set here: pass a `scope`
@@ -1 +1 @@
1
- {"version":3,"file":"with-session.d.ts","sourceRoot":"","sources":["../src/with-session.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAO3C,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AA2BlF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,WAAW,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,GAAG,OAAO,EAC1E,IAAI,EAAE,IAAI,EACV,IAAI,EAAE,WAAW,CAAC,KAAK,CAAC,EACxB,EAAE,EAAE,CAAC,MAAM,EAAE,UAAU,EAAE,GAAG,EAAE,cAAc,CAAC,KAAK,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,EAClE,OAAO,GAAE,kBAAkB,CAAC,KAAK,CAAM,GACtC,OAAO,CAAC,CAAC,CAAC,CAgEZ"}
1
+ {"version":3,"file":"with-session.d.ts","sourceRoot":"","sources":["../src/with-session.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAO3C,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AA2BlF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAsB,WAAW,CAAC,KAAK,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,GAAG,OAAO,EAC1E,IAAI,EAAE,IAAI,EACV,IAAI,EAAE,WAAW,CAAC,KAAK,CAAC,EACxB,EAAE,EAAE,CAAC,MAAM,EAAE,UAAU,EAAE,GAAG,EAAE,cAAc,CAAC,KAAK,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,EAClE,OAAO,GAAE,kBAAkB,CAAC,KAAK,CAAM,GACtC,OAAO,CAAC,CAAC,CAAC,CAyEZ"}
@@ -29,8 +29,9 @@ const RESOLVE_SESSION = `
29
29
  *
30
30
  * Active-role selection (in TS, not the resolver):
31
31
  * 1. `roleName` if given — must be one the user holds, else {@link RoleNotHeldError}.
32
- * 2. otherwise the user's default role, if any.
33
- * 3. otherwise none — a privilege-only request, which is **not** an error.
32
+ * 2. otherwise the user's sole role, if they hold exactly one.
33
+ * 3. otherwise the user's default role, if any.
34
+ * 4. otherwise none — a privilege-only request, which is **not** an error.
34
35
  *
35
36
  * Identity GUCs are transaction-local, so they vanish on COMMIT/ROLLBACK —
36
37
  * no cross-request leakage. Scope GUCs are not set here: pass a `scope`
@@ -81,7 +82,17 @@ export async function withSession(pool, auth, fn, options = {}) {
81
82
  }
82
83
  activeRole = auth.roleName;
83
84
  }
85
+ else if (row.roles.length === 1) {
86
+ // A single role is unambiguous — it's the active role whether or not it
87
+ // is flagged default. `roles` is distinct by name (resolve_session), so
88
+ // the same role held across several tenants still counts as one: an admin
89
+ // who only holds `security`, in any number of tenants, gets it
90
+ // auto-selected without having to request it.
91
+ activeRole = row.roles[0];
92
+ }
84
93
  else {
94
+ // Two or more distinct roles (e.g. different roles in different tenants):
95
+ // genuinely ambiguous, so fall back to the default role, else none.
85
96
  activeRole = row.defaultRole ?? null;
86
97
  }
87
98
  const ctx = {
@@ -1 +1 @@
1
- {"version":3,"file":"with-session.js","sourceRoot":"","sources":["../src/with-session.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAC1F,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AACvD,OAAO,EAAE,kBAA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YACjC,wEAAwE;YACxE,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC;YAC1B,UAAU;YACV,KAAK,EAAE,GAAG,CAAC,KAAgB;YAC3B,UAAU,EAAE,GAAG,CAAC,UAAU;SAC3B,CAAC;QAEF,MAAM,kBAAkB,CAAC,MAAM,EAAE;YAC/B,OAAO,EAAE,GAAG,CAAC,MAAM;YACnB,SAAS,EAAE,SAAS;YACpB,UAAU,EAAE,GAAG,CAAC,UAAU;YAC1B,UAAU,EAAE,GAAG,CAAC,UAAU;SAC3B,CAAC,CAAC;QAEH,oDAAoD;QACpD,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAEnC,GAAG,CAAC,KAAK,CACP;YACE,OAAO,EAAE,WAAW;YACpB,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,UAAU,EAAE,GAAG,CAAC,UAAU;YAC1B,SAAS,EAAE,GAAG,CAAC,KAAK,CAAC,MAAM;YAC3B,cAAc,EAAE,GAAG,CAAC,UAAU,CAAC,MAAM;SACtC,EACD,qBAAqB,CACtB,CAAC;QAEF,OAAO,EAAE,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACzB,CAAC,CAAC,CAAC;AACL,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smplcty/auth",
3
- "version": "5.0.0",
3
+ "version": "6.0.0",
4
4
  "description": "Robust, type-safe session and role-based authentication primitives for PostgreSQL apps using Row-Level Security.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,26 @@
1
+ name: auth_can_admin_user
2
+ language: plpgsql
3
+ volatility: stable
4
+ security: definer
5
+ # True when the current actor is a security admin for at least one tenant the
6
+ # target user holds a role in — i.e. they share a tenant where the actor holds
7
+ # `security`. This is the "a security admin manages the users in their tenants"
8
+ # rule, used by the users and user_communication_methods policies.
9
+ returns: boolean
10
+ args:
11
+ - name: target_user_id
12
+ type: bigint
13
+ body: |
14
+ BEGIN
15
+ RETURN EXISTS (
16
+ SELECT 1
17
+ FROM user_roles t
18
+ WHERE t.user_id = target_user_id
19
+ AND t.deleted_at IS NULL
20
+ AND auth_has_role('security', t.tenant_id)
21
+ );
22
+ END;
23
+ comment: >
24
+ True if the current actor holds the security role over a tenant the target
25
+ user belongs to. SECURITY DEFINER so RLS policies can call it without
26
+ recursing on user_roles.
@@ -0,0 +1,82 @@
1
+ name: auth_create_user
2
+ language: plpgsql
3
+ security: definer
4
+ # The authority-checked, atomic way for an app_rls request (a security admin) to
5
+ # provision a human user. Raw INSERT on `users` is closed under RLS — a user
6
+ # must never exist without the roles and contact methods that make it usable,
7
+ # and the grant of access must be authorized — so creation funnels through here.
8
+ #
9
+ # `user_data` shape:
10
+ # {
11
+ # "name": "Ada Lovelace",
12
+ # "communication_methods": [ { "channel": "email", "code": "ada@acme.com" } ],
13
+ # "accesses": [ { "tenant_id": 5, "role_id": 2 } ]
14
+ # }
15
+ # At least one communication method and one access are required. `channel` is
16
+ # resolved by name; `tenant_id`/`role_id` are ids the caller already resolved
17
+ # (the library pins none). A NULL/absent tenant_id is an all-tenants grant.
18
+ #
19
+ # Authority: the caller must hold `security` over every tenant in `accesses`;
20
+ # an all-tenants grant requires holding `security` globally. Any failure aborts
21
+ # the whole call — no partially-provisioned user is left behind. SECURITY
22
+ # DEFINER does the writes RLS would otherwise block, but current_user_id() still
23
+ # resolves to the caller, so the checks run against the calling admin.
24
+ returns: bigint
25
+ args:
26
+ - name: user_data
27
+ type: jsonb
28
+ body: |
29
+ DECLARE
30
+ v_user_id bigint;
31
+ v_access jsonb;
32
+ v_methods int;
33
+ BEGIN
34
+ IF current_user_id() IS NULL THEN
35
+ RAISE EXCEPTION 'auth_create_user: no authenticated actor (app.actor_id is unset)';
36
+ END IF;
37
+
38
+ IF jsonb_typeof(user_data -> 'accesses') IS DISTINCT FROM 'array'
39
+ OR jsonb_array_length(user_data -> 'accesses') = 0 THEN
40
+ RAISE EXCEPTION 'auth_create_user: at least one access (tenant_id + role_id) is required';
41
+ END IF;
42
+
43
+ IF jsonb_typeof(user_data -> 'communication_methods') IS DISTINCT FROM 'array'
44
+ OR jsonb_array_length(user_data -> 'communication_methods') = 0 THEN
45
+ RAISE EXCEPTION 'auth_create_user: at least one communication method is required';
46
+ END IF;
47
+
48
+ -- Authority: a security admin for each granted tenant; a global (NULL
49
+ -- tenant) grant requires holding security globally.
50
+ FOR v_access IN SELECT * FROM jsonb_array_elements(user_data -> 'accesses')
51
+ LOOP
52
+ IF NOT auth_has_role('security', (v_access ->> 'tenant_id')::bigint) THEN
53
+ RAISE EXCEPTION 'auth_create_user: not authorized to grant access to tenant %',
54
+ COALESCE(v_access ->> 'tenant_id', 'ALL');
55
+ END IF;
56
+ END LOOP;
57
+
58
+ INSERT INTO users (name, kind)
59
+ VALUES (user_data ->> 'name', 'human')
60
+ RETURNING user_id INTO v_user_id;
61
+
62
+ INSERT INTO user_communication_methods (user_id, communication_channel_id, code)
63
+ SELECT v_user_id, cc.communication_channel_id, m ->> 'code'
64
+ FROM jsonb_array_elements(user_data -> 'communication_methods') AS m
65
+ JOIN communication_channels cc
66
+ ON cc.name = m ->> 'channel' AND cc.deleted_at IS NULL;
67
+ GET DIAGNOSTICS v_methods = ROW_COUNT;
68
+ IF v_methods = 0 THEN
69
+ RAISE EXCEPTION 'auth_create_user: no communication method matched a known channel';
70
+ END IF;
71
+
72
+ INSERT INTO user_roles (user_id, tenant_id, role_id)
73
+ SELECT v_user_id, (a ->> 'tenant_id')::bigint, (a ->> 'role_id')::bigint
74
+ FROM jsonb_array_elements(user_data -> 'accesses') AS a;
75
+
76
+ RETURN v_user_id;
77
+ END;
78
+ comment: >
79
+ Authority-checked, atomic human-user provisioning (user + communication
80
+ methods + role assignments). The only app_rls path to create a user, since
81
+ RLS closes raw INSERT on users. Requires the caller to hold security over
82
+ every granted tenant (global security for an all-tenants grant).
@@ -0,0 +1,36 @@
1
+ name: auth_has_role
2
+ language: plpgsql
3
+ volatility: stable
4
+ security: definer
5
+ # True when the current request actor holds `role_name` with authority over
6
+ # `target_tenant_id`. A wildcard assignment (user_roles.tenant_id IS NULL)
7
+ # reaches every tenant, so it always qualifies. Passing a NULL target means
8
+ # "global authority over this role" — only a wildcard assignment satisfies it
9
+ # (a tenant-scoped assignment yields NULL, which is not true), so granting or
10
+ # acting on an all-tenants resource requires holding the role globally.
11
+ #
12
+ # SECURITY DEFINER so it reads user_roles/roles unfiltered — RLS policies call
13
+ # it without tripping the policies on those very tables (no recursion).
14
+ returns: boolean
15
+ args:
16
+ - name: role_name
17
+ type: text
18
+ - name: target_tenant_id
19
+ type: bigint
20
+ body: |
21
+ BEGIN
22
+ RETURN current_user_id() IS NOT NULL AND EXISTS (
23
+ SELECT 1
24
+ FROM user_roles ur
25
+ JOIN roles r ON r.role_id = ur.role_id AND r.deleted_at IS NULL
26
+ WHERE ur.user_id = current_user_id()
27
+ AND ur.deleted_at IS NULL
28
+ AND r.name = role_name
29
+ AND (ur.tenant_id IS NULL OR ur.tenant_id = target_tenant_id)
30
+ );
31
+ END;
32
+ comment: >
33
+ True if the current actor holds role_name over target_tenant_id (a wildcard
34
+ user_role reaches any tenant; a NULL target requires a wildcard, i.e. global,
35
+ assignment). SECURITY DEFINER so RLS policies can call it without recursing on
36
+ user_roles/roles.
@@ -0,0 +1,25 @@
1
+ name: auth_in_tenant
2
+ language: plpgsql
3
+ volatility: stable
4
+ security: definer
5
+ # True when the current actor holds ANY role reaching `target_tenant_id`
6
+ # (directly or via a wildcard assignment). Used where visibility is granted to
7
+ # every member of a tenant regardless of which role they hold — e.g. a tenant
8
+ # row is visible to anyone with access to that tenant.
9
+ returns: boolean
10
+ args:
11
+ - name: target_tenant_id
12
+ type: bigint
13
+ body: |
14
+ BEGIN
15
+ RETURN current_user_id() IS NOT NULL AND EXISTS (
16
+ SELECT 1
17
+ FROM user_roles ur
18
+ WHERE ur.user_id = current_user_id()
19
+ AND ur.deleted_at IS NULL
20
+ AND (ur.tenant_id IS NULL OR ur.tenant_id = target_tenant_id)
21
+ );
22
+ END;
23
+ comment: >
24
+ True if the current actor holds any role reaching target_tenant_id. SECURITY
25
+ DEFINER so RLS policies can call it without recursing on user_roles.
@@ -61,7 +61,7 @@ body: |
61
61
  END;
62
62
  comment: >
63
63
  SECURITY DEFINER pure resolver for sessions — bypasses RLS on auth
64
- tables so app_user can read session → user → roles without GUCs set
64
+ tables so app_rls can read session → user → roles without GUCs set
65
65
  first. Returns aggregate role/privilege info only (no raw PII); does
66
66
  no validation (expiry, revocation, and role selection live in
67
67
  withSession).
@@ -0,0 +1,38 @@
1
+ -- Back-fill the canonical values on the standard roles.
2
+ --
3
+ -- Seeds are insert-only (schema-flow >= 0.13.0), so on a database that already
4
+ -- had the `roles` rows before this library shipped display_name / description /
5
+ -- is_default / is_privilege, the seed never runs and those rows keep the column
6
+ -- defaults — most importantly `is_default = false` for *every* role. withSession
7
+ -- selects the default role from `is_default = true`, so with nothing flagged
8
+ -- there is no default role and every session that doesn't request one explicitly
9
+ -- breaks. The library is the only thing that knows the canonical set, so it owns
10
+ -- the back-fill rather than leaving each consumer to discover the gap at runtime.
11
+ --
12
+ -- The `display_name IS NULL` guard makes this idempotent and a no-op on a fresh
13
+ -- database (the seed already wrote the values), and leaves a role a consumer has
14
+ -- deliberately renamed/customised untouched. `deleted_at IS NULL` keeps it to the
15
+ -- live rows the partial-unique name index covers.
16
+ --
17
+ -- The audit trigger stamps updated_by from app.actor_id; set it to the app-init
18
+ -- principal first so the touched rows get a valid attribution (and so this works
19
+ -- on @smplcty/schema-std >= 0.1.0, which rejects actor-less writes outright).
20
+ SELECT set_config(
21
+ 'app.actor_id',
22
+ (SELECT user_id::text FROM users WHERE name = 'app-init' AND kind = 'service'),
23
+ true
24
+ );
25
+
26
+ UPDATE roles r
27
+ SET display_name = v.display_name,
28
+ description = v.description,
29
+ is_default = v.is_default,
30
+ is_privilege = v.is_privilege
31
+ FROM (VALUES
32
+ ('user', 'User', 'Standard signed-in user.', true, false),
33
+ ('settings', 'Settings', 'Account and organisation settings access.', false, false),
34
+ ('security', 'Security', 'Security administration.', false, false)
35
+ ) AS v (name, display_name, description, is_default, is_privilege)
36
+ WHERE r.name = v.name
37
+ AND r.display_name IS NULL
38
+ AND r.deleted_at IS NULL;
@@ -14,6 +14,10 @@ table: auth_domains
14
14
  # auth's data model, so auth ships it. Rows are configured at runtime
15
15
  # (admin UI) and resolved by auth_domain_id — there is no stable text key.
16
16
  mixins: [audit, soft_delete]
17
+ # Grants. RLS-gated writes by the request role (a settings admin).
18
+ grants:
19
+ - to: app_rls
20
+ privileges: [SELECT, INSERT, UPDATE]
17
21
  columns:
18
22
  - name: auth_domain_id
19
23
  type: bigserial
@@ -41,3 +45,15 @@ columns:
41
45
  type: jsonb
42
46
  nullable: false
43
47
  default: "'{}'::jsonb"
48
+ # RLS. Federation config is a settings concern: a settings admin sees and
49
+ # maintains the auth_domains of the tenants they have settings access to. (Sign-
50
+ # in itself reads auth_domains through the bypass pool pre-session, so ordinary
51
+ # users never need direct access here.)
52
+ rls: true
53
+ policies:
54
+ - name: auth_domains_settings
55
+ for: ALL
56
+ to: app_rls
57
+ permissive: true
58
+ using: auth_has_role('settings', auth_domains.tenant_id)
59
+ check: auth_has_role('settings', auth_domains.tenant_id)
@@ -1,5 +1,9 @@
1
1
  table: communication_channels
2
2
  mixins: [audit, soft_delete]
3
+ # Grants. Reference data: read-only for the request role (seeded by the owner).
4
+ grants:
5
+ - to: app_rls
6
+ privileges: [SELECT]
3
7
  columns:
4
8
  - name: communication_channel_id
5
9
  type: bigserial
@@ -1,5 +1,11 @@
1
1
  table: dev_otp_enrollments
2
2
  mixins: [soft_delete]
3
+ # Grants. TOTP secrets: never reachable by the RLS request role (app_rls). Only
4
+ # the trusted auth machinery (app_privileged) reads/writes them, during pre-auth
5
+ # sign-in.
6
+ grants:
7
+ - to: app_privileged
8
+ privileges: [SELECT, INSERT, UPDATE]
3
9
  columns:
4
10
  # The user_communication_method this enrollment is for. There can only
5
11
  # be one dev OTP enrollment per communication method (PK + FK).
@@ -1,5 +1,10 @@
1
1
  table: roles
2
2
  mixins: [audit, soft_delete]
3
+ # Grants. Reference data: the request role reads it; only the migration owner
4
+ # writes it (seeded). No INSERT/UPDATE for app_rls.
5
+ grants:
6
+ - to: app_rls
7
+ privileges: [SELECT]
3
8
  columns:
4
9
  - name: role_id
5
10
  type: bigserial
@@ -12,9 +17,11 @@ columns:
12
17
  type: text
13
18
  - name: description
14
19
  type: text
15
- # The role auto-selected by withSession when no roleName is requested.
16
- # An app should mark exactly one is_privilege=false role as default;
17
- # the library just picks the first default it finds.
20
+ # The role withSession auto-selects when no roleName is requested AND the
21
+ # user holds more than one role. A user who holds exactly one role always
22
+ # gets that one (default or not), so is_default only breaks ties for
23
+ # multi-role users. An app should mark exactly one is_privilege=false role as
24
+ # default; the library picks the first default it finds.
18
25
  - name: is_default
19
26
  type: boolean
20
27
  nullable: false
@@ -5,6 +5,12 @@ table: sessions
5
5
  # validateSession honor both; the library ships no delete setter (it's a
6
6
  # plain column write the app owns).
7
7
  mixins: [soft_delete]
8
+ # Grants. A credential: the RLS request role (app_rls) gets NOTHING — sessions
9
+ # are read via the SECURITY DEFINER resolve_session and written only by the
10
+ # trusted auth machinery. Only app_privileged (BYPASSRLS) touches the table.
11
+ grants:
12
+ - to: app_privileged
13
+ privileges: [SELECT, INSERT, UPDATE]
8
14
  columns:
9
15
  - name: session_id
10
16
  type: text
@@ -1,5 +1,9 @@
1
1
  table: tenants
2
2
  mixins: [audit, soft_delete]
3
+ # Grants. RLS-gated writes by the request role.
4
+ grants:
5
+ - to: app_rls
6
+ privileges: [SELECT, INSERT, UPDATE]
3
7
  columns:
4
8
  - name: tenant_id
5
9
  type: bigserial
@@ -32,3 +36,26 @@ indexes:
32
36
  unique: true
33
37
  where: 'deleted_at IS NULL'
34
38
  name: tenants_slug_key
39
+ # RLS. A tenant is visible to anyone with access to it (any role). Maintaining a
40
+ # tenant — including archiving it via deleted_at — requires holding `settings`
41
+ # over it; creating a tenant is a global act and requires holding `settings`
42
+ # globally (auth_has_role('settings', NULL) only matches a wildcard assignment).
43
+ # There is no hard-DELETE policy: tenants are soft-deleted like every auth table.
44
+ rls: true
45
+ policies:
46
+ - name: tenants_select
47
+ for: SELECT
48
+ to: app_rls
49
+ permissive: true
50
+ using: auth_in_tenant(tenants.tenant_id)
51
+ - name: tenants_insert
52
+ for: INSERT
53
+ to: app_rls
54
+ permissive: true
55
+ check: auth_has_role('settings', NULL::bigint)
56
+ - name: tenants_update
57
+ for: UPDATE
58
+ to: app_rls
59
+ permissive: true
60
+ using: auth_has_role('settings', tenants.tenant_id)
61
+ check: auth_has_role('settings', tenants.tenant_id)
@@ -1,5 +1,9 @@
1
1
  table: user_communication_methods
2
2
  mixins: [audit, soft_delete]
3
+ # Grants. RLS-gated writes by the request role.
4
+ grants:
5
+ - to: app_rls
6
+ privileges: [SELECT, INSERT, UPDATE]
3
7
  columns:
4
8
  - name: user_communication_method_id
5
9
  type: bigserial
@@ -25,3 +29,19 @@ indexes:
25
29
  unique: true
26
30
  where: 'deleted_at IS NULL'
27
31
  name: user_communication_methods_channel_code_key
32
+ # RLS. A communication method follows its owning user: you manage your own, and
33
+ # a security admin manages those of users they administer (auth_can_admin_user).
34
+ # Since a plain user can only "see" themselves, they can only touch their own
35
+ # contact methods; a security admin reaches every user in their tenants.
36
+ rls: true
37
+ policies:
38
+ - name: user_communication_methods_access
39
+ for: ALL
40
+ to: app_rls
41
+ permissive: true
42
+ using: |-
43
+ user_communication_methods.user_id = current_user_id()
44
+ OR auth_can_admin_user(user_communication_methods.user_id)
45
+ check: |-
46
+ user_communication_methods.user_id = current_user_id()
47
+ OR auth_can_admin_user(user_communication_methods.user_id)
@@ -1,5 +1,9 @@
1
1
  table: user_roles
2
2
  mixins: [audit, soft_delete]
3
+ # Grants. RLS-gated writes by the request role (a security admin assigns roles).
4
+ grants:
5
+ - to: app_rls
6
+ privileges: [SELECT, INSERT, UPDATE]
3
7
  columns:
4
8
  - name: user_role_id
5
9
  type: bigserial
@@ -24,3 +28,29 @@ columns:
24
28
  references:
25
29
  table: tenants
26
30
  column: tenant_id
31
+ # RLS. You can read your own role assignments; a security admin can read and
32
+ # manage assignments in the tenants where they hold security. Writing an
33
+ # assignment requires holding security over that tenant — and because
34
+ # auth_has_role(..., NULL) only matches a wildcard assignment, granting an
35
+ # all-tenants (global) role requires holding security globally. This is the same
36
+ # rule auth_create_user enforces, applied to changing an existing user's roles.
37
+ rls: true
38
+ policies:
39
+ - name: user_roles_select
40
+ for: SELECT
41
+ to: app_rls
42
+ permissive: true
43
+ using: |-
44
+ user_roles.user_id = current_user_id()
45
+ OR auth_has_role('security', user_roles.tenant_id)
46
+ - name: user_roles_insert
47
+ for: INSERT
48
+ to: app_rls
49
+ permissive: true
50
+ check: auth_has_role('security', user_roles.tenant_id)
51
+ - name: user_roles_update
52
+ for: UPDATE
53
+ to: app_rls
54
+ permissive: true
55
+ using: auth_has_role('security', user_roles.tenant_id)
56
+ check: auth_has_role('security', user_roles.tenant_id)
@@ -5,6 +5,15 @@ table: users
5
5
  # from app.actor_id, so seeding any user requires an actor: see the app-init
6
6
  # seed below + the perTxSqlPath note in schema-flow.config.yaml.
7
7
  mixins: [audit, soft_delete]
8
+ # Grants. app_rls (the RLS-bound request role) reads users and updates them
9
+ # under RLS; it cannot INSERT — creation is via auth_create_user (DEFINER), or
10
+ # OIDC auto-provisioning on the privileged role. app_privileged (the trusted,
11
+ # BYPASSRLS auth machinery, a member of app_rls) gets only the INSERT delta.
12
+ grants:
13
+ - to: app_rls
14
+ privileges: [SELECT, UPDATE]
15
+ - to: app_privileged
16
+ privileges: [INSERT]
8
17
  columns:
9
18
  - name: user_id
10
19
  type: bigserial
@@ -45,3 +54,30 @@ indexes:
45
54
  seeds:
46
55
  - name: 'app-init'
47
56
  kind: 'service'
57
+ # RLS. A user row is visible to the user themselves, to whoever created it (so a
58
+ # security admin can read back a user they just provisioned, before its roles
59
+ # land), and to a security admin sharing one of the user's tenants. There is
60
+ # deliberately NO INSERT policy: app_rls cannot raw-INSERT a user — provisioning
61
+ # goes through auth_create_user (atomic + authority-checked), or the privileged
62
+ # role for OIDC auto-provisioning (which is why app_privileged, not app_rls,
63
+ # holds the users INSERT grant). The owner/privileged pool bypasses all of this.
64
+ rls: true
65
+ policies:
66
+ - name: users_select
67
+ for: SELECT
68
+ to: app_rls
69
+ permissive: true
70
+ using: |-
71
+ users.user_id = current_user_id()
72
+ OR users.created_by = current_user_id()
73
+ OR auth_can_admin_user(users.user_id)
74
+ - name: users_update
75
+ for: UPDATE
76
+ to: app_rls
77
+ permissive: true
78
+ using: |-
79
+ users.created_by = current_user_id()
80
+ OR auth_can_admin_user(users.user_id)
81
+ check: |-
82
+ users.created_by = current_user_id()
83
+ OR auth_can_admin_user(users.user_id)