dq-export-connector 0.1.0.dev9__tar.gz → 0.1.0.dev11__tar.gz

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.
Files changed (33) hide show
  1. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/PKG-INFO +8 -6
  2. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/README.md +5 -4
  3. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/_models/bucket_validation_result.py +1 -2
  4. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/_models/export_report.py +1 -2
  5. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/bucket/datasets.py +29 -4
  6. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/bucket/export.py +18 -3
  7. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/bucket/paths.py +13 -3
  8. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/bucket/store.py +84 -84
  9. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/bucket/upload.py +6 -2
  10. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/errors.py +2 -1
  11. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/runner.py +17 -7
  12. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/pyproject.toml +9 -2
  13. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/tests/test_live_buckets.py +56 -0
  14. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/tests/test_paths.py +6 -0
  15. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/tests/test_runner.py +139 -9
  16. dq_export_connector-0.1.0.dev11/tests/test_store.py +164 -0
  17. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/uv.lock +10 -3
  18. dq_export_connector-0.1.0.dev9/tests/test_store.py +0 -46
  19. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/.gitignore +0 -0
  20. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/.python-version +0 -0
  21. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/__init__.py +0 -0
  22. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/_models/__init__.py +0 -0
  23. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/_models/export_connector_credentials.py +0 -0
  24. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/_models/export_worker_config.py +0 -0
  25. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/bucket/__init__.py +0 -0
  26. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/bucket/validate.py +0 -0
  27. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/log.py +0 -0
  28. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/redact.py +0 -0
  29. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/dq_export_connector/report.py +0 -0
  30. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/scripts/codegen-models.sh +0 -0
  31. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/tests/test_models_are_current.py +0 -0
  32. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/tests/test_redact.py +0 -0
  33. {dq_export_connector-0.1.0.dev9 → dq_export_connector-0.1.0.dev11}/tests/test_upload.py +0 -0
@@ -1,19 +1,20 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: dq-export-connector
3
- Version: 0.1.0.dev9
3
+ Version: 0.1.0.dev11
4
4
  Summary: Worker logic for the Export Connector DCR.
5
5
  Author: Decentriq
6
6
  Requires-Python: >=3.10
7
- Requires-Dist: obstore<0.12,>=0.11.1
8
7
  Requires-Dist: pydantic<2.8,>=2.7
8
+ Provides-Extra: bucket
9
+ Requires-Dist: obstore<0.12,>=0.11.1; extra == 'bucket'
9
10
  Description-Content-Type: text/markdown
10
11
 
11
12
  # dq-export-connector
12
13
 
13
14
  Worker logic for the **Export Connector DCR**: one package for every
