@sanoma-ai/connector-supabase 0.4.7 → 0.4.9
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 +70 -0
- package/dist/driver.d.ts +1 -0
- package/dist/vault.d.ts +11 -0
- package/dist/vault.js +103 -0
- package/dist/vault.js.map +1 -0
- package/package.json +16 -7
- package/sql/vault.sql +136 -0
package/README.md
CHANGED
|
@@ -116,3 +116,73 @@ SANOMA_LIVE=1 SANOMA_RECORD=1 SUPABASE_TEST_PROJECT_REF=<ref> pnpm vitest run co
|
|
|
116
116
|
```
|
|
117
117
|
|
|
118
118
|
License: FSL-1.1-ALv2.
|
|
119
|
+
|
|
120
|
+
## Supabase Vault as the secret store
|
|
121
|
+
|
|
122
|
+
Import the server-only `@sanoma-ai/connector-supabase/vault` entry in deployment config. This stores credentials in **Supabase Vault**, separate from Sanoma's built-in encrypted Postgres table. Company code still uses logical secret names and named connections. The example config fragment is:
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
import { supabaseVault } from "@sanoma-ai/connector-supabase/vault";
|
|
126
|
+
|
|
127
|
+
const secrets = {
|
|
128
|
+
store: supabaseVault(),
|
|
129
|
+
namespace: "production",
|
|
130
|
+
bindings: {
|
|
131
|
+
STRIPE_API_KEY: { path: "customer-stripe", management: "external" as const },
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
// Pass `secrets` to defineConfig alongside connectors/workflows.
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### Provision the database boundary
|
|
138
|
+
|
|
139
|
+
Install `sql/vault.sql` from this package **once**, as the project administrator in a project with the Vault extension enabled. The installer creates a private `sanoma_vault` schema; it does not create a runtime login or grant access to any namespace. Never add that schema or `vault` to Data API exposed schemas, or grant their tables/views to browser roles. The gateway removes default grants to `PUBLIC`, `anon`, `authenticated` and `service_role` on its own objects.
|
|
140
|
+
|
|
141
|
+
Create a dedicated login with no memberships or administrative privileges (not `postgres`, `service_role`, or a role with access to `vault`). Set its password through your administrator's protected credential flow. Grant only the gateway access and the intended namespace:
|
|
142
|
+
|
|
143
|
+
```sql
|
|
144
|
+
-- `sanoma_runtime` is the dedicated LOGIN created by your administrator.
|
|
145
|
+
GRANT USAGE ON SCHEMA sanoma_vault TO sanoma_runtime;
|
|
146
|
+
GRANT EXECUTE ON FUNCTION sanoma_vault.access(text,text,text,text,text,text)
|
|
147
|
+
TO sanoma_runtime;
|
|
148
|
+
INSERT INTO sanoma_vault.namespaces(login, namespace, writable)
|
|
149
|
+
VALUES ('sanoma_runtime', 'production', true);
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Each login/namespace gets a random prefix for Sanoma-managed Vault names. Namespace strings alone do not authorize anything: the gateway checks the database's `session_user`. It rejects logins with direct Vault schema access. Use a distinct login and namespace grant per deployment/company, and a database connection that preserves that login (not a shared admin connection with `SET ROLE`). The private schema must stay owned by an administrator; the runtime cannot modify its grants or functions.
|
|
153
|
+
|
|
154
|
+
To reference an existing Vault secret, an administrator maps its UUID without moving its value:
|
|
155
|
+
|
|
156
|
+
```sql
|
|
157
|
+
INSERT INTO sanoma_vault.external_secrets(login, namespace, path, secret_id)
|
|
158
|
+
VALUES ('sanoma_runtime', 'production', 'customer-stripe', '<existing-secret-uuid>');
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Declare that path with `management: "external"`. The gateway independently refuses writes/deletes to external mappings even if code incorrectly claims ownership. External rotation is detected on the next read. Deleting the underlying customer secret makes it missing; Sanoma does not recreate it.
|
|
162
|
+
|
|
163
|
+
### Supabase plus Cloudflare
|
|
164
|
+
|
|
165
|
+
Supply the scoped login's Postgres URL as `SUPABASE_VAULT_DATABASE_URL` to the **Sanoma Node runtime**, with TLS certificate verification enabled for remote connections. `databaseUrlEnv` selects another bootstrap variable. Supply `SANOMA_SIGNING_KEY` independently, plus the application's database URL. Vault values do **not** need `SANOMA_SECRETS_KEY`. With a Cloudflare Container host, configure its Worker deployment secrets and explicitly pass the required values to the container; a Worker secret is not automatically a container environment variable. This adapter uses `pg` in the container, not a browser or bare Worker binding.
|
|
166
|
+
|
|
167
|
+
The adapter opens at most four connections lazily, releases idle connections after one second, and exposes `close()` for tools/tests. Keep SQL statement/parameter logging and tracing configured to exclude credential values; the adapter uses bound parameters and sanitized errors, but database administrators control database logs. Never log the bootstrap URL.
|
|
168
|
+
|
|
169
|
+
### Semantics and recovery
|
|
170
|
+
|
|
171
|
+
- Maximum value: 65,536 UTF-8 bytes, including a serialized credential bundle. NUL is unsupported by Postgres text.
|
|
172
|
+
- Creates and compare-and-set replacements/deletes are atomic through the gateway. Supabase’s standard `postgres` administrator is not a superuser and lacks direct `UPDATE` on `vault.secrets`, so `SELECT FOR UPDATE` is unavailable. The gateway uses the administrator’s existing `DELETE` privilege to acquire a `SHARE` table lock for reads or `SHARE ROW EXCLUSIVE` for writes, then performs ordinary `SELECT` queries. These locks coordinate ordinary direct Vault writes and keep the encrypted metadata and decrypted value stable across queries. Versions include encrypted-row state and a random revision, never a plaintext password hash. No plaintext cache is kept.
|
|
173
|
+
- Locking is project-wide: gateway reads can run concurrently, but gateway writes serialize across all Vault secrets, including unrelated namespaces. Reads block Vault writes while held; gateway writes also block gateway reads. Locks last until the transaction ends, so long transactions increase contention for other Vault users. This favors consistent versions and atomic compare-and-set over per-secret write concurrency.
|
|
174
|
+
- Deletion removes the active row. Database backups/PITR may retain older encrypted data according to the project's retention policy. It is not cryptographic erasure.
|
|
175
|
+
- The gateway detects ordinary direct Vault updates, but project administrators remain trusted: they control grants, functions, metadata, and encryption custody. Runtime scope is not protection against a compromised project administrator.
|
|
176
|
+
- Supabase manages the project encryption key. Preserve the gateway grant/mapping/revision tables with database backups. A raw dump moved to another project may not be decryptable without the original Vault key; use Supabase's documented restore/key-transfer route or an authorized decrypt-and-reencrypt migration. Sanoma's cross-store migration is tracked separately in #468; this adapter does not export root keys or perform migration automatically.
|
|
177
|
+
|
|
178
|
+
See [Vault APIs and recovery](https://supabase.com/docs/guides/database/vault) and [Supabase's privilege constraints](https://supabase.com/kb/troubleshooting/revoking-privileges-on-storage-pg_cron-vault-and-extension-objects-has-no-effect). Tested with the actual Vault extension and standard administrator permissions in `supabase/postgres:17.6.1.136`; hosted-project permissions still depend on the project's installed grants/version.
|
|
179
|
+
|
|
180
|
+
### Verification
|
|
181
|
+
|
|
182
|
+
Normal tests mock the transport and never contact Supabase. The opt-in SQL proof creates and drops an isolated database and a generated login, using only synthetic values. Point `SANOMA_VAULT_TEST_DATABASE_URL` at a disposable Supabase instance using its standard non-superuser `postgres` administrator, with the Vault extension available and permission to create databases/logins. The test requires that this role lack direct `UPDATE` on `vault.secrets`; a superuser or broader grant would mask the permissions bug and is rejected. Then run:
|
|
183
|
+
|
|
184
|
+
```sh
|
|
185
|
+
pnpm vitest run connectors/supabase/test/vault-live.test.ts
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
It tests conformance, independent concurrent writers, external ownership/rotation, administrator/direct-view refusal, cross-namespace denial, ciphertext at rest and stale replacement after a direct Vault update. A concurrent outside-writer case holds a direct Vault update open, verifies that the gateway waits on the table lock, and checks that the stale replacement is rejected after the writer commits. Do not point the opt-in administrator URL at a production project.
|
package/dist/driver.d.ts
CHANGED
|
@@ -18,6 +18,7 @@ export interface SupabaseDriverOptions {
|
|
|
18
18
|
export declare function supabaseDriver({ bridge, timeoutMs }?: SupabaseDriverOptions): Readonly<{
|
|
19
19
|
vendor: string;
|
|
20
20
|
ops: Readonly<Record<string, import("@sanoma-ai/workflows").DriverFn>>;
|
|
21
|
+
authentication?: readonly string[];
|
|
21
22
|
env: z.ZodObject<{
|
|
22
23
|
SUPABASE_ACCESS_TOKEN: z.ZodString;
|
|
23
24
|
}, z.core.$strip>;
|
package/dist/vault.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type SecretStore } from "@sanoma-ai/workflows";
|
|
2
|
+
export interface SupabaseVaultOptions {
|
|
3
|
+
/** Bootstrap environment variable containing the scoped login's Postgres URL. Never a service-role API key. */
|
|
4
|
+
databaseUrlEnv?: string;
|
|
5
|
+
/** Must agree with the administrator's namespace grant. External bindings stay read-only either way. */
|
|
6
|
+
writable?: boolean;
|
|
7
|
+
}
|
|
8
|
+
/** Server-only adapter over sql/vault.sql. The app never receives the database URL or decrypted view. */
|
|
9
|
+
export declare function supabaseVault(options?: SupabaseVaultOptions): SecretStore & {
|
|
10
|
+
close(): Promise<void>;
|
|
11
|
+
};
|
package/dist/vault.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { SecretStoreError } from "@sanoma-ai/workflows";
|
|
2
|
+
import { Pool } from "pg";
|
|
3
|
+
const decoded = (result) => {
|
|
4
|
+
const v = result;
|
|
5
|
+
if (!v || typeof v.value !== "string" || typeof v.version !== "string" || !/^[a-f0-9]{64}$/.test(v.version))
|
|
6
|
+
throw new SecretStoreError("unavailable");
|
|
7
|
+
return {
|
|
8
|
+
value: v.value,
|
|
9
|
+
version: v.version,
|
|
10
|
+
...(typeof v.updatedAt === "string" && { updatedAt: v.updatedAt }),
|
|
11
|
+
...(typeof v.updatedBy === "string" && { updatedBy: v.updatedBy }),
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
/** Server-only adapter over sql/vault.sql. The app never receives the database URL or decrypted view. */
|
|
15
|
+
export function supabaseVault(options = {}) {
|
|
16
|
+
const env = options.databaseUrlEnv ?? "SUPABASE_VAULT_DATABASE_URL";
|
|
17
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(env))
|
|
18
|
+
throw new SecretStoreError("invalid_configuration");
|
|
19
|
+
const writable = options.writable ?? true;
|
|
20
|
+
let pool;
|
|
21
|
+
const invoke = async (operation, namespace, path, value, expected, by) => {
|
|
22
|
+
if (!namespace.trim() ||
|
|
23
|
+
namespace.includes("\0") ||
|
|
24
|
+
(path !== undefined && (!path || path.includes("\0") || path.length > 1024)))
|
|
25
|
+
throw new SecretStoreError("invalid_configuration");
|
|
26
|
+
try {
|
|
27
|
+
if (!pool) {
|
|
28
|
+
const connectionString = process.env[env];
|
|
29
|
+
if (!connectionString)
|
|
30
|
+
throw new SecretStoreError("invalid_configuration");
|
|
31
|
+
pool = new Pool({
|
|
32
|
+
connectionString,
|
|
33
|
+
max: 4,
|
|
34
|
+
idleTimeoutMillis: 1000,
|
|
35
|
+
connectionTimeoutMillis: 10_000,
|
|
36
|
+
statement_timeout: 15_000,
|
|
37
|
+
allowExitOnIdle: true,
|
|
38
|
+
});
|
|
39
|
+
// Idle connection errors must not surface provider payloads through an unhandled EventEmitter error.
|
|
40
|
+
pool.on("error", () => { });
|
|
41
|
+
}
|
|
42
|
+
const result = await pool.query("SELECT sanoma_vault.access($1, $2, $3, $4, $5, $6) AS result", [operation, namespace, path ?? null, value ?? null, expected ?? null, by ?? null]);
|
|
43
|
+
return result.rows[0]?.result;
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (error instanceof SecretStoreError)
|
|
47
|
+
throw error;
|
|
48
|
+
const code = error?.code;
|
|
49
|
+
throw new SecretStoreError(code === "42501"
|
|
50
|
+
? "denied"
|
|
51
|
+
: code === "SV001"
|
|
52
|
+
? "read_only"
|
|
53
|
+
: code === "SV002" || code === "23505"
|
|
54
|
+
? "conflict"
|
|
55
|
+
: code === "SV003"
|
|
56
|
+
? "too_large"
|
|
57
|
+
: code === "22023" || code === "42P01" || code === "42883" || code === "3F000"
|
|
58
|
+
? "invalid_configuration"
|
|
59
|
+
: "unavailable");
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const mutable = () => {
|
|
63
|
+
if (!writable)
|
|
64
|
+
throw new SecretStoreError("read_only");
|
|
65
|
+
};
|
|
66
|
+
return {
|
|
67
|
+
id: "supabase-vault",
|
|
68
|
+
capabilities: Object.freeze({
|
|
69
|
+
writable,
|
|
70
|
+
maxBytes: 65_536,
|
|
71
|
+
conditionalWrites: "atomic",
|
|
72
|
+
deletion: "destroy",
|
|
73
|
+
changeDetection: "read",
|
|
74
|
+
}),
|
|
75
|
+
async validate(namespace) {
|
|
76
|
+
const result = (await invoke("validate", namespace));
|
|
77
|
+
if (result?.protocol !== 1 || (writable && !result.writable))
|
|
78
|
+
throw new SecretStoreError("invalid_configuration");
|
|
79
|
+
},
|
|
80
|
+
async read({ namespace, path }) {
|
|
81
|
+
const result = await invoke("read", namespace, path);
|
|
82
|
+
return result === null ? undefined : decoded(result);
|
|
83
|
+
},
|
|
84
|
+
async write({ namespace, path }, value, { expectedVersion, by }) {
|
|
85
|
+
mutable();
|
|
86
|
+
if (value.includes("\0"))
|
|
87
|
+
throw new SecretStoreError("invalid_value");
|
|
88
|
+
if (Buffer.byteLength(value, "utf8") > 65_536)
|
|
89
|
+
throw new SecretStoreError("too_large");
|
|
90
|
+
return decoded(await invoke("write", namespace, path, value, expectedVersion, by));
|
|
91
|
+
},
|
|
92
|
+
async delete({ namespace, path }, { expectedVersion, by }) {
|
|
93
|
+
mutable();
|
|
94
|
+
await invoke("delete", namespace, path, undefined, expectedVersion, by);
|
|
95
|
+
},
|
|
96
|
+
async close() {
|
|
97
|
+
const current = pool;
|
|
98
|
+
pool = undefined;
|
|
99
|
+
await current?.end();
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=vault.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vault.js","sourceRoot":"","sources":["../src/vault.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAA0D,MAAM,sBAAsB,CAAC;AAChH,OAAO,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAS1B,MAAM,OAAO,GAAG,CAAC,MAAe,EAAe,EAAE;IAC/C,MAAM,CAAC,GAAG,MAAqC,CAAC;IAChD,IAAI,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,KAAK,KAAK,QAAQ,IAAI,OAAO,CAAC,CAAC,OAAO,KAAK,QAAQ,IAAI,CAAC,gBAAgB,CAAC,IAAI,C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AM,CAAC,UAAU,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,MAAM;gBAAE,MAAM,IAAI,gBAAgB,CAAC,WAAW,CAAC,CAAC;YACvF,OAAO,OAAO,CAAC,MAAM,MAAM,CAAC,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,eAAe,EAAE,EAAE,CAAC,CAAC,CAAC;QACrF,CAAC;QACD,KAAK,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,EAAE,EAAE,eAAe,EAAE,EAAE,EAAE;YACvD,OAAO,EAAE,CAAC;YACV,MAAM,MAAM,CAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,CAAC,CAAC;QAC1E,CAAC;QACD,KAAK,CAAC,KAAK;YACT,MAAM,OAAO,GAAG,IAAI,CAAC;YACrB,IAAI,GAAG,SAAS,CAAC;YACjB,MAAM,OAAO,EAAE,GAAG,EAAE,CAAC;QACvB,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanoma-ai/connector-supabase",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.9",
|
|
4
4
|
"description": "Supabase projects for Sanoma, through the OpenTofu provider and the Management API",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"connector",
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
"testdata/replies",
|
|
26
26
|
"logo.svg",
|
|
27
27
|
"README.md",
|
|
28
|
-
"LICENSE"
|
|
28
|
+
"LICENSE",
|
|
29
|
+
"sql"
|
|
29
30
|
],
|
|
30
31
|
"type": "module",
|
|
31
32
|
"sideEffects": false,
|
|
@@ -47,20 +48,28 @@
|
|
|
47
48
|
"./fake": {
|
|
48
49
|
"types": "./dist/fake.d.ts",
|
|
49
50
|
"default": "./dist/fake.js"
|
|
51
|
+
},
|
|
52
|
+
"./vault": {
|
|
53
|
+
"types": "./dist/vault.d.ts",
|
|
54
|
+
"default": "./dist/vault.js"
|
|
50
55
|
}
|
|
51
56
|
},
|
|
52
57
|
"publishConfig": {
|
|
53
58
|
"access": "public"
|
|
54
59
|
},
|
|
60
|
+
"dependencies": {
|
|
61
|
+
"pg": "^8.23.1"
|
|
62
|
+
},
|
|
55
63
|
"devDependencies": {
|
|
56
|
-
"@sanoma-ai/bridge": "0.
|
|
57
|
-
"@sanoma-ai/workflows": "0.
|
|
58
|
-
"
|
|
64
|
+
"@sanoma-ai/bridge": "0.5.0",
|
|
65
|
+
"@sanoma-ai/workflows": "0.10.1",
|
|
66
|
+
"@types/pg": "^8.23.1",
|
|
67
|
+
"msw": "^3.0.3",
|
|
59
68
|
"zod": "^4.6.5"
|
|
60
69
|
},
|
|
61
70
|
"peerDependencies": {
|
|
62
|
-
"@sanoma-ai/bridge": "^0.
|
|
63
|
-
"@sanoma-ai/workflows": "^0.
|
|
71
|
+
"@sanoma-ai/bridge": "^0.5.0",
|
|
72
|
+
"@sanoma-ai/workflows": "^0.10.1",
|
|
64
73
|
"zod": "^4"
|
|
65
74
|
},
|
|
66
75
|
"engines": {
|
package/sql/vault.sql
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
-- Install once as the project administrator. Never expose this schema through the Data API.
|
|
2
|
+
-- Runtime logins receive only schema USAGE and gateway EXECUTE, never table privileges.
|
|
3
|
+
BEGIN;
|
|
4
|
+
CREATE SCHEMA sanoma_vault;
|
|
5
|
+
REVOKE ALL ON SCHEMA sanoma_vault FROM PUBLIC;
|
|
6
|
+
CREATE TABLE sanoma_vault.namespaces (
|
|
7
|
+
login name NOT NULL,
|
|
8
|
+
namespace text NOT NULL,
|
|
9
|
+
prefix uuid NOT NULL DEFAULT gen_random_uuid() UNIQUE,
|
|
10
|
+
writable boolean NOT NULL DEFAULT false,
|
|
11
|
+
PRIMARY KEY (login, namespace)
|
|
12
|
+
);
|
|
13
|
+
-- Existing customer secrets are always read-only through this gateway.
|
|
14
|
+
CREATE TABLE sanoma_vault.external_secrets (
|
|
15
|
+
login name NOT NULL,
|
|
16
|
+
namespace text NOT NULL,
|
|
17
|
+
path text NOT NULL,
|
|
18
|
+
secret_id uuid NOT NULL,
|
|
19
|
+
PRIMARY KEY (login, namespace, path),
|
|
20
|
+
FOREIGN KEY (login, namespace) REFERENCES sanoma_vault.namespaces ON DELETE CASCADE
|
|
21
|
+
);
|
|
22
|
+
CREATE TABLE sanoma_vault.revisions (
|
|
23
|
+
secret_id uuid PRIMARY KEY,
|
|
24
|
+
revision uuid NOT NULL DEFAULT gen_random_uuid(),
|
|
25
|
+
updated_by text NOT NULL,
|
|
26
|
+
row_state text NOT NULL
|
|
27
|
+
);
|
|
28
|
+
REVOKE ALL ON ALL TABLES IN SCHEMA sanoma_vault FROM PUBLIC;
|
|
29
|
+
|
|
30
|
+
CREATE FUNCTION sanoma_vault.access(
|
|
31
|
+
operation text, ns text, path text DEFAULT NULL, value text DEFAULT NULL,
|
|
32
|
+
expected text DEFAULT NULL, actor text DEFAULT NULL
|
|
33
|
+
) RETURNS jsonb
|
|
34
|
+
LANGUAGE plpgsql SECURITY DEFINER SET search_path = '' SET timezone = 'UTC' AS $$
|
|
35
|
+
DECLARE
|
|
36
|
+
scope sanoma_vault.namespaces%ROWTYPE;
|
|
37
|
+
external_id uuid;
|
|
38
|
+
target_name text;
|
|
39
|
+
item vault.secrets%ROWTYPE;
|
|
40
|
+
revision uuid;
|
|
41
|
+
author text;
|
|
42
|
+
current_row_state text;
|
|
43
|
+
version text;
|
|
44
|
+
plaintext text;
|
|
45
|
+
BEGIN
|
|
46
|
+
-- Authentication is the actual login, never a caller-controlled tenant parameter or SET ROLE.
|
|
47
|
+
SELECT * INTO scope FROM sanoma_vault.namespaces
|
|
48
|
+
WHERE login = session_user AND namespace = ns;
|
|
49
|
+
IF NOT FOUND THEN RAISE EXCEPTION 'denied' USING ERRCODE = '42501'; END IF;
|
|
50
|
+
-- A project/admin/service role can bypass this boundary; reject it as a runtime identity.
|
|
51
|
+
IF pg_catalog.has_schema_privilege(session_user, 'vault', 'USAGE') THEN
|
|
52
|
+
RAISE EXCEPTION 'unsafe runtime role' USING ERRCODE = '42501';
|
|
53
|
+
END IF;
|
|
54
|
+
IF operation = 'validate' THEN RETURN jsonb_build_object('protocol', 1, 'writable', scope.writable); END IF;
|
|
55
|
+
IF operation NOT IN ('read', 'write', 'delete') OR path IS NULL OR length(path) = 0 OR length(path) > 1024 THEN
|
|
56
|
+
RAISE EXCEPTION 'invalid configuration' USING ERRCODE = '22023';
|
|
57
|
+
END IF;
|
|
58
|
+
SELECT secret_id INTO external_id FROM sanoma_vault.external_secrets
|
|
59
|
+
WHERE login = session_user AND namespace = ns AND external_secrets.path = access.path;
|
|
60
|
+
IF operation <> 'read' AND (external_id IS NOT NULL OR NOT scope.writable) THEN
|
|
61
|
+
RAISE EXCEPTION 'read only' USING ERRCODE = 'SV001';
|
|
62
|
+
END IF;
|
|
63
|
+
target_name := 'sanoma/' || scope.prefix::text || '/' || path;
|
|
64
|
+
-- Supabase's project administrator can DELETE but cannot UPDATE vault.secrets,
|
|
65
|
+
-- so SELECT FOR UPDATE is unavailable. Table locks use the existing DELETE
|
|
66
|
+
-- grant and also coordinate ordinary Vault writers outside this gateway.
|
|
67
|
+
-- Readers share a stable snapshot across the metadata and plaintext queries;
|
|
68
|
+
-- writers serialize absent-row creation and compare-and-set replacement.
|
|
69
|
+
IF operation = 'read' THEN
|
|
70
|
+
LOCK TABLE vault.secrets IN SHARE MODE;
|
|
71
|
+
ELSE
|
|
72
|
+
LOCK TABLE vault.secrets IN SHARE ROW EXCLUSIVE MODE;
|
|
73
|
+
END IF;
|
|
74
|
+
IF external_id IS NOT NULL THEN
|
|
75
|
+
SELECT * INTO item FROM vault.secrets WHERE id = external_id;
|
|
76
|
+
ELSE
|
|
77
|
+
SELECT * INTO item FROM vault.secrets WHERE name = target_name;
|
|
78
|
+
END IF;
|
|
79
|
+
IF item.id IS NOT NULL THEN
|
|
80
|
+
current_row_state := encode(sha256(convert_to(item.secret || item.nonce::text || item.updated_at::text, 'UTF8')), 'hex');
|
|
81
|
+
SELECT r.revision, CASE WHEN r.row_state = current_row_state THEN r.updated_by END INTO revision, author
|
|
82
|
+
FROM sanoma_vault.revisions r WHERE r.secret_id = item.id;
|
|
83
|
+
-- Hash encrypted bytes, never a plaintext password. Include the row identity and gateway revision.
|
|
84
|
+
version := encode(sha256(convert_to(item.id::text || item.secret || item.nonce::text ||
|
|
85
|
+
item.updated_at::text || coalesce(revision::text, ''), 'UTF8')), 'hex');
|
|
86
|
+
END IF;
|
|
87
|
+
IF operation = 'read' THEN
|
|
88
|
+
IF item.id IS NULL THEN RETURN NULL; END IF;
|
|
89
|
+
ELSE
|
|
90
|
+
IF version IS DISTINCT FROM expected OR (operation = 'delete' AND item.id IS NULL) THEN
|
|
91
|
+
RAISE EXCEPTION 'conflict' USING ERRCODE = 'SV002';
|
|
92
|
+
END IF;
|
|
93
|
+
IF operation = 'delete' THEN
|
|
94
|
+
DELETE FROM vault.secrets WHERE id = item.id;
|
|
95
|
+
DELETE FROM sanoma_vault.revisions WHERE secret_id = item.id;
|
|
96
|
+
RETURN NULL;
|
|
97
|
+
END IF;
|
|
98
|
+
IF value IS NULL OR actor IS NULL OR length(actor) > 1024 THEN
|
|
99
|
+
RAISE EXCEPTION 'invalid value' USING ERRCODE = '22023';
|
|
100
|
+
END IF;
|
|
101
|
+
IF octet_length(value) > 65536 THEN RAISE EXCEPTION 'too large' USING ERRCODE = 'SV003'; END IF;
|
|
102
|
+
IF item.id IS NULL THEN
|
|
103
|
+
item.id := vault.create_secret(value, target_name, 'Managed by Sanoma');
|
|
104
|
+
ELSE
|
|
105
|
+
PERFORM vault.update_secret(item.id, value);
|
|
106
|
+
END IF;
|
|
107
|
+
SELECT * INTO item FROM vault.secrets WHERE id = item.id;
|
|
108
|
+
current_row_state := encode(sha256(convert_to(item.secret || item.nonce::text || item.updated_at::text, 'UTF8')), 'hex');
|
|
109
|
+
INSERT INTO sanoma_vault.revisions AS r (secret_id, updated_by, row_state) VALUES (item.id, actor, current_row_state)
|
|
110
|
+
ON CONFLICT (secret_id) DO UPDATE SET revision = gen_random_uuid(), updated_by = excluded.updated_by, row_state = excluded.row_state
|
|
111
|
+
RETURNING r.revision, r.updated_by INTO revision, author;
|
|
112
|
+
SELECT * INTO item FROM vault.secrets WHERE id = item.id;
|
|
113
|
+
version := encode(sha256(convert_to(item.id::text || item.secret || item.nonce::text ||
|
|
114
|
+
item.updated_at::text || revision::text, 'UTF8')), 'hex');
|
|
115
|
+
END IF;
|
|
116
|
+
SELECT decrypted_secret INTO plaintext FROM vault.decrypted_secrets WHERE id = item.id;
|
|
117
|
+
RETURN jsonb_build_object('value', plaintext, 'version', version, 'updatedAt', item.updated_at, 'updatedBy', author);
|
|
118
|
+
EXCEPTION WHEN unique_violation THEN
|
|
119
|
+
RAISE EXCEPTION 'conflict' USING ERRCODE = 'SV002';
|
|
120
|
+
END;
|
|
121
|
+
$$;
|
|
122
|
+
REVOKE ALL ON FUNCTION sanoma_vault.access(text, text, text, text, text, text) FROM PUBLIC;
|
|
123
|
+
-- Supabase may install default grants to API roles on new objects. Remove those too.
|
|
124
|
+
DO $revoke$
|
|
125
|
+
DECLARE api_role text;
|
|
126
|
+
BEGIN
|
|
127
|
+
FOREACH api_role IN ARRAY ARRAY['anon', 'authenticated', 'service_role'] LOOP
|
|
128
|
+
IF EXISTS (SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = api_role) THEN
|
|
129
|
+
EXECUTE format('REVOKE ALL ON SCHEMA sanoma_vault FROM %I', api_role);
|
|
130
|
+
EXECUTE format('REVOKE ALL ON ALL TABLES IN SCHEMA sanoma_vault FROM %I', api_role);
|
|
131
|
+
EXECUTE format('REVOKE ALL ON ALL FUNCTIONS IN SCHEMA sanoma_vault FROM %I', api_role);
|
|
132
|
+
END IF;
|
|
133
|
+
END LOOP;
|
|
134
|
+
END;
|
|
135
|
+
$revoke$;
|
|
136
|
+
COMMIT;
|