@ship.zone/runner 0.2.3 → 1.0.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,23 @@
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
13
  } from './interfaces.ts';
14
- import * as plugins from './plugins.ts';
14
+ import { acceptSpecVersion, runnerSpecVersion } from './spec-version.ts';
15
+ import { isRecord } from './validation.ts';
16
+ import { validateCompiledJobSchema, validateWireMessage } from './wire-schema.ts';
15
17
 
16
- const identifierPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
17
18
  const sha256Pattern = /^[a-f0-9]{64}$/;
18
19
  const reservedEnvironmentNames = ['FOSS_CI_INPUTS_JSON', 'FOSS_CI_MATRIX_JSON'] as const;
20
+ const npmUserConfigEnvironmentName = 'NPM_CONFIG_USERCONFIG';
19
21
  const maximumCommandArgumentBytes = 16 * 1024;
20
22
  const maximumCommandBytes = 128 * 1024;
21
23
  const maximumCombinedEnvironmentEntries = 128;
@@ -38,65 +40,6 @@ const transferLimitNames = [
38
40
  'maximumWorkspaceEntries',
39
41
  ] as const satisfies readonly (keyof ITransferLimits)[];
40
42
 
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
43
  const assertWellFormedUnicode = (value: string): void => {
101
44
  for (let index = 0; index < value.length; index += 1) {
102
45
  const codeUnit = value.charCodeAt(index);
@@ -184,166 +127,96 @@ const sha256 = async (value: string): Promise<string> => {
184
127
  export const computeCompiledPlanDigest = async (job: unknown): Promise<string> =>
185
128
  await sha256(canonicalizeJson(projectCompiledPlan(job)));
186
129
 
187
- const validateIdentifier = (value: unknown, field: string): string => {
188
- if (typeof value !== 'string' || !identifierPattern.test(value)) {
189
- throw new ProtocolError(`Invalid ${field}`);
130
+ /** A leased job this runner does not execute; it is refused as `runner_error` before acceptance. */
131
+ export class UnsupportedJobError extends ProtocolError {
132
+ constructor(message: string) {
133
+ super(message);
134
+ this.name = 'UnsupportedJobError';
190
135
  }
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}))$/;
136
+ }
196
137
 
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}`);
138
+ const deepFreeze = <T>(value: T): T => {
139
+ if (typeof value === 'object' && value !== null) {
140
+ for (const entry of Object.values(value)) deepFreeze(entry);
141
+ Object.freeze(value);
215
142
  }
216
143
  return value;
217
144
  };
218
145
 
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
-
146
+ /**
147
+ * Validates capabilities against the published `RunnerCapabilities` schema and returns an
148
+ * immutable copy, the snapshot every lease is checked against.
149
+ */
263
150
  export const createRunnerCapabilitySnapshot = (
264
151
  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',
152
+ ): IRunnerCapabilities =>
153
+ deepFreeze(
154
+ validateWireMessage<IRunnerCapabilities>('RunnerCapabilities', structuredClone(capabilities)),
273
155
  );
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
- };
156
+
157
+ const hasSteps = (
158
+ job: TCompiledRunnerJob,
159
+ ): job is Extract<TCompiledRunnerJob, { steps: ICompiledStep[] }> => 'steps' in job;
160
+
161
+ const isLinuxPlatform = (platform: string): boolean => platform.startsWith('linux/');
312
162
 
313
163
  const requireCapabilityFit = (
314
- job: ICompiledRunnerJob,
164
+ job: TCompiledRunnerJob,
315
165
  capabilities: IRunnerCapabilities,
316
166
  ): void => {
317
- if (!capabilities.executionProfiles.includes(job.requirements.executionProfile)) {
167
+ const requirements = job.requirements;
168
+ if (!capabilities.executionProfiles.includes(requirements.executionProfile)) {
318
169
  throw new ProtocolError('Job execution profile is not supported by this runner');
319
170
  }
320
- if (job.execution.profile !== job.requirements.executionProfile) {
321
- throw new ProtocolError('Job execution profile does not match its requirement');
171
+ if (!capabilities.isolation.includes(requirements.isolation)) {
172
+ throw new ProtocolError('Job isolation is not supported by this runner');
322
173
  }
323
- for (const label of job.requirements.labels) {
174
+ if (requirements.platform !== undefined) {
175
+ if (!capabilities.platforms.includes(requirements.platform)) {
176
+ throw new ProtocolError('Job platform is not executed natively by this runner');
177
+ }
178
+ } else if (!capabilities.platforms.some(isLinuxPlatform)) {
179
+ throw new ProtocolError('Job requires a linux platform this runner does not execute');
180
+ }
181
+ for (const label of requirements.labels) {
324
182
  if (!capabilities.labels.includes(label)) {
325
183
  throw new ProtocolError('Job requires an unavailable runner label');
326
184
  }
327
185
  }
328
- for (const feature of job.requirements.features) {
186
+ for (const feature of requirements.features) {
329
187
  if (!capabilities.features.includes(feature)) {
330
188
  throw new ProtocolError('Job requires an unavailable runner feature');
331
189
  }
332
190
  }
333
- if (!capabilities.networks.includes(job.execution.network)) {
191
+ if (!capabilities.networks.includes(job.network.mode)) {
334
192
  throw new ProtocolError('Job network mode is not supported by this runner');
335
193
  }
336
194
  if (!capabilities.sourceFormats.includes(job.source.format)) {
337
195
  throw new ProtocolError('Job source format is not supported by this runner');
338
196
  }
339
197
  for (const name of transferLimitNames) {
340
- if (job.requirements.limits[name] > capabilities.limits[name]) {
198
+ if (requirements.limits[name] > capabilities.limits[name]) {
341
199
  throw new ProtocolError(`Job requirement ${name} exceeds runner capability`);
342
200
  }
343
201
  }
202
+ const resources = job.resources;
203
+ const maxima = capabilities.resources;
204
+ if (resources && maxima) {
205
+ const pairs = [
206
+ [resources.memoryBytes, maxima.maximumMemoryBytes, 'memoryBytes'],
207
+ [resources.cpus, maxima.maximumCpus, 'cpus'],
208
+ [resources.pids, maxima.maximumPids, 'pids'],
209
+ [resources.sharedMemoryBytes, maxima.maximumSharedMemoryBytes, 'sharedMemoryBytes'],
210
+ ] as const;
211
+ for (const [value, maximum, name] of pairs) {
212
+ if (value !== undefined && value > maximum) {
213
+ throw new ProtocolError(`Job resource ${name} exceeds runner capability`);
214
+ }
215
+ }
216
+ }
344
217
  };
345
218
 
346
- const requireTransferCoherence = (job: ICompiledRunnerJob): void => {
219
+ const requireTransferCoherence = (job: TCompiledRunnerJob): void => {
347
220
  const limits = job.requirements.limits;
348
221
  if (!job.requirements.features.includes('source.tar-gz')) {
349
222
  throw new ProtocolError('Job does not require its source transfer feature');
@@ -388,7 +261,7 @@ const requireTransferCoherence = (job: ICompiledRunnerJob): void => {
388
261
  if (cache.access === 'read-write' && job.permissions.caches !== 'read-write') {
389
262
  throw new ProtocolError('Read-write cache declaration lacks read-write permission');
390
263
  }
391
- for (const path of cache.paths) {
264
+ for (const path of 'paths' in cache ? cache.paths : []) {
392
265
  if (
393
266
  cachePaths.some((existing) =>
394
267
  existing === path || existing.startsWith(`${path}/`) || path.startsWith(`${existing}/`)
@@ -402,15 +275,13 @@ const requireTransferCoherence = (job: ICompiledRunnerJob): void => {
402
275
  if (job.artifacts.length > 0) {
403
276
  if (
404
277
  job.permissions.artifacts !== 'write' ||
405
- !job.requirements.features.includes('artifacts.v1')
278
+ !job.requirements.features.includes('artifacts')
406
279
  ) {
407
280
  throw new ProtocolError('Job artifact declarations are not authorized');
408
281
  }
409
282
  }
410
283
  if (job.caches.length > 0) {
411
- if (
412
- job.permissions.caches === 'none' || !job.requirements.features.includes('caches.v1')
413
- ) {
284
+ if (job.permissions.caches === 'none' || !job.requirements.features.includes('caches')) {
414
285
  throw new ProtocolError('Job cache declarations are not authorized');
415
286
  }
416
287
  }
@@ -428,11 +299,31 @@ const requireCanonicalReservedJson = (value: string, name: string): void => {
428
299
  }
429
300
  };
430
301
 
431
- const requireExecutionCoherence = (job: ICompiledRunnerJob): void => {
432
- for (const secretName of Object.keys(job.secrets)) {
302
+ const requireExecutionCoherence = (job: TCompiledRunnerJob): void => {
303
+ const secretTargets = Object.keys(job.secrets);
304
+ const npmRead = job.npmRead !== undefined;
305
+ for (const secretName of secretTargets) {
433
306
  if (secretName.startsWith('FOSS_CI_')) {
434
307
  throw new ProtocolError('Secret targets may not use reserved FOSS_CI names');
435
308
  }
309
+ if (npmRead && secretName === npmUserConfigEnvironmentName) {
310
+ throw new ProtocolError(`Secret targets may not use the reserved ${secretName}`);
311
+ }
312
+ }
313
+ if (job.resources?.sharedMemoryBytes !== undefined && job.resources.memoryBytes !== undefined) {
314
+ if (job.resources.sharedMemoryBytes > job.resources.memoryBytes) {
315
+ throw new ProtocolError('Job shared memory exceeds its memory ceiling');
316
+ }
317
+ }
318
+ if (!hasSteps(job)) {
319
+ const referenced = new Set(job.build.secrets.map((secret) => secret.environment));
320
+ if (
321
+ [...referenced].some((target) => !Object.hasOwn(job.secrets, target)) ||
322
+ secretTargets.some((target) => !referenced.has(target))
323
+ ) {
324
+ throw new ProtocolError('Build secrets and job secret targets must correspond exactly');
325
+ }
326
+ return;
436
327
  }
437
328
  for (const step of job.steps) {
438
329
  const environmentNames = Object.keys(step.environment);
@@ -444,6 +335,9 @@ const requireExecutionCoherence = (job: ICompiledRunnerJob): void => {
444
335
  ) {
445
336
  throw new ProtocolError('Step environment uses an unknown reserved FOSS_CI name');
446
337
  }
338
+ if (npmRead && name === npmUserConfigEnvironmentName) {
339
+ throw new ProtocolError(`Step environment may not define the reserved ${name}`);
340
+ }
447
341
  if (Object.hasOwn(job.secrets, name)) {
448
342
  throw new ProtocolError('Step environment and secret targets must be unique');
449
343
  }
@@ -455,7 +349,8 @@ const requireExecutionCoherence = (job: ICompiledRunnerJob): void => {
455
349
  requireCanonicalReservedJson(step.environment[name], name);
456
350
  }
457
351
  if (
458
- environmentNames.length + Object.keys(job.secrets).length > maximumCombinedEnvironmentEntries
352
+ environmentNames.length + secretTargets.length + (npmRead ? 1 : 0) >
353
+ maximumCombinedEnvironmentEntries
459
354
  ) {
460
355
  throw new ProtocolError('Step environment and secret targets exceed the protocol limit');
461
356
  }
@@ -472,8 +367,118 @@ const requireExecutionCoherence = (job: ICompiledRunnerJob): void => {
472
367
  }
473
368
  };
474
369
 
370
+ const candidateReferences = (job: TCompiledRunnerJob): string[] => {
371
+ const images: TImageReference[] = hasSteps(job)
372
+ ? [job.execution.image]
373
+ : job.build.baseImages.map((baseImage) => baseImage.image);
374
+ return images.flatMap((image) => typeof image === 'string' ? [] : [image.candidate]);
375
+ };
376
+
377
+ const imageName = (pinnedImage: string): string => pinnedImage.slice(0, pinnedImage.indexOf('@'));
378
+
379
+ /**
380
+ * Checks the lease rules that tie `grants`, `bindings`, and `npmGrants` to the leased job: every
381
+ * candidate reference has exactly one binding and no binding is unreferenced; grants are unique per
382
+ * registry, repository, and access; every bound image has a pull grant for its repository, compared
383
+ * as the exact `registry/repository` name of the binding; an `oci-image` lease holds exactly one
384
+ * push grant and any other lease none; and npm grants correspond one to one to `npmRead` entries.
385
+ */
386
+ const requireLeaseCoherence = (lease: IJobLease): void => {
387
+ const references = candidateReferences(lease.job);
388
+ const referenced = new Set(references);
389
+ const bound = new Set<string>();
390
+ for (const binding of lease.bindings) {
391
+ if (!referenced.has(binding.candidate) || bound.has(binding.candidate)) {
392
+ throw new ProtocolError('Lease bindings do not match the job candidate references');
393
+ }
394
+ bound.add(binding.candidate);
395
+ }
396
+ if (bound.size !== referenced.size) {
397
+ throw new ProtocolError('Lease bindings do not match the job candidate references');
398
+ }
399
+ const grantKeys = new Set<string>();
400
+ for (const grant of lease.grants) {
401
+ const key = JSON.stringify([grant.registry, grant.repository, grant.access]);
402
+ if (grantKeys.has(key)) {
403
+ throw new ProtocolError('Lease holds more than one grant for a registry repository access');
404
+ }
405
+ grantKeys.add(key);
406
+ }
407
+ for (const binding of lease.bindings) {
408
+ const name = imageName(binding.image);
409
+ if (
410
+ !lease.grants.some((grant) =>
411
+ grant.access === 'pull' && `${grant.registry}/${grant.repository}` === name
412
+ )
413
+ ) {
414
+ throw new ProtocolError('Lease binds an image without a pull grant for its repository');
415
+ }
416
+ }
417
+ const pushGrants = lease.grants.filter((grant) => grant.access === 'push').length;
418
+ const expectedPushGrants = lease.job.requirements.executionProfile === 'oci-image' ? 1 : 0;
419
+ if (pushGrants !== expectedPushGrants) {
420
+ throw new ProtocolError('Lease push grants do not match the job execution profile');
421
+ }
422
+ const npmRead = lease.job.npmRead ?? [];
423
+ const npmGrants = lease.npmGrants ?? [];
424
+ const scopeKey = (scopes: readonly string[]): string => JSON.stringify([...scopes].sort());
425
+ const remaining = [...npmGrants];
426
+ for (const entry of npmRead) {
427
+ const index = remaining.findIndex((grant) =>
428
+ grant.registry === entry.registry && scopeKey(grant.scopes) === scopeKey(entry.scopes)
429
+ );
430
+ if (index < 0) throw new ProtocolError('Lease npm grants do not match the job npmRead');
431
+ remaining.splice(index, 1);
432
+ }
433
+ if (remaining.length > 0) {
434
+ throw new ProtocolError('Lease npm grants do not match the job npmRead');
435
+ }
436
+ };
437
+
438
+ /**
439
+ * Narrows a coherent lease to the one shape this runner executes and refuses every other shape:
440
+ * the `vm` and `oci-image` profiles, `microvm` isolation, egress networking, candidate images and
441
+ * image grants, and npm read grants.
442
+ */
443
+ export const requireExecutableLease = (lease: IJobLease): IOciJobLease => {
444
+ const job = lease.job;
445
+ if (job.requirements.executionProfile !== 'oci' || !hasSteps(job)) {
446
+ throw new UnsupportedJobError(
447
+ `Execution profile ${job.requirements.executionProfile} is not supported by this runner`,
448
+ );
449
+ }
450
+ if (job.execution.profile !== 'oci') {
451
+ throw new UnsupportedJobError('Job execution does not match the oci profile');
452
+ }
453
+ if (job.requirements.isolation !== 'container') {
454
+ throw new UnsupportedJobError('microvm isolation is not supported by this runner');
455
+ }
456
+ if (job.network.mode !== 'none') {
457
+ throw new UnsupportedJobError('egress networking is not enforced by this runner');
458
+ }
459
+ if (typeof job.execution.image !== 'string' || lease.bindings.length > 0) {
460
+ throw new UnsupportedJobError('Candidate image bindings are not supported by this runner');
461
+ }
462
+ if (lease.grants.length > 0) {
463
+ throw new UnsupportedJobError('Image grants are not supported by this runner');
464
+ }
465
+ if (job.npmRead !== undefined || lease.npmGrants !== undefined) {
466
+ throw new UnsupportedJobError('npm read grants are not delivered by this runner');
467
+ }
468
+ return {
469
+ jobId: lease.jobId,
470
+ attemptId: lease.attemptId,
471
+ leaseId: lease.leaseId,
472
+ fencingToken: lease.fencingToken,
473
+ leaseExpiresAt: lease.leaseExpiresAt,
474
+ job: job as IOciRunnerJob,
475
+ grants: [],
476
+ bindings: [],
477
+ };
478
+ };
479
+
475
480
  export const validateCapabilityFit = (
476
- job: ICompiledRunnerJob,
481
+ job: TCompiledRunnerJob,
477
482
  capabilities: IRunnerCapabilities,
478
483
  ): void => {
479
484
  const snapshot = createRunnerCapabilitySnapshot(capabilities);
@@ -483,18 +488,25 @@ export const validateCapabilityFit = (
483
488
  export class RunnerProtocolValidator {
484
489
  private readonly capabilities: IRunnerCapabilities;
485
490
 
486
- constructor(capabilities: IRunnerCapabilities) {
491
+ constructor(
492
+ capabilities: IRunnerCapabilities,
493
+ private readonly implementedSpec: string = runnerSpecVersion,
494
+ ) {
487
495
  this.capabilities = createRunnerCapabilitySnapshot(capabilities);
488
496
  }
489
497
 
490
- public async validateJob(jobUnknown: unknown): Promise<ICompiledRunnerJob> {
491
- if (!validateRunnerJobSchema(jobUnknown)) {
492
- const details = safeAjvErrors();
498
+ /**
499
+ * Validates a compiled job: the published schema, the specification version acceptance rule,
500
+ * the compiled plan digest, internal coherence, and fit against the capability snapshot.
501
+ */
502
+ public async validateJob(jobUnknown: unknown): Promise<TCompiledRunnerJob> {
503
+ const job = validateCompiledJobSchema<TCompiledRunnerJob>(jobUnknown);
504
+ const acceptance = acceptSpecVersion(this.implementedSpec, job.spec);
505
+ if (acceptance !== 'accepted') {
493
506
  throw new ProtocolError(
494
- `Compiled runner job failed schema validation${details ? `: ${details}` : ''}`,
507
+ `Job specification version is not accepted by this runner (${acceptance})`,
495
508
  );
496
509
  }
497
- const job = jobUnknown as ICompiledRunnerJob;
498
510
  const digest = await computeCompiledPlanDigest(job);
499
511
  if (!sha256Pattern.test(job.compiledPlanDigest) || digest !== job.compiledPlanDigest) {
500
512
  throw new ProtocolError('Compiled runner job digest does not match');
@@ -505,26 +517,19 @@ export class RunnerProtocolValidator {
505
517
  return job;
506
518
  }
507
519
 
520
+ /** Validates a lease against the published `JobLease` schema, its job, and lease coherence. */
508
521
  public async validateJobLease(leaseUnknown: unknown): Promise<IJobLease> {
509
522
  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
- };
523
+ const { job: jobUnknown, ...envelope } = leaseUnknown;
524
+ const job = await this.validateJob(jobUnknown);
525
+ const lease = validateWireMessage<IJobLease>('JobLease', { ...envelope, job });
526
+ requireLeaseCoherence(lease);
527
+ return lease;
528
+ }
529
+
530
+ /** Validates a lease and narrows it to the `oci` shape this runner executes. */
531
+ public async validateExecutableLease(leaseUnknown: unknown): Promise<IOciJobLease> {
532
+ return requireExecutableLease(await this.validateJobLease(leaseUnknown));
528
533
  }
529
534
  }
530
535