@cratis/chronicle 6.64.0 → 6.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/ChronicleClient.ts +2 -1
  2. package/ChronicleOptions.ts +65 -23
  3. package/README.md +1 -1
  4. package/connection/ChronicleConnection.auth.spec.ts +3 -3
  5. package/connection/ChronicleConnection.ts +24 -7
  6. package/connection/ChronicleConnectionString.spec.ts +85 -0
  7. package/connection/ChronicleConnectionString.ts +186 -12
  8. package/connection/ChronicleTlsMaterial.spec.ts +160 -0
  9. package/connection/ChronicleTlsMaterial.ts +121 -0
  10. package/connection/CompatibilityPreflight.ts +31 -5
  11. package/connection/LeastConnectionsLoadBalancerStrategy.ts +4 -2
  12. package/connection/LoadBalancerStrategyFactory.ts +7 -2
  13. package/connection/TokenProvider.ts +4 -1
  14. package/connection/fetchOAuthAccessToken.ts +4 -2
  15. package/connection/for_ChronicleConnection/when_checking_compatibility/before_append.spec.ts +12 -1
  16. package/connection/for_ChronicleConnection/when_creating_clients/with_correlated_multi_host_callers.spec.ts +1 -1
  17. package/connection/for_ChronicleConnection/when_deferring_client_creation/and_connecting.spec.ts +1 -1
  18. package/connection/for_CompatibilityPreflight/when_verifying/with_concurrent_calls.spec.ts +2 -2
  19. package/connection/for_CompatibilityPreflight/when_verifying/with_kernel_versions.spec.ts +38 -0
  20. package/connection/for_CompatibilityPreflight/when_verifying/with_the_check_skipped.spec.ts +23 -0
  21. package/connection/for_TraceContextMiddleware/when_calling/with_active_context.spec.ts +1 -1
  22. package/connection/for_TraceContextMiddleware/when_calling/with_grpc_instrumentation.spec.ts +1 -1
  23. package/dist/ChronicleClient.d.ts.map +1 -1
  24. package/dist/ChronicleClient.js +2 -1
  25. package/dist/ChronicleClient.js.map +1 -1
  26. package/dist/ChronicleOptions.d.ts +18 -0
  27. package/dist/ChronicleOptions.d.ts.map +1 -1
  28. package/dist/ChronicleOptions.js +55 -23
  29. package/dist/ChronicleOptions.js.map +1 -1
  30. package/dist/connection/ChronicleConnection.d.ts +3 -0
  31. package/dist/connection/ChronicleConnection.d.ts.map +1 -1
  32. package/dist/connection/ChronicleConnection.js +21 -7
  33. package/dist/connection/ChronicleConnection.js.map +1 -1
  34. package/dist/connection/ChronicleConnectionString.d.ts +50 -1
  35. package/dist/connection/ChronicleConnectionString.d.ts.map +1 -1
  36. package/dist/connection/ChronicleConnectionString.js +154 -12
  37. package/dist/connection/ChronicleConnectionString.js.map +1 -1
  38. package/dist/connection/ChronicleTlsMaterial.d.ts +54 -0
  39. package/dist/connection/ChronicleTlsMaterial.d.ts.map +1 -0
  40. package/dist/connection/ChronicleTlsMaterial.js +88 -0
  41. package/dist/connection/ChronicleTlsMaterial.js.map +1 -0
  42. package/dist/connection/CompatibilityPreflight.d.ts +7 -1
  43. package/dist/connection/CompatibilityPreflight.d.ts.map +1 -1
  44. package/dist/connection/CompatibilityPreflight.js +24 -4
  45. package/dist/connection/CompatibilityPreflight.js.map +1 -1
  46. package/dist/connection/LeastConnectionsLoadBalancerStrategy.d.ts +2 -1
  47. package/dist/connection/LeastConnectionsLoadBalancerStrategy.d.ts.map +1 -1
  48. package/dist/connection/LeastConnectionsLoadBalancerStrategy.js +3 -2
  49. package/dist/connection/LeastConnectionsLoadBalancerStrategy.js.map +1 -1
  50. package/dist/connection/LoadBalancerStrategyFactory.d.ts +2 -1
  51. package/dist/connection/LoadBalancerStrategyFactory.d.ts.map +1 -1
  52. package/dist/connection/LoadBalancerStrategyFactory.js +3 -2
  53. package/dist/connection/LoadBalancerStrategyFactory.js.map +1 -1
  54. package/dist/connection/TokenProvider.d.ts +4 -1
  55. package/dist/connection/TokenProvider.d.ts.map +1 -1
  56. package/dist/connection/TokenProvider.js +5 -1
  57. package/dist/connection/TokenProvider.js.map +1 -1
  58. package/dist/connection/fetchOAuthAccessToken.d.ts +2 -1
  59. package/dist/connection/fetchOAuthAccessToken.d.ts.map +1 -1
  60. package/dist/connection/fetchOAuthAccessToken.js +3 -2
  61. package/dist/connection/fetchOAuthAccessToken.js.map +1 -1
  62. package/dist/eventSequences/EventSequence.d.ts +3 -0
  63. package/dist/eventSequences/EventSequence.d.ts.map +1 -1
  64. package/dist/eventSequences/EventSequence.js +12 -3
  65. package/dist/eventSequences/EventSequence.js.map +1 -1
  66. package/dist/eventSequences/IEventSequence.d.ts +2 -0
  67. package/dist/eventSequences/IEventSequence.d.ts.map +1 -1
  68. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.d.ts +1 -1
  69. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.d.ts.map +1 -1
  70. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.js +3 -3
  71. package/dist/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.js.map +1 -1
  72. package/dist/eventSequences/ensureNamedTagBatchIsSupported.d.ts +2 -2
  73. package/dist/eventSequences/ensureNamedTagBatchIsSupported.d.ts.map +1 -1
  74. package/dist/eventSequences/ensureNamedTagBatchIsSupported.js +10 -3
  75. package/dist/eventSequences/ensureNamedTagBatchIsSupported.js.map +1 -1
  76. package/dist/index.d.ts +1 -0
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/index.js +1 -0
  79. package/dist/index.js.map +1 -1
  80. package/dist/testing/ReactorScenario.d.ts.map +1 -1
  81. package/dist/testing/ReactorScenario.js +0 -2
  82. package/dist/testing/ReactorScenario.js.map +1 -1
  83. package/dist/transactions/UnitOfWork.d.ts +1 -0
  84. package/dist/transactions/UnitOfWork.d.ts.map +1 -1
  85. package/dist/transactions/UnitOfWork.js +17 -11
  86. package/dist/transactions/UnitOfWork.js.map +1 -1
  87. package/dist/tsconfig.tsbuildinfo +1 -1
  88. package/eventSequences/EventSequence.ts +14 -3
  89. package/eventSequences/IEventSequence.ts +3 -0
  90. package/eventSequences/NamedTagsWithRegisteredEventSourceNotSupported.ts +3 -3
  91. package/eventSequences/ensureNamedTagBatchIsSupported.ts +11 -3
  92. package/eventSequences/for_EventSequence/when_appending_named_tags/given.fixture.ts +3 -2
  93. package/eventSequences/for_EventSequence/when_appending_named_tags/with_kernel_versions.spec.ts +92 -0
  94. package/eventSequences/for_EventSequence/when_appending_named_tags/with_registered_sources.spec.ts +28 -22
  95. package/for_ChronicleClient/connectTimeout.spec.ts +29 -0
  96. package/for_ChronicleClient/when_starting_background_work/with_a_correlated_caller.spec.ts +1 -1
  97. package/for_ChronicleOptions/when_configuring_keep_alive/with_skip_keep_alive.spec.ts +1 -1
  98. package/for_ChronicleOptions/when_configuring_the_connect_timeout/with_connect_timeout.spec.ts +23 -0
  99. package/for_index/when_importing_connection_helpers.spec.ts +13 -0
  100. package/index.ts +1 -0
  101. package/package.json +1 -1
  102. package/patterns/for_Patterns/when_querying_through_the_connection/after_resetting_the_channel.spec.ts +1 -1
  103. package/testing/ReactorScenario.ts +0 -3
  104. package/testing/for_ReactorScenario/when_recording_side_effects/with_named_tags.spec.ts +11 -13
  105. package/transactions/UnitOfWork.ts +18 -14
  106. package/transactions/for_UnitOfWork/when_committing_events_with_named_tags.spec.ts +87 -29
