@serve.zone/interfaces 32.76.0 → 32.78.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.
@@ -6,15 +6,21 @@ import {
6
6
  validateControllerCounter,
7
7
  validateControllerIdentifier,
8
8
  validateControllerNonNegativeInteger,
9
+ validateControllerStrictJson,
9
10
  } from '../private/controllercontract.js';
10
11
  import { readDataElements, readDataProperty, readExactDataRecord } from '../private/dataproperties.js';
11
- import { parseCanonicalIpAddress } from '../private/ipaddress.js';
12
+ import { ipv4PrefixOfMapped, parseCanonicalIpAddress } from '../private/ipaddress.js';
12
13
  import type { TCompleteKeyList } from '../private/keylist.js';
13
14
  import { networkDigest } from '../private/networkcontract.js';
14
15
  import { isCanonicalTokenList } from '../private/tokenlist.js';
16
+ import { isGatewayClientIdText } from '../private/gatewayclientid.js';
17
+ import { clusterIngressLimits, validateClusterRouteSourceAllowList } from './clusteringress.js';
15
18
  import { type IControllerPeerSet, validateControllerPeerSet } from './controller.js';
16
19
  import type { TSha256Digest } from './immutableimage.js';
20
+ import { isLocationName } from './location.js';
17
21
  import { isReleaseVersion } from './releaseversion.js';
22
+ import { runtimeSessionContract } from './runtimesession.js';
23
+ import { externalGatewayBootstrapContract } from './settings.js';
18
24
 
19
25
  /*
20
26
  * The gateway connector (AGL-1182): a gateway (dcrouter) dials its controller (Cloudly) on the
@@ -57,23 +63,57 @@ export const gatewayConnectorContract = Object.freeze({
57
63
  maximumRefusalDetailLength: 1024,
58
64
  maximumStorageBackendLength: 64,
59
65
  maximumStoragePathLength: 4096,
66
+ /**
67
+ * The longest `adoptGateway` credential bearer, in UTF-8 bytes: the credential bound of the
68
+ * Cloudly client session the bearer authenticates (`runtimeSessionContract.maximumCredentialBytes`).
69
+ */
70
+ maximumBearerBytes: runtimeSessionContract.maximumCredentialBytes,
60
71
  } as const);
61
72
 
62
73
  /**
63
- * One gateway as its controller records it.
74
+ * True for a gateway name: the location name rule (`isLocationName`), one lowercase RFC 1123 label
75
+ * of 1 to 63 characters. A controller keeps each name on one of its gateways.
76
+ */
77
+ export const isGatewayName = (valueArg: unknown): valueArg is string => isLocationName(valueArg);
78
+
79
+ /**
80
+ * One gateway as its controller records it (`validateGateway`).
64
81
  *
65
82
  * `connection` says how the two reach each other. A `legacy` gateway is the dcrouter the
66
83
  * controller still dials at its URL as the named gateway client. An `adopted` gateway dials the
67
84
  * controller and is never dialled, so it carries no URL.
85
+ *
86
+ * The controller gateway is the one gateway whose gateway client the controller's own
87
+ * gateway-client calls (`requests.gateway`, `requests.mail` and `requests.webpush` under control
88
+ * auth) are bound to: a `legacy` gateway by its `gatewayClientId`, an `adopted` one by a non-null
89
+ * `controllerGatewayClientId`. A controller holds at most one.
68
90
  */
