-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathplugin.ts
More file actions
696 lines (619 loc) · 24.2 KB
/
Copy pathplugin.ts
File metadata and controls
696 lines (619 loc) · 24.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
/**
* Bucket Provisioner Plugin for PostGraphile v5
*
* Adds S3 bucket provisioning support to PostGraphile v5:
*
* 1. `provisionBucket` mutation — explicitly provision an S3 bucket for a
* logical bucket row in the database. Reads the bucket config via RLS,
* then calls BucketProvisioner to create and configure the S3 bucket.
*
* 2. Auto-provisioning hook — wraps `create*` mutations on tables tagged
* with `@storageBuckets` to automatically provision the S3 bucket after
* the database row is created.
*
* 3. CORS update hook — wraps `update*` mutations on `@storageBuckets` tables
* to detect changes to `allowed_origins` and re-apply CORS rules to the
* S3 bucket.
*
* CORS resolution hierarchy (most specific wins):
* 1. Bucket-level `allowed_origins` column (per-bucket override)
* 2. Storage-module-level `allowed_origins` column (per-database default)
* 3. Plugin config `allowedOrigins` (global fallback)
* Supports `['*']` for open/CDN mode (wildcard CORS).
*
* Both pathways use `@constructive-io/bucket-provisioner` for the actual
* S3 operations (bucket creation, Block Public Access, CORS, policies,
* versioning, lifecycle rules).
*
* Detection: Uses the `@storageBuckets` smart tag on the codec (table).
* The storage module generator in constructive-db sets this tag on the
* generated buckets table via a smart comment:
* COMMENT ON TABLE buckets IS E'@storageBuckets\nStorage buckets table';
*/
import { context as grafastContext, lambda, object } from 'grafast';
import type { GraphileConfig } from 'graphile-config';
import { extendSchema, gql } from 'graphile-utils';
import { Logger } from '@pgpmjs/logger';
import { QuoteUtils } from '@pgsql/quotes';
import {
BucketProvisioner,
} from '@constructive-io/bucket-provisioner';
import type { StorageConnectionConfig, ProvisionResult } from '@constructive-io/bucket-provisioner';
import type {
BucketProvisionerPluginOptions,
BucketNameResolver,
} from './types';
const log = new Logger('graphile-bucket-provisioner:plugin');
// --- Storage module queries ---
/**
* Resolve the app-level storage module (scope = 'app').
*/
const APP_STORAGE_MODULE_QUERY = `
SELECT
id,
scope,
entity_table_id,
buckets_schema,
buckets_table,
endpoint,
public_url_prefix,
provider,
allowed_origins
FROM metaschema_modules_public.resolve_storage_modules($1)
WHERE scope = 'app'
LIMIT 1
`;
/**
* Resolve ALL storage modules for a database (for ownerId-based resolution).
*/
const ALL_STORAGE_MODULES_QUERY = `
SELECT
id,
scope,
entity_table_id,
buckets_schema,
buckets_table,
endpoint,
public_url_prefix,
provider,
allowed_origins,
entity_schema,
entity_table
FROM metaschema_modules_public.resolve_storage_modules($1)
`;
interface StorageModuleRow {
id: string;
scope: string;
entity_table_id: string | null;
buckets_schema: string;
buckets_table: string;
endpoint: string | null;
public_url_prefix: string | null;
provider: string | null;
allowed_origins: string[] | null;
entity_schema?: string | null;
entity_table?: string | null;
}
/**
* Resolve the storage module for a given scope.
* If ownerId is provided, probes entity tables to find the matching module.
* Otherwise, returns the app-level module.
*/
async function resolveStorageModule(
pgClient: any,
databaseId: string,
ownerId?: string,
): Promise<StorageModuleRow | null> {
if (!ownerId) {
// App-level resolution
const result = await pgClient.query(APP_STORAGE_MODULE_QUERY, [databaseId]);
return (result.rows[0] as StorageModuleRow) ?? null;
}
// Entity-scoped: load all modules and probe entity tables
const result = await pgClient.query(ALL_STORAGE_MODULES_QUERY, [databaseId]);
const modules = result.rows as StorageModuleRow[];
const entityModules = modules.filter((m) => m.entity_schema && m.entity_table);
for (const mod of entityModules) {
const entityTable = QuoteUtils.quoteQualifiedIdentifier(mod.entity_schema!, mod.entity_table!);
const probe = await pgClient.query(
`SELECT 1 FROM ${entityTable} WHERE id = $1 LIMIT 1`,
[ownerId],
);
if (probe.rows.length > 0) {
return mod;
}
}
return null;
}
interface BucketRow {
id: string;
key: string;
type: string;
is_public: boolean;
allowed_origins: string[] | null;
}
// --- Helpers ---
/**
* Resolve the connection config from the options. If the option is a lazy
* getter function, call it (and cache the result).
*/
function resolveConnection(
options: BucketProvisionerPluginOptions,
): StorageConnectionConfig {
if (typeof options.connection === 'function') {
const resolved = options.connection();
// Cache so subsequent calls don't re-evaluate
options.connection = resolved;
return resolved;
}
return options.connection;
}
/**
* Resolve the S3 bucket name from a logical bucket key.
*/
function resolveBucketName(
bucketKey: string,
databaseId: string,
options: BucketProvisionerPluginOptions,
): string {
if (options.resolveBucketName) {
return options.resolveBucketName(bucketKey, databaseId);
}
if (options.bucketNamePrefix) {
return `${options.bucketNamePrefix}-${bucketKey}`;
}
return bucketKey;
}
/**
* Resolve the database_id from the JWT context.
*/
async function resolveDatabaseId(pgClient: any): Promise<string | null> {
const result = await pgClient.query(
`SELECT jwt_private.current_database_id() AS id`,
);
return result.rows[0]?.id ?? null;
}
/**
* Resolve the effective CORS allowed origins using the 3-tier hierarchy:
* 1. Bucket-level allowed_origins (per-bucket override)
* 2. Storage-module-level allowed_origins (per-database default)
* 3. Plugin config allowedOrigins (global fallback)
*/
function resolveAllowedOrigins(
bucketOrigins: string[] | null | undefined,
storageModuleOrigins: string[] | null | undefined,
pluginOrigins: string[],
): string[] {
if (bucketOrigins && bucketOrigins.length > 0) {
return bucketOrigins;
}
if (storageModuleOrigins && storageModuleOrigins.length > 0) {
return storageModuleOrigins;
}
return pluginOrigins;
}
/**
* Build a BucketProvisioner with per-database connection overrides.
*/
function buildProvisioner(
options: BucketProvisionerPluginOptions,
storageModule: StorageModuleRow | null,
effectiveOrigins: string[],
): BucketProvisioner {
const connection = resolveConnection(options);
const effectiveConnection: StorageConnectionConfig = {
...connection,
...(storageModule?.endpoint ? { endpoint: storageModule.endpoint } : {}),
...(storageModule?.provider
? { provider: storageModule.provider as StorageConnectionConfig['provider'] }
: {}),
};
return new BucketProvisioner({
connection: effectiveConnection,
allowedOrigins: effectiveOrigins,
});
}
/**
* Core provisioning logic shared by both the explicit mutation and the
* auto-provisioning hook.
*/
async function provisionBucketForRow(
pgClient: any,
databaseId: string,
bucketKey: string,
bucketType: string,
bucketAllowedOrigins: string[] | null | undefined,
options: BucketProvisionerPluginOptions,
): Promise<ProvisionResult> {
const s3BucketName = resolveBucketName(bucketKey, databaseId, options);
const accessType = bucketType as 'public' | 'private' | 'temp';
// Read storage module config to check for endpoint/provider/CORS overrides
const storageModule = await resolveStorageModule(pgClient, databaseId);
// Resolve CORS origins using the 3-tier hierarchy
const effectiveOrigins = resolveAllowedOrigins(
bucketAllowedOrigins,
storageModule?.allowed_origins,
options.allowedOrigins,
);
const provisioner = buildProvisioner(options, storageModule, effectiveOrigins);
log.info(
`Provisioning S3 bucket "${s3BucketName}" (key="${bucketKey}", type="${accessType}", ` +
`origins=${JSON.stringify(effectiveOrigins)}) for database ${databaseId}`,
);
const result = await provisioner.provision({
bucketName: s3BucketName,
accessType,
versioning: options.versioning ?? false,
publicUrlPrefix: storageModule?.public_url_prefix ?? undefined,
allowedOrigins: effectiveOrigins,
});
log.info(
`Successfully provisioned S3 bucket "${s3BucketName}" ` +
`(provider=${result.provider}, blockPublicAccess=${result.blockPublicAccess})`,
);
return result;
}
/**
* Update CORS on an existing S3 bucket when allowed_origins changes.
*/
async function updateBucketCors(
pgClient: any,
databaseId: string,
bucketKey: string,
bucketType: string,
bucketAllowedOrigins: string[] | null | undefined,
options: BucketProvisionerPluginOptions,
): Promise<void> {
const s3BucketName = resolveBucketName(bucketKey, databaseId, options);
const accessType = bucketType as 'public' | 'private' | 'temp';
const storageModule = await resolveStorageModule(pgClient, databaseId);
const effectiveOrigins = resolveAllowedOrigins(
bucketAllowedOrigins,
storageModule?.allowed_origins,
options.allowedOrigins,
);
const provisioner = buildProvisioner(options, storageModule, effectiveOrigins);
log.info(
`Updating CORS on S3 bucket "${s3BucketName}" ` +
`(origins=${JSON.stringify(effectiveOrigins)}) for database ${databaseId}`,
);
await provisioner.updateCors({
bucketName: s3BucketName,
accessType,
allowedOrigins: effectiveOrigins,
});
log.info(`Successfully updated CORS on S3 bucket "${s3BucketName}"`);
}
// --- Plugin factory ---
/**
* Creates the bucket provisioner plugin.
*
* This plugin provides two provisioning pathways:
*
* 1. **Explicit `provisionBucket` mutation** — Call this mutation with a
* bucket key to provision (or re-provision) the S3 bucket. Protected
* by RLS on the buckets table.
*
* 2. **Auto-provisioning hook** — When `autoProvision` is true (default),
* wraps `create*` mutation resolvers on tables tagged with `@storageBuckets`
* to automatically provision the S3 bucket after the row is created.
*
* @param options - Plugin configuration (S3 credentials, CORS origins, naming)
*/
export function createBucketProvisionerPlugin(
options: BucketProvisionerPluginOptions,
): GraphileConfig.Plugin {
const autoProvision = options.autoProvision ?? true;
// The extendSchema plugin adds the explicit provisionBucket mutation
const mutationPlugin = extendSchema(() => ({
typeDefs: gql`
input ProvisionBucketInput {
"""The logical bucket key (e.g., "public", "private")"""
bucketKey: String!
"""
Owner entity ID for entity-scoped bucket provisioning.
Omit for app-level (database-wide) storage.
"""
ownerId: UUID
"""
Access type used only when the bucket row does not yet exist:
"public", "private", or "temp". Defaults to "private"
(or "public" when isPublic is true).
"""
type: String
"""
Whether the bucket is publicly readable, used only when creating
the row. Defaults to false unless type is "public".
"""
isPublic: Boolean
}
type ProvisionBucketPayload {
"""Whether provisioning succeeded"""
success: Boolean!
"""The S3 bucket name that was provisioned"""
bucketName: String!
"""The access type applied"""
accessType: String!
"""The storage provider used"""
provider: String!
"""The S3 endpoint (null for AWS S3 default)"""
endpoint: String
"""Error message if provisioning failed"""
error: String
}
extend type Mutation {
"""
Provision an S3 bucket for a logical bucket in the database.
Reads the bucket config via RLS, then creates and configures
the S3 bucket with the appropriate privacy policies, CORS rules,
and lifecycle settings.
"""
provisionBucket(
input: ProvisionBucketInput!
): ProvisionBucketPayload
}
`,
plans: {
Mutation: {
provisionBucket(_$mutation: any, fieldArgs: any) {
const $input = fieldArgs.getRaw('input');
const $withPgClient = (grafastContext() as any).get('withPgClient');
const $pgSettings = (grafastContext() as any).get('pgSettings');
const $combined = object({
input: $input,
withPgClient: $withPgClient,
pgSettings: $pgSettings,
});
return lambda($combined, async ({ input, withPgClient, pgSettings }: any) => {
const { bucketKey, ownerId, type: requestedType, isPublic: requestedIsPublic } = input;
if (!bucketKey || typeof bucketKey !== 'string') {
throw new Error('INVALID_BUCKET_KEY');
}
return withPgClient(pgSettings, async (pgClient: any) => {
// Resolve database ID from JWT context
const databaseId = await resolveDatabaseId(pgClient);
if (!databaseId) {
throw new Error('DATABASE_NOT_FOUND');
}
// Resolve storage module (app-level or entity-scoped via ownerId)
const storageModule = await resolveStorageModule(pgClient, databaseId, ownerId);
if (!storageModule) {
throw new Error(
ownerId
? 'STORAGE_MODULE_NOT_FOUND_FOR_OWNER: no storage module found for the given ownerId'
: 'STORAGE_MODULE_NOT_PROVISIONED',
);
}
// Look up the bucket row (RLS enforced via pgSettings)
const hasOwner = ownerId && storageModule.scope !== 'app';
const bucketsTable = QuoteUtils.quoteQualifiedIdentifier(storageModule.buckets_schema, storageModule.buckets_table);
// Ensure the bucket row exists (privileged create-on-demand for the
// post-provision Storage panel / re-provision flow). Runs under the
// same role/connection as the lookup below; ON CONFLICT keeps it
// idempotent so an existing bucket is left untouched. database_id and
// actor_id are populated by the buckets table's own triggers.
const ensureType = requestedType || (requestedIsPublic ? 'public' : 'private');
const ensureIsPublic =
typeof requestedIsPublic === 'boolean' ? requestedIsPublic : ensureType === 'public';
await pgClient.query(
hasOwner
? `INSERT INTO ${bucketsTable} (key, type, is_public, owner_id)
VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING`
: `INSERT INTO ${bucketsTable} (key, type, is_public)
VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`,
hasOwner
? [bucketKey, ensureType, ensureIsPublic, ownerId]
: [bucketKey, ensureType, ensureIsPublic],
);
const bucketResult = await pgClient.query(
hasOwner
? `SELECT id, key, type, is_public, allowed_origins
FROM ${bucketsTable}
WHERE key = $1 AND owner_id = $2
LIMIT 1`
: `SELECT id, key, type, is_public, allowed_origins
FROM ${bucketsTable}
WHERE key = $1
LIMIT 1`,
hasOwner ? [bucketKey, ownerId] : [bucketKey],
);
if (bucketResult.rows.length === 0) {
throw new Error('BUCKET_NOT_FOUND');
}
const bucket = bucketResult.rows[0] as BucketRow;
try {
const result = await provisionBucketForRow(
pgClient,
databaseId,
bucket.key,
bucket.type,
bucket.allowed_origins,
options,
);
return {
success: true,
bucketName: result.bucketName,
accessType: result.accessType,
provider: result.provider,
endpoint: result.endpoint,
error: null,
};
} catch (err: any) {
log.error(`Failed to provision bucket "${bucketKey}": ${err.message}`);
return {
success: false,
bucketName: resolveBucketName(bucket.key, databaseId, options),
accessType: bucket.type,
provider: resolveConnection(options).provider,
endpoint: resolveConnection(options).endpoint ?? null,
error: err.message,
};
}
});
});
},
},
},
}));
// If autoProvision is disabled, return only the mutation plugin
if (!autoProvision) {
return mutationPlugin;
}
// Build a composite plugin that includes both the mutation and the hook
return {
...mutationPlugin,
name: 'BucketProvisionerPlugin',
version: '0.1.0',
description:
'Auto-provisions S3 buckets when bucket rows are created, ' +
'updates CORS when allowed_origins changes on update, ' +
'and provides a provisionBucket mutation for explicit provisioning',
after: ['PgAttributesPlugin', 'PgMutationCreatePlugin', 'PgMutationUpdateDeletePlugin'],
schema: {
...mutationPlugin.schema,
hooks: {
...((mutationPlugin.schema as any)?.hooks ?? {}),
/**
* Wrap create and update mutation resolvers on tables tagged with @storageBuckets.
*
* - create*: After the row is created, provision the S3 bucket.
* - update*: After the row is updated, re-apply CORS if allowed_origins changed.
*
* If provisioning/CORS update fails, the DB row still exists (the mutation
* already committed), and the error is logged. Admin can retry via provisionBucket.
*/
GraphQLObjectType_fields_field(field: any, build: any, context: any) {
const {
scope: { isRootMutation, fieldName, pgCodec },
} = context;
// Only wrap root mutation fields
if (!isRootMutation || !pgCodec || !pgCodec.attributes) {
return field;
}
// Check for @storageBuckets smart tag
const tags = pgCodec.extensions?.tags;
if (!tags?.storageBuckets) {
return field;
}
const isCreate = fieldName.startsWith('create');
const isUpdate = fieldName.startsWith('update');
// Only wrap create and update mutations (not delete)
if (!isCreate && !isUpdate) {
return field;
}
log.debug(`Wrapping mutation "${fieldName}" for ${isCreate ? 'auto-provisioning' : 'CORS update'} (codec: ${pgCodec.name})`);
const defaultResolver = (obj: any) => obj[fieldName];
const { resolve: oldResolve = defaultResolver, ...rest } = field;
return {
...rest,
async resolve(source: any, args: any, graphqlContext: any, info: any) {
// Call the original resolver first (creates/updates the DB row)
const result = await oldResolve(source, args, graphqlContext, info);
try {
const inputKey = Object.keys(args.input || {}).find(
(k) => k !== 'clientMutationId',
);
const bucketInput = inputKey ? args.input[inputKey] : null;
const withPgClient = graphqlContext.withPgClient;
const pgSettings = graphqlContext.pgSettings;
if (!withPgClient) {
log.warn(`${isCreate ? 'Auto-provision' : 'CORS update'} skipped: withPgClient not available in context`);
return result;
}
if (isCreate) {
// --- CREATE: full provisioning ---
if (!bucketInput?.key || !bucketInput?.type) {
log.warn(
`Auto-provision skipped for "${fieldName}": ` +
`could not extract key/type from mutation input`,
);
return result;
}
await withPgClient(pgSettings, async (pgClient: any) => {
const databaseId = await resolveDatabaseId(pgClient);
if (!databaseId) {
log.warn('Auto-provision skipped: could not resolve database_id');
return;
}
await provisionBucketForRow(
pgClient,
databaseId,
bucketInput.key,
bucketInput.type,
bucketInput.allowedOrigins ?? bucketInput.allowed_origins ?? null,
options,
);
});
} else {
// --- UPDATE: re-apply CORS if allowed_origins is in the patch ---
const hasOriginsUpdate = bucketInput &&
('allowedOrigins' in bucketInput || 'allowed_origins' in bucketInput);
if (!hasOriginsUpdate) {
// allowed_origins not being changed, nothing to do
return result;
}
await withPgClient(pgSettings, async (pgClient: any) => {
const databaseId = await resolveDatabaseId(pgClient);
if (!databaseId) {
log.warn('CORS update skipped: could not resolve database_id');
return;
}
// Read the storage module config (app-level; auto-hook doesn't have ownerId context)
const storageModule = await resolveStorageModule(pgClient, databaseId);
if (!storageModule) {
log.warn('CORS update skipped: storage module not provisioned');
return;
}
// We need the bucket key — it may come from input or patch
// For updates, PostGraphile uses nodeId or the row's PK, so
// we read the bucket from the patch's key or from the nodeId
const patchKey = bucketInput?.key;
if (!patchKey) {
log.warn(
`CORS update skipped for "${fieldName}": ` +
`could not determine bucket key from mutation input`,
);
return;
}
// Read the full bucket row (post-update) to get type + origins
const bucketsTable = QuoteUtils.quoteQualifiedIdentifier(storageModule.buckets_schema, storageModule.buckets_table);
const bucketResult = await pgClient.query(
`SELECT id, key, type, is_public, allowed_origins
FROM ${bucketsTable}
WHERE key = $1
LIMIT 1`,
[patchKey],
);
if (bucketResult.rows.length === 0) {
log.warn(`CORS update skipped: bucket "${patchKey}" not found`);
return;
}
const bucket = bucketResult.rows[0] as BucketRow;
await updateBucketCors(
pgClient,
databaseId,
bucket.key,
bucket.type,
bucket.allowed_origins,
options,
);
});
}
} catch (err: any) {
log.error(
`${isCreate ? 'Auto-provision' : 'CORS update'} failed for "${fieldName}": ${err.message}. ` +
(isCreate
? `The bucket row was created but the S3 bucket was not provisioned. Use the provisionBucket mutation to retry.`
: `The bucket row was updated but CORS was not applied to the S3 bucket. Use the provisionBucket mutation to retry.`),
);
}
return result;
},
};
},
},
},
};
}
export const BucketProvisionerPlugin = createBucketProvisionerPlugin;
export default BucketProvisionerPlugin;