@ship.zone/runner 0.1.1 → 0.2.1

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,5 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { dirname, join, resolve } from '@std/path';
3
+ import { maximumArchivePathMetadataBytes } from './plugins.ts';
3
4
  import { ProtocolError, ResourceCleanupError, RunnerError } from './errors.ts';
4
5
  import type {
5
6
  ITransferDownload,
@@ -13,6 +14,7 @@ const tarBlockSize = 512;
13
14
  const maximumPaxHeaderBytes = 16 * 1024;
14
15
  const maximumPathBytes = 4096;
15
16
  const maximumPathSegmentBytes = 255;
17
+ const maximumRetainedSymlinkPathComponents = 1_000_000;
16
18
  const streamBufferBytes = 64 * 1024;
17
19
  const zeroBlock = new Uint8Array(tarBlockSize);
18
20
  const textEncoder = new TextEncoder();
@@ -38,12 +40,20 @@ export interface IExtractTarGzipOptions {
38
40
  expectedMetadata: ITransferMetadata;
39
41
  maximumExtractedBytes: number;
40
42
  maximumEntries: number;
43
+ maximumMaterializedEntries?: number;
44
+ maximumPathMetadataBytes?: number;
45
+ reserveBytes?: number;
46
+ reserveInodes?: number;
41
47
  signal?: AbortSignal;
42
48
  allowSymlinks?: boolean;
43
49
  allowedPaths?: string[];
44
50
  requireAllowedPaths?: boolean;
45
51
  }
46
52
 
53
+ export interface IExtractedArchiveMetadata extends IWorkspaceTreeMetadata {
54
+ materializedEntryCount: number;
55
+ }
56
+
47
57
  export interface ICreateTarGzipOptions {
48
58
  sourcePath: string;
49
59
  selections: string[];
@@ -53,6 +63,7 @@ export interface ICreateTarGzipOptions {
53
63
  maximumArchiveBytes: number;
54
64
  maximumExtractedBytes: number;
55
65
  maximumEntries: number;
66
+ maximumPathMetadataBytes?: number;
56
67
  allowSymlinks: boolean;
57
68
  requireAllSelections?: boolean;
58
69
  signal?: AbortSignal;
@@ -63,6 +74,7 @@ export interface ITransferArchiveFileOperations {
63
74
  makeTempFile(options: Deno.MakeTempOptions): Promise<string>;
64
75
  chmod(path: string, mode: number): Promise<void>;
65
76
  remove(path: string, options?: Deno.RemoveOptions): Promise<void>;
77
+ openRead?(path: string): Promise<Pick<Deno.FsFile, 'read' | 'stat' | 'close'>>;
66
78
  }
67
79
 
68
80
  export interface IPreparedTransferArchive {
@@ -81,7 +93,7 @@ interface IArchiveEntry {
81
93
  sizeBytes: number;
82
94
  executable: boolean;
83
95
  linkTarget?: string;
84
- symlinkScope: string[];
96
+ symlinkScope?: string[];
85
97
  snapshot: IFileSnapshot;
86
98
  }
87
99
 
@@ -126,6 +138,7 @@ const defaultFileOperations: ITransferArchiveFileOperations = {
126
138
  makeTempFile: (options) => Deno.makeTempFile(options),
127
139
  chmod: (path, mode) => Deno.chmod(path, mode),
128
140
  remove: (path, options) => Deno.remove(path, options),
141
+ openRead: (path) => Deno.open(path, { read: true }),
129
142
  };
130
143
 
131
144
  export const removePathIfPresent = async (
@@ -461,9 +474,7 @@ export const validateRelativeSelections = (
461
474
  return [...paths];
462
475
  };
463
476
 
464
- const compareUtf8 = (left: string, right: string): number => {
465
- const leftBytes = textEncoder.encode(left);
466
- const rightBytes = textEncoder.encode(right);
477
+ const compareUtf8Bytes = (leftBytes: Uint8Array, rightBytes: Uint8Array): number => {
467
478
  const length = Math.min(leftBytes.byteLength, rightBytes.byteLength);
468
479
  for (let index = 0; index < length; index++) {
469
480
  if (leftBytes[index] !== rightBytes[index]) return leftBytes[index] - rightBytes[index];
@@ -471,6 +482,53 @@ const compareUtf8 = (left: string, right: string): number => {
471
482
  return leftBytes.byteLength - rightBytes.byteLength;
472
483
  };
473
484
 
485
+ const compareUtf8 = (left: string, right: string): number =>
486
+ compareUtf8Bytes(textEncoder.encode(left), textEncoder.encode(right));
487
+
488
+ const yieldToEventLoop = (): Promise<void> =>
489
+ new Promise<void>((resolvePromise) => setTimeout(resolvePromise, 0));
490
+
491
+ const orderByUtf8Bytes = async <T>(
492
+ values: T[],
493
+ bytesFor: (value: T) => Uint8Array,
494
+ signal?: AbortSignal,
495
+ ): Promise<T[]> => {
496
+ const ordered: T[] = [];
497
+ const pending: Array<{ values: T[]; offset: number }> = [{ values, offset: 0 }];
498
+ let operationsUntilYield = 262_144;
499
+ while (pending.length > 0) {
500
+ if (signal?.aborted) throw signal.reason;
501
+ const group = pending.pop()!;
502
+ if (group.values.length === 1) {
503
+ ordered.push(group.values[0]);
504
+ continue;
505
+ }
506
+ const buckets = new Map<number, T[]>();
507
+ for (const value of group.values) {
508
+ const bytes = bytesFor(value);
509
+ const code = group.offset < bytes.byteLength ? bytes[group.offset] + 1 : 0;
510
+ const bucket = buckets.get(code);
511
+ if (bucket) bucket.push(value);
512
+ else buckets.set(code, [value]);
513
+ operationsUntilYield--;
514
+ if (operationsUntilYield === 0) {
515
+ await yieldToEventLoop();
516
+ if (signal?.aborted) throw signal.reason;
517
+ operationsUntilYield = 262_144;
518
+ }
519
+ }
520
+ const ended = buckets.get(0);
521
+ if (ended) ordered.push(...ended);
522
+ const codes = [...buckets.keys()].filter((code) => code > 0).sort((left, right) =>
523
+ left - right
524
+ );
525
+ for (let index = codes.length - 1; index >= 0; index--) {
526
+ pending.push({ values: buckets.get(codes[index])!, offset: group.offset + 1 });
527
+ }
528
+ }
529
+ return ordered;
530
+ };
531
+
474
532
  const decodeTarText = (bytes: Uint8Array, field: string): string => {
475
533
  const nul = bytes.indexOf(0);
476
534
  const valueBytes = nul === -1 ? bytes : bytes.subarray(0, nul);
@@ -681,7 +739,7 @@ const normalizeArchivePath = (value: string, type: string): string => {
681
739
  return pathSegments(normalized, maximumPathBytes, 'Tar archive').join('/');
682
740
  };
683
741
 
684
- const parseLinkTarget = (target: string): string[] => {
742
+ const validateLinkTarget = (target: string): void => {
685
743
  if (
686
744
  !target ||
687
745
  target.startsWith('/') ||
@@ -691,81 +749,326 @@ const parseLinkTarget = (target: string): string[] => {
691
749
  ) {
692
750
  throw new ProtocolError('Tar symlink target is unsafe');
693
751
  }
694
- const segments = target.split('/');
695
- if (
696
- segments.some((segment) =>
697
- !segment || textEncoder.encode(segment).byteLength > maximumPathSegmentBytes
698
- )
699
- ) {
700
- throw new ProtocolError('Tar symlink target is unsafe');
752
+ let offset = 0;
753
+ while (offset <= target.length) {
754
+ const separator = target.indexOf('/', offset);
755
+ const segment = target.slice(offset, separator === -1 ? target.length : separator);
756
+ if (!segment || textEncoder.encode(segment).byteLength > maximumPathSegmentBytes) {
757
+ throw new ProtocolError('Tar symlink target is unsafe');
758
+ }
759
+ if (separator === -1) break;
760
+ offset = separator + 1;
701
761
  }
702
- return segments;
703
762
  };
704
763
 
705
- const isComponentPrefix = (prefix: string[], value: string[]): boolean =>
706
- prefix.length <= value.length && prefix.every((component, index) => component === value[index]);
707
-
708
- const validateSymlinkSet = (symlinks: ISymlinkDescription[]): void => {
709
- const byPath = new Map(symlinks.map((entry) => [entry.path, entry]));
710
- const resolveTarget = (
711
- base: string[],
712
- target: string,
713
- scope: string[],
714
- active: Set<string>,
715
- ): string[] => {
716
- let current = [...base];
717
- for (const segment of parseLinkTarget(target)) {
718
- if (segment === '.') continue;
719
- if (segment === '..') {
720
- if (current.length <= scope.length) {
721
- throw new ProtocolError('Tar symlink target escapes its collection root');
722
- }
723
- current.pop();
724
- } else {
725
- current.push(segment);
726
- const linkedPath = current.join('/');
727
- const linked = byPath.get(linkedPath);
728
- if (linked) {
729
- if (active.has(linkedPath)) throw new ProtocolError('Tar symlink chain is cyclic');
730
- const nextActive = new Set(active);
731
- nextActive.add(linkedPath);
732
- current = resolveTarget(
733
- linkedPath.split('/').slice(0, -1),
734
- linked.target,
735
- scope,
736
- nextActive,
737
- );
738
- }
739
- }
740
- if (!isComponentPrefix(scope, current)) {
741
- throw new ProtocolError('Tar symlink target escapes its collection root');
742
- }
764
+ const validateSymlinkSet = async (
765
+ symlinks: ISymlinkDescription[],
766
+ signal?: AbortSignal,
767
+ ): Promise<void> => {
768
+ if (symlinks.length === 0) return;
769
+ let operationsUntilYield = 262_144;
770
+ const accountOperations = async (operations: number): Promise<void> => {
771
+ operationsUntilYield -= operations;
772
+ if (operationsUntilYield > 0) return;
773
+ await yieldToEventLoop();
774
+ if (signal?.aborted) throw signal.reason;
775
+ operationsUntilYield = 262_144;
776
+ };
777
+ type TResolution = { status: 'visiting' } | { status: 'resolved'; path: number };
778
+ interface IResolutionFrame {
779
+ path: number;
780
+ scope: number;
781
+ current: number;
782
+ target: string;
783
+ offset: number;
784
+ waitingFor?: number;
785
+ }
786
+ const edgeFactor = maximumRetainedSymlinkPathComponents + 1;
787
+ const segmentIds = new Map<string, number>();
788
+ const edges = new Map<number, number>();
789
+ const parents = [0];
790
+ const depths = [0];
791
+ const segmentId = (segment: string): number => {
792
+ const existing = segmentIds.get(segment);
793
+ if (existing !== undefined) return existing;
794
+ const identifier = segmentIds.size + 1;
795
+ if (identifier > maximumRetainedSymlinkPathComponents) {
796
+ throw new ProtocolError('Tar archive exceeds the retained symlink path component limit');
743
797
  }
798
+ segmentIds.set(segment, identifier);
799
+ return identifier;
800
+ };
801
+ const pathNodeForChild = (parent: number, segment: string): number => {
802
+ const key = parent * edgeFactor + segmentId(segment);
803
+ const existing = edges.get(key);
804
+ if (existing !== undefined) return existing;
805
+ const node = parents.length;
806
+ if (node > maximumRetainedSymlinkPathComponents) {
807
+ throw new ProtocolError('Tar archive exceeds the retained symlink path component limit');
808
+ }
809
+ parents.push(parent);
810
+ depths.push(depths[parent] + 1);
811
+ edges.set(key, node);
812
+ return node;
813
+ };
814
+ const pathNode = (segments: string[]): number => {
815
+ let current = 0;
816
+ for (const segment of segments) current = pathNodeForChild(current, segment);
744
817
  return current;
745
818
  };
819
+ const withinScope = (path: number, scope: number): boolean => {
820
+ let current = path;
821
+ while (depths[current] > depths[scope]) current = parents[current];
822
+ return current === scope;
823
+ };
824
+ const symlinkByPath = new Map<number, ISymlinkDescription>();
825
+ const nodeBySymlink = new Map<ISymlinkDescription, number>();
826
+ const symlinksByScope = new Map<number, ISymlinkDescription[]>();
746
827
  for (const symlink of symlinks) {
747
- const active = new Set([symlink.path]);
748
- resolveTarget(symlink.path.split('/').slice(0, -1), symlink.target, symlink.scope, active);
828
+ const pathSegments = symlink.path.split('/');
829
+ const path = pathNode(pathSegments);
830
+ const scope = pathNode(symlink.scope);
831
+ symlinkByPath.set(path, symlink);
832
+ nodeBySymlink.set(symlink, path);
833
+ const scoped = symlinksByScope.get(scope);
834
+ if (scoped) scoped.push(symlink);
835
+ else symlinksByScope.set(scope, [symlink]);
836
+ await accountOperations(pathSegments.length + symlink.scope.length);
837
+ }
838
+ const beginFrame = (entry: ISymlinkDescription, scope: number): IResolutionFrame => {
839
+ const path = nodeBySymlink.get(entry)!;
840
+ const current = parents[path];
841
+ if (!withinScope(current, scope)) {
842
+ throw new ProtocolError('Tar symlink target escapes its collection root');
843
+ }
844
+ return {
845
+ path,
846
+ scope,
847
+ current,
848
+ target: entry.target,
849
+ offset: 0,
850
+ };
851
+ };
852
+ for (const [scope, scopedSymlinks] of symlinksByScope) {
853
+ const resolutions = new Map<number, TResolution>();
854
+ for (const symlink of scopedSymlinks) {
855
+ const path = nodeBySymlink.get(symlink)!;
856
+ if (resolutions.get(path)?.status === 'resolved') continue;
857
+ resolutions.set(path, { status: 'visiting' });
858
+ const frames = [beginFrame(symlink, scope)];
859
+ while (frames.length > 0) {
860
+ const frame = frames[frames.length - 1];
861
+ if (frame.waitingFor) {
862
+ const resolution = resolutions.get(frame.waitingFor);
863
+ if (resolution?.status !== 'resolved') {
864
+ throw new ProtocolError('Tar symlink resolution did not complete');
865
+ }
866
+ frame.current = resolution.path;
867
+ frame.waitingFor = undefined;
868
+ continue;
869
+ }
870
+ if (frame.offset > frame.target.length) {
871
+ resolutions.set(frame.path, { status: 'resolved', path: frame.current });
872
+ frames.pop();
873
+ continue;
874
+ }
875
+ const separator = frame.target.indexOf('/', frame.offset);
876
+ const segment = frame.target.slice(
877
+ frame.offset,
878
+ separator === -1 ? frame.target.length : separator,
879
+ );
880
+ frame.offset = separator === -1 ? frame.target.length + 1 : separator + 1;
881
+ await accountOperations(1);
882
+ if (segment === '.') continue;
883
+ if (segment === '..') {
884
+ if (depths[frame.current] <= depths[frame.scope]) {
885
+ throw new ProtocolError('Tar symlink target escapes its collection root');
886
+ }
887
+ frame.current = parents[frame.current];
888
+ } else {
889
+ frame.current = pathNodeForChild(frame.current, segment);
890
+ const linked = symlinkByPath.get(frame.current);
891
+ if (linked) {
892
+ const linkedPath = nodeBySymlink.get(linked)!;
893
+ const resolution = resolutions.get(linkedPath);
894
+ if (resolution?.status === 'visiting') {
895
+ throw new ProtocolError('Tar symlink chain is cyclic');
896
+ }
897
+ if (resolution?.status === 'resolved') {
898
+ frame.current = resolution.path;
899
+ } else {
900
+ resolutions.set(linkedPath, { status: 'visiting' });
901
+ frame.waitingFor = linkedPath;
902
+ frames.push(beginFrame(linked, frame.scope));
903
+ }
904
+ }
905
+ }
906
+ }
907
+ }
749
908
  }
750
909
  };
751
910
 
752
- const assertArchiveStructure = (
753
- seen: Map<string, TArchiveEntryType>,
911
+ interface IArchiveStructureEntry {
912
+ path: string;
913
+ type: TArchiveEntryType;
914
+ order: number;
915
+ }
916
+
917
+ const recordArchiveStructure = (
918
+ byPath: Map<string, IArchiveStructureEntry>,
919
+ entries: IArchiveStructureEntry[],
754
920
  path: string,
755
921
  type: TArchiveEntryType,
756
922
  ): void => {
757
- if (seen.has(path)) throw new ProtocolError('Tar archive contains a duplicate path');
758
- const segments = path.split('/');
759
- for (let length = 1; length < segments.length; length++) {
760
- const ancestor = seen.get(segments.slice(0, length).join('/'));
761
- if (ancestor && ancestor !== 'directory') {
923
+ if (byPath.has(path)) throw new ProtocolError('Tar archive contains a duplicate path');
924
+ const entry = { path, type, order: entries.length };
925
+ byPath.set(path, entry);
926
+ entries.push(entry);
927
+ };
928
+
929
+ const orderArchiveHierarchy = async (
930
+ entries: IArchiveStructureEntry[],
931
+ signal?: AbortSignal,
932
+ ): Promise<IArchiveStructureEntry[]> => {
933
+ const ordered: IArchiveStructureEntry[] = [];
934
+ const pending: Array<{ entries: IArchiveStructureEntry[]; offset: number }> = [{
935
+ entries,
936
+ offset: 0,
937
+ }];
938
+ let operationsUntilYield = 262_144;
939
+ while (pending.length > 0) {
940
+ if (signal?.aborted) throw signal.reason;
941
+ const group = pending.pop()!;
942
+ if (group.entries.length === 1) {
943
+ ordered.push(group.entries[0]);
944
+ continue;
945
+ }
946
+ const buckets = new Map<number, IArchiveStructureEntry[]>();
947
+ for (const entry of group.entries) {
948
+ let code = 0;
949
+ if (group.offset < entry.path.length) {
950
+ const character = entry.path.charCodeAt(group.offset);
951
+ code = character === 0x2f ? 1 : character + 2;
952
+ }
953
+ const bucket = buckets.get(code);
954
+ if (bucket) bucket.push(entry);
955
+ else buckets.set(code, [entry]);
956
+ operationsUntilYield--;
957
+ if (operationsUntilYield === 0) {
958
+ await yieldToEventLoop();
959
+ if (signal?.aborted) throw signal.reason;
960
+ operationsUntilYield = 262_144;
961
+ }
962
+ }
963
+ const ended = buckets.get(0);
964
+ if (ended) ordered.push(...ended);
965
+ const descendants = buckets.get(1);
966
+ const following: IArchiveStructureEntry[][] = [];
967
+ if (descendants) following.push(descendants);
968
+ for (const [code, bucket] of buckets) {
969
+ if (code > 1) following.push(bucket);
970
+ }
971
+ for (let index = following.length - 1; index >= 0; index--) {
972
+ pending.push({ entries: following[index], offset: group.offset + 1 });
973
+ }
974
+ }
975
+ return ordered;
976
+ };
977
+
978
+ const validateArchiveStructure = async (
979
+ entries: IArchiveStructureEntry[],
980
+ maximumMaterializedEntries: number,
981
+ signal?: AbortSignal,
982
+ ): Promise<number> => {
983
+ const orderedEntries = await orderArchiveHierarchy(entries, signal);
984
+ const ancestors: IArchiveStructureEntry[] = [];
985
+ let previousDirectories: string[] = [];
986
+ let materializedDirectories = 0;
987
+ let nonDirectories = 0;
988
+ let operationsUntilYield = 262_144;
989
+ for (const entry of orderedEntries) {
990
+ while (
991
+ ancestors.length > 0 &&
992
+ !entry.path.startsWith(`${ancestors[ancestors.length - 1].path}/`)
993
+ ) {
994
+ ancestors.pop();
995
+ }
996
+ const ancestor = ancestors.at(-1);
997
+ if (ancestor?.type !== undefined && ancestor.type !== 'directory') {
762
998
  throw new ProtocolError('Tar archive contains entries below a non-directory');
763
999
  }
1000
+ if (ancestor && ancestor.order > entry.order) {
1001
+ throw new ProtocolError('Tar archive declares an ancestor after its descendants');
1002
+ }
1003
+
1004
+ const segments = entry.path.split('/');
1005
+ const directoryDepth = segments.length - (entry.type === 'directory' ? 0 : 1);
1006
+ let commonDirectories = 0;
1007
+ while (
1008
+ commonDirectories < directoryDepth &&
1009
+ commonDirectories < previousDirectories.length &&
1010
+ segments[commonDirectories] === previousDirectories[commonDirectories]
1011
+ ) {
1012
+ commonDirectories++;
1013
+ }
1014
+ materializedDirectories = checkedAdd(
1015
+ materializedDirectories,
1016
+ directoryDepth - commonDirectories,
1017
+ 'Tar materialized directory count overflow',
1018
+ );
1019
+ previousDirectories = segments.slice(0, directoryDepth);
1020
+ if (entry.type !== 'directory') nonDirectories++;
1021
+ const materializedEntries = checkedAdd(
1022
+ materializedDirectories,
1023
+ nonDirectories,
1024
+ 'Tar materialized entry count overflow',
1025
+ );
1026
+ if (materializedEntries > maximumMaterializedEntries) {
1027
+ throw new ProtocolError('Tar archive exceeds the effective workspace entry limit');
1028
+ }
1029
+ ancestors.push(entry);
1030
+ operationsUntilYield -= entry.path.length + segments.length;
1031
+ if (operationsUntilYield <= 0) {
1032
+ await yieldToEventLoop();
1033
+ if (signal?.aborted) throw signal.reason;
1034
+ operationsUntilYield = 262_144;
1035
+ }
764
1036
  }
765
- if ([...seen.keys()].some((candidate) => candidate.startsWith(`${path}/`))) {
766
- throw new ProtocolError('Tar archive declares an ancestor after its descendants');
1037
+ return materializedDirectories + nonDirectories;
1038
+ };
1039
+
1040
+ const addPathMetadataBytes = (
1041
+ current: number,
1042
+ value: string,
1043
+ maximum: number,
1044
+ ): number => {
1045
+ const next = checkedAdd(
1046
+ current,
1047
+ textEncoder.encode(value).byteLength,
1048
+ 'Archive path metadata byte count overflow',
1049
+ );
1050
+ if (next > maximum) {
1051
+ throw new ProtocolError('Archive exceeds the effective path metadata byte limit');
1052
+ }
1053
+ return next;
1054
+ };
1055
+
1056
+ const effectivePathMetadataLimit = (configured?: number): number => {
1057
+ const limit = configured ?? maximumArchivePathMetadataBytes;
1058
+ checkedInteger(limit, 'Maximum archive path metadata bytes', false);
1059
+ if (limit > maximumArchivePathMetadataBytes) {
1060
+ throw new ProtocolError('Maximum archive path metadata bytes exceeds the protocol ceiling');
767
1061
  }
768
- seen.set(path, type);
1062
+ return limit;
1063
+ };
1064
+
1065
+ const effectiveMaterializedEntryLimit = (options: IExtractTarGzipOptions): number => {
1066
+ const limit = options.maximumMaterializedEntries ?? checkedMultiply(
1067
+ options.maximumEntries,
1068
+ 2,
1069
+ 'Maximum materialized archive entries overflow',
1070
+ );
1071
+ return checkedInteger(limit, 'Maximum materialized archive entries');
769
1072
  };
770
1073
 
771
1074
  const maximumTarStreamBytes = (maximumExtractedBytes: number, maximumEntries: number): number => {
@@ -799,10 +1102,14 @@ const parseTarGzip = async (
799
1102
  options: IExtractTarGzipOptions,
800
1103
  destination: string,
801
1104
  extract: boolean,
802
- ): Promise<IWorkspaceTreeMetadata> => {
1105
+ ): Promise<IExtractedArchiveMetadata> => {
803
1106
  const allowedPaths = options.allowedPaths
804
1107
  ? validateRelativeSelections(options.allowedPaths, 'Cache declaration')
805
1108
  : undefined;
1109
+ const maximumPathMetadataBytes = effectivePathMetadataLimit(
1110
+ options.maximumPathMetadataBytes,
1111
+ );
1112
+ const maximumMaterializedEntries = effectiveMaterializedEntryLimit(options);
806
1113
  const archive = await Deno.open(options.archivePath, { read: true }).catch((error) => {
807
1114
  throw new RunnerError('Unable to open staged transfer archive', { cause: error });
808
1115
  });
@@ -822,18 +1129,23 @@ const parseTarGzip = async (
822
1129
  }
823
1130
  const bytes = new StreamBytes(
824
1131
  decompressed,
825
- maximumTarStreamBytes(options.maximumExtractedBytes, options.maximumEntries),
1132
+ maximumTarStreamBytes(
1133
+ options.expectedMetadata.extractedSizeBytes,
1134
+ options.expectedMetadata.entryCount,
1135
+ ),
826
1136
  options.signal,
827
1137
  );
828
- const seen = new Map<string, TArchiveEntryType>();
1138
+ const archiveStructure = new Map<string, IArchiveStructureEntry>();
1139
+ const archiveEntries: IArchiveStructureEntry[] = [];
829
1140
  const symlinks: ISymlinkDescription[] = [];
830
1141
  let localPax: { path?: string; linkpath?: string } | undefined;
831
1142
  let globalPaxSeen = false;
832
1143
  let logicalBytes = 0;
833
1144
  let entryCount = 0;
1145
+ let pathMetadataBytes = 0;
834
1146
  let complete = false;
835
1147
  let primaryError: unknown;
836
- let result: IWorkspaceTreeMetadata | undefined;
1148
+ let result: IExtractedArchiveMetadata | undefined;
837
1149
  try {
838
1150
  while (true) {
839
1151
  const header = await bytes.readExactly(tarBlockSize);
@@ -882,7 +1194,7 @@ const parseTarGzip = async (
882
1194
  if (
883
1195
  globalPaxSeen ||
884
1196
  localPax ||
885
- seen.size > 0 ||
1197
+ entryCount > 0 ||
886
1198
  records.size !== 1 ||
887
1199
  !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(records.get('comment') ?? '')
888
1200
  ) {
@@ -908,18 +1220,26 @@ const parseTarGzip = async (
908
1220
  throw new ProtocolError('Tar archive contains a hardlink, special, or unsupported entry');
909
1221
  }
910
1222
  entryCount = checkedAdd(entryCount, 1, 'Tar entry count overflow');
911
- if (entryCount > options.maximumEntries) {
1223
+ if (
1224
+ entryCount > options.maximumEntries ||
1225
+ entryCount > options.expectedMetadata.entryCount
1226
+ ) {
912
1227
  throw new ProtocolError('Tar archive exceeds the effective entry limit');
913
1228
  }
914
1229
  const entryPax = localPax;
915
1230
  localPax = undefined;
916
1231
  const path = normalizeArchivePath(entryPax?.path ?? headerPath, type);
1232
+ pathMetadataBytes = addPathMetadataBytes(
1233
+ pathMetadataBytes,
1234
+ path,
1235
+ maximumPathMetadataBytes,
1236
+ );
917
1237
  const entryType: TArchiveEntryType = type === '5'
918
1238
  ? 'directory'
919
1239
  : type === '2'
920
1240
  ? 'symlink'
921
1241
  : 'file';
922
- assertArchiveStructure(seen, path, entryType);
1242
+ recordArchiveStructure(archiveStructure, archiveEntries, path, entryType);
923
1243
  if (allowedPaths) {
924
1244
  const selected = allowedPaths.some((allowed) =>
925
1245
  path === allowed || path.startsWith(`${allowed}/`)
@@ -947,14 +1267,22 @@ const parseTarGzip = async (
947
1267
  if (sizeBytes !== 0) throw new ProtocolError('Tar symlink has a non-zero size');
948
1268
  const linkTarget = entryPax?.linkpath ??
949
1269
  decodeTarText(header.subarray(157, 257), 'link name');
950
- parseLinkTarget(linkTarget);
1270
+ validateLinkTarget(linkTarget);
1271
+ pathMetadataBytes = addPathMetadataBytes(
1272
+ pathMetadataBytes,
1273
+ linkTarget,
1274
+ maximumPathMetadataBytes,
1275
+ );
951
1276
  symlinks.push({ path, target: linkTarget, scope: [] });
952
1277
  } else {
953
1278
  if (entryPax?.linkpath !== undefined) {
954
1279
  throw new ProtocolError('Tar regular file has link metadata');
955
1280
  }
956
1281
  logicalBytes = checkedAdd(logicalBytes, sizeBytes, 'Tar logical byte count overflow');
957
- if (logicalBytes > options.maximumExtractedBytes) {
1282
+ if (
1283
+ logicalBytes > options.maximumExtractedBytes ||
1284
+ logicalBytes > options.expectedMetadata.extractedSizeBytes
1285
+ ) {
958
1286
  throw new ProtocolError('Tar archive exceeds the effective extracted byte limit');
959
1287
  }
960
1288
  let output: Deno.FsFile | undefined;
@@ -992,10 +1320,15 @@ const parseTarGzip = async (
992
1320
  }
993
1321
  }
994
1322
  if (localPax) throw new ProtocolError('Tar archive ends with unused PAX metadata');
995
- validateSymlinkSet(symlinks);
1323
+ const materializedEntryCount = await validateArchiveStructure(
1324
+ archiveEntries,
1325
+ maximumMaterializedEntries,
1326
+ options.signal,
1327
+ );
1328
+ await validateSymlinkSet(symlinks, options.signal);
996
1329
  if (allowedPaths && options.requireAllowedPaths) {
997
1330
  for (const allowed of allowedPaths) {
998
- if (!seen.has(allowed)) {
1331
+ if (!archiveStructure.has(allowed)) {
999
1332
  throw new ProtocolError('Cache archive omits a declared path');
1000
1333
  }
1001
1334
  }
@@ -1008,13 +1341,14 @@ const parseTarGzip = async (
1008
1341
  }
1009
1342
  if (extract) {
1010
1343
  for (const symlink of symlinks) {
1344
+ if (options.signal?.aborted) throw options.signal.reason;
1011
1345
  const target = join(destination, ...symlink.path.split('/'));
1012
1346
  await Deno.mkdir(dirname(target), { recursive: true, mode: 0o700 });
1013
1347
  await Deno.symlink(symlink.target, target);
1014
1348
  }
1015
1349
  }
1016
1350
  complete = true;
1017
- result = { logicalBytes, entryCount };
1351
+ result = { logicalBytes, entryCount, materializedEntryCount };
1018
1352
  } catch (error) {
1019
1353
  primaryError = error;
1020
1354
  }
@@ -1038,9 +1372,14 @@ const parseTarGzip = async (
1038
1372
 
1039
1373
  export const extractTarGzipArchive = async (
1040
1374
  options: IExtractTarGzipOptions,
1041
- ): Promise<IWorkspaceTreeMetadata> => {
1375
+ ): Promise<IExtractedArchiveMetadata> => {
1042
1376
  checkedInteger(options.maximumExtractedBytes, 'Maximum extracted bytes');
1043
1377
  checkedInteger(options.maximumEntries, 'Maximum archive entries');
1378
+ checkedInteger(options.expectedMetadata.extractedSizeBytes, 'Declared extracted bytes');
1379
+ checkedInteger(options.expectedMetadata.entryCount, 'Declared archive entries');
1380
+ effectiveMaterializedEntryLimit(options);
1381
+ checkedInteger(options.reserveBytes ?? 0, 'Archive staging byte reserve');
1382
+ checkedInteger(options.reserveInodes ?? 0, 'Archive staging inode reserve');
1044
1383
  if (
1045
1384
  options.expectedMetadata.extractedSizeBytes > options.maximumExtractedBytes ||
1046
1385
  options.expectedMetadata.entryCount > options.maximumEntries
@@ -1048,7 +1387,14 @@ export const extractTarGzipArchive = async (
1048
1387
  throw new ProtocolError('Transfer metadata exceeds the effective extraction limits');
1049
1388
  }
1050
1389
  const destination = await assertEmptyDirectory(options.destinationPath);
1051
- await parseTarGzip(options, destination, false);
1390
+ const inspected = await parseTarGzip(options, destination, false);
1391
+ await ensureStagingCapacity(
1392
+ destination,
1393
+ inspected.logicalBytes,
1394
+ inspected.materializedEntryCount,
1395
+ options.reserveBytes ?? 0,
1396
+ options.reserveInodes ?? 0,
1397
+ );
1052
1398
  return await parseTarGzip(options, destination, true);
1053
1399
  };
1054
1400
 
@@ -1106,27 +1452,38 @@ const selectedMembership = (
1106
1452
  path: string,
1107
1453
  type: TArchiveEntryType,
1108
1454
  selections: string[],
1109
- ): { accepted: boolean; scope: string[] } => {
1455
+ ): { accepted: boolean; selected?: string } => {
1110
1456
  const selected = selections.find((candidate) =>
1111
1457
  path === candidate || path.startsWith(`${candidate}/`)
1112
1458
  );
1113
1459
  if (selected) {
1114
1460
  return {
1115
1461
  accepted: true,
1116
- scope: path === selected ? selected.split('/').slice(0, -1) : selected.split('/'),
1462
+ selected,
1117
1463
  };
1118
1464
  }
1119
1465
  return {
1120
1466
  accepted: type === 'directory' &&
1121
1467
  selections.some((candidate) => candidate.startsWith(`${path}/`)),
1122
- scope: [],
1123
1468
  };
1124
1469
  };
1125
1470
 
1126
1471
  const collectArchiveEntries = async (
1127
1472
  options: ICreateTarGzipOptions,
1128
1473
  ): Promise<{ entries: IArchiveEntry[]; root: string; rootSnapshot: IFileSnapshot }> => {
1474
+ if (options.signal?.aborted) throw options.signal.reason;
1129
1475
  const selections = validateRelativeSelections(options.selections, 'Workspace export selection');
1476
+ const scopesBySelection = new Map<
1477
+ string,
1478
+ { descendantScope: string[]; selectedEntryScope: string[] }
1479
+ >();
1480
+ for (const selection of selections) {
1481
+ const descendantScope = selection.split('/');
1482
+ scopesBySelection.set(selection, {
1483
+ descendantScope,
1484
+ selectedEntryScope: descendantScope.slice(0, -1),
1485
+ });
1486
+ }
1130
1487
  const root = await Deno.realPath(options.sourcePath).catch((error) => {
1131
1488
  throw new RunnerError('Unable to resolve workspace export root', { cause: error });
1132
1489
  });
@@ -1138,9 +1495,78 @@ const collectArchiveEntries = async (
1138
1495
  const entries: IArchiveEntry[] = [];
1139
1496
  const present = new Set<string>();
1140
1497
  let logicalBytes = 0;
1498
+ let pathMetadataBytes = 0;
1499
+ let pendingPathMetadataBytes = 0;
1500
+ let pendingEntries = 0;
1501
+ const maximumPathMetadataBytes = effectivePathMetadataLimit(
1502
+ options.maximumPathMetadataBytes,
1503
+ );
1504
+ const retainPathMetadata = (value: string): void => {
1505
+ const next = addPathMetadataBytes(
1506
+ pathMetadataBytes,
1507
+ value,
1508
+ maximumPathMetadataBytes,
1509
+ );
1510
+ const retained = checkedAdd(
1511
+ next,
1512
+ pendingPathMetadataBytes,
1513
+ 'Workspace export retained path metadata overflow',
1514
+ );
1515
+ if (retained > maximumPathMetadataBytes) {
1516
+ throw new ProtocolError('Archive exceeds the effective path metadata byte limit');
1517
+ }
1518
+ pathMetadataBytes = next;
1519
+ };
1520
+ const collectChildren = async (
1521
+ absolutePath: string,
1522
+ parentPath: string,
1523
+ ): Promise<Array<{ name: string; nameBytes: Uint8Array; pathBytes: number } | undefined>> => {
1524
+ const children: Array<{ name: string; nameBytes: Uint8Array; pathBytes: number }> = [];
1525
+ for await (const child of Deno.readDir(absolutePath)) {
1526
+ if (options.signal?.aborted) throw options.signal.reason;
1527
+ const childPath = parentPath ? `${parentPath}/${child.name}` : child.name;
1528
+ pathSegments(childPath, maximumPathBytes, 'Workspace export');
1529
+ const nameBytes = textEncoder.encode(child.name);
1530
+ const pathBytes = textEncoder.encode(childPath).byteLength;
1531
+ const nextPendingEntries = checkedAdd(
1532
+ pendingEntries,
1533
+ 1,
1534
+ 'Workspace export pending entry count overflow',
1535
+ );
1536
+ const retainedEntries = checkedAdd(
1537
+ entries.length,
1538
+ nextPendingEntries,
1539
+ 'Workspace export retained entry count overflow',
1540
+ );
1541
+ if (
1542
+ retainedEntries > options.maximumEntries ||
1543
+ retainedEntries > options.expectedMetadata.entryCount
1544
+ ) {
1545
+ throw new ProtocolError('Workspace export exceeds the effective entry limit');
1546
+ }
1547
+ const nextPendingPathMetadataBytes = checkedAdd(
1548
+ pendingPathMetadataBytes,
1549
+ pathBytes,
1550
+ 'Workspace export pending path metadata overflow',
1551
+ );
1552
+ const retainedPathMetadataBytes = checkedAdd(
1553
+ pathMetadataBytes,
1554
+ nextPendingPathMetadataBytes,
1555
+ 'Workspace export retained path metadata overflow',
1556
+ );
1557
+ if (retainedPathMetadataBytes > maximumPathMetadataBytes) {
1558
+ throw new ProtocolError('Archive exceeds the effective path metadata byte limit');
1559
+ }
1560
+ pendingEntries = nextPendingEntries;
1561
+ pendingPathMetadataBytes = nextPendingPathMetadataBytes;
1562
+ children.push({ name: child.name, nameBytes, pathBytes });
1563
+ }
1564
+ return await orderByUtf8Bytes(children, (child) => child.nameBytes, options.signal);
1565
+ };
1141
1566
  const visit = async (path: string): Promise<void> => {
1142
1567
  if (options.signal?.aborted) throw options.signal.reason;
1143
1568
  pathSegments(path, maximumPathBytes, 'Workspace export');
1569
+ retainPathMetadata(path);
1144
1570
  const absolutePath = join(root, ...path.split('/'));
1145
1571
  const stat = await Deno.lstat(absolutePath);
1146
1572
  const type = typeForStat(stat);
@@ -1159,13 +1585,22 @@ const collectArchiveEntries = async (
1159
1585
  throw new RunnerError('Workspace export contains a symbolic link');
1160
1586
  }
1161
1587
  let linkTarget: string | undefined;
1588
+ let symlinkScope: string[] | undefined;
1162
1589
  if (type === 'symlink') {
1163
1590
  linkTarget = await Deno.readLink(absolutePath);
1164
- parseLinkTarget(linkTarget);
1591
+ validateLinkTarget(linkTarget);
1592
+ retainPathMetadata(linkTarget);
1593
+ const selectionScopes = scopesBySelection.get(membership.selected!)!;
1594
+ symlinkScope = path === membership.selected
1595
+ ? selectionScopes.selectedEntryScope
1596
+ : selectionScopes.descendantScope;
1165
1597
  }
1166
1598
  const sizeBytes = type === 'file' ? snapshot.size : 0;
1167
1599
  logicalBytes = checkedAdd(logicalBytes, sizeBytes, 'Workspace export byte count overflow');
1168
- if (logicalBytes > options.maximumExtractedBytes) {
1600
+ if (
1601
+ logicalBytes > options.maximumExtractedBytes ||
1602
+ logicalBytes > options.expectedMetadata.logicalBytes
1603
+ ) {
1169
1604
  throw new ProtocolError('Workspace export exceeds the effective extracted byte limit');
1170
1605
  }
1171
1606
  entries.push({
@@ -1175,26 +1610,38 @@ const collectArchiveEntries = async (
1175
1610
  sizeBytes,
1176
1611
  executable: type === 'file' && (snapshot.mode & 0o111) !== 0,
1177
1612
  ...(linkTarget === undefined ? {} : { linkTarget }),
1178
- symlinkScope: membership.scope,
1613
+ ...(symlinkScope === undefined ? {} : { symlinkScope }),
1179
1614
  snapshot,
1180
1615
  });
1181
1616
  present.add(path);
1182
- if (entries.length > options.maximumEntries) {
1617
+ if (
1618
+ entries.length > options.maximumEntries ||
1619
+ entries.length > options.expectedMetadata.entryCount
1620
+ ) {
1183
1621
  throw new ProtocolError('Workspace export exceeds the effective entry limit');
1184
1622
  }
1185
1623
  if (type === 'directory') {
1186
- const children: string[] = [];
1187
- for await (const child of Deno.readDir(absolutePath)) children.push(child.name);
1188
- children.sort(compareUtf8);
1189
- for (const child of children) await visit(`${path}/${child}`);
1624
+ const children = await collectChildren(absolutePath, path);
1625
+ for (let index = 0; index < children.length; index++) {
1626
+ if (options.signal?.aborted) throw options.signal.reason;
1627
+ const child = children[index]!;
1628
+ children[index] = undefined;
1629
+ pendingEntries--;
1630
+ pendingPathMetadataBytes -= child.pathBytes;
1631
+ await visit(`${path}/${child.name}`);
1632
+ }
1190
1633
  await assertSnapshot(absolutePath, snapshot);
1191
1634
  }
1192
1635
  };
1193
- const roots: string[] = [];
1194
- for await (const entry of Deno.readDir(root)) roots.push(entry.name);
1195
- roots.sort(compareUtf8);
1196
- for (const path of roots) await visit(path);
1197
- entries.sort((left, right) => compareUtf8(left.path, right.path));
1636
+ const roots = await collectChildren(root, '');
1637
+ for (let index = 0; index < roots.length; index++) {
1638
+ if (options.signal?.aborted) throw options.signal.reason;
1639
+ const rootEntry = roots[index]!;
1640
+ roots[index] = undefined;
1641
+ pendingEntries--;
1642
+ pendingPathMetadataBytes -= rootEntry.pathBytes;
1643
+ await visit(rootEntry.name);
1644
+ }
1198
1645
  if (options.requireAllSelections !== false) {
1199
1646
  for (const selection of selections) {
1200
1647
  if (!present.has(selection)) throw new RunnerError('Workspace export omits a selected path');
@@ -1206,12 +1653,13 @@ const collectArchiveEntries = async (
1206
1653
  ) {
1207
1654
  throw new ProtocolError('Workspace exporter returned mismatched tree metadata');
1208
1655
  }
1209
- validateSymlinkSet(
1656
+ await validateSymlinkSet(
1210
1657
  entries.filter((entry) => entry.type === 'symlink').map((entry) => ({
1211
1658
  path: entry.path,
1212
1659
  target: entry.linkTarget!,
1213
- scope: entry.symlinkScope,
1660
+ scope: entry.symlinkScope!,
1214
1661
  })),
1662
+ options.signal,
1215
1663
  );
1216
1664
  await assertSnapshot(root, rootSnapshot);
1217
1665
  return { entries, root, rootSnapshot };
@@ -1318,7 +1766,7 @@ const assertSafeAncestors = async (root: string, path: string, device: number):
1318
1766
  };
1319
1767
 
1320
1768
  const assertOpenFileSnapshot = async (
1321
- file: Deno.FsFile,
1769
+ file: Pick<Deno.FsFile, 'stat'>,
1322
1770
  expected: IFileSnapshot,
1323
1771
  ): Promise<void> => {
1324
1772
  const stat = await file.stat();
@@ -1340,6 +1788,7 @@ async function* tarChunks(
1340
1788
  entries: IArchiveEntry[],
1341
1789
  root: string,
1342
1790
  rootDevice: number,
1791
+ openRead: NonNullable<ITransferArchiveFileOperations['openRead']>,
1343
1792
  signal?: AbortSignal,
1344
1793
  ): AsyncGenerator<Uint8Array> {
1345
1794
  let index = 0;
@@ -1374,38 +1823,44 @@ async function* tarChunks(
1374
1823
  const type = entry.type === 'directory' ? '5' : entry.type === 'symlink' ? '2' : '0';
1375
1824
  yield tarHeader(pathField, type, entry.sizeBytes, entry.executable, linkField);
1376
1825
  if (entry.type === 'file') {
1377
- const file = await Deno.open(entry.absolutePath, { read: true });
1826
+ const file = await openRead(entry.absolutePath);
1378
1827
  let fileError: unknown;
1379
1828
  try {
1380
- await assertOpenFileSnapshot(file, entry.snapshot);
1381
- const buffer = new Uint8Array(streamBufferBytes);
1382
- let emitted = 0;
1383
- while (true) {
1384
- if (signal?.aborted) throw signal.reason;
1385
- const read = await file.read(buffer);
1386
- if (read === null) break;
1387
- emitted = checkedAdd(emitted, read, 'Workspace export file length overflow');
1388
- if (emitted > entry.sizeBytes) {
1389
- throw new RunnerError('Workspace export file grew during archive creation');
1829
+ {
1830
+ using _fileOwner = {
1831
+ [Symbol.dispose]: () => file.close(),
1832
+ };
1833
+ try {
1834
+ await assertOpenFileSnapshot(file, entry.snapshot);
1835
+ const buffer = new Uint8Array(streamBufferBytes);
1836
+ let emitted = 0;
1837
+ while (true) {
1838
+ if (signal?.aborted) throw signal.reason;
1839
+ const read = await file.read(buffer);
1840
+ if (read === null) break;
1841
+ emitted = checkedAdd(emitted, read, 'Workspace export file length overflow');
1842
+ if (emitted > entry.sizeBytes) {
1843
+ throw new RunnerError('Workspace export file grew during archive creation');
1844
+ }
1845
+ yield buffer.slice(0, read);
1846
+ }
1847
+ if (emitted !== entry.sizeBytes) {
1848
+ throw new RunnerError('Workspace export file shrank during archive creation');
1849
+ }
1850
+ await assertOpenFileSnapshot(file, entry.snapshot);
1851
+ } catch (error) {
1852
+ fileError = error;
1853
+ throw error;
1390
1854
  }
1391
- yield buffer.slice(0, read);
1392
1855
  }
1393
- if (emitted !== entry.sizeBytes) {
1394
- throw new RunnerError('Workspace export file shrank during archive creation');
1395
- }
1396
- await assertOpenFileSnapshot(file, entry.snapshot);
1397
1856
  } catch (error) {
1398
- fileError = error;
1399
- }
1400
- try {
1401
- file.close();
1402
- } catch (cleanupError) {
1857
+ if (error === fileError) throw error;
1858
+ const cleanupError = error instanceof SuppressedError ? error.error : error;
1403
1859
  throw new ResourceCleanupError(
1404
1860
  'Workspace export file cleanup failed',
1405
1861
  fileError === undefined ? [cleanupError] : [fileError, cleanupError],
1406
1862
  );
1407
1863
  }
1408
- if (fileError !== undefined) throw fileError;
1409
1864
  await assertSnapshot(entry.absolutePath, entry.snapshot);
1410
1865
  const padding = paddingFor(entry.sizeBytes);
1411
1866
  if (padding.byteLength) yield padding;
@@ -1474,7 +1929,13 @@ export const createTarGzipArchive = async (
1474
1929
  Uint8Array
1475
1930
  >;
1476
1931
  const compressed = iteratorStream(
1477
- tarChunks(collected.entries, collected.root, collected.rootSnapshot.dev, options.signal),
1932
+ tarChunks(
1933
+ collected.entries,
1934
+ collected.root,
1935
+ collected.rootSnapshot.dev,
1936
+ fileOperations.openRead ?? defaultFileOperations.openRead!,
1937
+ options.signal,
1938
+ ),
1478
1939
  ).pipeThrough(compressor);
1479
1940
  reader = compressed.getReader();
1480
1941
  while (true) {
@@ -1489,7 +1950,10 @@ export const createTarGzipArchive = async (
1489
1950
  await writeAll(output, value);
1490
1951
  }
1491
1952
  await assertSnapshot(collected.root, collected.rootSnapshot);
1492
- for (const entry of collected.entries) await assertSnapshot(entry.absolutePath, entry.snapshot);
1953
+ for (const entry of collected.entries) {
1954
+ if (options.signal?.aborted) throw options.signal.reason;
1955
+ await assertSnapshot(entry.absolutePath, entry.snapshot);
1956
+ }
1493
1957
  archiveSnapshot = snapshotFor(
1494
1958
  await Deno.lstat(path),
1495
1959
  'file',