Skip to content

Commit 3c6b73b

Browse files
Do not factor the files in an .rt.tar.gz as part of the overall review limits, check them independently []
1 parent fb582ed commit 3c6b73b

9 files changed

Lines changed: 181 additions & 65 deletions

File tree

‎dev_tools/pylibs/edgacknowledg/client/test/__init__.py‎

Lines changed: 44 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -55,14 +55,26 @@
5555
__all__ = ['IllegalFileAccessError']
5656

5757

58+
def _run_test_output(
59+
path: Path, max_rt_entries: Optional[int],
60+
max_rt_member_bytes: Optional[int]) -> edgtest.runtest.RunTestOutput:
61+
return edgtest.runtest.RunTestOutput(
62+
path,
63+
max_entries = max_rt_entries,
64+
max_member_bytes = max_rt_member_bytes
65+
)
66+
67+
5868
def _rt_path_for(config_dir: ConfinedPath, test_id: str) -> ConfinedPath:
5969
return config_dir / str(PurePosixPath(test_id).with_suffix(
6070
edgtest.runtest.RUN_TEST_OUTPUT_SUFFIX
6171
))
6272

6373

6474
def _create_status_dict(elog_file_paths: List[ConfinedPath], *,
65-
is_multi_config_run: bool) -> _StatusDict:
75+
is_multi_config_run: bool,
76+
max_rt_entries: Optional[int],
77+
max_rt_member_bytes: Optional[int]) -> _StatusDict:
6678
# test_id -> config_name -> combined_diff_hash.
6779
pending: Dict[str, Dict[str, str]] = {}
6880
lines_by_test_config: Dict[str, Dict[str, List[Dict[str, str]]]] = {}
@@ -85,7 +97,11 @@ def _create_status_dict(elog_file_paths: List[ConfinedPath], *,
8597
if config_name not in pending[key]:
8698
rt_file_path = _rt_path_for(elog_file_path.parent, key)
8799
pending[key][config_name] = (
88-
edgtest.runtest.grouping_combined_diff_hash(rt_file_path.path)
100+
edgtest.runtest.grouping_combined_diff_hash(
101+
rt_file_path.path,
102+
max_entries = max_rt_entries,
103+
max_member_bytes = max_rt_member_bytes
104+
)
89105
)
90106
lines_by_test_config[key][config_name] = []
91107

@@ -183,7 +199,9 @@ async def run_test_source_handler(channel: Channel,
183199
context: SandboxContext,
184200
test_home: ConfinedPath,
185201
run_dir: ConfinedPath,
186-
changes_files: Dict[str, ConfinedPath]
202+
changes_files: Dict[str, ConfinedPath], *,
203+
max_rt_entries: Optional[int] = None,
204+
max_rt_member_bytes: Optional[int] = None
187205
) -> None:
188206
'''Handle one test source request on ``channel``. Every file is reached
189207
from ``test_home`` or ``run_dir``, so it can't leave them, and commands
@@ -222,7 +240,9 @@ def test_id_to_path(test_id: str) -> ConfinedPath:
222240
'name': 'Changes List',
223241
'statuses': _create_status_dict(
224242
_matching_change_files(changes_files, 'changes.elog'),
225-
is_multi_config_run = is_multi_config_run
243+
is_multi_config_run = is_multi_config_run,
244+
max_rt_entries = max_rt_entries,
245+
max_rt_member_bytes = max_rt_member_bytes
226246
)
227247
}
228248
)
@@ -237,7 +257,9 @@ def test_id_to_path(test_id: str) -> ConfinedPath:
237257
'name': 'Regressions List',
238258
'statuses': _create_status_dict(
239259
regress_files,
240-
is_multi_config_run = is_multi_config_run
260+
is_multi_config_run = is_multi_config_run,
261+
max_rt_entries = max_rt_entries,
262+
max_rt_member_bytes = max_rt_member_bytes
241263
)
242264
}
243265
)
@@ -252,7 +274,9 @@ def test_id_to_path(test_id: str) -> ConfinedPath:
252274
'name': 'Improvements List',
253275
'statuses': _create_status_dict(
254276
improve_files,
255-
is_multi_config_run = is_multi_config_run
277+
is_multi_config_run = is_multi_config_run,
278+
max_rt_entries = max_rt_entries,
279+
max_rt_member_bytes = max_rt_member_bytes
256280
)
257281
}
258282
)
@@ -314,7 +338,8 @@ async def form_curr_diff_text(config_name: str,
314338
tmp_dir = Path(tmp_dir_name)
315339
entries: List[Tuple[Dict[str, Any], List[str]]] = []
316340

317-
with edgtest.runtest.RunTestOutput(case_rt_path.path) as rt_output:
341+
with _run_test_output(case_rt_path.path, max_rt_entries,
342+
max_rt_member_bytes) as rt_output:
318343
for case_number, case in enumerate(
319344
rt_output.metadata.get('cases', []),
320345
start = 1
@@ -413,14 +438,16 @@ async def form_curr_diff_text(config_name: str,
413438
)
414439

415440
if request_tag == RequestTags.TEST_SHOW_DIFF:
416-
with edgtest.runtest.RunTestOutput(rt_file_path.path) as rt_output:
441+
with _run_test_output(rt_file_path.path, max_rt_entries,
442+
max_rt_member_bytes) as rt_output:
417443
static_text = ''.join(rt_output.combined_static_diff())
418444
client_response = {
419445
'id': configured_test_id,
420446
**trunc_display_content(static_text)
421447
}
422448
elif request_tag == RequestTags.TEST_SHOW_RAW_OUTPUT:
423-
with edgtest.runtest.RunTestOutput(rt_file_path.path) as rt_output:
449+
with _run_test_output(rt_file_path.path, max_rt_entries,
450+
max_rt_member_bytes) as rt_output:
424451
raw_output = ''.join(rt_output.combined_raw_output())
425452
client_response = {
426453
'id': configured_test_id,
@@ -602,7 +629,9 @@ def __init__(self,
602629
slug: str,
603630
context: SandboxContext,
604631
test_home: ConfinedPath,
605-
root: ConfinedPath) -> None:
632+
root: ConfinedPath, *,
633+
max_rt_entries: Optional[int] = None,
634+
max_rt_member_bytes: Optional[int] = None) -> None:
606635
'''Requests reach files only through ``test_home`` and the run
607636
directory ``root``, and run commands in ``context``.
608637
'''
@@ -611,6 +640,8 @@ def __init__(self,
611640
self._context = context
612641
self._test_home = test_home
613642
self._root = root
643+
self._max_rt_entries = max_rt_entries
644+
self._max_rt_member_bytes = max_rt_member_bytes
614645

615646
def _changes_files(self) -> Dict[str, ConfinedPath]:
616647
'''Each configuration's changes file in the run, found now.'''
@@ -638,7 +669,9 @@ async def handle_request(self, channel: Channel) -> None:
638669
self._context,
639670
self._test_home,
640671
self._root,
641-
await edgutil.async_to_thread(self._changes_files)
672+
await edgutil.async_to_thread(self._changes_files),
673+
max_rt_entries = self._max_rt_entries,
674+
max_rt_member_bytes = self._max_rt_member_bytes
642675
)
643676