69
91
  export interface IGateway {
70
92
  id: string;
93
+ /** Unique among the controller's gateways; `isGatewayName`. */
71
94
  name: string;
72
95
  /** The location the gateway stands in (`data.ILocation`); every gateway stands in one. */
73
96
  locationId: string;
74
- forwardSourceAddresses: string[];
97
+ /**
98
+ * The sources the gateway's forwarded connections arrive from at a node, as canonical address
99
+ * prefixes (`192.0.2.10/32`) under the rules of `validateClusterRouteSourceAllowList`; empty when
100
+ * none is known. A cluster ingress admits a non-public hostname only from the union of every
101
+ * gateway's prefixes. The plain addresses a gateway states (`IGatewayAdoptionFacts`,
102
+ * `IGatewayStatusDocument` `forwardSourceAddresses`) become host prefixes here: `/32` for IPv4,
103
+ * `/128` for IPv6.
104
+ */
105
+ forwardSourcePrefixes: string[];
75
106
  connection:
76
- | { kind: 'legacy'; url: string; gatewayClientId: string }
107
+ | {
108
+ kind: 'legacy';
109
+ /**
110
+ * The dcrouter URL the controller dials: an absolute `http` or `https` URL in its canonical
111
+ * spelling, without userinfo, query, fragment or trailing slash.
112
+ */
113
+ url: string;
114
+ /** The gateway client the controller's calls run as. */
115
+ gatewayClientId: string;
116
+ }
77
117
  | {
78
118
  kind: 'adopted';
79
119
  /** Unix milliseconds on the controller's clock. */
@@ -82,6 +122,17 @@ export interface IGateway {
82
122
  machineUserId: string;
83
123
  /** Raised by every re-adoption; the previous generation is dead from then on. */
84
124
  credentialGeneration: number;
125
+ /**
126
+ * The one gateway client the controller's gateway-client calls are bound to over the
127
+ * connector socket.
128
+ *
129
+ * - A `new` adoption binds `null`; the gateway then refuses those calls
130
+ * `gateway-client-unbound`.
131
+ * - An `existing` re-adoption of a legacy gateway moves its `gatewayClientId` into this field.
132
+ * - A re-adoption of an already adopted gateway keeps this field unchanged, `null` included.
133
+ * - No operation changes a non-null binding to another value.
134
+ */
135
+ controllerGatewayClientId: string | null;
85
136
  };
86
137
  }
87
138
 
@@ -104,6 +155,44 @@ export interface IGatewayAdoptionFacts {
104
155
  * `compareWireTokens`, each once). A controller never pushes an area the gateway does not name.
105
156
  */
106
157
  controllerAreas: TGatewayConfigArea[];
158
+ /**
159
+ * What the gateway is adopted as, from its own connector store: `null` when it was never
160
+ * adopted, otherwise the controller and the gateway record it is adopted as.
161
+ *
162
+ * Not a security control: a gateway can state anything here, and the adoption code stays the
163
+ * authority. It only keeps two honest stores consistent. The controller checks it inside the
164
+ * transaction that would consume the code, after the code checks (`adoption-code-unknown`,
165
+ * `adoption-code-expired`, `adoption-code-used`), and refuses with the code left unconsumed:
166
+ *
167
+ * - `controller-mismatch` when `controllerId` is not this controller;
168
+ * - `gateway-mismatch` for a `new` code while `adoptedAs` is set;
169
+ * - `gateway-mismatch` for an `existing` code naming another gateway than `gatewayId`.
170
+ *
171
+ * Otherwise, `null` included, the adoption proceeds.
172
+ */
173
+ adoptedAs: { controllerId: string; gatewayId: string } | null;
174
+ }
175
+
176
+ /**
177
+ * What the controller answers a gateway that redeemed an adoption code (`adoptGateway`), validated
178
+ * by `validateAdoptGatewayResponse`. Answered once; keep it out of logs, it carries the bearer.
179
+ */
180
+ export interface IAdoptGatewayResponse {
181
+ gatewayId: string;
182
+ /** The gateway stores it and refuses any other controller and any older epoch from then on. */
183
+ controller: IControllerPeerSet;
184
+ /**
185
+ * The gateway authenticates its socket as `userId` with `bearer`, at most
186
+ * `gatewayConnectorContract.maximumBearerBytes` UTF-8 bytes; `generation` is the credential
187
+ * generation (`IGateway` `credentialGeneration`).
188
+ */
189
+ credential: { userId: string; generation: number; bearer: string };
190
+ /**
191
+ * The gateway client the controller's existing `requests.gateway`, `requests.mail` and
192
+ * `requests.webpush` calls are bound to once they run over the connector socket; `null` when
193
+ * the controller binds none (`IGateway` `controllerGatewayClientId`).
194
+ */
195
+ controllerGatewayClientId: string | null;
107
196
  }
108
197
 
109
198
  /** One whole area table of a desired state. */
