Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions api/collection_submission_actions/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from django.core.exceptions import PermissionDenied
from transitions import MachineError
from framework.exceptions import PermissionsError
from osf.exceptions import LicenseNotAcceptedError
from api.base.exceptions import Conflict
from django.core.exceptions import ValidationError

Expand Down Expand Up @@ -99,6 +100,8 @@ def create(self, validated_data):
f'Trigger "{trigger.db_name}" is not supported for the target CollectionSubmission '
f'with id [{collection_submission._id}] in state "{collection_submission.state.db_name}"',
)
except LicenseNotAcceptedError as exc:
raise ValidationError(str(exc))
except ValueError as exc:
raise ValidationError(exc)
return collection_submission.actions.last()
14 changes: 13 additions & 1 deletion api/collections/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

from osf import features
from osf.models import AbstractNode, Node, Collection, Guid, Registration, CedarMetadataRecord
from osf.exceptions import ValidationError, NodeStateError
from osf.exceptions import ValidationError, NodeStateError, LicenseNotAcceptedError
from website.project.licenses import validate_object_license_for_collection_provider
from api.base.serializers import LinksField, RelationshipField, LinkedNodesRelationshipSerializer, LinkedRegistrationsRelationshipSerializer, LinkedPreprintsRelationshipSerializer
from api.base.serializers import JSONAPISerializer, IDField, TypeField, VersionedDateTimeField, EnumField
from api.base.exceptions import InvalidModelValueError, RelationshipPostMakesNoChanges
Expand Down Expand Up @@ -408,6 +409,15 @@ def update(self, obj, validated_data):
return obj


def _validate_collected_object_license(referent, collection):
if not collection.provider_id:
return
try:
validate_object_license_for_collection_provider(referent, collection.provider)
except LicenseNotAcceptedError as e:
raise exceptions.ValidationError(detail=str(e))


class CollectionSubmissionCreateSerializer(CollectionSubmissionSerializer):
# Makes guid writeable only on create
guid = GuidRelationshipField(
Expand All @@ -429,6 +439,7 @@ def create(self, validated_data):
raise exceptions.ValidationError('"creator" must be specified.')
if not (creator.has_perm('write_collection', collection) or (hasattr(guid.referent, 'has_permission') and guid.referent.has_permission(creator, WRITE))):
raise exceptions.PermissionDenied('Must have write permission on either collection or collected object to collect.')
_validate_collected_object_license(guid.referent, collection)
cedar_record = None
if waffle.switch_is_active(features.COLLECTION_SUBMISSION_WITH_CEDAR) and collection.provider_id:
try:
Expand Down Expand Up @@ -482,6 +493,7 @@ def create(self, validated_data):
raise exceptions.ValidationError('"creator" must be specified.')
if not (creator.has_perm('write_collection', collection) or (hasattr(guid.referent, 'has_permission') and guid.referent.has_permission(creator, WRITE))):
raise exceptions.PermissionDenied('Must have write permission on either collection or collected object to collect.')
_validate_collected_object_license(guid.referent, collection)
cedar_record = None
if waffle.switch_is_active(features.COLLECTION_SUBMISSION_WITH_CEDAR) and collection.provider_id:
try:
Expand Down
9 changes: 7 additions & 2 deletions api/draft_registrations/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
)
from api.institutions.utils import update_institutions
from api.taxonomies.serializers import TaxonomizableSerializerMixin
from osf.exceptions import DraftRegistrationStateError
from osf.exceptions import DraftRegistrationStateError, LicenseNotAcceptedError
from osf.models import Node
from website import settings

