@ship.zone/runner 0.2.4 → 1.1.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.
@@ -1,21 +1,24 @@
1
1
  import { ProtocolError } from './errors.ts';
2
2
  import type {
3
- ICompiledRunnerJob,
3
+ ICompiledStep,
4
4
  IJobLease,
5
+ IOciJobLease,
6
+ IOciRunnerJob,
5
7
  IRunnerCapabilities,
6
8
  ITransferLimits,
7
- TExecutionProfile,
8
- TJobNetwork,
9
+ TCompiledRunnerJob,
10
+ TImageReference,
9
11
  TJsonObject,
10
12
  TJsonValue,
11
- TRunnerFeature,
12
- TSourceFormat,
13
+ TLeaseFeature,
13
14
  } from './interfaces.ts';
14
- import * as plugins from './plugins.ts';
15
+ import { acceptSpecVersion, runnerSpecVersion } from './spec-version.ts';
16
+ import { isRecord } from './validation.ts';
17
+ import { validateCompiledJobSchema, validateWireMessage } from './wire-schema.ts';
15
18
 
16
- const identifierPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
17
19
  const sha256Pattern = /^[a-f0-9]{64}$/;
18
20
  const reservedEnvironmentNames = ['FOSS_CI_INPUTS_JSON', 'FOSS_CI_MATRIX_JSON'] as const;
21
+ const npmUserConfigEnvironmentName = 'NPM_CONFIG_USERCONFIG';
19
22
  const maximumCommandArgumentBytes = 16 * 1024;
20
23
  const maximumCommandBytes = 128 * 1024;
21
24
  const maximumCombinedEnvironmentEntries = 128;
@@ -38,65 +41,6 @@ const transferLimitNames = [
38
41
  'maximumWorkspaceEntries',
39
42
  ] as const satisfies readonly (keyof ITransferLimits)[];
40
43
 