644677
async def handle_test_edit_request(

‎dev_tools/pylibs/edgacknowledg/forge/config.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,10 @@
3434
# The largest diff (of tests/, in bytes) a pull request may have: it is
3535
# held in memory, and copied and split into lines more than once.
3636
DEFAULT_MAX_DIFF_BYTES = 64 * 1024 * 1024
37-
# The most entries an artifact may have (its zip's, and its tarballs'
38-
# together), and the largest its zip's central directory may be: zipfile
39-
# reads all of that directory into memory, before we can count. CI's test
40-
# results reach about 170,000 entries, of about 106 bytes each there.
37+
# The most entries an artifact zip may have, and the largest its central
38+
# directory may be: zipfile reads all of that directory into memory, before
39+
# we can count. CI's test results reach about 170,000 entries, of about 106
40+
# bytes each there.
4141
DEFAULT_MAX_ARTIFACT_ENTRIES = 500_000
4242
DEFAULT_MAX_ARTIFACT_DIRECTORY_BYTES = 64 * 1024 * 1024
4343

‎dev_tools/pylibs/edgacknowledg/forge/publisher/pool_process.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@
5151
# Parallel cg_annotate runs in one process (it answers one request at a
5252
# time, so this only matters to a request running several).
5353
_BENCH_WORKERS = 2
54+
_MAX_RT_ENTRIES = 10_000
55+
_MAX_RT_MEMBER_BYTES = 64 * 1024 * 1024
5456

5557

5658
def build_handler(section: SectionRecord,
@@ -67,7 +69,9 @@ def build_handler(section: SectionRecord,
6769
section.slug,
6870
context,
6971
context.subpath(section.home),
70-
context.subpath(section.root)
72+
context.subpath(section.root),
73+
max_rt_entries = _MAX_RT_ENTRIES,
74+
max_rt_member_bytes = _MAX_RT_MEMBER_BYTES
7175
)
7276
if section.kind == KIND_BENCH:
7377
session = BenchReviewSession(

‎dev_tools/pylibs/edgacknowledg/forge/workspace.py‎

Lines changed: 2 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@
3333
import shutil
3434
import stat
3535
import struct
36-
import tarfile
3736
import urllib.parse
3837
import zipfile
3938

@@ -348,22 +347,6 @@ def _central_directory_size(zip_path: Path) -> Optional[int]:
348347
return directory_size
349348

350349

351-
def _check_inner_tarball(path: Path, budget: _Budget) -> None:
352-
'''Charge a (gzipped) tarball's decompressed size and entries to
353-
``budget``; reviewers' requests decompress these, so they're
354-
bombs-in-waiting otherwise.
355-
'''
356-
try:
357-
with tarfile.open(path, 'r:*') as archive:
358-
for member in archive:
359-
budget.count_entry()
360-
if not (member.isfile() or member.isdir()):
361-
raise UnsafeArchiveError(f"{path.name} contains a link or device")
362-
budget.spend(member.size)
363-
except tarfile.TarError as ex:
364-
raise UnsafeArchiveError(f"{path.name} is not a valid tarball") from ex
365-
366-
367350
def extract_artifact(
368351
zip_path: Path, destination: Path, *, max_bytes: int,
369352
max_entries: int = DEFAULT_MAX_ARTIFACT_ENTRIES,
@@ -372,8 +355,8 @@ def extract_artifact(
372355
373356
Rejects absolute or escaping paths and symlinks, and a zip whose central
374357
directory is over ``max_directory_bytes``, and stops once more than
375-
``max_bytes`` would be written, or ``max_entries`` entries made (counting
376-
inner tarballs' contents too).
358+
``max_bytes`` would be written, or ``max_entries`` zip entries made.
359+
Inner tarballs are checked when opened by a reviewer.
377360
'''
378361
directory_size = _central_directory_size(zip_path)
379362
if directory_size is not None and directory_size > max_directory_bytes:
@@ -382,7 +365,6 @@ def extract_artifact(
382365
f"({ENV_PREFIX}MAX_ARTIFACT_DIRECTORY_BYTES)"
383366
)
384367
budget = _Budget(max_bytes, max_entries)
385-
tarballs = []
386368
try:
387369
with zipfile.ZipFile(zip_path) as archive:
388370
for info in archive.infolist():
@@ -407,14 +389,9 @@ def extract_artifact(
407389
break
408390
budget.spend(len(chunk))
409391
sink.write(chunk)
410-
if target.name.endswith(('.tar.gz', '.tgz', '.tar')):
411-
tarballs.append(target)
412392
except zipfile.BadZipFile as ex:
413393
raise UnsafeArchiveError('artifact is not a valid zip archive') from ex
414394

415-
for tarball in tarballs:
416-
_check_inner_tarball(tarball, budget)
417-
418395

419396
class Workspaces:
420397
'''Clones and worktrees under ``home`` for one forge; a diff (``diff``)

‎dev_tools/pylibs/edgtest/runtest/__init__.py‎

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -958,20 +958,29 @@ def _unlink_missing_ok(path: Path) -> None:
958958
elif path.exists():
959959
path.unlink()
960960

961-
def read_combined_diff_hash(rt_file_path: Path) -> Optional[str]:
961+
def read_combined_diff_hash(rt_file_path: Path, *,
962+
max_entries: Optional[int] = None,
963+
max_member_bytes: Optional[int] = None
964+
) -> Optional[str]:
962965
'''Return metadata.combined_diff_hash, or None when there is no diff.'''
963-
with RunTestOutput(rt_file_path) as rt_output:
966+
with RunTestOutput(rt_file_path, max_entries = max_entries,
967+
max_member_bytes = max_member_bytes) as rt_output:
964968
return rt_output.metadata.get('combined_diff_hash')
965969

966-
def grouping_combined_diff_hash(rt_file_path: Path) -> str:
970+
def grouping_combined_diff_hash(rt_file_path: Path, *,
971+
max_entries: Optional[int] = None,
972+
max_member_bytes: Optional[int] = None) -> str:
967973
'''Return a combined diff hash suitable for grouping configs.
968974
969975
Missing .rt.tar files use the sentinel "missing". Archives with no
970976
change.diff members use the SHA-256 of empty content so they still group.
971977
'''
972978
if not rt_file_path.exists():
973979
return 'missing'
974-
combined = read_combined_diff_hash(rt_file_path)
980+
combined = read_combined_diff_hash(
981+
rt_file_path, max_entries = max_entries,
982+
max_member_bytes = max_member_bytes
983+
)
975984
if combined is None:
976985
return hash_diff_bytes(b'')
977986
return combined
@@ -1320,8 +1329,11 @@ def _read_tar_lines_member(tar: tarfile.TarFile,
13201329
class RunTestOutput:
13211330
'''Context manager for reading a structured .rt.tar run artifact once.'''
13221331

1323-
def __init__(self, path: Path) -> None:
1332+
def __init__(self, path: Path, *, max_entries: Optional[int] = None,
1333+
max_member_bytes: Optional[int] = None) -> None:
13241334
self.path = path
1335+
self._max_entries = max_entries
1336+
self._max_member_bytes = max_member_bytes
13251337
self._tar: Optional[tarfile.TarFile] = None
13261338
self._metadata: Optional[Dict[str, Any]] = None
13271339
self._member_names: Optional[Set[str]] = None
@@ -1332,6 +1344,22 @@ def __enter__(self) -> 'RunTestOutput':
13321344
'r:gz' if RT_TAR_GZ_SUPPORTED else 'r',
13331345
format = tarfile.PAX_FORMAT
13341346
)
1347+
try:
1348+
if self._max_entries is not None or self._max_member_bytes is not None:
1349+
for count, member in enumerate(self._tar, start = 1):
1350+
if self._max_entries is not None and count > self._max_entries:
1351+
raise ValueError('run artifact has too many entries')
1352+
if not (member.isfile() or member.isdir()):
1353+
raise RunTestOutputLinkError(
1354+
f"{member.name} is a link or device"
1355+
)
1356+
if (self._max_member_bytes is not None and
1357+
member.size > self._max_member_bytes):
1358+
raise ValueError(f"run artifact member {member.name} is too large")
1359+
except BaseException:
1360+
self._tar.close()
1361+
self._tar = None
1362+
raise
13351363
return self
13361364

13371365
def __exit__(self, _type: Any, _value: Any, _tb: Any) -> None:

‎dev_tools/services/acknowledg-forge/README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,8 @@ from the environment variable shown as a fallback.
111111
| `ACKNOWLEDG_FORGE_COMMENTS` | `0` | `1` enables comments (needs the forge token) |
112112
| `ACKNOWLEDG_FORGE_SETTLE_TIMEOUT` | `7200` | Seconds after a push to stop waiting for CI before commenting |
113113
| `ACKNOWLEDG_FORGE_MAX_ARTIFACT_BYTES` | 256 MiB | Largest artifact download |
114-
| `ACKNOWLEDG_FORGE_MAX_EXTRACTED_BYTES` | 2 GiB | Largest extracted artifact (including inner tarballs) |
115-
| `ACKNOWLEDG_FORGE_MAX_ARTIFACT_ENTRIES` | `500000` | Most entries in an artifact (including inner tarballs'). CI's test results reach about 170,000 |
114+
| `ACKNOWLEDG_FORGE_MAX_EXTRACTED_BYTES` | 2 GiB | Largest extracted artifact (including stored, compressed inner tarballs, but not their unextracted contents) |
115+
| `ACKNOWLEDG_FORGE_MAX_ARTIFACT_ENTRIES` | `500000` | Most ZIP entries in an artifact. Inner tarballs are checked when read |
116116
| `ACKNOWLEDG_FORGE_MAX_ARTIFACT_DIRECTORY_BYTES` | 64 MiB | Largest artifact zip central directory, which is read into memory whole (about 106 bytes per entry in CI's test results) |
117117
| `ACKNOWLEDG_FORGE_MAX_DIFF_BYTES` | 64 MiB | Largest diff of a pull request's `tests/`, which is held in memory and copied more than once: raising it may need a higher `mem_limit` for the service ([`compose.yaml`](compose.yaml)) |
118118
| `ACKNOWLEDG_FORGE_MAX_SPARSE_PATTERNS` | `20000` | Most sparse-checkout patterns in a review's worktree (up to two per test). Checking out takes time proportional to patterns times paths |

‎dev_tools/services/acknowledg-forge/SANDBOXING.md‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,7 @@ sequenceDiagram
279279
Note over S: check out its merge-base,<br/>symlinks as plain files
280280
Note over S: check_plain_tree(worktree)
281281
S->>F: download the CI artifact (size-capped)
282-
Note over S: extract it: no links, no escaping paths,<br/>inner tarballs size-capped
282+
Note over S: extract it: no links or escaping paths,<br/>stored inner tarballs size-capped
283283
S->>B: edg-rematerialize-test-run diff
284284
Note over B: worktree read-only,<br/>build-staging writable,<br/>time-limited
285285
B-->>S: output, exit status
@@ -512,9 +512,9 @@ them. Several layers keep the service from reading through one:
512512
writes, which also may not hold hard links.
513513
- The section's directories, including the bench baselines a pull request
514514
supplies, must be real directories.
515-
- CI artifacts may not contain links or escaping paths, nor may the
516-
`.rt.tar.gz` files inside them. Reading those tarballs later refuses link
517-
members as well.
515+
- CI artifact ZIPs may not contain links or escaping paths. When a reviewer
516+
opens a `.rt.tar.gz` file inside one, its entries are checked for links
517+
and devices, excessive counts, and oversized members.
518518
- The handlers open files through `ConfinedPath`, which opens each path
519519
component with `O_NOFOLLOW` relative to the last, so a symlink anywhere
520520
on the way is refused, even one created after a check. A refused path
@@ -525,8 +525,10 @@ them. Several layers keep the service from reading through one:
525525

526526
| Resource | Limit |
527527
| --- | --- |
528-
| Artifact download | `ACKNOWLEDG_FORGE_MAX_ARTIFACT_BYTES` (256 MiB), also counting the decompressed size of inner tarballs |
529-
| Artifact entries | `ACKNOWLEDG_FORGE_MAX_ARTIFACT_ENTRIES` (500,000), counting inner tarballs' too; and its zip's central directory, `ACKNOWLEDG_FORGE_MAX_ARTIFACT_DIRECTORY_BYTES` (64 MiB), checked before zipfile reads it |
528+
| Artifact download | `ACKNOWLEDG_FORGE_MAX_ARTIFACT_BYTES` (256 MiB) |
529+
| Extracted artifact | `ACKNOWLEDG_FORGE_MAX_EXTRACTED_BYTES` (2 GiB), counting the stored size of inner tarballs, not their unextracted contents |
530+
| Artifact entries | `ACKNOWLEDG_FORGE_MAX_ARTIFACT_ENTRIES` (500,000) for ZIP entries, 10,000 per inner tarball when opened; and its zip's central directory, `ACKNOWLEDG_FORGE_MAX_ARTIFACT_DIRECTORY_BYTES` (64 MiB), checked before zipfile reads it |
531+
| Inner tarball member | 64 MiB per member when a reviewer opens a tarball |
530532
| A pull request's diff of `tests/` | `ACKNOWLEDG_FORGE_MAX_DIFF_BYTES` (64 MiB) |
531533
| A review worktree's sparse-checkout patterns | `ACKNOWLEDG_FORGE_MAX_SPARSE_PATTERNS` (20,000) |
532534
| A file read for a reviewer | 64 MiB; a larger one fails the request |

0 commit comments

Comments
 (0)