@@ -2,8 +2,10 @@
2
2
  // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
3
 
4
4
  import * as grpc from '@grpc/grpc-js';
5
+ import * as tls from 'node:tls';
5
6
  import { formatServerAddress } from './formatServerAddress.js';
6
7
  import { LoadBalancerMode } from './LoadBalancerMode.js';
8
+ import { loadTlsMaterial, type ChronicleTlsMaterial } from './ChronicleTlsMaterial.js';
7
9
 
8
10
  const DEFAULT_PORT = 35000;
9
11
  const SRV_SCHEME = 'chronicle+srv';
@@ -12,6 +14,8 @@ const SRV_SCHEME = 'chronicle+srv';
12
14
  * Authentication mode for Chronicle connection.
13
15
  */
14
16
  export enum AuthenticationMode {
17
+ /** No authentication at all (`auth=none`, or a cleartext connection without credentials). */
18
+ None = 'None',
15
19
  ClientCredentials = 'ClientCredentials',
16
20
  ApiKey = 'ApiKey'
17
21
  }
@@ -105,6 +109,21 @@ export class ChronicleConnectionStringBuilder {
105
109
  private static readonly _apiKeyKey = 'apiKey';
106
110
  private static readonly _disableTlsKey = 'disableTls';
107
111
  private static readonly _skipKeepAliveKey = 'skipKeepAlive';
112
+ private static readonly _authKey = 'auth';
113
+ private static readonly _skipCompatibilityCheckKey = 'skipCompatibilityCheck';
114
+ private static readonly _caCertificatePathKey = 'caCertificatePath';
115
+ private static readonly _noAuthenticationValue = 'none';
116
+
117
+ /** Every option the builder knows, so a differently cased spelling folds to its canonical one. */
118
+ private static readonly _knownKeys = new Map<string, string>([
119
+ 'apiKey', 'auth', 'skipTlsValidation', 'disableTls', 'skipCompatibilityCheck', 'skipKeepAlive',
120
+ 'loadBalancer', 'srvNameServer', 'certificatePath', 'certificatePassword', 'caCertificatePath'
121
+ ].map(key => [key.toLowerCase(), key]));
122
+
123
+ /** Options whose value may legitimately hold an at sign, such as a path or a name server. */
124
+ private static readonly _keysThatMayHoldAtSign = new Set([
125
+ 'apikey', 'certificatepath', 'certificatepassword', 'cacertificatepath', 'loadbalancer', 'srvnameserver'
126
+ ]);
108
127
  private static readonly _skipTlsValidationKey = 'skipTlsValidation';
109
128
  private static readonly _certificatePathKey = 'certificatePath';
110
129
  private static readonly _certificatePasswordKey = 'certificatePassword';
@@ -198,14 +217,24 @@ export class ChronicleConnectionStringBuilder {
198
217
  }
199
218
 
200
219
  get authenticationMode(): AuthenticationMode {
201
- const hasClientCredentials = !!this.username && !!this.password;
220
+ const hasUsername = !!this.username;
221
+ const hasPassword = !!this.password;
222
+ const hasClientCredentials = hasUsername && hasPassword;
202
223
  const hasApiKey = !!this.apiKey;
224
+ const hasNoCredentials = !hasUsername && !hasPassword && !hasApiKey;
225
+
226
+ // Asking for no authentication is deliberate and beats anything else the connection string carries -
227
+ // credentials left in place by a shared configuration must not quietly turn the exchange back on.
228
+ if (this.noAuthentication) {
229
+ return AuthenticationMode.None;
230
+ }
203
231
 
204
232
  if (hasClientCredentials && hasApiKey) {
205
233
  throw new Error('Cannot specify both username/password and apiKey in the connection string');
206
234
  }
207
235
 
208
- if (hasClientCredentials) {
236
+ // No credentials at all means the development client credentials.
237
+ if (hasClientCredentials || hasNoCredentials) {
209
238
  return AuthenticationMode.ClientCredentials;
210
239
  }
211
240
 
@@ -213,7 +242,24 @@ export class ChronicleConnectionStringBuilder {
213
242
  return AuthenticationMode.ApiKey;
214
243
  }
215
244
 
216
- throw new Error('No authentication method specified. Provide either username/password or apiKey in the connection string');
245
+ throw new Error('Incomplete authentication. Provide both username and password, or an apiKey, in the connection string');
246
+ }
247
+
248
+ /**
249
+ * Whether `auth=none` is set: no authentication at all. It wins over any credentials or API key the
250
+ * connection string also carries.
251
+ */
252
+ get noAuthentication(): boolean {
253
+ return this._properties.get(ChronicleConnectionStringBuilder._authKey)?.toLowerCase() === ChronicleConnectionStringBuilder._noAuthenticationValue;
254
+ }
255
+
256
+ set noAuthentication(value: boolean) {
257
+ if (value) {
258
+ this._properties.set(ChronicleConnectionStringBuilder._authKey, ChronicleConnectionStringBuilder._noAuthenticationValue);
259
+ return;
260
+ }
261
+
262
+ this._properties.delete(ChronicleConnectionStringBuilder._authKey);
217
263
  }
218
264
 
219
265
  get apiKey(): string | undefined {
@@ -230,7 +276,7 @@ export class ChronicleConnectionStringBuilder {
230
276
  }
231
277
 
232
278
  get disableTls(): boolean {
233
- return this._properties.get(ChronicleConnectionStringBuilder._disableTlsKey) === 'true';
279
+ return this.booleanOption(ChronicleConnectionStringBuilder._disableTlsKey, false);
234
280
  }
235
281
 
236
282
  set disableTls(value: boolean) {
@@ -245,8 +291,7 @@ export class ChronicleConnectionStringBuilder {
245
291
  * always requires validation. A later major release will require validation by default.
246
292
  */
247
293
  get skipTlsValidation(): boolean {
248
- const raw = this._properties.get(ChronicleConnectionStringBuilder._skipTlsValidationKey);
249
- return raw === undefined || raw === 'true';
294
+ return this.booleanOption(ChronicleConnectionStringBuilder._skipTlsValidationKey, true);
250
295
  }
251
296
 
252
297
  set skipTlsValidation(value: boolean) {
@@ -260,7 +305,7 @@ export class ChronicleConnectionStringBuilder {
260
305
 
261
306
  /** Skip the client keep-alive connection for short-lived processes. Defaults to false. */
262
307
  get skipKeepAlive(): boolean {
263
- return this._properties.get(ChronicleConnectionStringBuilder._skipKeepAliveKey) === 'true';
308
+ return this.booleanOption(ChronicleConnectionStringBuilder._skipKeepAliveKey, false);
264
309
  }
265
310
 
266
311
  set skipKeepAlive(value: boolean) {
@@ -293,6 +338,37 @@ export class ChronicleConnectionStringBuilder {
293
338
  this._properties.delete(ChronicleConnectionStringBuilder._certificatePasswordKey);
294
339
  }
295
340
 
341
+ /**
342
+ * Whether to skip the server compatibility check on connect (`skipCompatibilityCheck=true`). An escape hatch
343
+ * for a known-safe client and kernel skew; it hides every other incompatibility too.
344
+ */
345
+ get skipCompatibilityCheck(): boolean {
346
+ return this.booleanOption(ChronicleConnectionStringBuilder._skipCompatibilityCheckKey, false);
347
+ }
348
+
349
+ set skipCompatibilityCheck(value: boolean) {
350
+ this._properties.set(ChronicleConnectionStringBuilder._skipCompatibilityCheckKey, value.toString());
351
+ }
352
+
353
+ /**
354
+ * The path to a PEM file with the certificate authorities the server certificate must chain to, in place of
355
+ * the system trust store (`caCertificatePath=`). Used only when `skipTlsValidation=false`; the file is
356
+ * nevertheless read when the connection is created, so a missing or unreadable file, or one without
357
+ * certificates, fails the connection setup.
358
+ */
359
+ get caCertificatePath(): string | undefined {
360
+ return this._properties.get(ChronicleConnectionStringBuilder._caCertificatePathKey);
361
+ }
362
+
363
+ set caCertificatePath(value: string | undefined) {
364
+ if (value) {
365
+ this._properties.set(ChronicleConnectionStringBuilder._caCertificatePathKey, value);
366
+ return;
367
+ }
368
+
369
+ this._properties.delete(ChronicleConnectionStringBuilder._caCertificatePathKey);
370
+ }
371
+
296
372
  /**
297
373
  * The strategy used to select one address from {@link hosts} (or the addresses
298
374
  * resolved from a `chronicle+srv://` host) on every connect/reconnect attempt.
@@ -342,9 +418,9 @@ export class ChronicleConnectionStringBuilder {
342
418
  let result = `${this.scheme}://`;
343
419
 
344
420
  if (this.username) {
345
- result += this.username;
421
+ result += encodeURIComponent(this.username);
346
422
  if (this.password) {
347
- result += `:${this.password}`;
423
+ result += `:${encodeURIComponent(this.password)}`;
348
424
  }
349
425
  result += '@';
350
426
  }
@@ -357,10 +433,18 @@ export class ChronicleConnectionStringBuilder {
357
433
  queryParameters.push(`apiKey=${encodeURIComponent(this.apiKey)}`);
358
434
  }
359
435
 
436
+ if (this.noAuthentication) {
437
+ queryParameters.push(`auth=${ChronicleConnectionStringBuilder._noAuthenticationValue}`);
438
+ }
439
+
360
440
  if (this.disableTls) {
361
441
  queryParameters.push('disableTls=true');
362
442
  }
363
443
 
444
+ if (this.skipCompatibilityCheck) {
445
+ queryParameters.push('skipCompatibilityCheck=true');
446
+ }
447
+
364
448
  this.appendSkipKeepAlive(queryParameters);
365
449
 
366
450
  if (this.hasExplicitSkipTlsValidation) {
@@ -375,6 +459,10 @@ export class ChronicleConnectionStringBuilder {
375
459
  queryParameters.push(`certificatePassword=${encodeURIComponent(this.certificatePassword)}`);
376
460
  }
377
461
 
462
+ if (this.caCertificatePath) {
463
+ queryParameters.push(`caCertificatePath=${encodeURIComponent(this.caCertificatePath)}`);
464
+ }
465
+
378
466
  if (this._properties.has(ChronicleConnectionStringBuilder._loadBalancerKey)) {
379
467
  queryParameters.push(`loadBalancer=${encodeURIComponent(this.loadBalancer)}`);
380
468
  }
@@ -389,6 +477,9 @@ export class ChronicleConnectionStringBuilder {
389
477
  key !== ChronicleConnectionStringBuilder._passwordKey &&
390
478
  key !== ChronicleConnectionStringBuilder._schemeKey &&
391
479
  key !== ChronicleConnectionStringBuilder._apiKeyKey &&
480
+ key !== ChronicleConnectionStringBuilder._authKey &&
481
+ key !== ChronicleConnectionStringBuilder._skipCompatibilityCheckKey &&
482
+ key !== ChronicleConnectionStringBuilder._caCertificatePathKey &&
392
483
  key !== ChronicleConnectionStringBuilder._disableTlsKey &&
393
484
  key !== ChronicleConnectionStringBuilder._skipTlsValidationKey &&
394
485
  key !== ChronicleConnectionStringBuilder._certificatePathKey &&
@@ -407,6 +498,37 @@ export class ChronicleConnectionStringBuilder {
407
498
  return result;
408
499
  }
409
500
 
501
+ private booleanOption(key: string, defaultValue: boolean): boolean {
502
+ const raw = this._properties.get(key);
503
+ if (raw === undefined) {
504
+ return defaultValue;
505
+ }
506
+
507
+ const normalized = raw.toLowerCase();
508
+ if (normalized === 'true') {
509
+ return true;
510
+ }
511
+
512
+ if (normalized === 'false') {
513
+ return false;
514
+ }
515
+
516
+ throw new Error(`The value of the '${key}' option is invalid.`);
517
+ }
518
+
519
+ private static hasMisplacedAtSign(pair: string): boolean {
520
+ if (!pair.includes('@')) {
521
+ return false;
522
+ }
523
+
524
+ const equalsIndex = pair.indexOf('=');
525
+ if (equalsIndex === -1 || pair.indexOf('@') < equalsIndex) {
526
+ return true;
527
+ }
528
+
529
+ return !ChronicleConnectionStringBuilder._keysThatMayHoldAtSign.has(decodeURIComponent(pair.slice(0, equalsIndex)).toLowerCase());
530
+ }
531
+
410
532
  private appendSkipKeepAlive(queryParameters: string[]): void {
411
533
  if (this.skipKeepAlive) queryParameters.push('skipKeepAlive=true');
412
534
  }
@@ -442,6 +564,13 @@ export class ChronicleConnectionStringBuilder {
442
564
  query = queryIndex === -1 ? '' : rest.slice(queryIndex + 1);
443
565
  }
444
566
 
567
+ // An at sign in the query means the user information held a separator that was not percent-encoded
568
+ // and spilled into it - unless the option is one that may hold one.
569
+ const pairs = query.length === 0 ? [] : query.split('&');
570
+ if (pairs.some(pair => ChronicleConnectionStringBuilder.hasMisplacedAtSign(pair))) {
571
+ throw new Error('The user information must be percent-encoded: it contains a separator');
572
+ }
573
+
445
574
  // The userinfo separator is the LAST '@' in the authority, so a host portion never
446
575
  // legitimately containing '@' can't be confused for one.
447
576
  const authoritySeparatorIndex = authority.lastIndexOf('@');
@@ -463,8 +592,17 @@ export class ChronicleConnectionStringBuilder {
463
592
  }
464
593
  this.hosts = hosts;
465
594
 
466
- for (const [key, queryValue] of new URLSearchParams(query)) {
467
- this._properties.set(key, decodeURIComponent(queryValue));
595
+ // Percent-decoding only: a literal '+' stays a plus, like the .NET client, and the value is decoded once.
596
+ for (const pair of pairs) {
597
+ const equalsIndex = pair.indexOf('=');
598
+ if (equalsIndex <= 0) {
599
+ continue;
600
+ }
601
+
602
+ const key = decodeURIComponent(pair.slice(0, equalsIndex));
603
+ this._properties.set(
604
+ ChronicleConnectionStringBuilder._knownKeys.get(key.toLowerCase()) ?? key,
605
+ decodeURIComponent(pair.slice(equalsIndex + 1)));
468
606
  }
469
607
  } catch (error) {
470
608
  throw new Error(`Invalid Chronicle connection string: ${error}`);
@@ -548,6 +686,21 @@ export class ChronicleConnectionString {
548
686
  return this._builder.skipKeepAlive;
549
687
  }
550
688
 
689
+ /** Whether `auth=none` is set: no authentication at all. */
690
+ get noAuthentication(): boolean {
691
+ return this._builder.noAuthentication;
692
+ }
693
+
694
+ /** Whether to skip the server compatibility check on connect. */
695
+ get skipCompatibilityCheck(): boolean {
696
+ return this._builder.skipCompatibilityCheck;
697
+ }
698
+
699
+ /** The path to a PEM file with the certificate authorities the server certificate must chain to. */
700
+ get caCertificatePath(): string | undefined {
701
+ return this._builder.caCertificatePath;
702
+ }
703
+
551
704
  /**
552
705
  * Whether TLS certificate validation is skipped. See
553
706
  * {@link ChronicleConnectionStringBuilder.skipTlsValidation}.
@@ -587,20 +740,41 @@ export class ChronicleConnectionString {
587
740
  const builder = new ChronicleConnectionStringBuilder(this.toString());
588
741
  builder.username = username;
589
742
  builder.password = password;
743
+ builder.noAuthentication = false;
590
744
  return new ChronicleConnectionString(builder.build());
591
745
  }
592
746
 
593
747
  withApiKey(apiKey: string): ChronicleConnectionString {
594
748
  const builder = new ChronicleConnectionStringBuilder(this.toString());
595
749
  builder.apiKey = apiKey;
750
+ builder.noAuthentication = false;
596
751
  return new ChronicleConnectionString(builder.build());
597
752
  }
598
753
 
599
- createCredentials(): grpc.ChannelCredentials {
754
+ /**
755
+ * Loads the TLS material the connection string names: the client certificate from `certificatePath` and the
756
+ * certificate authorities from `caCertificatePath`.
757
+ * @throws When a file is missing, unreadable or holds no usable material.
758
+ */
759
+ loadTlsMaterial(): ChronicleTlsMaterial {
760
+ return loadTlsMaterial(this);
761
+ }
762
+
763
+ /**
764
+ * Creates the gRPC channel credentials for this connection string.
765
+ * @param tlsMaterial - The TLS material to use. Defaults to loading what the connection string names.
766
+ */
767
+ createCredentials(tlsMaterial: ChronicleTlsMaterial = loadTlsMaterial(this)): grpc.ChannelCredentials {
600
768
  if (this.disableTls) {
601
769
  return grpc.credentials.createInsecure();
602
770
  }
603
771
 
772
+ if (!tlsMaterial.isEmpty) {
773
+ return grpc.credentials.createFromSecureContext(
774
+ tls.createSecureContext(tlsMaterial.connectOptions(this.skipTlsValidation)),
775
+ { rejectUnauthorized: !this.skipTlsValidation });
776
+ }
777
+
604
778
  if (this.skipTlsValidation) {
605
779
  // Chronicle generates a self-signed certificate in development, and skipTlsValidation
606
780
  // defaults to true so this works without extra configuration. grpc-js has no
@@ -0,0 +1,160 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { execFileSync } from 'node:child_process';
5
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
6
+ import { createServer, type Server } from 'node:https';
7
+ import type { AddressInfo } from 'node:net';
8
+ import { tmpdir } from 'node:os';
9
+ import { join } from 'node:path';
10
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
11
+ import { ChronicleConnectionString } from './ChronicleConnectionString.js';
12
+ import { loadTlsMaterial } from './ChronicleTlsMaterial.js';
13
+ import { fetchOAuthAccessToken } from './fetchOAuthAccessToken.js';
14
+
15
+ const directory = mkdtempSync(join(tmpdir(), 'chronicle-tls-'));
16
+
17
+ function hasOpenSsl(): boolean {
18
+ try {
19
+ execFileSync('openssl', ['version'], { stdio: 'ignore' });
20
+ return true;
21
+ } catch {
22
+ return false;
23
+ }
24
+ }
25
+
26
+ const openSslAvailable = hasOpenSsl();
27
+
28
+ interface Identity {
29
+ certificate: string;
30
+ key: string;
31
+ }
32
+
33
+ function openssl(...args: string[]): void {
34
+ execFileSync('openssl', args, { cwd: directory, stdio: 'ignore' });
35
+ }
36
+
37
+ /** Generates a self-signed certificate valid for localhost, with its PKCS#8 private key. */
38
+ function generateIdentity(name: string): Identity {
39
+ openssl('req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-keyout', `${name}.key`, '-out', `${name}.pem`,
40
+ '-subj', `/CN=${name}`, '-addext', 'subjectAltName=DNS:localhost,IP:127.0.0.1', '-days', '2');
41
+ return { certificate: join(directory, `${name}.pem`), key: join(directory, `${name}.key`) };
42
+ }
43
+
44
+ function connectionStringFor(options: string): ChronicleConnectionString {
45
+ return new ChronicleConnectionString(`chronicle://localhost:35000?${options}`);
46
+ }
47
+
48
+ describe.skipIf(!openSslAvailable)('ChronicleTlsMaterial', () => {
49
+ let server: { identity: Identity; client: Identity; stranger: Identity };
50
+
51
+ beforeAll(() => {
52
+ server = {
53
+ identity: generateIdentity('server'),
54
+ client: generateIdentity('client'),
55
+ stranger: generateIdentity('stranger')
56
+ };
57
+ });
58
+
59
+ afterAll(() => rmSync(directory, { recursive: true, force: true }));
60
+
61
+ describe('when the connection string names no TLS material', () => {
62
+ it('should be empty', () => expect(loadTlsMaterial(connectionStringFor('skipTlsValidation=false')).isEmpty).toBe(true));
63
+ });
64
+
65
+ describe('when the CA certificate file is missing', () => {
66
+ it('should fail even while validation is skipped', () =>
67
+ expect(() => loadTlsMaterial(connectionStringFor('caCertificatePath=%2Fno%2Fsuch.pem'))).toThrow(/Cannot read the CA certificate file/));
68
+ });
69
+
70
+ describe('when the CA certificate file holds no certificates', () => {
71
+ it('should fail', () => {
72
+ const path = join(directory, 'empty.pem');
73
+ writeFileSync(path, 'not a certificate');
74
+ expect(() => loadTlsMaterial(connectionStringFor(`caCertificatePath=${encodeURIComponent(path)}`))).toThrow(/does not contain any PEM certificates/);
75
+ });
76
+ });
77
+
78
+ describe('when a client certificate is a PKCS#12 file with the wrong password', () => {
79
+ it('should fail', () => {
80
+ openssl('pkcs12', '-export', '-in', 'client.pem', '-inkey', 'client.key', '-out', 'client.p12', '-passout', 'pass:changeit');
81
+ const path = encodeURIComponent(join(directory, 'client.p12'));
82
+ expect(() => loadTlsMaterial(connectionStringFor(`certificatePath=${path}&certificatePassword=wrong`))).toThrow(/could not be loaded/);
83
+ expect(loadTlsMaterial(connectionStringFor(`certificatePath=${path}&certificatePassword=changeit`)).isEmpty).toBe(false);
84
+ });
85
+ });
86
+
87
+ describe('when a client certificate is a PEM bundle with the key listed first', () => {
88
+ it('should load', () => {
89
+ const path = join(directory, 'bundle.pem');
90
+ writeFileSync(path, readFileSync(server.client.key, 'latin1') + readFileSync(server.client.certificate, 'latin1'));
91
+ expect(loadTlsMaterial(connectionStringFor(`certificatePath=${encodeURIComponent(path)}`)).isEmpty).toBe(false);
92
+ });
93
+ });
94
+
95
+ describe('when a client certificate PEM has no private key', () => {
96
+ it('should fail', () => {
97
+ expect(() => loadTlsMaterial(connectionStringFor(`certificatePath=${encodeURIComponent(server.client.certificate)}`))).toThrow(/both a certificate and a private key/);
98
+ });
99
+ });
100
+
101
+ describe('when fetching a token from a TLS server', () => {
102
+ const listen = async (requireClientCertificate: boolean): Promise<{ instance: Server; endpoint: string }> => {
103
+ const instance = createServer({
104
+ key: readFileSync(server.identity.key),
105
+ cert: readFileSync(server.identity.certificate),
106
+ ca: readFileSync(server.client.certificate),
107
+ requestCert: requireClientCertificate,
108
+ rejectUnauthorized: requireClientCertificate
109
+ }, (_request, response) => {
110
+ response.setHeader('content-type', 'application/json');
111
+ response.end(JSON.stringify({ access_token: 'token', expires_in: 3600 }));
112
+ });
113
+ await new Promise<void>(resolve => instance.listen(0, '127.0.0.1', resolve));
114
+ return { instance, endpoint: `https://localhost:${(instance.address() as AddressInfo).port}/connect/token` };
115
+ };
116
+
117
+ it('should validate the server against the configured certificate authority', async () => {
118
+ const { instance, endpoint } = await listen(false);
119
+ try {
120
+ const trusted = loadTlsMaterial(connectionStringFor(`caCertificatePath=${encodeURIComponent(server.identity.certificate)}`));
121
+ await expect(fetchOAuthAccessToken(endpoint, 'id', 'secret', false, trusted)).resolves.toMatchObject({ access_token: 'token' });
122
+ } finally {
123
+ instance.close();
124
+ }
125
+ });
126
+
127
+ it('should reject a server the configured certificate authority does not vouch for', async () => {
128
+ const { instance, endpoint } = await listen(false);
129
+ try {
130
+ const stranger = loadTlsMaterial(connectionStringFor(`caCertificatePath=${encodeURIComponent(server.stranger.certificate)}`));
131
+ await expect(fetchOAuthAccessToken(endpoint, 'id', 'secret', false, stranger)).rejects.toThrow();
132
+ } finally {
133
+ instance.close();
134
+ }
135
+ });
136
+
137
+ it('should ignore the certificate authority while validation is skipped', async () => {
138
+ const { instance, endpoint } = await listen(false);
139
+ try {
140
+ const stranger = loadTlsMaterial(connectionStringFor(`caCertificatePath=${encodeURIComponent(server.stranger.certificate)}`));
141
+ await expect(fetchOAuthAccessToken(endpoint, 'id', 'secret', true, stranger)).resolves.toMatchObject({ access_token: 'token' });
142
+ } finally {
143
+ instance.close();
144
+ }
145
+ });
146
+
147
+ it('should present the client certificate to a server that requires one', async () => {
148
+ const { instance, endpoint } = await listen(true);
149
+ try {
150
+ const bundle = join(directory, 'mutual.pem');
151
+ writeFileSync(bundle, readFileSync(server.client.certificate, 'latin1') + readFileSync(server.client.key, 'latin1'));
152
+ const material = loadTlsMaterial(connectionStringFor(`certificatePath=${encodeURIComponent(bundle)}`));
153
+ await expect(fetchOAuthAccessToken(endpoint, 'id', 'secret', true, material)).resolves.toMatchObject({ access_token: 'token' });
154
+ await expect(fetchOAuthAccessToken(endpoint, 'id', 'secret', true)).rejects.toThrow();
155
+ } finally {
156
+ instance.close();
157
+ }
158
+ });
159
+ });
160
+ });
@@ -0,0 +1,121 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { readFileSync } from 'node:fs';
5
+ import { createSecureContext } from 'node:tls';
6
+
7
+ /** The connection string options that name TLS material. */
8
+ export interface ChronicleTlsMaterialSource {
9
+ readonly caCertificatePath?: string;
10
+ readonly certificatePath?: string;
11
+ readonly certificatePassword?: string;
12
+ }
13
+
14
+ /** The Node TLS options a Chronicle connection hands to its HTTPS clients and gRPC channel. */
15
+ export interface ChronicleTlsConnectOptions {
16
+ ca?: Buffer;
17
+ pfx?: Buffer;
18
+ cert?: Buffer;
19
+ key?: Buffer;
20
+ passphrase?: string;
21
+ rejectUnauthorized: boolean;
22
+ }
23
+
24
+ interface ClientIdentity {
25
+ readonly pfx?: Buffer;
26
+ readonly cert?: Buffer;
27
+ readonly key?: Buffer;
28
+ readonly passphrase?: string;
29
+ }
30
+
31
+ const certificateBlock = /-----BEGIN CERTIFICATE-----/;
32
+ const privateKeyBlock = /-----BEGIN (?:ENCRYPTED |RSA |EC )?PRIVATE KEY-----/;
33
+
34
+ function readFile(path: string, description: string): Buffer {
35
+ try {
36
+ return readFileSync(path);
37
+ } catch (error) {
38
+ throw new Error(`Cannot read the ${description} '${path}': ${error instanceof Error ? error.message : String(error)}`, { cause: error });
39
+ }
40
+ }
41
+
42
+ /**
43
+ * The TLS material a connection string names: the client identity from `certificatePath` and the certificate
44
+ * authorities from `caCertificatePath`.
45
+ *
46
+ * It is loaded once when the connection is created, so a missing or unreadable file fails the connection setup
47
+ * instead of every reconnect - and also when validation is skipped or TLS is disabled, so the option cannot lie
48
+ * dormant until validation is switched on.
49
+ */
50
+ export class ChronicleTlsMaterial {
51
+ /** No TLS material beyond the platform defaults. */
52
+ static readonly None = new ChronicleTlsMaterial();
53
+
54
+ constructor(
55
+ private readonly _certificateAuthorities?: Buffer,
56
+ private readonly _identity?: ClientIdentity
57
+ ) {}
58
+
59
+ /** Whether this configures anything beyond the platform defaults. */
60
+ get isEmpty(): boolean {
61
+ return this._certificateAuthorities === undefined && this._identity === undefined;
62
+ }
63
+
64
+ /**
65
+ * The options for a Node TLS client. The certificate authorities replace the system trust store, and
66
+ * only when certificate validation is on.
67
+ */
68
+ connectOptions(skipTlsValidation: boolean): ChronicleTlsConnectOptions {
69
+ return {
70
+ ...(!skipTlsValidation && this._certificateAuthorities ? { ca: this._certificateAuthorities } : {}),
71
+ ...this._identity,
72
+ rejectUnauthorized: !skipTlsValidation
73
+ };
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Loads the TLS material `source` names.
79
+ *
80
+ * `caCertificatePath` is a PEM file with one or more certificate authorities. `certificatePath` is a PKCS#12
81
+ * file (`.p12`/`.pfx`), or a PEM file holding the certificate chain and the private key; `certificatePassword`
82
+ * unlocks either.
83
+ * @throws When a file is missing, unreadable or holds no usable material.
84
+ */
85
+ export function loadTlsMaterial(source: ChronicleTlsMaterialSource): ChronicleTlsMaterial {
86
+ const authorities = source.caCertificatePath ? loadCertificateAuthorities(source.caCertificatePath) : undefined;
87
+ const identity = source.certificatePath ? loadClientIdentity(source.certificatePath, source.certificatePassword) : undefined;
88
+ return authorities === undefined && identity === undefined ? ChronicleTlsMaterial.None : new ChronicleTlsMaterial(authorities, identity);
89
+ }
90
+
91
+ function loadCertificateAuthorities(path: string): Buffer {
92
+ const contents = readFile(path, 'CA certificate file');
93
+ if (!certificateBlock.test(contents.toString('latin1'))) {
94
+ throw new Error(`The CA certificate file '${path}' does not contain any PEM certificates.`);
95
+ }
96
+
97
+ return contents;
98
+ }
99
+
100
+ function loadClientIdentity(path: string, password: string | undefined): ClientIdentity {
101
+ const contents = readFile(path, 'client certificate');
102
+ const text = contents.toString('latin1');
103
+ const isPem = text.includes('-----BEGIN');
104
+ if (isPem && (!certificateBlock.test(text) || !privateKeyBlock.test(text))) {
105
+ throw new Error(`The client certificate '${path}' must hold both a certificate and a private key.`);
106
+ }
107
+
108
+ const identity: ClientIdentity = isPem
109
+ ? { cert: contents, key: contents, passphrase: password }
110
+ : { pfx: contents, passphrase: password };
111
+
112
+ // Building the context validates the password and that the key belongs to the certificate, now rather
113
+ // than on the first connection attempt.
114
+ try {
115
+ createSecureContext(identity);
116
+ } catch (error) {
117
+ throw new Error(`The client certificate '${path}' could not be loaded: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
118
+ }
119
+
120
+ return identity;
121
+ }