dserver-signed-url-plugin 0.1.0__py3-none-any.whl
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.
- dserver_signed_url_plugin/__init__.py +779 -0
- dserver_signed_url_plugin/config.py +33 -0
- dserver_signed_url_plugin/schemas.py +92 -0
- dserver_signed_url_plugin/sql_models.py +47 -0
- dserver_signed_url_plugin/version.py +24 -0
- dserver_signed_url_plugin-0.1.0.dist-info/METADATA +595 -0
- dserver_signed_url_plugin-0.1.0.dist-info/RECORD +10 -0
- dserver_signed_url_plugin-0.1.0.dist-info/WHEEL +4 -0
- dserver_signed_url_plugin-0.1.0.dist-info/entry_points.txt +2 -0
- dserver_signed_url_plugin-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,779 @@
|
|
|
1
|
+
"""dserver plugin for generating signed URLs for dataset access."""
|
|
2
|
+
|
|
3
|
+
try:
|
|
4
|
+
from importlib.metadata import version, PackageNotFoundError
|
|
5
|
+
except ModuleNotFoundError:
|
|
6
|
+
from importlib_metadata import version, PackageNotFoundError
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
__version__ = version(__name__)
|
|
10
|
+
except PackageNotFoundError:
|
|
11
|
+
# package is not installed
|
|
12
|
+
pass
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import logging
|
|
16
|
+
from datetime import datetime, timedelta, timezone
|
|
17
|
+
from urllib.parse import unquote
|
|
18
|
+
|
|
19
|
+
import click
|
|
20
|
+
import dtoolcore
|
|
21
|
+
import dtoolcore.utils
|
|
22
|
+
|
|
23
|
+
from botocore.exceptions import ClientError
|
|
24
|
+
|
|
25
|
+
from flask import abort, current_app, jsonify
|
|
26
|
+
from flask.cli import AppGroup
|
|
27
|
+
from flask_smorest import Blueprint
|
|
28
|
+
from flask_smorest import abort as smorest_abort
|
|
29
|
+
|
|
30
|
+
from dservercore import ExtensionABC, sql_db
|
|
31
|
+
from dservercore.utils import (
|
|
32
|
+
register_dataset,
|
|
33
|
+
generate_dataset_info,
|
|
34
|
+
dataset_uri_exists,
|
|
35
|
+
)
|
|
36
|
+
from dservercore.utils_auth import (
|
|
37
|
+
jwt_required,
|
|
38
|
+
get_jwt_identity,
|
|
39
|
+
may_search,
|
|
40
|
+
may_register,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
from .config import Config, CONFIG_SECRETS_TO_OBFUSCATE
|
|
44
|
+
from .schemas import (
|
|
45
|
+
SignedURLsResponseSchema,
|
|
46
|
+
SignedItemURLResponseSchema,
|
|
47
|
+
UploadRequestSchema,
|
|
48
|
+
UploadURLsResponseSchema,
|
|
49
|
+
UploadCompleteRequestSchema,
|
|
50
|
+
UploadCompleteResponseSchema,
|
|
51
|
+
)
|
|
52
|
+
from .sql_models import PendingUpload
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
logger = logging.getLogger(__name__)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# Create the Flask-smorest blueprint
|
|
59
|
+
signed_url_bp = Blueprint(
|
|
60
|
+
"signed-urls",
|
|
61
|
+
__name__,
|
|
62
|
+
url_prefix="/signed-urls",
|
|
63
|
+
description="Endpoints for generating signed URLs for dataset access"
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# Create CLI command group for pending upload management
|
|
67
|
+
pending_upload_cli = AppGroup(
|
|
68
|
+
"pending_upload",
|
|
69
|
+
help="Pending upload management commands."
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@pending_upload_cli.command(name="list")
|
|
74
|
+
@click.option("--older-than", type=int, default=None,
|
|
75
|
+
help="Only show uploads older than N hours")
|
|
76
|
+
def list_pending_uploads(older_than):
|
|
77
|
+
"""List all pending uploads."""
|
|
78
|
+
query = PendingUpload.query
|
|
79
|
+
|
|
80
|
+
if older_than is not None:
|
|
81
|
+
cutoff = datetime.now(timezone.utc) - timedelta(hours=older_than)
|
|
82
|
+
query = query.filter(PendingUpload.created_at < cutoff)
|
|
83
|
+
|
|
84
|
+
pending = query.all()
|
|
85
|
+
|
|
86
|
+
if not pending:
|
|
87
|
+
click.echo("No pending uploads found.")
|
|
88
|
+
return
|
|
89
|
+
|
|
90
|
+
click.echo(f"Found {len(pending)} pending upload(s):\n")
|
|
91
|
+
for p in pending:
|
|
92
|
+
age = datetime.now(timezone.utc) - p.created_at.replace(tzinfo=timezone.utc)
|
|
93
|
+
age_hours = age.total_seconds() / 3600
|
|
94
|
+
click.echo(f" UUID: {p.uuid}")
|
|
95
|
+
click.echo(f" Name: {p.name}")
|
|
96
|
+
click.echo(f" URI: {p.uri}")
|
|
97
|
+
click.echo(f" Creator: {p.creator_username}")
|
|
98
|
+
click.echo(f" Created: {p.created_at.isoformat()} ({age_hours:.1f} hours ago)")
|
|
99
|
+
click.echo(f" Items: {len(p.manifest.get('items', {}))}")
|
|
100
|
+
click.echo()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@pending_upload_cli.command(name="cleanup")
|
|
104
|
+
@click.option("--older-than", type=int, required=True,
|
|
105
|
+
help="Delete uploads older than N hours")
|
|
106
|
+
@click.option("--dry-run", is_flag=True,
|
|
107
|
+
help="Show what would be deleted without actually deleting")
|
|
108
|
+
@click.option("--delete-storage", is_flag=True,
|
|
109
|
+
help="Also delete the proto-dataset from storage")
|
|
110
|
+
def cleanup_pending_uploads(older_than, dry_run, delete_storage):
|
|
111
|
+
"""Clean up stale pending uploads.
|
|
112
|
+
|
|
113
|
+
This removes pending upload records from the database. Optionally,
|
|
114
|
+
it can also delete the associated proto-datasets from storage.
|
|
115
|
+
"""
|
|
116
|
+
cutoff = datetime.now(timezone.utc) - timedelta(hours=older_than)
|
|
117
|
+
pending = PendingUpload.query.filter(PendingUpload.created_at < cutoff).all()
|
|
118
|
+
|
|
119
|
+
if not pending:
|
|
120
|
+
click.echo(f"No pending uploads older than {older_than} hours found.")
|
|
121
|
+
return
|
|
122
|
+
|
|
123
|
+
click.echo(f"Found {len(pending)} pending upload(s) older than {older_than} hours:")
|
|
124
|
+
|
|
125
|
+
for p in pending:
|
|
126
|
+
click.echo(f" - {p.uuid} ({p.name})")
|
|
127
|
+
|
|
128
|
+
if delete_storage and not dry_run:
|
|
129
|
+
try:
|
|
130
|
+
# Try to delete the proto-dataset from storage
|
|
131
|
+
proto = dtoolcore.ProtoDataSet.from_uri(p.uri)
|
|
132
|
+
# Note: dtoolcore doesn't have a delete method for proto-datasets
|
|
133
|
+
# This would need storage-broker specific implementation
|
|
134
|
+
click.secho(f" Warning: Storage deletion not implemented", fg="yellow")
|
|
135
|
+
except Exception as e:
|
|
136
|
+
click.secho(f" Warning: Could not access storage: {e}", fg="yellow")
|
|
137
|
+
|
|
138
|
+
if dry_run:
|
|
139
|
+
click.echo("\nDry run - no changes made.")
|
|
140
|
+
return
|
|
141
|
+
|
|
142
|
+
# Delete from database
|
|
143
|
+
for p in pending:
|
|
144
|
+
sql_db.session.delete(p)
|
|
145
|
+
|
|
146
|
+
sql_db.session.commit()
|
|
147
|
+
click.secho(f"\nDeleted {len(pending)} pending upload record(s) from database.", fg="green")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@pending_upload_cli.command(name="delete")
|
|
151
|
+
@click.argument("uuid")
|
|
152
|
+
@click.option("--delete-storage", is_flag=True,
|
|
153
|
+
help="Also delete the proto-dataset from storage")
|
|
154
|
+
def delete_pending_upload(uuid, delete_storage):
|
|
155
|
+
"""Delete a specific pending upload by UUID."""
|
|
156
|
+
pending = PendingUpload.query.filter_by(uuid=uuid).first()
|
|
157
|
+
|
|
158
|
+
if pending is None:
|
|
159
|
+
click.secho(f"No pending upload found with UUID: {uuid}", fg="red")
|
|
160
|
+
return
|
|
161
|
+
|
|
162
|
+
click.echo(f"Deleting pending upload:")
|
|
163
|
+
click.echo(f" UUID: {pending.uuid}")
|
|
164
|
+
click.echo(f" Name: {pending.name}")
|
|
165
|
+
click.echo(f" URI: {pending.uri}")
|
|
166
|
+
|
|
167
|
+
if delete_storage:
|
|
168
|
+
try:
|
|
169
|
+
proto = dtoolcore.ProtoDataSet.from_uri(pending.uri)
|
|
170
|
+
click.secho(" Warning: Storage deletion not implemented", fg="yellow")
|
|
171
|
+
except Exception as e:
|
|
172
|
+
click.secho(f" Warning: Could not access storage: {e}", fg="yellow")
|
|
173
|
+
|
|
174
|
+
sql_db.session.delete(pending)
|
|
175
|
+
sql_db.session.commit()
|
|
176
|
+
click.secho(f"\nDeleted pending upload record from database.", fg="green")
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _extract_base_uri(uri):
|
|
180
|
+
"""Extract base URI from dataset URI."""
|
|
181
|
+
return uri.rsplit("/", 1)[0]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _rewrite_url(url):
|
|
185
|
+
"""Rewrite URL if host rewriting is configured.
|
|
186
|
+
|
|
187
|
+
This is used when dserver runs in a container and the internal
|
|
188
|
+
hostname (e.g., 'minio') needs to be replaced with an externally
|
|
189
|
+
accessible hostname (e.g., 'localhost').
|
|
190
|
+
|
|
191
|
+
:param url: Original URL
|
|
192
|
+
:returns: Rewritten URL (or original if no rewrite configured)
|
|
193
|
+
"""
|
|
194
|
+
rewrite_config = Config.SIGNED_URL_HOST_REWRITE
|
|
195
|
+
if not rewrite_config:
|
|
196
|
+
return url
|
|
197
|
+
|
|
198
|
+
# Format is "internal|external", e.g.
|
|
199
|
+
# "http://minio:9000|http://localhost:9000"
|
|
200
|
+
internal, sep, external = rewrite_config.partition('|')
|
|
201
|
+
if not sep or not internal or not external:
|
|
202
|
+
logger.warning(
|
|
203
|
+
f"Invalid SIGNED_URL_HOST_REWRITE format: {rewrite_config!r} "
|
|
204
|
+
f"(expected 'internal|external', e.g. "
|
|
205
|
+
f"'http://minio:9000|http://localhost:9000')"
|
|
206
|
+
)
|
|
207
|
+
return url
|
|
208
|
+
|
|
209
|
+
return url.replace(internal, external, 1)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _rewrite_urls_dict(urls_dict):
|
|
213
|
+
"""Apply URL rewriting to all URLs in a dictionary.
|
|
214
|
+
|
|
215
|
+
:param urls_dict: Dictionary potentially containing URL values
|
|
216
|
+
:returns: Dictionary with rewritten URLs
|
|
217
|
+
"""
|
|
218
|
+
result = {}
|
|
219
|
+
for key, value in urls_dict.items():
|
|
220
|
+
if isinstance(value, str) and ('://' in value):
|
|
221
|
+
result[key] = _rewrite_url(value)
|
|
222
|
+
elif isinstance(value, dict):
|
|
223
|
+
result[key] = _rewrite_urls_dict(value)
|
|
224
|
+
elif isinstance(value, list):
|
|
225
|
+
result[key] = [
|
|
226
|
+
_rewrite_url(v) if isinstance(v, str) and '://' in v else v
|
|
227
|
+
for v in value
|
|
228
|
+
]
|
|
229
|
+
else:
|
|
230
|
+
result[key] = value
|
|
231
|
+
return result
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _get_storage_broker(uri):
|
|
235
|
+
"""Get storage broker instance for a dataset URI.
|
|
236
|
+
|
|
237
|
+
:param uri: Dataset URI
|
|
238
|
+
:returns: Storage broker instance
|
|
239
|
+
:raises: ValueError if broker doesn't support signing
|
|
240
|
+
"""
|
|
241
|
+
try:
|
|
242
|
+
dataset = dtoolcore.DataSet.from_uri(uri)
|
|
243
|
+
storage_broker = dataset._storage_broker
|
|
244
|
+
except Exception as e:
|
|
245
|
+
logger.error(f"Failed to get storage broker for {uri}: {e}")
|
|
246
|
+
raise ValueError(f"Cannot access dataset at {uri}: {e}")
|
|
247
|
+
|
|
248
|
+
# Check if broker supports signing
|
|
249
|
+
if not hasattr(storage_broker, 'generate_dataset_signed_urls'):
|
|
250
|
+
raise ValueError(
|
|
251
|
+
f"Storage broker {type(storage_broker).__name__} does not support "
|
|
252
|
+
"signed URL generation"
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
return storage_broker
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
@signed_url_bp.route("/dataset/<path:uri>", methods=["GET"])
|
|
259
|
+
@signed_url_bp.response(200, SignedURLsResponseSchema)
|
|
260
|
+
@jwt_required()
|
|
261
|
+
def get_dataset_signed_urls(uri):
|
|
262
|
+
"""Get signed URLs for reading an entire dataset.
|
|
263
|
+
|
|
264
|
+
Returns a set of time-limited signed URLs that can be used to download
|
|
265
|
+
all components of a dataset (admin metadata, manifest, README, items,
|
|
266
|
+
overlays, and annotations) without requiring direct storage backend
|
|
267
|
+
credentials.
|
|
268
|
+
"""
|
|
269
|
+
username = get_jwt_identity()
|
|
270
|
+
uri = unquote(uri)
|
|
271
|
+
base_uri = _extract_base_uri(uri)
|
|
272
|
+
|
|
273
|
+
# Authorization check - user must have search permissions on base URI
|
|
274
|
+
if not may_search(username, base_uri):
|
|
275
|
+
logger.warning(
|
|
276
|
+
f"User {username} denied access to signed URLs for {uri}: "
|
|
277
|
+
"no search permission on base URI"
|
|
278
|
+
)
|
|
279
|
+
abort(403, description="You do not have search permission for this base URI. Please contact an administrator.")
|
|
280
|
+
|
|
281
|
+
# Check dataset exists in dserver
|
|
282
|
+
if not dataset_uri_exists(uri):
|
|
283
|
+
logger.warning(f"Dataset not found in dserver: {uri}")
|
|
284
|
+
abort(404, description="Dataset not found")
|
|
285
|
+
|
|
286
|
+
# Get storage broker
|
|
287
|
+
try:
|
|
288
|
+
storage_broker = _get_storage_broker(uri)
|
|
289
|
+
except ValueError as e:
|
|
290
|
+
logger.error(f"Failed to get storage broker: {e}")
|
|
291
|
+
abort(501, description=str(e))
|
|
292
|
+
|
|
293
|
+
# Generate signed URLs
|
|
294
|
+
expiry_seconds = Config.SIGNED_URL_READ_EXPIRY_SECONDS
|
|
295
|
+
try:
|
|
296
|
+
urls = storage_broker.generate_dataset_signed_urls(expiry_seconds)
|
|
297
|
+
except Exception as e:
|
|
298
|
+
logger.error(f"Failed to generate signed URLs for {uri}: {e}")
|
|
299
|
+
abort(500, description=f"Failed to generate signed URLs: {e}")
|
|
300
|
+
|
|
301
|
+
# Rewrite URLs if host rewriting is configured
|
|
302
|
+
urls = _rewrite_urls_dict(urls)
|
|
303
|
+
|
|
304
|
+
expiry_timestamp = (
|
|
305
|
+
datetime.now(timezone.utc) + timedelta(seconds=expiry_seconds)
|
|
306
|
+
).isoformat()
|
|
307
|
+
|
|
308
|
+
return {
|
|
309
|
+
'uri': uri,
|
|
310
|
+
'expiry_seconds': expiry_seconds,
|
|
311
|
+
'expiry_timestamp': expiry_timestamp,
|
|
312
|
+
**urls
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
@signed_url_bp.route("/item/<path:uri>/<identifier>", methods=["GET"])
|
|
317
|
+
@signed_url_bp.response(200, SignedItemURLResponseSchema)
|
|
318
|
+
@jwt_required()
|
|
319
|
+
def get_item_signed_url(uri, identifier):
|
|
320
|
+
"""Get signed URL for a single dataset item.
|
|
321
|
+
|
|
322
|
+
Returns a time-limited signed URL for downloading a specific item
|
|
323
|
+
from a dataset. This is more efficient than getting URLs for the
|
|
324
|
+
entire dataset when only one item is needed.
|
|
325
|
+
"""
|
|
326
|
+
username = get_jwt_identity()
|
|
327
|
+
uri = unquote(uri)
|
|
328
|
+
base_uri = _extract_base_uri(uri)
|
|
329
|
+
|
|
330
|
+
# Authorization check
|
|
331
|
+
if not may_search(username, base_uri):
|
|
332
|
+
logger.warning(
|
|
333
|
+
f"User {username} denied access to signed URL for item {identifier} "
|
|
334
|
+
f"in {uri}: no search permission on base URI"
|
|
335
|
+
)
|
|
336
|
+
abort(403, description="You do not have search permission for this base URI. Please contact an administrator.")
|
|
337
|
+
|
|
338
|
+
# Check dataset exists
|
|
339
|
+
if not dataset_uri_exists(uri):
|
|
340
|
+
abort(404, description="Dataset not found")
|
|
341
|
+
|
|
342
|
+
# Get storage broker
|
|
343
|
+
try:
|
|
344
|
+
storage_broker = _get_storage_broker(uri)
|
|
345
|
+
except ValueError as e:
|
|
346
|
+
abort(501, description=str(e))
|
|
347
|
+
|
|
348
|
+
# Get manifest to verify item exists
|
|
349
|
+
try:
|
|
350
|
+
manifest = storage_broker.get_manifest()
|
|
351
|
+
except Exception as e:
|
|
352
|
+
logger.error(f"Failed to get manifest for {uri}: {e}")
|
|
353
|
+
abort(500, description=f"Failed to get manifest: {e}")
|
|
354
|
+
|
|
355
|
+
if identifier not in manifest.get('items', {}):
|
|
356
|
+
abort(404, description=f"Item {identifier} not found in dataset")
|
|
357
|
+
|
|
358
|
+
# Generate signed URL for the item
|
|
359
|
+
expiry_seconds = Config.SIGNED_URL_READ_EXPIRY_SECONDS
|
|
360
|
+
try:
|
|
361
|
+
item_key = storage_broker.data_key_prefix + identifier
|
|
362
|
+
url = storage_broker.generate_signed_read_url(item_key, expiry_seconds)
|
|
363
|
+
except Exception as e:
|
|
364
|
+
logger.error(f"Failed to generate signed URL for item {identifier}: {e}")
|
|
365
|
+
abort(500, description=f"Failed to generate signed URL: {e}")
|
|
366
|
+
|
|
367
|
+
# Rewrite URL if host rewriting is configured
|
|
368
|
+
url = _rewrite_url(url)
|
|
369
|
+
|
|
370
|
+
expiry_timestamp = (
|
|
371
|
+
datetime.now(timezone.utc) + timedelta(seconds=expiry_seconds)
|
|
372
|
+
).isoformat()
|
|
373
|
+
|
|
374
|
+
return {
|
|
375
|
+
'uri': uri,
|
|
376
|
+
'identifier': identifier,
|
|
377
|
+
'expiry_seconds': expiry_seconds,
|
|
378
|
+
'expiry_timestamp': expiry_timestamp,
|
|
379
|
+
'url': url
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
@signed_url_bp.route("/upload/<path:base_uri>", methods=["POST"])
|
|
384
|
+
@signed_url_bp.arguments(UploadRequestSchema)
|
|
385
|
+
@signed_url_bp.response(200, UploadURLsResponseSchema)
|
|
386
|
+
@jwt_required()
|
|
387
|
+
def get_upload_signed_urls(request_data, base_uri):
|
|
388
|
+
"""Get signed URLs for uploading a new dataset.
|
|
389
|
+
|
|
390
|
+
The server creates a proto-dataset in storage and returns signed URLs
|
|
391
|
+
for uploading README and items. The proto-dataset is not yet frozen,
|
|
392
|
+
allowing detection of incomplete uploads.
|
|
393
|
+
|
|
394
|
+
After uploading README and items, the client should call the upload-complete
|
|
395
|
+
endpoint to freeze the dataset and trigger registration.
|
|
396
|
+
|
|
397
|
+
Repeating the request for an unfinished upload of the same UUID to the
|
|
398
|
+
same base URI resumes it: the pending upload record is refreshed and a
|
|
399
|
+
fresh set of signed URLs is returned.
|
|
400
|
+
"""
|
|
401
|
+
username = get_jwt_identity()
|
|
402
|
+
base_uri = unquote(base_uri)
|
|
403
|
+
|
|
404
|
+
# Authorization check - user must have register permissions
|
|
405
|
+
if not may_register(username, base_uri):
|
|
406
|
+
logger.warning(
|
|
407
|
+
f"User {username} denied upload to {base_uri}: "
|
|
408
|
+
"no register permission"
|
|
409
|
+
)
|
|
410
|
+
abort(403, description="You do not have register permission for this base URI. Please contact an administrator.")
|
|
411
|
+
|
|
412
|
+
dataset_uuid = request_data['uuid']
|
|
413
|
+
name = request_data['name']
|
|
414
|
+
creator_username = request_data['creator_username']
|
|
415
|
+
frozen_at = request_data['frozen_at']
|
|
416
|
+
hash_function = request_data.get('hash_function', 'md5sum_hexdigest')
|
|
417
|
+
items = request_data.get('items', [])
|
|
418
|
+
tags = request_data.get('tags', [])
|
|
419
|
+
annotations = request_data.get('annotations', {})
|
|
420
|
+
overlays = request_data.get('overlays', {})
|
|
421
|
+
|
|
422
|
+
# Item hashes are pinned into the signed upload URLs as Content-MD5 and
|
|
423
|
+
# verified by the storage backend, which requires MD5 hashes
|
|
424
|
+
if hash_function != 'md5sum_hexdigest':
|
|
425
|
+
abort(400, description=(
|
|
426
|
+
f"Unsupported hash function '{hash_function}'; "
|
|
427
|
+
f"only 'md5sum_hexdigest' is supported"
|
|
428
|
+
))
|
|
429
|
+
|
|
430
|
+
if not dtoolcore.utils.name_is_valid(name):
|
|
431
|
+
abort(400, description=(
|
|
432
|
+
f"Invalid dataset name '{name}'. Names may be up to 80 "
|
|
433
|
+
f"characters long and contain only alphanumeric characters "
|
|
434
|
+
f"and the special characters - _ ."
|
|
435
|
+
))
|
|
436
|
+
|
|
437
|
+
# Generate dataset URI
|
|
438
|
+
dataset_uri = f"{base_uri}/{dataset_uuid}"
|
|
439
|
+
|
|
440
|
+
# Check if dataset already exists
|
|
441
|
+
if dataset_uri_exists(dataset_uri):
|
|
442
|
+
abort(409, description=f"Dataset {dataset_uuid} already exists at {base_uri}")
|
|
443
|
+
|
|
444
|
+
# An unfinished upload of the same UUID to the same location may be
|
|
445
|
+
# resumed; the same UUID pending at a different location is a conflict.
|
|
446
|
+
pending_upload = PendingUpload.query.filter_by(uuid=dataset_uuid).first()
|
|
447
|
+
if pending_upload is not None and pending_upload.uri != dataset_uri:
|
|
448
|
+
abort(409, description=(
|
|
449
|
+
f"A pending upload with UUID {dataset_uuid} already exists "
|
|
450
|
+
f"at a different location"
|
|
451
|
+
))
|
|
452
|
+
|
|
453
|
+
expiry_seconds = Config.SIGNED_URL_WRITE_EXPIRY_SECONDS
|
|
454
|
+
|
|
455
|
+
try:
|
|
456
|
+
# Build manifest with items (will be used when freezing)
|
|
457
|
+
manifest_items = {}
|
|
458
|
+
for item in items:
|
|
459
|
+
relpath = item['relpath']
|
|
460
|
+
identifier = dtoolcore.utils.generate_identifier(relpath)
|
|
461
|
+
manifest_items[identifier] = {
|
|
462
|
+
"relpath": relpath,
|
|
463
|
+
"size_in_bytes": item['size_in_bytes'],
|
|
464
|
+
"hash": item['hash'],
|
|
465
|
+
"utc_timestamp": item['utc_timestamp'],
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
manifest = {
|
|
469
|
+
"dtoolcore_version": dtoolcore.__version__,
|
|
470
|
+
"hash_function": hash_function,
|
|
471
|
+
"items": manifest_items,
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
proto_dataset = None
|
|
475
|
+
if pending_upload is not None:
|
|
476
|
+
# Resume an interrupted upload: reuse the existing proto-dataset
|
|
477
|
+
try:
|
|
478
|
+
proto_dataset = dtoolcore.ProtoDataSet.from_uri(dataset_uri)
|
|
479
|
+
logger.info(f"Resuming pending upload for {dataset_uri}")
|
|
480
|
+
except Exception:
|
|
481
|
+
logger.warning(
|
|
482
|
+
f"Pending upload record exists for {dataset_uri} but the "
|
|
483
|
+
f"proto-dataset could not be loaded; recreating it"
|
|
484
|
+
)
|
|
485
|
+
|
|
486
|
+
if proto_dataset is None:
|
|
487
|
+
# Create a proto-dataset (not frozen yet)
|
|
488
|
+
# This allows us to detect incomplete uploads
|
|
489
|
+
logger.debug(f"Creating proto-dataset {dataset_uri}")
|
|
490
|
+
|
|
491
|
+
# Build admin metadata with the client-provided UUID
|
|
492
|
+
admin_metadata = {
|
|
493
|
+
"uuid": dataset_uuid,
|
|
494
|
+
"dtoolcore_version": dtoolcore.__version__,
|
|
495
|
+
"name": name,
|
|
496
|
+
"type": "protodataset",
|
|
497
|
+
"creator_username": creator_username,
|
|
498
|
+
"created_at": datetime.now(timezone.utc).timestamp(),
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
# Create proto-dataset with custom admin metadata
|
|
502
|
+
proto_dataset = dtoolcore.generate_proto_dataset(
|
|
503
|
+
admin_metadata=admin_metadata,
|
|
504
|
+
base_uri=base_uri,
|
|
505
|
+
)
|
|
506
|
+
proto_dataset.create()
|
|
507
|
+
proto_dataset.put_readme("") # Empty README, will be uploaded
|
|
508
|
+
|
|
509
|
+
# Add tags to proto-dataset
|
|
510
|
+
if tags:
|
|
511
|
+
for tag in tags:
|
|
512
|
+
proto_dataset.put_tag(tag)
|
|
513
|
+
|
|
514
|
+
# Add annotations to proto-dataset
|
|
515
|
+
if annotations:
|
|
516
|
+
for ann_name, ann_value in annotations.items():
|
|
517
|
+
proto_dataset.put_annotation(ann_name, ann_value)
|
|
518
|
+
|
|
519
|
+
# Write overlays directly to storage; they are plain JSON objects
|
|
520
|
+
# and do not interfere with freezing
|
|
521
|
+
if overlays:
|
|
522
|
+
for overlay_name, overlay in overlays.items():
|
|
523
|
+
proto_dataset._storage_broker.put_overlay(overlay_name, overlay)
|
|
524
|
+
|
|
525
|
+
# Store pending upload in database for use when freezing
|
|
526
|
+
if pending_upload is None:
|
|
527
|
+
pending_upload = PendingUpload(
|
|
528
|
+
uuid=dataset_uuid,
|
|
529
|
+
uri=proto_dataset.uri,
|
|
530
|
+
base_uri=base_uri,
|
|
531
|
+
name=name,
|
|
532
|
+
creator_username=creator_username,
|
|
533
|
+
frozen_at=frozen_at,
|
|
534
|
+
manifest=manifest,
|
|
535
|
+
)
|
|
536
|
+
sql_db.session.add(pending_upload)
|
|
537
|
+
else:
|
|
538
|
+
pending_upload.name = name
|
|
539
|
+
pending_upload.creator_username = creator_username
|
|
540
|
+
pending_upload.frozen_at = frozen_at
|
|
541
|
+
pending_upload.manifest = manifest
|
|
542
|
+
pending_upload.created_at = datetime.now(timezone.utc)
|
|
543
|
+
sql_db.session.commit()
|
|
544
|
+
|
|
545
|
+
# Get storage broker from the created proto-dataset to generate signed URLs
|
|
546
|
+
storage_broker = proto_dataset._storage_broker
|
|
547
|
+
|
|
548
|
+
# Generate signed URLs for README and items
|
|
549
|
+
upload_urls = {
|
|
550
|
+
'readme': storage_broker.generate_signed_write_url(
|
|
551
|
+
storage_broker.get_readme_key(), expiry_seconds),
|
|
552
|
+
'items': {}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
# Generate URLs for each item. Where the storage broker supports it,
|
|
556
|
+
# the item's object metadata and Content-MD5 are pinned into the
|
|
557
|
+
# signature, so the storage backend itself rejects uploads whose
|
|
558
|
+
# content does not match the claimed hash.
|
|
559
|
+
for item in items:
|
|
560
|
+
relpath = item['relpath']
|
|
561
|
+
identifier = dtoolcore.utils.generate_identifier(relpath)
|
|
562
|
+
if hasattr(storage_broker, 'generate_signed_item_write_url'):
|
|
563
|
+
url, headers = storage_broker.generate_signed_item_write_url(
|
|
564
|
+
relpath, item['hash'], expiry_seconds)
|
|
565
|
+
else:
|
|
566
|
+
item_key = storage_broker.data_key_prefix + identifier
|
|
567
|
+
url = storage_broker.generate_signed_write_url(
|
|
568
|
+
item_key, expiry_seconds)
|
|
569
|
+
headers = {}
|
|
570
|
+
upload_urls['items'][identifier] = {
|
|
571
|
+
'url': url,
|
|
572
|
+
'relpath': relpath,
|
|
573
|
+
'headers': headers,
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
except dtoolcore.DtoolCoreInvalidNameError as e:
|
|
577
|
+
logger.warning(f"Invalid name in upload request for {dataset_uri}: {e}")
|
|
578
|
+
abort(400, description=str(e))
|
|
579
|
+
except dtoolcore.DtoolCoreValueError as e:
|
|
580
|
+
logger.warning(f"Invalid value in upload request for {dataset_uri}: {e}")
|
|
581
|
+
abort(400, description=str(e))
|
|
582
|
+
except ClientError as e:
|
|
583
|
+
error_code = e.response.get('Error', {}).get('Code', 'Unknown')
|
|
584
|
+
logger.error(
|
|
585
|
+
f"Storage backend rejected upload request for {dataset_uri}: {e}"
|
|
586
|
+
)
|
|
587
|
+
smorest_abort(502, message=(
|
|
588
|
+
f"The storage backend rejected the request ({error_code}). "
|
|
589
|
+
f"The server's storage credentials may lack write permission "
|
|
590
|
+
f"for this base URI. Please contact an administrator."
|
|
591
|
+
))
|
|
592
|
+
except Exception as e:
|
|
593
|
+
logger.error(f"Failed to process upload request for {dataset_uri}: {e}")
|
|
594
|
+
abort(500, description=f"Failed to process upload request: {e}")
|
|
595
|
+
|
|
596
|
+
# Rewrite URLs if host rewriting is configured
|
|
597
|
+
upload_urls = _rewrite_urls_dict(upload_urls)
|
|
598
|
+
|
|
599
|
+
expiry_timestamp = (
|
|
600
|
+
datetime.now(timezone.utc) + timedelta(seconds=expiry_seconds)
|
|
601
|
+
).isoformat()
|
|
602
|
+
|
|
603
|
+
return {
|
|
604
|
+
'uuid': dataset_uuid,
|
|
605
|
+
'uri': dataset_uri,
|
|
606
|
+
'base_uri': base_uri,
|
|
607
|
+
'expiry_seconds': expiry_seconds,
|
|
608
|
+
'expiry_timestamp': expiry_timestamp,
|
|
609
|
+
'upload_urls': upload_urls
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
@signed_url_bp.route("/upload-complete", methods=["POST"])
|
|
614
|
+
@signed_url_bp.arguments(UploadCompleteRequestSchema)
|
|
615
|
+
@signed_url_bp.response(200, UploadCompleteResponseSchema)
|
|
616
|
+
@jwt_required()
|
|
617
|
+
def signal_upload_complete(request_data):
|
|
618
|
+
"""Signal that a dataset upload is complete.
|
|
619
|
+
|
|
620
|
+
After uploading all dataset components using the signed URLs from
|
|
621
|
+
the upload endpoint, call this endpoint to freeze the proto-dataset
|
|
622
|
+
and trigger dataset registration in dserver.
|
|
623
|
+
"""
|
|
624
|
+
username = get_jwt_identity()
|
|
625
|
+
uri = request_data['uri']
|
|
626
|
+
base_uri = _extract_base_uri(uri)
|
|
627
|
+
|
|
628
|
+
# Extract UUID from URI
|
|
629
|
+
dataset_uuid = uri.rsplit("/", 1)[-1]
|
|
630
|
+
|
|
631
|
+
# Authorization check
|
|
632
|
+
if not may_register(username, base_uri):
|
|
633
|
+
logger.warning(
|
|
634
|
+
f"User {username} denied upload-complete for {uri}: "
|
|
635
|
+
"no register permission"
|
|
636
|
+
)
|
|
637
|
+
abort(403, description="You do not have register permission for this base URI. Please contact an administrator.")
|
|
638
|
+
|
|
639
|
+
# Check if we have pending upload data for this UUID in the database
|
|
640
|
+
pending_upload = PendingUpload.query.filter_by(uuid=dataset_uuid).first()
|
|
641
|
+
if pending_upload is None:
|
|
642
|
+
logger.warning(f"No pending upload found for {uri}")
|
|
643
|
+
abort(400, description="No pending upload found for this dataset")
|
|
644
|
+
|
|
645
|
+
# The pending upload must have been initiated for this exact URI;
|
|
646
|
+
# otherwise a user with register permission elsewhere could hijack or
|
|
647
|
+
# discard someone else's pending upload
|
|
648
|
+
if pending_upload.uri != uri:
|
|
649
|
+
logger.warning(
|
|
650
|
+
f"Upload-complete URI mismatch: request for {uri}, but pending "
|
|
651
|
+
f"upload {dataset_uuid} is registered for {pending_upload.uri}"
|
|
652
|
+
)
|
|
653
|
+
abort(409, description=(
|
|
654
|
+
"Pending upload for this UUID was initiated for a different URI"
|
|
655
|
+
))
|
|
656
|
+
|
|
657
|
+
manifest = pending_upload.manifest
|
|
658
|
+
frozen_at = pending_upload.frozen_at
|
|
659
|
+
|
|
660
|
+
# Load proto-dataset and freeze it
|
|
661
|
+
try:
|
|
662
|
+
proto_dataset = dtoolcore.ProtoDataSet.from_uri(uri)
|
|
663
|
+
except dtoolcore.DtoolCoreTypeError as e:
|
|
664
|
+
# Already frozen? Try loading as DataSet
|
|
665
|
+
try:
|
|
666
|
+
dataset = dtoolcore.DataSet.from_uri(uri)
|
|
667
|
+
logger.info(f"Dataset {uri} already frozen, proceeding with registration")
|
|
668
|
+
except Exception as inner_e:
|
|
669
|
+
logger.warning(f"Upload complete but dataset invalid: {uri} - {e}")
|
|
670
|
+
abort(400, description=f"Invalid or incomplete dataset: {e}")
|
|
671
|
+
except Exception as e:
|
|
672
|
+
logger.error(f"Failed to load proto-dataset {uri}: {e}")
|
|
673
|
+
abort(400, description=f"Failed to load dataset: {e}")
|
|
674
|
+
else:
|
|
675
|
+
# Freeze the proto-dataset with the stored manifest
|
|
676
|
+
try:
|
|
677
|
+
proto_dataset.freeze_with_manifest(manifest, frozen_at=frozen_at)
|
|
678
|
+
logger.debug(f"Froze proto-dataset {uri}")
|
|
679
|
+
except ClientError as e:
|
|
680
|
+
error_code = e.response.get('Error', {}).get('Code', 'Unknown')
|
|
681
|
+
logger.error(f"Storage backend rejected freeze of {uri}: {e}")
|
|
682
|
+
smorest_abort(502, message=(
|
|
683
|
+
f"The storage backend rejected the request ({error_code}). "
|
|
684
|
+
f"The server's storage credentials may lack write permission "
|
|
685
|
+
f"for this base URI. Please contact an administrator."
|
|
686
|
+
))
|
|
687
|
+
except dtoolcore.DtoolCoreFrozenDataSetError:
|
|
688
|
+
# A concurrent upload-complete request froze the dataset after
|
|
689
|
+
# this request loaded it. Proceed with registration, as when
|
|
690
|
+
# loading finds an already frozen dataset.
|
|
691
|
+
logger.info(
|
|
692
|
+
f"Dataset {uri} was frozen by a concurrent request, "
|
|
693
|
+
"proceeding with registration")
|
|
694
|
+
except Exception as e:
|
|
695
|
+
logger.error(f"Failed to freeze proto-dataset {uri}: {e}")
|
|
696
|
+
abort(500, description=f"Failed to freeze dataset: {e}")
|
|
697
|
+
|
|
698
|
+
# Load the frozen dataset
|
|
699
|
+
try:
|
|
700
|
+
dataset = dtoolcore.DataSet.from_uri(uri)
|
|
701
|
+
except Exception as e:
|
|
702
|
+
logger.error(f"Failed to load frozen dataset {uri}: {e}")
|
|
703
|
+
abort(500, description=f"Failed to load frozen dataset: {e}")
|
|
704
|
+
|
|
705
|
+
# Generate dataset info for registration
|
|
706
|
+
try:
|
|
707
|
+
dataset_info = generate_dataset_info(dataset, base_uri)
|
|
708
|
+
except Exception as e:
|
|
709
|
+
logger.error(f"Failed to generate dataset info for {uri}: {e}")
|
|
710
|
+
abort(500, description=f"Failed to generate dataset info: {e}")
|
|
711
|
+
|
|
712
|
+
# Register in dserver
|
|
713
|
+
try:
|
|
714
|
+
register_dataset(dataset_info)
|
|
715
|
+
except Exception as e:
|
|
716
|
+
logger.error(f"Failed to register dataset {uri}: {e}")
|
|
717
|
+
abort(500, description=f"Failed to register dataset: {e}")
|
|
718
|
+
|
|
719
|
+
# Clean up pending upload record from database. A concurrent request
|
|
720
|
+
# may already have removed it, so delete by query: deleting the loaded
|
|
721
|
+
# object would warn that it expected to delete a row and matched none.
|
|
722
|
+
PendingUpload.query.filter_by(uuid=dataset_uuid).delete()
|
|
723
|
+
sql_db.session.commit()
|
|
724
|
+
|
|
725
|
+
logger.info(f"Successfully registered dataset from upload: {uri}")
|
|
726
|
+
|
|
727
|
+
return {
|
|
728
|
+
'uri': uri,
|
|
729
|
+
'status': 'registered',
|
|
730
|
+
'name': dataset.name,
|
|
731
|
+
'uuid': dataset.uuid
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
class SignedURLExtension(ExtensionABC):
|
|
736
|
+
"""dserver extension for generating signed URLs for dataset access.
|
|
737
|
+
|
|
738
|
+
This extension allows dserver to act as a storage access delegate,
|
|
739
|
+
generating time-limited signed URLs for S3, Azure, and other storage
|
|
740
|
+
backends. Users can access datasets through dserver without requiring
|
|
741
|
+
direct backend credentials.
|
|
742
|
+
"""
|
|
743
|
+
|
|
744
|
+
def init_app(self, app):
|
|
745
|
+
"""Initialize the extension with the Flask app."""
|
|
746
|
+
# Register configuration
|
|
747
|
+
app.config.setdefault(
|
|
748
|
+
'SIGNED_URL_READ_EXPIRY_SECONDS',
|
|
749
|
+
Config.SIGNED_URL_READ_EXPIRY_SECONDS
|
|
750
|
+
)
|
|
751
|
+
app.config.setdefault(
|
|
752
|
+
'SIGNED_URL_WRITE_EXPIRY_SECONDS',
|
|
753
|
+
Config.SIGNED_URL_WRITE_EXPIRY_SECONDS
|
|
754
|
+
)
|
|
755
|
+
|
|
756
|
+
# Register CLI commands for pending upload management
|
|
757
|
+
app.cli.add_command(pending_upload_cli)
|
|
758
|
+
|
|
759
|
+
logger.info(
|
|
760
|
+
f"SignedURLExtension initialized with read_expiry="
|
|
761
|
+
f"{Config.SIGNED_URL_READ_EXPIRY_SECONDS}s, write_expiry="
|
|
762
|
+
f"{Config.SIGNED_URL_WRITE_EXPIRY_SECONDS}s"
|
|
763
|
+
)
|
|
764
|
+
|
|
765
|
+
def register_dataset(self, dataset_info):
|
|
766
|
+
"""Called when a dataset is registered - no action needed."""
|
|
767
|
+
pass
|
|
768
|
+
|
|
769
|
+
def get_config(self):
|
|
770
|
+
"""Return initial Config object."""
|
|
771
|
+
return Config
|
|
772
|
+
|
|
773
|
+
def get_config_secrets_to_obfuscate(self):
|
|
774
|
+
"""Return config secrets never to be exposed clear text."""
|
|
775
|
+
return CONFIG_SECRETS_TO_OBFUSCATE
|
|
776
|
+
|
|
777
|
+
def get_blueprint(self):
|
|
778
|
+
"""Return the Flask blueprint for this extension."""
|
|
779
|
+
return signed_url_bp
|