@@ -129,7 +218,7 @@ export interface IGatewayAreaTable {
129
218
  *
130
219
  * Documents are ordered by `(epoch, revision)` (`data.compareControllerRevisionOrder`): a newer one
131
220
  * is applied, an equal one is an idempotent replay answered with the stored report, and an older
132
- * one is refused `stale`.
221
+ * one is refused `desired-state-stale` (`gatewayConnectorRefusals`).
133
222
  */
134
223
  export interface IGatewayDesiredState {
135
224
  gatewayId: string;
@@ -141,14 +230,115 @@ export interface IGatewayDesiredState {
141
230
  }
142
231
 
143
232
  /**
144
- * Every reason a gateway refuses an area of a desired state. Each is reported per area in
145
- * `IGatewayAreaApplyState.refusal`.
233
+ * Every reason one side of the gateway connector answers instead of a request. The controller
234
+ * answers them instead of `adoptGateway`, `registerGatewaySession`, `pushGatewayStatus` and
235
+ * `createGatewayAdoptionCode`, and instead of a legacy gateway setting it no longer owns. The
236
+ * gateway answers them instead of a whole `applyDesiredState` document, an `exportGatewayArea`, a
237
+ * gateway-client call on the connector socket, or an HTTP call authenticated with a token of its
238
+ * controller-bound gateway client.
239
+ *
240
+ * Each is answered as a `TypedResponseError` whose `errorData` is
241
+ * `IGatewayConnectorRefusalErrorData` and whose text carries the detail, so a peer acts on the code
242
+ * without reading prose. A refusal of one area inside an applied document is none of these: the
243
+ * gateway reports it per area (`gatewayApplyRefusals`). An adoption code that names no location is
244
+ * refused `location-not-found` from `locationRefusals`.
146
245
  */
147
- export const gatewayApplyRefusals = Object.freeze([
148
- /** The document is older than the one the gateway applied, by `(epoch, revision)`. */
149
- 'stale',
150
- /** The document comes from another controller than the one that adopted the gateway. */
246
+ export const gatewayConnectorRefusals = Object.freeze([
247
+ /** No adoption code has the value the gateway redeemed. */
248
+ 'adoption-code-unknown',
249
+ /** The adoption code's lifetime ended before the gateway redeemed it. */
250
+ 'adoption-code-expired',
251
+ /** The adoption code was redeemed already; a code adopts once. */
252
+ 'adoption-code-used',
253
+ /** A code for a new gateway names a name another gateway of this controller carries. */
254
+ 'gateway-name-taken',
255
+ /** A code for an existing gateway, or a gateway identity, names no gateway the controller records. */
256
+ 'gateway-not-found',
257
+ /** The controller's public origin is not a canonical `https` origin, so no gateway can adopt it. */
258
+ 'controller-origin-invalid',
259
+ /** The socket authenticated with a gateway credential generation a re-adoption has replaced. */
260
+ 'credential-generation-stale',
261
+ /** A hello whose `registrationSequence` does not exceed the one the same socket sent before. */
262
+ 'registration-sequence-not-advancing',
263
+ /**
264
+ * The peer belongs to another controller: a hello whose `known.controllerId` names another
265
+ * controller, a desired state whose `controllerId` is not the controller that adopted the
266
+ * gateway, or an `adoptGateway` whose facts' `adoptedAs.controllerId` is not this controller
267
+ * (the code stays unconsumed). Nothing is pushed, applied or adopted.
268
+ */
151
269
  'controller-mismatch',
270
+ /**
271
+ * An epoch above the one the refusing side holds: a hello whose `known.epoch` is above this
272
+ * controller's epoch (nothing is pushed), or a desired state whose `epoch` is above the
273
+ * controller epoch the gateway stored (nothing is applied or stored).
274
+ */
275
+ 'controller-epoch-ahead',
276
+ /** A gateway call on a socket that has no accepted `registerGatewaySession`. */
277
+ 'gateway-session-required',
278
+ /**
279
+ * A status push sooner than `gatewayConnectorContract.minimumStatusPushIntervalMs` after the last
280
+ * accepted one. The gateway sends its newest document again once the interval has passed.
281
+ */
282
+ 'status-too-frequent',
283
+ /**
284
+ * The controller gateway is adopted. The controller answers it to an edit of the legacy gateway
285
+ * URL or client id setting and to the legacy gateway credential bootstrap, which no longer apply.
286
+ * The gateway answers it to any HTTP call with a token of its controller-bound gateway client
287
+ * (`controllerGatewayClientId`): that client is served on the connector socket only.
288
+ */
289
+ 'controller-gateway-adopted',
290
+ /**
291
+ * The request failed its contract validator (`validateGatewayDesiredState` for a desired state);
292
+ * the error text carries the validator's sentences.
293
+ */
294
+ 'request-invalid',
295
+ /**
296
+ * A desired state older by `(epoch, revision)` than the one the gateway applied; the error text
297
+ * names the applied epoch and revision. An equal one is no refusal: the gateway answers it with
298
+ * the stored report.
299
+ */
300
+ 'desired-state-stale',
301
+ /**
302
+ * The request names another gateway: a desired state whose `gatewayId` is not the gateway's own
303
+ * (nothing is applied), or an `adoptGateway` whose facts' `adoptedAs` contradicts the code: a
304
+ * `new` code while `adoptedAs` is set, or an `existing` code for another gateway than
305
+ * `adoptedAs.gatewayId` (nothing is adopted and the code stays unconsumed).
306
+ */
307
+ 'gateway-mismatch',
308
+ /**
309
+ * An `exportGatewayArea` for an area the gateway does not take from a controller
310
+ * (`controllerAreas`); the same meaning as the per-area refusal of that name.
311
+ */
312
+ 'unsupported-area',
313
+ /**
314
+ * A gateway-client call on the connector socket of a gateway adopted without a controller binding
315
+ * (`controllerGatewayClientId: null`).
316
+ */
317
+ 'gateway-client-unbound',
318
+ ] as const);
319
+
320
+ /** One of the reasons one side of the gateway connector answers instead of a request. */
321
+ export type TGatewayConnectorRefusal = typeof gatewayConnectorRefusals[number];
322
+
323
+ /** A connector refusal as `TypedResponseError.errorData`; the error text carries its detail. */
324
+ export interface IGatewayConnectorRefusalErrorData {
325
+ code: TGatewayConnectorRefusal;
326
+ /** Never: the same request is refused again until the state the code names has changed. */
327
+ retryable: false;
328
+ }
329
+
330
+ /** True for one of `gatewayConnectorRefusals`. */
331
+ export const isGatewayConnectorRefusal = (valueArg: unknown): valueArg is TGatewayConnectorRefusal => (
332
+ (gatewayConnectorRefusals as readonly unknown[]).includes(valueArg)
333
+ );
334
+
335
+ /**
336
+ * Every reason a gateway refuses an area of a desired state it accepted as a whole. Each is
337
+ * reported per area in `IGatewayAreaApplyState.refusal`. A refusal of the whole document (stale,
338
+ * from another controller, for another gateway, invalid) is answered on the request instead
339
+ * (`gatewayConnectorRefusals`) and never stored in a report.
340
+ */
341
+ export const gatewayApplyRefusals = Object.freeze([
152
342
  /** A table failed validation; a gateway validates every table first and then applies none. */
153
343
  'invalid-table',
154
344
  /** The document carries an area the gateway does not take from a controller (`controllerAreas`). */
@@ -315,9 +505,18 @@ export const computeGatewayAreaTableDigest = async (
315
505
 
316
506
  const adoptionFactsKeyList = [
317
507
  'dcrouterVersion', 'interfacesVersion', 'hostname', 'publicIps', 'proxyIps', 'forwardSourceAddresses',
318
- 'controllerAreas',
508
+ 'controllerAreas', 'adoptedAs',
319
509
  ] as const;
320
510
  const adoptionFactsKeys: TCompleteKeyList<IGatewayAdoptionFacts, typeof adoptionFactsKeyList> = adoptionFactsKeyList;
511
+ type TGatewayAdoptedAs = NonNullable<IGatewayAdoptionFacts['adoptedAs']>;
512
+ const adoptedAsKeyList = ['controllerId', 'gatewayId'] as const;
513
+ const adoptedAsKeys: TCompleteKeyList<TGatewayAdoptedAs, typeof adoptedAsKeyList> = adoptedAsKeyList;
514
+ const adoptGatewayResponseKeyList = ['gatewayId', 'controller', 'credential', 'controllerGatewayClientId'] as const;
515
+ const adoptGatewayResponseKeys: TCompleteKeyList<IAdoptGatewayResponse, typeof adoptGatewayResponseKeyList> =
516
+ adoptGatewayResponseKeyList;
517
+ const adoptionCredentialKeyList = ['userId', 'generation', 'bearer'] as const;
518
+ const adoptionCredentialKeys: TCompleteKeyList<IAdoptGatewayResponse['credential'], typeof adoptionCredentialKeyList> =
519
+ adoptionCredentialKeyList;
321
520
  const areaTableKeyList = ['area', 'digest', 'content', 'takeover'] as const;
322
521
  const areaTableKeys: TCompleteKeyList<IGatewayAreaTable, typeof areaTableKeyList> = areaTableKeyList;
323
522
  const desiredStateKeyList = ['gatewayId', 'controllerId', 'epoch', 'revision', 'areas'] as const;
@@ -340,6 +539,18 @@ const registerSessionKeys: TCompleteKeyList<IRegisterGatewaySessionRequest, type
340
539
  registerSessionKeyList;
341
540
  const areaExportKeyList = ['area', 'digest', 'content'] as const;
342
541
  const areaExportKeys: TCompleteKeyList<IGatewayAreaExport, typeof areaExportKeyList> = areaExportKeyList;
542
+ const gatewayKeyList = ['id', 'name', 'locationId', 'forwardSourcePrefixes', 'connection'] as const;
543
+ const gatewayKeys: TCompleteKeyList<IGateway, typeof gatewayKeyList> = gatewayKeyList;
544
+ type TLegacyGatewayConnection = Extract<IGateway['connection'], { kind: 'legacy' }>;
545
+ const legacyConnectionKeyList = ['kind', 'url', 'gatewayClientId'] as const;
546
+ const legacyConnectionKeys: TCompleteKeyList<TLegacyGatewayConnection, typeof legacyConnectionKeyList> =
547
+ legacyConnectionKeyList;
548
+ type TAdoptedGatewayConnection = Extract<IGateway['connection'], { kind: 'adopted' }>;
549
+ const adoptedConnectionKeyList = [
550
+ 'kind', 'adoptedAt', 'machineUserId', 'credentialGeneration', 'controllerGatewayClientId',
551
+ ] as const;
552
+ const adoptedConnectionKeys: TCompleteKeyList<TAdoptedGatewayConnection, typeof adoptedConnectionKeyList> =
553
+ adoptedConnectionKeyList;
343
554
 
344
555
  const areaOwners: readonly IGatewayAreaApplyState['owner'][] = ['controller', 'gateway'];
345
556
  const areaApplyStates: readonly IGatewayAreaApplyState['state'][] = ['applied', 'rejected', 'not-attempted'];
@@ -386,11 +597,16 @@ const validateAddresses = (valueArg: unknown, pathArg: string): string[] => {
386
597
  if (addresses === null) {
387
598
  return [`${pathArg} must be a dense list of at most ${gatewayConnectorContract.maximumAddresses} addresses`];
388
599
  }
389
- const errors = addresses.flatMap((addressArg, indexArg) => (
390
- parseCanonicalIpAddress(addressArg) === null
391
- ? [`${pathArg}[${indexArg}] must be a canonical IPv4 or IPv6 address`]
392
- : []
393
- ));
600
+ const errors = addresses.flatMap((addressArg, indexArg) => {
601
+ const address = parseCanonicalIpAddress(addressArg);
602
+ if (address === null) {
603
+ return [`${pathArg}[${indexArg}] must be a canonical IPv4 or IPv6 address`];
604
+ }
605
+ // An IPv4 source is stated as IPv4, so its host prefix is one the cluster allow-list admits.
606
+ return ipv4PrefixOfMapped({ family: address.family, network: address.value, length: 128 }) === null
607
+ ? []
608
+ : [`${pathArg}[${indexArg}] must not be IPv4-mapped; write the IPv4 address`];
609
+ });
394
610
  if (new Set(addresses).size !== addresses.length) {
395
611
  errors.push(`${pathArg} must name each address once`);
396
612
  }
@@ -424,15 +640,6 @@ const validateKeyedList = (
424
640
  return errors;
425
641
  };
426
642
 
427
- const validateStrictJson = (valueArg: unknown, pathArg: string): string[] => {
428
- try {
429
- canonicalizeStrictJson(valueArg, failAreaTable, pathArg);
430
- return [];
431
- } catch {
432
- return [`${pathArg} must be strict canonical JSON: safe integers only, no undefined, cycle or accessor`];
433
- }
434
- };
435
-
436
643
  const validateAreaTable = (valueArg: unknown, pathArg: string): string[] => {
437
644
  const record = readExactDataRecord(valueArg, areaTableKeys);
438
645
  if (record === null) {
@@ -441,7 +648,7 @@ const validateAreaTable = (valueArg: unknown, pathArg: string): string[] => {
441
648
  const errors = [
442
649
  ...validateArea(record.area, `${pathArg} area`),
443
650
  ...validateDigest(record.digest, `${pathArg} digest`),
444
- ...validateStrictJson(record.content, `${pathArg} content`),
651
+ ...validateControllerStrictJson(record.content, `${pathArg} content`),
445
652
  ];
446
653
  if (record.takeover !== null) {
447
654
  const takeover = readExactDataRecord(record.takeover, ['localDigest']);
@@ -458,7 +665,7 @@ const validateAreaTable = (valueArg: unknown, pathArg: string): string[] => {
458
665
  * The envelope only: every table's digest has the digest form and its content is strict canonical
459
666
  * JSON, but whether the digest is `computeGatewayAreaTableDigest` of the content, what the content
460
667
  * of an area must hold, and how the document orders against the one applied are the gateway's to
461
- * judge (`invalid-table`, `stale`).
668
+ * judge (`invalid-table`, `desired-state-stale`).
462
669
  */
463
670
  export const validateGatewayDesiredState = (
464
671
  valueArg: unknown,
@@ -556,9 +763,20 @@ export const validateGatewayAdoptionFacts = (
556
763
  ...validateAddresses(record.proxyIps, `${pathArg} proxyIps`),
557
764
  ...validateAddresses(record.forwardSourceAddresses, `${pathArg} forwardSourceAddresses`),
558
765
  ...validateControllerAreas(record.controllerAreas, `${pathArg} controllerAreas`),
766
+ ...validateNullable(record.adoptedAs, `${pathArg} adoptedAs`, validateAdoptedAs),
559
767
  ];
560
768
  };
561
769
 
770
+ const validateAdoptedAs = (valueArg: unknown, pathArg: string): string[] => {
771
+ const record = readExactDataRecord(valueArg, adoptedAsKeys);
772
+ return record === null
773
+ ? [`${pathArg} must be null or use its exact schema`]
774
+ : [
775
+ ...validateControllerIdentifier(record.controllerId, `${pathArg} controllerId`),
776
+ ...validateControllerIdentifier(record.gatewayId, `${pathArg} gatewayId`),
777
+ ];
778
+ };
779
+
562
780
  /** The range as data, or the reason it is refused. */
563
781
  const readPortRange = (valueArg: unknown, pathArg: string): IGatewayPortRange | string => {
564
782
  const record = readExactDataRecord(valueArg, ['from', 'to']);
@@ -709,6 +927,145 @@ export const validateGatewayAreaExport = (
709
927
  return [
710
928
  ...validateArea(record.area, `${pathArg} area`),
711
929
  ...validateDigest(record.digest, `${pathArg} digest`),
712
- ...validateStrictJson(record.content, `${pathArg} content`),
930
+ ...validateControllerStrictJson(record.content, `${pathArg} content`),
713
931
  ];
714
932
  };
933
+
934
+ const validateGatewayClientId = (valueArg: unknown, pathArg: string): string[] => (
935
+ isGatewayClientIdText(valueArg)
936
+ ? []
937
+ : [`${pathArg} must be 1 to ${externalGatewayBootstrapContract.maximumGatewayClientIdLength} visible ASCII `
938
+ + 'characters']
939
+ );
940
+
941
+ /** The host of a legacy gateway URL: an IPv6 literal, or lowercase RFC 1123 labels (IPv4 included). */
942
+ const isLegacyGatewayUrlHost = (hostnameArg: string): boolean => (
943
+ /^\[[0-9a-f:.]+\]$/.test(hostnameArg)
944
+ || (hostnameArg.length <= gatewayConnectorContract.maximumHostnameLength
945
+ && hostnameArg.split('.').every((labelArg) => dnsZoneLabel.test(labelArg)))
946
+ );
947
+
948
+ const validateLegacyGatewayUrl = (valueArg: unknown, pathArg: string): string[] => {
949
+ const maximum = externalGatewayBootstrapContract.maximumGatewayUrlLength;
950
+ const refusal = [`${pathArg} must be an absolute http or https URL of at most ${maximum} characters in its `
951
+ + 'canonical spelling, without userinfo, query, fragment or trailing slash'];
952
+ if (typeof valueArg !== 'string' || valueArg.length === 0 || valueArg.length > maximum) {
953
+ return refusal;
954
+ }
955
+ let parsed: URL;
956
+ try {
957
+ parsed = new URL(valueArg);
958
+ } catch {
959
+ return refusal;
960
+ }
961
+ return (parsed.protocol === 'http:' || parsed.protocol === 'https:')
962
+ && parsed.username === '' && parsed.password === '' && parsed.search === '' && parsed.hash === ''
963
+ && isLegacyGatewayUrlHost(parsed.hostname)
964
+ && !valueArg.endsWith('/')
965
+ && parsed.href.replace(/\/+$/, '') === valueArg
966
+ ? []
967
+ : refusal;
968
+ };
969
+
970
+ /** 0 to the allowlist's maximum prefixes; a non-empty list follows `validateClusterRouteSourceAllowList`. */
971
+ const validateForwardSourcePrefixes = (valueArg: unknown, pathArg: string): string[] => {
972
+ const maximum = clusterIngressLimits.maximumSourceAllowListEntries;
973
+ const prefixes = readDataElements(valueArg, maximum);
974
+ if (prefixes === null) {
975
+ return [`${pathArg} must list 0 to ${maximum} address prefixes`];
976
+ }
977
+ return prefixes.length === 0 ? [] : validateClusterRouteSourceAllowList(valueArg, pathArg);
978
+ };
979
+
980
+ const validateGatewayConnection = (valueArg: unknown, pathArg: string): string[] => {
981
+ const kind = readDataProperty(valueArg, 'kind')?.value;
982
+ if (kind === 'legacy') {
983
+ const record = readExactDataRecord(valueArg, legacyConnectionKeys);
984
+ return record === null
985
+ ? [`${pathArg} must use the exact legacy schema`]
986
+ : [
987
+ ...validateLegacyGatewayUrl(record.url, `${pathArg} url`),
988
+ ...validateGatewayClientId(record.gatewayClientId, `${pathArg} gatewayClientId`),
989
+ ];
990
+ }
991
+ if (kind === 'adopted') {
992
+ const record = readExactDataRecord(valueArg, adoptedConnectionKeys);
993
+ return record === null
994
+ ? [`${pathArg} must use the exact adopted schema`]
995
+ : [
996
+ ...validateControllerNonNegativeInteger(record.adoptedAt, `${pathArg} adoptedAt`),
997
+ ...validateControllerIdentifier(record.machineUserId, `${pathArg} machineUserId`),
998
+ ...validateControllerCounter(record.credentialGeneration, `${pathArg} credentialGeneration`),
999
+ ...validateNullable(record.controllerGatewayClientId, `${pathArg} controllerGatewayClientId`,
1000
+ validateGatewayClientId),
1001
+ ];
1002
+ }
1003
+ return [`${pathArg} kind must be one of legacy, adopted`];
1004
+ };
1005
+
1006
+ /**
1007
+ * Validates one gateway record and names every reason it is refused.
1008
+ *
1009
+ * The record alone: whether its name is unique, its location exists and at most one gateway is the
1010
+ * controller gateway is the controller's to judge against the gateways it records.
1011
+ */
1012
+ export const validateGateway = (
1013
+ valueArg: unknown,
1014
+ pathArg = 'gateway',
1015
+ ): string[] => {
1016
+ const record = readExactDataRecord(valueArg, gatewayKeys);
1017
+ if (record === null) {
1018
+ return [`${pathArg} must use its exact schema`];
1019
+ }
1020
+ return [
1021
+ ...validateControllerIdentifier(record.id, `${pathArg} id`),
1022
+ ...(isGatewayName(record.name)
1023
+ ? []
1024
+ : [`${pathArg} name must be one lowercase RFC 1123 label of 1 to 63 characters`]),
1025
+ ...validateControllerIdentifier(record.locationId, `${pathArg} locationId`),
1026
+ ...validateForwardSourcePrefixes(record.forwardSourcePrefixes, `${pathArg} forwardSourcePrefixes`),
1027
+ ...validateGatewayConnection(record.connection, `${pathArg} connection`),
1028
+ ];
1029
+ };
1030
+
1031
+ const utf8Encoder = new TextEncoder();
1032
+
1033
+ /** A bearer of 1 to `maximumBearerBytes` UTF-8 bytes; the refusal names the field, never the value. */
1034
+ const validateBearer = (valueArg: unknown, pathArg: string): string[] => (
1035
+ typeof valueArg === 'string' && valueArg.length > 0
1036
+ && utf8Encoder.encode(valueArg).byteLength <= gatewayConnectorContract.maximumBearerBytes
1037
+ ? []
1038
+ : [`${pathArg} must be a string of 1 to ${gatewayConnectorContract.maximumBearerBytes} UTF-8 bytes`]
1039
+ );
1040
+
1041
+ /**
1042
+ * Validates the controller's whole `adoptGateway` answer and names every reason it is refused. A
1043
+ * gateway checks the answer with this before it writes anything. No refusal carries the bearer.
1044
+ *
1045
+ * The answer alone: whether `controllerGatewayClientId` names a gateway client the gateway holds is
1046
+ * the gateway's to judge against its own store.
1047
+ */
1048
+ export const validateAdoptGatewayResponse = (
1049
+ valueArg: unknown,
1050
+ pathArg = 'adopt gateway response',
1051
+ ): string[] => {
1052
+ const record = readExactDataRecord(valueArg, adoptGatewayResponseKeys);
1053
+ if (record === null) {
1054
+ return [`${pathArg} must use its exact schema`];
1055
+ }
1056
+ const errors = [
1057
+ ...validateControllerIdentifier(record.gatewayId, `${pathArg} gatewayId`),
1058
+ ...validateControllerPeerSet(record.controller, `${pathArg} controller`),
1059
+ ];
1060
+ const credential = readExactDataRecord(record.credential, adoptionCredentialKeys);
1061
+ errors.push(...(credential === null
1062
+ ? [`${pathArg} credential must use its exact schema`]
1063
+ : [
1064
+ ...validateControllerIdentifier(credential.userId, `${pathArg} credential userId`),
1065
+ ...validateControllerCounter(credential.generation, `${pathArg} credential generation`),
1066
+ ...validateBearer(credential.bearer, `${pathArg} credential bearer`),
1067
+ ]));
1068
+ errors.push(...validateNullable(record.controllerGatewayClientId, `${pathArg} controllerGatewayClientId`,
1069
+ validateGatewayClientId));
1070
+ return errors;
1071
+ };
package/ts/data/user.ts CHANGED
@@ -142,7 +142,12 @@ export interface IIdentity extends IIdentityCredential {
142
142
  name: string;
143
143
  userId: string;
144
144
  type: 'machine' | 'human';
145
- role: 'admin' | 'user' | 'api' | 'cluster';
145
+ /**
146
+ * `gateway` is a gateway's (dcrouter's) machine identity, minted by its adoption
147
+ * (`adoptGateway`). It is its own role so every guard that names roles excludes it by type;
148
+ * Cloudly admits it only on the gateway's own connector calls.
149
+ */
150
+ role: 'admin' | 'user' | 'api' | 'cluster' | 'gateway';
146
151
  expiresAt: number;
147
152
  }
148
153
 
@@ -150,7 +155,8 @@ export interface IUser {
150
155
  id: string;
151
156
  data: {
152
157
  type: 'machine' | 'human';
153
- role: 'admin' | 'user' | 'api' | 'cluster';
158
+ /** As `IIdentity.role`; a `gateway` user is a machine user. */
159
+ role: 'admin' | 'user' | 'api' | 'cluster' | 'gateway';
154
160
  username?: string;
155
161
  password?: string;
156
162
  tokens?: IToken[];
@@ -2,6 +2,7 @@
2
2
  * The value rules the controller contracts (`data/controller.ts`, `data/gatewayconnector.ts`) share,
3
3
  * stated as refusals a validator can collect so it names every reason a body is refused.
4
4
  */
5
+ import { canonicalizeStrictJson } from './canonicaljson.js';
5
6
  import { networkId } from './networkcontract.js';
6
7
 
7
8
  /** The generic canonical identifier: the rule `networkId` reads, never a second spelling of it. */
@@ -29,6 +30,20 @@ export const validateControllerNonNegativeInteger = (valueArg: unknown, pathArg:
29
30
  : [`${pathArg} must be a non-negative safe integer`]
30
31
  );
31
32
 
33
+ const failStrictJson = (reasonArg: string): never => {
34
+ throw new Error(`Controller contract value rejected: ${reasonArg}.`);
35
+ };
36
+
37
+ /** A value that is strict canonical JSON: safe integers only, no `undefined`, cycle or accessor. */
38
+ export const validateControllerStrictJson = (valueArg: unknown, pathArg: string): string[] => {
39
+ try {
40
+ canonicalizeStrictJson(valueArg, failStrictJson, pathArg);
41
+ return [];
42
+ } catch {
43
+ return [`${pathArg} must be strict canonical JSON: safe integers only, no undefined, cycle or accessor`];
44
+ }
45
+ };
46
+
32
47
  /** A canonical `https` origin: no userinfo, path, query, fragment, trailing slash or default port. */
33
48
  export const validateControllerOrigin = (
34
49
  valueArg: unknown,
@@ -0,0 +1,13 @@
1
+ import { externalGatewayBootstrapContract } from '../data/settings.js';
2
+
3
+ /**
4
+ * The one rule a gateway client id is stated in: 1 to
5
+ * `externalGatewayBootstrapContract.maximumGatewayClientIdLength` visible ASCII characters, no
6
+ * whitespace. The id is dcrouter's; this only refuses what could never be one.
7
+ */
8
+ export const isGatewayClientIdText = (valueArg: unknown): valueArg is string => (
9
+ typeof valueArg === 'string'
10
+ && valueArg.length > 0
11
+ && valueArg.length <= externalGatewayBootstrapContract.maximumGatewayClientIdLength
12
+ && /^[\x21-\x7e]+$/.test(valueArg)
13
+ );
@@ -31,6 +31,11 @@ import type { IMailOverviewDomain, IMailOverviewEmail } from './mail.js';
31
31
  * envelope used by the newer mail contracts. The method strings
32
32
  * 'exportCertificate' and 'importCertificate' likewise keep their deployed
33
33
  * names and deliberately lack a gateway prefix.
34
+ *
35
+ * Over the gateway connector socket an adopted gateway (`data.IGateway`) serves its controller's
36
+ * gateway-client calls without a credential: the socket is authenticated as the gateway and the
37
+ * calls are bound to its `controllerGatewayClientId`. The credential handover
38
+ * (`provisionGatewayClientCredential`, `finalizeGatewayClientCredential`) stays on HTTP.
34
39
  */
35
40
 
36
41
  export interface IReq_GetGatewayCapabilities extends plugins.typedrequestInterfaces.implementsTR<
@@ -257,7 +262,11 @@ export interface IReq_SyncGatewayClientDnsRecord extends plugins.typedrequestInt
257
262
  > {
258
263
  method: 'syncGatewayClientDnsRecord';
259
264
  request: {
260
- apiToken: string;
265
+ /**
266
+ * The gateway client's credential. Required over HTTP, omitted over the connector socket, where
267
+ * the gateway client is the controller-bound one (`data.IGateway` `controllerGatewayClientId`).
268
+ */
269
+ apiToken?: string;
261
270
  identity?: never;
262
271
  ownership: IGatewayClientHostnameOwnership;
263
272
  } & (
@@ -282,7 +291,11 @@ export interface IReq_GetGatewayClientCertificate extends plugins.typedrequestIn
282
291
  > {
283
292
  method: 'getGatewayClientCertificate';
284
293
  request: {
285
- apiToken: string;
294
+ /**
295
+ * The gateway client's credential. Required over HTTP, omitted over the connector socket, where
296
+ * the gateway client is the controller-bound one (`data.IGateway` `controllerGatewayClientId`).
297
+ */
298
+ apiToken?: string;
286
299
  identity?: never;
287
300
  ownership: IGatewayClientHostnameOwnership;
288
301
  };
@@ -301,7 +314,11 @@ export interface IReq_ReleaseGatewayClientCertificate extends plugins.typedreque
301
314
  > {
302
315
  method: 'releaseGatewayClientCertificate';
303
316
  request: {
304
- apiToken: string;
317
+ /**
318
+ * The gateway client's credential. Required over HTTP, omitted over the connector socket, where
319
+ * the gateway client is the controller-bound one (`data.IGateway` `controllerGatewayClientId`).
320
+ */
321
+ apiToken?: string;
305
322
  identity?: never;
306
323
  ownership: IGatewayClientHostnameOwnership;
307
324
  };