Skip to content

Commit ea0fb42

Browse files
committed
fix(search): validate permission upload manifests and file inputs
1 parent b2faf89 commit ea0fb42

15 files changed

Lines changed: 245 additions & 62 deletions

File tree

‎apps/docs/content/docs/cli/organizations.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,7 @@ sim organizations search sources permissions imports put-part <sourceId> <import
351351
| --- | --- | --- |
352352
| `--organization <value>` | Yes | Organization identifier. |
353353
| `--field <value>` | Yes | CSV file this part belongs to. Accepted values: `userMapping`, `projectPermissions`. |
354-
| `--content <value>` | Yes | Complete CSV records, at most 5,000 rows and 1 MiB of UTF-8; an optional header may appear in each part. |
354+
| `--content <value\|@file>` | Yes | Complete CSV records, at most 5,000 rows and 1 MiB of UTF-8; an optional header may appear in each part. (@path / @- reads a file or stdin verbatim, including trailing newlines; @@value for a literal leading @). |
355355

356356
</CommandTable>
357357

‎apps/docs/content/docs/cli/reference.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4074,7 +4074,7 @@ sim organizations search sources permissions imports put-part <sourceId> <import
40744074
| --- | --- | --- |
40754075
| `--organization <value>` | Yes | Organization identifier. |
40764076
| `--field <value>` | Yes | CSV file this part belongs to. Accepted values: `userMapping`, `projectPermissions`. |
4077-
| `--content <value>` | Yes | Complete CSV records, at most 5,000 rows and 1 MiB of UTF-8; an optional header may appear in each part. |
4077+
| `--content <value\|@file>` | Yes | Complete CSV records, at most 5,000 rows and 1 MiB of UTF-8; an optional header may appear in each part. (@path / @- reads a file or stdin verbatim, including trailing newlines; @@value for a literal leading @). |
40784078

40794079
</CommandTable>
40804080

‎apps/docs/openapi-v2-resources.json‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25028,13 +25028,13 @@
2502825028
"type": "integer",
2502925029
"minimum": 1,
2503025030
"maximum": 4096,
25031-
"description": "Number of parts containing this file."
25031+
"description": "Number of nonempty parts containing this file. Both files together may contain at most 4,096 parts."
2503225032
},
2503325033
"rowCount": {
2503425034
"type": "integer",
2503525035
"minimum": 1,
2503625036
"maximum": 500000,
25037-
"description": "Physical user records, excluding headers and empty lines."
25037+
"description": "Physical user records, excluding headers and empty lines. Must be between parts and parts × 5,000."
2503825038
}
2503925039
},
2504025040
"required": ["filename", "parts", "rowCount"],
@@ -25055,13 +25055,13 @@
2505525055
"type": "integer",
2505625056
"minimum": 1,
2505725057
"maximum": 4096,
25058-
"description": "Number of parts containing this file."
25058+
"description": "Number of nonempty parts containing this file. Both files together may contain at most 4,096 parts."
2505925059
},
2506025060
"rowCount": {
2506125061
"type": "integer",
2506225062
"minimum": 1,
2506325063
"maximum": 5000000,
25064-
"description": "Physical data records, excluding headers and empty lines."
25064+
"description": "Physical data records, excluding headers and empty lines. Must be between parts and parts × 5,000."
2506525065
}
2506625066
},
2506725067
"required": ["filename", "parts", "rowCount"],
@@ -25071,8 +25071,8 @@
2507125071
},
2507225072
"required": ["provider", "expectedRevision", "userMapping", "projectPermissions"],
2507325073
"additionalProperties": false,
25074-
"title": "Create source permission import",
25075-
"description": "Permission import input."
25074+
"description": "Permission import input.",
25075+
"title": "Create source permission import"
2507625076
},
2507725077
"PutSourcePermissionImportResponse": {
2507825078
"type": "object",
@@ -25108,7 +25108,6 @@
2510825108
"content": {
2510925109
"type": "string",
2511025110
"minLength": 1,
25111-
"maxLength": 1048576,
2511225111
"description": "Complete CSV records, at most 5,000 rows and 1 MiB of UTF-8; an optional header may appear in each part."
2511325112
}
2511425113
},

‎apps/docs/public/static/examples/gitlab/export-permissions.py‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,7 @@ def user_rows():
264264
yield user_id, users[user_id]
265265

