Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle forbidden characters in asset path #1201

Merged
merged 6 commits into from
Jul 27, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion dandiapi/api/tests/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ class DraftAssetFactory(factory.django.DjangoModelFactory):
class Meta:
model = Asset

path = factory.Faker('file_path', extension='nwb')
path = factory.Faker('file_path', absolute=False, extension='nwb')
blob = factory.SubFactory(AssetBlobFactory)

@factory.lazy_attribute
Expand Down
45 changes: 45 additions & 0 deletions dandiapi/api/tests/test_asset.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,51 @@ def test_asset_create(api_client, user, draft_version, asset_blob):
assert draft_version.status == Version.Status.PENDING


@pytest.mark.parametrize(
'path,valid',
[
('foo.txt', True),
('/foo', False),
('', False),
('/', False),
('./foo', False),
('../foo', False),
('foo/.', False),
('foo/..', False),
('foo/./bar', False),
('foo/../bar', False),
('foo//bar', False),
('foo\0bar', False),
('foo/.bar', True),
],
)
@pytest.mark.django_db
def test_asset_create_path_validation(api_client, user, draft_version, asset_blob, path, valid):
assign_perm('owner', user, draft_version.dandiset)
api_client.force_authenticate(user=user)

metadata = {
'schemaVersion': settings.DANDI_SCHEMA_VERSION,
'encodingFormat': 'application/x-nwb',
'path': path,
'meta': 'data',
'foo': ['bar', 'baz'],
'1': 2,
danlamanna marked this conversation as resolved.
Show resolved Hide resolved
}

resp = api_client.post(
f'/api/dandisets/{draft_version.dandiset.identifier}'
f'/versions/{draft_version.version}/assets/',
{'metadata': metadata, 'blob_id': asset_blob.blob_id},
format='json',
)

if valid:
assert resp.status_code == 200, resp.data
else:
assert resp.status_code != 200, resp.data
DeepikaGhodki marked this conversation as resolved.
Show resolved Hide resolved


@pytest.mark.django_db
def test_asset_create_embargo(api_client, user, draft_version, embargoed_asset_blob):
assign_perm('owner', user, draft_version.dandiset)
Expand Down
28 changes: 27 additions & 1 deletion dandiapi/api/views/asset.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
MinioStorage = type('FakeMinioStorage', (), {})

import os.path
from pathlib import Path, PurePath
from urllib.parse import urlencode

from django.core.paginator import EmptyPage, Page, Paginator
Expand Down Expand Up @@ -251,9 +252,33 @@ def validate(self, data):
{'blob_id': 'Exactly one of blob_id or zarr_id must be specified.'}
)

if 'path' not in data['metadata']:
if 'path' not in data['metadata'] or not data['metadata']['path']:
DeepikaGhodki marked this conversation as resolved.
Show resolved Hide resolved
raise serializers.ValidationError({'metadata': 'No path specified in metadata.'})

path = data['metadata']['path']
DeepikaGhodki marked this conversation as resolved.
Show resolved Hide resolved
# paths starting with /
if PurePath.is_absolute(Path(path)):
DeepikaGhodki marked this conversation as resolved.
Show resolved Hide resolved
raise serializers.ValidationError(
{'metadata': 'Absolute path not allowed for an asset'}
)

sub_paths = path.split('/')
# checking for . in path
for sub_path in sub_paths:
if len(set(sub_path)) == 1 and sub_path[0] == '.':
raise serializers.ValidationError(
{'metadata': 'Invalid characters (.) in file path'}
)

# Invalid characters ['\0']
filepath_regex = '^[^\0]+$'
DeepikaGhodki marked this conversation as resolved.
Show resolved Hide resolved
# match characters repeating more than once
multiple_occurrence_regex = '[/]{2,}'
if not re.search(filepath_regex, path):
raise serializers.ValidationError({'metadata': 'Invalid characters (\0) in file name'})
if re.search(multiple_occurrence_regex, path):
raise serializers.ValidationError({'metadata': 'Invalid characters (/)) in file name'})

return data


Expand Down Expand Up @@ -409,6 +434,7 @@ def create(self, request, versions__dandiset__pk, versions__version):
_maybe_validate_asset_metadata(asset)

serializer = AssetDetailSerializer(instance=asset)
print(serializer.data)
DeepikaGhodki marked this conversation as resolved.
Show resolved Hide resolved
return Response(serializer.data, status=status.HTTP_200_OK)

@swagger_auto_schema(
Expand Down