Expand Down Expand Up @@ -50,7 +50,10 @@ class DraftRegistrationSerializer(DraftRegistrationLegacySerializer, Taxonomizab

category = ser.ChoiceField(required=False, choices=category_choices, help_text='Choices: ' + category_choices_string)
tags = ValuesListField(attr_name='name', child=ser.CharField(), required=False)
node_license = NodeLicenseSerializer(required=False, source='license')
node_license = NodeLicenseSerializer(
required=False, source='license',
error_messages={'null': 'A license is required for a registration.'},
)

links = LinksField({
'self': 'get_absolute_url',
Expand Down Expand Up @@ -200,6 +203,8 @@ def update(self, draft, validated_data):
raise exceptions.PermissionDenied
except DraftRegistrationStateError as e:
raise InvalidModelValueError(detail=str(e))
except LicenseNotAcceptedError as e:
raise exceptions.ValidationError(detail=str(e))

return draft

Expand Down
5 changes: 4 additions & 1 deletion api/registrations/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,10 @@ class RegistrationSerializer(NodeSerializer):
fork = HideIfWithdrawal(ser.BooleanField(read_only=True, source='is_fork'))
collection = HideIfWithdrawal(ser.BooleanField(read_only=True, source='is_collection'))
access_requests_enabled = HideIfWithdrawal(ser.BooleanField(read_only=True))
node_license = HideIfWithdrawal(NodeLicenseSerializer(required=False, source='license'))
node_license = HideIfWithdrawal(
NodeLicenseSerializer(required=False, source='license'),
error_messages={'null': 'A license is required for a registration.'},
)
tags = HideIfWithdrawal(ValuesListField(attr_name='name', child=ser.CharField(), required=False))
article_doi = ser.CharField(required=False, allow_null=True)
public = HideIfWithdrawal(
Expand Down
93 changes: 93 additions & 0 deletions api_tests/collections/test_collection_license_provider.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import pytest

from api.base.settings.defaults import API_BASE
from osf.models import NodeLicense
from osf.utils.workflows import CollectionSubmissionStates
from osf_tests.factories import (
AuthUserFactory,
CollectionProviderFactory,
NodeLicenseRecordFactory,
ProjectFactory,
)


@pytest.mark.django_db
class TestCollectionLicenseEnforcedByProvider:

@pytest.fixture()
def user(self):
return AuthUserFactory()

@pytest.fixture()
def cc0(self):
return NodeLicense.objects.get(name='CC0 1.0 Universal')

@pytest.fixture()
def mit(self):
return NodeLicense.objects.get(name='MIT License')

@pytest.fixture()
def provider(self, user, cc0):
provider = CollectionProviderFactory(creator=user)
provider.licenses_acceptable.add(cc0)
return provider

@pytest.fixture()
def collection(self, provider):
return provider.primary_collection

def make_project(self, user, node_license):
project = ProjectFactory(creator=user, is_public=True)
if node_license:
project.node_license = NodeLicenseRecordFactory(node_license=node_license)
project.save()
return project

def submit(self, app, user, collection, project):
return app.post_json_api(
f'/{API_BASE}collections/{collection._id}/collected_metadata/',
{'data': {'type': 'collected-metadata', 'attributes': {'guid': project._id}}},
auth=user.auth,
expect_errors=True,
)

def test_submit_with_accepted_license(self, app, user, collection, cc0):
res = self.submit(app, user, collection, self.make_project(user, cc0))
assert res.status_code == 201

def test_submit_with_unaccepted_license_rejected(self, app, user, collection, provider, mit):
res = self.submit(app, user, collection, self.make_project(user, mit))
assert res.status_code == 400
assert res.json['errors'][0]['detail'] == f"The license '{mit.name}' is not accepted by {provider.name}."

def test_submit_without_license_rejected(self, app, user, collection):
res = self.submit(app, user, collection, self.make_project(user, None))
assert res.status_code == 400

def test_submit_to_unrestricted_provider(self, app, user, collection, provider, mit):
provider.licenses_acceptable.clear()
res = self.submit(app, user, collection, self.make_project(user, mit))
assert res.status_code == 201

def test_license_change_blocked_while_submission_active(self, app, user, collection, provider, cc0, mit):
project = self.make_project(user, cc0)
submission = collection.collect_object(project, user)
assert submission.machine_state in (
CollectionSubmissionStates.PENDING.value, CollectionSubmissionStates.ACCEPTED.value,
)
payload = {
'data': {
'type': 'nodes',
'id': project._id,
'attributes': {'node_license': {'year': '2026', 'copyright_holders': ['A']}},
'relationships': {'license': {'data': {'type': 'licenses', 'id': mit._id}}},
},
}
res = app.patch_json_api(f'/{API_BASE}nodes/{project._id}/', payload, auth=user.auth, expect_errors=True)
assert res.status_code == 400
assert 'is not accepted by' in res.json['errors'][0]['detail']

submission.machine_state = CollectionSubmissionStates.REMOVED.value
submission.save()
res = app.patch_json_api(f'/{API_BASE}nodes/{project._id}/', payload, auth=user.auth)
assert res.status_code == 200
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import pytest

from api.base.settings.defaults import API_BASE
from osf.models import NodeLicense
from osf_tests.factories import (
AuthUserFactory,
DraftRegistrationFactory,
RegistrationProviderFactory,
)


@pytest.mark.django_db
class TestDraftRegistrationLicenseEnforcedByProvider:

@pytest.fixture()
def user(self):
return AuthUserFactory()

@pytest.fixture()
def cc0(self):
return NodeLicense.objects.get(name='CC0 1.0 Universal')

@pytest.fixture()
def mit(self):
return NodeLicense.objects.get(name='MIT License')

@pytest.fixture()
def provider(self, cc0):
provider = RegistrationProviderFactory()
provider.licenses_acceptable.add(cc0)
return provider

@pytest.fixture()
def draft(self, user, provider):
return DraftRegistrationFactory(initiator=user, provider=provider)

def payload(self, draft, license_id):
return {
'data': {
'type': 'draft_registrations',
'id': draft._id,
'attributes': {'node_license': {'year': '2026', 'copyright_holders': ['A']}},
'relationships': {'license': {'data': {'type': 'licenses', 'id': license_id}}},
},
}

def test_accepted_license(self, app, user, draft, cc0):
res = app.patch_json_api(
f'/{API_BASE}draft_registrations/{draft._id}/', self.payload(draft, cc0._id), auth=user.auth,
)
assert res.status_code == 200

def test_unaccepted_license(self, app, user, draft, provider, mit):
res = app.patch_json_api(
f'/{API_BASE}draft_registrations/{draft._id}/', self.payload(draft, mit._id),
auth=user.auth, expect_errors=True,
)
assert res.status_code == 400
assert res.json['errors'][0]['detail'] == f"The license '{mit.name}' is not accepted by {provider.name}."

def test_no_license_always_rejected(self, app, user, draft, provider):
no_license = NodeLicense.objects.get(license_id='NONE')
provider.licenses_acceptable.add(no_license)
res = app.patch_json_api(
f'/{API_BASE}draft_registrations/{draft._id}/', self.payload(draft, no_license._id),
auth=user.auth, expect_errors=True,
)
assert res.status_code == 400
assert 'Registrations require a license' in res.json['errors'][0]['detail']

def test_null_node_license_has_clear_message(self, app, user, draft):
res = app.patch_json_api(
f'/{API_BASE}draft_registrations/{draft._id}/',
{'data': {'type': 'draft_registrations', 'id': draft._id, 'attributes': {'node_license': None}}},
auth=user.auth, expect_errors=True,
)
assert res.status_code == 400
assert res.json['errors'][0]['detail'] == 'A license is required for a registration.'
8 changes: 4 additions & 4 deletions api_tests/providers/tasks/test_bulk_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ def csv_parsed_1(self, subjects):
'Category': 'project',
'Affiliated Institutions': [],
'License': {
'name': 'No license',
'name': 'MIT License',
'required_fields': {
'year': '2030', 'copyright_holders': ['jane doe', 'john doe', 'joan doe']
}
Expand Down Expand Up @@ -187,7 +187,7 @@ def csv_parsed_2(self, subjects):
'Category': 'project',
'Affiliated Institutions': [],
'License': {
'name': 'No license',
'name': 'MIT License',
'required_fields': {
'year': '2030', 'copyright_holders': ['jane doe', 'john doe', 'joan doe']
}
Expand Down Expand Up @@ -225,7 +225,7 @@ def csv_parsed_extra_bib(self, subjects):
'Category': 'project',
'Affiliated Institutions': [],
'License': {
'name': 'No license',
'name': 'MIT License',
'required_fields': {
'year': '2030', 'copyright_holders': ['jane doe', 'john doe', 'joan doe']
}
Expand Down Expand Up @@ -262,7 +262,7 @@ def csv_parsed_invalid_affiliation(self, subjects, institution):
'Category': 'project',
'Affiliated Institutions': [institution.name],
'License': {
'name': 'No license',
'name': 'MIT License',
'required_fields': {
'year': '2030', 'copyright_holders': ['jane doe', 'john doe', 'joan doe']
}
Expand Down
6 changes: 6 additions & 0 deletions api_tests/registrations/views/test_registration_detail.py
Original file line number Diff line number Diff line change
Expand Up @@ -1187,6 +1187,12 @@ def node(self, user_admin_contrib, user_write_contrib, user_read_contrib):
node.save()
return node

@pytest.fixture()
def license_no(self):
# The inherited tests use `license_no` as "a license that requires a year and copyright holders".
# Registrations may not use 'No license', so use another license with the same required fields.
return NodeLicense.objects.get(name='MIT License')

@pytest.fixture()
def url_node(self, node):
return f'/{API_BASE}registrations/{node._id}/'
Expand Down
Loading
Loading