@serve.zone/interfaces 32.86.0 → 32.87.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.
- package/changelog.md +9 -0
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/data/gateway.d.ts +20 -0
- package/dist_ts/data/gateway.js +125 -1
- package/dist_ts/data/gatewayareas.d.ts +891 -0
- package/dist_ts/data/gatewayareas.js +298 -0
- package/dist_ts/data/gatewayareas.validation.d.ts +104 -0
- package/dist_ts/data/gatewayareas.validation.js +1770 -0
- package/dist_ts/data/gatewayconnector.d.ts +73 -1
- package/dist_ts/data/gatewayconnector.js +145 -2
- package/dist_ts/data/index.d.ts +2 -0
- package/dist_ts/data/index.js +3 -1
- package/dist_ts/private/enginekeyentries.d.ts +17 -0
- package/dist_ts/private/enginekeyentries.js +34 -0
- package/dist_ts/requests/gatewayconnector.d.ts +44 -0
- package/package.json +2 -2
- package/readme.md +151 -3
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/data/gateway.ts +149 -0
- package/ts/data/gatewayareas.ts +1135 -0
- package/ts/data/gatewayareas.validation.ts +2026 -0
- package/ts/data/gatewayconnector.ts +186 -0
- package/ts/data/index.ts +2 -0
- package/ts/private/enginekeyentries.ts +38 -0
- package/ts/requests/gatewayconnector.ts +45 -0
|
@@ -0,0 +1,2026 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Validation and pure readers of the five gateway area contents (`gatewayareas.ts`; Linus rulings
|
|
3
|
+
* 117 §2 and 121).
|
|
4
|
+
*
|
|
5
|
+
* `validateGatewayAreaTables` judges the contents of one whole document in the shipped apply order
|
|
6
|
+
* (`gatewayConfigAreaApplyOrder`) and is what a gateway runs before it applies any area (a refused
|
|
7
|
+
* area is its `invalid-table`) and what a controller runs before it sends. A refusal names the
|
|
8
|
+
* area, the member, the row id, the key path and a code; it never carries a value, so a refusal of
|
|
9
|
+
* a secret-bearing row can be logged and stored.
|
|
10
|
+
*
|
|
11
|
+
* The validators judge and never rewrite: no path normalises, sorts, lowercases or fills in a value,
|
|
12
|
+
* and nothing is written back into what they read. Canonical spelling is the author's (the gateway's
|
|
13
|
+
* exporter, the controller's compile), because the digest is over the table as written and one
|
|
14
|
+
* meaning must have one digest (Linus ruling 124, §3).
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import {
|
|
18
|
+
canonicalizeStrictJson,
|
|
19
|
+
compareWireTokens,
|
|
20
|
+
createCanonicalJsonSha256Hex,
|
|
21
|
+
} from '../private/canonicaljson.js';
|
|
22
|
+
import { isPlainRecord, readDataElements, readDataProperty, readExactDataRecord } from '../private/dataproperties.js';
|
|
23
|
+
import { matchesEngineKeyEntry, readEngineKeyEntries } from '../private/enginekeyentries.js';
|
|
24
|
+
import { isGatewayClientIdText } from '../private/gatewayclientid.js';
|
|
25
|
+
import { normalizeCoreMailCredentialVerifier } from './coremail.runtime.js';
|
|
26
|
+
import {
|
|
27
|
+
isGatewayClientHostname,
|
|
28
|
+
validateGatewayAllowedDnsRecordAddresses,
|
|
29
|
+
validateGatewayClientDnsRecord,
|
|
30
|
+
} from './gateway.js';
|
|
31
|
+
import {
|
|
32
|
+
gatewayAreaContentContract,
|
|
33
|
+
gatewayAreaMembers,
|
|
34
|
+
gatewayAreaRefusedEngineKeys,
|
|
35
|
+
gatewayBlockRuleTypes,
|
|
36
|
+
gatewayDnsRecordTypes,
|
|
37
|
+
gatewayDnsStaticRecordTypes,
|
|
38
|
+
gatewayMailIdentityScramIterations,
|
|
39
|
+
gatewayRoutePathClasses,
|
|
40
|
+
isGatewayApiTokenScope,
|
|
41
|
+
type IGatewayDnsStaticRecordRow,
|
|
42
|
+
type TGatewayAreaContent,
|
|
43
|
+
type TGatewayRoutePortEntry,
|
|
44
|
+
type TGatewayRoutePortsInput,
|
|
45
|
+
} from './gatewayareas.js';
|
|
46
|
+
import { gatewayConfigAreaApplyOrder, isGatewayConfigArea, type IGatewayAreaTable, type TGatewayConfigArea } from './gatewayconnector.js';
|
|
47
|
+
|
|
48
|
+
// ---------------------------------------------------------------------------------------------
|
|
49
|
+
// Refusals
|
|
50
|
+
// ---------------------------------------------------------------------------------------------
|
|
51
|
+
|
|
52
|
+
/** Every reason an area content is refused. */
|
|
53
|
+
export const gatewayAreaContentRefusalCodes = Object.freeze([
|
|
54
|
+
/** The content is not strict canonical JSON (safe integers, Unicode scalar strings, no accessor). */
|
|
55
|
+
'not-strict-json',
|
|
56
|
+
/** An object is missing a key, carries an extra key, or is no plain object. */
|
|
57
|
+
'exact-keys',
|
|
58
|
+
/**
|
|
59
|
+
* A member's value is outside its type or its stated rule. Also a document's table whose area is
|
|
60
|
+
* outside `gatewayConfigAreaApplyOrder`: that refusal has `area: null` and the table's position in
|
|
61
|
+
* the document as its path (`[n]`).
|
|
62
|
+
*/
|
|
63
|
+
'invalid-value',
|
|
64
|
+
/** A row list, an inner list, a text or an engine configuration exceeds its bound. */
|
|
65
|
+
'bound-exceeded',
|
|
66
|
+
/** A row id is no string of 1 to `maximumRowIdLength` characters without control characters, or breaks its member's id form. */
|
|
67
|
+
'invalid-row-id',
|
|
68
|
+
/** Row ids are not strictly ascending (`compareWireTokens`), which includes a repeated id. */
|
|
69
|
+
'rows-not-ascending',
|
|
70
|
+
/** A set is not strictly ascending, which includes a repeated entry. */
|
|
71
|
+
'set-not-ascending',
|
|
72
|
+
/**
|
|
73
|
+
* A natural key that must be unique in its member repeats (a zone name, a username, a static
|
|
74
|
+
* record's `(name, type, value)`).
|
|
75
|
+
*/
|
|
76
|
+
'duplicate-key',
|
|
77
|
+
/** A hard reference names no row of its target member. */
|
|
78
|
+
'dangling-reference',
|
|
79
|
+
/** A record names a zone whose source is not `dcrouter`. */
|
|
80
|
+
'reference-not-dcrouter-zone',
|
|
81
|
+
/**
|
|
82
|
+
* Hard references between rows of one member form a cycle through two or more rows
|
|
83
|
+
* (`routes.sourceProfiles[].extendsProfiles[]`); every row on the cycle is refused. A row that
|
|
84
|
+
* names itself is `invalid-value`.
|
|
85
|
+
*/
|
|
86
|
+
'reference-cycle',
|
|
87
|
+
/** A cross-area hard reference cannot be judged because the document carries no table of the area it points to. */
|
|
88
|
+
'referenced-area-missing',
|
|
89
|
+
/** The document carries the area more than once. */
|
|
90
|
+
'area-repeated',
|
|
91
|
+
/** A sealed value is not `{ version, value }` with a 22-character base64url version, or its value breaks the member's encoding. */
|
|
92
|
+
'invalid-sealed-value',
|
|
93
|
+
/** A lifted secret is set without its engine member, or the engine member exists without the secret. */
|
|
94
|
+
'secret-engine-mismatch',
|
|
95
|
+
/**
|
|
96
|
+
* Engine configuration carries, at any depth, a key or `parent.name` member of
|
|
97
|
+
* `gatewayAreaRefusedEngineKeys.secret` or of `gatewayAreaRefusedEngineKeys.headerInjection`.
|
|
98
|
+
*/
|
|
99
|
+
'secret-in-engine-config',
|
|
100
|
+
/** Engine configuration carries, at any depth, a key of `gatewayAreaRefusedEngineKeys.hostPath`. */
|
|
101
|
+
'host-path-in-engine-config',
|
|
102
|
+
/** A route's engine configuration carries a member this contract types beside it (`ingress`, `remoteIngress`, `vpnOnly`). */
|
|
103
|
+
'typed-member-in-engine-config',
|
|
104
|
+
/** An API token scope breaks the scope syntax. */
|
|
105
|
+
'invalid-scope',
|
|
106
|
+
/** A verifier breaks its form (`IGatewayTokenHash`, `IGatewayScramVerifier`, `IGatewayCoreMailCredentialVerifier`). */
|
|
107
|
+
'invalid-verifier',
|
|
108
|
+
/** A member that never changes under one row id changed (`validateGatewayAreaContentChange`). */
|
|
109
|
+
'immutable-member-changed',
|
|
110
|
+
] as const);
|
|
111
|
+
|
|
112
|
+
/** One reason an area content is refused. */
|
|
113
|
+
export type TGatewayAreaContentRefusalCode = typeof gatewayAreaContentRefusalCodes[number];
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* One refusal of an area content: where and why, never a value. `rowId` is the row's id when the
|
|
117
|
+
* id itself is valid; `path` is the key path inside the row or singleton (`[n]` for a list
|
|
118
|
+
* position, and the row's position when its id is invalid).
|
|
119
|
+
*/
|
|
120
|
+
export interface IGatewayAreaContentRefusal {
|
|
121
|
+
/** `null` only for a document's table whose area is outside `gatewayConfigAreaApplyOrder`. */
|
|
122
|
+
area: TGatewayConfigArea | null;
|
|
123
|
+
/** The area member; `null` for the content object or the document. */
|
|
124
|
+
member: string | null;
|
|
125
|
+
rowId: string | null;
|
|
126
|
+
path: string | null;
|
|
127
|
+
code: TGatewayAreaContentRefusalCode;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** One line for a log or an apply report's `invalid-table` detail; values never appear. */
|
|
131
|
+
export const formatGatewayAreaContentRefusal = (refusalArg: IGatewayAreaContentRefusal): string => [
|
|
132
|
+
refusalArg.area ?? '-',
|
|
133
|
+
refusalArg.member ?? '-',
|
|
134
|
+
refusalArg.rowId === null ? '-' : JSON.stringify(refusalArg.rowId),
|
|
135
|
+
refusalArg.path ?? '-',
|
|
136
|
+
refusalArg.code,
|
|
137
|
+
].join(' ');
|
|
138
|
+
|
|
139
|
+
// ---------------------------------------------------------------------------------------------
|
|
140
|
+
// Encodings both sides share
|
|
141
|
+
// ---------------------------------------------------------------------------------------------
|
|
142
|
+
|
|
143
|
+
const failEncoding = (reasonArg: string): never => {
|
|
144
|
+
throw new Error(`Gateway area value rejected: ${reasonArg}.`);
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
/** One basic-auth user as SmartProxy states it. */
|
|
148
|
+
export interface IGatewayBasicAuthUser {
|
|
149
|
+
username: string;
|
|
150
|
+
password: string;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* The `value` of a sealed `basicAuthUsers`: the strict canonical JSON of the whole SmartProxy
|
|
155
|
+
* `security.basicAuth.users` list, in its stated order.
|
|
156
|
+
*/
|
|
157
|
+
export const encodeGatewayBasicAuthUsers = (usersArg: readonly IGatewayBasicAuthUser[]): string => (
|
|
158
|
+
canonicalizeStrictJson(usersArg.map((userArg) => ({ username: userArg.username, password: userArg.password })),
|
|
159
|
+
failEncoding, 'basic-auth users')
|
|
160
|
+
);
|
|
161
|
+
|
|
162
|
+
/** The users of a sealed `basicAuthUsers` value; `null` when the value is not that encoding. */
|
|
163
|
+
export const decodeGatewayBasicAuthUsers = (valueArg: string): IGatewayBasicAuthUser[] | null => {
|
|
164
|
+
const parsed = parseCanonicalJson(valueArg);
|
|
165
|
+
const entries = readDataElements(parsed, gatewayAreaContentContract.maximumListEntries);
|
|
166
|
+
if (entries === null || entries.length === 0) {
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
const users: IGatewayBasicAuthUser[] = [];
|
|
170
|
+
for (const entry of entries) {
|
|
171
|
+
const user = readExactDataRecord(entry, ['username', 'password']);
|
|
172
|
+
if (user === null || typeof user.username !== 'string' || user.username.length === 0
|
|
173
|
+
|| typeof user.password !== 'string' || user.password.length === 0) {
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
users.push({ username: user.username, password: user.password });
|
|
177
|
+
}
|
|
178
|
+
return users;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
/** The `value` of a sealed `requestHeaders`: the strict canonical JSON of the whole `headers.request` record. */
|
|
182
|
+
export const encodeGatewayRequestHeaders = (headersArg: Readonly<Record<string, string>>): string => (
|
|
183
|
+
canonicalizeStrictJson({ ...headersArg }, failEncoding, 'request headers')
|
|
184
|
+
);
|
|
185
|
+
|
|
186
|
+
/** The record of a sealed `requestHeaders` value; `null` when the value is not that encoding. */
|
|
187
|
+
export const decodeGatewayRequestHeaders = (valueArg: string): Record<string, string> | null => {
|
|
188
|
+
const parsed = parseCanonicalJson(valueArg);
|
|
189
|
+
if (!isPlainRecord(parsed)) {
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
const names = Object.keys(parsed);
|
|
193
|
+
if (names.length === 0 || names.length > gatewayAreaContentContract.maximumListEntries) {
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
const headers: Record<string, string> = {};
|
|
197
|
+
for (const name of names) {
|
|
198
|
+
const property = readDataProperty(parsed, name);
|
|
199
|
+
if (name.length === 0 || property === null || typeof property.value !== 'string') {
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
headers[name] = property.value;
|
|
203
|
+
}
|
|
204
|
+
return headers;
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
/** Ports `canonicalizeGatewayRoutePorts` refuses; the message names the entry by position, never a route. */
|
|
208
|
+
export class GatewayRoutePortsError extends Error {
|
|
209
|
+
public constructor(reasonArg: string) {
|
|
210
|
+
super(`Gateway route ports rejected: ${reasonArg}.`);
|
|
211
|
+
this.name = 'GatewayRoutePortsError';
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const isRoutePort = (valueArg: unknown): valueArg is number => (
|
|
216
|
+
typeof valueArg === 'number' && Number.isSafeInteger(valueArg) && valueArg >= 1 && valueArg <= 65_535
|
|
217
|
+
);
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* The table's one spelling of a route's `match.ports` (`IGatewayRouteRow.route`) from any spelling
|
|
221
|
+
* SmartProxy takes: the maximal runs of the ports named, ascending, a port alone as a number and a
|
|
222
|
+
* run of two or more consecutive ports as `{ from, to }`; overlapping and touching entries merge.
|
|
223
|
+
* A bare `443` answers `[443]`, `[445, 80, { from: 443, to: 444 }]` answers
|
|
224
|
+
* `[80, { from: 443, to: 445 }]`. Throws `GatewayRoutePortsError` for a port outside 1 to 65535, a
|
|
225
|
+
* range whose `from` is above its `to`, or an entry that is neither. Both authors of route rows (a
|
|
226
|
+
* gateway's exporter, the controller's compile) call it; the validators only judge its result.
|
|
227
|
+
*/
|
|
228
|
+
export const canonicalizeGatewayRoutePorts = (portsArg: TGatewayRoutePortsInput): TGatewayRoutePortEntry[] => {
|
|
229
|
+
const entries = readDataElements(typeof portsArg === 'number' ? [portsArg] : portsArg, Number.MAX_SAFE_INTEGER);
|
|
230
|
+
if (entries === null) {
|
|
231
|
+
throw new GatewayRoutePortsError('the ports are neither a port nor a dense list');
|
|
232
|
+
}
|
|
233
|
+
const spans = entries.map((entryArg, indexArg): [number, number] => {
|
|
234
|
+
if (typeof entryArg === 'number') {
|
|
235
|
+
if (!isRoutePort(entryArg)) {
|
|
236
|
+
throw new GatewayRoutePortsError(`entry ${indexArg} is no port from 1 to 65535`);
|
|
237
|
+
}
|
|
238
|
+
return [entryArg, entryArg];
|
|
239
|
+
}
|
|
240
|
+
const range = readExactDataRecord(entryArg, ['from', 'to']);
|
|
241
|
+
const from = range?.from;
|
|
242
|
+
const to = range?.to;
|
|
243
|
+
if (!isRoutePort(from) || !isRoutePort(to) || from > to) {
|
|
244
|
+
throw new GatewayRoutePortsError(`entry ${indexArg} is no range { from, to } of ports from 1 to 65535 with from at most to`);
|
|
245
|
+
}
|
|
246
|
+
return [from, to];
|
|
247
|
+
});
|
|
248
|
+
spans.sort((leftArg, rightArg) => leftArg[0] - rightArg[0] || leftArg[1] - rightArg[1]);
|
|
249
|
+
const runs: [number, number][] = [];
|
|
250
|
+
for (const [from, to] of spans) {
|
|
251
|
+
const last = runs[runs.length - 1];
|
|
252
|
+
if (last !== undefined && from <= last[1] + 1) {
|
|
253
|
+
last[1] = Math.max(last[1], to);
|
|
254
|
+
} else {
|
|
255
|
+
runs.push([from, to]);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return runs.map(([from, to]) => (from === to ? from : { from, to }));
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
/** The parsed value when `valueArg` is exactly the strict canonical JSON of what it parses to. */
|
|
262
|
+
const parseCanonicalJson = (valueArg: string): unknown => {
|
|
263
|
+
try {
|
|
264
|
+
const parsed: unknown = JSON.parse(valueArg);
|
|
265
|
+
return canonicalizeStrictJson(parsed, failEncoding) === valueArg ? parsed : undefined;
|
|
266
|
+
} catch {
|
|
267
|
+
return undefined;
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
/** The digest domain of `createGatewayDnsStaticRecordId`. */
|
|
272
|
+
const gatewayDnsStaticRecordIdDomain = 'serve.zone/gateway-dns-static-record';
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* The id of a static record: `static-` and the SHA-256 of the record's name, type and value, so
|
|
276
|
+
* both sides derive one id and no row id carries a record value.
|
|
277
|
+
*/
|
|
278
|
+
export const createGatewayDnsStaticRecordId = async (
|
|
279
|
+
recordArg: Pick<IGatewayDnsStaticRecordRow, 'name' | 'type' | 'value'>,
|
|
280
|
+
): Promise<string> => `static-${await createCanonicalJsonSha256Hex(canonicalizeStrictJson({
|
|
281
|
+
domain: gatewayDnsStaticRecordIdDomain,
|
|
282
|
+
name: recordArg.name,
|
|
283
|
+
type: recordArg.type,
|
|
284
|
+
value: recordArg.value,
|
|
285
|
+
}, failEncoding, 'static record'), failEncoding)}`;
|
|
286
|
+
|
|
287
|
+
// ---------------------------------------------------------------------------------------------
|
|
288
|
+
// Scopes and value rules
|
|
289
|
+
// ---------------------------------------------------------------------------------------------
|
|
290
|
+
|
|
291
|
+
interface IScope {
|
|
292
|
+
sink: IGatewayAreaContentRefusal[];
|
|
293
|
+
area: TGatewayConfigArea;
|
|
294
|
+
member: string | null;
|
|
295
|
+
rowId: string | null;
|
|
296
|
+
/** Prefix of every path, ending in `.` or empty. */
|
|
297
|
+
prefix: string;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const refuse = (scopeArg: IScope, pathArg: string | null, codeArg: TGatewayAreaContentRefusalCode): void => {
|
|
301
|
+
const path = pathArg === null ? (scopeArg.prefix === '' ? null : scopeArg.prefix.replace(/\.$/, ''))
|
|
302
|
+
: `${scopeArg.prefix}${pathArg}`;
|
|
303
|
+
scopeArg.sink.push({ area: scopeArg.area, member: scopeArg.member, rowId: scopeArg.rowId, path, code: codeArg });
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
const nested = (scopeArg: IScope, pathArg: string): IScope => ({ ...scopeArg, prefix: `${scopeArg.prefix}${pathArg}.` });
|
|
307
|
+
|
|
308
|
+
const contract = gatewayAreaContentContract;
|
|
309
|
+
const controlCharacter = /[\u0000-\u001f\u007f]/;
|
|
310
|
+
const sealedVersionPattern = /^[A-Za-z0-9_-]{22}$/;
|
|
311
|
+
const zoneLabel = /^[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9])?$/;
|
|
312
|
+
const portKey = /^[1-9][0-9]{0,4}$/;
|
|
313
|
+
const clientTypes = ['onebox', 'cloudly', 'custom'] as const;
|
|
314
|
+
|
|
315
|
+
const isRowId = (valueArg: unknown): valueArg is string => (
|
|
316
|
+
typeof valueArg === 'string' && valueArg.length > 0 && valueArg.length <= contract.maximumRowIdLength
|
|
317
|
+
&& !controlCharacter.test(valueArg)
|
|
318
|
+
);
|
|
319
|
+
|
|
320
|
+
const isZoneName = (valueArg: unknown): valueArg is string => (
|
|
321
|
+
typeof valueArg === 'string' && valueArg.length > 0 && valueArg.length <= 253
|
|
322
|
+
&& valueArg.split('.').every((labelArg) => zoneLabel.test(labelArg))
|
|
323
|
+
);
|
|
324
|
+
|
|
325
|
+
const isPort = (valueArg: unknown): valueArg is number => (
|
|
326
|
+
typeof valueArg === 'number' && Number.isSafeInteger(valueArg) && valueArg >= 1 && valueArg <= 65_535
|
|
327
|
+
);
|
|
328
|
+
|
|
329
|
+
const isInteger = (valueArg: unknown, minimumArg: number): valueArg is number => (
|
|
330
|
+
typeof valueArg === 'number' && Number.isSafeInteger(valueArg) && valueArg >= minimumArg
|
|
331
|
+
);
|
|
332
|
+
|
|
333
|
+
/** A text: 1 to `maximumArg` characters without control characters. */
|
|
334
|
+
const isText = (valueArg: unknown, maximumArg: number): valueArg is string => (
|
|
335
|
+
typeof valueArg === 'string' && valueArg.length > 0 && valueArg.length <= maximumArg && !controlCharacter.test(valueArg)
|
|
336
|
+
);
|
|
337
|
+
|
|
338
|
+
/** Exactly these keys, or a refusal; returns the copied record or `null`. */
|
|
339
|
+
const exact = (scopeArg: IScope, valueArg: unknown, keysArg: readonly string[], pathArg: string | null):
|
|
340
|
+
Record<string, unknown> | null => {
|
|
341
|
+
const record = readExactDataRecord(valueArg, keysArg);
|
|
342
|
+
if (record === null) {
|
|
343
|
+
refuse(scopeArg, pathArg, 'exact-keys');
|
|
344
|
+
}
|
|
345
|
+
return record;
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
const check = (scopeArg: IScope, okArg: boolean, pathArg: string, codeArg: TGatewayAreaContentRefusalCode = 'invalid-value'):
|
|
349
|
+
void => {
|
|
350
|
+
if (!okArg) {
|
|
351
|
+
refuse(scopeArg, pathArg, codeArg);
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
const checkText = (scopeArg: IScope, valueArg: unknown, pathArg: string, maximumArg: number = contract.maximumNameLength): void => {
|
|
356
|
+
if (typeof valueArg === 'string' && valueArg.length > maximumArg) {
|
|
357
|
+
refuse(scopeArg, pathArg, 'bound-exceeded');
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
check(scopeArg, isText(valueArg, maximumArg), pathArg);
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
const checkNullableText = (scopeArg: IScope, valueArg: unknown, pathArg: string, maximumArg: number = contract.maximumNameLength):
|
|
364
|
+
void => {
|
|
365
|
+
if (valueArg !== null) {
|
|
366
|
+
checkText(scopeArg, valueArg, pathArg, maximumArg);
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
const checkBoolean = (scopeArg: IScope, valueArg: unknown, pathArg: string): void => (
|
|
371
|
+
check(scopeArg, typeof valueArg === 'boolean', pathArg)
|
|
372
|
+
);
|
|
373
|
+
|
|
374
|
+
const checkNullableBoolean = (scopeArg: IScope, valueArg: unknown, pathArg: string): void => (
|
|
375
|
+
check(scopeArg, valueArg === null || typeof valueArg === 'boolean', pathArg)
|
|
376
|
+
);
|
|
377
|
+
|
|
378
|
+
const checkInteger = (scopeArg: IScope, valueArg: unknown, pathArg: string, minimumArg: number, nullableArg = false):
|
|
379
|
+
void => check(scopeArg, (nullableArg && valueArg === null) || isInteger(valueArg, minimumArg), pathArg);
|
|
380
|
+
|
|
381
|
+
const checkOneOf = (scopeArg: IScope, valueArg: unknown, pathArg: string, valuesArg: readonly unknown[], nullableArg = false):
|
|
382
|
+
void => check(scopeArg, (nullableArg && valueArg === null) || valuesArg.includes(valueArg), pathArg);
|
|
383
|
+
|
|
384
|
+
/** A bounded list, or a refusal; `null` when refused. */
|
|
385
|
+
const list = (scopeArg: IScope, valueArg: unknown, pathArg: string, maximumArg: number = contract.maximumListEntries):
|
|
386
|
+
unknown[] | null => {
|
|
387
|
+
if (Array.isArray(valueArg) && valueArg.length > maximumArg) {
|
|
388
|
+
refuse(scopeArg, pathArg, 'bound-exceeded');
|
|
389
|
+
return null;
|
|
390
|
+
}
|
|
391
|
+
const entries = readDataElements(valueArg, maximumArg);
|
|
392
|
+
if (entries === null) {
|
|
393
|
+
refuse(scopeArg, pathArg, 'invalid-value');
|
|
394
|
+
}
|
|
395
|
+
return entries;
|
|
396
|
+
};
|
|
397
|
+
|
|
398
|
+
/** A set of texts, strictly ascending by `compareWireTokens`. */
|
|
399
|
+
const checkTextSet = (
|
|
400
|
+
scopeArg: IScope,
|
|
401
|
+
valueArg: unknown,
|
|
402
|
+
pathArg: string,
|
|
403
|
+
isEntryArg: (entryArg: unknown) => boolean = (entryArg) => isText(entryArg, contract.maximumNameLength),
|
|
404
|
+
entryCodeArg: TGatewayAreaContentRefusalCode = 'invalid-value',
|
|
405
|
+
): void => {
|
|
406
|
+
const entries = list(scopeArg, valueArg, pathArg);
|
|
407
|
+
if (entries === null) {
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
if (!entries.every(isEntryArg)) {
|
|
411
|
+
refuse(scopeArg, pathArg, entryCodeArg);
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
check(scopeArg, entries.every((entryArg, indexArg) => indexArg === 0
|
|
415
|
+
|| compareWireTokens(entries[indexArg - 1] as string, entryArg as string) < 0), pathArg, 'set-not-ascending');
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
/** A set of ports, strictly ascending. */
|
|
419
|
+
const checkPortSet = (scopeArg: IScope, valueArg: unknown, pathArg: string): void => {
|
|
420
|
+
const entries = list(scopeArg, valueArg, pathArg);
|
|
421
|
+
if (entries === null) {
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
if (!entries.every(isPort)) {
|
|
425
|
+
refuse(scopeArg, pathArg, 'invalid-value');
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
check(scopeArg, entries.every((entryArg, indexArg) => indexArg === 0
|
|
429
|
+
|| (entries[indexArg - 1] as number) < (entryArg as number)), pathArg, 'set-not-ascending');
|
|
430
|
+
};
|
|
431
|
+
|
|
432
|
+
const checkScopes = (scopeArg: IScope, valueArg: unknown, pathArg: string): void => (
|
|
433
|
+
checkTextSet(scopeArg, valueArg, pathArg, isGatewayApiTokenScope, 'invalid-scope')
|
|
434
|
+
);
|
|
435
|
+
|
|
436
|
+
const checkSealed = (scopeArg: IScope, valueArg: unknown, pathArg: string, decodeArg?: (valueArg: string) => unknown):
|
|
437
|
+
void => {
|
|
438
|
+
const sealed = readExactDataRecord(valueArg, ['version', 'value']);
|
|
439
|
+
if (sealed === null || typeof sealed.version !== 'string' || !sealedVersionPattern.test(sealed.version)
|
|
440
|
+
|| typeof sealed.value !== 'string' || sealed.value.length === 0) {
|
|
441
|
+
refuse(scopeArg, pathArg, 'invalid-sealed-value');
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
if (sealed.value.length > contract.maximumSealedValueLength) {
|
|
445
|
+
refuse(scopeArg, pathArg, 'bound-exceeded');
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
if (decodeArg && (decodeArg(sealed.value) ?? null) === null) {
|
|
449
|
+
refuse(scopeArg, pathArg, 'invalid-sealed-value');
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
|
|
453
|
+
const checkNullableSealed = (
|
|
454
|
+
scopeArg: IScope,
|
|
455
|
+
valueArg: unknown,
|
|
456
|
+
pathArg: string,
|
|
457
|
+
decodeArg?: (valueArg: string) => unknown,
|
|
458
|
+
): void => {
|
|
459
|
+
if (valueArg !== null) {
|
|
460
|
+
checkSealed(scopeArg, valueArg, pathArg, decodeArg);
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
/** Canonical padded base64 of `minimumBytesArg` to `maximumBytesArg` bytes. */
|
|
465
|
+
const isCanonicalBase64 = (valueArg: unknown, minimumBytesArg: number, maximumBytesArg: number): boolean => {
|
|
466
|
+
if (typeof valueArg !== 'string' || valueArg.length === 0 || valueArg.length % 4 !== 0
|
|
467
|
+
|| !/^[A-Za-z0-9+/]+={0,2}$/.test(valueArg)) {
|
|
468
|
+
return false;
|
|
469
|
+
}
|
|
470
|
+
try {
|
|
471
|
+
const decoded = globalThis.atob(valueArg);
|
|
472
|
+
return globalThis.btoa(decoded) === valueArg && decoded.length >= minimumBytesArg
|
|
473
|
+
&& decoded.length <= maximumBytesArg;
|
|
474
|
+
} catch {
|
|
475
|
+
return false;
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
const checkScramVerifier = (scopeArg: IScope, valueArg: unknown, pathArg: string, iterationsArg: number | null): void => {
|
|
480
|
+
const verifier = readExactDataRecord(valueArg, ['algorithm', 'salt', 'iterations', 'storedKey', 'serverKey']);
|
|
481
|
+
check(scopeArg, verifier !== null
|
|
482
|
+
&& verifier.algorithm === 'SCRAM-SHA-256'
|
|
483
|
+
&& isCanonicalBase64(verifier.salt, 16, 64)
|
|
484
|
+
&& isInteger(verifier.iterations, 4096) && (verifier.iterations as number) <= 1_000_000
|
|
485
|
+
&& (iterationsArg === null || verifier.iterations === iterationsArg)
|
|
486
|
+
&& isCanonicalBase64(verifier.storedKey, 32, 32)
|
|
487
|
+
&& isCanonicalBase64(verifier.serverKey, 32, 32), pathArg, 'invalid-verifier');
|
|
488
|
+
};
|
|
489
|
+
|
|
490
|
+
const checkAttribution = (
|
|
491
|
+
scopeArg: IScope,
|
|
492
|
+
valueArg: unknown,
|
|
493
|
+
pathArg: string,
|
|
494
|
+
requireArg: { appId: boolean | null; externalKey: boolean | null },
|
|
495
|
+
): void => {
|
|
496
|
+
const client = exact(scopeArg, valueArg, ['gatewayClientType', 'gatewayClientId', 'appId', 'externalKey'], pathArg);
|
|
497
|
+
if (client === null) {
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
const inner = nested(scopeArg, pathArg);
|
|
501
|
+
checkOneOf(inner, client.gatewayClientType, 'gatewayClientType', clientTypes);
|
|
502
|
+
check(inner, isGatewayClientIdText(client.gatewayClientId), 'gatewayClientId');
|
|
503
|
+
for (const key of ['appId', 'externalKey'] as const) {
|
|
504
|
+
const value = client[key];
|
|
505
|
+
const required = requireArg[key];
|
|
506
|
+
if (value === null) {
|
|
507
|
+
check(inner, required !== true, key);
|
|
508
|
+
} else {
|
|
509
|
+
check(inner, required !== false, key);
|
|
510
|
+
checkText(inner, value, key);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
};
|
|
514
|
+
|
|
515
|
+
// ---------------------------------------------------------------------------------------------
|
|
516
|
+
// Engine configuration
|
|
517
|
+
// ---------------------------------------------------------------------------------------------
|
|
518
|
+
|
|
519
|
+
/** The value at a dotted path of own data properties; `undefined` when a step is absent. */
|
|
520
|
+
const engineValueAt = (valueArg: unknown, pathArg: string): unknown => {
|
|
521
|
+
let current = valueArg;
|
|
522
|
+
for (const segment of pathArg.split('.')) {
|
|
523
|
+
const property = readDataProperty(current, segment);
|
|
524
|
+
if (property === null) {
|
|
525
|
+
return undefined;
|
|
526
|
+
}
|
|
527
|
+
current = property.value;
|
|
528
|
+
}
|
|
529
|
+
return current;
|
|
530
|
+
};
|
|
531
|
+
|
|
532
|
+
// Every list of the vocabulary goes through the one reader (`readEngineKeyEntries`), at module load:
|
|
533
|
+
// an entry that is neither a key name nor `parent.name` fails the import rather than never matching.
|
|
534
|
+
const refusedSecretMembers = readEngineKeyEntries([
|
|
535
|
+
...gatewayAreaRefusedEngineKeys.secret, ...gatewayAreaRefusedEngineKeys.headerInjection,
|
|
536
|
+
]);
|
|
537
|
+
const refusedHostPathMembers = readEngineKeyEntries(gatewayAreaRefusedEngineKeys.hostPath);
|
|
538
|
+
|
|
539
|
+
/** The refusal of an engine key under its parent key, or `null` for a key outside the vocabulary. */
|
|
540
|
+
const refusedEngineKeyCode = (parentArg: string | null, keyArg: string): TGatewayAreaContentRefusalCode | null => {
|
|
541
|
+
if (matchesEngineKeyEntry(refusedSecretMembers, parentArg, keyArg)) {
|
|
542
|
+
return 'secret-in-engine-config';
|
|
543
|
+
}
|
|
544
|
+
return matchesEngineKeyEntry(refusedHostPathMembers, parentArg, keyArg) ? 'host-path-in-engine-config' : null;
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
type TEngineWalkStep =
|
|
548
|
+
| { kind: 'visit'; value: unknown; path: string; parent: string | null }
|
|
549
|
+
| { kind: 'refuse'; path: string; code: TGatewayAreaContentRefusalCode };
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Refuses every key of `gatewayAreaRefusedEngineKeys` at any depth of one strict JSON value, record
|
|
553
|
+
* keys included, in document order (keys ascending by `compareWireTokens`). A refused member is not
|
|
554
|
+
* walked further, so each refusal names the outermost vocabulary key. Iterative, so a deep value
|
|
555
|
+
* cannot exhaust the stack; the value has passed `canonicalizeStrictJson`, so it holds data only.
|
|
556
|
+
*/
|
|
557
|
+
const refuseEngineKeys = (scopeArg: IScope, valueArg: unknown, pathArg: string): void => {
|
|
558
|
+
const pending: TEngineWalkStep[] = [{ kind: 'visit', value: valueArg, path: pathArg, parent: null }];
|
|
559
|
+
while (pending.length > 0) {
|
|
560
|
+
const step = pending.pop()!;
|
|
561
|
+
if (step.kind === 'refuse') {
|
|
562
|
+
refuse(scopeArg, step.path, step.code);
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
const next: TEngineWalkStep[] = [];
|
|
566
|
+
if (Array.isArray(step.value)) {
|
|
567
|
+
// A list between two keys is transparent: its entries keep the list's own parent key.
|
|
568
|
+
(readDataElements(step.value, step.value.length) ?? []).forEach((entryArg, indexArg) => {
|
|
569
|
+
next.push({ kind: 'visit', value: entryArg, path: `${step.path}[${indexArg}]`, parent: step.parent });
|
|
570
|
+
});
|
|
571
|
+
} else if (isPlainRecord(step.value)) {
|
|
572
|
+
for (const key of Object.keys(step.value).sort(compareWireTokens)) {
|
|
573
|
+
const code = refusedEngineKeyCode(step.parent, key);
|
|
574
|
+
next.push(code === null
|
|
575
|
+
? { kind: 'visit', value: readDataProperty(step.value, key)?.value, path: `${step.path}.${key}`, parent: key }
|
|
576
|
+
: { kind: 'refuse', path: `${step.path}.${key}`, code });
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
for (let index = next.length - 1; index >= 0; index--) {
|
|
580
|
+
pending.push(next[index]);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
};
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* An engine configuration object within its bound, walked for the refused key vocabulary at any
|
|
587
|
+
* depth (`gatewayAreaRefusedEngineKeys`). Every engine configuration of every area goes through
|
|
588
|
+
* here, policy override values included, so no call site can skip the walk. `false` when its shape
|
|
589
|
+
* is refused (and then it is not walked); a vocabulary refusal leaves it `true`.
|
|
590
|
+
*/
|
|
591
|
+
const checkEngineConfig = (scopeArg: IScope, valueArg: unknown, pathArg: string): boolean => {
|
|
592
|
+
if (!isPlainRecord(valueArg)) {
|
|
593
|
+
refuse(scopeArg, pathArg, 'invalid-value');
|
|
594
|
+
return false;
|
|
595
|
+
}
|
|
596
|
+
let length: number;
|
|
597
|
+
try {
|
|
598
|
+
length = canonicalizeStrictJson(valueArg, failEncoding).length;
|
|
599
|
+
} catch {
|
|
600
|
+
refuse(scopeArg, pathArg, 'not-strict-json');
|
|
601
|
+
return false;
|
|
602
|
+
}
|
|
603
|
+
if (length > contract.maximumEngineConfigLength) {
|
|
604
|
+
refuse(scopeArg, pathArg, 'bound-exceeded');
|
|
605
|
+
return false;
|
|
606
|
+
}
|
|
607
|
+
refuseEngineKeys(scopeArg, valueArg, pathArg);
|
|
608
|
+
return true;
|
|
609
|
+
};
|
|
610
|
+
|
|
611
|
+
/** A lifted secret is set exactly when its engine member is an object. */
|
|
612
|
+
const checkLiftedCoherence = (
|
|
613
|
+
scopeArg: IScope,
|
|
614
|
+
engineArg: unknown,
|
|
615
|
+
engineMemberArg: string,
|
|
616
|
+
secretArg: unknown,
|
|
617
|
+
secretPathArg: string,
|
|
618
|
+
): void => {
|
|
619
|
+
check(scopeArg, isPlainRecord(engineValueAt(engineArg, engineMemberArg)) === (secretArg !== null), secretPathArg,
|
|
620
|
+
'secret-engine-mismatch');
|
|
621
|
+
};
|
|
622
|
+
|
|
623
|
+
// ---------------------------------------------------------------------------------------------
|
|
624
|
+
// Row lists and singletons
|
|
625
|
+
// ---------------------------------------------------------------------------------------------
|
|
626
|
+
|
|
627
|
+
/**
|
|
628
|
+
* A row list: bounded, ids valid and strictly ascending. Calls `checkRowArg` for every row with a
|
|
629
|
+
* scope naming the row, and answers the valid ids.
|
|
630
|
+
*/
|
|
631
|
+
const rowList = (
|
|
632
|
+
scopeArg: IScope,
|
|
633
|
+
memberArg: string,
|
|
634
|
+
valueArg: unknown,
|
|
635
|
+
maximumArg: number,
|
|
636
|
+
checkRowArg: (rowScopeArg: IScope, rowArg: unknown) => void,
|
|
637
|
+
): string[] => {
|
|
638
|
+
const memberScope: IScope = { ...scopeArg, member: memberArg, rowId: null, prefix: '' };
|
|
639
|
+
if (Array.isArray(valueArg) && valueArg.length > maximumArg) {
|
|
640
|
+
refuse(memberScope, null, 'bound-exceeded');
|
|
641
|
+
return [];
|
|
642
|
+
}
|
|
643
|
+
const rows = readDataElements(valueArg, maximumArg);
|
|
644
|
+
if (rows === null) {
|
|
645
|
+
refuse(memberScope, null, 'invalid-value');
|
|
646
|
+
return [];
|
|
647
|
+
}
|
|
648
|
+
const ids: string[] = [];
|
|
649
|
+
let previous: string | null = null;
|
|
650
|
+
rows.forEach((rowArg, indexArg) => {
|
|
651
|
+
const id = readDataProperty(rowArg, 'id')?.value;
|
|
652
|
+
const rowScope: IScope = isRowId(id)
|
|
653
|
+
? { ...memberScope, rowId: id }
|
|
654
|
+
: { ...memberScope, prefix: `[${indexArg}].` };
|
|
655
|
+
if (!isRowId(id)) {
|
|
656
|
+
refuse(rowScope, 'id', 'invalid-row-id');
|
|
657
|
+
} else {
|
|
658
|
+
if (previous !== null && compareWireTokens(previous, id) >= 0) {
|
|
659
|
+
refuse(rowScope, 'id', 'rows-not-ascending');
|
|
660
|
+
}
|
|
661
|
+
previous = id;
|
|
662
|
+
ids.push(id);
|
|
663
|
+
}
|
|
664
|
+
checkRowArg(rowScope, rowArg);
|
|
665
|
+
});
|
|
666
|
+
return ids;
|
|
667
|
+
};
|
|
668
|
+
|
|
669
|
+
/** A singleton: `null` or an object checked by `checkArg`. */
|
|
670
|
+
const singleton = (
|
|
671
|
+
scopeArg: IScope,
|
|
672
|
+
memberArg: string,
|
|
673
|
+
valueArg: unknown,
|
|
674
|
+
checkArg: (memberScopeArg: IScope, valueArg: unknown) => void,
|
|
675
|
+
): void => {
|
|
676
|
+
if (valueArg !== null) {
|
|
677
|
+
checkArg({ ...scopeArg, member: memberArg, rowId: null, prefix: '' }, valueArg);
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
|
|
681
|
+
/** A singleton that is always stated: `null` is refused, an object is checked by `checkArg`. */
|
|
682
|
+
const requiredSingleton = (
|
|
683
|
+
scopeArg: IScope,
|
|
684
|
+
memberArg: string,
|
|
685
|
+
valueArg: unknown,
|
|
686
|
+
checkArg: (memberScopeArg: IScope, valueArg: unknown) => void,
|
|
687
|
+
): void => {
|
|
688
|
+
const memberScope: IScope = { ...scopeArg, member: memberArg, rowId: null, prefix: '' };
|
|
689
|
+
if (valueArg === null) {
|
|
690
|
+
refuse(memberScope, null, 'invalid-value');
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
checkArg(memberScope, valueArg);
|
|
694
|
+
};
|
|
695
|
+
|
|
696
|
+
/** The ids a row list carries, read without judging it (for references across members). */
|
|
697
|
+
const readRowIds = (valueArg: unknown): Set<string> => {
|
|
698
|
+
const ids = new Set<string>();
|
|
699
|
+
if (Array.isArray(valueArg)) {
|
|
700
|
+
for (const row of valueArg) {
|
|
701
|
+
const id = readDataProperty(row, 'id')?.value;
|
|
702
|
+
if (typeof id === 'string') {
|
|
703
|
+
ids.add(id);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
return ids;
|
|
708
|
+
};
|
|
709
|
+
|
|
710
|
+
/** The rows' natural keys repeat: one refusal per repeat, on the later row (`pathArg` `null`: the row). */
|
|
711
|
+
const checkUniqueKey = (scopeArg: IScope, memberArg: string, rowsArg: unknown, keyArg: (rowArg: unknown) => unknown,
|
|
712
|
+
pathArg: string | null): void => {
|
|
713
|
+
if (!Array.isArray(rowsArg)) {
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
const seen = new Set<string>();
|
|
717
|
+
rowsArg.forEach((rowArg) => {
|
|
718
|
+
const key = keyArg(rowArg);
|
|
719
|
+
if (typeof key !== 'string') {
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
if (seen.has(key)) {
|
|
723
|
+
const id = readDataProperty(rowArg, 'id')?.value;
|
|
724
|
+
refuse({ ...scopeArg, member: memberArg, rowId: isRowId(id) ? id : null, prefix: '' }, pathArg, 'duplicate-key');
|
|
725
|
+
}
|
|
726
|
+
seen.add(key);
|
|
727
|
+
});
|
|
728
|
+
};
|
|
729
|
+
|
|
730
|
+
const field = (rowArg: unknown, keyArg: string): unknown => readDataProperty(rowArg, keyArg)?.value;
|
|
731
|
+
|
|
732
|
+
// ---------------------------------------------------------------------------------------------
|
|
733
|
+
// security
|
|
734
|
+
// ---------------------------------------------------------------------------------------------
|
|
735
|
+
|
|
736
|
+
const capabilityKeys = [
|
|
737
|
+
'readDomains', 'readDnsRecords', 'readRoutes', 'syncRoutes', 'syncDnsRecords', 'readMail', 'manageMail',
|
|
738
|
+
'readCertificates', 'requestCertificates', 'readWebPush', 'manageWebPush',
|
|
739
|
+
] as const;
|
|
740
|
+
|
|
741
|
+
const compareRouteTargets = (leftArg: Record<string, unknown>, rightArg: Record<string, unknown>): number => {
|
|
742
|
+
const host = compareWireTokens(leftArg.host as string, rightArg.host as string);
|
|
743
|
+
if (host !== 0) {
|
|
744
|
+
return host;
|
|
745
|
+
}
|
|
746
|
+
const leftPorts = leftArg.ports as number[];
|
|
747
|
+
const rightPorts = rightArg.ports as number[];
|
|
748
|
+
for (let index = 0; index < Math.min(leftPorts.length, rightPorts.length); index++) {
|
|
749
|
+
if (leftPorts[index] !== rightPorts[index]) {
|
|
750
|
+
return leftPorts[index] - rightPorts[index];
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
return leftPorts.length - rightPorts.length || Number(leftArg.allowAnyPort) - Number(rightArg.allowAnyPort);
|
|
754
|
+
};
|
|
755
|
+
|
|
756
|
+
const checkTokenPolicy = (scopeArg: IScope, valueArg: unknown): void => {
|
|
757
|
+
const policy = exact(scopeArg, valueArg, [
|
|
758
|
+
'role', 'scopes', 'gatewayClient', 'hostnamePatterns', 'allowedRouteTargets', 'allowedDnsRecordAddresses',
|
|
759
|
+
'capabilities',
|
|
760
|
+
], 'policy');
|
|
761
|
+
if (policy === null) {
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
const inner = nested(scopeArg, 'policy');
|
|
765
|
+
checkOneOf(inner, policy.role, 'role', ['admin', 'gatewayClient', 'operator']);
|
|
766
|
+
checkScopes(inner, policy.scopes, 'scopes');
|
|
767
|
+
if (policy.gatewayClient === null) {
|
|
768
|
+
check(inner, policy.role !== 'gatewayClient', 'gatewayClient');
|
|
769
|
+
} else {
|
|
770
|
+
check(inner, policy.role === 'gatewayClient', 'gatewayClient');
|
|
771
|
+
const client = exact(inner, policy.gatewayClient, ['type', 'id', 'policyGeneration'], 'gatewayClient');
|
|
772
|
+
if (client !== null) {
|
|
773
|
+
const clientScope = nested(inner, 'gatewayClient');
|
|
774
|
+
checkOneOf(clientScope, client.type, 'type', clientTypes);
|
|
775
|
+
check(clientScope, isGatewayClientIdText(client.id), 'id');
|
|
776
|
+
checkInteger(clientScope, client.policyGeneration, 'policyGeneration', 1);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
checkTextSet(inner, policy.hostnamePatterns, 'hostnamePatterns');
|
|
780
|
+
const targets = list(inner, policy.allowedRouteTargets, 'allowedRouteTargets');
|
|
781
|
+
if (targets !== null) {
|
|
782
|
+
const records: Record<string, unknown>[] = [];
|
|
783
|
+
targets.forEach((targetArg, indexArg) => {
|
|
784
|
+
const path = `allowedRouteTargets[${indexArg}]`;
|
|
785
|
+
const target = exact(inner, targetArg, ['host', 'ports', 'allowAnyPort'], path);
|
|
786
|
+
if (target === null) {
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
const targetScope = nested(inner, path);
|
|
790
|
+
const before = targetScope.sink.length;
|
|
791
|
+
checkText(targetScope, target.host, 'host', 253);
|
|
792
|
+
checkPortSet(targetScope, target.ports, 'ports');
|
|
793
|
+
checkBoolean(targetScope, target.allowAnyPort, 'allowAnyPort');
|
|
794
|
+
if (targetScope.sink.length === before) {
|
|
795
|
+
records.push(target);
|
|
796
|
+
}
|
|
797
|
+
});
|
|
798
|
+
if (records.length === targets.length) {
|
|
799
|
+
check(inner, records.every((recordArg, indexArg) => indexArg === 0
|
|
800
|
+
|| compareRouteTargets(records[indexArg - 1], recordArg) < 0), 'allowedRouteTargets', 'set-not-ascending');
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
if (validateGatewayAllowedDnsRecordAddresses(policy.allowedDnsRecordAddresses).length > 0) {
|
|
804
|
+
refuse(inner, 'allowedDnsRecordAddresses', 'invalid-value');
|
|
805
|
+
} else {
|
|
806
|
+
checkTextSet(inner, policy.allowedDnsRecordAddresses, 'allowedDnsRecordAddresses', () => true);
|
|
807
|
+
}
|
|
808
|
+
const capabilities = exact(inner, policy.capabilities, capabilityKeys, 'capabilities');
|
|
809
|
+
if (capabilities !== null) {
|
|
810
|
+
for (const key of capabilityKeys) {
|
|
811
|
+
checkBoolean(nested(inner, 'capabilities'), capabilities[key], key);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
};
|
|
815
|
+
|
|
816
|
+
const validateSecurity = (scopeArg: IScope, contentArg: Record<string, unknown>): void => {
|
|
817
|
+
const bounds = contract.maximumRows.security;
|
|
818
|
+
rowList(scopeArg, 'blockRules', contentArg.blockRules, bounds.blockRules, (rowScopeArg, rowArg) => {
|
|
819
|
+
const row = exact(rowScopeArg, rowArg, ['id', 'type', 'value', 'matchMode', 'reason', 'enabled'], null);
|
|
820
|
+
if (row === null) {
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
checkOneOf(rowScopeArg, row.type, 'type', gatewayBlockRuleTypes);
|
|
824
|
+
checkText(rowScopeArg, row.value, 'value');
|
|
825
|
+
checkOneOf(rowScopeArg, row.matchMode, 'matchMode', row.type === 'organization' ? ['exact', 'contains'] : [null]);
|
|
826
|
+
checkNullableText(rowScopeArg, row.reason, 'reason', contract.maximumTextLength);
|
|
827
|
+
checkBoolean(rowScopeArg, row.enabled, 'enabled');
|
|
828
|
+
});
|
|
829
|
+
rowList(scopeArg, 'apiTokens', contentArg.apiTokens, bounds.apiTokens, (rowScopeArg, rowArg) => {
|
|
830
|
+
const row = exact(rowScopeArg, rowArg, ['id', 'name', 'credential', 'scopes', 'policy', 'expiresAt', 'enabled'], null);
|
|
831
|
+
if (row === null) {
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
checkText(rowScopeArg, row.name, 'name');
|
|
835
|
+
const credential = readExactDataRecord(row.credential, ['algorithm', 'hash']);
|
|
836
|
+
check(rowScopeArg, credential !== null && credential.algorithm === 'sha256'
|
|
837
|
+
&& typeof credential.hash === 'string' && /^[a-f0-9]{64}$/.test(credential.hash), 'credential', 'invalid-verifier');
|
|
838
|
+
checkScopes(rowScopeArg, row.scopes, 'scopes');
|
|
839
|
+
if (row.policy !== null) {
|
|
840
|
+
checkTokenPolicy(rowScopeArg, row.policy);
|
|
841
|
+
}
|
|
842
|
+
checkInteger(rowScopeArg, row.expiresAt, 'expiresAt', 1, true);
|
|
843
|
+
checkBoolean(rowScopeArg, row.enabled, 'enabled');
|
|
844
|
+
});
|
|
845
|
+
singleton(scopeArg, 'proxyPolicy', contentArg.proxyPolicy, (memberScopeArg, valueArg) => {
|
|
846
|
+
checkEngineConfig(memberScopeArg, valueArg, 'proxyPolicy');
|
|
847
|
+
});
|
|
848
|
+
};
|
|
849
|
+
|
|
850
|
+
// ---------------------------------------------------------------------------------------------
|
|
851
|
+
// dns
|
|
852
|
+
// ---------------------------------------------------------------------------------------------
|
|
853
|
+
|
|
854
|
+
/**
|
|
855
|
+
* The `A` form the gateway's DNS encoder takes (dcrouter's record value owner, after smartdns
|
|
856
|
+
* `encode_a`): four decimal octets of one to three digits, each at most 255, nothing around them.
|
|
857
|
+
*/
|
|
858
|
+
const isDnsIpv4Value = (valueArg: string): boolean => {
|
|
859
|
+
const octets = valueArg.split('.');
|
|
860
|
+
return octets.length === 4 && octets.every((octetArg) => /^[0-9]{1,3}$/.test(octetArg) && Number(octetArg) <= 255);
|
|
861
|
+
};
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* The `AAAA` form the gateway's DNS encoder takes (smartdns 11.1.0 `encode_aaaa`, as dcrouter's
|
|
865
|
+
* record value owner ports it): hex groups of one to four digits, either case, eight of them, or at
|
|
866
|
+
* most eight with exactly one `::`; no IPv4 tail, no zone id, nothing around them. `net.isIPv6`
|
|
867
|
+
* differs on all three and is not this check.
|
|
868
|
+
*/
|
|
869
|
+
const isDnsIpv6Value = (valueArg: string): boolean => {
|
|
870
|
+
const halves = valueArg.split('::');
|
|
871
|
+
if (halves.length > 2) {
|
|
872
|
+
return false;
|
|
873
|
+
}
|
|
874
|
+
const groups = halves.flatMap((halfArg) => (halfArg === '' ? [] : halfArg.split(':')));
|
|
875
|
+
return groups.every((groupArg) => /^[0-9A-Fa-f]{1,4}$/.test(groupArg))
|
|
876
|
+
&& (halves.length === 2 ? groups.length <= 8 : groups.length === 8);
|
|
877
|
+
};
|
|
878
|
+
|
|
879
|
+
/** A record value: a bounded text, and for `A` and `AAAA` an address in the form the gateway serves. */
|
|
880
|
+
const checkRecordValue = (scopeArg: IScope, typeArg: unknown, valueArg: unknown): void => {
|
|
881
|
+
checkText(scopeArg, valueArg, 'value', contract.maximumRecordValueLength);
|
|
882
|
+
if (isText(valueArg, contract.maximumRecordValueLength) && (typeArg === 'A' || typeArg === 'AAAA')) {
|
|
883
|
+
check(scopeArg, typeArg === 'A' ? isDnsIpv4Value(valueArg) : isDnsIpv6Value(valueArg), 'value');
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
|
|
887
|
+
const validateDns = (scopeArg: IScope, contentArg: Record<string, unknown>): void => {
|
|
888
|
+
const bounds = contract.maximumRows.dns;
|
|
889
|
+
const nameservers = rowList(scopeArg, 'nameservers', contentArg.nameservers, bounds.nameservers,
|
|
890
|
+
(rowScopeArg, rowArg) => {
|
|
891
|
+
if (exact(rowScopeArg, rowArg, ['id'], null) !== null && rowScopeArg.rowId !== null) {
|
|
892
|
+
check(rowScopeArg, isGatewayClientHostname(rowScopeArg.rowId), 'id', 'invalid-row-id');
|
|
893
|
+
}
|
|
894
|
+
});
|
|
895
|
+
if (contentArg.server === null) {
|
|
896
|
+
check({ ...scopeArg, member: 'server', rowId: null, prefix: '' }, nameservers.length === 0, 'server');
|
|
897
|
+
}
|
|
898
|
+
singleton(scopeArg, 'server', contentArg.server, (memberScopeArg, valueArg) => {
|
|
899
|
+
const server = exact(memberScopeArg, valueArg, ['primaryNameserver'], null);
|
|
900
|
+
if (server !== null) {
|
|
901
|
+
check(memberScopeArg, typeof server.primaryNameserver === 'string'
|
|
902
|
+
&& nameservers.includes(server.primaryNameserver), 'primaryNameserver', 'dangling-reference');
|
|
903
|
+
}
|
|
904
|
+
});
|
|
905
|
+
singleton(scopeArg, 'acme', contentArg.acme, (memberScopeArg, valueArg) => {
|
|
906
|
+
const acme = exact(memberScopeArg, valueArg, [
|
|
907
|
+
'accountEmail', 'enabled', 'useProduction', 'directoryUrl', 'autoRenew', 'renewThresholdDays',
|
|
908
|
+
], null);
|
|
909
|
+
if (acme === null) {
|
|
910
|
+
return;
|
|
911
|
+
}
|
|
912
|
+
checkText(memberScopeArg, acme.accountEmail, 'accountEmail');
|
|
913
|
+
checkBoolean(memberScopeArg, acme.enabled, 'enabled');
|
|
914
|
+
checkBoolean(memberScopeArg, acme.useProduction, 'useProduction');
|
|
915
|
+
checkNullableText(memberScopeArg, acme.directoryUrl, 'directoryUrl', 2048);
|
|
916
|
+
checkBoolean(memberScopeArg, acme.autoRenew, 'autoRenew');
|
|
917
|
+
checkInteger(memberScopeArg, acme.renewThresholdDays, 'renewThresholdDays', 1);
|
|
918
|
+
});
|
|
919
|
+
const providerIds = rowList(scopeArg, 'providers', contentArg.providers, bounds.providers, (rowScopeArg, rowArg) => {
|
|
920
|
+
const row = exact(rowScopeArg, rowArg, ['id', 'name', 'credentials'], null);
|
|
921
|
+
if (row === null) {
|
|
922
|
+
return;
|
|
923
|
+
}
|
|
924
|
+
checkText(rowScopeArg, row.name, 'name');
|
|
925
|
+
const credentials = exact(rowScopeArg, row.credentials, ['type', 'apiToken'], 'credentials');
|
|
926
|
+
if (credentials !== null) {
|
|
927
|
+
checkOneOf(rowScopeArg, credentials.type, 'credentials.type', ['cloudflare']);
|
|
928
|
+
checkSealed(rowScopeArg, credentials.apiToken, 'credentials.apiToken');
|
|
929
|
+
}
|
|
930
|
+
});
|
|
931
|
+
const providers = new Set(providerIds);
|
|
932
|
+
const domainSources = new Map<string, unknown>();
|
|
933
|
+
const domainNames = new Map<string, unknown>();
|
|
934
|
+
rowList(scopeArg, 'domains', contentArg.domains, bounds.domains, (rowScopeArg, rowArg) => {
|
|
935
|
+
const row = exact(rowScopeArg, rowArg, ['id', 'name', 'source', 'providerId', 'description'], null);
|
|
936
|
+
if (row === null) {
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
if (rowScopeArg.rowId !== null) {
|
|
940
|
+
domainSources.set(rowScopeArg.rowId, row.source);
|
|
941
|
+
domainNames.set(rowScopeArg.rowId, row.name);
|
|
942
|
+
}
|
|
943
|
+
check(rowScopeArg, isZoneName(row.name), 'name');
|
|
944
|
+
checkOneOf(rowScopeArg, row.source, 'source', ['dcrouter', 'provider']);
|
|
945
|
+
if (row.source === 'provider') {
|
|
946
|
+
check(rowScopeArg, typeof row.providerId === 'string', 'providerId');
|
|
947
|
+
if (typeof row.providerId === 'string') {
|
|
948
|
+
check(rowScopeArg, providers.has(row.providerId), 'providerId', 'dangling-reference');
|
|
949
|
+
}
|
|
950
|
+
} else {
|
|
951
|
+
check(rowScopeArg, row.providerId === null, 'providerId');
|
|
952
|
+
}
|
|
953
|
+
checkNullableText(rowScopeArg, row.description, 'description', contract.maximumTextLength);
|
|
954
|
+
});
|
|
955
|
+
checkUniqueKey(scopeArg, 'domains', contentArg.domains, (rowArg) => field(rowArg, 'name'), 'name');
|
|
956
|
+
rowList(scopeArg, 'records', contentArg.records, bounds.records, (rowScopeArg, rowArg) => {
|
|
957
|
+
const row = exact(rowScopeArg, rowArg, ['id', 'domainId', 'name', 'type', 'value', 'ttl'], null);
|
|
958
|
+
if (row === null) {
|
|
959
|
+
return;
|
|
960
|
+
}
|
|
961
|
+
if (typeof row.domainId !== 'string') {
|
|
962
|
+
refuse(rowScopeArg, 'domainId', 'invalid-value');
|
|
963
|
+
} else if (!domainSources.has(row.domainId)) {
|
|
964
|
+
refuse(rowScopeArg, 'domainId', 'dangling-reference');
|
|
965
|
+
} else if (domainSources.get(row.domainId) !== 'dcrouter') {
|
|
966
|
+
refuse(rowScopeArg, 'domainId', 'reference-not-dcrouter-zone');
|
|
967
|
+
} else {
|
|
968
|
+
// A record lies inside its zone: the zone's name itself or a name below it, as written.
|
|
969
|
+
const zone = domainNames.get(row.domainId);
|
|
970
|
+
if (isText(row.name, 253) && isZoneName(zone)) {
|
|
971
|
+
check(rowScopeArg, row.name === zone || row.name.endsWith(`.${zone}`), 'name');
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
checkText(rowScopeArg, row.name, 'name', 253);
|
|
975
|
+
checkOneOf(rowScopeArg, row.type, 'type', gatewayDnsRecordTypes);
|
|
976
|
+
checkRecordValue(rowScopeArg, row.type, row.value);
|
|
977
|
+
checkInteger(rowScopeArg, row.ttl, 'ttl', 1);
|
|
978
|
+
});
|
|
979
|
+
rowList(scopeArg, 'staticRecords', contentArg.staticRecords, bounds.staticRecords, (rowScopeArg, rowArg) => {
|
|
980
|
+
const row = exact(rowScopeArg, rowArg, ['id', 'name', 'type', 'value', 'ttl', 'useIngressProxy'], null);
|
|
981
|
+
if (row === null) {
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
984
|
+
if (rowScopeArg.rowId !== null) {
|
|
985
|
+
check(rowScopeArg, /^static-[a-f0-9]{64}$/.test(rowScopeArg.rowId), 'id', 'invalid-row-id');
|
|
986
|
+
}
|
|
987
|
+
checkText(rowScopeArg, row.name, 'name', 253);
|
|
988
|
+
checkOneOf(rowScopeArg, row.type, 'type', gatewayDnsStaticRecordTypes);
|
|
989
|
+
checkRecordValue(rowScopeArg, row.type, row.value);
|
|
990
|
+
checkInteger(rowScopeArg, row.ttl, 'ttl', 1, true);
|
|
991
|
+
checkNullableBoolean(rowScopeArg, row.useIngressProxy, 'useIngressProxy');
|
|
992
|
+
});
|
|
993
|
+
// The id derives from `(name, type, value)` and is judged by form only, so the record is the key.
|
|
994
|
+
checkUniqueKey(scopeArg, 'staticRecords', contentArg.staticRecords, (rowArg) => {
|
|
995
|
+
const record = [field(rowArg, 'name'), field(rowArg, 'type'), field(rowArg, 'value')];
|
|
996
|
+
return record.every((partArg) => typeof partArg === 'string') ? JSON.stringify(record) : null;
|
|
997
|
+
}, null);
|
|
998
|
+
rowList(scopeArg, 'protectedHostnames', contentArg.protectedHostnames, bounds.protectedHostnames,
|
|
999
|
+
(rowScopeArg, rowArg) => {
|
|
1000
|
+
const row = exact(rowScopeArg, rowArg, ['id', 'reason'], null);
|
|
1001
|
+
if (row === null) {
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
1004
|
+
if (rowScopeArg.rowId !== null) {
|
|
1005
|
+
check(rowScopeArg, isGatewayClientHostname(rowScopeArg.rowId), 'id', 'invalid-row-id');
|
|
1006
|
+
}
|
|
1007
|
+
checkText(rowScopeArg, row.reason, 'reason', contract.maximumTextLength);
|
|
1008
|
+
});
|
|
1009
|
+
rowList(scopeArg, 'authorityZones', contentArg.authorityZones, bounds.authorityZones, (rowScopeArg, rowArg) => {
|
|
1010
|
+
if (exact(rowScopeArg, rowArg, ['id'], null) !== null && rowScopeArg.rowId !== null) {
|
|
1011
|
+
check(rowScopeArg, isZoneName(rowScopeArg.rowId), 'id', 'invalid-row-id');
|
|
1012
|
+
}
|
|
1013
|
+
});
|
|
1014
|
+
rowList(scopeArg, 'clientHostnames', contentArg.clientHostnames, bounds.clientHostnames, (rowScopeArg, rowArg) => {
|
|
1015
|
+
const row = exact(rowScopeArg, rowArg, ['id', 'client', 'record', 'holdsCertificate'], null);
|
|
1016
|
+
if (row === null) {
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
if (rowScopeArg.rowId !== null) {
|
|
1020
|
+
check(rowScopeArg, isGatewayClientHostname(rowScopeArg.rowId), 'id', 'invalid-row-id');
|
|
1021
|
+
}
|
|
1022
|
+
checkAttribution(rowScopeArg, row.client, 'client', { appId: true, externalKey: false });
|
|
1023
|
+
if (row.record !== null) {
|
|
1024
|
+
const record = exact(rowScopeArg, row.record, ['type', 'value', 'ttl'], 'record');
|
|
1025
|
+
if (record !== null) {
|
|
1026
|
+
check(rowScopeArg, validateGatewayClientDnsRecord(record).length === 0, 'record');
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
checkBoolean(rowScopeArg, row.holdsCertificate, 'holdsCertificate');
|
|
1030
|
+
});
|
|
1031
|
+
};
|
|
1032
|
+
|
|
1033
|
+
// ---------------------------------------------------------------------------------------------
|
|
1034
|
+
// routes
|
|
1035
|
+
// ---------------------------------------------------------------------------------------------
|
|
1036
|
+
|
|
1037
|
+
const checkOverride = (scopeArg: IScope, valueArg: unknown, pathArg: string): void => {
|
|
1038
|
+
const override = exact(scopeArg, valueArg, ['mode', 'value'], pathArg);
|
|
1039
|
+
if (override === null) {
|
|
1040
|
+
return;
|
|
1041
|
+
}
|
|
1042
|
+
const inner = nested(scopeArg, pathArg);
|
|
1043
|
+
checkOneOf(inner, override.mode, 'mode', ['inherit', 'clear', 'set']);
|
|
1044
|
+
if (override.mode === 'set') {
|
|
1045
|
+
checkEngineConfig(inner, override.value, 'value');
|
|
1046
|
+
} else {
|
|
1047
|
+
check(inner, override.value === null, 'value');
|
|
1048
|
+
}
|
|
1049
|
+
};
|
|
1050
|
+
|
|
1051
|
+
const checkExceededAction = (scopeArg: IScope, valueArg: unknown, pathArg: string): void => {
|
|
1052
|
+
if (valueArg === null) {
|
|
1053
|
+
return;
|
|
1054
|
+
}
|
|
1055
|
+
const action = exact(scopeArg, valueArg, ['type', 'errorMessage'], pathArg);
|
|
1056
|
+
if (action !== null) {
|
|
1057
|
+
checkOneOf(nested(scopeArg, pathArg), action.type, 'type', ['429']);
|
|
1058
|
+
checkNullableText(nested(scopeArg, pathArg), action.errorMessage, 'errorMessage', contract.maximumTextLength);
|
|
1059
|
+
}
|
|
1060
|
+
};
|
|
1061
|
+
|
|
1062
|
+
const checkSourceBinding = (scopeArg: IScope, valueArg: unknown, pathArg: string, profilesArg: Set<string>): void => {
|
|
1063
|
+
const binding = exact(scopeArg, valueArg, [
|
|
1064
|
+
'id', 'sourceProfileRef', 'rateLimit', 'challenge', 'maxConnections', 'onExceeded', 'pathPolicies',
|
|
1065
|
+
], pathArg);
|
|
1066
|
+
if (binding === null) {
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
const inner = nested(scopeArg, pathArg);
|
|
1070
|
+
checkNullableText(inner, binding.id, 'id');
|
|
1071
|
+
if (typeof binding.sourceProfileRef !== 'string') {
|
|
1072
|
+
refuse(inner, 'sourceProfileRef', 'invalid-value');
|
|
1073
|
+
} else {
|
|
1074
|
+
check(inner, profilesArg.has(binding.sourceProfileRef), 'sourceProfileRef', 'dangling-reference');
|
|
1075
|
+
}
|
|
1076
|
+
checkOverride(inner, binding.rateLimit, 'rateLimit');
|
|
1077
|
+
checkOverride(inner, binding.challenge, 'challenge');
|
|
1078
|
+
checkInteger(inner, binding.maxConnections, 'maxConnections', 0, true);
|
|
1079
|
+
checkExceededAction(inner, binding.onExceeded, 'onExceeded');
|
|
1080
|
+
const pathPolicies = list(inner, binding.pathPolicies, 'pathPolicies');
|
|
1081
|
+
pathPolicies?.forEach((policyArg, indexArg) => {
|
|
1082
|
+
const path = `pathPolicies[${indexArg}]`;
|
|
1083
|
+
const policy = exact(inner, policyArg, [
|
|
1084
|
+
'id', 'pathClass', 'pathPatterns', 'rateLimit', 'challenge', 'maxConnections', 'onExceeded',
|
|
1085
|
+
], path);
|
|
1086
|
+
if (policy === null) {
|
|
1087
|
+
return;
|
|
1088
|
+
}
|
|
1089
|
+
const policyScope = nested(inner, path);
|
|
1090
|
+
checkNullableText(policyScope, policy.id, 'id');
|
|
1091
|
+
checkOneOf(policyScope, policy.pathClass, 'pathClass', gatewayRoutePathClasses);
|
|
1092
|
+
if (policy.pathPatterns !== null) {
|
|
1093
|
+
checkTextSet(policyScope, policy.pathPatterns, 'pathPatterns');
|
|
1094
|
+
}
|
|
1095
|
+
checkOverride(policyScope, policy.rateLimit, 'rateLimit');
|
|
1096
|
+
checkOverride(policyScope, policy.challenge, 'challenge');
|
|
1097
|
+
checkInteger(policyScope, policy.maxConnections, 'maxConnections', 0, true);
|
|
1098
|
+
checkExceededAction(policyScope, policy.onExceeded, 'onExceeded');
|
|
1099
|
+
});
|
|
1100
|
+
};
|
|
1101
|
+
|
|
1102
|
+
/** The route members typed beside a route's SmartProxy configuration (Linus ruling 121, Q15). */
|
|
1103
|
+
const routeTypedMembers = ['ingress', 'remoteIngress', 'vpnOnly'] as const;
|
|
1104
|
+
|
|
1105
|
+
/**
|
|
1106
|
+
* The rows that lie on a cycle of hard references through two or more rows (Tarjan's strongly
|
|
1107
|
+
* connected components, iterative). `edgesArg` maps each row id to the row ids it references; a
|
|
1108
|
+
* reference to an id outside the map is no edge.
|
|
1109
|
+
*/
|
|
1110
|
+
const findReferenceCycles = (edgesArg: ReadonlyMap<string, readonly string[]>): Set<string> => {
|
|
1111
|
+
const order = new Map<string, number>();
|
|
1112
|
+
const lowest = new Map<string, number>();
|
|
1113
|
+
const stack: string[] = [];
|
|
1114
|
+
const onStack = new Set<string>();
|
|
1115
|
+
const onCycle = new Set<string>();
|
|
1116
|
+
const enter = (nodeArg: string): void => {
|
|
1117
|
+
order.set(nodeArg, order.size);
|
|
1118
|
+
lowest.set(nodeArg, order.get(nodeArg)!);
|
|
1119
|
+
stack.push(nodeArg);
|
|
1120
|
+
onStack.add(nodeArg);
|
|
1121
|
+
};
|
|
1122
|
+
for (const root of edgesArg.keys()) {
|
|
1123
|
+
if (order.has(root)) {
|
|
1124
|
+
continue;
|
|
1125
|
+
}
|
|
1126
|
+
enter(root);
|
|
1127
|
+
const frames: { node: string; next: number }[] = [{ node: root, next: 0 }];
|
|
1128
|
+
while (frames.length > 0) {
|
|
1129
|
+
const frame = frames[frames.length - 1];
|
|
1130
|
+
const targets = edgesArg.get(frame.node)!;
|
|
1131
|
+
if (frame.next < targets.length) {
|
|
1132
|
+
const target = targets[frame.next++];
|
|
1133
|
+
if (!edgesArg.has(target)) {
|
|
1134
|
+
continue;
|
|
1135
|
+
}
|
|
1136
|
+
if (!order.has(target)) {
|
|
1137
|
+
enter(target);
|
|
1138
|
+
frames.push({ node: target, next: 0 });
|
|
1139
|
+
} else if (onStack.has(target)) {
|
|
1140
|
+
lowest.set(frame.node, Math.min(lowest.get(frame.node)!, order.get(target)!));
|
|
1141
|
+
}
|
|
1142
|
+
continue;
|
|
1143
|
+
}
|
|
1144
|
+
frames.pop();
|
|
1145
|
+
if (frames.length > 0) {
|
|
1146
|
+
const parent = frames[frames.length - 1].node;
|
|
1147
|
+
lowest.set(parent, Math.min(lowest.get(parent)!, lowest.get(frame.node)!));
|
|
1148
|
+
}
|
|
1149
|
+
if (lowest.get(frame.node) === order.get(frame.node)) {
|
|
1150
|
+
const component: string[] = [];
|
|
1151
|
+
let member: string;
|
|
1152
|
+
do {
|
|
1153
|
+
member = stack.pop()!;
|
|
1154
|
+
onStack.delete(member);
|
|
1155
|
+
component.push(member);
|
|
1156
|
+
} while (member !== frame.node);
|
|
1157
|
+
if (component.length > 1) {
|
|
1158
|
+
component.forEach((memberArg) => onCycle.add(memberArg));
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
return onCycle;
|
|
1164
|
+
};
|
|
1165
|
+
|
|
1166
|
+
/** True for a `match.ports` in its one spelling: what `canonicalizeGatewayRoutePorts` answers. */
|
|
1167
|
+
const isCanonicalRoutePorts = (valueArg: unknown): boolean => {
|
|
1168
|
+
const entries = readDataElements(valueArg, Number.MAX_SAFE_INTEGER);
|
|
1169
|
+
if (entries === null) {
|
|
1170
|
+
return false;
|
|
1171
|
+
}
|
|
1172
|
+
let previousEnd = -1;
|
|
1173
|
+
for (const entry of entries) {
|
|
1174
|
+
let span: [number, number];
|
|
1175
|
+
if (isRoutePort(entry)) {
|
|
1176
|
+
span = [entry, entry];
|
|
1177
|
+
} else {
|
|
1178
|
+
const range = readExactDataRecord(entry, ['from', 'to']);
|
|
1179
|
+
const from = range?.from;
|
|
1180
|
+
const to = range?.to;
|
|
1181
|
+
if (!isRoutePort(from) || !isRoutePort(to) || from >= to) {
|
|
1182
|
+
return false;
|
|
1183
|
+
}
|
|
1184
|
+
span = [from, to];
|
|
1185
|
+
}
|
|
1186
|
+
// Ascending, and neither overlapping nor touching the entry before.
|
|
1187
|
+
if (span[0] <= previousEnd + 1) {
|
|
1188
|
+
return false;
|
|
1189
|
+
}
|
|
1190
|
+
previousEnd = span[1];
|
|
1191
|
+
}
|
|
1192
|
+
return true;
|
|
1193
|
+
};
|
|
1194
|
+
|
|
1195
|
+
/**
|
|
1196
|
+
* A route's ports in their one spelling (`IGatewayRouteRow.route`): `match.ports` as
|
|
1197
|
+
* `canonicalizeGatewayRoutePorts` answers it, and every `action.targets[].port` an integer 1 to 65535
|
|
1198
|
+
* or `'preserve'`. An absent member is the gateway's engine semantics to judge.
|
|
1199
|
+
*/
|
|
1200
|
+
const checkRoutePorts = (scopeArg: IScope, routeArg: unknown): void => {
|
|
1201
|
+
const ports = engineValueAt(routeArg, 'match.ports');
|
|
1202
|
+
if (ports !== undefined) {
|
|
1203
|
+
check(scopeArg, isCanonicalRoutePorts(ports), 'route.match.ports');
|
|
1204
|
+
}
|
|
1205
|
+
readDataElements(engineValueAt(routeArg, 'action.targets'), Number.MAX_SAFE_INTEGER)?.forEach((targetArg, indexArg) => {
|
|
1206
|
+
const port = readDataProperty(targetArg, 'port');
|
|
1207
|
+
if (port !== null) {
|
|
1208
|
+
check(scopeArg, isRoutePort(port.value) || port.value === 'preserve', `route.action.targets[${indexArg}].port`);
|
|
1209
|
+
}
|
|
1210
|
+
});
|
|
1211
|
+
};
|
|
1212
|
+
|
|
1213
|
+
const validateRoutes = (scopeArg: IScope, contentArg: Record<string, unknown>): void => {
|
|
1214
|
+
const bounds = contract.maximumRows.routes;
|
|
1215
|
+
const profileIds = readRowIds(contentArg.sourceProfiles);
|
|
1216
|
+
const targetIds = readRowIds(contentArg.networkTargets);
|
|
1217
|
+
rowList(scopeArg, 'routes', contentArg.routes, bounds.routes, (rowScopeArg, rowArg) => {
|
|
1218
|
+
const row = exact(rowScopeArg, rowArg, [
|
|
1219
|
+
'id', 'origin', 'systemKey', 'enabled', 'route', 'ingress', 'remoteIngress', 'vpnOnly', 'secrets', 'metadata',
|
|
1220
|
+
], null);
|
|
1221
|
+
if (row === null) {
|
|
1222
|
+
return;
|
|
1223
|
+
}
|
|
1224
|
+
checkOneOf(rowScopeArg, row.origin, 'origin', ['api', 'config']);
|
|
1225
|
+
if (row.origin === 'config') {
|
|
1226
|
+
check(rowScopeArg, isText(row.systemKey, contract.maximumRowIdLength)
|
|
1227
|
+
&& (row.systemKey as string).startsWith('config:') && (row.systemKey as string).length > 7, 'systemKey');
|
|
1228
|
+
} else {
|
|
1229
|
+
check(rowScopeArg, row.systemKey === null, 'systemKey');
|
|
1230
|
+
}
|
|
1231
|
+
checkBoolean(rowScopeArg, row.enabled, 'enabled');
|
|
1232
|
+
if (checkEngineConfig(rowScopeArg, row.route, 'route')) {
|
|
1233
|
+
for (const key of routeTypedMembers) {
|
|
1234
|
+
check(rowScopeArg, readDataProperty(row.route, key) === null, `route.${key}`, 'typed-member-in-engine-config');
|
|
1235
|
+
}
|
|
1236
|
+
checkRoutePorts(rowScopeArg, row.route);
|
|
1237
|
+
}
|
|
1238
|
+
if (row.ingress !== null) {
|
|
1239
|
+
const ingress = exact(rowScopeArg, row.ingress, ['directHub', 'smartVpn'], 'ingress');
|
|
1240
|
+
if (ingress !== null) {
|
|
1241
|
+
checkBoolean(nested(rowScopeArg, 'ingress'), ingress.directHub, 'directHub');
|
|
1242
|
+
checkBoolean(nested(rowScopeArg, 'ingress'), ingress.smartVpn, 'smartVpn');
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
if (row.remoteIngress !== null) {
|
|
1246
|
+
const remoteIngress = exact(rowScopeArg, row.remoteIngress, ['enabled', 'edgeFilter'], 'remoteIngress');
|
|
1247
|
+
if (remoteIngress !== null) {
|
|
1248
|
+
checkBoolean(nested(rowScopeArg, 'remoteIngress'), remoteIngress.enabled, 'enabled');
|
|
1249
|
+
checkTextSet(nested(rowScopeArg, 'remoteIngress'), remoteIngress.edgeFilter, 'edgeFilter');
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
checkBoolean(rowScopeArg, row.vpnOnly, 'vpnOnly');
|
|
1253
|
+
const secrets = exact(rowScopeArg, row.secrets, ['tlsKey', 'basicAuthUsers', 'jwtSecret', 'requestHeaders'],
|
|
1254
|
+
'secrets');
|
|
1255
|
+
if (secrets !== null) {
|
|
1256
|
+
checkNullableSealed(rowScopeArg, secrets.tlsKey, 'secrets.tlsKey');
|
|
1257
|
+
checkNullableSealed(rowScopeArg, secrets.basicAuthUsers, 'secrets.basicAuthUsers', decodeGatewayBasicAuthUsers);
|
|
1258
|
+
checkNullableSealed(rowScopeArg, secrets.jwtSecret, 'secrets.jwtSecret');
|
|
1259
|
+
checkNullableSealed(rowScopeArg, secrets.requestHeaders, 'secrets.requestHeaders', decodeGatewayRequestHeaders);
|
|
1260
|
+
if (isPlainRecord(row.route)) {
|
|
1261
|
+
checkLiftedCoherence(rowScopeArg, row.route, 'action.tls.certificate', secrets.tlsKey, 'secrets.tlsKey');
|
|
1262
|
+
checkLiftedCoherence(rowScopeArg, row.route, 'security.basicAuth', secrets.basicAuthUsers,
|
|
1263
|
+
'secrets.basicAuthUsers');
|
|
1264
|
+
checkLiftedCoherence(rowScopeArg, row.route, 'security.jwtAuth', secrets.jwtSecret, 'secrets.jwtSecret');
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
const metadata = exact(rowScopeArg, row.metadata, [
|
|
1268
|
+
'ownerType', 'client', 'sourceBindings', 'networkTargetRef', 'dnsMode', 'dnsProxied', 'managedRouteKind',
|
|
1269
|
+
], 'metadata');
|
|
1270
|
+
if (metadata === null) {
|
|
1271
|
+
return;
|
|
1272
|
+
}
|
|
1273
|
+
const inner = nested(rowScopeArg, 'metadata');
|
|
1274
|
+
checkOneOf(inner, metadata.ownerType, 'ownerType', ['operator', 'gatewayClient', 'system']);
|
|
1275
|
+
if (metadata.client === null) {
|
|
1276
|
+
check(inner, metadata.ownerType !== 'gatewayClient', 'client');
|
|
1277
|
+
} else {
|
|
1278
|
+
check(inner, metadata.ownerType === 'gatewayClient', 'client');
|
|
1279
|
+
checkAttribution(inner, metadata.client, 'client', { appId: null, externalKey: null });
|
|
1280
|
+
}
|
|
1281
|
+
list(inner, metadata.sourceBindings, 'sourceBindings')?.forEach((bindingArg, indexArg) => {
|
|
1282
|
+
checkSourceBinding(inner, bindingArg, `sourceBindings[${indexArg}]`, profileIds);
|
|
1283
|
+
});
|
|
1284
|
+
if (metadata.networkTargetRef !== null) {
|
|
1285
|
+
if (typeof metadata.networkTargetRef !== 'string') {
|
|
1286
|
+
refuse(inner, 'networkTargetRef', 'invalid-value');
|
|
1287
|
+
} else {
|
|
1288
|
+
check(inner, targetIds.has(metadata.networkTargetRef), 'networkTargetRef', 'dangling-reference');
|
|
1289
|
+
}
|
|
1290
|
+
// The gateway resolves the targets from the network target; a stored copy is a snapshot.
|
|
1291
|
+
check(rowScopeArg, engineValueAt(row.route, 'action.targets') === undefined, 'route.action.targets');
|
|
1292
|
+
}
|
|
1293
|
+
checkOneOf(inner, metadata.dnsMode, 'dnsMode', ['reconcile', 'observe', 'skip'], true);
|
|
1294
|
+
checkNullableBoolean(inner, metadata.dnsProxied, 'dnsProxied');
|
|
1295
|
+
checkOneOf(inner, metadata.managedRouteKind, 'managedRouteKind', ['letsencrypt-http01-forward'], true);
|
|
1296
|
+
});
|
|
1297
|
+
const profileReferences = new Map<string, readonly string[]>();
|
|
1298
|
+
const profileScopes = new Map<string, IScope>();
|
|
1299
|
+
rowList(scopeArg, 'sourceProfiles', contentArg.sourceProfiles, bounds.sourceProfiles, (rowScopeArg, rowArg) => {
|
|
1300
|
+
const row = exact(rowScopeArg, rowArg, ['id', 'name', 'description', 'security', 'secrets', 'extendsProfiles'],
|
|
1301
|
+
null);
|
|
1302
|
+
if (row === null) {
|
|
1303
|
+
return;
|
|
1304
|
+
}
|
|
1305
|
+
checkText(rowScopeArg, row.name, 'name');
|
|
1306
|
+
checkNullableText(rowScopeArg, row.description, 'description', contract.maximumTextLength);
|
|
1307
|
+
checkEngineConfig(rowScopeArg, row.security, 'security');
|
|
1308
|
+
const secrets = exact(rowScopeArg, row.secrets, ['basicAuthUsers', 'jwtSecret'], 'secrets');
|
|
1309
|
+
if (secrets !== null) {
|
|
1310
|
+
checkNullableSealed(rowScopeArg, secrets.basicAuthUsers, 'secrets.basicAuthUsers', decodeGatewayBasicAuthUsers);
|
|
1311
|
+
checkNullableSealed(rowScopeArg, secrets.jwtSecret, 'secrets.jwtSecret');
|
|
1312
|
+
if (isPlainRecord(row.security)) {
|
|
1313
|
+
checkLiftedCoherence(rowScopeArg, row.security, 'basicAuth', secrets.basicAuthUsers, 'secrets.basicAuthUsers');
|
|
1314
|
+
checkLiftedCoherence(rowScopeArg, row.security, 'jwtAuth', secrets.jwtSecret, 'secrets.jwtSecret');
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
const extendsProfiles = list(rowScopeArg, row.extendsProfiles, 'extendsProfiles');
|
|
1318
|
+
if (extendsProfiles !== null) {
|
|
1319
|
+
if (!extendsProfiles.every((entryArg) => typeof entryArg === 'string')
|
|
1320
|
+
|| new Set(extendsProfiles).size !== extendsProfiles.length
|
|
1321
|
+
|| (rowScopeArg.rowId !== null && extendsProfiles.includes(rowScopeArg.rowId))) {
|
|
1322
|
+
refuse(rowScopeArg, 'extendsProfiles', 'invalid-value');
|
|
1323
|
+
} else {
|
|
1324
|
+
if (!extendsProfiles.every((entryArg) => profileIds.has(entryArg as string))) {
|
|
1325
|
+
refuse(rowScopeArg, 'extendsProfiles', 'dangling-reference');
|
|
1326
|
+
}
|
|
1327
|
+
if (rowScopeArg.rowId !== null && !profileReferences.has(rowScopeArg.rowId)) {
|
|
1328
|
+
profileReferences.set(rowScopeArg.rowId, extendsProfiles as string[]);
|
|
1329
|
+
profileScopes.set(rowScopeArg.rowId, rowScopeArg);
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
});
|
|
1334
|
+
// A cycle of any length through `extendsProfiles`, judged here so a controller refuses it before it pushes.
|
|
1335
|
+
const cyclic = findReferenceCycles(profileReferences);
|
|
1336
|
+
for (const [id, profileScope] of profileScopes) {
|
|
1337
|
+
if (cyclic.has(id)) {
|
|
1338
|
+
refuse(profileScope, 'extendsProfiles', 'reference-cycle');
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
rowList(scopeArg, 'networkTargets', contentArg.networkTargets, bounds.networkTargets, (rowScopeArg, rowArg) => {
|
|
1342
|
+
const row = exact(rowScopeArg, rowArg, ['id', 'name', 'description', 'host', 'port'], null);
|
|
1343
|
+
if (row === null) {
|
|
1344
|
+
return;
|
|
1345
|
+
}
|
|
1346
|
+
checkText(rowScopeArg, row.name, 'name');
|
|
1347
|
+
checkNullableText(rowScopeArg, row.description, 'description', contract.maximumTextLength);
|
|
1348
|
+
if (typeof row.host === 'string') {
|
|
1349
|
+
checkText(rowScopeArg, row.host, 'host', 253);
|
|
1350
|
+
} else {
|
|
1351
|
+
const hosts = list(rowScopeArg, row.host, 'host');
|
|
1352
|
+
if (hosts !== null) {
|
|
1353
|
+
check(rowScopeArg, hosts.length >= 2 && hosts.every((hostArg) => isText(hostArg, 253))
|
|
1354
|
+
&& new Set(hosts).size === hosts.length, 'host');
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
check(rowScopeArg, isPort(row.port), 'port');
|
|
1358
|
+
});
|
|
1359
|
+
rowList(scopeArg, 'targetProfiles', contentArg.targetProfiles, bounds.targetProfiles, (rowScopeArg, rowArg) => {
|
|
1360
|
+
const row = exact(rowScopeArg, rowArg, [
|
|
1361
|
+
'id', 'name', 'description', 'domains', 'targets', 'routeRefs', 'allowRoutesByClientSourceIp',
|
|
1362
|
+
], null);
|
|
1363
|
+
if (row === null) {
|
|
1364
|
+
return;
|
|
1365
|
+
}
|
|
1366
|
+
checkText(rowScopeArg, row.name, 'name');
|
|
1367
|
+
checkNullableText(rowScopeArg, row.description, 'description', contract.maximumTextLength);
|
|
1368
|
+
checkTextSet(rowScopeArg, row.domains, 'domains');
|
|
1369
|
+
const targets = list(rowScopeArg, row.targets, 'targets');
|
|
1370
|
+
if (targets !== null) {
|
|
1371
|
+
const records = targets.map((targetArg) => readExactDataRecord(targetArg, ['ip', 'port']));
|
|
1372
|
+
if (!records.every((recordArg) => recordArg !== null && isText(recordArg.ip, 64) && isPort(recordArg.port))) {
|
|
1373
|
+
refuse(rowScopeArg, 'targets', 'invalid-value');
|
|
1374
|
+
} else {
|
|
1375
|
+
check(rowScopeArg, records.every((recordArg, indexArg) => {
|
|
1376
|
+
if (indexArg === 0) {
|
|
1377
|
+
return true;
|
|
1378
|
+
}
|
|
1379
|
+
const previous = records[indexArg - 1]!;
|
|
1380
|
+
const order = compareWireTokens(previous.ip as string, recordArg!.ip as string);
|
|
1381
|
+
return order < 0 || (order === 0 && (previous.port as number) < (recordArg!.port as number));
|
|
1382
|
+
}), 'targets', 'set-not-ascending');
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
checkTextSet(rowScopeArg, row.routeRefs, 'routeRefs', (entryArg) => isRowId(entryArg));
|
|
1386
|
+
checkBoolean(rowScopeArg, row.allowRoutesByClientSourceIp, 'allowRoutesByClientSourceIp');
|
|
1387
|
+
});
|
|
1388
|
+
checkUniqueKey(scopeArg, 'targetProfiles', contentArg.targetProfiles, (rowArg) => field(rowArg, 'name'), 'name');
|
|
1389
|
+
rowList(scopeArg, 'disabledSystemRoutes', contentArg.disabledSystemRoutes, bounds.disabledSystemRoutes,
|
|
1390
|
+
(rowScopeArg, rowArg) => {
|
|
1391
|
+
if (exact(rowScopeArg, rowArg, ['id'], null) !== null && rowScopeArg.rowId !== null) {
|
|
1392
|
+
check(rowScopeArg, /^(?:email|dns):./.test(rowScopeArg.rowId), 'id', 'invalid-row-id');
|
|
1393
|
+
}
|
|
1394
|
+
});
|
|
1395
|
+
singleton(scopeArg, 'http3', contentArg.http3, (memberScopeArg, valueArg) => {
|
|
1396
|
+
const http3 = exact(memberScopeArg, valueArg, ['enabled', 'quicSettings', 'altSvc', 'udpSettings'], null);
|
|
1397
|
+
if (http3 === null) {
|
|
1398
|
+
return;
|
|
1399
|
+
}
|
|
1400
|
+
checkNullableBoolean(memberScopeArg, http3.enabled, 'enabled');
|
|
1401
|
+
const groups: [string, readonly string[]][] = [
|
|
1402
|
+
['quicSettings', ['maxIdleTimeout', 'maxConcurrentBidiStreams', 'maxConcurrentUniStreams', 'initialCongestionWindow']],
|
|
1403
|
+
['altSvc', ['port', 'maxAge']],
|
|
1404
|
+
['udpSettings', ['sessionTimeout', 'maxSessionsPerIP', 'maxDatagramSize']],
|
|
1405
|
+
];
|
|
1406
|
+
for (const [groupKey, keys] of groups) {
|
|
1407
|
+
if (http3[groupKey] === null) {
|
|
1408
|
+
continue;
|
|
1409
|
+
}
|
|
1410
|
+
const group = exact(memberScopeArg, http3[groupKey], keys, groupKey);
|
|
1411
|
+
if (group !== null) {
|
|
1412
|
+
for (const key of keys) {
|
|
1413
|
+
checkInteger(nested(memberScopeArg, groupKey), group[key], key, 0, true);
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
});
|
|
1418
|
+
};
|
|
1419
|
+
|
|
1420
|
+
// ---------------------------------------------------------------------------------------------
|
|
1421
|
+
// mail
|
|
1422
|
+
// ---------------------------------------------------------------------------------------------
|
|
1423
|
+
|
|
1424
|
+
const checkPortRecord = (scopeArg: IScope, valueArg: unknown, pathArg: string,
|
|
1425
|
+
checkEntryArg: (entryScopeArg: IScope, entryArg: unknown, keyArg: string) => void): void => {
|
|
1426
|
+
if (!isPlainRecord(valueArg)) {
|
|
1427
|
+
refuse(scopeArg, pathArg, 'invalid-value');
|
|
1428
|
+
return;
|
|
1429
|
+
}
|
|
1430
|
+
const keys = Object.keys(valueArg);
|
|
1431
|
+
if (keys.length > 65_535) {
|
|
1432
|
+
refuse(scopeArg, pathArg, 'bound-exceeded');
|
|
1433
|
+
return;
|
|
1434
|
+
}
|
|
1435
|
+
for (const key of keys) {
|
|
1436
|
+
const property = readDataProperty(valueArg, key);
|
|
1437
|
+
if (!portKey.test(key) || Number(key) > 65_535 || property === null) {
|
|
1438
|
+
refuse(scopeArg, pathArg, 'invalid-value');
|
|
1439
|
+
return;
|
|
1440
|
+
}
|
|
1441
|
+
checkEntryArg(nested(scopeArg, pathArg), property.value, key);
|
|
1442
|
+
}
|
|
1443
|
+
};
|
|
1444
|
+
|
|
1445
|
+
const checkInboundTarget = (scopeArg: IScope, valueArg: unknown): void => {
|
|
1446
|
+
const type = readDataProperty(valueArg, 'type')?.value;
|
|
1447
|
+
if (type === 'smtpForward') {
|
|
1448
|
+
const target = exact(scopeArg, valueArg, ['type', 'smtpForward'], 'inboundTarget');
|
|
1449
|
+
const forward = target && exact(scopeArg, target.smtpForward, [
|
|
1450
|
+
'host', 'port', 'credentialRef', 'preserveHeaders', 'addHeaders',
|
|
1451
|
+
], 'inboundTarget.smtpForward');
|
|
1452
|
+
if (forward) {
|
|
1453
|
+
const inner = nested(scopeArg, 'inboundTarget.smtpForward');
|
|
1454
|
+
checkText(inner, forward.host, 'host', 253);
|
|
1455
|
+
check(inner, isPort(forward.port), 'port');
|
|
1456
|
+
checkNullableText(inner, forward.credentialRef, 'credentialRef');
|
|
1457
|
+
checkNullableBoolean(inner, forward.preserveHeaders, 'preserveHeaders');
|
|
1458
|
+
if (forward.addHeaders !== null) {
|
|
1459
|
+
check(inner, isPlainRecord(forward.addHeaders) && Object.keys(forward.addHeaders).every((keyArg) => (
|
|
1460
|
+
keyArg.length > 0 && typeof readDataProperty(forward.addHeaders, keyArg)?.value === 'string'
|
|
1461
|
+
)), 'addHeaders');
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
} else if (type === 'typedEndpoint') {
|
|
1465
|
+
const target = exact(scopeArg, valueArg, ['type', 'typedEndpoint'], 'inboundTarget');
|
|
1466
|
+
const endpoint = target && exact(scopeArg, target.typedEndpoint, ['method', 'serviceRef', 'queueName', 'timeoutMs'],
|
|
1467
|
+
'inboundTarget.typedEndpoint');
|
|
1468
|
+
if (endpoint) {
|
|
1469
|
+
const inner = nested(scopeArg, 'inboundTarget.typedEndpoint');
|
|
1470
|
+
checkText(inner, endpoint.method, 'method');
|
|
1471
|
+
checkNullableText(inner, endpoint.serviceRef, 'serviceRef');
|
|
1472
|
+
checkNullableText(inner, endpoint.queueName, 'queueName');
|
|
1473
|
+
checkInteger(inner, endpoint.timeoutMs, 'timeoutMs', 1, true);
|
|
1474
|
+
}
|
|
1475
|
+
} else if (type === 'coreMail') {
|
|
1476
|
+
const target = exact(scopeArg, valueArg, ['type', 'coreMail'], 'inboundTarget');
|
|
1477
|
+
const coreMail = target && exact(scopeArg, target.coreMail, ['coreMailServiceId'], 'inboundTarget.coreMail');
|
|
1478
|
+
if (coreMail) {
|
|
1479
|
+
checkText(nested(scopeArg, 'inboundTarget.coreMail'), coreMail.coreMailServiceId, 'coreMailServiceId');
|
|
1480
|
+
}
|
|
1481
|
+
} else {
|
|
1482
|
+
refuse(scopeArg, 'inboundTarget.type', 'invalid-value');
|
|
1483
|
+
}
|
|
1484
|
+
};
|
|
1485
|
+
|
|
1486
|
+
const checkCoreMailVerifiers = (scopeArg: IScope, valueArg: unknown): void => {
|
|
1487
|
+
const credentials = list(scopeArg, valueArg, 'credentials');
|
|
1488
|
+
if (credentials === null) {
|
|
1489
|
+
return;
|
|
1490
|
+
}
|
|
1491
|
+
const versions: number[] = [];
|
|
1492
|
+
credentials.forEach((credentialArg, indexArg) => {
|
|
1493
|
+
const path = `credentials[${indexArg}]`;
|
|
1494
|
+
const record = readExactDataRecord(credentialArg, [
|
|
1495
|
+
'credentialId', 'version', 'state', 'format', 'verificationHash', 'acceptUntil',
|
|
1496
|
+
]);
|
|
1497
|
+
if (record === null) {
|
|
1498
|
+
refuse(scopeArg, path, 'exact-keys');
|
|
1499
|
+
return;
|
|
1500
|
+
}
|
|
1501
|
+
const { acceptUntil, ...native } = record;
|
|
1502
|
+
let valid = (record.state === 'current') === (acceptUntil === null);
|
|
1503
|
+
try {
|
|
1504
|
+
const normalized = normalizeCoreMailCredentialVerifier(
|
|
1505
|
+
acceptUntil === null ? native : { ...native, acceptUntil }, path,
|
|
1506
|
+
);
|
|
1507
|
+
valid &&= normalized.verificationHash === record.verificationHash;
|
|
1508
|
+
} catch {
|
|
1509
|
+
valid = false;
|
|
1510
|
+
}
|
|
1511
|
+
if (!valid) {
|
|
1512
|
+
refuse(scopeArg, path, 'invalid-verifier');
|
|
1513
|
+
return;
|
|
1514
|
+
}
|
|
1515
|
+
versions.push(record.version as number);
|
|
1516
|
+
});
|
|
1517
|
+
if (versions.length === credentials.length) {
|
|
1518
|
+
check(scopeArg, versions.every((versionArg, indexArg) => indexArg === 0 || versions[indexArg - 1] < versionArg),
|
|
1519
|
+
'credentials', 'set-not-ascending');
|
|
1520
|
+
}
|
|
1521
|
+
};
|
|
1522
|
+
|
|
1523
|
+
/**
|
|
1524
|
+
* The dns domain ids a mail table's `linkedDomainId` is judged against: the document's own dns
|
|
1525
|
+
* table, `missing` when a whole document carries none, `unjudged` for one area on its own.
|
|
1526
|
+
*/
|
|
1527
|
+
type TDnsDomainReference = Set<string> | 'missing' | 'unjudged';
|
|
1528
|
+
|
|
1529
|
+
const validateMail = (scopeArg: IScope, contentArg: Record<string, unknown>, dnsDomainsArg: TDnsDomainReference): void => {
|
|
1530
|
+
const bounds = contract.maximumRows.mail;
|
|
1531
|
+
// The server settings are always stated (Linus ruling 128, B1): a gateway always stores them, and
|
|
1532
|
+
// mail that is not configured is `enabled: false`, never `null`.
|
|
1533
|
+
requiredSingleton(scopeArg, 'server', contentArg.server, (memberScopeArg, valueArg) => {
|
|
1534
|
+
const server = exact(memberScopeArg, valueArg, [
|
|
1535
|
+
'enabled', 'outboundMode', 'emailConfig', 'tlsKey', 'emailPortConfig', 'tlsSource',
|
|
1536
|
+
], null);
|
|
1537
|
+
if (server === null) {
|
|
1538
|
+
return;
|
|
1539
|
+
}
|
|
1540
|
+
checkBoolean(memberScopeArg, server.enabled, 'enabled');
|
|
1541
|
+
checkOneOf(memberScopeArg, server.outboundMode, 'outboundMode', ['direct', 'remoteIngress']);
|
|
1542
|
+
if (server.emailConfig !== null) {
|
|
1543
|
+
checkEngineConfig(memberScopeArg, server.emailConfig, 'emailConfig');
|
|
1544
|
+
}
|
|
1545
|
+
checkNullableSealed(memberScopeArg, server.tlsKey, 'tlsKey');
|
|
1546
|
+
if (server.tlsKey !== null) {
|
|
1547
|
+
check(memberScopeArg, isPlainRecord(engineValueAt(server.emailConfig, 'tls')), 'tlsKey', 'secret-engine-mismatch');
|
|
1548
|
+
}
|
|
1549
|
+
// Always the object (Linus ruling 128, B2): no port configuration is `{ portMapping: null,
|
|
1550
|
+
// portSettings: {} }`, so `null` fails the shape check like any other non-object.
|
|
1551
|
+
const portConfig = exact(memberScopeArg, server.emailPortConfig, ['portMapping', 'portSettings'],
|
|
1552
|
+
'emailPortConfig');
|
|
1553
|
+
if (portConfig !== null) {
|
|
1554
|
+
const inner = nested(memberScopeArg, 'emailPortConfig');
|
|
1555
|
+
if (portConfig.portMapping !== null) {
|
|
1556
|
+
// The gateway maps a port missing from the mapping to port + 10000, as it does without one,
|
|
1557
|
+
// so an empty mapping is a second spelling of `null`.
|
|
1558
|
+
if (isPlainRecord(portConfig.portMapping) && Object.keys(portConfig.portMapping).length === 0) {
|
|
1559
|
+
refuse(inner, 'portMapping', 'invalid-value');
|
|
1560
|
+
} else {
|
|
1561
|
+
checkPortRecord(inner, portConfig.portMapping, 'portMapping', (entryScopeArg, entryArg, keyArg) => {
|
|
1562
|
+
check(entryScopeArg, isPort(entryArg), keyArg);
|
|
1563
|
+
});
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
checkPortRecord(inner, portConfig.portSettings, 'portSettings', (entryScopeArg, entryArg, keyArg) => {
|
|
1567
|
+
const settings = exact(entryScopeArg, entryArg, ['terminateTls', 'routeName'], keyArg);
|
|
1568
|
+
if (settings !== null) {
|
|
1569
|
+
checkBoolean(nested(entryScopeArg, keyArg), settings.terminateTls, 'terminateTls');
|
|
1570
|
+
checkNullableText(nested(entryScopeArg, keyArg), settings.routeName, 'routeName');
|
|
1571
|
+
}
|
|
1572
|
+
});
|
|
1573
|
+
}
|
|
1574
|
+
checkOneOf(memberScopeArg, server.tlsSource, 'tlsSource', ['managedCertificate', 'configuredMaterial']);
|
|
1575
|
+
});
|
|
1576
|
+
rowList(scopeArg, 'domains', contentArg.domains, bounds.domains, (rowScopeArg, rowArg) => {
|
|
1577
|
+
const row = exact(rowScopeArg, rowArg, [
|
|
1578
|
+
'id', 'domain', 'linkedDomainId', 'subdomain', 'dkim', 'rateLimits', 'edgeFilter',
|
|
1579
|
+
], null);
|
|
1580
|
+
if (row === null) {
|
|
1581
|
+
return;
|
|
1582
|
+
}
|
|
1583
|
+
check(rowScopeArg, isZoneName(row.domain), 'domain');
|
|
1584
|
+
if (typeof row.linkedDomainId !== 'string') {
|
|
1585
|
+
refuse(rowScopeArg, 'linkedDomainId', 'invalid-value');
|
|
1586
|
+
} else if (dnsDomainsArg instanceof Set) {
|
|
1587
|
+
check(rowScopeArg, dnsDomainsArg.has(row.linkedDomainId), 'linkedDomainId', 'dangling-reference');
|
|
1588
|
+
}
|
|
1589
|
+
checkNullableText(rowScopeArg, row.subdomain, 'subdomain', 63);
|
|
1590
|
+
const dkim = exact(rowScopeArg, row.dkim, [
|
|
1591
|
+
'initialSelector', 'keySize', 'rotateKeys', 'rotationIntervalDays', 'retirementOverlapDays',
|
|
1592
|
+
], 'dkim');
|
|
1593
|
+
if (dkim !== null) {
|
|
1594
|
+
const inner = nested(rowScopeArg, 'dkim');
|
|
1595
|
+
checkText(inner, dkim.initialSelector, 'initialSelector', 63);
|
|
1596
|
+
checkInteger(inner, dkim.keySize, 'keySize', 1);
|
|
1597
|
+
checkBoolean(inner, dkim.rotateKeys, 'rotateKeys');
|
|
1598
|
+
checkInteger(inner, dkim.rotationIntervalDays, 'rotationIntervalDays', 1);
|
|
1599
|
+
checkInteger(inner, dkim.retirementOverlapDays, 'retirementOverlapDays', 0, true);
|
|
1600
|
+
}
|
|
1601
|
+
if (row.rateLimits !== null) {
|
|
1602
|
+
const limits = exact(rowScopeArg, row.rateLimits, ['outbound', 'inbound'], 'rateLimits');
|
|
1603
|
+
const groups: [string, readonly string[]][] = [
|
|
1604
|
+
['outbound', ['messagesPerMinute', 'messagesPerHour', 'messagesPerDay']],
|
|
1605
|
+
['inbound', ['messagesPerMinute', 'connectionsPerIp', 'recipientsPerMessage']],
|
|
1606
|
+
];
|
|
1607
|
+
for (const [groupKey, keys] of limits === null ? [] : groups) {
|
|
1608
|
+
if (limits![groupKey] === null) {
|
|
1609
|
+
continue;
|
|
1610
|
+
}
|
|
1611
|
+
const group = exact(nested(rowScopeArg, 'rateLimits'), limits![groupKey], keys, groupKey);
|
|
1612
|
+
if (group !== null) {
|
|
1613
|
+
for (const key of keys) {
|
|
1614
|
+
checkInteger(nested(rowScopeArg, `rateLimits.${groupKey}`), group[key], key, 0, true);
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
checkTextSet(rowScopeArg, row.edgeFilter, 'edgeFilter');
|
|
1620
|
+
});
|
|
1621
|
+
checkUniqueKey(scopeArg, 'domains', contentArg.domains, (rowArg) => field(rowArg, 'domain'), 'domain');
|
|
1622
|
+
if (dnsDomainsArg === 'missing' && Array.isArray(contentArg.domains) && contentArg.domains.length > 0) {
|
|
1623
|
+
refuse({ ...scopeArg, member: 'domains', rowId: null, prefix: '' }, 'linkedDomainId', 'referenced-area-missing');
|
|
1624
|
+
}
|
|
1625
|
+
rowList(scopeArg, 'smtpAccounts', contentArg.smtpAccounts, bounds.smtpAccounts, (rowScopeArg, rowArg) => {
|
|
1626
|
+
const row = exact(rowScopeArg, rowArg, [
|
|
1627
|
+
'id', 'username', 'description', 'enabled', 'credential', 'senderScope', 'recipientScope', 'mailPolicy',
|
|
1628
|
+
], null);
|
|
1629
|
+
if (row === null) {
|
|
1630
|
+
return;
|
|
1631
|
+
}
|
|
1632
|
+
checkText(rowScopeArg, row.username, 'username');
|
|
1633
|
+
check(rowScopeArg, typeof row.description === 'string' && row.description.length <= contract.maximumTextLength,
|
|
1634
|
+
'description');
|
|
1635
|
+
checkBoolean(rowScopeArg, row.enabled, 'enabled');
|
|
1636
|
+
checkScramVerifier(rowScopeArg, row.credential, 'credential', null);
|
|
1637
|
+
const sender = exact(rowScopeArg, row.senderScope, ['addresses', 'domains'], 'senderScope');
|
|
1638
|
+
if (sender !== null) {
|
|
1639
|
+
checkTextSet(nested(rowScopeArg, 'senderScope'), sender.addresses, 'addresses');
|
|
1640
|
+
checkTextSet(nested(rowScopeArg, 'senderScope'), sender.domains, 'domains');
|
|
1641
|
+
}
|
|
1642
|
+
const recipient = exact(rowScopeArg, row.recipientScope, ['mode', 'addresses', 'domains'], 'recipientScope');
|
|
1643
|
+
if (recipient !== null) {
|
|
1644
|
+
checkOneOf(nested(rowScopeArg, 'recipientScope'), recipient.mode, 'mode', ['any', 'restricted']);
|
|
1645
|
+
checkTextSet(nested(rowScopeArg, 'recipientScope'), recipient.addresses, 'addresses');
|
|
1646
|
+
checkTextSet(nested(rowScopeArg, 'recipientScope'), recipient.domains, 'domains');
|
|
1647
|
+
}
|
|
1648
|
+
const policy = exact(rowScopeArg, row.mailPolicy, ['dkimSign', 'queue'], 'mailPolicy');
|
|
1649
|
+
if (policy !== null) {
|
|
1650
|
+
checkBoolean(nested(rowScopeArg, 'mailPolicy'), policy.dkimSign, 'dkimSign');
|
|
1651
|
+
checkOneOf(nested(rowScopeArg, 'mailPolicy'), policy.queue, 'queue', ['normal', 'priority', 'bulk'], true);
|
|
1652
|
+
}
|
|
1653
|
+
});
|
|
1654
|
+
checkUniqueKey(scopeArg, 'smtpAccounts', contentArg.smtpAccounts, (rowArg) => field(rowArg, 'username'), 'username');
|
|
1655
|
+
rowList(scopeArg, 'identities', contentArg.identities, bounds.identities, (rowScopeArg, rowArg) => {
|
|
1656
|
+
const row = exact(rowScopeArg, rowArg, [
|
|
1657
|
+
'id', 'client', 'localPart', 'domain', 'enabled', 'displayName', 'inboundTarget', 'smtp', 'credential',
|
|
1658
|
+
], null);
|
|
1659
|
+
if (row === null) {
|
|
1660
|
+
return;
|
|
1661
|
+
}
|
|
1662
|
+
checkAttribution(rowScopeArg, row.client, 'client', { appId: true, externalKey: true });
|
|
1663
|
+
check(rowScopeArg, isText(row.localPart, 64) && !/[@\sA-Z]/.test(row.localPart as string), 'localPart');
|
|
1664
|
+
check(rowScopeArg, isZoneName(row.domain), 'domain');
|
|
1665
|
+
checkBoolean(rowScopeArg, row.enabled, 'enabled');
|
|
1666
|
+
checkNullableText(rowScopeArg, row.displayName, 'displayName');
|
|
1667
|
+
if (row.inboundTarget !== null) {
|
|
1668
|
+
checkInboundTarget(rowScopeArg, row.inboundTarget);
|
|
1669
|
+
}
|
|
1670
|
+
const smtp = exact(rowScopeArg, row.smtp, ['enabled', 'username'], 'smtp');
|
|
1671
|
+
if (smtp !== null) {
|
|
1672
|
+
checkBoolean(nested(rowScopeArg, 'smtp'), smtp.enabled, 'enabled');
|
|
1673
|
+
checkText(nested(rowScopeArg, 'smtp'), smtp.username, 'username');
|
|
1674
|
+
}
|
|
1675
|
+
checkScramVerifier(rowScopeArg, row.credential, 'credential', gatewayMailIdentityScramIterations);
|
|
1676
|
+
});
|
|
1677
|
+
checkUniqueKey(scopeArg, 'identities', contentArg.identities, (rowArg) => {
|
|
1678
|
+
const localPart = field(rowArg, 'localPart');
|
|
1679
|
+
const domain = field(rowArg, 'domain');
|
|
1680
|
+
return typeof localPart === 'string' && typeof domain === 'string' ? `${localPart}@${domain}` : null;
|
|
1681
|
+
}, 'localPart');
|
|
1682
|
+
rowList(scopeArg, 'coreMailPeers', contentArg.coreMailPeers, bounds.coreMailPeers, (rowScopeArg, rowArg) => {
|
|
1683
|
+
const row = exact(rowScopeArg, rowArg, ['id', 'client', 'coreMailServiceId', 'transferOrigin', 'credentials'], null);
|
|
1684
|
+
if (row === null) {
|
|
1685
|
+
return;
|
|
1686
|
+
}
|
|
1687
|
+
checkAttribution(rowScopeArg, row.client, 'client', { appId: false, externalKey: false });
|
|
1688
|
+
checkText(rowScopeArg, row.coreMailServiceId, 'coreMailServiceId');
|
|
1689
|
+
checkText(rowScopeArg, row.transferOrigin, 'transferOrigin', 2048);
|
|
1690
|
+
checkCoreMailVerifiers(rowScopeArg, row.credentials);
|
|
1691
|
+
});
|
|
1692
|
+
};
|
|
1693
|
+
|
|
1694
|
+
// ---------------------------------------------------------------------------------------------
|
|
1695
|
+
// edges
|
|
1696
|
+
// ---------------------------------------------------------------------------------------------
|
|
1697
|
+
|
|
1698
|
+
const performanceKeys = [
|
|
1699
|
+
'profile', 'maxStreamsPerEdge', 'totalWindowBudgetBytes', 'minStreamWindowBytes', 'maxStreamWindowBytes',
|
|
1700
|
+
'sustainedStreamWindowBytes', 'quicDatagramReceiveBufferBytes', 'streamFramePayloadBytes',
|
|
1701
|
+
'firstDataConnectTimeoutMs', 'clientWriteTimeoutMs', 'maxHalfClosedStreams', 'halfCloseDrainTimeoutMs',
|
|
1702
|
+
'serverFirstPorts',
|
|
1703
|
+
] as const;
|
|
1704
|
+
|
|
1705
|
+
/**
|
|
1706
|
+
* A list member of an edge setting that is `null` or a non-empty list judged by `checkListArg`: the
|
|
1707
|
+
* gateway stores an empty list as no setting, so `[]` is a second spelling of `null` (ruling 125, Q-b7).
|
|
1708
|
+
*/
|
|
1709
|
+
const checkNullableNonEmptyList = (
|
|
1710
|
+
scopeArg: IScope,
|
|
1711
|
+
valueArg: unknown,
|
|
1712
|
+
pathArg: string,
|
|
1713
|
+
checkListArg: (scopeArg: IScope, valueArg: unknown, pathArg: string) => void,
|
|
1714
|
+
): void => {
|
|
1715
|
+
if (valueArg === null) {
|
|
1716
|
+
return;
|
|
1717
|
+
}
|
|
1718
|
+
if (Array.isArray(valueArg) && valueArg.length === 0) {
|
|
1719
|
+
refuse(scopeArg, pathArg, 'invalid-value');
|
|
1720
|
+
return;
|
|
1721
|
+
}
|
|
1722
|
+
checkListArg(scopeArg, valueArg, pathArg);
|
|
1723
|
+
};
|
|
1724
|
+
|
|
1725
|
+
const checkPerformance = (scopeArg: IScope, valueArg: unknown, pathArg: string): void => {
|
|
1726
|
+
if (valueArg === null) {
|
|
1727
|
+
return;
|
|
1728
|
+
}
|
|
1729
|
+
const performance = exact(scopeArg, valueArg, performanceKeys, pathArg);
|
|
1730
|
+
if (performance === null) {
|
|
1731
|
+
return;
|
|
1732
|
+
}
|
|
1733
|
+
// Settings that state nothing are the owner's `performance: null`, never an object of `null`s.
|
|
1734
|
+
if (performanceKeys.every((keyArg) => performance[keyArg] === null)) {
|
|
1735
|
+
refuse(scopeArg, pathArg, 'invalid-value');
|
|
1736
|
+
return;
|
|
1737
|
+
}
|
|
1738
|
+
const inner = nested(scopeArg, pathArg);
|
|
1739
|
+
for (const key of performanceKeys) {
|
|
1740
|
+
if (key === 'profile') {
|
|
1741
|
+
checkOneOf(inner, performance.profile, 'profile', ['balanced', 'throughput', 'highConcurrency'], true);
|
|
1742
|
+
} else if (key === 'serverFirstPorts') {
|
|
1743
|
+
checkNullableNonEmptyList(inner, performance.serverFirstPorts, 'serverFirstPorts', checkPortSet);
|
|
1744
|
+
} else {
|
|
1745
|
+
checkInteger(inner, performance[key], key, 0, true);
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
};
|
|
1749
|
+
|
|
1750
|
+
const egressSettingKeys = [
|
|
1751
|
+
'allowedPorts', 'allowPrivateRanges', 'deniedCidrs', 'allowedHostPatterns', 'maxConcurrentStreams',
|
|
1752
|
+
] as const;
|
|
1753
|
+
|
|
1754
|
+
/**
|
|
1755
|
+
* An edge's egress policy in its one spelling (ruling 125, Q-b7): always the object, so `null` fails
|
|
1756
|
+
* the shape check (the gateway reads no policy and a disabled one alike; ruling 128, B2's pattern);
|
|
1757
|
+
* enabled, it states its ports (the gateway's default `[25]` written out); disabled, every setting is
|
|
1758
|
+
* `null`, because the gateway keeps only `enabled` of a disabled policy; a list is `null` or non-empty.
|
|
1759
|
+
*/
|
|
1760
|
+
const checkEgress = (scopeArg: IScope, valueArg: unknown): void => {
|
|
1761
|
+
const egress = exact(scopeArg, valueArg, ['enabled', ...egressSettingKeys], 'egress');
|
|
1762
|
+
if (egress === null) {
|
|
1763
|
+
return;
|
|
1764
|
+
}
|
|
1765
|
+
const inner = nested(scopeArg, 'egress');
|
|
1766
|
+
checkBoolean(inner, egress.enabled, 'enabled');
|
|
1767
|
+
if (egress.enabled === false) {
|
|
1768
|
+
for (const key of egressSettingKeys) {
|
|
1769
|
+
check(inner, egress[key] === null, key);
|
|
1770
|
+
}
|
|
1771
|
+
return;
|
|
1772
|
+
}
|
|
1773
|
+
if (egress.enabled === true) {
|
|
1774
|
+
check(inner, egress.allowedPorts !== null, 'allowedPorts');
|
|
1775
|
+
}
|
|
1776
|
+
checkNullableNonEmptyList(inner, egress.allowedPorts, 'allowedPorts', checkPortSet);
|
|
1777
|
+
checkNullableBoolean(inner, egress.allowPrivateRanges, 'allowPrivateRanges');
|
|
1778
|
+
checkNullableNonEmptyList(inner, egress.deniedCidrs, 'deniedCidrs', checkTextSet);
|
|
1779
|
+
checkNullableNonEmptyList(inner, egress.allowedHostPatterns, 'allowedHostPatterns', checkTextSet);
|
|
1780
|
+
checkInteger(inner, egress.maxConcurrentStreams, 'maxConcurrentStreams', 0, true);
|
|
1781
|
+
};
|
|
1782
|
+
|
|
1783
|
+
const validateEdges = (scopeArg: IScope, contentArg: Record<string, unknown>): void => {
|
|
1784
|
+
// The hub is always stated (ruling 125, Q-b5): a hub that is off is `enabled: false`, never `null`.
|
|
1785
|
+
requiredSingleton(scopeArg, 'hub', contentArg.hub, (memberScopeArg, valueArg) => {
|
|
1786
|
+
const hub = exact(memberScopeArg, valueArg, ['enabled', 'hubDomain', 'performance'], null);
|
|
1787
|
+
if (hub !== null) {
|
|
1788
|
+
checkBoolean(memberScopeArg, hub.enabled, 'enabled');
|
|
1789
|
+
checkNullableText(memberScopeArg, hub.hubDomain, 'hubDomain', 253);
|
|
1790
|
+
checkPerformance(memberScopeArg, hub.performance, 'performance');
|
|
1791
|
+
}
|
|
1792
|
+
});
|
|
1793
|
+
rowList(scopeArg, 'edges', contentArg.edges, contract.maximumRows.edges.edges, (rowScopeArg, rowArg) => {
|
|
1794
|
+
const row = exact(rowScopeArg, rowArg, [
|
|
1795
|
+
'id', 'name', 'secret', 'listenPorts', 'listenPortsUdp', 'enabled', 'autoDerivePorts', 'performance', 'egress',
|
|
1796
|
+
'tags', 'publicIp', 'publicIpv6', 'mailHostname',
|
|
1797
|
+
], null);
|
|
1798
|
+
if (row === null) {
|
|
1799
|
+
return;
|
|
1800
|
+
}
|
|
1801
|
+
checkText(rowScopeArg, row.name, 'name');
|
|
1802
|
+
checkSealed(rowScopeArg, row.secret, 'secret');
|
|
1803
|
+
checkPortSet(rowScopeArg, row.listenPorts, 'listenPorts');
|
|
1804
|
+
checkPortSet(rowScopeArg, row.listenPortsUdp, 'listenPortsUdp');
|
|
1805
|
+
checkBoolean(rowScopeArg, row.enabled, 'enabled');
|
|
1806
|
+
checkBoolean(rowScopeArg, row.autoDerivePorts, 'autoDerivePorts');
|
|
1807
|
+
checkPerformance(rowScopeArg, row.performance, 'performance');
|
|
1808
|
+
checkEgress(rowScopeArg, row.egress);
|
|
1809
|
+
checkTextSet(rowScopeArg, row.tags, 'tags');
|
|
1810
|
+
checkNullableText(rowScopeArg, row.publicIp, 'publicIp', 64);
|
|
1811
|
+
checkNullableText(rowScopeArg, row.publicIpv6, 'publicIpv6', 64);
|
|
1812
|
+
checkNullableText(rowScopeArg, row.mailHostname, 'mailHostname', 253);
|
|
1813
|
+
});
|
|
1814
|
+
};
|
|
1815
|
+
|
|
1816
|
+
// ---------------------------------------------------------------------------------------------
|
|
1817
|
+
// Entry points
|
|
1818
|
+
// ---------------------------------------------------------------------------------------------
|
|
1819
|
+
|
|
1820
|
+
const validateArea = (
|
|
1821
|
+
sinkArg: IGatewayAreaContentRefusal[],
|
|
1822
|
+
areaArg: TGatewayConfigArea,
|
|
1823
|
+
contentArg: unknown,
|
|
1824
|
+
dnsDomainsArg: TDnsDomainReference,
|
|
1825
|
+
): void => {
|
|
1826
|
+
const scope: IScope = { sink: sinkArg, area: areaArg, member: null, rowId: null, prefix: '' };
|
|
1827
|
+
try {
|
|
1828
|
+
canonicalizeStrictJson(contentArg, failEncoding);
|
|
1829
|
+
} catch {
|
|
1830
|
+
refuse(scope, null, 'not-strict-json');
|
|
1831
|
+
return;
|
|
1832
|
+
}
|
|
1833
|
+
const content = exact(scope, contentArg, gatewayAreaMembers[areaArg], null);
|
|
1834
|
+
if (content === null) {
|
|
1835
|
+
return;
|
|
1836
|
+
}
|
|
1837
|
+
switch (areaArg) {
|
|
1838
|
+
case 'security':
|
|
1839
|
+
validateSecurity(scope, content);
|
|
1840
|
+
break;
|
|
1841
|
+
case 'dns':
|
|
1842
|
+
validateDns(scope, content);
|
|
1843
|
+
break;
|
|
1844
|
+
case 'routes':
|
|
1845
|
+
validateRoutes(scope, content);
|
|
1846
|
+
break;
|
|
1847
|
+
case 'mail':
|
|
1848
|
+
validateMail(scope, content, dnsDomainsArg);
|
|
1849
|
+
break;
|
|
1850
|
+
case 'edges':
|
|
1851
|
+
validateEdges(scope, content);
|
|
1852
|
+
break;
|
|
1853
|
+
}
|
|
1854
|
+
};
|
|
1855
|
+
|
|
1856
|
+
/**
|
|
1857
|
+
* Validates one area's content on its own and names every reason it is refused. Cross-area hard
|
|
1858
|
+
* references (`mail.domains[].linkedDomainId`) are not judged here: `validateGatewayAreaTables`
|
|
1859
|
+
* judges them per whole document. An area outside `gatewayConfigAreaApplyOrder` is refused
|
|
1860
|
+
* `invalid-value` with `area: null`.
|
|
1861
|
+
*/
|
|
1862
|
+
export const validateGatewayAreaContent = (
|
|
1863
|
+
areaArg: TGatewayConfigArea,
|
|
1864
|
+
contentArg: unknown,
|
|
1865
|
+
): IGatewayAreaContentRefusal[] => {
|
|
1866
|
+
if (!isGatewayConfigArea(areaArg)) {
|
|
1867
|
+
return [{ area: null, member: null, rowId: null, path: null, code: 'invalid-value' }];
|
|
1868
|
+
}
|
|
1869
|
+
const sink: IGatewayAreaContentRefusal[] = [];
|
|
1870
|
+
validateArea(sink, areaArg, contentArg, 'unjudged');
|
|
1871
|
+
return sink;
|
|
1872
|
+
};
|
|
1873
|
+
|
|
1874
|
+
/**
|
|
1875
|
+
* Validates the contents of one whole document (a desired state's `areas`, or the five exports a
|
|
1876
|
+
* takeover carries) and names every reason they are refused, area by area in
|
|
1877
|
+
* `gatewayConfigAreaApplyOrder`. Cross-area hard references are judged against the document's own
|
|
1878
|
+
* tables: a mail table with domains needs the document's dns table (`referenced-area-missing`). A
|
|
1879
|
+
* table whose area is outside `gatewayConfigAreaApplyOrder` is refused `invalid-value` with
|
|
1880
|
+
* `area: null` and its position in `tablesArg` as the path (`[n]`), never skipped.
|
|
1881
|
+
*
|
|
1882
|
+
* What it enforces inside engine configuration is the closed key vocabulary
|
|
1883
|
+
* (`gatewayAreaRefusedEngineKeys`) at any depth; completeness against the engine types is the
|
|
1884
|
+
* gateway's own classification (see `gatewayareas.ts`).
|
|
1885
|
+
*
|
|
1886
|
+
* Not judged here, because no single document shows it: whether a sealed value's version names the
|
|
1887
|
+
* value the gateway stored under it (the gateway refuses the same version with a different value as
|
|
1888
|
+
* `invalid-table`), whether a domain changed `source` or `providerId` under one id
|
|
1889
|
+
* (`validateGatewayAreaContentChange`), and every engine semantic (the gateway's own check).
|
|
1890
|
+
*/
|
|
1891
|
+
export const validateGatewayAreaTables = (
|
|
1892
|
+
tablesArg: readonly Pick<IGatewayAreaTable, 'area' | 'content'>[],
|
|
1893
|
+
): IGatewayAreaContentRefusal[] => {
|
|
1894
|
+
const sink: IGatewayAreaContentRefusal[] = [];
|
|
1895
|
+
const byArea = new Map<TGatewayConfigArea, unknown>();
|
|
1896
|
+
tablesArg.forEach((table, indexArg) => {
|
|
1897
|
+
if (!isGatewayConfigArea(table.area)) {
|
|
1898
|
+
// Outside the vocabulary, so the refusal names the table by its position in the document.
|
|
1899
|
+
sink.push({ area: null, member: null, rowId: null, path: `[${indexArg}]`, code: 'invalid-value' });
|
|
1900
|
+
return;
|
|
1901
|
+
}
|
|
1902
|
+
if (byArea.has(table.area)) {
|
|
1903
|
+
sink.push({ area: table.area, member: null, rowId: null, path: null, code: 'area-repeated' });
|
|
1904
|
+
return;
|
|
1905
|
+
}
|
|
1906
|
+
byArea.set(table.area, table.content);
|
|
1907
|
+
});
|
|
1908
|
+
const dnsDomains: TDnsDomainReference = byArea.has('dns')
|
|
1909
|
+
? readRowIds(readDataProperty(byArea.get('dns'), 'domains')?.value)
|
|
1910
|
+
: 'missing';
|
|
1911
|
+
for (const area of gatewayConfigAreaApplyOrder) {
|
|
1912
|
+
if (byArea.has(area)) {
|
|
1913
|
+
validateArea(sink, area, byArea.get(area), dnsDomains);
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
return sink;
|
|
1917
|
+
};
|
|
1918
|
+
|
|
1919
|
+
/**
|
|
1920
|
+
* Judges a change of one area's content against the content it replaces, both already valid: a
|
|
1921
|
+
* domain keeps its `source` and `providerId` under one id. Every other area has no such rule yet.
|
|
1922
|
+
*/
|
|
1923
|
+
export const validateGatewayAreaContentChange = <TArea extends TGatewayConfigArea>(
|
|
1924
|
+
areaArg: TArea,
|
|
1925
|
+
previousArg: TGatewayAreaContent<TArea>,
|
|
1926
|
+
nextArg: TGatewayAreaContent<TArea>,
|
|
1927
|
+
): IGatewayAreaContentRefusal[] => {
|
|
1928
|
+
if (areaArg !== 'dns') {
|
|
1929
|
+
return [];
|
|
1930
|
+
}
|
|
1931
|
+
const previous = new Map((previousArg as TGatewayAreaContent<'dns'>).domains.map((domainArg) => [domainArg.id, domainArg]));
|
|
1932
|
+
const refusals: IGatewayAreaContentRefusal[] = [];
|
|
1933
|
+
for (const domain of (nextArg as TGatewayAreaContent<'dns'>).domains) {
|
|
1934
|
+
const before = previous.get(domain.id);
|
|
1935
|
+
for (const key of ['source', 'providerId'] as const) {
|
|
1936
|
+
if (before !== undefined && before[key] !== domain[key]) {
|
|
1937
|
+
refusals.push({ area: 'dns', member: 'domains', rowId: domain.id, path: key, code: 'immutable-member-changed' });
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
return refusals;
|
|
1942
|
+
};
|
|
1943
|
+
|
|
1944
|
+
// ---------------------------------------------------------------------------------------------
|
|
1945
|
+
// Secret-bearing rows
|
|
1946
|
+
// ---------------------------------------------------------------------------------------------
|
|
1947
|
+
|
|
1948
|
+
/** One secret-class value of a table, by where it is and its version, never its value. */
|
|
1949
|
+
export interface IGatewayAreaSecretReference {
|
|
1950
|
+
area: TGatewayConfigArea;
|
|
1951
|
+
member: string;
|
|
1952
|
+
/** `null` for a singleton. */
|
|
1953
|
+
rowId: string | null;
|
|
1954
|
+
/** The key path inside the row or singleton. */
|
|
1955
|
+
path: string;
|
|
1956
|
+
secretClass: 'sealed' | 'verifier';
|
|
1957
|
+
/** The sealed version; `null` for a verifier. */
|
|
1958
|
+
version: string | null;
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
/**
|
|
1962
|
+
* Every secret-class value of a valid area content: what a controller seals, and what its
|
|
1963
|
+
* revisions and diffs name by version instead of by value.
|
|
1964
|
+
*/
|
|
1965
|
+
export const listGatewayAreaSecrets = <TArea extends TGatewayConfigArea>(
|
|
1966
|
+
areaArg: TArea,
|
|
1967
|
+
contentArg: TGatewayAreaContent<TArea>,
|
|
1968
|
+
): IGatewayAreaSecretReference[] => {
|
|
1969
|
+
const references: IGatewayAreaSecretReference[] = [];
|
|
1970
|
+
const sealed = (memberArg: string, rowIdArg: string | null, pathArg: string,
|
|
1971
|
+
valueArg: { version: string } | null): void => {
|
|
1972
|
+
if (valueArg !== null) {
|
|
1973
|
+
references.push({ area: areaArg, member: memberArg, rowId: rowIdArg, path: pathArg, secretClass: 'sealed',
|
|
1974
|
+
version: valueArg.version });
|
|
1975
|
+
}
|
|
1976
|
+
};
|
|
1977
|
+
const verifier = (memberArg: string, rowIdArg: string, pathArg: string): void => {
|
|
1978
|
+
references.push({ area: areaArg, member: memberArg, rowId: rowIdArg, path: pathArg, secretClass: 'verifier',
|
|
1979
|
+
version: null });
|
|
1980
|
+
};
|
|
1981
|
+
switch (areaArg) {
|
|
1982
|
+
case 'security': {
|
|
1983
|
+
const content = contentArg as TGatewayAreaContent<'security'>;
|
|
1984
|
+
content.apiTokens.forEach((rowArg) => verifier('apiTokens', rowArg.id, 'credential'));
|
|
1985
|
+
break;
|
|
1986
|
+
}
|
|
1987
|
+
case 'dns': {
|
|
1988
|
+
const content = contentArg as TGatewayAreaContent<'dns'>;
|
|
1989
|
+
content.providers.forEach((rowArg) => sealed('providers', rowArg.id, 'credentials.apiToken',
|
|
1990
|
+
rowArg.credentials.apiToken));
|
|
1991
|
+
break;
|
|
1992
|
+
}
|
|
1993
|
+
case 'routes': {
|
|
1994
|
+
const content = contentArg as TGatewayAreaContent<'routes'>;
|
|
1995
|
+
for (const row of content.routes) {
|
|
1996
|
+
for (const key of ['tlsKey', 'basicAuthUsers', 'jwtSecret', 'requestHeaders'] as const) {
|
|
1997
|
+
sealed('routes', row.id, `secrets.${key}`, row.secrets[key]);
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
for (const row of content.sourceProfiles) {
|
|
2001
|
+
for (const key of ['basicAuthUsers', 'jwtSecret'] as const) {
|
|
2002
|
+
sealed('sourceProfiles', row.id, `secrets.${key}`, row.secrets[key]);
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
break;
|
|
2006
|
+
}
|
|
2007
|
+
case 'mail': {
|
|
2008
|
+
const content = contentArg as TGatewayAreaContent<'mail'>;
|
|
2009
|
+
sealed('server', null, 'tlsKey', content.server.tlsKey);
|
|
2010
|
+
content.smtpAccounts.forEach((rowArg) => verifier('smtpAccounts', rowArg.id, 'credential'));
|
|
2011
|
+
content.identities.forEach((rowArg) => verifier('identities', rowArg.id, 'credential'));
|
|
2012
|
+
content.coreMailPeers.forEach((rowArg) => {
|
|
2013
|
+
if (rowArg.credentials.length > 0) {
|
|
2014
|
+
verifier('coreMailPeers', rowArg.id, 'credentials');
|
|
2015
|
+
}
|
|
2016
|
+
});
|
|
2017
|
+
break;
|
|
2018
|
+
}
|
|
2019
|
+
case 'edges': {
|
|
2020
|
+
const content = contentArg as TGatewayAreaContent<'edges'>;
|
|
2021
|
+
content.edges.forEach((rowArg) => sealed('edges', rowArg.id, 'secret', rowArg.secret));
|
|
2022
|
+
break;
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
return references;
|
|
2026
|
+
};
|