Repository navigation
Expand file tree
/
Copy pathdatasource-admin-service.ts
More file actions
1537 lines (1454 loc) · 75.3 KB
/
Copy pathdatasource-admin-service.ts
File metadata and controls
1537 lines (1454 loc) · 75.3 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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* DatasourceAdminService — implements {@link IDatasourceAdminService}
* (ADR-0015 Addendum) on top of injected persistence + secret + driver probe
* callbacks.
*
* Like its federation sibling `ExternalDatasourceService`, this service is
* intentionally decoupled from the kernel: every side effect (connection probe,
* metadata read/write, secret write, bound-object count, hot pool (de)register)
* is injected via {@link DatasourceAdminServiceConfig}, so the lifecycle rules
* (origin gating, secret indirection, removal safety) are pure and unit-testable.
*
* Invariants enforced here, independent of the wiring:
* - Code-defined datasources (`origin: 'code'`) are read-only — update/remove
* reject them, and create refuses a name a code datasource already owns.
* - A runtime datasource never shadows a code one (code wins on collision).
* - Credentials never persist in cleartext: the cleartext {@link SecretInput}
* transits create/update/test only; create/update write it to the secret
* store and persist only the returned `credentialsRef`.
* - The read path never SERVES a credential, whatever a stored row holds
* (#8081): `getDatasource` redacts driver `config` through
* `datasource-config-redaction.ts`. That invariant is about what leaves this
* service, and is separate from the one above — rows written before #8078
* can and do hold inline cleartext, which is why it is stated on its own
* rather than treated as a consequence.
* - A record reaches the store only once `DatasourceSchema` accepts it as it
* will be stored, the bound `credentialsRef` included (#21058) — the same
* contract the build and meta doors enforce, so this door cannot persist a
* row the meta read path then reports `valid: false`. A `label`/`active`-only
* edit is the one write not judged.
* - Removal is refused while objects are still bound to the datasource — and
* (#6504) equally refused when the bound-object count could not be taken
* over a COMPLETE object set, since an under-count and "nothing is bound"
* are the same zero.
*/
import { DatasourceSchema, externalBindingDatasourceRefusal, validateDriverConfig } from '@objectstack/spec/data';
import { MetadataProtectionFields } from '@objectstack/spec/kernel';
import type { IPubSub } from '@objectstack/spec/contracts';
import { assertDatasourcePoolSupported } from './datasource-pool-support.js';
import { datasourceConnectivityChanged } from './datasource-connectivity-change.js';
import { redactDatasourceConfig, restoreRedactedConfig } from './datasource-config-redaction.js';
import { planCredentialMigration } from './datasource-credential-migration.js';
import { borrowedConnectorOf } from './datasource-connector-credential.js';
import type {
IDatasourceAdminService,
DatasourceDraft,
SecretInput,
TestConnectionResult,
DatasourceSummary,
CredentialMigrationResult,
} from './contracts/index.js';
import type { Logger } from './logger.js';
/** Datasource name rule (mirrors `DatasourceSchema.name`). */
const NAME_RE = /^[a-z_][a-z0-9_]*$/;
/**
* Stand-in for the `credentialsRef` a supplied secret WILL be bound under,
* used only by the record judgement ({@link DatasourceAdminService.recordRefusal}).
*
* The real ref does not exist until `writeSecret` runs, and the judgement has
* to run before anything is written — a refused record must leave no secret
* behind. Any non-empty string is equivalent here: `DatasourceSchema`'s
* refinements read a binding through the connect path's own truthy test
* (`if (credentialsRef)`), never through the ref's content. It never reaches
* the store: the judged record is a copy.
*/
const PENDING_SECRET_REF = 'pending:secret-binding';
/**
* Stand-in `name` for the record the test door judges. A probe's subject is
* the connection, not the datasource's identity: the console's "Test
* connection" sends `{ driver, config, secret }` and no name at all, and
* the test door has never judged one. `DatasourceSchema` requires a name, so
* the judged copy carries this fixed, rule-conforming one.
*/
const PROBE_DRAFT_NAME = 'connection_test_draft';
/**
* The patch keys whose write leaves the record judgement out (#21058). Exactly
* the two the existing gates already exempt: renaming a datasource and taking
* it out of service (`active: false`) must stay possible on a row stored before
* a gate landed. Every other patched key, and any supplied secret, is a change
* to what the record binds, and the record is judged whole.
*/
const RECORD_JUDGE_EXEMPT_PATCH_KEYS: ReadonlySet<string> = new Set(['label', 'active']);
/**
* [#28633] The top-level keys `DatasourceSchema` declares that a write door
* deliberately does NOT take from the request body, each for its reason:
*
* - `origin` — provenance, "server-managed, read-only" and "never accepted
* from client input" (the schema's own words): the door stamps `runtime`.
* - the ADR-0010 protection envelope (`MetadataProtectionFields`: the `_lock*`
* family, `_provenance`, `_packageId`, `_packageVersion`) — set by a code
* package's loader, never by an author's write. The metadata save door
* refuses an authored lock for that reason (ADR-0010 §3.5); storing one here
* would be the way around it.
*
* Read off those declarations, so a protection field added later is left out
* here the day it lands.
*/
const SERVER_STAMPED_KEYS: ReadonlySet<string> = new Set(['origin', ...Object.keys(MetadataProtectionFields)]);
let storedKeysCache: readonly string[] | undefined;
/**
* [#28633] The top-level keys a create, an edit and a probe take from the
* body: every key `DatasourceSchema` declares, minus {@link SERVER_STAMPED_KEYS}.
*
* Derived from the schema's shape at run time, never listed by hand. The hand
* list that stood here (`name`, `label`, `driver`, `schemaMode`, `config`,
* `external`, `pool`, `active`) left out `ssl`, `autoConnect` and
* `description`: the doors accepted them (the schema declares them, so the
* undeclared-key refusal lets them through) and then dropped them, and a
* datasource saved with a TLS block connected without one. A key the schema
* declares later is stored the day it lands.
*/
function storedDatasourceKeys(): readonly string[] {
if (!storedKeysCache) {
const shape = (DatasourceSchema as unknown as { shape: Record<string, unknown> }).shape;
storedKeysCache = Object.freeze(Object.keys(shape).filter((key) => !SERVER_STAMPED_KEYS.has(key)));
}
return storedKeysCache;
}
/** `body`'s members under {@link storedDatasourceKeys} whose value is not `undefined`. */
function storedKeysOf(body: object): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const key of storedDatasourceKeys()) {
const value = (body as Record<string, unknown>)[key];
if (value !== undefined) out[key] = value;
}
return out;
}
/**
* [#28633] The one `ssl` member that is key material: the client private key.
* `ca` and `cert` are public certificates; `key` is the secret half of the
* client certificate (the schema: "Client private key").
*/
const SSL_PRIVATE_KEY = 'key';
/**
* [#28633] Why `body` cannot be taken as it is: its `ssl` block carries a
* client private key. `undefined` when it carries none.
*
* This door keeps credentials out of the stored record: a cleartext `secret`
* transits the request and only the `credentialsRef` the secret store mints is
* stored. `ssl.key` has no such channel, so storing it would put key material
* in the datasource row in cleartext. Refused by name, never by value, before
* anything is read, written or probed. The rest of the block (`enabled`,
* `rejectUnauthorized`, `ca`, `cert`) is stored.
*/
function inlineSslKeyRefusal(heading: string, body: object): string | undefined {
const ssl = (body as { ssl?: unknown }).ssl;
if (!ssl || typeof ssl !== 'object') return undefined;
if ((ssl as Record<string, unknown>)[SSL_PRIVATE_KEY] === undefined) return undefined;
return (
`${heading}\n`
+ '`ssl.key`: a TLS client private key is not accepted through this door. It would be stored in cleartext '
+ 'in the datasource record, and this door stores no credential there: only a `secret` it seals into the '
+ 'secret store, which takes no TLS key. Leave `ssl.key` out (`enabled`, `rejectUnauthorized`, `ca` and '
+ '`cert` are stored) and send the request again. Nothing was written or probed.'
);
}
/** {@link inlineSslKeyRefusal} for a write door: refuses by throwing (a `400` at the route). */
function assertNoInlineSslKey(heading: string, body: object): void {
const refusal = inlineSslKeyRefusal(heading, body);
if (refusal) throw new Error(refusal);
}
/** `ssl` as a read may serve it: the private key withheld, every other member as stored. */
function servableSsl(ssl: Record<string, unknown> | undefined): Record<string, unknown> | undefined {
if (!ssl || typeof ssl !== 'object') return ssl;
if (!(SSL_PRIVATE_KEY in ssl)) return ssl;
const { [SSL_PRIVATE_KEY]: _withheld, ...rest } = ssl;
return rest;
}
/** A copy of `record` carrying the binding a supplied secret is about to create. */
function withPendingSecretRef(record: StoredDatasource): StoredDatasource {
return { ...record, external: { ...(record.external ?? {}), credentialsRef: PENDING_SECRET_REF } };
}
/**
* [#13805] Cluster channel for datasource record writes — the DRIVER
* registry's adopter of the cluster-invalidation family `metadata.mutated`
* (#13331) established (ruled 2026-09-01: the same bridge shape, a symmetric
* create + delete signal, convergence by re-reading the shared datasource
* records, no second propagation mechanism).
*
* Published by the {@link DatasourceAdminService} that performed a create,
* update or delete (see {@link DatasourceAdminService.attachDatasourceMutationPubSub})
* and consumed by every peer replica, which CONVERGES its own live pool for
* that name from its OWN read of the shared datasource records — it never
* replays the write. Distinct from `metadata.mutated` on purpose: that channel
* repairs the ObjectQL OBJECT registry behind `/api/v1/meta/*`, while this one
* repairs the ObjectQL DRIVER registry behind `/api/v1/datasources/*` — the
* state `registerPool` / `unregisterPool` mutate on the serving replica only,
* so that before this channel a `DELETE` recovered `/api/v1/ready` on the one
* replica that served it and every other replica kept the stuck driver until
* restart.
*/
export const DATASOURCE_MUTATION_CLUSTER_CHANNEL = 'datasource.mutated';
/**
* [#13805] Payload for {@link DATASOURCE_MUTATION_CLUSTER_CHANNEL}.
*
* ⭐ A SIGNAL, never trusted content — the contract `ClusterMetadataMutationPayload`
* carries, adopted verbatim: only the record's ADDRESS rides the channel. The
* receiving replica re-reads the shared record for `name` and converges its
* pool from that read — builds what the read says should be live, rebuilds
* what changed, evicts what is gone — so the shared store stays the single
* source of truth, and a duplicate or re-ordered delivery converges to the
* same pool state as a single one. Symmetric by construction: create, update
* and delete all publish this one shape, and a receiver cannot tell which it
* was without reading, which is the point.
*/
export interface ClusterDatasourceMutationPayload {
/** Origin nodeId — used for loopback suppression. */
originNode?: string;
/** The datasource whose shared record was just written. */
name: string;
}
/**
* A persisted datasource record (subset of `Datasource`). `origin` distinguishes
* code-defined from runtime; `external.credentialsRef` is the opaque secret
* handle — never a cleartext credential.
*/
export interface StoredDatasource {
name: string;
label?: string;
driver: string;
schemaMode?: 'managed' | 'external' | 'validate-only';
config?: Record<string, unknown>;
external?: (Record<string, unknown> & { credentialsRef?: string }) | undefined;
pool?: Record<string, unknown>;
active?: boolean;
/** Force a live connection at boot even when managed + unrouted (ADR-0062 D2(c)). */
autoConnect?: boolean;
/** Datasource-level TLS block (`DatasourceSchema.ssl`), read by the driver factory. */
ssl?: Record<string, unknown>;
/** Internal description. */
description?: string;
origin?: 'code' | 'runtime';
/** Package that defines a code-origin datasource, when known. */
definedIn?: string;
}
/** What a connection probe needs (cleartext secret is transient, never stored). */
export interface ProbeInput {
driver: string;
config: Record<string, unknown>;
/** Cleartext secret used for this probe only (e.g. password / DSN). */
secret?: string;
external?: Record<string, unknown>;
/** [#28633] The draft's TLS block, exactly as a Save would store it. */
ssl?: Record<string, unknown>;
timeoutMs?: number;
}
/**
* Injected dependencies. The plugin supplies real implementations backed by the
* driver registry, `IMetadataService` (runtime store), and the secret store;
* tests supply fakes.
*/
export interface DatasourceAdminServiceConfig {
/** Probe a connection live (driver connect + cheap round-trip). */
probe: (input: ProbeInput) => Promise<TestConnectionResult>;
/** Read every datasource record (code + runtime). */
listDatasourceRecords: () => Promise<StoredDatasource[]>;
/** Read one datasource record by name. */
getDatasourceRecord: (name: string) => Promise<StoredDatasource | undefined>;
/** Persist a runtime datasource record into the runtime metadata store. */
putDatasourceRecord: (record: StoredDatasource) => Promise<void>;
/** Remove a runtime datasource record from the runtime metadata store. */
deleteDatasourceRecord: (name: string) => Promise<void>;
/** Encrypt + store a secret, returning an opaque `credentialsRef`. */
writeSecret: (input: SecretInput, hint: { name: string }) => Promise<string>;
/** Best-effort delete of a stored secret by ref (cleanup on remove/rewrap). */
removeSecret?: (credentialsRef: string) => Promise<void>;
/**
* Dereference a `credentialsRef` back to its cleartext — the secret store's
* READ side (`SecretBinder.resolve`).
*
* Optional, and its absence is load-bearing rather than cosmetic: the connect
* path is FAIL-CLOSED on a `credentialsRef` it cannot resolve (ADR-0062 D3),
* so a host that can write secrets but not read them back would have every
* ref-bearing datasource refuse to connect. {@link
* DatasourceAdminService.migrateCredential} therefore refuses to run at all
* without it — writing a ref it cannot verify is what would turn a working
* datasource into a broken one (#8155).
*/
readSecret?: (credentialsRef: string) => Promise<string | undefined>;
/** Count objects bound to a datasource (removal blocked while > 0). */
countBoundObjects: (datasource: string) => Promise<number>;
/**
* [#6504] The same count, plus whether the object set it was taken over could
* be read COMPLETELY.
*
* {@link countBoundObjects} is derived from the metadata service's object
* listing, and that listing is short — silently — while a loader is down
* (ADR-0110 D3). The number is therefore not merely an under-report: it is
* the input to a guard over a DESTRUCTIVE operation. `0` returned during an
* outage reads exactly like "nothing is bound", so
* {@link DatasourceAdminService.removeDatasource} deletes a datasource whose
* objects were simply unreadable, and unbinds its secret on the way out.
* This is the card's harm one step past description: a count nobody can
* check is being spent as a safety verdict.
*
* Optional for the reason `IMetadataService.listDiagnosed` itself is: a host
* whose metadata service predates the verdict cannot report the distinction,
* so its absence means "unchanged behaviour", never "complete". A host that
* supplies it gets a removal that refuses rather than guesses.
*/
countBoundObjectsDiagnosed?: (
datasource: string,
) => Promise<{ count: number; degraded: boolean; errors: string[] }>;
/**
* [ADR-0015 §4.2 · #25277] The objects that name `datasource` as theirs, each
* with its `external` binding as declared (absent when it has none) — the
* input to {@link DatasourceAdminService.boundExternalRefusal}, which judges a
* datasource this door is about to store as managed against the objects
* bound to it with `external`.
*
* Required, not optional like {@link countBoundObjectsDiagnosed}: that member
* refines a verdict the door already has, while this one IS the verdict's
* input. A host that could leave it out would store the pair the metadata
* save door refuses, which is the defect this seam exists to close.
*
* The plugin answers it from the engine's object registry, the registry the
* metadata save door writes through to, so an object saved or imported at
* runtime is counted the moment it is saved.
*/
listObjectsBoundTo: (datasource: string) => Promise<Array<{ name?: unknown; external?: unknown }>>;
/**
* [ADR-0015 D7] Why a datasource naming connector instance `connector` in
* `external.connector` cannot borrow its credential — the instance is not
* declared, is a catalog descriptor, lends no credential or is disabled, or
* no connector credential source is registered — or `undefined` when it
* can. The create / update / test-connection judgement for such a
* datasource: a runtime-created datasource never passes `defineStack`'s
* check, so this door asks the one the connect path asks.
*
* Optional only for hosts and fakes with no such datasource: absent, a
* draft that names a connector is refused, since nothing could lend it a
* credential.
*/
connectorRefusal?: (connector: string) => Promise<string | undefined>;
/** Hot-(re)register a runtime datasource's connection pool after write. */
registerPool?: (record: StoredDatasource) => Promise<void> | void;
/** Tear down a runtime datasource's pool on remove. */
unregisterPool?: (name: string) => Promise<void> | void;
/**
* Rebuild a runtime datasource's pool after an update that changed its
* connectivity-bearing fields (#13804): evict the pool built from
* `previous`, build + register a new one from `next`, and on failure KEEP
* the previous pool live with a loud degraded verdict (never pool-less).
*
* Optional: a host that wired only `registerPool` falls back to it, whose
* idempotency guard retains the old pool — the pre-#13804 behaviour, and
* the safe direction for a host that cannot express a swap.
*/
reregisterPool?: (previous: StoredDatasource, next: StoredDatasource) => Promise<void> | void;
/**
* [#13805] Converge THIS replica's live pool for `name` after a PEER wrote
* the shared datasource record — the receive half of
* {@link DatasourceAdminService.attachDatasourceMutationPubSub}.
*
* The host owns it because the read it must perform is the SHARED one: the
* durable row every replica writes (`sys_metadata` in the shipped plugin),
* not the metadata service's per-replica registry — on the host-config
* boot that registry has no cluster seam of its own, and is exactly the
* stale read a peer must not converge from. Contract for the host: re-read
* that record, then build what is missing, rebuild what changed, evict what
* is gone — never replay the mutation, and never touch a pool the host did
* not build itself. Optional: a host without it still PUBLISHES (peers that
* converge get the signal) and applies nothing it receives, stated once at
* `debug` when the transport attaches.
*/
convergePool?: (name: string) => Promise<void> | void;
/**
* Last connect verdict per datasource, from `DatasourceConnectionService`
* (framework#3827). Absent (a host without the connection service) means the
* list reports `unvalidated` throughout — the pre-#3827 behavior, and honest:
* with nothing attempting connects there is genuinely no verdict to report.
*/
connectionStates?: () => ReadonlyArray<{
name: string;
availability: 'available' | 'blocked' | 'failed' | 'unattempted';
reason?: string;
}>;
logger?: Logger;
}
/** Map a connection verdict onto the admin list's `status` field. */
function summaryStatus(
availability: 'available' | 'blocked' | 'failed' | 'unattempted' | undefined,
): DatasourceSummary['status'] {
switch (availability) {
case 'available':
return 'ok';
case 'blocked':
return 'blocked';
case 'failed':
return 'error';
// `unattempted` and "no record at all" are the same answer to the only
// question this field asks: nobody has tried, so nothing is known.
default:
return 'unvalidated';
}
}
/**
* A copy of `record` whose driver `config` no longer carries `key`.
*
* Pure — the caller's stored record object is never mutated, so a concurrent
* reader (the connect path holds raw records) is unaffected until the write
* lands.
*/
function withoutConfigKey(record: StoredDatasource, key: string): StoredDatasource {
const { [key]: _removed, ...config } = (record.config ?? {}) as Record<string, unknown>;
return { ...record, config };
}
/** Spread `remaining` onto a result only when there is something to report. */
function withRemaining(remaining: string[]): { remaining?: string[] } {
return remaining.length > 0 ? { remaining } : {};
}
/**
* [#6504] A refusal caused by a metadata read that could not be completed —
* carrying the ADR-0112 envelope so it does not land as a 400 alongside this
* service's genuine client errors.
*
* 503 / `SERVICE_UNAVAILABLE` for the reason `metadataStoreUnavailableError`
* (#5532) picks them in `metadata-protocol`: nothing about the REQUEST is
* wrong, the condition is a dependency outage that may clear, and a caller
* SHOULD retry. `SERVICE_UNAVAILABLE` is the standard catalog's own code for
* 503 (`HttpStatusErrorCodeMap[503]`), so this registers no new ledger
* vocabulary for a distinction the routes already know how to render.
*
* The loader messages ride on `cause` rather than in `message`: they name
* internal datasources and tables, and the message is served to an API caller.
*/
/**
* The refusal every by-name door answers when `name` resolves no stored
* datasource: here `updateDatasource`, `removeDatasource` and
* `migrateCredential`; in `ExternalDatasourceService`, `testConnection` and
* the federation guard every Sync door runs first; and `GET /datasources/:name`
* answers in its words.
*
* It carries the ADR-0112 envelope (`404` / `RESOURCE_NOT_FOUND`) so the admin
* routes answer it exactly as `GET /datasources/:name` answers the same name.
* A plain `Error` here was rendered `400 DATASOURCE_ADMIN_ERROR`, which tells an
* SDK or AI caller its request was malformed rather than that the datasource
* does not exist — and the read sibling already said the latter.
*
* [#27618] ONE helper for the package, so every by-name door names a missing
* datasource in one spelling. Exported from this module for its siblings only:
* ⛔ not from the package index, which would widen the public surface.
*/
export function datasourceNotFoundError(name: string): Error {
// GET's own words, so every by-name door names the missing datasource alike.
const err = new Error(`Datasource "${name}" does not exist.`) as Error & { code?: string; status?: number };
err.code = 'RESOURCE_NOT_FOUND';
err.status = 404;
return err;
}
/**
* [#28928] Refuse a `secret` whose value is the empty string, on create and on
* edit, before anything is read for the secret or written.
*
* A create sealed it as the datasource's credential, and an edit took it as a
* rotation: a new `sys_secret` row holding nothing, `external.credentialsRef`
* repointed at it, and the working row removed. The live pool kept serving, so
* the datasource broke only at its next connect, with nothing left to restore.
* The console never sends one (it leaves `secret` out of an untouched field);
* a script or an SDK call that clears the field is what reached it.
*
* `null` and an absent `secret` are unchanged: they keep the stored
* credential. A whitespace-only value is a value, sealed and used as sent.
* Only the empty string is judged, so the answer cannot echo a credential.
*/
function assertSecretNotEmpty(heading: string, secret: SecretInput | undefined): void {
if (secret == null || (secret as { value?: unknown }).value !== '') return;
throw new Error(
`${heading}\nThe \`secret\` is empty. Send the credential to store, or leave \`secret\` out (or null) `
+ 'to keep the stored one. Nothing was written.',
);
}
function metadataIncompleteError(message: string, errors: string[]): Error {
const err = new Error(message) as Error & { code?: string; status?: number; cause?: unknown };
err.code = 'SERVICE_UNAVAILABLE';
err.status = 503;
if (errors.length > 0) err.cause = new Error(errors.join('; '));
return err;
}
export class DatasourceAdminService implements IDatasourceAdminService {
constructor(private readonly config: DatasourceAdminServiceConfig) {}
private get logger(): Logger | undefined {
return this.config.logger;
}
// ── [#13805] the cluster half of every record write ────────────────────────
//
// Before this seam the driver registry had no cluster propagation in either
// direction: each replica filled its registry at boot from the shared
// records and mutated it only for the writes IT served. This seam adopts
// the family `metadata.mutated` established — the state owner publishes an
// address, peers converge from their own read — and adopts it SYMMETRICALLY:
// a delete-only broadcast would have made delete more cluster-aware than
// create, a new asymmetry in the opposite direction rather than a repair.
/** The cluster transport, when a bridge attached one. [#13805] */
private clusterPubSub?: IPubSub;
/** This node's cluster id — stamps `originNode` for loopback suppression. */
private clusterNodeId?: string;
/** Disposer for the cluster subscription, when attached. */
private clusterUnsubscribe?: () => void;
/**
* One in-flight convergence per datasource name. Two signals for one name
* in quick succession (a create chased by an update) must converge in
* order: two concurrent builds would both open a pool and the registry
* would keep one and discard the other — an open connection nothing closes.
* The publisher's `partitionKey` keeps the order per name on the wire; this
* keeps it on receipt.
*/
private readonly convergeChains = new Map<string, Promise<void>>();
/**
* [#13805] Attach a cluster pub/sub transport so this replica's datasource
* writes fan out on {@link DATASOURCE_MUTATION_CLUSTER_CHANNEL} and peer
* writes converge this replica's live pools. Mirrors
* `ObjectStackProtocolImplementation.attachMetadataMutationPubSub()` —
* including its idempotency on the `(pubsub, nodeId)` pair — and is called
* the same way: by `MetadataClusterBridgePlugin` in
* `@objectstack/service-cluster`, once per kernel boot at `kernel:ready`,
* after both services exist. Only `IPubSub` from `@objectstack/spec/contracts`
* crosses this seam: this package takes no dependency on the cluster
* service, and `@objectstack/objectql` — the registry's owner — is handed
* no bus at all (the layering line the card's triage drew).
*
* ⭐ Receipt runs CONVERGENCE, not trust: the payload is an address, and the
* host's `convergePool` re-reads the shared record before touching any
* pool. Duplicates are harmless (same read, same pool state); loss is
* bounded the way it always was — by the next boot's full rehydration —
* because no shipped driver exceeds at-most-once delivery (`IPubSub`'s own
* contract). This channel narrows "until every replica restarts" to "one
* network hop"; it does not promise more.
*
* @returns a disposer that detaches the bridge.
*/
attachDatasourceMutationPubSub(pubsub: IPubSub, nodeId: string): () => void {
if (this.clusterPubSub === pubsub && this.clusterNodeId === nodeId) {
return () => this.detachDatasourceMutationPubSub();
}
this.detachDatasourceMutationPubSub();
this.clusterPubSub = pubsub;
this.clusterNodeId = nodeId;
if (!this.config.convergePool) {
this.logger?.debug?.(
`datasource admin: no convergePool seam wired — peer writes on ${DATASOURCE_MUTATION_CLUSTER_CHANNEL} are published from here but not applied here`,
);
}
this.clusterUnsubscribe = pubsub.subscribe<ClusterDatasourceMutationPayload>(
DATASOURCE_MUTATION_CLUSTER_CHANNEL,
(msg) => {
const p = msg.payload;
// Loopback guard — never re-converge what this node just wrote: the
// pool seam already ran here, synchronously, at the door that
// persisted the record.
if (p?.originNode && p.originNode === this.clusterNodeId) return;
if (typeof p?.name !== 'string' || p.name.length === 0) return;
const converge = this.config.convergePool;
if (!converge) return;
this.enqueueConvergence(p.name, converge);
},
);
this.logger?.info?.(
`datasource admin: attached to the ${DATASOURCE_MUTATION_CLUSTER_CHANNEL} cluster channel (node=${nodeId})`,
);
return () => this.detachDatasourceMutationPubSub();
}
/** Tear down the cluster wiring. Safe to call multiple times. [#13805] */
detachDatasourceMutationPubSub(): void {
if (this.clusterUnsubscribe) {
try {
this.clusterUnsubscribe();
} catch {
/* idempotent */
}
this.clusterUnsubscribe = undefined;
}
this.clusterPubSub = undefined;
this.clusterNodeId = undefined;
}
/** Serialise a peer signal's convergence behind any in flight for the same name. */
private enqueueConvergence(name: string, converge: NonNullable<DatasourceAdminServiceConfig['convergePool']>): void {
const previous = this.convergeChains.get(name) ?? Promise.resolve();
const next = previous
.then(() => converge(name))
.catch((err) => {
this.logger?.warn(`datasource admin: converging '${name}' after a peer write failed`, err);
});
this.convergeChains.set(name, next);
void next.then(() => {
if (this.convergeChains.get(name) === next) this.convergeChains.delete(name);
});
}
/**
* [#13805] The cluster half of a record write: publish the datasource's
* ADDRESS to peers. Best-effort and fire-and-forget — a publish failure must
* never fail the write it announces (the record is already persisted and
* this replica's pool already follows it), matching the protocol's
* `publishMetadataMutation` verbatim. No-op until a bridge attaches a
* transport.
*
* Called from the three doors that move a record: create, update, remove.
* Deliberately NOT from `migrateCredential`: that write leaves the live pool
* alone by design (the credential VALUE is unchanged, only where it is read
* from moves), so a peer has nothing to converge — and a signal would have
* every peer rebuild a working pool over a `credentialsRef` that
* dereferences to the same secret.
*/
private publishDatasourceMutation(name: string): void {
if (!this.clusterPubSub) return;
const payload: ClusterDatasourceMutationPayload = { originNode: this.clusterNodeId, name };
void this.clusterPubSub
.publish(DATASOURCE_MUTATION_CLUSTER_CHANNEL, payload, { partitionKey: `datasource:${name}` })
.catch((err) => {
this.logger?.warn(`datasource admin: publishing '${name}' to peer replicas failed`, err);
});
}
async listDatasources(): Promise<DatasourceSummary[]> {
const records = await this.config.listDatasourceRecords();
// Group by name; code wins on collision, and a shadowed runtime row marks
// the effective (code) entry as conflicting.
const byName = new Map<string, { code?: StoredDatasource; runtime?: StoredDatasource }>();
for (const rec of records) {
const slot = byName.get(rec.name) ?? {};
if (rec.origin === 'runtime') slot.runtime = rec;
else slot.code = rec;
byName.set(rec.name, slot);
}
// Last connect verdict per datasource (framework#3827). Without this the
// `status` below was a constant, so a datasource that died at boot looked
// exactly like one nobody had tested.
const states = new Map(
(this.config.connectionStates?.() ?? []).map((s) => [s.name, s]),
);
const summaries: DatasourceSummary[] = [];
for (const [name, slot] of byName) {
const effective = slot.code ?? slot.runtime;
if (!effective) continue;
const state = states.get(name);
const status = summaryStatus(state?.availability);
summaries.push({
name,
label: effective.label,
driver: effective.driver,
schemaMode: effective.schemaMode ?? 'managed',
origin: slot.code ? 'code' : 'runtime',
active: effective.active ?? true,
status,
...(status !== 'ok' && status !== 'unvalidated' && state?.reason
? { statusReason: state.reason }
: {}),
...(slot.code?.definedIn ? { definedIn: slot.code.definedIn } : {}),
...(slot.code && slot.runtime ? { conflictsWithCode: true } : {}),
});
}
return summaries;
}
/**
* Read one datasource's full detail for editing, with every stored credential
* redacted out of `config` (#8081).
*
* Returns `config`, `origin`, a `hasSecret` flag so the UI can show "leave
* blank to keep" without ever receiving the `credentialsRef`, and
* `redactedConfigKeys` naming what was withheld. Returns `undefined` when the
* name is unknown.
*
* ## The claim this comment used to make
*
* It said "with the credential stripped", and described `config` as
* "non-sensitive — credentials live in `sys_secret`, never in config". Both
* halves were false, and load-bearing: nothing here stripped anything, and
* `config` was returned verbatim. A datasource row written before #8078
* carries `config.password` / `config.authToken` in cleartext (that is the
* whole reason #8078 exists), and this method served it — to every caller of
* `GET /api/v1/datasources/:name` — under a comment asserting it could not.
* A safety claim that no code performs is worse than no claim: it is what
* stops the next reader from looking.
*
* What makes the claim true now is {@link redactDatasourceConfig}, which also
* covers the credential the old sentence could not have described — the one
* embedded in a `postgresql://user:pass@host` URL, which lives in `config`
* and is not `config.password`. Refusing such a URL at the WRITE door remains
* unruled (#7990) and is deliberately untouched here; hiding it on the way
* out is a separate act and is what this method owes its callers.
*
* The stored record is not modified. Cleartext already at rest stays at rest
* until the migration this card proposes runs — closing the read path is what
* stops it being SERVED, not what removes it.
*/
async getDatasource(name: string): Promise<
| (Pick<
StoredDatasource,
'name' | 'label' | 'driver' | 'schemaMode' | 'config' | 'active' | 'definedIn' | 'ssl' | 'autoConnect' | 'description'
> & {
origin: 'code' | 'runtime';
hasSecret: boolean;
redactedConfigKeys: string[];
})
| undefined
> {
const rec = await this.config.getDatasourceRecord(name);
if (!rec) return undefined;
const hasSecret = Boolean(rec.external?.credentialsRef);
const { config, redactedKeys } = redactDatasourceConfig(rec.driver, rec.config);
return {
name: rec.name,
label: rec.label,
driver: rec.driver,
schemaMode: rec.schemaMode ?? 'managed',
config,
active: rec.active ?? true,
// [#28633] The other keys the doors now store, so an edit form reads back
// what was saved. `ssl` is served without its private key, whatever the
// row holds: the key never leaves this service, as a `config` credential
// does not (#8081).
...(rec.ssl !== undefined ? { ssl: servableSsl(rec.ssl) } : {}),
...(rec.autoConnect !== undefined ? { autoConnect: rec.autoConnect } : {}),
...(rec.description !== undefined ? { description: rec.description } : {}),
origin: rec.origin === 'runtime' ? 'runtime' : 'code',
hasSecret,
redactedConfigKeys: redactedKeys,
...(rec.definedIn ? { definedIn: rec.definedIn } : {}),
};
}
async testConnection(input: DatasourceDraft, secret?: SecretInput): Promise<TestConnectionResult> {
// [#28612] First, and as a refusal (a `400` at the route) rather than a
// failed probe: the probe below is built from the known keys only, so a
// top-level `password` or any other key the schema refuses would vanish
// and the answer would be about a different connection than the one
// described.
if (input && typeof input === 'object') {
this.assertNoUndeclaredTopLevelKey('This connection draft is not a valid datasource.', input);
}
if (!input?.driver) {
return { ok: false, error: 'A driver is required to test a connection.' };
}
// Checked BEFORE the probe: a misspelled key makes the driver fall back to
// its own defaults, so the probe would open a connection to localhost and
// report a green "Connection successful" for a datasource that points
// somewhere else entirely — the wizard's version of #4410's core bug.
try {
this.assertValidConfig(input.driver, input.config);
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
// [#21058] And the pairing, by the same reasoning one level up: a mongo
// `url` that names no user (or a composed config with no `username`)
// drops a supplied secret on the factory's floor — `buildMongoAuth` /
// `buildMongoUrl` never read it — so the probe connects anonymously and
// reports green for a pairing `createDatasource` refuses. Judged on the
// record a Save would persist, as create judges it, minus the identity the
// probe does not have.
//
// [#28633] And probed from that same record: the projection a Save stores
// is the one the probe reads, so a test opens TLS exactly as the saved
// datasource will.
const draft = this.toRecord({ ...input, name: PROBE_DRAFT_NAME });
const keyRefusal = inlineSslKeyRefusal('This connection draft is not a valid datasource.', draft);
if (keyRefusal) return { ok: false, error: keyRefusal };
const refusal = this.recordRefusal(
this.withSecretBinding({ ...draft, origin: 'runtime' }, secret),
'This connection draft is not a valid datasource.',
);
if (refusal) return { ok: false, error: refusal };
const lendRefusal = await this.connectorLendRefusal({ name: PROBE_DRAFT_NAME, external: input.external } as StoredDatasource);
if (lendRefusal) return { ok: false, error: lendRefusal };
const queryTimeoutMs = (input.external as { queryTimeoutMs?: number } | undefined)?.queryTimeoutMs;
try {
return await this.config.probe({
driver: draft.driver,
config: draft.config ?? {},
secret: secret?.value,
external: draft.external,
...(draft.ssl !== undefined ? { ssl: draft.ssl } : {}),
...(typeof queryTimeoutMs === 'number' ? { timeoutMs: queryTimeoutMs } : {}),
});
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
async createDatasource(input: DatasourceDraft, secret?: SecretInput): Promise<DatasourceSummary> {
this.assertValidName(input?.name);
assertSecretNotEmpty(`Invalid datasource '${input.name}'.`, secret);
this.assertNoDraftCredentialsRef(input);
this.assertNoUndeclaredTopLevelKey(`Invalid datasource '${input.name}'.`, input);
assertNoInlineSslKey(`Invalid datasource '${input.name}'.`, input);
if (!input.driver) throw new Error('A driver is required to create a datasource.');
this.assertValidConfig(input.driver, input.config);
// The wizard is a publish door for `pool` too (#5714). Rejected BEFORE the
// record is persisted: `tryRegisterPool` swallows its failures into a
// warning, so a datasource saved with an unhonourable pool would sit in the
// store with the block still in it, exactly as silently as before.
assertDatasourcePoolSupported({ driver: input.driver, pool: input.pool, name: input.name });
const existing = await this.config.getDatasourceRecord(input.name);
if (existing) {
if (existing.origin === 'code' || existing.origin === undefined) {
throw new Error(
`Cannot create datasource '${input.name}': a code-defined datasource owns this name (read-only).`,
);
}
throw new Error(`Datasource '${input.name}' already exists.`);
}
const record: StoredDatasource = {
...this.toRecord(input),
origin: 'runtime',
};
// [#21058] Before the secret write: a refused record must leave nothing
// behind, the bound secret included.
this.assertValidRecord(this.withSecretBinding(record, secret));
// [ADR-0015 §4.2 · #25277] Same position, same reason: objects can name a
// datasource before it exists (the save door gives no verdict on a
// binding whose datasource it cannot see), so a create is judged too.
await this.assertNoExternalBindingConflict(record);
// [ADR-0015 D7] Same position: a record that names a connector instance no
// source can lend leaves nothing behind.
await this.assertConnectorLendable(record);
if (secret) {
const credentialsRef = await this.config.writeSecret(secret, { name: input.name });
record.external = { ...(record.external ?? {}), credentialsRef };
}
await this.config.putDatasourceRecord(record);
// [#13804] A record born `active: false` gets no live pool. Every other
// lifecycle path already reads the flag this way — `connectDeclared` skips
// `active === false` at boot, and boot rehydration filters on
// `active ?? true` — so this door was the one place a deliberately
// disabled datasource still came up serving.
if (record.active !== false) await this.tryRegisterPool(record);
// [#13805] After the pool seam, whatever it decided: peers converge from
// the shared record, not from what this replica did with its own pool.
this.publishDatasourceMutation(record.name);
return this.toSummary(record);
}
async updateDatasource(
name: string,
patch: Partial<DatasourceDraft>,
secret?: SecretInput,
): Promise<DatasourceSummary> {
const existing = await this.config.getDatasourceRecord(name);
if (!existing) throw datasourceNotFoundError(name);
if (existing.origin !== 'runtime') {
throw new Error(`Datasource '${name}' is code-defined and cannot be edited at runtime.`);
}
// [#28549 · #28612] Whatever else the patch touches, a `label`/`active`-only
// edit included: that exemption spares a row stored before a gate, and this
// judges a key the author is writing now.
this.assertNoUndeclaredTopLevelKey(`Invalid datasource '${existing.name}'.`, patch);
assertNoInlineSslKey(`Invalid datasource '${existing.name}'.`, patch);
assertSecretNotEmpty(`Invalid datasource '${existing.name}'.`, secret);
// Merge patch over the existing record; `name`/`origin` are never patched.
// [#28633] Every key the create door stores is patchable the same way
// ({@link storedDatasourceKeys}); `external` keeps its own rule below.
const { name: _name, external: _external, ...patched } = storedKeysOf(patch);
const patchedKeys = Object.keys(patched).concat(patch.external !== undefined ? ['external'] : []);
const merged: StoredDatasource = {
...existing,
...(patched as Partial<StoredDatasource>),
name: existing.name,
origin: 'runtime',
};
if (patch.external !== undefined) {
// Preserve the existing credentialsRef unless a new secret rewraps it.
merged.external = { ...patch.external, credentialsRef: existing.external?.credentialsRef };
}
// Judged on the MERGED record, but only when this write actually touches
// the pairing: a new `config`, or a new `driver` that reinterprets the
// stored one. An edit that renames a datasource or flips `active` must not
// be blocked by a config it is not touching — a record written before
// #4410 would otherwise become uneditable, including the `active: false`
// that takes a misconfigured datasource out of service.
if (patch.config !== undefined || patch.driver !== undefined) {
this.assertValidConfig(merged.driver, merged.config);
}
// Same judgement, same "only when this write touches the pairing" rule
// (#5714): a new `pool`, or a new `driver` that reinterprets the stored
// one. An edit that renames a datasource or flips `active` must not be
// blocked by a pool block it is not touching — otherwise a record written
// before this gate becomes uneditable, including the `active: false` that
// takes it out of service.
if (patch.pool !== undefined || patch.driver !== undefined) {
assertDatasourcePoolSupported({ driver: merged.driver, pool: merged.pool, name });
}
// [#21058] The whole merged record, with the binding it will carry — the
// existing `credentialsRef` (preserved above), or the one a supplied secret
// is about to write. Before `writeSecret`, so a refusal neither mints a new
// secret nor unbinds the old one. Skipped only for a `label`/`active`-only
// write, the exemption the two gates above already make.
//
// Judged BEFORE the redacted-credential restore below, for the reason that
// block states: the subject is what the author wrote, not the stored
// material the read path withheld from them. The cross-field verdicts do
// not move across the restore — it grafts back credential keys and swaps a
// url for its stored twin, which names the same user (`redactUrlPassword`
// keeps the userinfo username).
if (secret !== undefined || patchedKeys.some((key) => !RECORD_JUDGE_EXEMPT_PATCH_KEYS.has(key))) {
this.assertValidRecord(this.withSecretBinding(merged, secret));
// [ADR-0015 §4.2 · #25277] The merged record against the objects bound
// to it, under the same condition: a `label`/`active`-only write stays
// possible on a row that already pairs badly, so it can still be taken
// out of service. The secret does not move the verdict.
await this.assertNoExternalBindingConflict(merged);
}
// [ADR-0015 D7] Only when this write touches `external`, by the same
// reasoning: an instance removed from the stack must not make the row's
// `active: false` unreachable.
if (patch.external !== undefined) await this.assertConnectorLendable(merged);
if (secret) {
const prevRef = existing.external?.credentialsRef;
const credentialsRef = await this.config.writeSecret(secret, { name });
merged.external = { ...(merged.external ?? {}), credentialsRef };
if (prevRef && prevRef !== credentialsRef) await this.tryRemoveSecret(prevRef);
}
// Carry forward the credential material `getDatasource()` redacts (#8081)
// — AFTER the gate above, and only when this patch is round-tripping the
// same driver's config back.
//
// After, because the two judgements have different subjects. The gate
// judges what the AUTHOR wrote, and #8078's refusal of an inline credential
// is aimed at exactly that. This restore replaces material the author never
// saw, was never offered the chance to write, and is not asking to change;
// running the gate over it would refuse a legacy row for the contents of
// its own stored config and make `active: false` — the way a misconfigured
// datasource is taken out of service — unreachable on the rows most likely
// to need it. Same shape as the `credentialsRef` preserved a few lines up,
// which is likewise carried across a patch without being re-judged.
//
// Only when the driver is unchanged: a patch that re-points a datasource at
// a different driver is rewiring the connection, and one driver's stored
// credential is not evidence about another's.
//
// This preserves cleartext already at rest; it does not create any. Getting
// that cleartext OUT of the store is the migration this card proposes
// (scope item 3) and is deliberately not attempted here — a write path that
// quietly dropped a credential the operator still depends on would be the
// destructive sweep that decision is reserved for.
if (patch.config !== undefined && merged.driver === existing.driver) {
merged.config = restoreRedactedConfig(existing.driver, merged.config, existing.config);
}
// [#28633] The same carry-forward for the one `ssl` member a read withholds:
// a patched `ssl` block without a private key (what `getDatasource()`
// served) keeps the stored one. This door never takes a new one
// ({@link assertNoInlineSslKey}), so it preserves a key already at rest and
// creates none.
const storedKey = existing.ssl?.[SSL_PRIVATE_KEY];
if (patch.ssl !== undefined && storedKey !== undefined && merged.ssl && !(SSL_PRIVATE_KEY in merged.ssl)) {
merged.ssl = { ...merged.ssl, [SSL_PRIVATE_KEY]: storedKey };
}
await this.config.putDatasourceRecord(merged);
// [#13804] What "Save" means for the LIVE pool, decided by what actually
// changed — never unconditionally. The old tail called `registerPool` on
// every update, and the connect path's idempotency guard turned that into
// `already-registered` while a driver held the name: the merged record was
// persisted, the pool built from the OLD record kept serving, and
// `toSummary` reported the ORIGINAL connect's retained `connected` — a