41
- const transferLimitBounds: Record<keyof ITransferLimits, readonly [number, number]> = {
42
- maximumSourceArchiveBytes: [0, 8_589_934_592],
43
- maximumSourceExtractedBytes: [0, 68_719_476_736],
44
- maximumSourceEntries: [0, 1_000_000],
45
- maximumArtifactArchiveBytes: [0, 17_179_869_184],
46
- maximumArtifactExtractedBytes: [0, 137_438_953_472],
47
- maximumArtifactEntries: [0, 1_000_000],
48
- maximumArtifacts: [0, 64],
49
- maximumCacheArchiveBytes: [0, 17_179_869_184],
50
- maximumCacheExtractedBytes: [0, 137_438_953_472],
51
- maximumCacheEntries: [0, 1_000_000],
52
- maximumCaches: [0, 32],
53
- maximumLogChunkBytes: [1, 65_536],
54
- maximumTotalLogBytes: [0, 1_073_741_824],
55
- maximumWorkspaceBytes: [16_777_216, 1_099_511_627_776],
56
- maximumWorkspaceEntries: [1, 2_000_000],
57
- };
58
-
59
- const isRecord = (value: unknown): value is Record<string, unknown> =>
60
- typeof value === 'object' && value !== null && !Array.isArray(value);
61
-
62
- const assertExactKeys = (
63
- value: Record<string, unknown>,
64
- required: readonly string[],
65
- optional: readonly string[] = [],
66
- field = 'value',
67
- ): void => {
68
- const allowed = new Set([...required, ...optional]);
69
- if (
70
- required.some((key) => !Object.hasOwn(value, key)) ||
71
- Object.keys(value).some((key) => !allowed.has(key))
72
- ) {
73
- throw new ProtocolError(`Invalid ${field} shape`);
74
- }
75
- };
76
-
77
- const sanitizeErrorText = (value: string): string =>
78
- [...value].map((character) => {
79
- const codePoint = character.codePointAt(0) ?? 0;
80
- return codePoint < 0x20 || codePoint === 0x7f ? '?' : character;
81
- }).join('');
82
-
83
- const safeAjvErrors = (): string => {
84
- const validationErrors: unknown = validateRunnerJobSchema.errors;
85
- const errors = Array.isArray(validationErrors) ? validationErrors.slice(0, 8) : [];
86
- const details = errors.map((errorUnknown: unknown) => {
87
- const error = isRecord(errorUnknown) ? errorUnknown : {};
88
- const instancePath = typeof error.instancePath === 'string' ? error.instancePath : '/';
89
- const errorMessage = typeof error.message === 'string' ? error.message : 'is invalid';
90
- const path = sanitizeErrorText(instancePath).slice(0, 160);
91
- const message = sanitizeErrorText(errorMessage).slice(0, 160);
92
- return `${path} ${message}`;
93
- }).join('; ');
94
- return details.slice(0, 1024);
95
- };
96
-
97
- const ajv = new plugins.Ajv2020({ allErrors: true, strict: true });
98
- const validateRunnerJobSchema = ajv.compile<ICompiledRunnerJob>(plugins.runnerJobSchema);
99
-
100
44
  const assertWellFormedUnicode = (value: string): void => {
101
45
  for (let index = 0; index < value.length; index += 1) {
102
46
  const codeUnit = value.charCodeAt(index);
@@ -184,166 +128,123 @@ const sha256 = async (value: string): Promise<string> => {
184
128
  export const computeCompiledPlanDigest = async (job: unknown): Promise<string> =>
185
129
  await sha256(canonicalizeJson(projectCompiledPlan(job)));
186
130
 
187
- const validateIdentifier = (value: unknown, field: string): string => {
188
- if (typeof value !== 'string' || !identifierPattern.test(value)) {
189
- throw new ProtocolError(`Invalid ${field}`);
131
+ /** A leased job this runner does not execute; it is refused as `runner_error` before acceptance. */
132
+ export class UnsupportedJobError extends ProtocolError {
133
+ constructor(message: string) {
134
+ super(message);
135
+ this.name = 'UnsupportedJobError';
190
136
  }
191
- return value;
192
- };
193
-
194
- const timestampPattern =
195
- /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/;
137
+ }
196
138
 
197
- const validateTimestamp = (value: unknown, field: string): string => {
198
- if (typeof value !== 'string') throw new ProtocolError(`Invalid ${field}`);
199
- const match = timestampPattern.exec(value);
200
- if (!match) throw new ProtocolError(`Invalid ${field}`);
201
- const year = Number(match[1]);
202
- const month = Number(match[2]);
203
- const day = Number(match[3]);
204
- const hour = Number(match[4]);
205
- const minute = Number(match[5]);
206
- const second = Number(match[6]);
207
- const offsetHour = match[7] === undefined ? 0 : Number(match[7]);
208
- const offsetMinute = match[8] === undefined ? 0 : Number(match[8]);
209
- const lastDay = new Date(Date.UTC(year, month, 0)).getUTCDate();
210
- if (
211
- month < 1 || month > 12 || day < 1 || day > lastDay || hour > 23 || minute > 59 ||
212
- second > 59 || offsetHour > 23 || offsetMinute > 59 || !Number.isFinite(Date.parse(value))
213
- ) {
214
- throw new ProtocolError(`Invalid ${field}`);
139
+ const deepFreeze = <T>(value: T): T => {
140
+ if (typeof value === 'object' && value !== null) {
141
+ for (const entry of Object.values(value)) deepFreeze(entry);
142
+ Object.freeze(value);
215
143
  }
216
144
  return value;
217
145
  };
218
146
 
219
- const validateTransferLimits = (value: unknown, field: string): ITransferLimits => {
220
- if (!isRecord(value)) throw new ProtocolError(`Invalid ${field}`);
221
- assertExactKeys(value, transferLimitNames, [], field);
222
- const limits = {} as ITransferLimits;
223
- for (const name of transferLimitNames) {
224
- const entry = value[name];
225
- const [minimum, maximum] = transferLimitBounds[name];
226
- if (
227
- typeof entry !== 'number' || !Number.isSafeInteger(entry) || entry < minimum ||
228
- entry > maximum
229
- ) {
230
- throw new ProtocolError(`Invalid ${field}.${name}`);
231
- }
232
- limits[name] = entry;
233
- }
234
- return limits;
235
- };
236
-
237
- const validateCapabilityArray = (
238
- value: unknown,
239
- field: string,
240
- minimum: number,
241
- maximum: number,
242
- allowed?: ReadonlySet<string>,
243
- identifiers = false,
244
- ): string[] => {
245
- if (
246
- !Array.isArray(value) || value.length < minimum || value.length > maximum ||
247
- value.some((entry) => typeof entry !== 'string')
248
- ) {
249
- throw new ProtocolError(`Invalid runner capabilities ${field}`);
250
- }
251
- const entries = value as string[];
252
- if (
253
- new Set(entries).size !== entries.length ||
254
- entries.some((entry) =>
255
- allowed ? !allowed.has(entry) : identifiers && !identifierPattern.test(entry)
256
- )
257
- ) {
258
- throw new ProtocolError(`Invalid runner capabilities ${field}`);
259
- }
260
- return [...entries];
261
- };
262
-
147
+ /**
148
+ * Validates capabilities against the published `RunnerCapabilities` schema and returns an
149
+ * immutable copy, the snapshot every lease is checked against.
150
+ */
263
151
  export const createRunnerCapabilitySnapshot = (
264
152
  capabilities: IRunnerCapabilities,
265
- ): IRunnerCapabilities => {
266
- const value: unknown = capabilities;
267
- if (!isRecord(value)) throw new ProtocolError('Invalid runner capabilities');
268
- assertExactKeys(
269
- value,
270
- ['executionProfiles', 'labels', 'features', 'networks', 'sourceFormats', 'limits'],
271
- [],
272
- 'runner capabilities',
153
+ ): IRunnerCapabilities =>
154
+ deepFreeze(
155
+ validateWireMessage<IRunnerCapabilities>('RunnerCapabilities', structuredClone(capabilities)),
273
156
  );
274
- const executionProfiles = validateCapabilityArray(
275
- value.executionProfiles,
276
- 'executionProfiles',
277
- 1,
278
- 16,
279
- new Set(['oci.v1']),
280
- ) as TExecutionProfile[];
281
- const labels = validateCapabilityArray(value.labels, 'labels', 0, 32, undefined, true);
282
- const features = validateCapabilityArray(
283
- value.features,
284
- 'features',
285
- 0,
286
- 16,
287
- new Set(['source.tar-gz', 'artifacts.v1', 'caches.v1']),
288
- ) as TRunnerFeature[];
289
- const networks = validateCapabilityArray(
290
- value.networks,
291
- 'networks',
292
- 1,
293
- 2,
294
- new Set(['none', 'bridge']),
295
- ) as TJobNetwork[];
296
- const sourceFormats = validateCapabilityArray(
297
- value.sourceFormats,
298
- 'sourceFormats',
299
- 1,
300
- 1,
301
- new Set(['tar.gz']),
302
- ) as TSourceFormat[];
303
- const limits = validateTransferLimits(value.limits, 'runner capabilities limits');
304
- Object.freeze(executionProfiles);
305
- Object.freeze(labels);
306
- Object.freeze(features);
307
- Object.freeze(networks);
308
- Object.freeze(sourceFormats);
309
- Object.freeze(limits);
310
- return Object.freeze({ executionProfiles, labels, features, networks, sourceFormats, limits });
311
- };
157
+
158
+ const hasSteps = (
159
+ job: TCompiledRunnerJob,
160
+ ): job is Extract<TCompiledRunnerJob, { steps: ICompiledStep[] }> => 'steps' in job;
161
+
162
+ const isLinuxPlatform = (platform: string): boolean => platform.startsWith('linux/');
312
163
 
313
164
  const requireCapabilityFit = (
314
- job: ICompiledRunnerJob,
165
+ job: TCompiledRunnerJob,
315
166
  capabilities: IRunnerCapabilities,
316
167
  ): void => {
317
- if (!capabilities.executionProfiles.includes(job.requirements.executionProfile)) {
168
+ const requirements = job.requirements;
169
+ if (!capabilities.executionProfiles.includes(requirements.executionProfile)) {
318
170
  throw new ProtocolError('Job execution profile is not supported by this runner');
319
171
  }
320
- if (job.execution.profile !== job.requirements.executionProfile) {
321
- throw new ProtocolError('Job execution profile does not match its requirement');
172
+ if (!capabilities.isolation.includes(requirements.isolation)) {
173
+ throw new ProtocolError('Job isolation is not supported by this runner');
174
+ }
175
+ if (requirements.platform !== undefined) {
176
+ if (!capabilities.platforms.includes(requirements.platform)) {
177
+ throw new ProtocolError('Job platform is not executed natively by this runner');
178
+ }
179
+ } else if (!capabilities.platforms.some(isLinuxPlatform)) {
180
+ throw new ProtocolError('Job requires a linux platform this runner does not execute');
322
181
  }
323
- for (const label of job.requirements.labels) {
182
+ for (const label of requirements.labels) {
324
183
  if (!capabilities.labels.includes(label)) {
325
184
  throw new ProtocolError('Job requires an unavailable runner label');
326
185
  }
327
186
  }
328
- for (const feature of job.requirements.features) {
187
+ for (const feature of requirements.features) {
329
188
  if (!capabilities.features.includes(feature)) {
330
189
  throw new ProtocolError('Job requires an unavailable runner feature');
331
190
  }
332
191
  }
333
- if (!capabilities.networks.includes(job.execution.network)) {
192
+ if (!capabilities.networks.includes(job.network.mode)) {
334
193
  throw new ProtocolError('Job network mode is not supported by this runner');
335
194
  }
336
195
  if (!capabilities.sourceFormats.includes(job.source.format)) {
337
196
  throw new ProtocolError('Job source format is not supported by this runner');
338
197
  }
339
198
  for (const name of transferLimitNames) {
340
- if (job.requirements.limits[name] > capabilities.limits[name]) {
199
+ if (requirements.limits[name] > capabilities.limits[name]) {
341
200
  throw new ProtocolError(`Job requirement ${name} exceeds runner capability`);
342
201
  }
343
202
  }
203
+ const resources = job.resources;
204
+ const maxima = capabilities.resources;
205
+ if (resources && maxima) {
206
+ const pairs = [
207
+ [resources.memoryBytes, maxima.maximumMemoryBytes, 'memoryBytes'],
208
+ [resources.cpus, maxima.maximumCpus, 'cpus'],
209
+ [resources.pids, maxima.maximumPids, 'pids'],
210
+ [resources.sharedMemoryBytes, maxima.maximumSharedMemoryBytes, 'sharedMemoryBytes'],
211
+ ] as const;
212
+ for (const [value, maximum, name] of pairs) {
213
+ if (value !== undefined && value > maximum) {
214
+ throw new ProtocolError(`Job resource ${name} exceeds runner capability`);
215
+ }
216
+ }
217
+ }
218
+ if (
219
+ capabilities.maximumTimeoutMs !== undefined && job.timeoutMs > capabilities.maximumTimeoutMs
220
+ ) {
221
+ throw new ProtocolError('Job timeoutMs exceeds runner capability');
222
+ }
344
223
  };
345
224
 
346
- const requireTransferCoherence = (job: ICompiledRunnerJob): void => {
225
+ /**
226
+ * Checks that a lease uses only the lease features of the capability snapshot: a pull grant
227
+ * requires `image-pull-grants`, a binding `candidate-bindings`, and `npmGrants`
228
+ * `npm-read-grants`. A snapshot without `leaseFeatures` imposes no such condition.
229
+ */
230
+ const requireLeaseFeatureFit = (lease: IJobLease, capabilities: IRunnerCapabilities): void => {
231
+ const advertised = capabilities.leaseFeatures;
232
+ if (advertised === undefined) return;
233
+ const used: Array<[boolean, TLeaseFeature]> = [
234
+ [lease.grants.some((grant) => grant.access === 'pull'), 'image-pull-grants'],
235
+ [lease.bindings.length > 0, 'candidate-bindings'],
236
+ [lease.npmGrants !== undefined, 'npm-read-grants'],
237
+ ];
238
+ for (const [uses, feature] of used) {
239
+ if (uses && !advertised.includes(feature)) {
240
+ throw new ProtocolError(
241
+ `Lease uses ${feature}, a lease feature this runner does not advertise`,
242
+ );
243
+ }
244
+ }
245
+ };
246
+
247
+ const requireTransferCoherence = (job: TCompiledRunnerJob): void => {
347
248
  const limits = job.requirements.limits;
348
249
  if (!job.requirements.features.includes('source.tar-gz')) {
349
250
  throw new ProtocolError('Job does not require its source transfer feature');
@@ -388,7 +289,7 @@ const requireTransferCoherence = (job: ICompiledRunnerJob): void => {
388
289
  if (cache.access === 'read-write' && job.permissions.caches !== 'read-write') {
389
290
  throw new ProtocolError('Read-write cache declaration lacks read-write permission');
390
291
  }
391
- for (const path of cache.paths) {
292
+ for (const path of 'paths' in cache ? cache.paths : []) {
392
293
  if (
393
294
  cachePaths.some((existing) =>
394
295
  existing === path || existing.startsWith(`${path}/`) || path.startsWith(`${existing}/`)
@@ -402,15 +303,13 @@ const requireTransferCoherence = (job: ICompiledRunnerJob): void => {
402
303
  if (job.artifacts.length > 0) {
403
304
  if (
404
305
  job.permissions.artifacts !== 'write' ||
405
- !job.requirements.features.includes('artifacts.v1')
306
+ !job.requirements.features.includes('artifacts')
406
307
  ) {
407
308
  throw new ProtocolError('Job artifact declarations are not authorized');
408
309
  }
409
310
  }
410
311
  if (job.caches.length > 0) {
411
- if (
412
- job.permissions.caches === 'none' || !job.requirements.features.includes('caches.v1')
413
- ) {
312
+ if (job.permissions.caches === 'none' || !job.requirements.features.includes('caches')) {
414
313
  throw new ProtocolError('Job cache declarations are not authorized');
415
314
  }
416
315
  }
@@ -428,11 +327,31 @@ const requireCanonicalReservedJson = (value: string, name: string): void => {
428
327
  }
429
328
  };
430
329
 
431
- const requireExecutionCoherence = (job: ICompiledRunnerJob): void => {
432
- for (const secretName of Object.keys(job.secrets)) {
330
+ const requireExecutionCoherence = (job: TCompiledRunnerJob): void => {
331
+ const secretTargets = Object.keys(job.secrets);
332
+ const npmRead = job.npmRead !== undefined;
333
+ for (const secretName of secretTargets) {
433
334
  if (secretName.startsWith('FOSS_CI_')) {
434
335
  throw new ProtocolError('Secret targets may not use reserved FOSS_CI names');
435
336
  }
337
+ if (npmRead && secretName === npmUserConfigEnvironmentName) {
338
+ throw new ProtocolError(`Secret targets may not use the reserved ${secretName}`);
339
+ }
340
+ }
341
+ if (job.resources?.sharedMemoryBytes !== undefined && job.resources.memoryBytes !== undefined) {
342
+ if (job.resources.sharedMemoryBytes > job.resources.memoryBytes) {
343
+ throw new ProtocolError('Job shared memory exceeds its memory ceiling');
344
+ }
345
+ }
346
+ if (!hasSteps(job)) {
347
+ const referenced = new Set(job.build.secrets.map((secret) => secret.environment));
348
+ if (
349
+ [...referenced].some((target) => !Object.hasOwn(job.secrets, target)) ||
350
+ secretTargets.some((target) => !referenced.has(target))
351
+ ) {
352
+ throw new ProtocolError('Build secrets and job secret targets must correspond exactly');
353
+ }
354
+ return;
436
355
  }
437
356
  for (const step of job.steps) {
438
357
  const environmentNames = Object.keys(step.environment);
@@ -444,6 +363,9 @@ const requireExecutionCoherence = (job: ICompiledRunnerJob): void => {
444
363
  ) {
445
364
  throw new ProtocolError('Step environment uses an unknown reserved FOSS_CI name');
446
365
  }
366
+ if (npmRead && name === npmUserConfigEnvironmentName) {
367
+ throw new ProtocolError(`Step environment may not define the reserved ${name}`);
368
+ }
447
369
  if (Object.hasOwn(job.secrets, name)) {
448
370
  throw new ProtocolError('Step environment and secret targets must be unique');
449
371
  }
@@ -455,7 +377,8 @@ const requireExecutionCoherence = (job: ICompiledRunnerJob): void => {
455
377
  requireCanonicalReservedJson(step.environment[name], name);
456
378
  }
457
379
  if (
458
- environmentNames.length + Object.keys(job.secrets).length > maximumCombinedEnvironmentEntries
380
+ environmentNames.length + secretTargets.length + (npmRead ? 1 : 0) >
381
+ maximumCombinedEnvironmentEntries
459
382
  ) {
460
383
  throw new ProtocolError('Step environment and secret targets exceed the protocol limit');
461
384
  }
@@ -472,8 +395,118 @@ const requireExecutionCoherence = (job: ICompiledRunnerJob): void => {
472
395
  }
473
396
  };
474
397
 
398
+ const candidateReferences = (job: TCompiledRunnerJob): string[] => {
399
+ const images: TImageReference[] = hasSteps(job)
400
+ ? [job.execution.image]
401
+ : job.build.baseImages.map((baseImage) => baseImage.image);
402
+ return images.flatMap((image) => typeof image === 'string' ? [] : [image.candidate]);
403
+ };
404
+
405
+ const imageName = (pinnedImage: string): string => pinnedImage.slice(0, pinnedImage.indexOf('@'));
406
+
407
+ /**
408
+ * Checks the lease rules that tie `grants`, `bindings`, and `npmGrants` to the leased job: every
409
+ * candidate reference has exactly one binding and no binding is unreferenced; grants are unique per
410
+ * registry, repository, and access; every bound image has a pull grant for its repository, compared
411
+ * as the exact `registry/repository` name of the binding; an `oci-image` lease holds exactly one
412
+ * push grant and any other lease none; and npm grants correspond one to one to `npmRead` entries.
413
+ */
414
+ const requireLeaseCoherence = (lease: IJobLease): void => {
415
+ const references = candidateReferences(lease.job);
416
+ const referenced = new Set(references);
417
+ const bound = new Set<string>();
418
+ for (const binding of lease.bindings) {
419
+ if (!referenced.has(binding.candidate) || bound.has(binding.candidate)) {
420
+ throw new ProtocolError('Lease bindings do not match the job candidate references');
421
+ }
422
+ bound.add(binding.candidate);
423
+ }
424
+ if (bound.size !== referenced.size) {
425
+ throw new ProtocolError('Lease bindings do not match the job candidate references');
426
+ }
427
+ const grantKeys = new Set<string>();
428
+ for (const grant of lease.grants) {
429
+ const key = JSON.stringify([grant.registry, grant.repository, grant.access]);
430
+ if (grantKeys.has(key)) {
431
+ throw new ProtocolError('Lease holds more than one grant for a registry repository access');
432
+ }
433
+ grantKeys.add(key);
434
+ }
435
+ for (const binding of lease.bindings) {
436
+ const name = imageName(binding.image);
437
+ if (
438
+ !lease.grants.some((grant) =>
439
+ grant.access === 'pull' && `${grant.registry}/${grant.repository}` === name
440
+ )
441
+ ) {
442
+ throw new ProtocolError('Lease binds an image without a pull grant for its repository');
443
+ }
444
+ }
445
+ const pushGrants = lease.grants.filter((grant) => grant.access === 'push').length;
446
+ const expectedPushGrants = lease.job.requirements.executionProfile === 'oci-image' ? 1 : 0;
447
+ if (pushGrants !== expectedPushGrants) {
448
+ throw new ProtocolError('Lease push grants do not match the job execution profile');
449
+ }
450
+ const npmRead = lease.job.npmRead ?? [];
451
+ const npmGrants = lease.npmGrants ?? [];
452
+ const scopeKey = (scopes: readonly string[]): string => JSON.stringify([...scopes].sort());
453
+ const remaining = [...npmGrants];
454
+ for (const entry of npmRead) {
455
+ const index = remaining.findIndex((grant) =>
456
+ grant.registry === entry.registry && scopeKey(grant.scopes) === scopeKey(entry.scopes)
457
+ );
458
+ if (index < 0) throw new ProtocolError('Lease npm grants do not match the job npmRead');
459
+ remaining.splice(index, 1);
460
+ }
461
+ if (remaining.length > 0) {
462
+ throw new ProtocolError('Lease npm grants do not match the job npmRead');
463
+ }
464
+ };
465
+
466
+ /**
467
+ * Narrows a coherent lease to the one shape this runner executes and refuses every other shape:
468
+ * the `vm` and `oci-image` profiles, `microvm` isolation, egress networking, candidate images and
469
+ * image grants, and npm read grants.
470
+ */
471
+ export const requireExecutableLease = (lease: IJobLease): IOciJobLease => {
472
+ const job = lease.job;
473
+ if (job.requirements.executionProfile !== 'oci' || !hasSteps(job)) {
474
+ throw new UnsupportedJobError(
475
+ `Execution profile ${job.requirements.executionProfile} is not supported by this runner`,
476
+ );
477
+ }
478
+ if (job.execution.profile !== 'oci') {
479
+ throw new UnsupportedJobError('Job execution does not match the oci profile');
480
+ }
481
+ if (job.requirements.isolation !== 'container') {
482
+ throw new UnsupportedJobError('microvm isolation is not supported by this runner');
483
+ }
484
+ if (job.network.mode !== 'none') {
485
+ throw new UnsupportedJobError('egress networking is not enforced by this runner');
486
+ }
487
+ if (typeof job.execution.image !== 'string' || lease.bindings.length > 0) {
488
+ throw new UnsupportedJobError('Candidate image bindings are not supported by this runner');
489
+ }
490
+ if (lease.grants.length > 0) {
491
+ throw new UnsupportedJobError('Image grants are not supported by this runner');
492
+ }
493
+ if (job.npmRead !== undefined || lease.npmGrants !== undefined) {
494
+ throw new UnsupportedJobError('npm read grants are not delivered by this runner');
495
+ }
496
+ return {
497
+ jobId: lease.jobId,
498
+ attemptId: lease.attemptId,
499
+ leaseId: lease.leaseId,
500
+ fencingToken: lease.fencingToken,
501
+ leaseExpiresAt: lease.leaseExpiresAt,
502
+ job: job as IOciRunnerJob,
503
+ grants: [],
504
+ bindings: [],
505
+ };
506
+ };
507
+
475
508
  export const validateCapabilityFit = (
476
- job: ICompiledRunnerJob,
509
+ job: TCompiledRunnerJob,
477
510
  capabilities: IRunnerCapabilities,
478
511
  ): void => {
479
512
  const snapshot = createRunnerCapabilitySnapshot(capabilities);
@@ -483,18 +516,25 @@ export const validateCapabilityFit = (
483
516
  export class RunnerProtocolValidator {
484
517
  private readonly capabilities: IRunnerCapabilities;
485
518
 
486
- constructor(capabilities: IRunnerCapabilities) {
519
+ constructor(
520
+ capabilities: IRunnerCapabilities,
521
+ private readonly implementedSpec: string = runnerSpecVersion,
522
+ ) {
487
523
  this.capabilities = createRunnerCapabilitySnapshot(capabilities);
488
524
  }
489
525
 
490
- public async validateJob(jobUnknown: unknown): Promise<ICompiledRunnerJob> {
491
- if (!validateRunnerJobSchema(jobUnknown)) {
492
- const details = safeAjvErrors();
526
+ /**
527
+ * Validates a compiled job: the published schema, the specification version acceptance rule,
528
+ * the compiled plan digest, internal coherence, and fit against the capability snapshot.
529
+ */
530
+ public async validateJob(jobUnknown: unknown): Promise<TCompiledRunnerJob> {
531
+ const job = validateCompiledJobSchema<TCompiledRunnerJob>(jobUnknown);
532
+ const acceptance = acceptSpecVersion(this.implementedSpec, job.spec);
533
+ if (acceptance !== 'accepted') {
493
534
  throw new ProtocolError(
494
- `Compiled runner job failed schema validation${details ? `: ${details}` : ''}`,
535
+ `Job specification version is not accepted by this runner (${acceptance})`,
495
536
  );
496
537
  }
497
- const job = jobUnknown as ICompiledRunnerJob;
498
538
  const digest = await computeCompiledPlanDigest(job);
499
539
  if (!sha256Pattern.test(job.compiledPlanDigest) || digest !== job.compiledPlanDigest) {
500
540
  throw new ProtocolError('Compiled runner job digest does not match');
@@ -505,26 +545,23 @@ export class RunnerProtocolValidator {
505
545
  return job;
506
546
  }
507
547
 
548
+ /**
549
+ * Validates a lease against the published `JobLease` schema, its job, lease coherence, and the
550
+ * lease features of the capability snapshot.
551
+ */
508
552
  public async validateJobLease(leaseUnknown: unknown): Promise<IJobLease> {
509
553
  if (!isRecord(leaseUnknown)) throw new ProtocolError('Invalid job lease');
510
- assertExactKeys(
511
- leaseUnknown,
512
- ['jobId', 'attemptId', 'leaseId', 'fencingToken', 'leaseExpiresAt', 'job'],
513
- [],
514
- 'job lease',
515
- );
516
- const fencingToken = leaseUnknown.fencingToken;
517
- if (typeof fencingToken !== 'string' || fencingToken.length < 16 || fencingToken.length > 512) {
518
- throw new ProtocolError('Invalid job lease fencing token');
519
- }
520
- return {
521
- jobId: validateIdentifier(leaseUnknown.jobId, 'job lease jobId'),
522
- attemptId: validateIdentifier(leaseUnknown.attemptId, 'job lease attemptId'),
523
- leaseId: validateIdentifier(leaseUnknown.leaseId, 'job lease leaseId'),
524
- fencingToken,
525
- leaseExpiresAt: validateTimestamp(leaseUnknown.leaseExpiresAt, 'job lease leaseExpiresAt'),
526
- job: await this.validateJob(leaseUnknown.job),
527
- };
554
+ const { job: jobUnknown, ...envelope } = leaseUnknown;
555
+ const job = await this.validateJob(jobUnknown);
556
+ const lease = validateWireMessage<IJobLease>('JobLease', { ...envelope, job });
557
+ requireLeaseCoherence(lease);
558
+ requireLeaseFeatureFit(lease, this.capabilities);
559
+ return lease;
560
+ }
561
+
562
+ /** Validates a lease and narrows it to the `oci` shape this runner executes. */
563
+ public async validateExecutableLease(leaseUnknown: unknown): Promise<IOciJobLease> {
564
+ return requireExecutableLease(await this.validateJobLease(leaseUnknown));
528
565
  }
529
566
  }
530
567