266266
output.parent.mkdir(parents=True, exist_ok=True)
267+
total_bytes = 0
267268
# Publish the pair together, so an interrupted export cannot mix new and old CSVs.
268269
with tempfile.TemporaryDirectory(dir=output.parent, prefix=".gitlab-export-") as temporary:
269270
for name, header, rows, max_rows in [
@@ -274,20 +275,18 @@ def user_rows():
274275
buffer = io.StringIO(newline="")
275276
writer = csv.writer(buffer, lineterminator="\n")
276277
writer.writerow(header)
277-
size = 0
278278
with path.open("wb") as handle:
279-
handle.write(buffer.getvalue().encode("utf-8"))
280-
size = handle.tell()
279+
total_bytes += handle.write(buffer.getvalue().encode("utf-8"))
281280
for count, row in enumerate(rows, 1):
282281
if count > max_rows:
283282
raise ExportError(f"{name} exceeds Sim's {max_rows:,}-row limit.")
284283
buffer.seek(0)
285284
buffer.truncate()
286285
writer.writerow(row)
287286
content = buffer.getvalue().encode("utf-8")
288-
size += len(content)
289-
if size > MAX_BYTES:
290-
raise ExportError(f"{name} exceeds the CSV byte limit ({MAX_BYTES:,} bytes).")
287+
total_bytes += len(content)
288+
if total_bytes > MAX_BYTES:
289+
raise ExportError(f"The CSV pair exceeds the CSV byte limit ({MAX_BYTES:,} bytes).")
291290
handle.write(content)
292291
path.chmod(0o600)
293292
if not users:

‎apps/docs/public/static/examples/gitlab/upload-permissions.py‎

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
from datetime import datetime, timezone
77
from email.utils import parsedate_to_datetime
88
from http.client import HTTPException
9-
import io
109
import json
1110
import os
1211
from pathlib import Path
@@ -49,16 +48,7 @@ def stage_files(directory, sources):
4948
if (not source.name.strip() or len(source.name) > 255
5049
or any(ord(char) < 32 or ord(char) == 127 or char in "/\\" for char in source.name)):
5150
raise UploadError("Use CSV filenames of 1–255 characters without control characters.")
52-
buffer = io.StringIO(newline="")
53-
writer = csv.writer(buffer, lineterminator="\n", quoting=csv.QUOTE_ALL)
54-
55-
def encode(row):
56-
buffer.seek(0)
57-
buffer.truncate()
58-
writer.writerow(row)
59-
return buffer.getvalue().encode("utf-8")
60-
61-
header_bytes = encode(header)
51+
header_bytes = (",".join(header) + "\n").encode("utf-8")
6252
content = bytearray(header_bytes)
6353
row_count, part_rows, part_count = 0, 0, 0
6454

@@ -81,6 +71,7 @@ def save_part():
8171
before = os.fstat(handle.fileno())
8272
first_record = True
8373
record_characters = 0
74+
record_lines = []
8475

8576
def lines():
8677
nonlocal record_characters
@@ -91,22 +82,27 @@ def lines():
9182
record_characters += len(line)
9283
if record_characters > 8192:
9384
raise UploadError(f"{field}: CSV record exceeds the field length limits.")
85+
record_lines.append(line)
9486
yield line
9587

9688
for row in csv.reader(lines(), strict=True):
9789
record_characters = 0
90+
record = "".join(record_lines)
91+
record_lines.clear()
9892
if not row:
9993
continue
10094
if len(row) != 2:
10195
raise UploadError(f"{field}: every CSV record must have exactly two columns.")
10296
if first_record:
10397
first_record = False
104-
if row == header:
98+
if [cell.strip() for cell in row] == header:
99+
header_bytes = (record if record.endswith(("\n", "\r")) else record + "\n").encode("utf-8")
100+
content = bytearray(header_bytes)
105101
continue
106102
row_count += 1
107103
if row_count > max_rows:
108104
raise UploadError(f"{field}: exceeds {max_rows:,} data records.")
109-
encoded = encode(row)
105+
encoded = (record if record.endswith(("\n", "\r")) else record + "\n").encode("utf-8")
110106
if len(header_bytes) + len(encoded) > PART_BYTES:
111107
raise UploadError(f"{field}: a CSV record exceeds the part size limit.")
112108
if part_rows == PART_ROWS or len(content) + len(encoded) > PART_BYTES:

‎apps/docs/scripts/fixtures/content-baseline.json‎

Lines changed: 59 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6192,6 +6192,27 @@
61926192
"bytes": 69,
61936193
"line": 238
61946194
},
6195+
{
6196+
"lang": "bash",
6197+
"meta": null,
6198+
"sha256": "74d9b766eac6b565c6287e10884f95c2f74ecd8dd4947b488cda0ff1c1f16597",
6199+
"bytes": 80,
6200+
"line": 266
6201+
},
6202+
{
6203+
"lang": "bash",
6204+
"meta": null,
6205+
"sha256": "48441bc81c5893bfd1567acf2a401eb191e4b7bef2862b8c29aa158a517adb82",
6206+
"bytes": 93,
6207+
"line": 300
6208+
},
6209+
{
6210+
"lang": "bash",
6211+
"meta": null,
6212+
"sha256": "4b74edf3d708c0fafd7bb8ba6a827644f65d6cd755a4cf1822b5308a45eb76c3",
6213+
"bytes": 106,
6214+
"line": 330
6215+
},
61956216
{
61966217
"lang": "bash",
61976218
"meta": null,
@@ -11978,6 +11999,41 @@
1197811999
"bytes": 63,
1197912000
"line": 3932
1198012001
},
12002+
{
12003+
"lang": "bash",
12004+
"meta": null,
12005+
"sha256": "48441bc81c5893bfd1567acf2a401eb191e4b7bef2862b8c29aa158a517adb82",
12006+
"bytes": 93,
12007+
"line": 3987
12008+
},
12009+
{
12010+
"lang": "bash",
12011+
"meta": null,
12012+
"sha256": "74d9b766eac6b565c6287e10884f95c2f74ecd8dd4947b488cda0ff1c1f16597",
12013+
"bytes": 80,
12014+
"line": 4019
12015+
},
12016+
{
12017+
"lang": "bash",
12018+
"meta": null,
12019+
"sha256": "4b74edf3d708c0fafd7bb8ba6a827644f65d6cd755a4cf1822b5308a45eb76c3",
12020+
"bytes": 106,
12021+
"line": 4053
12022+
},
12023+
{
12024+
"lang": "bash",
12025+
"meta": null,
12026+
"sha256": "229448ff3c47ffdfdd720fb88b38edcf58f51d063f7b7836d4f4fdc478f99b5c",
12027+
"bytes": 69,
12028+
"line": 4597
12029+
},
12030+
{
12031+
"lang": "bash",
12032+
"meta": null,
12033+
"sha256": "7863a0cbd4e2cb3715358cca55047765a210f9a42a3dd171e42f574185fe0ab9",
12034+
"bytes": 73,
12035+
"line": 4629
12036+
},
1198112037
{
1198212038
"lang": "bash",
1198312039
"meta": null,
@@ -12132,20 +12188,6 @@
1213212188
"bytes": 40,
1213312189
"line": 4568
1213412190
},
12135-
{
12136-
"lang": "bash",
12137-
"meta": null,
12138-
"sha256": "229448ff3c47ffdfdd720fb88b38edcf58f51d063f7b7836d4f4fdc478f99b5c",
12139-
"bytes": 69,
12140-
"line": 4597
12141-
},
12142-
{
12143-
"lang": "bash",
12144-
"meta": null,
12145-
"sha256": "7863a0cbd4e2cb3715358cca55047765a210f9a42a3dd171e42f574185fe0ab9",
12146-
"bytes": 73,
12147-
"line": 4629
12148-
},
1214912191
{
1215012192
"lang": "bash",
1215112193
"meta": null,
@@ -177236,9 +177278,9 @@
177236177278
{
177237177279
"lang": "yaml",
177238177280
"meta": "title=\".gitlab-ci.yml\"",
177239-
"sha256": "95f1b2ec16f400d5e0ebe5cd67ae2b9f6476f2c86696a54f9a983b2b8d02a5c7",
177240-
"bytes": 1613,
177241-
"line": 129
177281+
"sha256": "3f47223510e46a34bef7e0714f39cc3500b6fae9ecd717016b82a65bfc71d185",
177282+
"bytes": 1111,
177283+
"line": 161
177242177284
},
177243177285
{
177244177286
"lang": "bash",

‎apps/docs/scripts/test-gitlab-export-e2e.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,16 @@ def interrupted_grants():
344344
assert expected in str(error), str(error)
345345
assert not output.exists(), "Published an incomplete CSV pair"
346346
report["checks"].append({"name": scenario, "passed": True})
347+
writer_globals["MAX_BYTES"] = 60
348+
output = root / "combined-csv-byte-bound"
349+
try:
350+
exporter["write_export"](output, iter([("a/b", 1)]),
351+
{1: "alice@example.com", 2: "bob@example.com"})
352+
raise AssertionError("Published two individually small CSVs exceeding the combined limit")
353+
except exporter["ExportError"] as error:
354+
assert "CSV byte limit" in str(error), str(error)
355+
assert not output.exists(), "Published an oversized CSV pair"
356+
report["checks"].append({"name": "combined-csv-byte-bound", "passed": True})
347357
assert not any(endpoint == "trap" for _, endpoint, _, _ in GitLabFixture.calls)
348358
report["passed"] = True
349359
finally:

‎apps/docs/scripts/test-permission-upload-e2e.py‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ def handle_request(self):
7676
assert payload["field"] == expected_field
7777
assert len(payload["content"].encode("utf-8")) <= 1024 * 1024
7878
rows = list(csv.reader(io.StringIO(payload["content"], newline=""), strict=True))
79+
if state["scenario"] == "padded-headers":
80+
rows = [[cell.strip() for cell in row] for row in rows]
7981
header = ["user_id", "email"] if expected_field == "userMapping" else ["project_path", "user_id"]
8082
assert rows[0] == header and 1 <= len(rows) - 1 <= 5000
8183
state["parts"][number] = payload
@@ -126,7 +128,7 @@ def run():
126128
thread = threading.Thread(target=server.serve_forever, daemon=True)
127129
thread.start()
128130
try:
129-
for scenario in ("parts", "record-bound", "retry", "validation-error", "conflict", "redirect", "create-unavailable",
131+
for scenario in ("parts", "record-bound", "padded-headers", "retry", "validation-error", "conflict", "redirect", "create-unavailable",
130132
"malformed", "invalid-utf8", "empty", "too-many-users"):
131133
started = time.monotonic()
132134
state = {"scenario": scenario, "requests": [], "creates": 0, "completes": 0,
@@ -151,6 +153,9 @@ def run():
151153
handle.write("user_id,email\n")
152154
for _ in range(500001):
153155
handle.write("1,alice@example.com\n")
156+
elif scenario == "padded-headers":
157+
users.write_text(" user_id , email \n 1 , alice@example.com \n")
158+
grants.write_text(" project_path , user_id \n team/project , 1 \n")
154159
result = subprocess.run([
155160
sys.executable, str(SCRIPT), "--provider", "gitlab", "--expected-revision", "17",
156161
"--user-mapping", str(users), "--project-permissions", str(grants),
@@ -159,17 +164,17 @@ def run():
159164
"SIM_ORG_ID": "org-fixture", "SIM_SOURCE_ID": "source-fixture",
160165
"SIM_API_KEY": TOKEN, "SSL_CERT_FILE": str(cert)})
161166
assert TOKEN not in result.stdout + result.stderr, "API key leaked"
162-
if scenario in ("parts", "record-bound", "retry"):
167+
if scenario in ("parts", "record-bound", "padded-headers", "retry"):
163168
assert result.returncode == 0, result.stderr
164169
assert json.loads(result.stdout)["revision"] == 18
165170
assert state["published"] and state["creates"] == 1
166171
assert state["rows"]["projectPermissions"] == expected
167-
assert state["rows"]["userMapping"] == [["1", "alice@example.com"]] * 2
172+
assert state["rows"]["userMapping"] == [["1", "alice@example.com"]] * (1 if scenario == "padded-headers" else 2)
168173
if scenario == "parts":
169174
assert state["manifest"]["projectPermissions"]["parts"] > 2, "Did not split on UTF-8 bytes"
170175
elif scenario == "record-bound":
171176
assert state["manifest"]["projectPermissions"]["parts"] == 2
172-
else:
177+
elif scenario == "retry":
173178
assert len(state["attempts"][0]) == 2 and len(state["attempts"][1]) == 2
174179
assert state["completes"] == 2
175180
for attempts in state["attempts"].values():

0 commit comments

Comments
 (0)