14
- Connector Kind, each in its own sub-package. The **bucket** kind uploads each
15
- Input's dataset to S3, Azure Blob or GCS through
16
- [`obstore`](https://developmentseed.org/obstore/).
15
+ Connector Kind, each in its own sub-package with an extra of the same name for
16
+ its dependencies. The **bucket** kind uploads each Input's dataset to S3, Azure
17
+ Blob or GCS through [`obstore`](https://developmentseed.org/obstore/).
17
18
 
18
19
  ddc pins this package by hash in a fully locked `requirements.txt` and runs
19
20
  `dq_export_connector.runner.main` in the task's Python environment. It is
@@ -48,4 +49,5 @@ uv run mypy dq_export_connector tests
48
49
  Bump `version` in `pyproject.toml`, then push a `dq-export-connector-v<version>`
49
50
  tag; the `Publish dq-export-connector to PyPI` workflow tests, builds and uploads
50
51
  it. Use `.devN` versions while developing; PyPI releases can't be replaced.
51
- ddc then pins the new version in a new `export_connector/v0/worker/<version>/`.
52
+ ddc then pins the new version for each kind that should run it, in a new
53
+ `export_connector/v0/worker/<version>/<kind>/`, written by `worker/lock.sh`.
@@ -1,9 +1,9 @@
1
1
  # dq-export-connector
2
2
 
3
3
  Worker logic for the **Export Connector DCR**: one package for every
4
- Connector Kind, each in its own sub-package. The **bucket** kind uploads each
5
- Input's dataset to S3, Azure Blob or GCS through
6
- [`obstore`](https://developmentseed.org/obstore/).
4
+ Connector Kind, each in its own sub-package with an extra of the same name for
5
+ its dependencies. The **bucket** kind uploads each Input's dataset to S3, Azure
6
+ Blob or GCS through [`obstore`](https://developmentseed.org/obstore/).
7
7
 
8
8
  ddc pins this package by hash in a fully locked `requirements.txt` and runs
9
9
  `dq_export_connector.runner.main` in the task's Python environment. It is
@@ -38,4 +38,5 @@ uv run mypy dq_export_connector tests
38
38
  Bump `version` in `pyproject.toml`, then push a `dq-export-connector-v<version>`
39
39
  tag; the `Publish dq-export-connector to PyPI` workflow tests, builds and uploads
40
40
  it. Use `.devN` versions while developing; PyPI releases can't be replaced.
41
- ddc then pins the new version in a new `export_connector/v0/worker/<version>/`.
41
+ ddc then pins the new version for each kind that should run it, in a new
42
+ `export_connector/v0/worker/<version>/<kind>/`, written by `worker/lock.sh`.
@@ -21,8 +21,7 @@ class ExportMessage(BaseModel):
21
21
  message: Annotated[
22
22
  str,
23
23
  Field(
24
- description='Safe to show to the user: no credentials and no dataset values. A\nlonger one is cut, ending in `…`.',
25
- max_length=1000,
24
+ description='Safe to show to the user: no credentials and no dataset values. Writers\ncut it to 1,000 characters, marking the cut with `…`.'
26
25
  ),
27
26
  ]
28
27
 
@@ -61,8 +61,7 @@ class ExportMessage(BaseModel):
61
61
  message: Annotated[
62
62
  str,
63
63
  Field(
64
- description='Safe to show to the user: no credentials and no dataset values. A\nlonger one is cut, ending in `…`.',
65
- max_length=1000,
64
+ description='Safe to show to the user: no credentials and no dataset values. Writers\ncut it to 1,000 characters, marking the cut with `…`.'
66
65
  ),
67
66
  ]
68
67
 
@@ -1,17 +1,21 @@
1
1
  """How an Input's dataset maps to files. A ZIP whose entries are all stored
2
2
  without compression is unpacked, each entry keeping its path. Anything else,
3
- including a ZIP with a compressed entry, is one raw file named `data`."""
3
+ including a ZIP with a compressed or an encrypted entry, is one raw file named
4
+ `data`."""
4
5
 
5
6
  from __future__ import annotations
6
7
 
7
8
  import zipfile
8
9
  from collections.abc import Iterator
9
10
  from contextlib import contextmanager
10
- from dataclasses import dataclass
11
+ from dataclasses import dataclass, field
11
12
  from pathlib import Path
12
13
  from typing import BinaryIO
13
14
 
14
15
  RAW_FILE_NAME = "data"
16
+ # The ZIP general purpose flags of an encrypted entry and of a UTF-8 name.
17
+ _ENCRYPTED = 0x1
18
+ _UTF8_NAME = 0x800
15
19
 
16
20
 
17
21
  @dataclass(frozen=True)
@@ -20,6 +24,7 @@ class DatasetFile:
20
24
 
21
25
  path: str
22
26
  size: int
27
+ zip_entry: zipfile.ZipInfo | None = field(default=None, compare=False)
23
28
 
24
29
 
25
30
  @dataclass(frozen=True)
@@ -46,10 +51,28 @@ def open_dataset(dataset_path: Path) -> Iterator[tuple[Layout, _Reader]]:
46
51
  size = dataset_path.stat().st_size
47
52
  yield Layout([DatasetFile(RAW_FILE_NAME, size)], "a ZIP with compressed entries"), _RawReader(dataset_path)
48
53
  return
49
- files = [DatasetFile(entry.filename, entry.file_size) for entry in entries if not entry.is_dir()]
54
+ if any(entry.flag_bits & _ENCRYPTED for entry in entries):
55
+ size = dataset_path.stat().st_size
56
+ yield Layout([DatasetFile(RAW_FILE_NAME, size)], "a ZIP with encrypted entries"), _RawReader(dataset_path)
57
+ return
58
+ named = [(_name(entry), entry) for entry in entries]
59
+ # An entry is a directory by its name alone, whatever its attributes say.
60
+ files = [DatasetFile(name, entry.file_size, entry) for name, entry in named if not name.endswith("/")]
50
61
  yield Layout(files, None), _ZipReader(archive)
51
62
 
52
63
 
64
+ def _name(entry: zipfile.ZipInfo) -> str:
65
+ """`zipfile` decodes a name without the UTF-8 flag as CP437. Many tools
66
+ write UTF-8 without setting the flag, so such a name is read as UTF-8 when
67
+ it is valid UTF-8."""
68
+ if entry.flag_bits & _UTF8_NAME:
69
+ return entry.filename
70
+ try:
71
+ return entry.filename.encode("cp437").decode("utf-8")
72
+ except UnicodeDecodeError:
73
+ return entry.filename
74
+
75
+
53
76
  class _Reader:
54
77
  def open(self, file: DatasetFile) -> BinaryIO:
55
78
  raise NotImplementedError
@@ -68,4 +91,6 @@ class _ZipReader(_Reader):
68
91
  self._archive = archive
69
92
 
70
93
  def open(self, file: DatasetFile) -> BinaryIO:
71
- return self._archive.open(file.path) # type: ignore[return-value]
94
+ if file.zip_entry is None:
95
+ raise ValueError(f"{file.path!r} isn't an entry of the ZIP")
96
+ return self._archive.open(file.zip_entry) # type: ignore[return-value]
@@ -70,7 +70,9 @@ def export(
70
70
  for bucket_input in connector.inputs:
71
71
  _check_input(bucket_input, connection, export_prefix, inputs_dir, report)
72
72
  for bucket_input, receipt_input in zip(connector.inputs, receipt.inputs):
73
- _export_input(bucket_input, connection, export_prefix, inputs_dir, store, [receipt_input.totals, receipt.totals])
73
+ _export_input(
74
+ bucket_input, connection, export_prefix, inputs_dir, store, [receipt_input.totals, receipt.totals], report
75
+ )
74
76
  logger.info(
75
77
  "Export finished: %d Inputs, %d files, %d bytes",
76
78
  len(receipt.inputs),
@@ -93,9 +95,14 @@ def _check_input(
93
95
  else:
94
96
  logger.info("Input %s is written as one raw file: it is %s", bucket_input.leaf_id, layout.raw_reason)
95
97
  try:
98
+ paths: set[str] = set()
96
99
  for file in layout.files:
97
100
  check_dataset_path(file.path)
98
101
  check_key(_key(connection, export_prefix, destination, file), connection)
102
+ # Two entries of one name would be written to one key.
103
+ if file.path in paths:
104
+ raise InvalidPathError(f"the path '{file.path}' appears more than once")
105
+ paths.add(file.path)
99
106
  except InvalidPathError as error:
100
107
  raise ExportConnectorError(
101
108
  ErrorCode.BUCKET_INVALID_PATH, f"Nothing was exported: in the dataset for '{destination}/', {error}"
@@ -113,6 +120,7 @@ def _export_input(
113
120
  inputs_dir: Path,
114
121
  store: Any,
115
122
  totals: list[ExportTotals],
123
+ report: ReportBuilder,
116
124
  ) -> None:
117
125
  leaf_id = bucket_input.leaf_id
118
126
  destination = bucket_input.destination_directory
@@ -133,6 +141,12 @@ def _export_input(
133
141
  try:
134
142
  upload(store, key, source, plan)
135
143
  except StorageError as error:
144
+ if plan.multipart:
145
+ report.warn(
146
+ ErrorCode.BUCKET_PARTS_MAY_REMAIN,
147
+ f"Parts of the unfinished upload of '{key}' may remain in the {location(connection)}. They"
148
+ " don't show up as files, and a lifecycle rule for incomplete uploads removes them",
149
+ )
136
150
  code = classify_error(error.cause)
137
151
  raise ExportConnectorError(
138
152
  code,
@@ -149,10 +163,11 @@ def _export_input(
149
163
  @contextmanager
150
164
  def _reading(destination: str) -> Iterator[None]:
151
165
  """A stored ZIP that is corrupt raises `BadZipFile`, or `EOFError` for an
152
- entry cut short, when its entry is read."""
166
+ entry cut short, when its entry is read. One that needs a newer ZIP version
167
+ than `zipfile` supports raises `NotImplementedError`."""
153
168
  try:
154
169
  yield
155
- except (OSError, EOFError, zipfile.BadZipFile) as error:
170
+ except (OSError, EOFError, NotImplementedError, zipfile.BadZipFile) as error:
156
171
  raise ExportConnectorError(
157
172
  ErrorCode.READ_FAILED,
158
173
  f"The dataset for '{destination}/' couldn't be read: {str(error) or type(error).__name__}",
@@ -19,6 +19,7 @@ AZURE_MAX_KEY_CHARACTERS = 1024
19
19
  AZURE_MAX_KEY_SEGMENTS = 254
20
20
 
21
21
  _RESERVED_GCS_PREFIX = ".well-known/acme-challenge/"
22
+ _QUOTED_KEY_END = 200
22
23
 
23
24
 
24
25
  class InvalidPathError(ValueError):
@@ -64,12 +65,21 @@ def check_key(key: str, connection: BucketConnection1 | BucketConnection2 | Buck
64
65
  match connection:
65
66
  case BucketConnection1() | BucketConnection3():
66
67
  if len(key.encode("utf-8")) > PROVIDER_MAX_KEY_BYTES:
67
- raise InvalidPathError(f"the object key {key!r} is longer than {PROVIDER_MAX_KEY_BYTES} bytes")
68
+ raise InvalidPathError(f"an object key is longer than {PROVIDER_MAX_KEY_BYTES} bytes: {_shortened(key)!r}")
68
69
  case BucketConnection2():
69
70
  if len(key) > AZURE_MAX_KEY_CHARACTERS:
70
- raise InvalidPathError(f"the object key {key!r} is longer than {AZURE_MAX_KEY_CHARACTERS} characters")
71
+ raise InvalidPathError(
72
+ f"an object key is longer than {AZURE_MAX_KEY_CHARACTERS} characters: {_shortened(key)!r}"
73
+ )
71
74
  if key.count("/") + 1 > AZURE_MAX_KEY_SEGMENTS:
72
- raise InvalidPathError(f"the object key {key!r} has more than {AZURE_MAX_KEY_SEGMENTS} segments")
75
+ raise InvalidPathError(
76
+ f"an object key has more than {AZURE_MAX_KEY_SEGMENTS} segments: {_shortened(key)!r}"
77
+ )
78
+
79
+
80
+ def _shortened(key: str) -> str:
81
+ """Both ends of a key too long to quote whole in a report message."""
82
+ return key if len(key) <= 2 * _QUOTED_KEY_END else f"{key[:_QUOTED_KEY_END]}…{key[-_QUOTED_KEY_END:]}"
73
83
 
74
84
 
75
85
  def _is_control(character: str) -> bool:
@@ -3,6 +3,7 @@ failures map to."""
3
3
 
4
4
  from __future__ import annotations
5
5
 
6
+ import re
6
7
  from collections.abc import Callable
7
8
  from datetime import timedelta
8
9
  from typing import TYPE_CHECKING, Any, TypeVar
@@ -24,6 +25,7 @@ from dq_export_connector._models.export_worker_config import (
24
25
  )
25
26
 
26
27
  from dq_export_connector.errors import ErrorCode, ExportConnectorError
28
+ from dq_export_connector.redact import MASK
27
29
 
28
30
  if TYPE_CHECKING:
29
31
  from obstore.store import ClientConfig, RetryConfig
@@ -46,21 +48,36 @@ RETRY_CONFIG: RetryConfig = {
46
48
  }
47
49
 
48
50
  # object_store's whole-request `timeout` (30s by default) would abort any part
49
- # upload that takes longer, so it is pushed out of reach; `read_timeout` resets
50
- # on every read and is what detects a stalled connection.
51
+ # upload that takes longer, so it is pushed out of reach, and `read_timeout`
52
+ # is what detects a stalled connection. For an upload it runs while the part
53
+ # is sent, so it has to cover a whole part, and parts grow with the file: at
54
+ # 60s, a part of a very large file would time out on a healthy connection.
51
55
  CLIENT_CONFIG: ClientConfig = {
52
56
  "connect_timeout": timedelta(seconds=30),
53
57
  "timeout": _NEVER_IN_PRACTICE,
54
- "read_timeout": timedelta(seconds=60),
58
+ "read_timeout": timedelta(minutes=10),
55
59
  }
56
60
 
57
61
  T = TypeVar("T")
58
62
 
59
63
 
64
+ _HTTP_ERROR = re.compile(r"HttpError \{\s*kind: (?P<kind>\w+),\s*source: reqwest::Error \{(?P<source>.*)", re.DOTALL)
65
+ _STRING_LITERAL = re.compile(r'"((?:[^"\\]|\\.)*)"')
66
+
67
+
60
68
  def describe(error: Exception) -> str:
61
- """obstore's message without the `Debug source:` dump it appends, which
62
- repeats the error."""
63
- return str(error).split("\n\nDebug source:", 1)[0]
69
+ """obstore's message without the `Debug source:` dump it appends. For a
70
+ request that couldn't be sent, the message stops at "error sending
71
+ request", so the causes the dump holds, such as a DNS failure or a refused
72
+ connection, are appended."""
73
+ message, _, dump = str(error).partition("\n\nDebug source:")
74
+ http_error = _HTTP_ERROR.search(dump)
75
+ if http_error is None:
76
+ return message
77
+ causes = _STRING_LITERAL.findall(http_error["source"])
78
+ if http_error["kind"] == "Timeout":
79
+ causes.append("timed out")
80
+ return ": ".join([message, *causes])
64
81
 
65
82
 
66
83
  class StorageError(Exception):
@@ -86,91 +103,40 @@ def storage_call(call: Callable[[], T]) -> T:
86
103
  raise StorageError(error) from error
87
104
 
88
105
 
89
- # Provider error codes that mean bad credentials. They are checked before the
90
- # error's type: S3's SignatureDoesNotMatch and InvalidAccessKeyId arrive as a
91
- # 403, which object_store raises as permission denied.
92
- _CREDENTIAL_CODES: tuple[str, ...] = (
93
- # S3
94
- "SignatureDoesNotMatch",
95
- "InvalidAccessKeyId",
96
- "InvalidSecurityToken",
97
- "ExpiredToken",
98
- # Azure
99
- "AuthenticationFailed",
100
- # GCS
101
- "invalid_grant",
102
- "Invalid JWT",
103
- )
106
+ # S3 and Azure answer a credential they reject with a 403, which obstore
107
+ # raises as permission denied, so the code in the response body is what tells
108
+ # it from a missing permission. Azure also answers this way for a container
109
+ # that doesn't exist.
110
+ _REJECTED_CREDENTIAL_CODES = frozenset({"SignatureDoesNotMatch", "InvalidAccessKeyId", "AuthenticationFailed"})
111
+
112
+ # The response follows this in obstore's message. The object key comes before
113
+ # it, so nothing in a key can pass for a provider's code.
114
+ _RESPONSE_START = " - Server returned non-2xx status code: "
115
+ _RESPONSE_CODE = re.compile(r"<Code>(\w+)</Code>")
104
116
 
105
- # Provider error codes recognised in an error's message, checked in order.
106
- # object_store wraps many non-2xx responses in a generic error, so the
107
- # provider's code in the message is often the only signal.
108
- _MESSAGE_CLASSIFIERS: list[tuple[ErrorCode, tuple[str, ...]]] = [
109
- (
110
- ErrorCode.UNAUTHENTICATED,
111
- (
112
- # S3
113
- "SignatureDoesNotMatch",
114
- "InvalidAccessKeyId",
115
- "InvalidSecurityToken",
116
- "ExpiredToken",
117
- # Azure
118
- "AuthenticationFailed",
119
- # GCS
120
- "invalid_grant",
121
- "Invalid JWT",
122
- "status code: 401",
123
- ),
124
- ),
125
- (
126
- ErrorCode.ACCESS_DENIED,
127
- (
128
- "AccessDenied", # S3
129
- "AuthorizationFailure", # Azure
130
- "AuthorizationPermissionMismatch", # Azure
131
- "PERMISSION_DENIED", # GCS
132
- "status code: 403",
133
- ),
134
- ),
135
- (
136
- ErrorCode.DESTINATION_NOT_FOUND,
137
- (
138
- "NoSuchBucket", # S3
139
- # S3, for a bucket in another region than the connection's
140
- "PermanentRedirect",
141
- "incorrectly configured region",
142
- "ContainerNotFound", # Azure
143
- "bucket does not exist", # GCS
144
- "status code: 404",
145
- ),
146
- ),
147
- (
148
- ErrorCode.UNREACHABLE,
149
- (
150
- "error sending request",
151
- "dns error",
152
- "Connection refused",
153
- "connection refused",
154
- "operation timed out",
155
- ),
156
- ),
157
- ]
117
+ # How object_store reports S3's redirect for a bucket in another region than
118
+ # the connection's.
119
+ _OTHER_REGION = "this normally indicates an incorrectly configured region"
158
120
 
159
121
 
160
122
  def classify_error(error: Exception) -> ErrorCode:
161
- """Maps a storage error to a code, the same for every Bucket Provider."""
162
- message = str(error)
163
- if any(code in message for code in _CREDENTIAL_CODES):
164
- return ErrorCode.UNAUTHENTICATED
123
+ """Maps a storage error to a code, the same for every Bucket Provider. Each
124
+ rule is one a real provider's response was seen to need."""
165
125
  if isinstance(error, obstore.exceptions.UnauthenticatedError):
166
126
  return ErrorCode.UNAUTHENTICATED
167
127
  if isinstance(error, obstore.exceptions.PermissionDeniedError):
128
+ response_code = _RESPONSE_CODE.search(str(error).rpartition(_RESPONSE_START)[2])
129
+ if response_code is not None and response_code[1] in _REJECTED_CREDENTIAL_CODES:
130
+ return ErrorCode.UNAUTHENTICATED
168
131
  return ErrorCode.ACCESS_DENIED
169
132
  if isinstance(error, FileNotFoundError):
170
133
  return ErrorCode.DESTINATION_NOT_FOUND
171
- for code, needles in _MESSAGE_CLASSIFIERS:
172
- if any(needle in message for needle in needles):
173
- return code
134
+ message, _, dump = str(error).partition("\n\nDebug source:")
135
+ if message.endswith(_OTHER_REGION):
136
+ return ErrorCode.DESTINATION_NOT_FOUND
137
+ # The request got no response: it couldn't connect, timed out or was cut off.
138
+ if _HTTP_ERROR.search(dump) is not None:
139
+ return ErrorCode.UNREACHABLE
174
140
  return ErrorCode.UNKNOWN
175
141
 
176
142
 
@@ -199,14 +165,37 @@ def failure_sentence(code: ErrorCode, where: str) -> str:
199
165
  return f"The {where} returned an error"
200
166
 
201
167
 
168
+ # How obstore's errors for credentials it can't parse begin. S3's keys are only
169
+ # checked by a request.
170
+ _CREDENTIAL_PARSE_ERRORS = (
171
+ "Generic MicrosoftAzure error: Missing component in SAS query pair",
172
+ "Generic MicrosoftAzure error: Failed parsing an SAS key",
173
+ "Generic GCS error: GCP credential error:",
174
+ "Generic AwsLcCryptoProvider error: Error reading pem file",
175
+ "Generic AwsLcCryptoProvider error: Invalid RSA key",
176
+ )
177
+
178
+ # A value serde rejects, echoed in quotes or backticks with Rust's escaping,
179
+ # which the redactor's variants don't always match. Backticked identifiers are
180
+ # field names and stay.
181
+ _ECHOED_VALUE = re.compile(r'"(?:[^"\\]|\\.)*"|`(?![A-Za-z_][A-Za-z0-9_]*`)[^`]*`')
182
+
183
+
202
184
  def build_store(connection: BucketConnection, credentials: BucketCredentials) -> Any:
203
185
  """obstore parses the credentials here, so a malformed GCS key or Azure SAS
204
- token fails before any request."""
186
+ token fails before any request, as does an address no URL can hold, such as
187
+ an Azure account name with a space."""
205
188
  try:
206
189
  return _store(connection, credentials)
207
190
  except obstore.exceptions.BaseError as error:
191
+ message = describe(error)
192
+ if message.startswith(_CREDENTIAL_PARSE_ERRORS):
193
+ without_values = _ECHOED_VALUE.sub(lambda value: f"{value[0][0]}{MASK}{value[0][-1]}", message)
194
+ raise ExportConnectorError(
195
+ ErrorCode.INVALID_CREDENTIALS, f"The credentials couldn't be read: {without_values}"
196
+ ) from error
208
197
  raise ExportConnectorError(
209
- ErrorCode.INVALID_CREDENTIALS, f"The credentials couldn't be read: {describe(error)}"
198
+ ErrorCode.UNREACHABLE, f"{failure_sentence(ErrorCode.UNREACHABLE, location(connection.root))}: {message}"
210
199
  ) from error
211
200
 
212
201
 
@@ -217,7 +206,7 @@ def _store(connection: BucketConnection, credentials: BucketCredentials) -> Any:
217
206
  return S3Store(
218
207
  bucket=s3.bucket,
219
208
  region=s3.region,
220
- access_key_id=s3_credentials.s3.access_key,
209
+ access_key_id=_checked_s3_access_key(s3_credentials.s3.access_key),
221
210
  secret_access_key=s3_credentials.s3.secret_key,
222
211
  retry_config=RETRY_CONFIG,
223
212
  client_options=CLIENT_CONFIG,
@@ -240,6 +229,17 @@ def _store(connection: BucketConnection, credentials: BucketCredentials) -> Any:
240
229
  raise ValueError(f"Credentials for {type(credentials.root).__name__} don't match {type(connection.root).__name__}")
241
230
 
242
231
 
232
+ def _checked_s3_access_key(access_key: str) -> str:
233
+ """The access key is sent in a header, and object_store panics on one no
234
+ header can hold."""
235
+ if not access_key.isprintable() or " " in access_key:
236
+ raise ExportConnectorError(
237
+ ErrorCode.INVALID_CREDENTIALS,
238
+ "The S3 access key in the credentials contains whitespace or a control character",
239
+ )
240
+ return access_key
241
+
242
+
243
243
  def _normalize_azure_sas_token(sas_token: str) -> str:
244
244
  """The portal's "Blob SAS token" includes a leading `?`. A SAS URL is
245
245
  rejected rather than parsed: its account and container would be ignored,
@@ -2,8 +2,12 @@
2
2
 
3
3
  S3 and GCS allow at most 10,000 parts per upload (Azure 50,000 blocks), so the
4
4
  part size grows with the file: at the 8 MiB default of the AWS SDKs and CLI, a
5
- file larger than about 78 GiB would run out of parts. obstore aborts a
6
- multipart upload that fails.
5
+ file larger than about 78 GiB would run out of parts.
6
+
7
+ obstore aborts a multipart upload that fails while the source is still being
8
+ read. It sends no abort when a part fails once the source is exhausted, and it
9
+ exposes no call to abort one, so the parts of such an upload stay at the
10
+ destination until its lifecycle rules remove them.
7
11
  """
8
12
 
9
13
  from __future__ import annotations
@@ -21,6 +21,7 @@ class ErrorCode(str, Enum):
21
21
  # Warnings
22
22
  EMPTY_DATASET = "EMPTY_DATASET"
23
23
  BUCKET_PROBE_NOT_DELETED = "BUCKET_PROBE_NOT_DELETED"
24
+ BUCKET_PARTS_MAY_REMAIN = "BUCKET_PARTS_MAY_REMAIN"
24
25
 
25
26
 
26
27
  # ddc's limit on a report message, in characters.
@@ -41,7 +42,7 @@ class ExportConnectorError(Exception):
41
42
  self.message = message
42
43
 
43
44
 
44
- def internal_error_message(error: Exception, activity: str) -> str:
45
+ def internal_error_message(error: BaseException, activity: str) -> str:
45
46
  """Names the error's type and where it was raised, but not its message,
46
47
  which could hold dataset values."""
47
48
  error_type = type(error)
@@ -18,9 +18,6 @@ from dq_export_connector._models.export_worker_config import (
18
18
  ExportConnectorDcrComputeAction2,
19
19
  ExportWorkerConfig,
20
20
  )
21
- from dq_export_connector.bucket import store
22
- from dq_export_connector.bucket.export import export
23
- from dq_export_connector.bucket.validate import validate_connection
24
21
  from dq_export_connector.errors import ErrorCode, ExportConnectorError, internal_error_message
25
22
  from dq_export_connector.log import configure, logger
26
23
  from dq_export_connector.redact import Redactor, sealed_values
@@ -45,7 +42,7 @@ def main(
45
42
  credentials_path: Path = CREDENTIALS_PATH,
46
43
  inputs_dir: Path = INPUTS_DIR,
47
44
  output_dir: Path = OUTPUT_DIR,
48
- build_store: Callable[[Any, Any], Any] = store.build_store,
45
+ build_store: Callable[[Any, Any], Any] | None = None,
49
46
  ) -> None:
50
47
  credentials_json = json.loads(credentials_path.read_text())
51
48
  redactor = Redactor(sealed_values(credentials_json))
@@ -59,7 +56,10 @@ def main(
59
56
  build_store,
60
57
  redactor,
61
58
  )
62
- except Exception:
59
+ except (KeyboardInterrupt, SystemExit):
60
+ raise
61
+ # A panic in obstore's Rust code is a `BaseException`.
62
+ except BaseException:
63
63
  logger.exception("The export worker failed")
64
64
  raise WorkerFailed("The export worker failed; its redacted error is in the platform logs") from None
65
65
 
@@ -69,9 +69,16 @@ def run(
69
69
  credentials: ExportConnectorCredentials,
70
70
  inputs_dir: Path,
71
71
  output_dir: Path,
72
- build_store: Callable[[Any, Any], Any],
72
+ build_store: Callable[[Any, Any], Any] | None,
73
73
  redactor: Redactor,
74
74
  ) -> None:
75
+ # A kind's modules import what its extra installs, so they load only for
76
+ # a run of that kind.
77
+ from dq_export_connector.bucket import store
78
+ from dq_export_connector.bucket.export import export
79
+ from dq_export_connector.bucket.validate import validate_connection
80
+
81
+ build_store = build_store or store.build_store
75
82
  logger.info("dq-export-connector %s", version("dq-export-connector"))
76
83
  connector = config.connector.root
77
84
  bucket_credentials = credentials.root.bucket
@@ -100,10 +107,13 @@ def _reporting(report: ReportBuilder, activity: str, action: Callable[[], None])
100
107
  did before it."""
101
108
  try:
102
109
  action()
110
+ except (KeyboardInterrupt, SystemExit):
111
+ raise
103
112
  except ExportConnectorError as error:
104
113
  logger.error("The %s failed with %s: %s", activity, error.code.value, error.message)
105
114
  report.fail(error.code, error.message)
106
- except Exception as error:
115
+ # A panic in obstore's Rust code is a `BaseException`.
116
+ except BaseException as error:
107
117
  logger.exception("An internal error stopped the %s", activity)
108
118
  report.fail(ErrorCode.INTERNAL_ERROR, internal_error_message(error, activity))
109
119
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dq-export-connector"
3
- version = "0.1.0.dev9"
3
+ version = "0.1.0.dev11"
4
4
  description = "Worker logic for the Export Connector DCR."
5
5
  readme = "README.md"
6
6
  authors = [{ name = "Decentriq" }]
@@ -10,12 +10,19 @@ requires-python = ">=3.10"
10
10
  # locked one. pydantic stays at the version dq_validation runs in that image;
11
11
  # newer ones need a newer typing_extensions.
12
12
  dependencies = [
13
- "obstore>=0.11.1,<0.12",
14
13
  "pydantic>=2.7,<2.8",
15
14
  ]
16
15
 
16
+ # One extra per Connector Kind, holding what only that kind needs: ddc locks
17
+ # `dq-export-connector[<kind>]`, so a run installs no other kind's packages.
18
+ [project.optional-dependencies]
19
+ bucket = [
20
+ "obstore>=0.11.1,<0.12",
21
+ ]
22
+
17
23
  [dependency-groups]
18
24
  dev = [
25
+ "dq-export-connector[bucket]",
19
26
  "mypy>=1.13",
20
27
  "pytest>=8.3",
21
28
  ]
@@ -132,3 +132,59 @@ def test_an_export_lands_in_the_bucket(tmp_path: Path, provider: tuple[dict[str,
132
132
  None,
133
133
  {f"{prefix}/zipped/dir with space/part #1.csv": b"a,b\n", f"{prefix}/raw/data": b"raw bytes"},
134
134
  )
135
+
136
+
137
+ def _write_error_code(tmp_path: Path, name: str, connection: dict[str, Any], credentials: dict[str, Any]) -> Any:
138
+ output = _main(tmp_path / name, VALIDATE, connection, credentials, {})
139
+ return json.loads((output / runner.VALIDATION_RESULT_FILE).read_text())["error"]["code"]
140
+
141
+
142
+ def test_s3_failures_are_classified(tmp_path: Path) -> None:
143
+ connection, credentials = _s3("dq-export-connector-live-tests")
144
+ keys = credentials["bucket"]["s3"]
145
+ cases = {
146
+ "secret": (connection, {"bucket": {"s3": {**keys, "secretKey": "x" * 40}}}),
147
+ "access": (connection, {"bucket": {"s3": {**keys, "accessKey": "AKIAAAAAAAAAAAAAAAAA"}}}),
148
+ "bucket": ({**connection, "bucket": f"dq-no-such-bucket-{uuid.uuid4().hex}"}, credentials),
149
+ "region": ({**connection, "region": "eu-central-1"}, credentials),
150
+ }
151
+ for name in cases:
152
+ (tmp_path / name).mkdir()
153
+ assert {name: _write_error_code(tmp_path, name, *case) for name, case in cases.items()} == {
154
+ "secret": "UNAUTHENTICATED",
155
+ "access": "UNAUTHENTICATED",
156
+ "bucket": "DESTINATION_NOT_FOUND",
157
+ "region": "DESTINATION_NOT_FOUND",
158
+ }
159
+
160
+
161
+ def test_azure_failures_are_classified(tmp_path: Path) -> None:
162
+ connection, credentials = _azure("dq-export-connector-live-tests")
163
+ token = credentials["bucket"]["azureBlob"]["sasToken"]
164
+ signature = token[token.index("sig=") :].split("&")[0]
165
+ cases = {
166
+ "signature": (connection, {"bucket": {"azureBlob": {"sasToken": token.replace(signature, "sig=AAAA")}}}),
167
+ "container": ({**connection, "container": f"no-such-{uuid.uuid4().hex[:12]}"}, credentials),
168
+ }
169
+ for name in cases:
170
+ (tmp_path / name).mkdir()
171
+ assert {name: _write_error_code(tmp_path, name, *case) for name, case in cases.items()} == {
172
+ "signature": "UNAUTHENTICATED",
173
+ "container": "UNAUTHENTICATED",
174
+ }
175
+
176
+
177
+ def test_gcs_failures_are_classified(tmp_path: Path) -> None:
178
+ connection, credentials = _gcs("dq-export-connector-live-tests")
179
+ account = json.loads(credentials["bucket"]["gcs"]["serviceAccountJson"])
180
+ unknown = {**account, "client_email": "nobody@" + account["client_email"].split("@")[1]}
181
+ cases = {
182
+ "account": (connection, {"bucket": {"gcs": {"serviceAccountJson": json.dumps(unknown)}}}),
183
+ "bucket": ({**connection, "bucket": f"dq-no-such-bucket-{uuid.uuid4().hex}"}, credentials),
184
+ }
185
+ for name in cases:
186
+ (tmp_path / name).mkdir()
187
+ assert {name: _write_error_code(tmp_path, name, *case) for name, case in cases.items()} == {
188
+ "account": "UNAUTHENTICATED",
189
+ "bucket": "DESTINATION_NOT_FOUND",
190
+ }
@@ -48,6 +48,12 @@ def test_key_limits_follow_the_provider():
48
48
  ]] == [True, False, False, True, True, False]
49
49
 
50
50
 
51
+ def test_a_key_that_is_too_long_is_quoted_by_its_ends_after_the_reason():
52
+ with pytest.raises(InvalidPathError) as raised:
53
+ check_key("a" * 600 + "b" * 600, S3)
54
+ assert str(raised.value) == f"an object key is longer than 1024 bytes: '{'a' * 200}…{'b' * 200}'"
55
+
56
+
51
57
  def test_the_gcs_reserved_prefix_is_rejected_for_every_provider():
52
58
  assert [_accepted(".well-known/acme-challenge/x", connection) for connection in [S3, AZURE, GCS]] == [False] * 3
53
59
 
@@ -5,6 +5,7 @@ import io
5
5
  import json
6
6
  import os
7
7
  import re
8
+ import warnings
8
9
  import zipfile
9
10
  from pathlib import Path
10
11
 
@@ -15,6 +16,7 @@ from obstore.store import LocalStore, MemoryStore
15
16
  from dq_export_connector import runner
16
17
  from dq_export_connector.bucket import export
17
18
  from dq_export_connector.bucket.store import StorageError
19
+ from dq_export_connector.bucket.upload import MIN_PART_SIZE
18
20
  from dq_export_connector.errors import MAX_MESSAGE_LENGTH
19
21
 
20
22
  SECRET_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
@@ -102,25 +104,59 @@ def test_stored_zips_are_unpacked_and_other_datasets_written_raw(tmp_path, monke
102
104
  "segA": _zip({"part-0.csv": b"a,b\n", "sub/": b"", "sub/part-1.csv": b"c,d\n"}),
103
105
  "segB": b"raw bytes",
104
106
  "segC": _zip({"x.csv": b"compressed"}, compression=zipfile.ZIP_DEFLATED),
107
+ "segD": _encrypted(_zip({"y.csv": b"encrypted"})),
105
108
  }
106
- config = _config(EXPORT, [("segA", "seg_a"), ("segB", "seg_b"), ("segC", "seg_c")])
109
+ config = _config(EXPORT, [("segA", "seg_a"), ("segB", "seg_b"), ("segC", "seg_c"), ("segD", "seg_d")])
107
110
  _run(tmp_path, config, datasets, store, monkeypatch)
108
111
  seg_c_size = len(datasets["segC"])
112
+ seg_d_size = len(datasets["segD"])
109
113
  assert (_objects(store), _report(tmp_path)) == (
110
114
  {
111
115
  "decentriq/seg_a/part-0.csv": b"a,b\n",
112
116
  "decentriq/seg_a/sub/part-1.csv": b"c,d\n",
113
117
  "decentriq/seg_b/data": b"raw bytes",
114
118
  "decentriq/seg_c/data": datasets["segC"],
119
+ "decentriq/seg_d/data": datasets["segD"],
115
120
  },
116
121
  {
117
122
  "version": "V0",
118
123
  "warnings": [],
119
- "receipt": _receipt([("segA", "seg_a", 2, 8), ("segB", "seg_b", 1, 9), ("segC", "seg_c", 1, seg_c_size)]),
124
+ "receipt": _receipt(
125
+ [
126
+ ("segA", "seg_a", 2, 8),
127
+ ("segB", "seg_b", 1, 9),
128
+ ("segC", "seg_c", 1, seg_c_size),
129
+ ("segD", "seg_d", 1, seg_d_size),
130
+ ]
131
+ ),
120
132
  },
121
133
  )
122
134
 
123
135
 
136
+ def test_names_and_directories_are_read_as_the_dataset_preview_reads_them(tmp_path, monkeypatch):
137
+ buffer = io.BytesIO()
138
+ with zipfile.ZipFile(buffer, "w") as archive:
139
+ archive.writestr("über.csv", b"utf-8")
140
+ archive.writestr("cafX.csv", b"cp437")
141
+ flagged_as_directory = zipfile.ZipInfo("report.csv")
142
+ flagged_as_directory.external_attr = 0x10
143
+ archive.writestr(flagged_as_directory, b"content")
144
+ dataset = bytearray(buffer.getvalue().replace(b"cafX.csv", b"caf\x82.csv"))
145
+ # Clears the UTF-8 flag of the first entry in its local and its central header.
146
+ for signature, flags_offset in ((b"PK\x03\x04", 7), (b"PK\x01\x02", 9)):
147
+ dataset[dataset.index(signature) + flags_offset] &= ~0x08
148
+ store = MemoryStore()
149
+ _run(tmp_path, _config(EXPORT, [("segA", "seg_a")]), {"segA": bytes(dataset)}, store, monkeypatch)
150
+ assert (_objects(store), _report(tmp_path)["receipt"]) == (
151
+ {
152
+ "decentriq/seg_a/über.csv": b"utf-8",
153
+ "decentriq/seg_a/café.csv": b"cp437",
154
+ "decentriq/seg_a/report.csv": b"content",
155
+ },
156
+ _receipt([("segA", "seg_a", 3, 17)]),
157
+ )
158
+
159
+
124
160
  def test_a_bad_path_fails_the_run_before_anything_is_written(tmp_path, monkeypatch):
125
161
  store = MemoryStore()
126
162
  datasets = {"good": b"3", "empty": _zip({}), "bad": _zip({"ok.csv": b"1", "../escape.csv": b"2"})}
@@ -145,12 +181,34 @@ def test_a_bad_path_fails_the_run_before_anything_is_written(tmp_path, monkeypat
145
181
  )
146
182
 
147
183
 
184
+ def test_a_zip_with_one_name_twice_fails_the_run_before_anything_is_written(tmp_path, monkeypatch):
185
+ store = MemoryStore()
186
+ buffer = io.BytesIO()
187
+ with zipfile.ZipFile(buffer, "w") as archive, warnings.catch_warnings():
188
+ warnings.simplefilter("ignore", UserWarning)
189
+ archive.writestr("x.csv", b"1")
190
+ archive.writestr("x.csv", b"22")
191
+ _run(tmp_path, _config(EXPORT, [("twice", "twice")]), {"twice": buffer.getvalue()}, store, monkeypatch)
192
+ assert (_objects(store), _report(tmp_path)) == (
193
+ {},
194
+ {
195
+ "version": "V0",
196
+ "error": {
197
+ "code": "BUCKET_INVALID_PATH",
198
+ "message": "Nothing was exported: in the dataset for 'twice/', the path 'x.csv' appears more than once",
199
+ },
200
+ "warnings": [],
201
+ "receipt": _receipt([("twice", "twice", 0, 0)]),
202
+ },
203
+ )
204
+
205
+
148
206
  def test_a_failed_input_stops_the_run_and_keeps_what_was_written(tmp_path, monkeypatch):
149
207
  upload = export.upload
150
208
 
151
209
  def denied_for_seg_b(store, key, source, plan):
152
210
  if "/seg_b/" in key:
153
- raise StorageError(RuntimeError("AccessDenied: Access Denied"))
211
+ raise StorageError(obstore.exceptions.PermissionDeniedError("Access Denied"))
154
212
  upload(store, key, source, plan)
155
213
 
156
214
  monkeypatch.setattr(export, "upload", denied_for_seg_b)
@@ -164,7 +222,7 @@ def test_a_failed_input_stops_the_run_and_keeps_what_was_written(tmp_path, monke
164
222
  "error": {
165
223
  "code": "ACCESS_DENIED",
166
224
  "message": "The credentials may not write to the bucket 'acme' in eu-central-1, so writing"
167
- " 'decentriq/seg_b/data' failed after 0 of 1 files for 'seg_b/': AccessDenied: Access Denied",
225
+ " 'decentriq/seg_b/data' failed after 0 of 1 files for 'seg_b/': Access Denied",
168
226
  },
169
227
  "warnings": [],
170
228
  "receipt": _receipt([("segA", "seg_a", 1, 1), ("segB", "seg_b", 0, 0), ("segC", "seg_c", 0, 0)]),
@@ -172,17 +230,51 @@ def test_a_failed_input_stops_the_run_and_keeps_what_was_written(tmp_path, monke
172
230
  )
173
231
 
174
232
 
233
+ def test_a_failed_multipart_upload_warns_that_its_parts_may_remain(tmp_path, monkeypatch):
234
+ def failing(*_):
235
+ raise StorageError(RuntimeError("AccessDenied: Access Denied"))
236
+
237
+ monkeypatch.setattr(export, "upload", failing)
238
+ dataset = bytes(MIN_PART_SIZE + 1)
239
+ _run(tmp_path, _config(EXPORT, [("segA", "seg_a")]), {"segA": dataset}, MemoryStore(), monkeypatch)
240
+ assert _report(tmp_path)["warnings"] == [
241
+ {
242
+ "code": "BUCKET_PARTS_MAY_REMAIN",
243
+ "message": "Parts of the unfinished upload of 'decentriq/seg_a/data' may remain in the bucket 'acme' in"
244
+ " eu-central-1. They don't show up as files, and a lifecycle rule for incomplete uploads removes them",
245
+ }
246
+ ]
247
+
248
+
249
+ def _encrypted(data):
250
+ """Sets the encryption flag in the local and the central header."""
251
+ data = bytearray(data)
252
+ for signature, flags_offset in ((b"PK\x03\x04", 6), (b"PK\x01\x02", 8)):
253
+ data[data.index(signature) + flags_offset] |= 0x1
254
+ return bytes(data)
255
+
256
+
257
+ def _needing_version_25_5(data):
258
+ """Sets the version needed to extract in the central header."""
259
+ data = bytearray(data)
260
+ data[data.index(b"PK\x01\x02") + 6] = 0xFF
261
+ return bytes(data)
262
+
263
+
175
264
  @pytest.mark.parametrize(
176
- ("corrupt", "reason"),
265
+ ("entries", "corrupt", "reason"),
177
266
  [
178
- (lambda data: data.replace(b"hello world", b"hellO world"), "Bad CRC-32 for file 'a.csv'"),
179
- (lambda data: data.replace(b"PK\x03\x04", b"PK\x00\x00", 1), "Bad magic number for file header"),
267
+ ({"a.csv": b"hello world"}, lambda data: data.replace(b"hello world", b"hellO world"), "Bad CRC-32 for file 'a.csv'"),
268
+ ({"a.csv": b"hello world"}, lambda data: data.replace(b"PK\x03\x04", b"PK\x00\x00", 1), "Bad magic number for file header"),
269
+ ({"a.csv": b"hello world"}, _needing_version_25_5, "zip file version 25.5"),
270
+ # Over 8 MiB, so the entry is read inside obstore's multipart upload.
271
+ ({"big.csv": b"x" * 8 * 1024 * 1024 + b"y"}, lambda data: data.replace(b"xy", b"xz"), "Bad CRC-32 for file 'big.csv'"),
180
272
  ],
181
273
  )
182
- def test_a_corrupt_stored_zip_is_unreadable(tmp_path, monkeypatch, corrupt, reason):
274
+ def test_a_corrupt_stored_zip_is_unreadable(tmp_path, monkeypatch, entries, corrupt, reason):
183
275
  store = MemoryStore()
184
276
  config = _config(EXPORT, [("segA", "seg_a")])
185
- _run(tmp_path, config, {"segA": corrupt(_zip({"a.csv": b"hello world"}))}, store, monkeypatch)
277
+ _run(tmp_path, config, {"segA": corrupt(_zip(entries))}, store, monkeypatch)
186
278
  assert (_objects(store), _report(tmp_path)) == (
187
279
  {},
188
280
  {
@@ -194,6 +286,21 @@ def test_a_corrupt_stored_zip_is_unreadable(tmp_path, monkeypatch, corrupt, reas
194
286
  )
195
287
 
196
288
 
289
+ def test_an_entry_cut_short_is_unreadable(tmp_path, monkeypatch):
290
+ # zipfile raises a bare EOFError for an entry that ends before its size.
291
+ # The tests' Python checks for overlapped entries and raises BadZipFile
292
+ # first, so the read is replaced.
293
+ def cut_short(*_):
294
+ raise EOFError
295
+
296
+ monkeypatch.setattr(export, "upload", cut_short)
297
+ _run(tmp_path, _config(EXPORT, [("segA", "seg_a")]), {"segA": _zip({"a.csv": b"x"})}, MemoryStore(), monkeypatch)
298
+ assert _report(tmp_path)["error"] == {
299
+ "code": "READ_FAILED",
300
+ "message": "The dataset for 'seg_a/' couldn't be read: EOFError",
301
+ }
302
+
303
+
197
304
  def test_a_long_message_is_cut_after_its_credentials_are_masked(tmp_path, monkeypatch):
198
305
  prefix = (
199
306
  "The bucket 'acme' in eu-central-1 returned an error, so writing 'decentriq/seg_a/data' failed after 0 of 1"
@@ -240,6 +347,29 @@ def test_an_internal_error_is_reported_without_its_message(tmp_path, monkeypatch
240
347
  }
241
348
 
242
349
 
350
+ def test_a_panic_is_reported_as_an_internal_error(tmp_path, monkeypatch):
351
+ class PanicException(BaseException):
352
+ pass
353
+
354
+ def panicking(*_):
355
+ raise PanicException("a dataset value")
356
+
357
+ line = panicking.__code__.co_firstlineno + 1
358
+ monkeypatch.setattr(export, "upload", panicking)
359
+ _run(tmp_path, _config(EXPORT, [("segA", "seg_a")]), {"segA": b"x"}, MemoryStore(), monkeypatch)
360
+ assert _report(tmp_path) == {
361
+ "version": "V0",
362
+ "error": {
363
+ "code": "INTERNAL_ERROR",
364
+ "message": "An internal error stopped the export:"
365
+ f" {__name__}.test_a_panic_is_reported_as_an_internal_error.<locals>.PanicException at {__name__}:{line}"
366
+ " (error message removed due to data privacy)",
367
+ },
368
+ "warnings": [],
369
+ "receipt": _receipt([("segA", "seg_a", 0, 0)]),
370
+ }
371
+
372
+
243
373
  def test_the_connection_test_writes_and_deletes_its_probe(tmp_path, monkeypatch):
244
374
  store = MemoryStore()
245
375
  logs = _run(tmp_path, _config(VALIDATE, []), {}, store, monkeypatch)
@@ -0,0 +1,164 @@
1
+ import json
2
+ import socket
3
+ from datetime import timedelta
4
+ from typing import TYPE_CHECKING
5
+
6
+ import obstore
7
+ import obstore.exceptions
8
+ from obstore.store import S3Store
9
+
10
+ from dq_export_connector._models.export_connector_credentials import BucketCredentials
11
+ from dq_export_connector._models.export_worker_config import BucketConnection
12
+ from dq_export_connector.bucket.store import build_store, classify_error, describe
13
+ from dq_export_connector.errors import ErrorCode, ExportConnectorError
14
+
15
+ if TYPE_CHECKING:
16
+ from obstore.store import ClientConfig
17
+
18
+
19
+ def _build_error(connection, credentials):
20
+ try:
21
+ build_store(BucketConnection.model_validate(connection), BucketCredentials.model_validate(credentials))
22
+ except ExportConnectorError as error:
23
+ return error.code, error.message
24
+ return None
25
+
26
+
27
+ def test_malformed_credentials_are_invalid_before_any_request():
28
+ gcs = {"type": "gcs", "bucket": "b", "pathPrefix": None}
29
+ azure = {"type": "azureBlob", "accountName": "a", "container": "c", "pathPrefix": None}
30
+ service_account = {"private_key_id": "i", "client_email": "a@b.iam.gserviceaccount.com"}
31
+ bad_key = "-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n"
32
+ decode_error = (
33
+ "The credentials couldn't be read: Generic GCS error: GCP credential error: Unable to decode service account"
34
+ " file: "
35
+ )
36
+ assert [
37
+ _build_error(gcs, {"gcs": {"serviceAccountJson": "not json"}}),
38
+ _build_error(gcs, {"gcs": {"serviceAccountJson": json.dumps({"private_key": 5})}}),
39
+ _build_error(gcs, {"gcs": {"serviceAccountJson": json.dumps({"client_email": "a@b"})}}),
40
+ _build_error(azure, {"azureBlob": {"sasToken": "garbage"}}),
41
+ _build_error(gcs, {"gcs": {"serviceAccountJson": json.dumps({**service_account, "private_key": "not a pem"})}}),
42
+ _build_error(gcs, {"gcs": {"serviceAccountJson": json.dumps({**service_account, "private_key": bad_key})}}),
43
+ ] == [
44
+ (ErrorCode.INVALID_CREDENTIALS, decode_error + "expected ident at line 1 column 2"),
45
+ (ErrorCode.INVALID_CREDENTIALS, decode_error + "invalid type: integer `***`, expected a string at line 1 column 17"),
46
+ (ErrorCode.INVALID_CREDENTIALS, decode_error + "missing field `private_key` at line 1 column 23"),
47
+ (
48
+ ErrorCode.INVALID_CREDENTIALS,
49
+ "The credentials couldn't be read: Generic MicrosoftAzure error: Missing component in SAS query pair",
50
+ ),
51
+ (
52
+ ErrorCode.INVALID_CREDENTIALS,
53
+ "The credentials couldn't be read: Generic AwsLcCryptoProvider error: Error reading pem file: no items found",
54
+ ),
55
+ (
56
+ ErrorCode.INVALID_CREDENTIALS,
57
+ "The credentials couldn't be read: Generic AwsLcCryptoProvider error: Invalid RSA key: InvalidEncoding",
58
+ ),
59
+ ]
60
+
61
+
62
+ def test_an_s3_access_key_no_header_can_hold_is_invalid():
63
+ s3 = {"type": "s3", "region": "eu-central-1", "bucket": "b", "pathPrefix": None}
64
+ error = (
65
+ ErrorCode.INVALID_CREDENTIALS,
66
+ "The S3 access key in the credentials contains whitespace or a control character",
67
+ )
68
+ assert [
69
+ _build_error(s3, {"s3": {"accessKey": access_key, "secretKey": "s"}})
70
+ for access_key in ["AKIA\n", " AKIA", "AK\u0001IA", "AKIA"]
71
+ ] == [error, error, error, None]
72
+
73
+
74
+ def test_a_rejected_credential_is_masked_however_rust_escapes_it():
75
+ gcs = {"type": "gcs", "bucket": "b", "pathPrefix": None}
76
+ # serde quotes a rejected string as Rust's Debug does, with \u{1} for the
77
+ # control character, which neither of the redactor's variants matches.
78
+ assert _build_error(gcs, {"gcs": {"serviceAccountJson": json.dumps("SECRET\u0001KEY")}}) == (
79
+ ErrorCode.INVALID_CREDENTIALS,
80
+ "The credentials couldn't be read: Generic GCS error: GCP credential error: Unable to decode service account"
81
+ ' file: invalid type: string "***", expected struct ServiceAccountCredentials at line 1 column 17',
82
+ )
83
+
84
+
85
+ def test_an_address_no_url_can_hold_is_unreachable():
86
+ azure = {"type": "azureBlob", "accountName": "my account", "container": "c", "pathPrefix": None}
87
+ assert _build_error(azure, {"azureBlob": {"sasToken": "sv=1&sig=2"}}) == (
88
+ ErrorCode.UNREACHABLE,
89
+ "The container 'c' of account 'my account' couldn't be reached: Generic MicrosoftAzure error: Unable parse"
90
+ " source url. Url: https://my account.blob.core.windows.net, Error: invalid international domain name",
91
+ )
92
+
93
+
94
+ def _put_error(port, client_options: "ClientConfig"):
95
+ store = S3Store(
96
+ bucket="b",
97
+ region="eu-west-1",
98
+ access_key_id="a",
99
+ secret_access_key="s",
100
+ endpoint=f"http://127.0.0.1:{port}",
101
+ retry_config={"max_retries": 0},
102
+ client_options=client_options,
103
+ )
104
+ try:
105
+ obstore.put(store, "k", b"x")
106
+ except obstore.exceptions.BaseError as error:
107
+ # Leaves out the request's URL and duration.
108
+ return classify_error(error), describe(error).split(" - ", 1)[1]
109
+ return None
110
+
111
+
112
+ def test_a_request_that_couldnt_be_sent_is_unreachable_and_keeps_its_cause():
113
+ with socket.socket() as closed:
114
+ closed.bind(("127.0.0.1", 0))
115
+ closed_port = closed.getsockname()[1]
116
+ # The kernel completes connections to a listening socket that never
117
+ # accepts them, so the request gets no response.
118
+ with socket.socket() as silent:
119
+ silent.bind(("127.0.0.1", 0))
120
+ silent.listen()
121
+ errors = [
122
+ _put_error(closed_port, {"allow_http": True}),
123
+ _put_error(silent.getsockname()[1], {"allow_http": True, "read_timeout": timedelta(milliseconds=200)}),
124
+ ]
125
+ assert errors == [
126
+ (ErrorCode.UNREACHABLE, "HTTP error: error sending request: tcp connect error: Connection refused"),
127
+ (ErrorCode.UNREACHABLE, "HTTP error: error sending request: timed out"),
128
+ ]
129
+
130
+
131
+ def test_obstores_debug_dump_is_left_out():
132
+ error = obstore.exceptions.GenericError("Generic S3 error: failed\n\nDebug source:\nGeneric {\n store: \"S3\",\n}")
133
+ assert describe(error) == "Generic S3 error: failed"
134
+
135
+
136
+ def _denied(key, response):
137
+ return obstore.exceptions.PermissionDeniedError(
138
+ f"The operation lacked the necessary privileges to complete for path {key}: Error performing PUT"
139
+ f" https://s3.eu-west-3.amazonaws.com/b/k in 110ms - Server returned non-2xx status code: 403 Forbidden:"
140
+ f" {response}"
141
+ )
142
+
143
+
144
+ def test_a_403_is_a_rejected_credential_only_by_the_code_in_its_response():
145
+ assert [
146
+ classify_error(_denied("k", "<Error><Code>SignatureDoesNotMatch</Code><Message>m</Message></Error>")),
147
+ classify_error(_denied("k", "<Error><Code>InvalidAccessKeyId</Code><Message>m</Message></Error>")),
148
+ classify_error(_denied("k", '\ufeff<?xml version="1.0"?><Error><Code>AuthenticationFailed</Code></Error>')),
149
+ classify_error(_denied("k", "<Error><Code>AccessDenied</Code><Message>m</Message></Error>")),
150
+ classify_error(_denied("<Code>SignatureDoesNotMatch</Code>", "<Error><Code>AccessDenied</Code></Error>")),
151
+ ] == [ErrorCode.UNAUTHENTICATED] * 3 + [ErrorCode.ACCESS_DENIED] * 2
152
+
153
+
154
+ def test_an_error_obstore_gives_no_type_and_no_cause_is_unknown():
155
+ error = obstore.exceptions.GenericError("Generic S3 error: AccessDenied, status code: 403, dns error")
156
+ assert classify_error(error) == ErrorCode.UNKNOWN
157
+
158
+
159
+ def test_a_bucket_in_another_region_is_not_found_there():
160
+ error = obstore.exceptions.GenericError(
161
+ "Generic S3 error: Error performing PUT https://s3.us-east-1.amazonaws.com/b/k in 482ms - Received redirect"
162
+ " without LOCATION, this normally indicates an incorrectly configured region"
163
+ )
164
+ assert classify_error(error) == ErrorCode.DESTINATION_NOT_FOUND
@@ -96,27 +96,34 @@ wheels = [
96
96
 
97
97
  [[package]]
98
98
  name = "dq-export-connector"
99
- version = "0.1.0.dev9"
99
+ version = "0.1.0.dev11"
100
100
  source = { editable = "." }
101
101
  dependencies = [
102
- { name = "obstore" },
103
102
  { name = "pydantic" },
104
103
  ]
105
104
 
105
+ [package.optional-dependencies]
106
+ bucket = [
107
+ { name = "obstore" },
108
+ ]
109
+
106
110
  [package.dev-dependencies]
107
111
  dev = [
112
+ { name = "dq-export-connector", extra = ["bucket"] },
108
113
  { name = "mypy" },
109
114
  { name = "pytest" },
110
115
  ]
111
116
 
112
117
  [package.metadata]
113
118
  requires-dist = [
114
- { name = "obstore", specifier = ">=0.11.1,<0.12" },
119
+ { name = "obstore", marker = "extra == 'bucket'", specifier = ">=0.11.1,<0.12" },
115
120
  { name = "pydantic", specifier = ">=2.7,<2.8" },
116
121
  ]
122
+ provides-extras = ["bucket"]
117
123
 
118
124
  [package.metadata.requires-dev]
119
125
  dev = [
126
+ { name = "dq-export-connector", extras = ["bucket"] },
120
127
  { name = "mypy", specifier = ">=1.13" },
121
128
  { name = "pytest", specifier = ">=8.3" },
122
129
  ]
@@ -1,46 +0,0 @@
1
- import obstore.exceptions
2
-
3
- from dq_export_connector._models.export_connector_credentials import BucketCredentials
4
- from dq_export_connector._models.export_worker_config import BucketConnection
5
- from dq_export_connector.bucket.store import build_store, classify_error, describe
6
- from dq_export_connector.errors import ErrorCode, ExportConnectorError
7
-
8
-
9
- def _build_error(connection, credentials):
10
- try:
11
- build_store(BucketConnection.model_validate(connection), BucketCredentials.model_validate(credentials))
12
- except ExportConnectorError as error:
13
- return error.code, error.message
14
- return None
15
-
16
-
17
- def test_malformed_credentials_are_invalid_before_any_request():
18
- gcs = {"type": "gcs", "bucket": "b", "pathPrefix": None}
19
- azure = {"type": "azureBlob", "accountName": "a", "container": "c", "pathPrefix": None}
20
- assert [
21
- _build_error(gcs, {"gcs": {"serviceAccountJson": "not json"}}),
22
- _build_error(azure, {"azureBlob": {"sasToken": "garbage"}}),
23
- ] == [
24
- (
25
- ErrorCode.INVALID_CREDENTIALS,
26
- "The credentials couldn't be read: Generic GCS error: GCP credential error: Unable to decode service"
27
- " account file: expected ident at line 1 column 2",
28
- ),
29
- (
30
- ErrorCode.INVALID_CREDENTIALS,
31
- "The credentials couldn't be read: Generic MicrosoftAzure error: Missing component in SAS query pair",
32
- ),
33
- ]
34
-
35
-
36
- def test_obstores_debug_dump_is_left_out():
37
- error = obstore.exceptions.GenericError("Generic S3 error: failed\n\nDebug source:\nGeneric {\n store: \"S3\",\n}")
38
- assert describe(error) == "Generic S3 error: failed"
39
-
40
-
41
- def test_a_bucket_in_another_region_is_not_found_there():
42
- error = obstore.exceptions.GenericError(
43
- "Generic S3 error: Error performing PUT https://s3.us-east-1.amazonaws.com/b/k in 482ms - Received redirect"
44
- " without LOCATION, this normally indicates an incorrectly configured region"
45
- )
46
- assert classify_error(error) == ErrorCode.DESTINATION_NOT_FOUND